import { LightningElement, api } from "lwc"; import { toJson } from "dxUtils/normalizers"; type Option = { value: string; label: string; disabled: boolean; }; // API structure modeled after: // https://ant.design/components/checkbox/ // https://github.com/ant-design/ant-design/blob/master/components/checkbox/Group.tsx export default class CheckboxGroup extends LightningElement { @api disabled: boolean = false; @api legend!: string; @api get options(): Option[] { const statefulOptions = this._options.map((option) => ({ ...option, checked: this._value.includes(option.value), disabled: this.disabled || option.disabled })); return statefulOptions; } set options(value) { this._options = toJson(value); } @api get defaultValue(): string[] | null { return this._defaultValue; } set defaultValue(value) { this._value = toJson(value) || []; } @api get value(): string[] { return this._value; } set value(value) { if (this.defaultValue) { console.error( "Do not supply both value and default-value to form groups." ); } this._value = toJson(value) || []; } private _defaultValue: string[] | null = null; private _options: Option[] = []; private _value: string[] = []; private updateValue(checkedValue: string) { this._value = this._value.includes(checkedValue) ? this._value.filter((val) => val !== checkedValue) : [...this._value, checkedValue]; } private onChange(e: CustomEvent) { const { checked, value: checkedValue, originalEvent } = e.detail; this.updateValue(checkedValue); this.dispatchEvent( new CustomEvent("change", { detail: { checked, checkedValue, originalEvent, value: this._value } }) ); } }