Refactoring: moving the draggable code in a common class.

This commit is contained in:
John Livingston 2024-07-30 12:54:05 +02:00
parent eb76e7ebb9
commit fbc9a39485
No known key found for this signature in database
GPG Key ID: B17B5640CE66CDBC
8 changed files with 260 additions and 181 deletions

View File

@ -2,16 +2,14 @@
//
// SPDX-License-Identifier: AGPL-3.0-only
import { CustomElement } from 'shared/components/element.js'
import { api } from '@converse/headless'
import tplMucNotes from '../templates/muc-notes'
import { __ } from 'i18n'
import { DraggablesCustomElement } from '../../../shared/components/draggables/index.js'
import '../styles/muc-notes.scss'
export default class MUCNotesView extends CustomElement {
currentDraggedNote = null
export default class MUCNotesView extends DraggablesCustomElement {
static get properties () {
return {
model: { type: Object, attribute: true },
@ -27,16 +25,16 @@ export default class MUCNotesView extends CustomElement {
return
}
this.draggableTagName = 'livechat-converse-muc-note'
this.droppableTagNames = ['livechat-converse-muc-note']
this.droppableAlwaysBottomTagNames = []
// Adding or removing a new note: we must update.
this.listenTo(this.model, 'add', () => this.requestUpdate())
this.listenTo(this.model, 'remove', () => this.requestUpdate())
this.listenTo(this.model, 'sort', () => this.requestUpdate())
// this._handleDragStartBinded = this._handleDragStart.bind(this)
// this._handleDragOverBinded = this._handleDragOver.bind(this)
// this._handleDragLeaveBinded = this._handleDragLeave.bind(this)
// this._handleDragEndBinded = this._handleDragEnd.bind(this)
// this._handleDropBinded = this._handleDrop.bind(this)
await super.initialize()
}
render () {
@ -90,6 +88,29 @@ export default class MUCNotesView extends CustomElement {
})
}
}
_dropDone (draggedEl, droppedOnEl, onTopHalf) {
super._dropDone(...arguments)
console.log('[livechat note drag&drop] Note dropped...')
const note = draggedEl.model
if (!note) {
throw new Error('No model for the draggedEl')
}
const targetNote = droppedOnEl.model
if (!targetNote) {
throw new Error('No model for the droppedOnEl')
}
if (note === targetNote) {
console.log('[livechat note drag&drop] Note dropped on itself, nothing to do')
return
}
let newOrder = targetNote.get('order') ?? 0
if (!onTopHalf) { newOrder = Math.max(0, newOrder + 1) }
this._saveOrders(this.model, note, newOrder)
}
}
api.elements.define('livechat-converse-muc-notes', MUCNotesView)

View File

