import { FlatTemplatable } from "tempstream"; import { ProxyFormField } from "../fields/proxy-field.js"; import { CheckboxWithValue } from "./checkbox.js"; import { FieldGroup } from "./field-group.js"; import { FormControlContext } from "./form-control.js"; import { FormFieldControl } from "./form-field-control.js"; import { CheckboxedListField } from "../fields/checkboxed-list.js"; export type DefaultCheckboxOptions = { id?: string; label?: string; hide_errors?: boolean; readonly?: boolean; name?: string; checkboxNameToLabel?: (name: string) => string; classes?: string[]; }; export class CheckboxGroup< Options extends DefaultCheckboxOptions = DefaultCheckboxOptions, > extends FormFieldControl { constructor( public field: CheckboxedListField, public options: Options = {} as Options ) { super([field]); } wrapGroup( fctx: FormControlContext, checkboxes: CheckboxWithValue[] ): Promise { return new FieldGroup(checkboxes, { label: this.options.label, classes: [ ...(this.options.classes || []), "field-group--checkboxes", ], }).render(fctx); } async render(fctx: FormControlContext): Promise { const { parsed: values } = await this.field.getParsedValue( fctx.ctx, fctx.data.raw_values ); const checkboxes = (await this.field.generateOptions(fctx.ctx)).map( (option) => new CheckboxWithValue( new ProxyFormField( false, this.field.name, false, Object.keys(values || {}).includes(option.value) ), { id: this.field.name + "__" + option.value, label: ( this.options.checkboxNameToLabel || ((s: string) => s) )(option.value), default_value: false, }, option.value ) ); return this.wrapGroup(fctx, checkboxes); } }