import { Controller } from '@hotwired/stimulus' import Sortable from 'sortablejs' import { useFetch } from '../mixins/use_fetch' /* stimulusFetch: 'lazy' */ export default class extends Controller { static targets = [ 'item', 'handle', 'positionField', 'positionLabel' ] static values = { url: String } connect() { useFetch(this) new Sortable(this.element, { item: '[data-sortable-target="item"]', handle: '[data-sortable-target="handle"]', sort: true, onEnd: () => { this.updateOrdering() if (this.urlValue) { this.saveOrdering() } } }) } updateOrdering() { this.positionFieldTargets.forEach((field, index) => { field.value = index + 1 }) this.positionLabelTargets.forEach((label, index) => { label.innerText = index + 1 }) } saveOrdering() { const body = new FormData() this.positionFieldTargets.forEach(field => { body.append(`sorting[${field.dataset.id}]`, field.value) }) fetch(this.urlValue, this.getInitObject('post', body)) } }