@3mo/checkbox-group
Version:
A checkbox-group web-component based on Material Web Components.
93 lines (90 loc) • 2.62 kB
JavaScript
import { __decorate } from "tslib";
import { component, property, css, html, style, eventListener } from '@a11d/lit';
import { Checkbox } from '@3mo/checkbox';
/**
* @element mo-checkbox-group
*
* @ssr true
*
* @attr direction
*/
let CheckboxGroup = class CheckboxGroup extends Checkbox {
constructor() {
super(...arguments);
this.direction = 'vertical';
this.handleSlotChange = () => {
this.updateValue();
this.checkboxes.forEach(checkbox => checkbox.change.subscribe(this.updateValue));
};
this.updateValue = () => {
const childrenSelected = this.childrenSelected;
if (childrenSelected !== this.selected) {
this.selected = childrenSelected;
this.change.dispatch(childrenSelected);
}
};
}
get checkboxes() {
return [...this.children].filter((child) => child instanceof Checkbox);
}
get childrenSelected() {
if (this.checkboxes.every(e => e.selected === true)) {
return true;
}
else if (this.checkboxes.every(e => e.selected === false)) {
return false;
}
else {
return 'indeterminate';
}
}
set childrenSelected(selected) {
if (selected === 'indeterminate') {
return;
}
this.checkboxes.forEach(checkbox => {
if (checkbox.selected !== selected) {
checkbox.selected = selected;
checkbox.change.dispatch(selected);
}
});
}
handleChanged() {
// Whenever "selected" changes, wether by user interaction or by the children changing
// we need to update the childrenSelected state.
this.childrenSelected = this.selected;
}
static get styles() {
return css `
${super.styles}
:host {
--mo-checkbox-group-nested-margin: 32px;
height: auto;
min-height: 32px;
}
::slotted(*) {
margin-inline-start: var(--mo-checkbox-group-nested-margin);
}
`;
}
get template() {
return html `
<mo-flex>
${super.template}
<mo-flex direction=${this.direction} ${style({ flex: '1' })}>
<slot =${() => this.handleSlotChange()}></slot>
</mo-flex>
</mo-flex>
`;
}
};
__decorate([
property()
], CheckboxGroup.prototype, "direction", void 0);
__decorate([
eventListener('change')
], CheckboxGroup.prototype, "handleChanged", null);
CheckboxGroup = __decorate([
component('mo-checkbox-group')
], CheckboxGroup);
export { CheckboxGroup };