Skip to content

Commit ec709cc

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

File tree

1 file changed

+18
-11
lines changed

1 file changed

+18
-11
lines changed

app/javascript/controllers/drag_and_drop_controller.js

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -32,16 +32,18 @@ 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)
42+
4143
const sourceContainer = this.sourceContainer
42-
this.#insertDraggedItem(container, this.dragItem)
43-
await this.#submitDropRequest(this.dragItem, container)
44-
this.#reloadSourceFrame(sourceContainer);
44+
this.#insertDraggedItem(targetContainer, this.dragItem)
45+
await this.#submitDropRequest(this.dragItem, targetContainer)
46+
this.#reloadSourceFrame(sourceContainer)
4547
}
4648

4749
dragEnd() {
@@ -65,17 +67,22 @@ export default class extends Controller {
6567
this.containerTargets.forEach(container => container.classList.remove(this.hoverContainerClass))
6668
}
6769

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

7383
if (!/^\d+$/.test(currentValue)) return
7484

75-
const count = parseInt(currentValue)
76-
if (count > 0) {
77-
counterElement.textContent = count - 1
78-
}
85+
counterElement.textContent = fn(parseInt(currentValue))
7986
}
8087
}
8188

0 commit comments

Comments
 (0)