import {Controller} from "stimulus" import Sortable from "sortablejs"; import Rails from "@rails/ujs"; export default class extends Controller { static get values() { return {url: String} } static get targets() { return ["table", "body", "actions", "idCheckbox", "idsCheckbox"] } connect() { new Sortable(this.bodyTarget, { handle: '.table-drag-sort-handle', onEnd: (event) => { Rails.ajax({ url: this.urlValue, type: "PATCH", data: this.getIdsDataString(), }); } }) } getIdsDataString() { const table = this.tableTarget let data = "" const handles = [...table.querySelectorAll(".table-drag-sort-handle")] handles.map(handle => { data += `ids[]=${handle.dataset.id}&` }) return data } toggleIds(event) { const checkbox = event.target this.toggleIdsCheckboxes(checkbox.checked) this.toggleIdCheckboxes(checkbox.checked) this.syncFields() this.toggleActions() } toggleId(event) { this.toggleIdsCheckboxes(false) this.syncFields() this.toggleActions() } toggleActions() { const idFields = this.getIdFields() if(idFields.length > 0) { this.actionsTarget.classList.remove('d-none') } else { this.actionsTarget.classList.add('d-none') } } toggleIdsCheckboxes(checked) { this.idsCheckboxTargets.forEach((checkbox) => { checkbox.checked = checked }); } toggleIdCheckboxes(checked) { this.idCheckboxTargets.forEach((checkbox) => { checkbox.checked = checked }); } syncFields() { this.removeIds() if(this.idsCheckboxTarget.checked) { this.addId('') } else { this.idCheckboxTargets.forEach((checkbox) => { if(checkbox.checked) { this.addId(checkbox.value) } }); } } addId(id) { let field = this.getIdField(id) if (!field) { field = this.newIdField(id) this.actionsTarget.querySelector('form').insertAdjacentHTML('afterbegin', field) } } removeIds() { const fields = this.getIdFields() fields.forEach((field) => { this.actionsTarget.querySelector('form').removeChild(field) }); } removeId(id) { const field = this.getIdField(id) if (field) { this.actionsTarget.querySelector('form').removeChild(field) } } newIdField(id) { const template = this.actionsTarget.querySelector('[data-table-target="idFieldTemplate"]') return template.innerHTML.replace(/ID/g, id) } getIdFields() { return this.actionsTarget.querySelectorAll(`input[name="ids[]"]`); } getIdField(id) { return this.actionsTarget.querySelector(`input[name="ids[]"][value="${id}"]`); } }