Skip to content

Commit

Permalink
Merge pull request #34 from dkniffin/update-backend-on-dragend
Browse files Browse the repository at this point in the history
Only update backend on dragend
  • Loading branch information
dkniffin authored Jul 16, 2024
2 parents b4d22fe + ff5d0f7 commit 714be9c
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions app/assets/javascripts/activeadmin_reorderable.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
const setupReorderable = ({ table, onUpdate }) => {
const setupReorderable = ({ table, onDragover, onDragEnd }) => {
const rows = table.getElementsByTagName('tbody')[0].rows

let dragSrc = null
let srcIndex = null

for (var i = 0; i < rows.length; i++) {
const row = rows[i]
Expand All @@ -15,6 +16,7 @@ const setupReorderable = ({ table, onUpdate }) => {
e.dataTransfer.effectAllowed = "move"

dragSrc = row
srcIndex = row.rowIndex

// Apply styling a millisecond later, so the dragging image shows up correctly
setTimeout(() => { row.classList.add("dragged-row") }, 1)
Expand All @@ -34,15 +36,21 @@ const setupReorderable = ({ table, onUpdate }) => {
} else {
table.tBodies[0].insertBefore(dragSrc, row)
}
onUpdate(dragSrc)
onDragover(dragSrc)
}
})

row.addEventListener("dragend", () => {
// Disable dragging, so only the handle can start the dragging again
row.setAttribute("draggable", "false")
row.classList.remove("dragged-row")

if (srcIndex != row.rowIndex) {
onDragEnd(dragSrc)
}

dragSrc = null
srcIndex = null
})
}
}
Expand Down Expand Up @@ -85,18 +93,21 @@ document.addEventListener("DOMContentLoaded", () => {
document.querySelectorAll("table.aa-reorderable").forEach((table) => {
setupReorderable({
table,
onUpdate: (row) => {
onDragover: (_row) => {
const allRows = table.getElementsByTagName('tbody')[0].rows
const handle = row.querySelector(".reorder-handle")
const url = handle.dataset["reorderUrl"]
const rowIndex = Array.prototype.indexOf.call(allRows, row)

for (var i = 0; i < allRows.length; i++) {
const loopRow = allRows[i]
const index = i + 1
updateEvenOddClasses(loopRow, index)
updatePositionText(loopRow, index)
}
},
onDragEnd: (row) => {
const handle = row.querySelector(".reorder-handle")
const url = handle.dataset["reorderUrl"]
const allRows = table.getElementsByTagName('tbody')[0].rows
const rowIndex = Array.prototype.indexOf.call(allRows, row)

updateBackend(url, rowIndex + 1)
}
Expand Down

0 comments on commit 714be9c

Please sign in to comment.