@ -11,7 +11,7 @@ export function tplMucNote (el, note) {
return !el.edit
? html`
<div draggable="true" class="note-line">
<div draggable="true" class="note-line draggables-line">
<div class="note-description">${note.get('description') ?? ''}</div>
<button class="note-action" title="${__('Edit')}"
@click=${el.toggleEdit}
@ -25,7 +25,7 @@ export function tplMucNote (el, note) {
</button>
</div>`
: html`
<div class="note-line">
<div class="note-line draggables-line">
<form class="converse-form" @submit=${el.saveNote}>
${_tplNoteForm(note)}
<fieldset class="form-group">

View File

@ -2,17 +2,14 @@
//
// SPDX-License-Identifier: AGPL-3.0-only
import { CustomElement } from 'shared/components/element.js'
import { api } from '@converse/headless'
import tplMucTaskLists from '../templates/muc-task-lists'
import { __ } from 'i18n'
import { DraggablesCustomElement } from '../../../shared/components/draggables/index.js'
import '../styles/muc-task-lists.scss'
import '../styles/muc-task-drag.scss'
export default class MUCTaskListsView extends CustomElement {
currentDraggedTask = null
export default class MUCTaskListsView extends DraggablesCustomElement {
static get properties () {
return {
model: { type: Object, attribute: true },
@ -27,42 +24,22 @@ export default class MUCTaskListsView extends CustomElement {
return
}
this.draggableTagName = 'livechat-converse-muc-task'
this.droppableTagNames = ['livechat-converse-muc-task', 'livechat-converse-muc-task-list']
this.droppableAlwaysBottomTagNames = ['livechat-converse-muc-task-list']
// Adding or removing a new task list: we must update.
this.listenTo(this.model, 'add', () => this.requestUpdate())
this.listenTo(this.model, 'remove', () => this.requestUpdate())
this.listenTo(this.model, 'sort', () => this.requestUpdate())
this._handleDragStartBinded = this._handleDragStart.bind(this)
this._handleDragOverBinded = this._handleDragOver.bind(this)
this._handleDragLeaveBinded = this._handleDragLeave.bind(this)
this._handleDragEndBinded = this._handleDragEnd.bind(this)
this._handleDropBinded = this._handleDrop.bind(this)
return super.initialize()
}
render () {
return tplMucTaskLists(this, this.model)
}
connectedCallback () {
super.connectedCallback()
this.currentDraggedTask = null
this.addEventListener('dragstart', this._handleDragStartBinded)
this.addEventListener('dragover', this._handleDragOverBinded)
this.addEventListener('dragleave', this._handleDragLeaveBinded)
this.addEventListener('dragend', this._handleDragEndBinded)
this.addEventListener('drop', this._handleDropBinded)
}
disconnectedCallback () {
super.disconnectedCallback()
this.currentDraggedTask = null
this.removeEventListener('dragstart', this._handleDragStartBinded)
this.removeEventListener('dragover', this._handleDragOverBinded)
this.removeEventListener('dragleave', this._handleDragLeaveBinded)
this.removeEventListener('dragend', this._handleDragEndBinded)
this.removeEventListener('drop', this._handleDropBinded)
}
async submitCreateTaskList (ev) {
ev.preventDefault()
@ -96,15 +73,7 @@ export default class MUCTaskListsView extends CustomElement {
}
}
_getParentTaskEl (target) {
return target.closest?.('livechat-converse-muc-task')
}
_getParentTaskOrTaskListEl (target) {
return target.closest?.('livechat-converse-muc-task, livechat-converse-muc-task-list')
}
_isATaskEl (target) {
isATaskEl (target) {
return target.nodeName?.toLowerCase() === 'livechat-converse-muc-task'
}
@ -112,71 +81,18 @@ export default class MUCTaskListsView extends CustomElement {
return target.nodeName?.toLowerCase() === 'livechat-converse-muc-task-list'
}
_isOnTopHalf (ev, taskEl) {
const y = ev.clientY
const bounding = taskEl.getBoundingClientRect()
return (y <= bounding.y + (bounding.height / 2))
}
_resetDropOver () {
document.querySelectorAll('.livechat-drag-bottom-half, .livechat-drag-top-half').forEach(
el => el.classList.remove('livechat-drag-bottom-half', 'livechat-drag-top-half')
)
}
_handleDragStart (ev) {
// The draggable=true is on a livechat-converse-muc-task child
const possibleTaskEl = ev.target.parentElement
if (!this._isATaskEl(possibleTaskEl)) { return }
console.log('[livechat task drag&drop] Starting to drag a task...')
this.currentDraggedTask = possibleTaskEl
this._resetDropOver()
}
_handleDragOver (ev) {
if (!this.currentDraggedTask) { return }
const taskOrTaskListEl = this._getParentTaskOrTaskListEl(ev.target)
if (!taskOrTaskListEl) { return }
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/drop_event says we should preventDefault
ev.preventDefault()
// Are we on the top or bottom part of the taskEl?
// Note: for task list, we always add the task in the task list, so no need to test here.
const topHalf = this._isATaskEl(taskOrTaskListEl) ? this._isOnTopHalf(ev, taskOrTaskListEl) : false
taskOrTaskListEl.classList.add(topHalf ? 'livechat-drag-top-half' : 'livechat-drag-bottom-half')
taskOrTaskListEl.classList.remove(topHalf ? 'livechat-drag-bottom-half' : 'livechat-drag-top-half')
}
_handleDragLeave (ev) {
if (!this.currentDraggedTask) { return }
const taskOrTaskListEl = this._getParentTaskOrTaskListEl(ev.target)
if (!taskOrTaskListEl) { return }
taskOrTaskListEl.classList.remove('livechat-drag-bottom-half', 'livechat-drag-top-half')
}
_handleDragEnd (_ev) {
this.currentDraggedTask = null
this._resetDropOver()
}
_handleDrop (_ev) {
if (!this.currentDraggedTask) { return }
const droppedOnEl = document.querySelector('.livechat-drag-bottom-half, .livechat-drag-top-half')
const droppedOntaskOrTaskListEl = this._getParentTaskOrTaskListEl(droppedOnEl)
if (!droppedOntaskOrTaskListEl) { return }
_dropDone (draggedEl, droppedOnEl, onTopHalf) {
super._dropDone(...arguments)
console.log('[livechat task drag&drop] Task dropped...')
const task = this.currentDraggedTask.model
const task = draggedEl.model
let newOrder, targetTasklist
if (this.isATaskListEl(droppedOntaskOrTaskListEl)) {
if (this.isATaskListEl(droppedOnEl)) {
// We dropped on a task list, we must add as first entry.
newOrder = 0
targetTasklist = droppedOntaskOrTaskListEl.model
targetTasklist = droppedOnEl.model
if (task.get('list') !== targetTasklist.get('id')) {
console.log('[livechat task drag&drop] Changing task list...')
task.set('list', targetTasklist.get('id'))
@ -185,9 +101,9 @@ export default class MUCTaskListsView extends CustomElement {
console.log('[livechat task drag&drop] Task dropped on tasklist, but already first item, nothing to do')
return
}
} else if (this._isATaskEl(droppedOntaskOrTaskListEl)) {
} else if (this.isATaskEl(droppedOnEl)) {
// We dropped on a task, we must get its order (+1 if !onTopHalf)
const droppedOnTask = droppedOntaskOrTaskListEl.model
const droppedOnTask = droppedOnEl.model
if (task === droppedOnTask) {
// But of course, if dropped on itself there is nothing to do.
console.log('[livechat task drag&drop] Task dropped on itself, nothing to do')
@ -199,9 +115,8 @@ export default class MUCTaskListsView extends CustomElement {
task.set('list', droppedOnTask.get('list'))
}
const topHalf = droppedOnEl.classList.contains('livechat-drag-top-half')
newOrder = droppedOnTask.get('order') ?? 0
if (!topHalf) { newOrder = Math.max(0, newOrder + 1) }
if (!onTopHalf) { newOrder = Math.max(0, newOrder + 1) }
if (typeof newOrder !== 'number' || isNaN(newOrder)) {
console.error(
@ -217,45 +132,7 @@ export default class MUCTaskListsView extends CustomElement {
return
}
if (typeof newOrder !== 'number' || isNaN(newOrder)) {
console.error('[livechat task drag&drop] Computed new order is not a number, aborting.')
return
}
console.log('[livechat task drag&drop] Task new order will be ' + newOrder)
console.log('[livechat task drag&drop] Reordering tasks...')
let currentOrder = newOrder + 1
for (const t of targetTasklist.getTasks()) {
if (t === task) {
console.log('[livechat task drag&drop] Skipping the currently moved task')
continue
}
let order = t.get('order') ?? 0
if (typeof order !== 'number' || isNaN(order)) {
console.error('[livechat task drag&drop] Found a task with an invalid order, fixing it.')
order = currentOrder // this will cause the code bellow to increment task order
}
if (order < newOrder) { continue }
currentOrder++
if (order > currentOrder) {
console.log(
`Task "${t.get('name')}" as already on order greater than ${currentOrder.toString()}, stoping.`
)
break
}
console.log(`Changing order of task "${t.get('name')}" to ${currentOrder}`)
t.set('order', currentOrder)
t.saveItem() // TODO: handle errors?
}
console.log('[livechat task drag&drop] Setting new order on the moved task')
task.set('order', newOrder)
task.saveItem() // TODO: handle errors?
this._resetDropOver()
this._saveOrders(targetTasklist.getTasks(), task, newOrder)
}
}

View File

@ -1,27 +0,0 @@
/*
* SPDX-FileCopyrightText: 2024 John Livingston <https://www.john-livingston.fr/>
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
.conversejs {
livechat-converse-muc-task {
&.livechat-drag-bottom-half .task-line {
border-bottom: 4px solid blue;
}
&.livechat-drag-top-half .task-line {
border-top: 4px solid blue;
}
}
livechat-converse-muc-task-list {
&.livechat-drag-bottom-half .task-list-line {
border-bottom: 4px solid blue;
}
&.livechat-drag-top-half .task-list-line {
border-top: 4px solid blue;
}
}
}

View File

@ -16,7 +16,7 @@ export default function tplMucTaskList (el, tasklist) {
// eslint-disable-next-line no-undef
const i18nTaskListName = __(LOC_task_list_name)
return html`
<div class="task-list-line">
<div class="task-list-line draggables-line">
${el.collapsed
? html`
<button @click=${el.toggleTasks} class="task-list-toggle-tasks">

View File

@ -13,7 +13,7 @@ export function tplMucTask (el, task) {
const doneId = 'livechat-task-done-id-' + task.get('id')
return !el.edit
? html`
<div draggable="true" class="task-line" ?task-is-done=${done}>
<div draggable="true" class="task-line draggables-line" ?task-is-done=${done}>
<div class="form-check">
<input
id="${doneId}"
@ -42,7 +42,7 @@ export function tplMucTask (el, task) {
</button>
</div>`
: html`
<div class="task-line">
<div class="task-line draggables-line">
<form class="converse-form" @submit=${el.saveTask}>
${_tplTaskForm(task)}
<fieldset class="form-group">

View File

@ -0,0 +1,189 @@
import { CustomElement } from 'shared/components/element.js'
import './styles/draggables.scss'
/**
* This is the base class for custom elements that contains draggable items.
*/
export class DraggablesCustomElement extends CustomElement {
currentDragged = null
/**
* The tag name for draggable elements.
* Example: livechat-converse-muc-note.
* Must be set in derived class.
*/
draggableTagName = 'invalid-tag-name'
/**
* The tag names on which we can drop the element.
* Examples: livechat-converse-muc-note, livechat-converse-muc-task, livechat-converse-muc-task-list.
* Must be set in derived class.
*/
droppableTagNames = []
/**
* Tag names for which we will always drop to bottom (for example: task lists)
*/
droppableAlwaysBottomTagNames = []
initialize () {
this._handleDragStartBinded = this._handleDragStart.bind(this)
this._handleDragOverBinded = this._handleDragOver.bind(this)
this._handleDragLeaveBinded = this._handleDragLeave.bind(this)
this._handleDragEndBinded = this._handleDragEnd.bind(this)
this._handleDropBinded = this._handleDrop.bind(this)
return super.initialize()
}
connectedCallback () {
super.connectedCallback()
this.currentDragged = null
this.addEventListener('dragstart', this._handleDragStartBinded)
this.addEventListener('dragover', this._handleDragOverBinded)
this.addEventListener('dragleave', this._handleDragLeaveBinded)
this.addEventListener('dragend', this._handleDragEndBinded)
this.addEventListener('drop', this._handleDropBinded)
}
disconnectedCallback () {
super.disconnectedCallback()
this.currentDragged = null
this.removeEventListener('dragstart', this._handleDragStartBinded)
this.removeEventListener('dragover', this._handleDragOverBinded)
this.removeEventListener('dragleave', this._handleDragLeaveBinded)
this.removeEventListener('dragend', this._handleDragEndBinded)
this.removeEventListener('drop', this._handleDropBinded)
}
_isADraggableEl (target) {
return target.nodeName?.toLowerCase() === this.draggableTagName
}
_getParentDroppableEl (target) {
return target.closest?.(this.droppableTagNames.join(','))
}
_isOnTopHalf (ev, el) {
const y = ev.clientY
const bounding = el.getBoundingClientRect()
return (y <= bounding.y + (bounding.height / 2))
}
_resetDropOver () {
document.querySelectorAll('.livechat-drag-bottom-half, .livechat-drag-top-half').forEach(
el => el.classList.remove('livechat-drag-bottom-half', 'livechat-drag-top-half')
)
}
_handleDragStart (ev) {
// The draggable=true is on a child bode
const possibleEl = ev.target.parentElement
if (!this._isADraggableEl(possibleEl)) { return }
console.log('[livechat drag&drop] Starting to drag a ' + this.draggableTagName + '...')
this.currentDragged = possibleEl
this._resetDropOver()
}
_handleDragOver (ev) {
if (!this.currentDragged) { return }
const droppableEl = this._getParentDroppableEl(ev.target)
if (!droppableEl) { return }
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/drop_event says we should preventDefault
ev.preventDefault()
// Are we on the top or bottom part of the droppableEl?
let topHalf = false
if (!this.droppableAlwaysBottomTagNames.includes(droppableEl.nodeName.toLowerCase())) {
topHalf = this._isOnTopHalf(ev, droppableEl)
}
droppableEl.classList.add(topHalf ? 'livechat-drag-top-half' : 'livechat-drag-bottom-half')
droppableEl.classList.remove(topHalf ? 'livechat-drag-bottom-half' : 'livechat-drag-top-half')
}
_handleDragLeave (ev) {
if (!this.currentDragged) { return }
const el = this._getParentDroppableEl(ev.target)
if (!el) { return }
el.classList.remove('livechat-drag-bottom-half', 'livechat-drag-top-half')
}
_handleDragEnd (_ev) {
this.currentDragged = null
this._resetDropOver()
}
_handleDrop (_ev) {
if (!this.currentDragged) { return }
let droppedOnEl = document.querySelector('.livechat-drag-bottom-half, .livechat-drag-top-half')
droppedOnEl = this._getParentDroppableEl(droppedOnEl)
if (!droppedOnEl) { return }
console.log('[livechat drag&drop] ' + this.draggableTagName + ' dropped...')
try {
this._dropDone(this.currentDragged, droppedOnEl, droppedOnEl.classList.contains('livechat-drag-top-half'))
} catch (err) {
console.error(err)
}
this._resetDropOver()
}
/**
* The callback when a valid drop occurs.
* Must be overloaded.
*/
_dropDone (draggedEl, droppedOnEl, onTopHalf) {
console.debug('[livechat drag&drop] Drop done:', draggedEl, droppedOnEl, onTopHalf)
}
/**
* This method can be called from _dropDone to save the new objects orders.
* For it to work, models must respect following constraints:
* * be a Model
* * have the order attribute
* * have an id attribute (for logging)
* * have get, set and saveItem methods
*/
_saveOrders (models, currentModel, newOrder) {
if (typeof newOrder !== 'number' || isNaN(newOrder)) {
console.error('[livechat drag&drop] Computed new order is not a number, aborting.')
return
}
console.log('[livechat drag&drop] Reordering models... Model new order will be ' + newOrder)
let currentOrder = newOrder + 1
for (const m of models) {
if (m === currentModel) {
console.log('[livechat drag&drop] Skipping the currently moved model')
continue
}
let order = m.get('order') ?? 0
if (typeof order !== 'number' || isNaN(order)) {
console.error('[livechat drag&drop] Found a model with an invalid order, fixing it.')
order = currentOrder // this will cause the code bellow to increment model order
}
if (order < newOrder) { continue }
currentOrder++
if (order > currentOrder) {
console.log(
`Object "${m.get('id')}" as already on order greater than ${currentOrder.toString()}, stoping.`
)
break
}
console.log(`Changing order of model "${m.get('id')}" to ${currentOrder}`)
m.set('order', currentOrder)
m.saveItem() // TODO: handle errors?
}
console.log('[livechat drag&drop] Setting new order on the moved model')
currentModel.set('order', newOrder)
currentModel.saveItem() // TODO: handle errors?
}
}

View File

@ -0,0 +1,19 @@
/*
* SPDX-FileCopyrightText: 2024 John Livingston <https://www.john-livingston.fr/>
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
.conversejs {
// FIXME: the use of ">" only works if the draggables-lines is a direct
// child of the element.
// We should find a better way to do this (and that will not break for nested
// elements, like task in tast-list).
.livechat-drag-bottom-half > .draggables-line {
border-bottom: 4px solid blue;
}
.livechat-drag-top-half > .draggables-line {
border-top: 4px solid blue;
}
}