Sha256: 73add6a322258f53d8c7f844f3392bd8d4dd7e2e6546f8fe68f4147832d8991a

Contents?: true

Size: 1.96 KB

Versions: 2

Compression:

Stored size: 1.96 KB

Contents

import {Controller} from "stimulus"

export default class extends Controller {
    static get targets() {
        return ["actions", "idCheckbox", "idsCheckbox"]
    }

    toggleIds(event) {
        const checkbox = event.target
        this.toggleIdsCheckboxes(checkbox.checked)
        this.toggleIdCheckboxes(checkbox.checked)
        this.syncFields()
    }

    toggleId(event) {
        this.toggleIdsCheckboxes(false)
        this.syncFields()
    }

    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.insertAdjacentHTML('afterbegin', field)
        }
    }

    removeIds() {
        const fields = this.getIdFields()
        fields.forEach((field) => {
            this.actionsTarget.removeChild(field)
        });
    }

    removeId(id) {
        const field = this.getIdField(id)
        if (field) {
            this.actionsTarget.removeChild(field)
        }
    }

    newIdField(id) {
        const template = this.actionsTarget.querySelector('[data-index-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}"]`);
    }
}

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
headmin-0.1.2 src/js/headmin/controllers/index_controller.js
headmin-0.1.1 src/js/headmin/controllers/index_controller.js