Skip to content

Commit 39d9659

Browse files
committed
Modify counters optimistically too
1 parent 37325ea commit 39d9659

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

app/javascript/controllers/drag_and_drop_controller.js

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -32,15 +32,16 @@ export default class extends Controller {
3232
}
3333

3434
async drop(event) {
35-
const container = this.#containerContaining(event.target)
35+
const targetContainer = this.#containerContaining(event.target)
3636

37-
if (!container || container === this.sourceContainer) { return }
37+
if (!targetContainer || targetContainer === this.sourceContainer) { return }
3838

3939
this.wasDropped = true
40+
this.#increaseCounter(targetContainer)
4041
this.#decreaseCounter(this.sourceContainer)
4142
const sourceContainer = this.sourceContainer
42-
this.#insertDraggedItem(container, this.dragItem)
43-
await this.#submitDropRequest(this.dragItem, container)
43+
this.#insertDraggedItem(targetContainer, this.dragItem)
44+
await this.#submitDropRequest(this.dragItem, targetContainer)
4445
this.#reloadSourceFrame(sourceContainer);
4546
}
4647

@@ -65,17 +66,22 @@ export default class extends Controller {
6566
this.containerTargets.forEach(container => container.classList.remove(this.hoverContainerClass))
6667
}
6768

68-
#decreaseCounter(sourceContainer) {
69-
const counterElement = sourceContainer.querySelector("[data-drag-and-drop-counter]")
69+
#increaseCounter(container) {
70+
this.#modifyCounter(container, count => count + 1)
71+
}
72+
73+
#decreaseCounter(container) {
74+
this.#modifyCounter(container, count => Math.max(0, count - 1))
75+
}
76+
77+
#modifyCounter(container, fn) {
78+
const counterElement = container.querySelector("[data-drag-and-drop-counter]")
7079
if (counterElement) {
7180
const currentValue = counterElement.textContent.trim()
7281

7382
if (!/^\d+$/.test(currentValue)) return
7483

75-
const count = parseInt(currentValue)
76-
if (count > 0) {
77-
counterElement.textContent = count - 1
78-
}
84+
counterElement.textContent = fn(parseInt(currentValue))
7985
}
8086
}
8187

0 commit comments

Comments
 (0)