import { LightningElement, api } from "lwc"; import cx from "classnames"; import { reflectBooleanAttribute } from "dxUtils/lwc"; export default class Checkbox extends LightningElement { @api disabled: boolean = false; @api errorMessage?: string = "Please check this box if you want to proceed"; @api label?: string; @api type: "checkbox" | "radio" = "checkbox"; @api value!: string; private _checked: boolean = false; private _required: boolean = false; private _name: string | null = null; @api get checked(): boolean { return this._checked; } set checked(value: boolean) { this._checked = value; } @api get name(): string | null { return this._name; } set name(value: string | null) { this._name = value; this.setAttribute("name", value); // reflect to HTML } @api get required(): boolean { return this._required; } set required(value: boolean) { this._required = value; reflectBooleanAttribute(this, "required", value); } private showValidity = false; private get valid(): boolean { return !!(!this.required || this.checked); } private get showError(): boolean { return this.showValidity && !this.valid; } private get className() { return cx("container", this.showError && "show-error"); } @api reportValidity(): boolean { this.showValidity = true; return this.valid; } @api checkValidity(): boolean { return this.valid; } private onChange(e: InputEvent) { this._checked = ((e.currentTarget as HTMLInputElement) || {}).checked; this.dispatchEvent( new CustomEvent("change", { detail: { originalEvent: e, checked: this._checked, value: this.value } }) ); this.showValidity = true; } }