@stimulus-components/checkbox-select-all
Version:
A Stimulus controller for managing checkbox lists.
2 lines (1 loc) • 1.9 kB
JavaScript
(function(global,factory){typeof exports=="object"&&typeof module<"u"?module.exports=factory(require("@hotwired/stimulus")):typeof define=="function"&&define.amd?define(["@hotwired/stimulus"],factory):(global=typeof globalThis<"u"?globalThis:global||self,global.StimulusCheckboxSelectAll=factory(global.Stimulus))})(this,function(stimulus){"use strict";const _CheckboxSelectAll=class _CheckboxSelectAll extends stimulus.Controller{initialize(){this.toggle=this.toggle.bind(this),this.refresh=this.refresh.bind(this)}checkboxAllTargetConnected(checkbox){checkbox.addEventListener("change",this.toggle),this.refresh()}checkboxTargetConnected(checkbox){checkbox.addEventListener("change",this.refresh),this.refresh()}checkboxAllTargetDisconnected(checkbox){checkbox.removeEventListener("change",this.toggle),this.refresh()}checkboxTargetDisconnected(checkbox){checkbox.removeEventListener("change",this.refresh),this.refresh()}toggle(e){e.preventDefault(),this.checkboxTargets.forEach(checkbox=>{checkbox.checked=e.target.checked,this.triggerInputEvent(checkbox)})}refresh(){const checkboxesCount=this.checkboxTargets.length,checkboxesCheckedCount=this.checked.length;this.disableIndeterminateValue?this.checkboxAllTarget.checked=checkboxesCheckedCount===checkboxesCount:(this.checkboxAllTarget.checked=checkboxesCheckedCount>0,this.checkboxAllTarget.indeterminate=checkboxesCheckedCount>0&&checkboxesCheckedCount<checkboxesCount)}triggerInputEvent(checkbox){const event=new Event("input",{bubbles:!1,cancelable:!0});checkbox.dispatchEvent(event)}get checked(){return this.checkboxTargets.filter(checkbox=>checkbox.checked)}get unchecked(){return this.checkboxTargets.filter(checkbox=>!checkbox.checked)}};_CheckboxSelectAll.targets=["checkboxAll","checkbox"],_CheckboxSelectAll.values={disableIndeterminate:{type:Boolean,default:!1}};let CheckboxSelectAll=_CheckboxSelectAll;return CheckboxSelectAll});