import { Controller } from "@hotwired/stimulus"; import Sortable from "sortablejs"; export default class extends Controller { static targets = ["container"]; connect() { this.sortable = Sortable.create(this.containerTarget, { animation: 150, handle: ".drag-handle", group: this.element.dataset.sortableGroup || null, // Enable cross-container dragging if group is defined onEnd: this.reorder.bind(this), // Trigger reordering }); } reorder(event) { const new_items = Array.from(event.to.children); const items = Array.from(event.from.children); // Update sort order and parent course section (if applicable) in the list the item moved to new_items.forEach((item, index) => { const sortInput = item.querySelector("[data-sort-order]"); const sectionInput = item.querySelector("[data-course-section-id]"); if (sortInput) { sortInput.value = index; // Update sort_order based on position } if (sectionInput && event.to.dataset.courseSectionId) { sectionInput.value = event.to.dataset.courseSectionId; // Update parent task ID } }); if(event.to !== event.from) { // Update sort order and parent course section (if applicable) in the list the item was moved from items.forEach((item, index) => { const sortInput = item.querySelector("[data-sort-order]"); const sectionInput = item.querySelector("[data-course-section-id]"); if (sortInput) { sortInput.value = index; // Update sort_order based on position } if (sectionInput && event.from.dataset.courseSectionId) { sectionInput.value = event.from.dataset.courseSectionId; // Update parent task ID } }); } } }