api reference
Form API Reference
createForm: controls laid out in nested rows and columns with percentage widths, number formats and units, date, date-time and time pickers, a file drop area, disabled and read-only states, rules, and binding to a grid or the data router.
API reference › The form module
All 30 pages Everything on one page → Developer guide →
The form module
modules/form is an opt-in form builder: named items laid out in nested rows and columns, in its own bundle that grows grid core by nothing. It is a sold Lattice feature. The main owner pain it removes is the same one the shell removes - asynchronous redraw: when createForm(el, config) returns, every item is already in the document and already measurable, so there is no awaitRedraw() and no deferred paint. A host that reads getItem(name).el on the very next line measures a real element in the same synchronous task.
import { createForm } from '@toclocoinc/lattice-grid/modules/form';
const form = createForm(document.querySelector('#form'), {
rows: [
{ fieldset: 'Account', items: [
{ type: 'input', name: 'name', label: 'Name', value: 'Ada' },
{ type: 'number', name: 'age', label: 'Age', min: 0, max: 120 },
{ type: 'checkbox', name: 'active', label: 'Active' },
] },
{ cols: [
{ spacer: true },
{ type: 'button', name: 'save', label: 'Save' },
] },
],
});
form.getItem('name').setValue('Grace'); // a silent write, no event
form.getValue(); // { name: 'Grace', age: null, active: false }
form.on('beforeChange', (e) => { if (e.name === 'age' && e.value > 120) e.preventDefault(); });
form.setDensity('comfortable'); // control heights follow the grid's row height
form.destroy();
Rows, columns and blocks. A form is a tree of rows and cols, each nesting the other to any depth, plus items to lay controls side by side. A rows block stacks its children vertically and stretches them to its width; a cols block lays its children side by side, sharing the width equally by default (flex: 1 1 0, min-width: 0 - a child’s own width, flex or css still wins, and a percentage width is a share of the row’s width after its gaps, so three 33.3% items sit on one line) and stacking them into one column once the container drops below config.colsBreakpoint (default 480px, via a container query - 0 or false turns stacking off, so the row never stacks at any width). With wrap: true on the block (or the root config), a percentage width instead resolves against its own rendered line's gaps, not the whole row's - a 100% item fills a line alone and a 50%/50% pair shares just the one gap between them, so a row of many items wrapping onto several lines keeps every line's items flush to its right edge; hiding an item frees its line slot, and showing it again restores the layout. A container is the default block shape (a flex box along its axis); a fieldset is a native <fieldset>/<legend> with its children in a body below; a spacer is flexible space and a separator a rule - or, given a label (a literal such as 'or', or a key resolved through config.messages), a muted label centred between two rules (“ - - or - - ”), the label also its accessible name - both plain blocks. A text item renders a read-only display carrying its value - a label/value pair, not an editable control - and the basic controls are input (subtype text, email, password or url), number (step/min/max), textarea, checkbox, button, rating (a row of icons, whole or half steps, click or arrow), stage (a pipeline of chevron steps), chips (a row of pill buttons for one or several options) and combo (a searchable combobox, described below).
One item, one handle. Every item is a wrapper holding an optional <label> (associated to its control by for/id), the control, and an optional help line. Per item: name, label, labelPosition (top/left), hiddenLabel, labelWidth, width, height, padding, placeholder, helpMessage, hidden, disabled, readOnly and value. getItem(name) returns the handle - { el, name, getValue, setValue, setOptions, reload, show, hide, enable, disable, focus, blur, isVisible, getLabel, setLabel, setHelp } - or undefined for an unknown name, and forEach(fn) hands every handle to fn in document order. setValue(values) writes values silently by name (unknown keys are ignored), getValue() snapshots every named value-holding item as { name: value } (a button holds no value and is not included), and clear() resets each user-editable item to its empty value - '' for text, null for a number, a stage or a single chips, [] for a multi chips, false for a checkbox, 0 for a rating - without firing an event. getItem(name).setLabel(text) changes the item's visible label and its accessible name after the form is built, returning the item for chaining: a field's own <label> text, a button's caption, or - on a handle for a named fieldset - its legend; a hidden label (labelPosition: 'hidden') stays visually hidden but its accessible name still updates, since both read the same element. getLabel() reads the current label back, and setHelp(text) changes the help line under the control (null removes it). Both survive setDensity, setReadOnly, show()/hide() and any re-render, and are what a later getItem reports. A fieldset is not a value-holding item, but naming it - { fieldset: 'Account', name: 'account', items: […] } - makes it retrievable through getItem(name) for exactly this: a handle whose setLabel/getLabel reach the legend.
Events. A field fires input as the user types (the value is live, not yet committed) and change once the edit commits; a checkbox fires change on toggle; a button fires click. Every interactive item fires focus and blur, and an otp fires complete once every box is filled. A change is gated by a cancellable beforeChange - a handler calls event.preventDefault(reason?) or returns false (or a Promise of either) to refuse the commit, which then reverts the control to its last committed value - and the emitted events are subscribed with form.on(name, fn) (or '*' for every past-tense event) and detached with form.off(name, fn). A handler that throws does not stop the others - every handler still runs - and surfaces as an uncaught error: the original error is re-raised on the next microtask, so window.onerror and unhandled-error reporting see it.
Validation. An item declares required (an empty value fails), a validation rule - a built-in name (email, number, integer, url), a whole-value RegExp, or a function (value, item) => boolean | string | void that returns true/undefined for pass, false for a fail, or a string that is the failure message - and the message options errorMessage, successMessage and preMessage. form.validate() checks every rule-bearing item and returns true/false, marking each invalid item with aria-invalid and an associated message (and each pass with its successMessage); item.validate() checks one item. A validationMode of change re-checks an item once its edit commits, blur re-checks it as it loses focus, and submit (the default) checks it only on validate(). The default rule messages live in the module's catalogue - overridable through config.messages - and a validated event reports every failure as { name, rule, message }. The control registry exposes a per-control validate(el, item, value) hook that later controls (file, combo, custom) plug into.
Density. A density level - compact, standard (default) or comfortable - drives every control's height, padding, label gap and fieldset spacing from the grid's own --lattice-* tokens (a control stands one --lattice-row-height tall, so a form beside a grid follows that grid's density), each with a literal fallback so a form on a bare page still draws. form.setDensity(level) changes it live with one attribute write and no re-render, and an unknown level is ignored. The module imports no grid and no core source, ships in its own bundle and UMD global, and destroy() empties the element, removes only what the module added, restores the host's own inline style, and drops every item record, listener and handler.
Spacing and label gap. config.spacing sets the vertical gap between stacked items - a px number or a CSS length - and config.labelGap the gap between an item's label and its field; both default from the density scale, so leaving them unset changes nothing. They are the theme tokens --lattice-form-item-gap and --lattice-form-label-gap, so a CSS theme can set the default a form without an explicit spacing falls back to, and a rows container or fieldset that sets its own spacing overrides it for its own items only. form.setSpacing(value) applies the gap live with one property write and no re-render (null clears the override). Horizontal cols containers keep their own gap, and help/validation lines sit inside the item wrapper, so an item showing a validation message keeps the same gap to the next item as one without.
Disabled and read-only, defined once. Both states are one contract applied identically to every control. disabled leaves the tab order (unless focusableWhenDisabled), shows no hover or active response, sets cursor: not-allowed, carries aria-disabled (or the native disabled attribute), is excluded from validate(), and is styled from the --lattice-disabled-foreground/--lattice-disabled-background/--lattice-disabled-border tokens with text at or above 3:1. readOnly stays focusable and in the tab order, keeps its value readable, selectable and copied, refuses every change path before it happens - typing, click, paste, drop, wheel and the keyboard do nothing, pop-ups open view-only or not at all, and a checkbox, radio, toggle, radiogroup or checkboxgroup guards pointerdown/click/Space/Enter so the value never flickers - carries aria-readonly, is still validated and still appears in getValue()/submit, and is styled from the --lattice-readonly-foreground/--lattice-readonly-background/--lattice-readonly-border tokens (subtle fill, cursor: default, the lock icon). Both are set per item (disabled, readOnly, readOnlyWhen) and form-wide with form.setDisabled(bool) and form.setReadOnly(bool).
Data binding. config.bind binds the form to a record instead of a static config. bind: { grid, rowKey } binds a grid row: when no layout is declared, one item per column is generated from the grid's own columns - their titles, types and editors - so a boolean column becomes a checkbox and a number column a number; the form follows the grid's density by default; save() writes the dirty items once through the grid's edit path (permissions, read-only, parse, validation and the beforeEdit gate honoured); and revert() restores the bound values. External edits to the row update a clean item in place and leave a dirty one alone, flagging it with isConflicted(). bind: { router, route, key, onSave? } follows a data-router record with the same update-unless-dirty rule: the form reads the record eagerly through router.get(route, key) - so a form created after the ingest still fills at once, whatever the order - then subscribes to the route's keyed diffs, and destroy() unsubscribes. save() writes the dirty items back through router.apply, then calls bind.onSave(changes, record) when the host gave one (may be async; a rejection reverts the router record and leaves the form dirty). A form group takes the same bind once: every member fills with its own fields off the record, and group.save() writes one router update with all the members' dirty fields, calling onSave once. A plain object of values initialises the form and is written back by save(). isDirty(name?) reports an unsaved user edit on one item or the whole form, and editing is the only thing that marks an item dirty - setValue(), revert() and bound-record updates are silent. The binding is duck-typed against the grid's public API, so the module still imports no grid and no core source.
Custom controls. registerControl(type, definition) makes a control type a first-class item: the definition's create(el, item, api) builds the control's DOM into el, getValue(el)/setValue(el, value) round-trip the value through getValue()/setValue(), and an optional validate(value, item, el) refuses a bad commit (return true to accept, false or a message to refuse, a Promise is awaited). The registered control gets the same wrapper, label, item API, events and density as a built-in, and a later registration for the same type replaces the earlier one. Its api talks back through the same path a native edit takes: api.onChange() reads the control's current value through getValue(el) and commits it (running beforeChange, validation and change), api.onChange(value) commits the given value, and api.onInput()/api.onInput(value) report the live value.
Styling a custom control. The form styles the control's frame - its label, help, validation line and density spacing - but never the markup create builds: a <button>, <input>, <select> or any other element inside it sizes and looks exactly as the same markup outside the form, so five inline buttons stay on one line at their own width. To take the form's field look, put the opt-in class lat-form__native on a native <input>, <textarea>, <select> or <button>: it gets the field box (full width, row height, field border and background), the field focus ring and the disabled look. A control that should fill the remaining height of a fixed-height form sets the item's height to '100%' and gives the item css: { flex: '1 1 auto', minHeight: 0 } so its wrapper grows into the spare space; the form then sizes the .lat-form__custom container to that height, so the markup create builds - which fills it with its own height: 100% or flex: 1 - gets the whole remaining space, exactly as a content container with the same height does. An item without a height is unchanged.
A content container. { type: 'container', name, html, width, height, padding } is a place in the form that shows host HTML or hosts another Lattice view, not a layout block - a block that also names rows/cols/items stays the plain layout container whatever its type. It renders <div class="lat-form__container" role="region">, sized by width/height (a px number, a CSS length, or 'content', the default, to size to its own content) with an optional padding; a height of '100%' fills the remaining height of a fixed-height form when the item grows into it (css: { flex: '1 1 auto' }). An html string is rebuilt node by node rather than assigned through innerHTML: every <script> element, every on* attribute and every javascript:-scheme value is dropped, and everything else - inline styles included, because the host authored them - survives untouched; an html value that is already an element is appended as is, with no sanitising. The item carries no value: it never appears in getValue()/setValue() and is skipped by validate(), exactly like a button. After creation, form.getItem(name).attach(viewOrElement, { keep? }) appends an element - or, for an object exposing .el, .root or .element (a createGrid/createChart/createKanban/createCalendar/createGantt/createForm result), that element - sized to the region (width 100%; height forced to the region's own configured height only when one was set, otherwise the view keeps its own). A second attach() replaces the first, and form.destroy() tears the item down too, destroying the attached view (calling its own destroy() when it has one) unless keep: true was given either time; attachHTML(html) replaces the content with sanitised host HTML the same way. getWidget() returns whatever is currently attached, or null. A nested createForm attached this way keeps its own value: the outer form's getValue() never merges it.
A grid item. { type: 'grid', name, columns, rowKey, value, createGrid } renders a real Lattice grid as a form field - the label, helpMessage, width/height, hidden/visibleWhen, readOnly/disabled, density, theme tokens and dark mode work as for any item, and every column option the grid accepts is allowed in columns (a cell is editable when its column says edit: true). A height of '100%' makes the grid fill the remaining height of a fixed-height form - give the item css: { flex: '1 1 auto', minHeight: 0 } so it grows into the spare space, and the grid host fills what is left after the optional row-control toolbar; a number or a CSS-length height stays fixed. The form bundles no grid core, so the factory is handed in: createGrid on the item, or once on the form config. The item's value is its rows - form.getValue()[name] is an array of row objects (valueAs: 'rows', the default) or of arrays in column order (valueAs: 'arrays'), and setValue loads rows given in either shape. A money-shaped currency cell reads as its plain amount. fields: { prop: { row: <rowKey value>, col: <field> } } maps single cells to further top-level properties of the form value, read and written like any field (getValue(), setValue(), getItem(prop), dirty tracking, a bind record, a rule's visibleWhen); valueRows: false drops the rows array and keeps only those cells. Events: a typed edit runs the cancellable beforeChange first - once for the item and once for each mapped property the edit touches - and a veto cancels the edit; the grid's own column validators gate it as they always do. Once it lands the form fires change once for the item and once for each mapped property that moved, and the same happens once per row added or removed. Validation: required means at least one row; form.validate() re-checks every cell - the column's validation, its edit.validate, and min/max in a number column's edit.props - marks each offending cell (aria-invalid, the invalid class, a tooltip), and fails the item with a message naming the row and the column (Row 2, Cost: Must be at most 1000., from the catalogue in every bundled locale, taken from the grid's own locale unless messages says otherwise); getItem(name).focus() lands on the first offending cell. Rows: rowControls: true (off by default) adds keyboard-operable Add row and Delete row buttons under the grid - delete acts on the selected rows, else the row holding the focused cell - and the handle offers addRow(row?), removeRows(keys) and getGrid(); newRow supplies defaults for a blank row. Totals: totals: { row, column } adds a display-only totals row (pinned beneath the body) and/or a computed totals column, each summing the number columns or reduced by 'sum', 'avg', 'count' or your own function; neither is ever part of the value. form.clear() empties the rows, and createFormGroup merges the item and its mapped cells like any other.
Declarative rules. An item's visibleWhen, readOnlyWhen or requiredWhen is a rule re-evaluated on every committed change: a constant, a function of the whole { name: value } snapshot, or a condition on one named item's value with equals, in, empty or fn. A visibleWhen that is false hides the item, a readOnlyWhen that is true makes its control read-only, and a requiredWhen that is true marks it required - its commit path then refuses an empty value. A rule composes on the item's own hidden/readOnly baseline, so it never fights the item API's hide()/show()/enable()/disable().
Wizards. A steps array turns the form into a wizard: each { id, label, rows } step is one body, only the active one visible, under a step indicator whose stepOrientation is horizontal (default) or vertical. form.next(), form.goToStep(index) to a later step, and a click on a later indicator step all validate the current step's items first - exactly as form.validate() does, so a refused move shows the same errors, fires the validated event and moves focus to the first invalid item, resolving false and staying put. form.back(), goToStep(index) to an earlier step and an earlier indicator step go back without validating; the indicator marks each step pending, active, complete or in error, and never disagrees with the form. On the last step next() reads "Finish" and validates in place, resolving false while it is invalid. Set validateSteps: false to opt out - the integrator then runs validate() itself, and forward navigation is unchecked.
Files and rich text. A file item is an uploader field: drop, paste or pick, with accept (extensions or MIME patterns), maxSize and maxFiles enforced at admission, and a host upload(file, { onProgress, signal }) callback that does the actual upload. The file list shows per-file progress and status with retry and remove, and the value is the accepted file entries - a rejected file stays visible with a message but never enters the value. A richtext item is a sanitised HTML editor: toolbar presets (basic/html/rich or an item-name array) over bold, italic, underline, strikethrough, colour, case, paragraph styles, lists, alignment, links, images, source view and undo/redo, with keyboard shortcuts and paste cleanup. Its whitelist sanitiser is the security boundary, shared with the grid's rich-text editor as one implementation: scripts, event handlers, srcdoc, id/name clobbering and javascript:/vbscript:/data: URLs never survive pasting, dropping or setValue, and every _blank link carries rel="noopener noreferrer". Both honour density, theme tokens, readOnly/disabled and the item API, and clear to [] (file) or '' (richtext). The same rich-text editor is available as a grid pop-up editor for long text with edit: { editor: 'richtext' }.
Passwords and one-time codes. A password input carries a reveal button inside the field: an eye that toggles the input between the native password and text types, keyboard-operable like any button, carrying aria-pressed and a name from the catalogue (“Show password”/“Hide password”). It returns to hidden when focus leaves the field and when the form validates or submits, and reveal: false renders a bare password input with no button - the value, events and validation are unchanged. An otp item is a one-time-code entry of single-character boxes: length (default 6) sets how many, mode (numeric default or alphanumeric) drives each box’s inputmode/pattern and the characters it admits, the first box advertises autocomplete="one-time-code", and mask hides each glyph behind the password disc. Typing advances, Backspace steps back and clears, the arrow keys move, and pasting fills every box (spaces and dashes stripped). getValue() returns the joined string, setValue() fills the boxes, and a complete event fires once every box is filled. Screen readers hear one labelled group, each box announced as “Digit n of length”.
Buttons and button rows. A button item is an acting control, not a value: it takes an icon (a name from the grid’s icon set, an image URL or data: URI, or an element) with iconPosition (start default / end), sitting a density-scaled gap (about 0.5em) from the text and vertically centred with it, a variant (primary, secondary default, tonal, outline, text or danger - theme-token colours, light and dark), fullWidth to span the form (inside a cols row it fills its own column, so two full-width buttons keep sharing the row), a size (sm/md/lg), a textTransform (none default / uppercase) and a buttonType (button, submit or reset). A submit button runs form.validate() first and only then fires a submit event on the form’s element with the values in event.detail.values when valid; a reset button calls form.clear(). loading: true (or item.setLoading(bool)) swaps the icon for a spinner, keeps the width, sets aria-busy and makes the button ignore clicks; a href turns it into a link styled as a button. An icon with no label is icon-only: it requires ariaLabel and renders square. A { type: 'buttons', align, items } row lays a group of buttons out along the width with align start (default), end, center, stretch or space-between, and each child takes the same options as a button item.
A button is an action item, and its states are named tokens. Because a button acts rather than holds a value, the view draws no field <label>, required asterisk, help line or hint line for it - its label is its own text, shown once - and in a labelPosition: 'left' form it lines up with the fields’ input column (unless fullWidth spans the row). Every variant defines the same state matrix in light and dark, each state’s colours read from an overridable --lattice-button-<variant>-<state> token: rest; hover (one step toward the foreground - a shade in light, a tint in dark); active (a deeper step); focus-visible (a 2px accent ring with a 2px offset, never removed); disabled (muted text, border and fill with text at or above 3:1 against its fill, cursor: not-allowed, no hover or pressed change, aria-disabled, and still in the tab order only when focusableWhenDisabled: true keeps it focusable instead of natively disabled); loading (the spinner from loading); and toggled (a distinct pressed look). toggle: true makes the button two-state: it flips aria-pressed and fires change with the new boolean (starting pressed when value is true). The swatches below show each variant’s fill per state, light and dark.
| Variant | Rest | Hover | Active | Toggled | Disabled |
|---|---|---|---|---|---|
| primary | |||||
| secondary | |||||
| tonal | |||||
| outline | |||||
| text | |||||
| danger |
| Member | Description |
|---|---|
| createForm(el, config?) | Create a form. config is { rows | cols, density, spacing, labelGap, labelPosition, labelWidth, requiredHint, colsBreakpoint, bind, css, messages, steps, stepOrientation }; rows stacks the top-level blocks vertically, cols lays them left-to-right sharing the width equally (used when rows is absent), spacing is the vertical gap between items (a px number or a CSS length, defaulting to the density's gap) and labelGap the gap between an item's label and its field (defaulting to half the density's space), labelPosition (top default / left / hidden) and labelWidth are the defaults every item inherits (an item’s own value wins), requiredHint is the placeholder marker a required field with no visible label shows (true appends " *", a string resolves through the catalogue, false shows nothing), colsBreakpoint is the container width below which a cols container stacks into one column (default 480px; 0 or false never stacks), bind binds the form to a record ({ grid, rowKey }, { router, route, key, onSave? } or a plain values object), messages supplies a t(key, params) catalogue for the separator's accessible label and the validation defaults, and a steps array turns the form into a wizard with a horizontal (default) or vertical stepOrientation. Returns { el, config, getItem, getValue, setValue, clear, validate, forEach, on, off, setDensity, setSpacing, setReadOnly, setDisabled, isDirty, isConflicted, save, revert, steps, activeStep, next, back, goToStep, destroy }. |
| createForm(el, config?) | Create a form. config is { rows | cols, density, spacing, labelGap, labelPosition, labelWidth, requiredHint, colsBreakpoint, bind, css, messages, steps, stepOrientation, validateSteps, createGrid }; rows stacks the top-level blocks vertically, cols lays them left-to-right sharing the width equally (used when rows is absent), spacing is the vertical gap between items (a px number or a CSS length, defaulting to the density's gap) and labelGap the gap between an item's label and its field (defaulting to half the density's space), labelPosition (top default / left / hidden) and labelWidth are the defaults every item inherits (an item’s own value wins), requiredHint is the placeholder marker a required field with no visible label shows (true appends " *", a string resolves through the catalogue, false shows nothing), colsBreakpoint is the container width below which a cols container stacks into one column (default 480px), bind binds the form to a record ({ grid, rowKey }, { router, route, key, onSave? } or a plain values object), messages supplies a t(key, params) catalogue for the separator's accessible label and the validation defaults, a steps array turns the form into a wizard with a horizontal (default) or vertical stepOrientation, and validateSteps: false opts out of validating the current step on a forward move (the integrator runs validate() itself). Returns { el, config, getItem, getValue, setValue, clear, validate, forEach, on, off, setDensity, setSpacing, setReadOnly, setDisabled, isDirty, isConflicted, save, revert, steps, activeStep, next, back, goToStep, destroy }. |
| registerControl(type, definition) | Register a custom control type as a first-class item. definition is { create(el, item, api), getValue(el), setValue(el, value), validate?(value, item, el), destroy?(el) }; the control gets the same wrapper, label, item API, events and density as a built-in, and an item height of '100%' fills the remaining height of a fixed-height form, as a container does. A later registration for the same type replaces the earlier one. |
| item | Each item: type (a built-in input/number/textarea/checkbox/button/text/combo/rating/stage or a registered custom type), name, label, labelPosition (top/left), hiddenLabel, labelWidth, width and height (each a number, a CSS length or 'content'), padding, placeholder, helpMessage, hidden, disabled, readOnly, value, required, validation, errorMessage, successMessage, preMessage, validationMode, css, and the rules visibleWhen, readOnlyWhen, requiredWhen. input takes subtype (a password subtype also reveal); number takes step/min/max. rating takes max, allowHalf, allowClear, icon or icons ({ filled, empty }), labels, showValue and size (sm/md/lg); stage takes stages, current, completed, clickable and showIcons; chips takes options ({ value, label, icon?, disabled? }), multiple, allowEmpty, wrap and max; otp takes length, mode (numeric/alphanumeric) and mask. select, radiogroup and checkboxgroup take options; a radiogroup/checkboxgroup also takes orientation (vertical/horizontal) or columns (an n-column grid read across then down). button takes icon (a name, URL/data: URI or element), iconPosition (start/end), variant (primary/secondary/tonal/outline/text/danger), fullWidth, size (sm/md/lg), textTransform (none/uppercase), buttonType (button/submit/reset), loading, href, ariaLabel (required for an icon-only button), toggle (a two-state button that flips aria-pressed and fires change with the new boolean) and focusableWhenDisabled (keep a disabled button focusable and in the tab order, reading aria-disabled instead of being natively disabled); a { type: 'buttons', align, items } row lays buttons out by align (start/end/center/stretch/space-between), each child taking the same options. |
| getItem(name) | The item handle { el, name, getValue, setValue, setOptions, reload, show, hide, enable, disable, focus, blur, isVisible, validate, setLoading, getLabel, setLabel, setHelp } - el is the item's wrapper element. A container item's handle additionally has attach(viewOrElement, { keep? }), attachHTML(html) and getWidget(). A named fieldset is also retrievable this way, for a handle whose setLabel/getLabel reach its legend. undefined for an unknown name. |
| getItem(name).getLabel() | The item's current label - a field's label, a button's caption, or a fieldset's legend - or null when it carries none. |
| getItem(name).setLabel(text) | Change the item's visible label and its accessible name: a field's label, a button's caption, or (on a named fieldset's handle) its legend; on a registered custom control, the frame's own label and the label the control's item object carries. A hidden label (labelPosition: 'hidden') stays visually hidden but its accessible name still updates. Survives setDensity, setReadOnly, show()/hide() and any re-render, and is what a later getItem reports. Returns the item, for chaining. |
| getItem(name).setHelp(text) | Change the help line under the control; null removes it. Survives setDensity, setReadOnly, show()/hide() and any re-render, the same as setLabel. Returns the item, for chaining. |
| getValue() | Every named value-holding item as a plain { name: value } object, in document order. A button is not included. |
| setValue(values) | Write values into the matching named items, silently (no event fires). Keys that name no item are ignored. |
| clear() | Reset every user-editable item to its empty value - '' for a text field, null for a number, a stage or a single chips, [] for a multi chips, false for a checkbox, 0 for a rating. A read-only text display is left as it is. No event fires. |
| validate() | Check every item that declares required, validation or a control hook, paint each verdict (aria-invalid and an associated message on the failures, the item's successMessage on the passes) and report all failures through one validated event. Returns true only when no item failed. |
| forEach(fn) | Walk every item in document order, handing each handle to fn. |
| on(name, fn) | Subscribe to a form event - change, input, beforeChange (cancellable), click (buttons), focus, blur, complete (an otp filled) or validated - or to '*' for every past-tense event; returns an unsubscribe. A beforeChange handler cancels by calling preventDefault(reason?) or returning false (or a Promise of either). |
| off(name, fn) | Remove a handler registered with on. |
| setDensity(density) | Change the form's density live - compact, standard or comfortable - re-theming every control's height, padding, label gap and fieldset spacing with one attribute write and no re-render. An unknown value is ignored. |
| setSpacing(spacing) | Change the vertical gap between items live - a px number or a CSS length - re-theming every stacked container (rows, a fieldset body and the form root) with one property write and no re-render. null removes the override so the gap returns to the density default (or the --lattice-form-item-gap theme token). Horizontal cols containers keep their own gap. |
| setReadOnly(readOnly) | Set every item read-only (or back to editable) in one call. A read-only item stays focusable and in the tab order, keeps its value readable, selectable and copied, refuses every change path before it happens, carries aria-readonly, is still validated and still appears in getValue(), and is styled from the read-only tokens (subtle fill, cursor: default, the lock icon). Composes with each item's own readOnly and readOnlyWhen. |
| setDisabled(disabled) | Set every item disabled (or back to enabled) in one call. A disabled item leaves the tab order (unless focusableWhenDisabled), has no hover/active response, shows cursor: not-allowed, carries aria-disabled or the native disabled attribute, is excluded from validate(), and is styled from the disabled tokens with text at or above 3:1. |
| isDirty(name?) | Whether an item (or, with no name, the whole form) holds a value the user edited and has not yet saved or reverted. On an unbound form nothing is ever dirty. |
| isConflicted(name?) | Whether an item (or the whole form) is in conflict: the user has an unsaved edit, and an external change to the bound record arrived for the same item, which the form therefore did not overwrite. |
| save() | Save the dirty items. For a grid binding the writes go through the grid's own edit path in one call (permissions, read-only, parse, validation and the beforeEdit gate honoured); for a router binding they are applied back through router.apply and, when bind.onSave was given, handed to it (may be async - a rejection reverts the router record and keeps the items dirty); for a values binding they are written back into the bound object. Returns true when saved (or nothing to save), or a Promise<boolean> when the write is asynchronous. An unbound form returns false. |
| revert() | Restore every dirty item to its bound/committed value and clear the dirty and conflict flags. |
| next() | Advance a wizard one step, validating the current step's items first - as form.validate() does, so a refused move shows the same errors, fires validated and focuses the first invalid item. Resolves true when the wizard moved (or the final step validated), false while the current step is invalid or there is no next step; validateSteps: false skips the validation. Not a wizard: resolves false. |
| back() | Go back one step - always allowed, never validated. Resolves false when already on the first step. |
| goToStep(index) | Move a wizard to a step by index. Forward moves validate the steps passed over (the first invalid one is focused, marked in error and stops the move); backward moves are always allowed, and validateSteps: false skips the forward validation. Resolves false when an intermediate step is invalid or the index is out of range. |
| destroy() | Empty the element, remove only what the module added (class, density attribute, own inline style), and drop every item record, listener and handler. The host still owns the element. |
Values, a committed edit, a veto and density, executed
A form is created over the in-tree DOM test double: the configured value is read, silent writes and bulk
setValue land without an event, a half-step rating and a selected stage round-trip
through getValue()/setValue(), one committed edit fires change exactly once, a
beforeChange handler vetoes the next edit and the control reverts, clear() empties the fields,
and setDensity() re-themes the root - with the layout rects and the real Chrome control heights asserted
in test/form-browser.test.js.
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, {
colsBreakpoint: 400, // a cols block stacks below 400px
css: { gap: '2px' }, // the form root's own css
cols: [ // top-level columns, not rows
{ rows: [
{ type: 'input', name: 'name', label: 'Name', value: 'Ada', placeholder: 'Full name', helpMessage: 'As it appears' },
] },
{ fieldset: 'Account', items: [
{ type: 'input', subtype: 'email', name: 'email', label: 'Email', labelPosition: 'left', labelWidth: '6em', placeholder: 'you@example.com', value: 'a@b.c' },
{ type: 'number', name: 'age', label: 'Age', min: 0, max: 120, step: 1 },
{ type: 'checkbox', name: 'active', label: 'Active' },
{ type: 'rating', name: 'score', label: 'Score', max: 5, value: 4.5, allowHalf: true, allowClear: true, icons: { filled: 'star', empty: 'heart' }, labels: ['Poor', 'Fair', 'Good', 'Great', 'Best'], showValue: true, size: 'md' }, // icon: 'star' is the single-glyph shorthand
{ type: 'stage', name: 'phase', label: 'Phase', stages: ['Draft', 'Review', 'Approved'], current: 'Review', completed: 'Draft', clickable: true, showIcons: true },
{ type: 'button', name: 'save', label: 'Save' },
{ type: 'input', name: 'locked', label: 'Locked', readOnly: true, value: 'fixed', width: '12em', css: { opacity: '0.7' } },
{ type: 'input', name: 'off', label: 'Off', disabled: true, value: 'grey' },
{ text: 'read-only display', name: 'note', label: 'Note' },
] },
],
});
const name = form.getItem('name');
const started = name.getValue(); // 'Ada' - the configured value
name.setValue('Bob'); // a silent write, no event
form.setValue({ age: 36 }); // bulk silent write
const snapshot = form.getValue(); // { name: 'Bob', age: 36, active: false, … }
const score = form.getItem('score').getValue(); // 4.5 - the configured half rating
const phase = form.getItem('phase').getValue(); // 'Review' - the current stage
form.setValue({ score: 3, phase: 'Approved' }); // bulk silent writes land too
const rating = form.getItem('score').getValue(); // 3
const stage = form.getItem('phase').getValue(); // 'Approved'
let walked = 0;
form.forEach(() => { walked += 1; }); // 10 items, the button too
let changes = 0;
const onChange = () => { changes += 1; };
form.on('change', onChange); // subscribe to committed edits
const input = name.el.querySelector('input');
input.value = 'Zed';
input.dispatchEvent(new TestEvent('change', { bubbles: true }));
const committed = form.getValue().name; // 'Zed' - one change event
form.on('beforeChange', (e) => { e.preventDefault(); }); // veto every commit
input.value = 'Nope';
input.dispatchEvent(new TestEvent('change', { bubbles: true }));
const vetoed = form.getValue().name; // still 'Zed'
const reverted = input.value; // the control reverted to 'Zed'
form.setDensity('comfortable'); // control heights follow the grid's row height
const density = root.getAttribute('data-density'); // 'comfortable'
const note = form.getItem('note').getValue(); // the read-only text display
const emailType = form.getItem('email').el.querySelector('input').type;
const lockedReadOnly = form.getItem('locked').el.querySelector('input').readOnly;
const offDisabled = form.getItem('off').el.querySelector('input').disabled;
form.clear(); // empty the editable fields
const after = form.getValue(); // name '', age null, active false
form.off('change', onChange); // detach the handler
form.destroy();
return [started, snapshot.name, snapshot.age, walked, changes, committed, vetoed, reverted, density, after.active, note, emailType, lockedReadOnly, offDisabled, score, phase, rating, stage].join('|');
Spacing and label gap, executed
The vertical gap between items and the gap between a label and its field are form-level options, read as inline custom properties a CSS theme can also set; setSpacing re-themes live - with the real Chrome rects asserted in test/form-spacing-2183-browser.test.js.
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, {
spacing: 24, // a px number, 24px between items
labelGap: 2, // a px number, 2px label to field
rows: [
{ type: 'input', name: 'a', label: 'A' },
{ type: 'input', name: 'b', label: 'B' },
],
});
const spacing = root.style.getPropertyValue('--lattice-form-item-gap'); // '24px'
const labelGap = root.style.getPropertyValue('--lattice-form-label-gap'); // '2px'
form.setSpacing(16); // live re-theme, no re-render
const live = root.style.getPropertyValue('--lattice-form-item-gap'); // '16px'
const stillLabel = root.style.getPropertyValue('--lattice-form-label-gap'); // '2px'
form.setSpacing('8px'); // a CSS length works too
const css = root.style.getPropertyValue('--lattice-form-item-gap'); // '8px'
form.setSpacing(null); // null clears the override
const cleared = root.style.getPropertyValue('--lattice-form-item-gap'); // '' (density default)
form.setSpacing('1.5rem'); // any CSS length
const rem = root.style.getPropertyValue('--lattice-form-item-gap'); // '1.5rem'
form.destroy();
return [spacing, labelGap, live, stillLabel, css, cleared, rem].join('|');
A button's caption after the form is built, executed
A two-step flow written by hand - show()/hide() swap the visible section, and the same button that moved you there relabels itself from Next to Submit via setLabel(). The caption and the accessible name are the same text, so there is nothing left pointing at “Next”.
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, {
rows: [
{ type: 'input', name: 'email', label: 'Email' },
{ type: 'input', name: 'amount', label: 'Amount', hidden: true }, // step 2, not shown yet
{ type: 'button', name: 'advance', label: 'Next' },
],
});
const advance = form.getItem('advance');
const buttonEl = advance.el.querySelector('button');
const captionBefore = advance.getLabel(); // 'Next'
const renderedBefore = buttonEl.textContent; // 'Next'
form.getItem('email').hide(); // leave step 1
form.getItem('amount').show(); // enter step 2
const captionAfter = advance.setLabel('Submit').getLabel(); // chains, then reads back 'Submit'
const renderedAfter = buttonEl.textContent; // 'Submit'
const ariaLabel = buttonEl.getAttribute('aria-label'); // null - the caption itself is the accessible name
form.destroy();
return [captionBefore, renderedBefore, captionAfter, renderedAfter, String(ariaLabel)].join('|');
Any item prop, changed after build, executed
getItem(name).set(props) applies any subset of an item's own config after the form is already built - placeholder, label, required and the rest of the props listed on FormItemLiveProps - re-rendering only what changed and returning the item for chaining, the same contract setLabel/setHelp are now thin wrappers over. setPlaceholder/getPlaceholder are shortcuts for set({ placeholder })/get('placeholder'). Below, a city field's placeholder follows whatever the user just typed into a country field, through an ordinary change handler; set({ required: true }) shows the same call working for a prop with no dedicated shortcut, and a prop the item does not carry warns once on the console and is otherwise ignored - the field's value is never touched by a set() that cannot apply.
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, {
rows: [
{ type: 'input', name: 'country', label: 'Country', placeholder: 'Country' },
{ type: 'input', name: 'city', label: 'City', placeholder: 'City' },
],
});
form.on('change', ({ name, value }) => { // the placeholder follows another field
if (name === 'country') form.getItem('city').set({ placeholder: value ? `City in ${value}` : 'City' });
});
const city = form.getItem('city');
const before = city.getPlaceholder(); // 'City'
const countryInput = form.getItem('country').el.querySelector('input');
countryInput.value = 'France';
countryInput.dispatchEvent(new TestEvent('change', { bubbles: true }));
const after = city.getPlaceholder(); // 'City in France'
const rendered = city.el.querySelector('input').placeholder; // the same text, live on the native input
const chained = city.set({ required: true }).get('required'); // true - set() chains and get() reads it back
city.set({ bogus: true }); // not a live prop: warns once, ignored
form.destroy();
return [before, after, rendered, String(chained)].join('|');
Percentage widths in a cols row, executed
A percentage width in a cols row is a share of the row’s width after its gaps, so three 33.3% items each subtract two-thirds of the gap and sit on one line - with the real-Chrome geometry asserted in test/form-width-2202-browser.test.js.
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, {
cols: [ // three columns side by side
{ type: 'input', name: 'opportunity', label: 'Opportunity name', width: '33.3%' },
{ type: 'input', name: 'account', label: 'Account', width: '33.3%' },
{ type: 'input', name: 'contacts', label: 'Contacts', width: '33.3%' },
],
});
// Each basis is 33.3% minus that item's share of the row's two gaps, so the
// three items total 100% of the row after the gaps and stay on one line.
const flexOf = (name) => form.getItem(name).el.style.getPropertyValue('--lattice-item-flex');
const widths = [flexOf('opportunity'), flexOf('account'), flexOf('contacts')].join('|');
form.destroy();
return widths;
Per-line percentage widths with wrap, executed
wrap: true on a cols block resolves each percentage width against its own rendered line's gaps rather than the whole row's: a hidden item frees its line slot, so the gap count the remaining items on that line share drops too - here two 50% items alone subtract one gap each once their sibling is hidden, instead of the row's two - with the real-Chrome geometry (a full line, a wrapped 50/50 pair, mixed px and %, and a live hide/show) asserted in test/form-cols-wrap-2559-browser.test.js. columnGap/rowGap (named here as the theme's own default) feed the same per-line maths the flex basis below reads, through --lattice-cols-column-gap, so the basis stays correct whatever gap the row actually draws.
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const flexOf = (form, name) => form.getItem(name).el.style.getPropertyValue('--lattice-item-flex');
// `c` starts hidden, so the wrap row's first (and only) reflow counts just
// `a` and `b` on their line: one gap between the two of them, not the row's two.
const wrapped = createForm(createTestDom().root, {
wrap: true,
columnGap: 4, rowGap: 4, // the theme's own default, named explicitly
cols: [
{ type: 'input', name: 'a', label: 'A', width: '50%' },
{ type: 'input', name: 'b', label: 'B', width: '50%' },
{ type: 'input', name: 'c', label: 'C', width: '50%', hidden: true },
],
});
const wrappedFlex = [flexOf(wrapped, 'a'), flexOf(wrapped, 'b')];
wrapped.destroy();
// Without `wrap: true` the same row still uses the whole row's two gaps.
const plain = createForm(createTestDom().root, {
cols: [
{ type: 'input', name: 'a', label: 'A', width: '50%' },
{ type: 'input', name: 'b', label: 'B', width: '50%' },
{ type: 'input', name: 'c', label: 'C', width: '50%', hidden: true },
],
});
const plainFlex = [flexOf(plain, 'a'), flexOf(plain, 'b')];
plain.destroy();
return [...wrappedFlex, ...plainFlex].join('|');
Cols breakpoint and full-width buttons, executed
colsBreakpoint: 0 (or false) turns stacking off so a cols row never stacks, and a fullWidth button fills its own column while the columns keep sharing the row - with the real-Chrome geometry asserted in test/form-cols-breakpoint-2292-browser.test.js.
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, {
colsBreakpoint: false, // false (or 0): never stack
cols: [
{ type: 'button', name: 'ok', label: 'OK', fullWidth: true },
{ type: 'button', name: 'cancel', label: 'Cancel', fullWidth: true },
],
});
const neverFalse = root.style.getPropertyValue('--lattice-cols-container'); // 'lat-cols-never'
const okFull = form.getItem('ok').el.querySelector('button').getAttribute('data-full'); // 'true'
const cancelFull = form.getItem('cancel').el.querySelector('button').getAttribute('data-full'); // 'true'
form.destroy();
const zero = createForm(root, {
colsBreakpoint: 0, // 0 means never stack too
cols: [
{ type: 'input', name: 'a', label: 'A' },
{ type: 'input', name: 'b', label: 'B' },
],
});
const neverZero = root.style.getPropertyValue('--lattice-cols-container'); // 'lat-cols-never'
zero.destroy();
const positive = createForm(root, {
colsBreakpoint: 200, // a positive number keeps the old behaviour
cols: [
{ type: 'input', name: 'c', label: 'C' },
{ type: 'input', name: 'd', label: 'D' },
],
});
const positiveBp = root.style.getPropertyValue('--lattice-cols-container'); // 'lat-cols-bp-200'
positive.destroy();
return [neverFalse, okFull, cancelFull, neverZero, positiveBp].join('|');
Disabled and read-only, executed
The two states are one contract across every control, set per item or form-wide - with the real Chrome focus, cursor, token and value assertions over all 16 control types in test/form-disabled-readonly-2198-browser.test.js.
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, {
rows: [
{ type: 'input', name: 'name', label: 'Name', value: 'Ada' },
{ type: 'checkbox', name: 'active', label: 'Active', value: true },
{ type: 'rating', name: 'score', label: 'Score', max: 5, value: 3 },
{ type: 'input', name: 'need', label: 'Need', required: true },
],
});
form.setReadOnly(true); // the whole form is read-only
const nameRO = form.getItem('name').el.querySelector('input').readOnly; // true
const activeRO = form.getItem('active').el.querySelector('input').getAttribute('aria-readonly'); // 'true'
const scoreRO = form.getItem('score').el.querySelector('.lat-form__rating').getAttribute('aria-readonly'); // 'true'
const valueName = form.getValue().name; // 'Ada' - the value survives
form.setReadOnly(false); // editable again
const nameROafter = form.getItem('name').el.querySelector('input').readOnly; // false
form.setDisabled(true); // the whole form is disabled
const nameDisabled = form.getItem('name').el.querySelector('input').disabled; // true
const activeDisabled = form.getItem('active').el.querySelector('input').disabled; // true
const scoreDisabled = form.getItem('score').el.querySelector('.lat-form__rating').getAttribute('aria-disabled'); // 'true'
const validateDisabled = form.validate(); // true - the empty required field is skipped while disabled
form.setDisabled(false);
const validateEnabled = form.validate(); // false - the empty required field fails again
form.destroy();
return [nameRO, activeRO, scoreRO, valueName, nameROafter, nameDisabled, activeDisabled, scoreDisabled, validateDisabled, validateEnabled].join('|');
Label position, width and hidden labels, executed
labelPosition and labelWidth set at the form (or a container or fieldset) are the defaults every item inherits, an item’s own value winning. labelPosition: 'hidden' keeps the label as the accessible name but draws it off-page with no asterisk; a field with no label text falls back to aria-label (the placeholder), and a required field carries aria-required with the requiredHint marker on its placeholder. Real-Chrome geometry is asserted in test/form-label-options-2193-browser.test.js.
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, {
labelPosition: 'left', labelWidth: 140, // every label defaults left at 140px
requiredHint: true, // append " *" to a required placeholder
rows: [
{ type: 'input', name: 'left', label: 'Name' },
{ type: 'input', name: 'top', label: 'Title', labelPosition: 'top' }, // item wins
{ fieldset: 'Hidden', labelPosition: 'hidden', rows: [
{ type: 'input', name: 'email', label: 'Email', placeholder: 'you@example.com', required: true },
{ type: 'input', name: 'code', placeholder: 'Enter code', required: true }, // no label text
] },
],
});
const leftPos = form.getItem('left').el.getAttribute('data-label-position'); // 'left'
const leftFlex = form.getItem('left').el.querySelector('.lat-form__label').style.flex; // '0 0 140px'
const topPos = form.getItem('top').el.getAttribute('data-label-position'); // 'top'
const emailLabel = form.getItem('email').el.querySelector('.lat-form__label').textContent; // 'Email'
const emailInput = form.getItem('email').el.querySelector('input');
const emailPlaceholder = emailInput.placeholder; // 'you@example.com *'
const emailRequired = emailInput.getAttribute('aria-required'); // 'true'
const codeAria = form.getItem('code').el.querySelector('input').getAttribute('aria-label'); // 'Enter code'
form.destroy();
return [leftPos, leftFlex, topPos, emailLabel, emailPlaceholder, emailRequired, codeAria].join('|');
Common item properties - hiddenLabel, padding, width and height - executed
hiddenLabel: true keeps the label as the control’s accessible name without drawing it, so the field takes the full row whatever labelPosition says; padding is the space between the item’s cell and its control; width/height take a pixel number, a CSS length or 'content', and height applies to every item type. Each is live through getItem(name).set({…}). Real-Chrome geometry is asserted in test/form-item-common-2344-browser.test.js; this example drives the same logic through the test DOM.
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, { rows: [
{ type: 'input', name: 'hidden', label: 'Email', hiddenLabel: true },
{ type: 'input', name: 'padded', label: 'Name', padding: 10 },
{ type: 'input', name: 'content', label: 'Search', width: 'content' },
{ type: 'input', name: 'tall', label: 'Tall', height: 200 },
] });
const hiddenPos = form.getItem('hidden').el.getAttribute('data-label-position'); // 'hidden'
const hiddenClass = form.getItem('hidden').el.querySelector('.lat-form__label').classList.contains('lat-form__label--hidden'); // true
const padding = form.getItem('padded').el.style.padding; // '10px'
const contentWidth = form.getItem('content').el.style.width; // 'fit-content'
const height = form.getItem('tall').el.style.getPropertyValue('--lattice-form-item-height'); // '200px'
form.destroy();
return [hiddenPos, hiddenClass, padding, contentWidth, height].join('|');
A left label switching to the top below controlMinWidth, executed
controlMinWidth is a pixel number or CSS length set on the form, a fieldset/container or an item, inherited the same way as labelPosition and labelWidth. When an item’s labelPosition is 'left' and its own width minus the label column (labelWidth, or the label’s natural width when unset) minus the gap would leave the control narrower than controlMinWidth, the label moves to the top (data-label-effective="top", and read-only on getItem(name).labelEffectivePosition); it switches back once the item widens past the threshold again, with a few pixels of hysteresis so a width sitting on the line never flickers. The switch is measured per item with a ResizeObserver on the item’s own wrapper, so a shell splitter or a drawer resizing the host counts, not only the window. A checkbox or toggle item is unaffected (its label sits beside it by design), and without controlMinWidth nothing changes. Real-Chrome geometry, the hysteresis band and a real ResizeObserver are asserted in test/form-control-min-width-2554-browser.test.js; this example drives the same logic through the test DOM’s on-demand ResizeObserver shim.
const { createTestDom, triggerResize } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root, document: doc } = createTestDom();
const form = createForm(root, {
labelPosition: 'left', labelWidth: 140, controlMinWidth: 200, // the form default: switch below 140 + gap + 200
rows: [
{ type: 'input', name: 'a', label: 'Alpha' },
{ type: 'checkbox', name: 'chk', label: 'Check' }, // unaffected: its label sits beside it by design
{ fieldset: 'Set', controlMinWidth: 60, rows: [ // a fieldset's own, smaller threshold
{ type: 'input', name: 'b', label: 'Beta' },
] },
],
});
const el = (name) => form.getItem(name).el;
const resize = (width) => {
for (const name of ['a', 'chk', 'b']) doc.setRect(el(name), { width, height: 30, top: 0, left: 0 });
triggerResize();
};
resize(600);
const wideA = el('a').getAttribute('data-label-effective'); // 'left'
resize(300); // 300 - 140 = 160, under the form's 200 threshold
const narrowA = el('a').getAttribute('data-label-effective'); // 'top'
const narrowApi = form.getItem('a').labelEffectivePosition; // 'top', read-only
const narrowChk = el('chk').getAttribute('data-label-effective'); // 'left': a checkbox never switches
const narrowB = el('b').getAttribute('data-label-effective'); // 'left': 160 is still above the fieldset's own 60
doc.setRect(el('b'), { width: 190, height: 30, top: 0, left: 0 });
triggerResize();
const belowFieldsetB = el('b').getAttribute('data-label-effective'); // 'top': below the fieldset's own threshold too
form.destroy();
return [wideA, narrowA, narrowApi, narrowChk, narrowB, belowFieldsetB].join('|');
Help tooltips, read-only locks, field addons and panels, executed
Parity chrome: a tooltip draws a “?” trigger after the label, linked to the control by aria-describedby; a read-only field shows a muted lock inside its right edge (lockIcon: false hides it); an addons list draws round icon buttons (disabled with the field) and an avatar addon that follows the value; and a panel block is a bordered surface with a title, subtitle, divider and header actions. Real-Chrome geometry, light/dark and the 1280x800 screenshot are asserted in the form's browser test.
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
let panelAction = 0;
let addonValue = null;
const form = createForm(root, {
rows: [
{ type: 'input', name: 'name', label: 'Name', tooltip: 'Your full name', value: 'Ada' },
{ type: 'input', name: 'locked', label: 'Locked', readOnly: true, value: 'fixed' },
{ type: 'input', name: 'nofrl', label: 'No lock', readOnly: true, lockIcon: false, value: 'open' },
{ type: 'input', name: 'amount', label: 'Amount', value: '42',
addons: [{ icon: 'pencil', ariaLabel: 'Edit', onClick: (v) => { addonValue = v; } }] },
{ type: 'select', name: 'owner', label: 'Owner', value: 'ada',
options: [{ value: 'ada', label: 'Ada Lovelace' }, { value: 'grace', label: 'Grace Hopper' }],
addons: [{ avatar: true }] },
{ type: 'input', name: 'off', label: 'Off', disabled: true, value: 'grey',
addons: [{ icon: 'link', ariaLabel: 'Open' }] },
{ cols: [
{ panel: { title: 'Status', subtitle: 'Delivery state',
actions: [{ icon: 'pencil', ariaLabel: 'Edit status', onClick: () => { panelAction += 1; } }], collapsible: true },
items: [ { type: 'input', name: 'state', label: 'State', value: 'Draft' } ] },
{ panel: { title: 'Financials', subtitle: 'Budget' },
items: [ { type: 'number', name: 'budget', label: 'Budget', value: 120 } ] },
] },
],
});
const nameEl = form.getItem('name').el;
const tipTrigger = nameEl.querySelector('.lat-form__tooltip-trigger');
const tip = nameEl.querySelector('.lat-form__tooltip');
const nameInput = nameEl.querySelector('input');
const tooltipText = tip.textContent; // 'Your full name'
const tooltipLinked = nameInput.getAttribute('aria-describedby') === tip.id; // true
const triggerLabel = tipTrigger.getAttribute('aria-label'); // 'Help'
const locked = form.getItem('locked').el;
const lockEl = locked.querySelector('.lat-form__lock');
const lockVisible = lockEl !== null && lockEl.hidden === false; // true
const lockTitle = lockEl.title; // 'Read-only'
const noLock = form.getItem('nofrl').el.querySelector('.lat-form__lock') === null; // true
const addonBtn = form.getItem('amount').el.querySelector('.lat-form__addon');
const addonTag = addonBtn.tagName.toLowerCase(); // 'button'
const addonIcon = addonBtn.querySelector('svg') !== null; // true
addonBtn.dispatchEvent(new TestEvent('click', { bubbles: true }));
const clickedValue = String(addonValue); // '42'
const avatar = form.getItem('owner').el.querySelector('.lat-combo__avatar');
const avatarInitials = avatar ? avatar.textContent : ''; // 'AL'
const offAddon = form.getItem('off').el.querySelector('.lat-form__addon');
const addonDisabled = offAddon.disabled === true; // true - disabled with the field
const panels = root.querySelectorAll('.lat-form__panel');
const panelCount = String(panels.length); // '2'
const panelTitle = panels[0].querySelector('.lat-form__panel-title').textContent; // 'Status'
const panelSubtitle = panels[0].querySelector('.lat-form__panel-subtitle').textContent; // 'Delivery state'
const panelHeader = panels[0].querySelector('.lat-form__panel-header') !== null; // true - the divider line
const panelToggle = panels[0].querySelector('.lat-form__panel-collapse');
const collapsible = panelToggle !== null && panelToggle.getAttribute('aria-expanded') === 'true'; // true
const panelBtn = panels[0].querySelector('.lat-form__panel-action');
panelBtn.dispatchEvent(new TestEvent('click', { bubbles: true }));
const panelClicked = panelAction === 1; // true
form.destroy();
return [tooltipText, tooltipLinked, triggerLabel, lockVisible, lockTitle, noLock, clickedValue, addonTag, addonIcon, avatarInitials, addonDisabled, panelTitle, panelSubtitle, panelHeader, panelClicked, panelCount, collapsible].join('|');
A content container: sanitised HTML and an attached grid, executed
The real Chrome geometry - an attached grid filling the region and following it when it resizes, label position, padding and an explicit width/height, hidden/visibleWhen, and the inert disabled region - is asserted in test/form-container-2339-browser.test.js; this example proves the data-level contract headlessly.
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createGrid } = await import('../packages/dom/src/index.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { document, root } = createTestDom();
const form = createForm(root, {
rows: [
{ type: 'checkbox', name: 'show', label: 'Show', value: false },
{ type: 'container', name: 'note', label: 'Note', labelPosition: 'left', labelWidth: 80,
css: { borderLeft: '2px solid tomato' }, disabled: true, visibleWhen: { name: 'show', equals: true },
html: '<p style="color:red" onclick="bad()">Hi<script>window.pwned = true;</script></p>' },
{ type: 'container', name: 'box', label: 'Preview', width: '100%', height: 200 },
],
});
const noteWrap = form.getItem('note').el;
const noteEl = noteWrap.querySelector('.lat-form__container');
const scriptGone = noteEl.querySelector('script') === null; // true - the <script> never rendered
const styleKept = noteEl.querySelector('p').getAttribute('style'); // 'color:red' - inline styles survive
const onclickGone = noteEl.querySelector('p').getAttribute('onclick') === null; // true - on* stripped
const labelLeft = noteWrap.getAttribute('data-label-position') === 'left';
const labelFlex = noteWrap.querySelector('.lat-form__label').style.flex; // '0 0 80px'
const cssApplied = noteWrap.style.borderLeft; // '2px solid tomato'
const disabledAria = noteEl.getAttribute('aria-disabled'); // 'true'
const hiddenBeforeShow = noteWrap.hidden; // true - visibleWhen is false
form.getItem('show').setValue(true); // re-evaluates visibleWhen
const visibleAfterShow = !noteWrap.hidden;
const gridHost = document.createElement('div');
const grid = createGrid(gridHost, {
rowKey: 'id',
columns: [{ field: 'id' }, { field: 'name' }],
rows: [{ id: 1, name: 'Ada' }],
});
form.getItem('box').attach(grid); // a grid exposes its root as `.element`
const attached = form.getItem('box').getWidget() === grid;
const widthFilled = grid.element.style.width; // '100%'
const inBox = form.getItem('box').el.querySelector('.lat-form__container').contains(grid.element);
const valueHasNoKeys = !('note' in form.getValue()) && !('box' in form.getValue());
form.getItem('box').attachHTML('<em>replaced</em>'); // destroys the attached grid and swaps the content
const widgetClearedAfterReplace = form.getItem('box').getWidget() === null;
const replacedText = form.getItem('box').el.querySelector('em').textContent;
form.destroy();
return [scriptGone, styleKept, onclickGone, labelLeft, labelFlex, cssApplied, disabledAria, hiddenBeforeShow, visibleAfterShow, attached, widthFilled, inBox, valueHasNoKeys, widgetClearedAfterReplace, replacedText].join('|');
A grid item: a cost projection in a form, executed
The real keys (a currency cell typed into and committed with Tab, the totals following), the row controls from the keyboard, read-only, the marked offending cell, dark mode and a preset are asserted in test/form-grid-2454-browser.test.js; this example proves the data-level contract headlessly.
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createGrid } = await import('../packages/dom/src/index.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, {
createGrid, // handed in: the form bundles no grid core
rows: [{
type: 'grid', name: 'costs', label: 'Cost projection', rowKey: 'id', height: 200,
columns: [
{ field: 'item', title: 'Item' },
{ field: 'cost', title: 'Cost', type: 'number', edit: true, validation: { min: 0, max: 1000 } },
{ field: 'qty', title: 'Qty', type: 'number', edit: true },
],
value: [
{ id: 'fuel', item: 'Fuel', cost: 120, qty: 2 },
{ id: 'crew', item: 'Crew', cost: 300, qty: 1 },
],
fields: { fuelCost: { row: 'fuel', col: 'cost' } }, // one cell, also a top-level property
totals: { row: true, column: { title: 'Line' } }, // display-only, never in the value
required: true, // at least one row
}],
});
const changes = [];
form.on('change', (e) => changes.push(e.name));
const grid = form.getItem('costs').getGrid();
// A person's edit: beforeChange, the column validators, then one change per property.
grid.edit.setCells([{ key: 'fuel', colId: 'cost', value: 150 }], 'cell', { origin: 'user' });
const edited = form.getValue().fuelCost; // 150
const fired = changes.join(','); // 'costs,fuelCost'
form.setValue({ fuelCost: 160 }); // a mapped cell is written like any field
const mapped = form.getValue().costs[0].cost; // 160: the rows follow
form.getItem('costs').addRow({ id: 'tyres', item: 'Tyres', cost: 5000, qty: 4 });
const failures = [];
form.on('validated', (e) => { if (e.name == null) failures.push(...e.failures); });
const ok = form.validate(); // false: 5000 is over the column's max
const rows = form.getValue().costs.length; // 3
const keys = Object.keys(form.getValue()).join('+'); // 'costs+fuelCost': no totals
form.destroy();
return [edited, fired, mapped, ok, failures[0].message, rows, keys].join('|');
A grid item: arrays, row controls and mapped cells only, executed
valueAs: 'arrays' reports each row as an array in column order; rowControls draws the Add row and Delete row buttons (newRow gives a blank row its defaults, and gridOptions passes any other grid option through); valueRows: false drops the rows array and keeps only the mapped cells.
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createGrid } = await import('../packages/dom/src/index.js');
const { createForm } = await import('../packages/modules/form/index.js');
const columns = [{ field: 'id' }, { field: 'item' }, { field: 'cost', type: 'number', edit: true }];
const { root } = createTestDom();
const arrays = createForm(root, {
createGrid,
rows: [{
type: 'grid', name: 'lines', rowKey: 'id', columns,
valueAs: 'arrays', // each row is [id, item, cost]
value: [['a', 'Fuel', 120]],
rowControls: true, // Add row / Delete row buttons
newRow: { item: 'New line', cost: 0 }, // defaults for the Add row button
gridOptions: { selection: 'multiple' }, // any other grid option
}],
});
root.querySelector('.lat-form__grid-add').dispatchEvent(new TestEvent('click'));
const shaped = arrays.getValue().lines.map((row) => row.join('/')).join(';');
const cellsOnly = createForm(createTestDom().root, {
createGrid,
rows: [{
type: 'grid', name: 'lines', rowKey: 'id', columns,
value: [{ id: 'a', item: 'Fuel', cost: 120 }],
fields: { fuelCost: { row: 'a', col: 'cost' } },
valueRows: false, // only the mapped cells are in the value
}],
});
const kept = Object.entries(cellsOnly.getValue()).map(([k, v]) => k + '=' + v).join(',');
arrays.destroy();
cellsOnly.destroy();
return [shaped, kept].join('|');
A grid item: label, states and rules, executed
A grid item takes the usual item options - helpMessage, width, labelPosition/labelWidth, css, validationMode - and the rule options visibleWhen, readOnlyWhen and requiredWhen, which may watch any other item or mapped cell; readOnly and disabled start it refusing edits (a disabled grid is inert and skipped by validate()).
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createGrid } = await import('../packages/dom/src/index.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, {
createGrid,
rows: [
{ type: 'checkbox', name: 'locked', label: 'Lock the plan' },
{ type: 'checkbox', name: 'detail', label: 'Show the plan' },
{
type: 'grid', name: 'plan', label: 'Plan', rowKey: 'id',
columns: [{ field: 'item', edit: true }, { field: 'cost', type: 'number', edit: true }],
value: [],
helpMessage: 'One row per cost line.',
width: 480, labelPosition: 'left', labelWidth: 80,
css: { margin: '0 auto' },
validationMode: 'change',
visibleWhen: { name: 'detail', equals: true }, // shown once the box is ticked
readOnlyWhen: { name: 'locked', equals: true }, // refuses edits while locked
requiredWhen: { name: 'detail', equals: true }, // at least one row, once visible
},
{
type: 'grid', name: 'frozen', rowKey: 'id', columns: [{ field: 'item' }],
value: [{ id: 'a', item: 'Fixed' }], readOnly: true, disabled: true,
},
],
});
const plan = form.getItem('plan');
const hidden = plan.isVisible(); // false
form.getItem('detail').setValue(true);
const shown = plan.isVisible(); // true
const required = form.validate(); // false: no rows yet
plan.addRow({ item: 'Fuel', cost: 120 });
form.getItem('locked').setValue(true);
const locked = plan.getGrid().edit.setCells(
[{ key: 'row-1', colId: 'cost', value: 1 }], 'cell', { origin: 'user' }); // 0 cells written
const frozen = form.getItem('frozen').el.querySelector('.lat-form__grid').getAttribute('aria-disabled');
form.destroy();
return [hidden, shown, required, locked, frozen, plan.el.style.width].join('|');
The button and the buttons row, executed
A button renders its variant, size, icon position, full width and text transform; an icon may be a built-in glyph name or a data: URI; an icon-only button carries its ariaLabel and a href renders a link styled as a button. A submit button validates first and only then fires submit with the values; reset clears; loading/setLoading swaps the icon for a spinner and ignores clicks; and a buttons row lays its children out by align - with the real Chrome geometry and the light/dark colours asserted in test/form-button-2194-browser.test.js.
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, {
rows: [
{ type: 'input', subtype: 'email', name: 'email', label: 'Email', required: true },
{ type: 'input', subtype: 'password', name: 'password', label: 'Password' },
{ type: 'button', name: 'signin', label: 'Sign in', variant: 'primary', fullWidth: true, buttonType: 'submit', icon: 'check' },
{ type: 'button', name: 'google', label: 'Continue with Google', variant: 'secondary', fullWidth: true, iconPosition: 'end', icon: 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><circle cx="8" cy="8" r="6"/></svg>' },
{ type: 'button', name: 'clear', label: 'Clear', variant: 'outline', fullWidth: true, buttonType: 'reset', textTransform: 'uppercase' },
{ type: 'button', name: 'help', icon: 'info', ariaLabel: 'Help' },
{ type: 'button', name: 'docs', label: 'Docs', href: 'https://example.com/docs' },
{ type: 'button', name: 'pin', label: 'Pin', variant: 'tonal', toggle: true, value: true },
{ type: 'button', name: 'ghost', label: 'Keep', disabled: true, focusableWhenDisabled: true },
{ type: 'buttons', align: 'space-between', items: [
{ name: 'cancel', label: 'Cancel', variant: 'text' },
{ name: 'save', label: 'Save', variant: 'primary' },
] },
],
});
const signin = form.getItem('signin').el.querySelector('.lat-button');
const google = form.getItem('google').el.querySelector('.lat-button');
const clear = form.getItem('clear').el.querySelector('.lat-button');
const help = form.getItem('help').el.querySelector('.lat-button');
const docs = form.getItem('docs').el.querySelector('.lat-button');
const variant = signin.getAttribute('data-variant');
const full = signin.getAttribute('data-full');
const iconPosition = google.querySelector('img') ? 'img' : 'none';
const googleImg = google.querySelector('img') !== null;
const caps = clear.getAttribute('data-text-transform');
const iconOnly = help.getAttribute('data-icon-only');
const helpLabel = help.getAttribute('aria-label');
const linkTag = docs.tagName.toLowerCase();
let submits = 0;
let values = null;
form.el.addEventListener('submit', (e) => { submits += 1; values = e.detail.values; });
signin.dispatchEvent(new TestEvent('click', { bubbles: true }));
const blocked = submits;
form.setValue({ email: 'ada@example.com', password: 's3cret' });
signin.dispatchEvent(new TestEvent('click', { bubbles: true }));
const submitted = submits;
const submittedValues = values.email + '/' + values.password;
clear.dispatchEvent(new TestEvent('click', { bubbles: true }));
const cleared = form.getValue().email;
form.getItem('signin').setLoading(true); // loading swaps the icon for a spinner and ignores clicks
const busy = signin.getAttribute('aria-busy');
const spinner = signin.querySelector('.lat-button__spinner') !== null;
form.getItem('signin').setLoading(false);
const row = root.querySelector('.lat-button-row');
const rowAlign = row.getAttribute('data-align');
const rowButtons = row.querySelectorAll('.lat-button').length;
const pin = form.getItem('pin').el.querySelector('.lat-button');
const pinStart = pin.getAttribute('aria-pressed');
const toggles = [];
form.on('change', (e) => toggles.push(e.value));
pin.dispatchEvent(new TestEvent('click', { bubbles: true }));
const pinAfter = pin.getAttribute('aria-pressed');
const toggleValue = toggles.length === 1 ? String(toggles[0]) : '';
const ghost = form.getItem('ghost').el.querySelector('.lat-button');
const ghostDisabled = ghost.disabled;
const ghostAriaDisabled = ghost.getAttribute('aria-disabled');
form.destroy();
return [variant, full, iconPosition, googleImg, caps, iconOnly, helpLabel, linkTag, blocked, submitted, submittedValues, cleared, busy, spinner, rowAlign, rowButtons, pinStart, pinAfter, toggleValue, ghostDisabled, ghostAriaDisabled].join('|');
Refreshing combo and select options, executed
getItem(name).setOptions(options) replaces a combo or select item's static options in place - the list re-renders, a value still present is kept, one gone is cleared with a single change event, and a changed label refreshes the shown value. getItem(name).reload() refetches a load-backed combo's first page (a static combo or select just re-renders).
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, {
rows: [
{ type: 'combo', name: 'fruit', label: 'Fruit', value: 'b',
options: [{ value: 'a', label: 'Alpha' }, { value: 'b', label: 'Beta' }] },
{ type: 'select', name: 'colour', label: 'Colour', value: 'blue',
options: ['red', 'green', 'blue'] },
],
});
const optionRows = (name) => [...form.getItem(name).el.querySelectorAll('.lat-combo__option')]
.filter((r) => !r.classList.contains('lat-combo__option--create')).length;
const comboTotal = (name) => { // the combo windows its rows, so read its total
const status = form.getItem(name).el.querySelector('.lat-combo__status');
const m = /^(\d+) results$/.exec(status ? status.textContent : '');
return m ? Number(m[1]) : -1;
};
let changes = 0;
form.on('change', () => { changes += 1; });
form.getItem('fruit').setOptions([ // add Gamma; 'b' stays
{ value: 'a', label: 'Alpha' },
{ value: 'b', label: 'Beta' },
{ value: 'g', label: 'Gamma' },
]);
const fruitRows = comboTotal('fruit'); // 3
const kept = form.getItem('fruit').getValue(); // 'b'
form.getItem('fruit').setOptions([{ value: 'a', label: 'Alpha' }]); // drop 'b'
const cleared = form.getItem('fruit').getValue() === null ? 'null' : 'kept';
const fruitChanges = changes; // 1
form.getItem('colour').setOptions(['red', 'blue', 'purple']); // 'blue' stays
const colourRows = optionRows('colour'); // 3
const keptColour = form.getItem('colour').getValue(); // 'blue'
form.destroy();
return [fruitRows, kept, cleared, fruitChanges, colourRows, keptColour].join('|');
The combo control
The same module also ships createCombo(el, config), the standalone form of the form's type: 'combo' item: a searchable combobox with dynamic server values, dependent lists, multi-select and multi-line options. It is a load-driven paging list - the search is debounced, a newer load aborts the older one, pages load on scroll and are cached, and reload() drops the cache - or a static options list when there is no server. Options are a bare value or { value, label, description, icon, avatar, color, dot, disabled }; a description adds a second line, an icon is a glyph name from the grid's icon set drawn as the real SVG (or a DOM node) and an avatar is an image URL or initials, each drawn round on the left of the list rows, the multi-select chips and the single-select shown value, in a virtualised list of variable-height rows; color tints the initials avatar and the icon (an SVG takes it as its fill or stroke, an element as its colour), and dot draws a small filled circle in that colour instead of any icon or avatar, with no letter; a disabled option shows but refuses a click. A multiple combo keeps its value as an array in selection order and draws chips that wrap, cap at maxHeight and scroll, with a +N summary and a selectAll action over the loaded set. chipPlacement moves those chips out of the control - 'above' or 'below' puts them in their own wrapping row beside the field, so the input stays a single clean search line and the list still opens directly under it. resolveLabels(values) supplies labels for a preselected value outside the first page, newOptions turns the box into free entry (with a create row while typing), optionTemplate replaces the row renderer and selectedTemplate the chips and shown value - either may return an HTMLElement (inserted as is) or an HTML string, sanitised before insertion with class kept on every tag the whitelist allows rather than only a lat-/dfc- prefixed one, so an icon-font template such as '<i class="fa fa-star"></i> Star' keeps its class - scripts, event handlers, javascript: URLs and style expressions are still removed. While a single-select combo is unfocused and selectedTemplate renders the shown value, the template alone is visible and the input's own label text is hidden behind it, so the field never reads the label twice; focusing the field (or typing) swaps that around - a plain icon/avatar adornment is unaffected, since it never duplicates the label text - and a form item's dependsOn clears and reloads it when a named parent item changes. The list opens in the same shared top-level layer the select and the date picker use, positioned against the field so a clipping or fixed-height ancestor never cuts it off.
| Member | Description |
|---|---|
| createCombo(el, config?) | Create a standalone combobox. config is the ComboConfig options below. Returns { el, root, input, getValue, setValue, reload, clear, open, close, focus, blur, setDisabled, setReadOnly, destroy }. |
| item | A type: 'combo' item takes the same options: load, options, multiple, value, resolveLabels, newOptions, optionTemplate, selectedTemplate, selectAll, debounce, pageSize, maxHeight, chipPlacement and dependsOn. |
| load({ search, page, signal }) | The paging loader, handed the debounced search, the zero-based page and an AbortSignal, and answering { items, total, hasMore } or a bare array. Absent when options is used. |
| getValue() / setValue(value) | Read the committed value (a single value, or an array in multiple mode), or write one silently - no event fires. |
| reload() / clear() | reload() drops the page cache and reloads page zero for the current search; clear() empties the selection and fires change. |
| open() / close() / focus() / blur() | Drive the popup and keyboard focus; setDisabled()/setReadOnly() gate editing, and destroy() tears the combo down. |
Dynamic values, chips, icons, avatars, templates and a dependent item, executed
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createCombo, createForm } = await import('../packages/modules/form/index.js');
const { document, root } = createTestDom();
// A paged, searchable, multi-select combo with resolved labels and free entry.
const peopleHost = document.createElement('div');
root.appendChild(peopleHost);
const people = createCombo(peopleHost, {
multiple: true,
selectAll: true,
debounce: 50,
pageSize: 10,
maxHeight: 64,
value: ['n0', 'zz9'],
resolveLabels: (values) => values.map((v) => ({ value: v, label: 'R:' + v })),
newOptions: true,
load: ({ search, page }) => {
const start = page * 10;
const items = [];
for (let i = start; i < start + 10 && i < 30; i++) items.push({ value: 'n' + i, label: 'Person ' + i });
return { items, total: 30, hasMore: start + 10 < 30 };
},
});
people.open();
const multi = people.getValue().join(','); // 'n0,zz9' - in selection order
// A static, custom-rendered combo.
const sizedHost = document.createElement('div');
root.appendChild(sizedHost);
const sized = createCombo(sizedHost, {
options: [{ value: 'a', label: 'Alpha' }, { value: 'b', label: 'Beta' }],
optionTemplate: (opt) => 'T:' + opt.label,
clearable: true, // a clear control shows while a value is held and empties it with one change
});
const sizedPopup = sized.root.querySelector('.lat-combo__popup'); // captured before open: the popup moves into the shared layer host while open
sized.open();
const renderedRow = Array.from(sizedPopup.querySelectorAll('.lat-combo__option')).find((r) => r.textContent === 'T:Alpha');
const rendered = renderedRow.textContent; // 'T:Alpha' - the optionTemplate applied
// A static combo with a real 'user' SVG icon, an initials avatar and a
// selectedTemplate over the shown value.
const decoHost = document.createElement('div');
root.appendChild(decoHost);
const deco = createCombo(decoHost, {
options: [
{ value: 'u', label: 'User', icon: 'user' },
{ value: 'b', label: 'Beta', avatar: 'BE', color: '#e81123' },
],
selectedTemplate: (opt) => 'S:' + opt.label,
});
const decoPopup = deco.root.querySelector('.lat-combo__popup'); // captured before open: the popup moves into the shared layer host while open
deco.open();
const decoRows = Array.from(decoPopup.querySelectorAll('.lat-combo__option'));
const hasIcon = decoRows.some((r) => r.querySelector('.lat-combo__icon') !== null); // true - the 'user' SVG
const hasAvatar = decoRows.some((r) => r.querySelector('.lat-combo__avatar') !== null); // true - round initials
deco.setValue('u');
const shown = deco.root.querySelector('.lat-combo__value').textContent; // 'S:User' - the selectedTemplate
deco.destroy();
// A form item whose combo depends on its parent.
const formHost = document.createElement('div');
root.appendChild(formHost);
const form = createForm(formHost, {
rows: [
{ type: 'input', name: 'country', label: 'Country', value: 'US' },
{ type: 'combo', name: 'city', label: 'City', value: 'NYC', dependsOn: ['country'],
load: () => ({ items: [{ value: 'NYC', label: 'New York' }], total: 1, hasMore: false }) },
],
});
const city = form.getItem('city').getValue(); // 'NYC' - the configured value
people.setDisabled(true);
people.setDisabled(false);
people.setReadOnly(true);
people.clear();
const cleared = people.getValue().length; // 0 - cleared
people.setValue('n1'); // a silent write
people.reload(); // keep the value, drop the pages
const kept = people.getValue().join(',');
people.close();
people.focus();
people.blur();
people.destroy();
sized.destroy();
// Chip placement: the chips wrap above the control in their own labelled row.
const aboveHost = document.createElement('div');
root.appendChild(aboveHost);
const above = createCombo(aboveHost, {
multiple: true,
chipPlacement: 'above',
options: [{ value: 'p', label: 'Pill' }, { value: 'q', label: 'Quill' }],
});
above.setValue(['p']);
const row = above.root.querySelector('.lat-combo__chip-row');
const chipRowAbove = above.root.getAttribute('data-chip-placement') === 'above'
&& row && !row.hidden && row.getAttribute('aria-label') === 'Selected: 1'
&& above.root.children[0] === row; // the row sits above the control
const aboveValue = above.getValue().join(','); // 'p' - the chip row leaves the value untouched
above.destroy();
form.destroy();
return [multi, rendered, hasIcon, hasAvatar, shown, city, cleared, kept, aboveValue, chipRowAbove].join('|');
A standalone select, mounted and driven from the handle, executed
createSelect is the form's themed select as its own factory: the
control a type: 'select' item draws, mounted into any element, and the piece another module takes on
injection - a kanban board's form: { createSelect } renders its column controls through it.
const { createSelect } = await import('../packages/modules/form/index.js');
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { document, root } = createTestDom();
// A single select: strings and { value, label } objects mix in one list.
const kitHost = document.createElement('div');
root.appendChild(kitHost);
const kit = createSelect(kitHost, {
options: ['Phone screen kit', { value: 'tech', label: 'Technical screen kit' }],
placeholder: 'Select interview kit',
ariaLabel: 'Interview kit',
selectedTemplate: (opt) => 'S:' + opt.label, // how the chosen option shows on the trigger
doc: document, // the owner document, for a select outside the main one
t: (key) => key, // the control's own strings resolve through this
});
const empty = kit.getValue(); // '' - nothing chosen yet
const placeholder = kit.trigger.textContent.trim(); // 'Select interview kit'
kit.setValue('tech'); // silent: no change event
const chosen = kit.getValue(); // 'tech'
const shown = kit.root.querySelector('.lat-combo__template').textContent.trim(); // 'S:Technical screen kit'
// A multi-select with custom option rendering, then disabled and read-only.
const tagHost = document.createElement('div');
root.appendChild(tagHost);
const tags = createSelect(tagHost, {
multiple: true,
value: ['a'],
options: [{ value: 'a', label: 'Alpha' }, { value: 'b', label: 'Beta' }],
optionTemplate: (opt) => 'O:' + opt.label,
disabled: false,
readOnly: false,
});
tags.setValue(['a', 'b']);
const multi = tags.getValue().join(','); // 'a,b'
tags.open(); // aria-controls names its listbox; a chosen option carries a check mark
const listbox = document.getElementById(tags.trigger.getAttribute('aria-controls'));
const listed = [...listbox.querySelectorAll('.lat-combo__option')].map((o) => o.textContent.trim()).join(',');
tags.close();
tags.setDisabled(true);
const disabled = tags.trigger.disabled; // true
tags.setReadOnly(true);
const readOnly = tags.trigger.getAttribute('aria-readonly') === 'true';
return [empty, placeholder, chosen, shown, multi, listed, disabled, readOnly].join('|');
Coloured status dots and icon tints, executed
A dot: '<colour>' shorthand draws a small filled circle before an option's
label with no letter, and an option's color tints its icon too. The RAG select below shows green, amber
and red dots - the amber one takes a hairline ring so it keeps 3:1 against a light field - while the owner
select tints a circleFilled icon green.
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, { rows: [
{ type: 'select', name: 'rag', label: 'RAG status', options: [
{ value: 'ok', label: 'On track', dot: '#2e7d32' },
{ value: 'warn', label: 'Watch', dot: '#ff8f00' },
{ value: 'fail', label: 'Blocked', dot: '#c62828' },
], value: 'ok' },
{ type: 'select', name: 'owner', label: 'Owner', options: [
{ value: 'ada', label: 'Ada', icon: 'circleFilled', color: '#2e7d32' },
], value: 'ada' },
] });
const rag = form.getItem('rag').el.querySelector('.lat-select');
const rows = [...rag.querySelectorAll('.lat-combo__option')];
const rowDots = rows.map((r) => r.querySelector('.lat-combo__dot'));
const okRow = rows.find((r) => r.getAttribute('data-value') === 'ok');
const warnRow = rows.find((r) => r.getAttribute('data-value') === 'warn');
const dot = okRow ? okRow.querySelector('.lat-combo__dot') : null;
const ringed = warnRow ? warnRow.querySelector('.lat-combo__dot').getAttribute('data-ring') === 'true' : false;
const ragValue = rag.querySelector('.lat-select__value');
const triggerDot = ragValue ? ragValue.querySelector('.lat-combo__dot') : null;
const owner = form.getItem('owner').el.querySelector('.lat-select');
const ownerValue = owner.querySelector('.lat-select__value');
const icon = ownerValue ? ownerValue.querySelector('.lat-combo__icon') : null;
const out = [
rowDots.filter(Boolean).length, // 3 - one dot per option row
dot ? dot.textContent : '', // '' - no letter
dot ? dot.style.background : '', // '#2e7d32' - the dot's fill
icon ? icon.style.color : '', // '#2e7d32' - the tinted icon
triggerDot !== null, // the trigger shows the dot
ringed, // the amber dot takes a ring
].join('|');
form.destroy();
return out;
The listbox control
A type: 'listbox' item is a scrolling, virtualised option list. selection picks the interaction mode: 'single' (the default, click or arrow selects), 'multiple' (click replaces the selection, Ctrl/Cmd+click toggles, Shift+click spans a range, a touch tap toggles) or 'checkbox' (a box per row plus a select-all row). filter: true adds a search box that narrows the rows by label and description without dropping an already-selected option it hides; groupBy: true buckets the options by their group field under sticky headers; sort: 'asc' | 'desc' orders the rows by label; render(opt) replaces a row's content, handed the option exactly as given so a field this module does not know about still reaches it. height (pixels) or rows (row count) sizes the viewport. reorder: true draws Move up/Move down buttons and accepts Alt+Arrow and drag, and the committed value becomes the full, reordered item array; connect: '<other item name>' links this list to another by name - a Move selected/Move all pair (and drag, either direction) move items between the two, and each side's value is simply the items it currently holds. min/max cap the selection count, like a multi chips item.
An editable ordered list. getItem(name).getOptions() reads the current item order exactly as given, independent of selection, the search text or a filter() predicate. With reorder: true, valueAs: 'order' makes the committed value the ordered array of option values in every selection mode - including the default 'single', where the value would otherwise be just the one selected item, and which an ordered-list item usually wants instead, since the list itself is the data. Every row click fires itemClick with the option and the mouse event, the already-selected row included, and Enter fires activate the same way. getItem(name).addOption(opt, index?), .removeOption(value) and .updateOption(value, patch) edit the list from the host, keeping selection and order consistent and each firing one change. dragHandle: true draws a grip and drags only from it (a plain pointer drag, not native HTML5 drag-and-drop, so it is driven the same way the grid's own row-drag handle is) and sizes rows to their content instead of a fixed height. getItem(name).filter(fn) (and filter(null) to clear it) shows only the options fn accepts, without touching the canonical order, the selection or the value.
| Member | Description |
|---|---|
| selection | 'single' (default), 'multiple' or 'checkbox'. |
| filter / groupBy / sort | A search box; sticky group headers from each option's group; label order 'asc'/'desc'/false. |
| render(opt) | A custom row renderer, returning a DOM node or an HTML string (sanitised before insertion). |
| reorder / connect | reorder: true makes the value the full reordered item array; connect: name exchanges items with the list box of that name. |
| valueAs | With reorder: true, 'order' makes the value the ordered array of option values in every selection mode, including 'single'. |
| dragHandle | true draws a drag grip and drags only from it; rows size to their content instead of a fixed height. |
| height / rows / min / max | The viewport size in pixels or rows; the selection-count floor/cap. |
| getItem(name).getOptions() | The options in their current order, independent of selection. |
| getItem(name).addOption(opt, index?) / .removeOption(value) / .updateOption(value, patch) | Edit the list from the host, keeping selection and order consistent; each fires one change. |
| getItem(name).filter(fn) | Show only the options fn accepts; filter(null) clears it. Never touches order or value. |
| itemClick / activate | form.on('itemClick', ...) fires on every row click (selected row included) with the option and the mouse event; activate fires the same way on Enter. |
Selection modes, filter, groups, sort, reorder and a connected pair, executed
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { document, root } = createTestDom();
const click = (el, init) => el.dispatchEvent(new TestEvent('click', { bubbles: true, ...init }));
// Multiple selection: Shift+click spans a range, values read in option order.
const multiHost = document.createElement('div');
root.appendChild(multiHost);
const multiForm = createForm(multiHost, { rows: [
{ type: 'listbox', name: 'fruit', label: 'Fruit', props: { selection: 'multiple' },
options: ['Apple', 'Banana', 'Cherry', 'Date'] },
] });
const fruitRows = multiHost.querySelectorAll('[role="option"]');
click(fruitRows[1]);
click(fruitRows[2], { shiftKey: true });
const spanValue = multiForm.getItem('fruit').getValue().join(','); // 'Banana,Cherry'
multiForm.destroy();
// filter narrows the rows; groupBy buckets by the group field; sort orders labels.
const groupHost = document.createElement('div');
root.appendChild(groupHost);
const groupForm = createForm(groupHost, { rows: [
{ type: 'listbox', name: 'food', label: 'Food', props: { filter: true, groupBy: true, height: 120 },
options: [
{ value: 'a', label: 'Apple', group: 'Fruit' },
{ value: 'b', label: 'Banana', group: 'Fruit' },
{ value: 'c', label: 'Carrot', group: 'Veg' },
] },
] });
const filterInput = groupHost.querySelector('.lat-listbox__filter');
filterInput.value = 'Ba';
filterInput.dispatchEvent(new TestEvent('input', { bubbles: true }));
const afterFilter = groupHost.querySelectorAll('[role="option"]').length; // 1 - only 'Banana' matches
filterInput.value = '';
filterInput.dispatchEvent(new TestEvent('input', { bubbles: true }));
const groupName = groupHost.querySelector('.lat-listbox__group-header').textContent; // the first bucket's heading
groupForm.destroy();
const sortHost = document.createElement('div');
root.appendChild(sortHost);
const sortForm = createForm(sortHost, { rows: [
{ type: 'listbox', name: 'sorted', label: 'Sorted', props: { sort: 'asc' }, options: ['Cherry', 'Apple', 'Banana'] },
] });
const sortedLabels = [...sortHost.querySelectorAll('.lat-listbox__title')].map((n) => n.textContent).join(',');
sortForm.destroy();
// A custom render() hook replaces a row's content.
const renderHost = document.createElement('div');
root.appendChild(renderHost);
const renderForm = createForm(renderHost, { rows: [
{ type: 'listbox', name: 'tmpl', label: 'Templated', props: { render: (opt) => 'R:' + opt.label },
options: ['Apple'] },
] });
const rendered = renderHost.querySelector('[role="option"]').textContent; // 'R:Apple'
renderForm.destroy();
// reorder: true makes Move up change the committed item order.
const orderHost = document.createElement('div');
root.appendChild(orderHost);
const orderForm = createForm(orderHost, { rows: [
{ type: 'listbox', name: 'order', label: 'Order', props: { selection: 'multiple', reorder: true },
options: ['Apple', 'Banana', 'Cherry'] },
] });
click(orderHost.querySelectorAll('[role="option"]')[2]);
const orderMoveUp = () => [...orderHost.querySelectorAll('.lat-listbox__toolbar-btn')].find((b) => b.textContent === 'Move up');
click(orderMoveUp());
click(orderMoveUp());
const reordered = orderForm.getItem('order').getValue().join(','); // 'Cherry,Apple,Banana'
orderForm.destroy();
// connect links two list boxes: Move selected exchanges items between them.
const connectHost = document.createElement('div');
root.appendChild(connectHost);
const connectForm = createForm(connectHost, { rows: [
{ type: 'listbox', name: 'available', label: 'Available', props: { selection: 'multiple', connect: 'chosen' },
options: ['Apple', 'Pear', 'Cherry'] },
{ type: 'listbox', name: 'chosen', label: 'Chosen', props: { selection: 'multiple', connect: 'available' }, options: [] },
] });
const availableEl = connectForm.getItem('available').el;
click(availableEl.querySelectorAll('[role="option"]')[1]);
click([...availableEl.querySelectorAll('.lat-listbox__toolbar-btn')].find((b) => b.textContent === 'Move selected'));
const chosenValue = connectForm.getItem('chosen').getValue().join(','); // 'Pear' - moved across
const availableValue = connectForm.getItem('available').getValue().join(','); // 'Apple,Cherry' - what remains
connectForm.destroy();
return [spanValue, afterFilter, groupName, 'asc:' + sortedLabels, rendered, reordered, chosenValue, availableValue].join('|');
An editable ordered list: raw option data, order-as-value, itemClick/activate, host edits, drag handle and filter, executed
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { document, root } = createTestDom();
const host = document.createElement('div');
root.appendChild(host);
const seen = [];
const events = [];
const form = createForm(host, { rows: [
{ type: 'listbox', name: 'steps', label: 'Steps',
props: {
reorder: true, valueAs: 'order', dragHandle: true,
render: (opt) => { seen.push(opt.note || null); return opt.label; },
},
options: [
{ value: 'a', label: 'Alpha', note: 'first' },
{ value: 'b', label: 'Beta' },
{ value: 'c', label: 'Charlie' },
] },
] });
form.on('itemClick', (e) => events.push('itemClick:' + e.option.value));
form.on('activate', (e) => events.push('activate:' + e.option.value));
const item = form.getItem('steps');
const rawNote = seen[0]; // 'first' - render(opt) saw the whole option, untouched
const order = item.getValue().join(','); // 'a,b,c' - single selection mode, but valueAs: 'order'
const el = item.el;
const rows = () => [...el.querySelectorAll('[role="option"]')];
rows()[0].dispatchEvent(new TestEvent('click', { bubbles: true }));
rows()[0].dispatchEvent(new TestEvent('click', { bubbles: true })); // clicked again, already selected
const itemClicksOnSelectedRow = events.filter((e) => e === 'itemClick:a').length === 2;
item.addOption({ value: 'd', label: 'Delta' });
item.updateOption('b', { label: 'Beta2' });
item.removeOption('b');
const afterEdits = item.getOptions().map((o) => o.value).join(','); // 'a,c,d'
const hasHandle = !!el.querySelector('.lat-listbox__handle');
const nativeDraggable = rows()[0].draggable === true; // false - dragHandle drags only from the grip
item.filter((opt) => opt.value !== 'a');
const filteredCount = rows().length; // 2 - 'c' and 'd', without touching order or value
item.filter(null);
// Last, since a keyboard move re-settles the virtual list's measured row
// heights against this fixture's fixed layout - nothing here reads rows() again.
const viewport = el.querySelector('[role="listbox"]');
viewport.focus();
viewport.dispatchEvent(new TestEvent('keydown', { key: 'ArrowDown', bubbles: true }));
viewport.dispatchEvent(new TestEvent('keydown', { key: 'Enter', bubbles: true }));
const activated = events.find((e) => e.startsWith('activate:')); // 'activate:c' - 'b' was just removed
form.destroy();
return [rawNote, order, itemClicksOnSelectedRow, activated, afterEdits, hasHandle, nativeDraggable, filteredCount].join('|');
Binding, dirty tracking, save, revert and conflict, executed
A form bound to a grid row generates one item per column with the column's editor, follows the grid's density, marks an edited item dirty, saves once through the grid's edit path and reverts an unsaved edit; a form bound to a data router fills in from the route's keyed diffs, a clean item follows an update and a dirty item is left in place and flagged conflicted.
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createHeadlessGrid } = await import('../packages/core/src/index.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { createDataRouter } = await import('../packages/modules/data-router/index.js');
const { root } = createTestDom();
// A grid row drives the form: no layout is declared, so one item per column is generated.
const grid = createHeadlessGrid({
rowKey: 'id',
columns: [
{ field: 'name', title: 'Name', type: 'text', edit: true },
{ field: 'age', title: 'Age', type: 'number', edit: true },
{ field: 'active', title: 'Active', type: 'boolean', edit: true },
],
rows: [{ id: 'a', name: 'Ada', age: 36, active: true }],
});
const form = createForm(root, { bind: { grid, rowKey: 'a' } });
const shown = [form.getValue().name, form.getValue().age, form.getValue().active].join(','); // Ada,36,true
// A committed edit marks the item dirty; programmatic writes stay silent.
const name = form.getItem('name').el.querySelector('input');
name.value = 'Grace';
name.dispatchEvent(new TestEvent('change', { bubbles: true }));
const dirtyName = form.isDirty('name'); // true
// save() writes the dirty items once through the grid's own edit path.
const saved = form.save(); // true
const written = grid.rows.byKey('a').data.name; // 'Grace'
const cleanAfterSave = form.isDirty('name'); // false
// revert() restores an unsaved edit to the bound value.
const age = form.getItem('age').el.querySelector('input');
age.value = '40';
age.dispatchEvent(new TestEvent('change', { bubbles: true }));
form.revert();
const reverted = form.getValue().age; // 36
// A router-bound form fills in from the route's keyed diffs.
const router = createDataRouter({ key: 'kind', rowKey: 'id' });
const { root: root2 } = createTestDom();
const routed = createForm(root2, {
bind: { router, route: 'person', key: 'a' },
rows: [
{ type: 'input', name: 'name', label: 'Name' },
{ type: 'number', name: 'age', label: 'Age' },
],
});
router.load([{ id: 'a', kind: 'person', name: 'Ada', age: 36 }]);
const routedName = routed.getItem('name').el.querySelector('input');
routedName.value = 'Grace';
routedName.dispatchEvent(new TestEvent('change', { bubbles: true }));
// An update changes the clean item and flags the dirty one instead of overwriting it.
router.load([{ id: 'a', kind: 'person', name: 'Srv', age: 40 }]);
const cleanAge = routed.getValue().age; // 40 - clean item followed
const keptName = routed.getValue().name; // 'Grace' - dirty item kept
const conflicted = routed.isConflicted('name'); // true
grid.destroy();
form.destroy();
routed.destroy();
return [shown, dirtyName, saved, written, cleanAfterSave, reverted, cleanAge, keptName, conflicted].join('|');
Router-bound forms and a form group, executed
One ingest of a mixed set routes TASKs to a task grid and a PROJECT to two forms that were
created after the ingest: the group fills at once through router.get, and
group.save() writes one router update with both members' dirty fields, calling onSave once.
(The PROJECT grid is attached with overlap: true so the grid and the two form members all show the same
record.)
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createHeadlessGrid } = await import('../packages/core/src/index.js');
const { createForm, createFormGroup } = await import('../packages/modules/form/index.js');
const { createDataRouter } = await import('../packages/modules/data-router/index.js');
// One ingest routes TASKs to a grid and a PROJECT to two forms; overlap: true lets
// the grid AND the forms all show the same record.
const router = createDataRouter({ key: 'type', rowKey: 'id', overlap: true });
const taskGrid = createHeadlessGrid({ rowKey: 'id', columns: [{ field: 'id' }, { field: 'title' }] });
const projectGrid = createHeadlessGrid({ rowKey: 'id', columns: [{ field: 'id' }, { field: 'name' }, { field: 'status' }] });
router.attach(taskGrid, 'TASK');
router.attach(projectGrid, 'PROJECT');
router.load([
{ id: 'P1', type: 'PROJECT', name: 'Apollo', status: 'open' },
{ id: 'T1', type: 'TASK', title: 'Wire it' },
{ id: 'T2', type: 'TASK', title: 'Ship it' },
]);
// The two forms are created AFTER the ingest and still fill at once.
const { root: root1 } = createTestDom();
const { root: root2 } = createTestDom();
const nameForm = createForm(root1, { rows: [{ type: 'input', name: 'name', label: 'Name' }] });
const statusForm = createForm(root2, { rows: [{ type: 'input', name: 'status', label: 'Status' }] });
const saves = [];
const group = createFormGroup([nameForm, statusForm], {
bind: { router, route: 'PROJECT', key: 'P1', onSave: (changes, record) => saves.push({ changes, record }) },
});
const filled = [nameForm.getValue().name, statusForm.getValue().status].join(','); // Apollo,open
const eager = router.get('PROJECT', 'P1').name; // Apollo - the eager read
// One edit in each member - one router update, one onSave call.
nameForm.getItem('name').el.querySelector('input').value = 'Artemis';
nameForm.getItem('name').el.querySelector('input').dispatchEvent(new TestEvent('change', { bubbles: true }));
statusForm.getItem('status').el.querySelector('input').value = 'review';
statusForm.getItem('status').el.querySelector('input').dispatchEvent(new TestEvent('change', { bubbles: true }));
const saved = await group.save(); // true
const project = projectGrid.rows.byKey('P1').data; // the grid followed the write
const once = saves.length === 1; // true
const both = Object.keys(saves[0].changes).sort().join(','); // name,status
group.destroy();
return [filled, eager, saved, project.name, project.status, once, both].join('|');
A custom control, declarative rules and a wizard, executed
registerControl makes a type a first-class item that round-trips its value; the
visibleWhen/readOnlyWhen/requiredWhen rules re-evaluate as values commit; and a
three-step wizard's next()/back()/goToStep() gate each forward move on the step's
validation - with the real Chrome assertions in test/form-browser.test.js.
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { registerControl, createForm } = await import('../packages/modules/form/index.js');
// A custom control type is a first-class item: it round-trips through the form API.
registerControl('star', {
create(el, item, api) {
const input = el.ownerDocument.createElement('input');
input.className = 'star-input';
input.setAttribute('data-max', String(item.props.max)); // the item's own `props` bag carries the control's settings
el.appendChild(input);
},
getValue(el) { return el.querySelector('.star-input').value; },
setValue(el, value) { el.querySelector('.star-input').value = value == null ? '' : String(value); },
});
const { root } = createTestDom();
const form = createForm(root, {
stepOrientation: 'vertical', // the indicator stacks
steps: [
{ id: 'one', label: 'One', rows: [
{ type: 'input', name: 'plan', label: 'Plan', requiredWhen: true },
{ type: 'input', name: 'code', label: 'Code' },
] },
{ id: 'two', label: 'Two', rows: [
{ type: 'star', name: 'rating', label: 'Rating', value: '3', props: { max: 5 } },
{ type: 'input', name: 'note', label: 'Note', visibleWhen: { name: 'rating', equals: '5' } },
{ type: 'input', name: 'review', label: 'Review', readOnlyWhen: { name: 'rating', in: ['4', '5'] } },
] },
{ id: 'three', label: 'Three', rows: [
{ type: 'input', name: 'summary', label: 'Summary' },
] },
],
});
const vertical = root.querySelector('.lat-form__stepper--vertical') !== null;
const blocked = await form.next(); // 'plan' is required and empty
form.getItem('plan').setValue('Basic'); // a silent write re-runs the rules
const advanced = await form.next(); // step one now validates
const active = form.activeStep; // 1
const custom = form.getItem('rating').getValue(); // '3' - the registered control round-trips
form.setValue({ rating: '5' }); // re-evaluates the rules
const noteHidden = form.getItem('note').el.hidden; // rating 5 → visible
const reviewReadOnly = form.getItem('review').el.querySelector('input').readOnly; // rating 5 → read-only
const wentBack = await form.back(); // back to step one, no validation
const jumped = await form.goToStep(2); // forward again, validating step one on the way
const finish = await form.next(); // on the last step, validates in place
form.destroy();
return [blocked, advanced, active, custom, noteHidden, reviewReadOnly, wentBack, jumped, finish, vertical].join('|');
Step validation, the validateSteps opt-out and the refused move, executed
A forward move - next(), goToStep() to a later step, or a click on a later indicator
step - validates the current step's items exactly as form.validate() does: a required item
left empty refuses the move, resolves false, paints the same aria-invalid and message, fires
validated and focuses the first invalid item, while back() never validates. validateSteps:
false restores the unchecked navigation - with the real Chrome indicator-click assertions in
test/form-steps-validate-2290-browser.test.js.
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
let validated = 0;
const form = createForm(root, {
steps: [
{ id: 'a', label: 'A', rows: [
{ type: 'input', name: 'x', label: 'X', required: true },
{ type: 'input', name: 'y', label: 'Y' },
] },
{ id: 'b', label: 'B', rows: [ { type: 'checkbox', name: 'done', label: 'Done', required: true } ] },
],
});
form.on('validated', () => { validated += 1; });
const blocked = await form.next(); // false - x is required and empty
const stayed = form.activeStep; // 0 - the move was refused
const xInput = form.getItem('x').el.querySelector('input');
const invalid = xInput.getAttribute('aria-invalid'); // 'true' - as validate() paints it
const message = form.getItem('x').el.querySelector('.lat-form__validation').textContent; // 'This field is required.'
const focused = root.ownerDocument.activeElement === xInput; // focus lands on the first invalid item
const fired = validated > 0; // the refused move emitted `validated`
form.getItem('x').setValue('Ada'); // fill the required item
const advanced = await form.next(); // true - step one now validates
const wentBack = await form.back(); // true - back never validates
form.destroy();
const uncheckedForm = createForm(root, {
validateSteps: false, // the integrator runs validate() itself
steps: [
{ id: 'a', label: 'A', rows: [ { type: 'input', name: 'x', label: 'X', required: true } ] },
{ id: 'b', label: 'B', rows: [] },
],
});
const unchecked = await uncheckedForm.next(); // true - no validation on the way
uncheckedForm.destroy();
return [blocked, stayed, invalid, message, focused, fired, advanced, wentBack, unchecked].join('|');
Required, a regex, a function, modes and the validated event, executed
An empty required item fails form.validate() with its catalogue message (overridden here to French) and
aria-invalid; a regex rule and a function rule each pass and fail through item.validate(); a
validationMode: 'change' item re-checks itself on a committed edit; and a final form.validate()
passes once every item is valid - with the real Chrome geometry and aria-invalid asserted in
test/form-browser.test.js.
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
let validated = 0;
const form = createForm(root, {
messages: { t: (key) => (key === 'form.validation.required' ? 'Pflichtfeld' : key) },
rows: [
{ type: 'input', name: 'name', label: 'Name', required: true },
{ type: 'input', name: 'code', label: 'Code', validation: /^[A-Z]{3}$/, errorMessage: 'Three capitals' },
{ type: 'input', name: 'age', label: 'Age', validation: (v) => v === '' || Number(v) >= 18 || 'Must be 18+', validationMode: 'change' },
{ type: 'input', name: 'site', label: 'Site', validation: 'url', successMessage: 'Reachable', preMessage: 'https://…' },
],
});
form.on('validated', () => { validated += 1; });
const emptyFails = form.validate(); // false - the required name is empty
const nameInput = form.getItem('name').el.querySelector('input');
const nameInvalid = nameInput.getAttribute('aria-invalid'); // 'true'
const nameMessage = form.getItem('name').el.querySelector('.lat-form__validation').textContent; // 'Pflichtfeld'
form.setValue({ code: 'abc' });
const codeFails = form.getItem('code').validate(); // false - the regex rule
form.setValue({ code: 'XYZ' });
const codePasses = form.getItem('code').validate(); // true
const ageInput = form.getItem('age').el.querySelector('input');
ageInput.value = '3';
ageInput.dispatchEvent(new TestEvent('change', { bubbles: true }));
const ageInvalid = ageInput.getAttribute('aria-invalid'); // 'true' - change mode
form.setValue({ name: 'Ada', age: 30, site: 'https://example.com' });
const allValid = form.validate(); // true
const success = form.getItem('site').el.querySelector('.lat-form__validation').textContent; // 'Reachable'
return [emptyFails, nameInvalid, nameMessage, codeFails, codePasses, ageInvalid, allValid, success, validated].join('|');
A server form enhanced in place, with the htmx adapter, executed
enhanceForm turns a server-rendered <form> into a Lattice form in
place - each named field keeps its name, value, label and validation, and the submit controls survive the
mount so hx-post still posts - and the htmx adapter's autoInitForm,
registerForm, destroyFormWithin, saveFormStateWithin and
restoreFormStateWithin drive it declaratively from data-lattice-form, the same
save/restore pattern as data-lattice-shell. The field mapping, submit preservation and
validate-before-post gate are driven against the real createForm in test/form-enhance.test.js,
and the adapter wiring in test/htmx-form.test.js.
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { enhanceForm } = await import('../packages/modules/form/index.js');
const H = await import('../packages/modules/htmx/index.js');
const { root, document: doc } = createTestDom();
// A server-rendered form: its fields and submit button are plain markup, so
// with JavaScript off it still posts exactly as the server rendered it.
const server = doc.createElement('form');
server.setAttribute(H.FORM_ATTR, '');
server.setAttribute('hx-post', '/contact');
const label = doc.createElement('label');
label.setAttribute('for', 'email');
label.textContent = 'Email';
const email = doc.createElement('input');
email.id = 'email';
email.name = 'email';
email.type = 'email';
email.required = true;
const submit = doc.createElement('button');
submit.type = 'submit';
server.appendChild(label);
server.appendChild(email);
server.appendChild(submit);
server.elements = [email, submit];
root.appendChild(server);
// The page's form module registers the enhancer once; the htmx adapter resolves
// it at build time rather than inlining the form engine into its bundle.
H.registerForm(enhanceForm);
const built = H.autoInitForm(root); // one form enhanced in place
const published = server.__latticeForm === built[0]; // the form published itself on the host
built[0].setValue({ email: 'a@b.c' }); // a silent write, no event
const saved = H.saveFormStateWithin(server); // values → the history attribute
built[0].setValue({ email: 'changed@x.y' }); // a later edit, as a swap would leave
const restoredCount = H.restoreFormStateWithin(server, H.autoInitForm);
const restored = built[0].getValue().email; // 'a@b.c' - the saved values win
const destroyed = H.destroyFormWithin(server); // scoped teardown on a swap
const gone = server.__latticeForm === null; // the host no longer publishes a form
return [H.FORM_ATTR, built.length, published, saved, restoredCount, restored, destroyed, gone].join('|');
Choice, toggle and date controls, executed
A select renders its own trigger and drop-down listbox on the combo's listbox and commits when an option is chosen - or keeps the native element with native: true.
The select's, the combo's and the date picker's popup all open in the same shared top-level layer, positioned
against the field and never clipped by an ancestor's overflow: hidden or fixed height:
it flips above when there is no room below, follows the field on scroll and resize, and closes on an outside
pointer down, Escape, Tab out or the field scrolling out of view;
a radiogroup and a checkboxgroup commit on their options' change - laid out vertically by
default, on one wrapping row with orientation: 'horizontal' (the radiogroup carries a matching
aria-orientation and ArrowLeft/ArrowRight move between radios), or in an n-column grid with
columns: n; a toggle is a
boolean switch; and a datepicker stores an ISO wall-clock value, reads a Date in its
timeZone like the grid's date columns, refuses a commit outside min/max,
and fences individual days off with disabledDates - an ISO list or a function such as
"Mondays only" (iso) => new Date(iso + 'T00:00:00Z').getUTCDay() !== 1, drawn disabled and
skipped by the arrow keys - with the keyboard and calendar-click path asserted in real Chrome in
test/form-browser.test.js. Its options take the same adornments as the combo's - a real
icon, a round avatar, a color that tints them, and a dot
colour shorthand - and both the list rows and the
shown value accept optionTemplate/selectedTemplate renderers (a DOM node or an
HTML string, sanitised before insertion). Values supplied in options keep their own type through
getValue() and the change payload - choosing { value: 1 } commits the
number 1, not the string '1'.
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, {
rows: [
{ type: 'select', name: 'size', label: 'Size', options: ['s', 'm', 'l'], value: 'm' },
{ type: 'select', name: 'nativeSize', label: 'Native size', native: true, options: ['s', 'm', 'l'], value: 'm' },
{ type: 'radiogroup', name: 'colour', label: 'Colour', options: ['red', 'green'], value: 'green' },
{ type: 'checkboxgroup', name: 'extras', label: 'Extras', options: [{ value: 'roof', label: 'Roof' }, { value: 'tow', label: 'Tow bar' }], value: ['tow'] },
{ type: 'toggle', name: 'auto', label: 'Automatic', value: true },
{ type: 'datepicker', name: 'day', label: 'Day', locale: 'en-GB', min: '2026-01-01', max: '2026-12-31', value: '2026-06-15', clearable: true },
{ type: 'datepicker', name: 'slot', label: 'Slot', mode: 'date-time', timeZone: 'UTC', value: new Date('2026-06-15T09:30:00Z') },
{ type: 'datepicker', name: 'clock', label: 'Clock', mode: 'time', value: '07:45' },
],
});
const started = [form.getValue().size, form.getValue().colour, form.getValue().extras.join(','), form.getValue().auto, form.getValue().day, form.getValue().slot, form.getValue().clock].join('|');
let changes = 0;
form.on('change', () => { changes += 1; });
const sizeOption = form.getItem('size').el.querySelector('[data-value="l"]');
sizeOption.dispatchEvent(new TestEvent('click', { bubbles: true }));
const toggle = form.getItem('auto').el.querySelector('input');
toggle.checked = false;
toggle.dispatchEvent(new TestEvent('change', { bubbles: true }));
const radio = form.getItem('colour').el.querySelectorAll('input')[0];
radio.checked = true;
radio.dispatchEvent(new TestEvent('change', { bubbles: true }));
const boxes = form.getItem('extras').el.querySelectorAll('input');
boxes[0].checked = true;
boxes[1].checked = true;
boxes[0].dispatchEvent(new TestEvent('change', { bubbles: true }));
const committed = [form.getValue().size, form.getValue().colour, form.getValue().extras.join(','), form.getValue().auto, changes].join('|');
const dayItem = form.getItem('day');
const dayPopup = dayItem.el.querySelector('.lat-form__datepicker-popup'); // captured before open: the popup moves into the shared layer host while open
dayItem.el.querySelector('.lat-form__datepicker-toggle').dispatchEvent(new TestEvent('click', { bubbles: true }));
dayPopup.querySelector('.lat-form__datepicker-day').dispatchEvent(new TestEvent('click', { bubbles: true }));
const clicked = form.getValue().day;
const dayInput = form.getItem('day').el.querySelector('input');
dayInput.value = '2025-01-01';
dayInput.dispatchEvent(new TestEvent('change', { bubbles: true }));
const refused = form.getValue().day;
dayInput.value = '2026-07-04';
dayInput.dispatchEvent(new TestEvent('change', { bubbles: true }));
const accepted = form.getValue().day;
const dayClear = form.getItem('day').el.querySelector('.lat-form__datepicker-clear');
dayClear.dispatchEvent(new TestEvent('click', { bubbles: true }));
const cleared = form.getValue().day === null;
form.getItem('clock').setValue('23:59');
const clock = form.getItem('clock').getValue();
const nativeSelect = form.getItem('nativeSize').el.querySelector('select');
const nativeRendered = nativeSelect !== null;
nativeSelect.value = 'l';
nativeSelect.dispatchEvent(new TestEvent('change', { bubbles: true }));
const nativeValue = form.getValue().nativeSize;
const native = [nativeRendered, nativeValue].join('|');
form.destroy();
return [started, committed, clicked, refused, accepted, clock, native, cleared].join('|');
A date picker limited to Mondays, executed
A datepicker item's disabledDates takes the same
shape as the daterange's - an ISO string list or a function (iso) =>
boolean over the day. Here the function admits only Mondays: every other day renders disabled and a
typed disabled day is refused with the catalogue message.
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, {
rows: [
{ type: 'datepicker', name: 'monday', label: 'Mondays only', locale: 'en-GB', value: '2026-06-01', disabledDates: (iso) => new Date(iso + 'T00:00:00Z').getUTCDay() !== 1 },
],
});
const item = form.getItem('monday');
const popup = item.el.querySelector('.lat-form__datepicker-popup'); // captured before open: the popup moves into the shared layer host while open
item.el.querySelector('.lat-form__datepicker-toggle').dispatchEvent(new TestEvent('click', { bubbles: true }));
const day = (n) => [].slice.call(popup.querySelectorAll('.lat-form__datepicker-day')).find((b) => b.textContent === String(n));
const fridayDisabled = day(5).disabled;
const mondayEnabled = !day(8).disabled;
const input = item.el.querySelector('input');
input.value = '2026-06-05';
input.dispatchEvent(new TestEvent('change', { bubbles: true }));
const refused = form.getValue().monday;
input.value = '2026-06-08';
input.dispatchEvent(new TestEvent('change', { bubbles: true }));
const accepted = form.getValue().monday;
form.destroy();
return [fridayDisabled, mondayEnabled, refused, accepted].join('|');
A date range picker, executed
A daterange item stores { start, end } ISO dates (or
YYYY-MM months with granularity: 'month') in one field, and opens a two-month popup
where the first click sets the start, the second the end, a click before the start restarts, and hovering
previews the span. min/max, minSpan/maxSpan and
disabledDates fence the choice; presets draws a left-hand list (today, yesterday,
last 7/30 days, this/last month by default); weekNumbers adds the ISO week column and
firstDay shifts the header. Apply commits and Cancel restores by default;
applyButton: false commits on the second click. The two-click span, presets, limits and month
mode are asserted in real Chrome in test/daterange-2255-browser.test.js.
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, { rows: [
{ type: 'daterange', name: 'range', label: 'Range', min: '2026-06-01', max: '2026-06-30', value: { start: '2026-06-01', end: '2026-06-30' } },
{ type: 'daterange', name: 'quick', label: 'Quick', applyButton: false, value: { start: '2026-06-20', end: '2026-06-20' } },
{ type: 'daterange', name: 'preset', label: 'Preset', presets: [{ label: 'Q2', range: ['2026-04-01', '2026-06-30'] }] },
{ type: 'daterange', name: 'limited', label: 'Limited', minSpan: 2, maxSpan: 5, disabledDates: ['2026-06-05'], value: { start: '2026-06-08', end: '2026-06-10' } },
{ type: 'daterange', name: 'weeks', label: 'Weeks', weekNumbers: true, firstDay: 1, value: { start: '2026-06-08', end: '2026-06-10' } },
{ type: 'daterange', name: 'months', label: 'Months', granularity: 'month', value: { start: '2024-03', end: '2024-03' } },
]});
const clickDay = function (item, label) {
const day = [].slice.call(item.el.querySelectorAll('.lat-form__daterange-day'))
.find(function (b) { return b.textContent === label && !b.disabled; });
day.dispatchEvent(new TestEvent('click', { bubbles: true }));
};
const apply = function (item) {
item.el.querySelector('.lat-form__daterange-apply').dispatchEvent(new TestEvent('click', { bubbles: true }));
};
const range = form.getItem('range');
range.el.querySelector('.lat-form__daterange-toggle').dispatchEvent(new TestEvent('click', { bubbles: true }));
clickDay(range, '10');
clickDay(range, '15');
apply(range);
const picked = form.getValue().range;
const quick = form.getItem('quick');
quick.el.querySelector('.lat-form__daterange-toggle').dispatchEvent(new TestEvent('click', { bubbles: true }));
clickDay(quick, '20');
clickDay(quick, '22');
const quickValue = form.getValue().quick;
const preset = form.getItem('preset');
preset.el.querySelector('.lat-form__daterange-toggle').dispatchEvent(new TestEvent('click', { bubbles: true }));
preset.el.querySelector('.lat-form__daterange-preset').dispatchEvent(new TestEvent('click', { bubbles: true }));
apply(preset);
const presetValue = form.getValue().preset;
const limited = form.getItem('limited');
limited.el.querySelector('.lat-form__daterange-toggle').dispatchEvent(new TestEvent('click', { bubbles: true }));
const day5Disabled = [].slice.call(limited.el.querySelectorAll('.lat-form__daterange-day'))
.find(function (b) { return b.textContent === '5'; }).disabled;
clickDay(limited, '8');
clickDay(limited, '8');
apply(limited);
const limitedValue = form.getValue().limited;
const weeks = form.getItem('weeks');
weeks.el.querySelector('.lat-form__daterange-toggle').dispatchEvent(new TestEvent('click', { bubbles: true }));
const weeknums = weeks.el.querySelectorAll('.lat-form__daterange-weeknum').length;
const firstDayMonday = weeks.el.querySelector('.lat-form__daterange-grid').children[1].textContent === '1';
const months = form.getItem('months');
months.el.querySelector('.lat-form__daterange-toggle').dispatchEvent(new TestEvent('click', { bubbles: true }));
const monthCells = [].slice.call(months.el.querySelectorAll('.lat-form__daterange-month'));
monthCells[0].dispatchEvent(new TestEvent('click', { bubbles: true }));
monthCells[2].dispatchEvent(new TestEvent('click', { bubbles: true }));
apply(months);
const monthsValue = form.getValue().months;
form.destroy();
return picked.start + '|' + picked.end + '|' + quickValue.start + '|' + quickValue.end + '|' + presetValue.start + '|' + presetValue.end + '|' + limitedValue.start + '|' + limitedValue.end + '|' + day5Disabled + '|' + (weeknums > 0) + '|' + firstDayMonday + '|' + monthsValue.start + '|' + monthsValue.end;
A formatted number field, executed
A number item edits the raw number and shows the grid's own
NumberFormat while blurred - currency, percent and fixed decimals - so getValue() stays a
number while the field reads £20,000.00. spinner: true draws two step buttons, and
locale resolves the typed-input separators, so a comma-decimal locale parses its own convention. The
focus/blur flip and the ArrowUp/ArrowDown stepping are asserted in real Chrome in
test/form-browser.test.js.
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, { rows: [
{ type: 'number', name: 'price', label: 'Price', format: { style: 'currency', currency: 'GBP' }, locale: 'en-GB', value: 20000 },
{ type: 'number', name: 'rate', label: 'Rate', format: { style: 'percent' }, locale: 'en-US', value: 0.25 },
{ type: 'number', name: 'qty', label: 'Qty', format: { decimals: 2 }, locale: 'en-GB', value: 5 },
{ type: 'number', name: 'eur', label: 'EUR', format: { style: 'currency', currency: 'EUR' }, locale: 'de-DE', value: 20000 },
{ type: 'number', name: 'steps', label: 'Steps', spinner: true, step: 5, min: 0, max: 100, value: 50 },
] });
const priceShown = form.getItem('price').el.querySelector('input').value; // '£20,000.00' blurred
const priceValue = form.getValue().price; // 20000, still a number
const rateShown = form.getItem('rate').el.querySelector('input').value; // '25%'
const rateValue = form.getValue().rate; // 0.25, the stored fraction
const qtyShown = form.getItem('qty').el.querySelector('input').value; // '5.00' fixed decimals
const eurGrouped = form.getItem('eur').el.querySelector('input').value.includes('20.000,00'); // true, de-DE separators
const spinners = form.getItem('steps').el.querySelectorAll('.lat-form__number-step').length; // 2
form.setValue({ price: 1500.5 });
const typedShown = form.getItem('price').el.querySelector('input').value; // '£1,500.50' reformats on write
const qtyInput = form.getItem('qty').el.querySelector('input');
qtyInput.focus(); // focused: the field edits the raw number
qtyInput.value = '2,500';
qtyInput.dispatchEvent(new TestEvent('change', { bubbles: true }));
const pastedValue = form.getValue().qty; // 2500, parsed in the locale convention
form.destroy();
return [priceShown, priceValue, rateShown, rateValue, qtyShown, eurGrouped, spinners, typedShown, pastedValue].join('|');
Unit-aware number fields, executed
A number item takes the grid's own unit configuration - system and
unit, plus the display options - and stores a plain number in the configured base unit. Blurred it shows
the quantity with its unit; typing any unit of the same system converts on commit (145 psi into a bar
field stores about 9.997), and an unknown unit is refused while the previous value is kept. A
scale makes a temperature field, whose conversion is affine (212 °F into a Celsius field
stores 100); unitPicker: true draws a compact selector that changes only the display unit.
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, { rows: [
{ type: 'number', name: 'pressure', label: 'Pressure', system: 'pressure', unit: 'bar', value: 10 },
{ type: 'number', name: 'capacity', label: 'Capacity', system: 'data', unit: 'GB', locale: 'en-US', value: 10 },
{ type: 'number', name: 'inlet', label: 'Inlet', scale: 'C', value: 100 },
{ type: 'number', name: 'gauge', label: 'Gauge', system: 'pressure', unit: 'bar', unitPicker: true, locale: 'en-US', value: 10 },
] });
const pressure = form.getItem('pressure');
const pInput = pressure.el.querySelector('input');
const shown = pInput.value; // '10 bar'
pInput.dispatchEvent(new TestEvent('focus'));
pInput.value = '145 psi';
pInput.dispatchEvent(new TestEvent('change', { bubbles: true }));
const psiStored = form.getValue().pressure.toFixed(3); // '9.997'
pInput.dispatchEvent(new TestEvent('blur'));
const cInput = form.getItem('capacity').el.querySelector('input');
cInput.dispatchEvent(new TestEvent('focus'));
cInput.value = '10,000M';
cInput.dispatchEvent(new TestEvent('change', { bubbles: true }));
const dataStored = form.getValue().capacity; // 10
cInput.dispatchEvent(new TestEvent('blur'));
pInput.dispatchEvent(new TestEvent('focus'));
pInput.value = '20 kg';
pInput.dispatchEvent(new TestEvent('change', { bubbles: true }));
const kept = form.getValue().pressure.toFixed(3); // '9.997', the old value
const refused = pressure.el.getAttribute('data-invalid'); // 'true'
pInput.dispatchEvent(new TestEvent('blur'));
const tInput = form.getItem('inlet').el.querySelector('input');
tInput.dispatchEvent(new TestEvent('focus'));
tInput.value = '212 °F';
tInput.dispatchEvent(new TestEvent('change', { bubbles: true }));
const celsius = Math.round(form.getValue().inlet); // 100
tInput.dispatchEvent(new TestEvent('blur'));
const gauge = form.getItem('gauge');
const gInput = gauge.el.querySelector('input');
const picker = gauge.el.querySelectorAll('select')[0];
picker.value = 'psi';
picker.dispatchEvent(new TestEvent('change', { bubbles: true }));
const picked = gInput.value; // '145.04 psi'
const unchanged = form.getValue().gauge; // 10, unchanged
form.destroy();
return [shown, psiStored, dataStored, kept, refused, celsius, picked, unchanged].join('|');
Choice-group layout, executed
A radiogroup and a checkboxgroup stack their options vertically by default;
orientation: 'horizontal' lays them on one wrapping row and carries a matching aria-orientation,
and columns: n lays them in an n-column grid read across then down - with the real-Chrome rows, wrapping,
keyboard and density gaps asserted in test/form-choice-layout-2177-browser.test.js.
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, { rows: [
{ type: 'radiogroup', name: 'billing', label: 'Billing', orientation: 'horizontal',
options: ['annual', 'monthly'], value: 'annual' },
{ type: 'checkboxgroup', name: 'grid', label: 'Grid', columns: 2,
options: ['a', 'b', 'c', 'd'] },
] });
const radioGroup = form.getItem('billing').el.querySelector('.lat-form__radiogroup');
const gridGroup = form.getItem('grid').el.querySelector('.lat-form__checkboxgroup');
const orientation = radioGroup.getAttribute('aria-orientation'); // 'horizontal'
const horizontal = radioGroup.classList.contains('lat-form__radiogroup--horizontal'); // true
const columns = gridGroup.classList.contains('lat-form__checkboxgroup--columns'); // true
const count = gridGroup.style.getPropertyValue('--lat-form-columns'); // '2'
form.destroy();
return [orientation, horizontal, columns, count].join('|');
A file field and a sanitised rich-text editor, executed
A file item admits no files until they are dropped or picked, round-trips its accepted
entries through getValue()/setValue(), and clears to an empty array; a richtext item
round-trips its sanitised HTML value. The in-tree DOM test double has no HTML parser, so the sanitiser degrades to a
text-only pass there - the real whitelist behaviour (scripts, event handlers and javascript: URLs dropped)
is asserted in real Chrome in test/form-browser.test.js.
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, { rows: [
{ type: 'file', name: 'docs', label: 'Documents', accept: ['.pdf'], maxSize: 1048576, maxFiles: 2, multiple: true, dropText: 'Drop here', hint: 'PDFs up to 1 MB', upload: (file, opts) => null },
{ type: 'richtext', name: 'body', label: 'Body', toolbar: 'rich', value: '<p>Hello <b>world</b></p>', minHeight: 120, maxHeight: 300, linkTarget: '_blank', colors: ['#1f2937'], headings: [['p', 'Paragraph'], ['h1', 'Heading 1']], allowedTags: null, maxImageSize: 512000, onImage: null, sanitizePaste: true },
] });
const fileEmpty = form.getValue().docs.length; // 0 - nothing admitted yet
const fileZone = !!form.getItem('docs').el.querySelector('.lat-uploader__zone');
form.setValue({ docs: [{ id: 'f1', name: 'a.pdf', size: 2048, type: 'application/pdf', status: 'done', progress: 100 }] });
const docName = form.getItem('docs').getValue()[0].name; // 'a.pdf'
const body = form.getItem('body').getValue(); // 'Hello world' - the test double strips tags
const editor = !!form.getItem('body').el.querySelector('.lat-form__richtext-editor');
form.clear();
const cleared = form.getValue().docs.length; // 0 - a file clears to []
form.destroy();
return [fileEmpty, fileZone, docName, body, editor, cleared].join('|');
A file drop area with a custom icon and browse word, executed
A file item’s icon is a glyph name from the file module’s own sprite set, an SVG
markup string, an element, or false for none; browseText replaces the browse link’s word, and the
drop area’s aria-label follows it. The custom cloud SVG, title, hint and word below are asserted in real Chrome in
test/form-browser.test.js.
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, { rows: [
{ type: 'file', name: 'contract', label: 'Contract', icon: '<svg viewBox="0 0 16 16"><path d="M4 12a3 3 0 0 1 0-6 4 4 0 0 1 7.7 1.2A2.5 2.5 0 0 1 13 12z" stroke="currentColor" stroke-width="1.5" fill="none" stroke-linecap="round"/></svg>', dropText: 'Drop the signed contract', hint: 'PDF only, 10 MB max', browseText: 'choose a file' },
] });
const control = form.getItem('contract').el.querySelector('.lat-uploader');
const cloud = !!(control.querySelector('.lat-uploader__icon') && control.querySelector('.lat-uploader__icon').getAttribute('viewBox') === '0 0 16 16'); // true - the cloud SVG
const browse = control.querySelector('.lat-uploader__browse').textContent; // 'choose a file'
const title = control.querySelector('.lat-uploader__title-rest').textContent; // 'Drop the signed contract'
const hint = control.querySelector('.lat-uploader__hint').textContent; // 'PDF only, 10 MB max'
const aria = control.querySelector('.lat-uploader__zone').getAttribute('aria-label'); // 'Drop the signed contract choose a file'
form.destroy();
return [cloud, browse, title, hint, aria].join('|');
A single-select and a multi-select chips row, executed
A chips item is a row of pill buttons: single mode behaves like a radio group (the first
option is selected by default, a click selects another), multi mode returns the selected values in option order and
caps the count at max, and allowEmpty with required fails form.validate()
when nothing is picked - with the real Chrome selection geometry and the light/dark computed colours asserted in
test/form-browser.test.js.
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, { rows: [
{ type: 'chips', name: 'lang', label: 'Language', options: [{ value: 'js', label: 'JavaScript' }, { value: 'ts', label: 'TypeScript' }, { value: 'py', label: 'Python', disabled: true }] },
{ type: 'chips', name: 'tags', label: 'Tags', multiple: true, max: 2, wrap: false, options: [{ value: 'a', label: 'A' }, { value: 'b', label: 'B' }, { value: 'c', label: 'C' }] },
{ type: 'chips', name: 'pick', label: 'Pick one', allowEmpty: true, required: true, options: [{ value: 'x', label: 'X' }, { value: 'y', label: 'Y' }] },
] });
const started = form.getItem('lang').getValue(); // 'js' - single mode defaults to the first option
const chips = form.getItem('lang').el.querySelectorAll('.lat-form__chip');
chips[1].dispatchEvent(new TestEvent('click', { bubbles: true }));
const clicked = form.getItem('lang').getValue(); // 'ts' - a click selects one chip
form.setValue({ tags: ['c', 'a'] }); // written in any order
const ordered = form.getItem('tags').getValue().join(','); // 'a,c' - read back in option order
const capped = form.getItem('tags').getValue().length; // 2 - the max cap holds
const requiredFails = form.validate(); // false - allowEmpty + required, nothing picked
return [started, clicked, ordered, capped, requiredFails].join('|');
A single and a multi-select toggle group, executed
A togglegroup item renders one two-state button per option. Single mode keeps
exactly one pressed, multi mode toggles each independently, and the value is a { id: boolean } map.
Each press fires one change whose detail carries the option's id and new
pressed state; gap spaces the buttons and full stretches the group
(or one button) to the item width.
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, { rows: [
{ type: 'togglegroup', name: 'view', label: 'View', options: [
{ id: 'grid', text: 'Grid', offText: 'List' },
{ id: 'map', text: 'Map' },
{ id: 'list', text: 'List', disabled: true },
] },
{ type: 'togglegroup', name: 'flags', label: 'Flags', multiselect: true, options: [
{ id: 'a', text: 'A' }, { id: 'b', text: 'B' }, { id: 'c', text: 'C' },
] },
{ type: 'togglegroup', name: 'stretch', label: 'Stretch', gap: 8, full: true, options: [
{ id: 'left', text: 'Left', full: true }, { id: 'right', text: 'Right' },
] },
] });
let viewChanges = 0;
let detail = '';
form.on('change', function (e) {
if (e.name === 'view') { viewChanges += 1; detail = e.id + ':' + e.pressed; }
});
const single = form.getItem('view').el.querySelector('.lat-form__togglegroup');
const sbtns = single.querySelectorAll('.lat-form__togglegroup-btn');
sbtns[1].dispatchEvent(new TestEvent('click', { bubbles: true }));
sbtns[0].dispatchEvent(new TestEvent('click', { bubbles: true }));
sbtns[0].dispatchEvent(new TestEvent('click', { bubbles: true })); // already pressed: no further change
const vv = form.getItem('view').getValue();
const singleCount = Object.values(vv).filter(function (v) { return v === true; }).length; // 1 - never two pressed
const flags = form.getItem('flags').el.querySelector('.lat-form__togglegroup');
const fbtns = flags.querySelectorAll('.lat-form__togglegroup-btn');
fbtns[0].dispatchEvent(new TestEvent('click', { bubbles: true }));
fbtns[2].dispatchEvent(new TestEvent('click', { bubbles: true }));
const fv = form.getItem('flags').getValue();
const flagsValue = [fv.a, fv.b, fv.c].join(','); // 'true,false,true' - independent toggles
const stretch = form.getItem('stretch').el.querySelector('.lat-form__togglegroup');
const gap = stretch.style.getPropertyValue('--lat-form-gap'); // '8px' - the gap
const fullGroup = stretch.getAttribute('data-full'); // 'true' - the group stretches
form.destroy();
return [singleCount, viewChanges, detail, flagsValue, gap, fullGroup].join('|');
A colour swatch field: palette, custom colours, clearable and read-only, executed
A color item's swatch or trailing icon opens a popover under the field: the
palette view's shared swatch grid (ten hues in five shades, a grey row, and a customColors row),
grayShades: false dropping the grey row, clearable adding a control that sets
null, editable: false making the text part read-only, and pickerOnly with
mode: 'picker' opening straight on the saturation/lightness picker with no palette view - with
the keyboard model, the computed swatch colours and the light/dark popover surface asserted in
test/form-color-browser.test.js.
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, { rows: [
{ type: 'color', name: 'brand', label: 'Brand', value: '#1a2b3c', clearable: true, customColors: ['#112233'] },
{ type: 'color', name: 'bg', label: 'Background', grayShades: false },
{ type: 'color', name: 'locked', label: 'Locked', value: '#ff0000', editable: false },
{ type: 'color', name: 'po', label: 'Picker only', pickerOnly: true, mode: 'picker' },
] });
// Palette view: the shared swatch grid (ten hues x five shades, the grey row, one custom colour).
const brandEl = form.getItem('brand').el.querySelector('.lat-form__color');
brandEl.querySelector('.lat-form__color-toggle').dispatchEvent(new TestEvent('click', { bubbles: true }));
const popover = brandEl.querySelector('.lat-form__color-popover');
const swatchCount = popover.querySelectorAll('.lat-form__swatch').length; // 56 = 50 + grey row (5) + custom (1)
popover.querySelectorAll('.lat-form__swatch')[7].dispatchEvent(new TestEvent('click', { bubbles: true }));
const picked = form.getValue().brand; // the clicked swatch's hex
const closed = popover.hidden; // true - a selection closes the popover
// setValue normalises rgb(); clear sets null.
form.getItem('brand').setValue('rgb(255, 0, 0)');
const normalized = form.getValue().brand; // '#ff0000'
brandEl.querySelector('.lat-form__color-clear').dispatchEvent(new TestEvent('click', { bubbles: true }));
const cleared = form.getValue().brand; // null
// grayShades: false drops the grey row.
const bgEl = form.getItem('bg').el.querySelector('.lat-form__color');
bgEl.querySelector('.lat-form__color-toggle').dispatchEvent(new TestEvent('click', { bubbles: true }));
const noGraySwatchCount = bgEl.querySelector('.lat-form__color-popover').querySelectorAll('.lat-form__swatch').length; // 50
// editable: false leaves the text part read-only.
const lockedReadOnly = form.getItem('locked').el.querySelector('.lat-form__color-input').readOnly; // true
// pickerOnly + mode: 'picker' opens straight on the picker, with no palette and no Back button.
const poEl = form.getItem('po').el.querySelector('.lat-form__color');
poEl.querySelector('.lat-form__color-toggle').dispatchEvent(new TestEvent('click', { bubbles: true }));
const poPopover = poEl.querySelector('.lat-form__color-popover');
const poHasPicker = !!poPopover.querySelector('.lat-form__color-picker'); // true
const poHasBack = !!poPopover.querySelector('.lat-form__color-back'); // false
return [swatchCount, picked, closed, normalized, cleared, noGraySwatchCount, lockedReadOnly, poHasPicker, poHasBack].join('|');
A time field: 12/24-hour, editable entry, object values and Close/Save, executed
A time item is the datepicker's clock under its own type name. It stores a
wall-clock time read from a Date, an HH:MM string, a number of minutes since midnight or
the object form { hour, minute, AM? }, and writes it as a string (HH:MM, or
hh:MM AM in 12-hour) or the object form with valueFormat. timeFormat: 12 adds
an AM/PM segment to the popup and display; editable: true lets the field text be typed, committing on
blur or Enter and refusing an invalid clock with a validation message; and controls: true adds Close
and Save so nothing commits until Save and Close discards - with the popup geometry and the Close/Save commit
asserted in real Chrome in test/form-time-2343-browser.test.js.
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, { rows: [
{ type: 'time', name: 'clock', label: 'Clock', value: '13:05' },
{ type: 'time', name: 'twelve', label: 'Twelve', timeFormat: 12, value: '13:05' },
{ type: 'time', name: 'obj', label: 'Object', valueFormat: 'object', timeFormat: 12, value: '13:05' },
{ type: 'time', name: 'typed', label: 'Typed', editable: true, value: '09:00' },
{ type: 'time', name: 'confirmed', label: 'Confirmed', controls: true, icon: 'clock', value: '08:15' },
] });
// A number of minutes since midnight and the object form read the same clock.
form.getItem('clock').setValue(785);
const minutes = form.getValue().clock; // '13:05'
form.getItem('clock').setValue({ hour: 13, minute: 5 });
const objectIn = form.getValue().clock; // '13:05'
// 12-hour: the display and the string value carry the AM/PM segment.
const twelveText = form.getItem('twelve').el.querySelector('input').value; // '01:05 PM'
const twelveValue = form.getValue().twelve; // '01:05 PM'
// valueFormat: 'object' stores { hour, minute, AM? }.
const objValue = form.getValue().obj;
const objText = 'hour=' + objValue.hour + ',minute=' + objValue.minute + ',AM=' + objValue.AM; // hour=1,minute=5,AM=false
// editable: true commits a typed clock on Enter, and refuses an invalid one.
const typedInput = form.getItem('typed').el.querySelector('input');
typedInput.value = '09:30';
typedInput.dispatchEvent(new TestEvent('keydown', { key: 'Enter', bubbles: true }));
const typedValue = form.getValue().typed; // '09:30'
typedInput.value = '25:00';
typedInput.dispatchEvent(new TestEvent('keydown', { key: 'Enter', bubbles: true }));
const refused = form.getValue().typed; // '09:30' - kept
const typedError = form.getItem('typed').el.querySelector('.lat-form__error') !== null; // true
// controls: true - Save commits the popup clock, Close discards it.
const confirmedEl = form.getItem('confirmed').el.querySelector('.lat-form__time');
const confirmedPopup = confirmedEl.querySelector('.lat-form__time-popup'); // captured before open: the popup moves into the shared layer host while open
confirmedEl.querySelector('.lat-form__time-toggle').dispatchEvent(new TestEvent('click', { bubbles: true }));
confirmedPopup.querySelector('.lat-form__time-hour').value = '10';
confirmedPopup.querySelector('.lat-form__time-hour').dispatchEvent(new TestEvent('change', { bubbles: true }));
const beforeSave = form.getValue().confirmed; // '08:15' - still uncommitted
confirmedPopup.querySelector('.lat-form__time-save').dispatchEvent(new TestEvent('click', { bubbles: true }));
const saved = form.getValue().confirmed; // '10:15'
confirmedEl.querySelector('.lat-form__time-toggle').dispatchEvent(new TestEvent('click', { bubbles: true }));
confirmedPopup.querySelector('.lat-form__time-hour').value = '11';
confirmedPopup.querySelector('.lat-form__time-hour').dispatchEvent(new TestEvent('change', { bubbles: true }));
confirmedPopup.querySelector('.lat-form__time-close').dispatchEvent(new TestEvent('click', { bubbles: true }));
const discarded = form.getValue().confirmed; // '10:15' - unchanged
return [minutes, objectIn, twelveText, twelveValue, objText, typedValue, refused, typedError, beforeSave, saved, discarded].join('|');
The speed dial control
For a small set of primary actions the form also ships createSpeedDial(el, config), the standalone
form of the type: 'speeddial' item: a round floating action button (FAB) anchored to a corner or edge of
its container - position is top-left, top-center, top-right,
middle-left, middle-right, bottom-left, bottom-center or
bottom-right, and fixed: true anchors it to the viewport instead. Pressing the FAB (or
hovering it with openOnHover) opens items - each { id, icon, text, disabled, render },
icon-only, text-only or both - as a linear strip whose direction is up, down,
left, right or auto (picked from position), or as a radial fan with
mode: 'radial' whose radial startAngle/endAngle/offset
default from position. modal: true paints a backdrop that swallows page clicks; a click on an
item fires itemClick once and closes, outside/Escape closes with focus back on the FAB, and the keyboard
model moves across items with the arrows (skipping disabled ones) and activates with Enter or Space. The FAB swaps
openIcon/closeIcon, may carry a text label, and takes one of seven theme
variants; dark mode and RTL mirroring are built in. The menu is a role="menu" of
role="menuitem"s; the FAB is a role="button" with aria-expanded and
aria-controls.
| Member | Description |
|---|---|
| createSpeedDial(el, config?) | Create a standalone speed dial. config is the SpeedDialConfig options below. Returns { el, fab, menu, open, close, toggle, setItems, setDisabled, destroy }. |
| item | A type: 'speeddial' item takes the same options (position, fixed, openOnHover, direction, mode, radial, modal, openIcon, closeIcon, variant, disabled) plus items; its label is the FAB text. |
| items | The actions, in order: each { id, icon, text, disabled, render }. icon is a glyph name drawn as the real SVG (or a URL/element), text the label, disabled an action that shows but refuses a click, and render(item, index) replaces the item's own content. |
| position / fixed | The eight corner/edge anchor positions; fixed: true anchors the FAB to the viewport instead of the container, and the menu opens into the room side of the anchor. |
| direction / mode / radial | A linear strip's direction (up, down, left, right, auto - the default, resolved from position), or mode: 'radial' with radial startAngle, endAngle and offset (angles default from position). |
| modal / openOnHover | modal: true paints a backdrop that swallows page clicks until the menu closes; openOnHover: true opens on pointer enter and closes on pointer leave. |
| openIcon / closeIcon / text / variant | The FAB's closed/open icons (default plus/close), an optional FAB text label, and one of seven theme variants: primary (default), secondary, outline, info, success, warning, danger. |
| open() / close() / toggle() | Drive the menu, emitting the matching open/close event on a real transition; setItems(list) replaces the actions, setDisabled() gates the FAB and destroy() tears it down. |
A FAB with a text label, disabled actions, a modal backdrop and hover, executed
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createSpeedDial, createForm } = await import('../packages/modules/form/index.js');
const { document, root } = createTestDom();
// A standalone speed dial: a text FAB, three actions (the middle disabled),
// a modal backdrop, opening a linear strip upward.
const host = document.createElement('div');
root.appendChild(host);
const sd = createSpeedDial(host, {
items: [
{ id: 'edit', icon: 'pencil', text: 'Edit' },
{ id: 'share', icon: 'share', text: 'Share', disabled: true },
{ id: 'trash', text: 'Delete' },
],
position: 'bottom-right',
direction: 'up',
modal: true,
text: 'Actions',
openIcon: 'plus',
closeIcon: 'close',
});
const fabButton = sd.fab.tagName === 'BUTTON'; // true - the FAB is a real button
const fabIcon = !!sd.fab.querySelector('svg'); // true - a glyph SVG
const itemCount = sd.menu.querySelectorAll('.lat-speeddial__item').length; // 3
const textOnly = sd.menu.querySelectorAll('.lat-speeddial__item')[2].getAttribute('data-text-only'); // 'true'
sd.open();
const expanded = sd.fab.getAttribute('aria-expanded'); // 'true'
const menuShown = sd.menu.hidden === false; // true
const backdropShown = root.querySelector('.lat-speeddial__backdrop').hidden === false; // true - modal backdrop
sd.toggle();
const toggledClosed = sd.menu.hidden; // true - toggle closes the open menu
sd.toggle();
// A click on an enabled item closes; a disabled item refuses.
sd.menu.querySelectorAll('.lat-speeddial__item')[0].dispatchEvent(new TestEvent('click', { bubbles: true }));
const closedAfterClick = sd.menu.hidden; // true
sd.open();
sd.menu.querySelectorAll('.lat-speeddial__item')[1].dispatchEvent(new TestEvent('click', { bubbles: true }));
const disabledIgnored = sd.menu.hidden === false; // true
// setItems replaces the strip; destroy removes the root.
sd.setItems([{ id: 'a', text: 'A' }, { id: 'b', text: 'B' }]);
const afterSetItems = sd.menu.querySelectorAll('.lat-speeddial__item').length; // 2
sd.destroy();
const destroyed = sd.el.parentNode === null; // true
// A form item: label is the FAB text, hover opens, Escape closes and returns
// focus; itemClick reports the activated action once.
const form = createForm(root, { rows: [{
type: 'speeddial', name: 'fab', label: 'More', position: 'top-left',
fixed: true, openOnHover: true, mode: 'linear', modal: true,
variant: 'danger', openIcon: 'plus', closeIcon: 'close',
radial: { startAngle: 0, endAngle: 90, offset: 64 },
items: [{ id: 'go', text: 'Go' }],
}] });
const item = form.getItem('fab');
const fab = item.el.querySelector('.lat-speeddial__fab');
const clicks = [];
form.on('itemClick', (e) => clicks.push(e.item.id + ':' + e.index));
fab.dispatchEvent(new TestEvent('pointerenter', { bubbles: true }));
const hoverOpened = fab.getAttribute('aria-expanded') === 'true'; // true
fab.dispatchEvent(new TestEvent('keydown', { key: 'Escape', bubbles: true }));
const escapeClosed = fab.getAttribute('aria-expanded') === 'false'; // true
const focusReturned = document.activeElement === fab; // true - focus back on the FAB
fab.dispatchEvent(new TestEvent('click', { bubbles: true }));
item.el.querySelector('.lat-speeddial__item').dispatchEvent(new TestEvent('click', { bubbles: true }));
const itemClickReported = clicks.join(','); // 'go:0'
const closedAfterFormItem = fab.getAttribute('aria-expanded') === 'false'; // true
return [fabButton, fabIcon, itemCount, textOnly, expanded, menuShown, backdropShown, toggledClosed, closedAfterClick, disabledIgnored, afterSetItems, destroyed, hoverOpened, escapeClosed, focusReturned, itemClickReported, closedAfterFormItem].join('|');
The avatar control
A type: 'avatar' item is a profile picture: with a value it shows value.src at
size (small, medium - the default, 64px - large, or a
pixel number), rounded to a circle with circle: true; with no value it falls back to preview
(an image URL), then icon, then the placeholder text (the catalogue's "Add a photo" by
default). Clicking the picture, pressing Enter/Space on it, or dropping a file onto it opens the file chooser
(accept defaults to ['image/*']); a file over maxSize is refused with a
catalogued message surfaced through the item's validate() rather than admitted. An admitted file
previews immediately as a data URL and commits { src, file, name, size, status: 'pending' }; with an
upload config (target, fieldName default 'file',
params, headers, autosend default true, updateFromResponse
default true) the file posts as multipart form data the moment it is admitted, moving status through
'uploading' (with progress) to 'done' or 'failed' and, when
updateFromResponse, reading src/id back from the JSON response.
removeIcon (default true) shows a clear control once there is a value, setting it to null;
readOnly shows the picture with no chooser or remove control. change fires on pick, on
upload completion (or failure) and on remove - never on a bare progress tick. The accessible name comes from
the item's label - with the picked-file preview, the real pixel size, the computed circle radius
and the multipart upload against a local mock endpoint asserted in test/form-avatar-2341-browser.test.js.
| Member | Description |
|---|---|
| value | The committed picture - { src, file, name, size, status, progress, id } - or null. Only src is required to read as a value; the rest describe a pending or in-flight upload. |
| size / circle | small, medium (default, 64px), large, or a pixel number; circle: true rounds the picture to 50%, otherwise it keeps the control's rounded-square radius. |
| preview / icon / placeholder | The empty-value fallback chain: an image URL, then a fallback image URL or element, then text (default the catalogue's "Add a photo"). |
| accept / maxSize | MIME patterns the chooser accepts (default ['image/*']) and the largest file size in bytes; a refused pick never becomes a value, and its message surfaces through validate(). |
| removeIcon | Shows the clear control once there is a value (default true); false removes it, leaving only the chooser. |
| upload | { target, fieldName, params, headers, autosend, updateFromResponse } - posts the admitted file as multipart form data and tracks status/progress on the value. |
| alt / required | The picture's accessible alt text; required: true fails validation with no picture. |
A required picture with a maxSize refusal, a circular avatar with remove, a preview/alt/accept/upload config and an icon fallback, executed
Four items: one shows the "Add a photo" placeholder, fails required validation
with no picture, and refuses an oversized pick with a catalogued message rather than ever admitting it as a value;
one starts with a circular picture and its remove control clears it to null, firing
change once; one shows a preview image with its alt text, a restricted
accept list on the chooser, removeIcon: false and an upload config
(fieldName, params, headers, autosend: false so nothing posts,
updateFromResponse: false); and one with no value and no preview falls back to its
icon image, past the placeholder text.
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, { rows: [
{ type: 'avatar', name: 'pic', label: 'Photo', required: true, maxSize: 1000 },
{ type: 'avatar', name: 'pfp', label: 'Avatar', circle: true, value: { src: 'https://example.com/a.png', name: 'a.png', size: 10 } },
{ type: 'avatar', name: 'thumb', label: 'Thumbnail', alt: 'User thumbnail', accept: ['image/png'],
preview: 'https://example.com/preview.png', removeIcon: false,
upload: { target: 'https://example.com/upload', fieldName: 'photo', params: { kind: 'avatar' }, headers: { 'X-Test': '1' }, autosend: false, updateFromResponse: false } },
{ type: 'avatar', name: 'ic', label: 'Icon fallback', icon: 'https://example.com/fallback.png', placeholder: 'Pick a thumbnail' },
] });
const picEl = form.getItem('pic').el.querySelector('.lat-form__avatar');
const placeholderShown = !!picEl.querySelector('.lat-form__avatar-placeholder-text'); // true
const requiredFails = form.validate(); // false - empty and required
// An oversized pick is refused with a catalogued message; the value never changes.
const input = picEl.querySelector('.lat-form__avatar-input');
input.files = [{ name: 'big.png', size: 5000, type: 'image/png' }];
input.dispatchEvent(new TestEvent('change'));
const stillEmpty = form.getItem('pic').getValue() === null; // true
form.validate();
const rejectMessage = form.getItem('pic').el.querySelector('.lat-form__validation').textContent;
const pfpEl = form.getItem('pfp').el.querySelector('.lat-form__avatar');
const circleClass = pfpEl.querySelector('.lat-form__avatar-picture')
.classList.contains('lat-form__avatar-picture--circle'); // true
let changed = 'unset';
form.on('change', (e) => { if (e.name === 'pfp') changed = e.value; });
pfpEl.querySelector('.lat-form__avatar-remove').dispatchEvent(new TestEvent('click', { bubbles: true }));
const removedToNull = form.getItem('pfp').getValue() === null; // true
// preview/alt/accept/removeIcon, and an upload config that never posts (autosend: false).
const thumbEl = form.getItem('thumb').el.querySelector('.lat-form__avatar');
const thumbImg = thumbEl.querySelector('.lat-form__avatar-img');
const previewShown = thumbImg.src; // the preview URL
const altText = thumbImg.alt; // 'User thumbnail'
const acceptAttr = thumbEl.querySelector('.lat-form__avatar-input').accept; // 'image/png'
const removeHiddenByOption = thumbEl.querySelector('.lat-form__avatar-remove').hidden; // true
// With no value and no preview, icon is the fallback ahead of the placeholder text.
const icEl = form.getItem('ic').el.querySelector('.lat-form__avatar');
const iconShown = icEl.querySelector('.lat-form__avatar-img').src;
return [placeholderShown, requiredFails, stillEmpty, rejectMessage, circleClass, removedToNull, changed === null,
previewShown, altText, acceptAttr, removeHiddenByOption, iconShown].join('|');
A toggle switch with ON/OFF text, size, variant and label position, executed
A toggle item's onLabel/offLabel draw short text inside the
track by default or beside it per props.labelPosition; size scales the switch from the
density tokens, variant picks round, square or slim, the state
label swaps with the checked state and repaints on a silent setValue, and a toggle with none of the
options still renders the bare switch - with the real Chrome geometry, keyboard model, read-only/disabled
behaviour and the light/dark label contrast asserted in test/form-toggle-2257-browser.test.js.
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, { rows: [
{ type: 'toggle', name: 'auto', label: 'Auto', value: true, onLabel: 'ON', offLabel: 'OFF' },
{ type: 'toggle', name: 'lean', label: 'Lean', value: false, onLabel: '1', offLabel: '0', size: 'small', variant: 'slim' },
{ type: 'toggle', name: 'square', label: 'Square', value: true, variant: 'square', onLabel: 'Yes', offLabel: 'No', props: { labelPosition: 'after' } },
{ type: 'toggle', name: 'plain', label: 'Plain', value: true },
] });
const autoField = form.getItem('auto').el.querySelector('.lat-form__toggle-field');
const autoInput = autoField.querySelector('input');
const autoLabel = autoField.querySelector('.lat-form__toggle-label');
const onText = autoLabel.textContent; // 'ON' - the checked state
const insidePosition = autoField.getAttribute('data-label-position'); // 'inside'
let changes = 0;
form.on('change', () => { changes += 1; });
autoInput.checked = false;
autoInput.dispatchEvent(new TestEvent('change', { bubbles: true }));
const offText = autoLabel.textContent; // 'OFF' - swapped by the committed edit
const committed = form.getValue().auto; // false
form.setValue({ auto: true }); // silent write repaints the label
const resetText = autoLabel.textContent; // 'ON'
const lean = form.getItem('lean').el.querySelector('input');
const leanSize = lean.getAttribute('data-size'); // 'small'
const leanVariant = lean.getAttribute('data-variant'); // 'slim'
const squareField = form.getItem('square').el.querySelector('.lat-form__toggle-field');
const squareVariant = squareField.querySelector('input').getAttribute('data-variant'); // 'square'
const squarePosition = squareField.getAttribute('data-label-position'); // 'after'
const plain = form.getItem('plain').el;
const bare = !plain.querySelector('.lat-form__toggle-field'); // true - no label, no wrapper
return [onText, offText, committed, resetText, changes, leanSize, leanVariant, squareVariant, squarePosition, insidePosition, bare].join('|');
Password reveal and one-time-code entry, executed
A password input's reveal button renders inside the field with its catalogue name and
aria-pressed, and reveal: false drops it; an otp item renders length
single-character boxes of the given mode (optionally masked) and round-trips the joined code through
getValue()/setValue(). The toggle by click and a real keyboard press, the reset on blur,
typing/Backspace/paste, complete firing once and the real Chrome geometry are asserted in
test/form-password-otp-browser.test.js.
const { createTestDom } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, { rows: [
{ type: 'input', name: 'secret', label: 'Secret', subtype: 'password', value: 'hunter2', reveal: true },
{ type: 'input', name: 'quiet', label: 'Quiet', subtype: 'password', value: 'hunter2', reveal: false },
{ type: 'otp', name: 'code', label: 'Code', length: 6, mode: 'numeric' },
{ type: 'otp', name: 'word', label: 'Word', length: 4, mode: 'alphanumeric', mask: true },
] });
// Password reveal: an eye inside the field, named from the catalogue; reveal:false drops it.
const eye = form.getItem('secret').el.querySelector('.lat-form__password-btn');
const masked = form.getItem('secret').el.querySelector('input').type; // 'password'
const pressed = eye.getAttribute('aria-pressed'); // 'false'
const eyeName = eye.getAttribute('aria-label'); // 'Show password'
const noEye = form.getItem('quiet').el.querySelector('.lat-form__password-btn') === null; // true
// OTP: length boxes, one numeric inputmode, each digit announced.
const code = form.getItem('code').el.querySelector('.lat-form__otp');
const boxCount = code.querySelectorAll('.lat-form__otp-input').length; // 6
const inputmode = code.querySelector('.lat-form__otp-input').getAttribute('inputmode'); // 'numeric'
const pattern = code.querySelector('.lat-form__otp-input').getAttribute('pattern'); // '[0-9]'
const third = code.querySelectorAll('.lat-form__otp-input')[2].getAttribute('aria-label'); // 'Digit 3 of 6'
const wordMask = form.getItem('word').el.querySelector('.lat-form__otp-input').classList.contains('lat-form__otp-input--masked'); // true
// Round-trip: setValue fills the boxes (separators stripped), getValue joins them.
form.setValue({ code: '123 456', word: 'ab-7' });
const joined = form.getValue().code; // '123456'
const wordJoined = form.getValue().word; // 'ab7'
form.destroy();
return [masked, pressed, eyeName, noEye, boxCount, inputmode, pattern, third, wordMask, joined, wordJoined].join('|');
A single slider snapped to a step, and a range slider, executed
A slider item renders a track with one draggable thumb, or two with
range: true (the value is then [low, high], and the thumbs cannot cross - a
reversed configured pair is put in ascending order on build). min/max/step
bound and snap the value exactly as a number item's do, and setValue clamps and snaps
the same way. Each thumb is a role="slider" carrying aria-valuemin/-valuemax/
-valuenow/-valuetext; the keyboard moves it (arrows one step, PageUp/PageDown ten steps,
Home/End), a pointer drag and a click on the track move it too, and change fires once per committed
move. tick/majorTick draw scale marks (the major ones labelled through
tickTemplate), tooltip (default true) shows the live value while dragging
or focused, and mode: 'vertical'/inverse change the track's layout and direction. The
real Chrome drag geometry, every key, range thumbs not crossing, tick/major-tick layout, vertical/inverse
rendering, the tooltip and the fill-versus-track contrast are asserted in
test/form-slider-2340-browser.test.js; the value/event contract in test/form-slider-2340.test.js.
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createForm } = await import('../packages/modules/form/index.js');
const { root } = createTestDom();
const form = createForm(root, { rows: [
{ type: 'slider', name: 'vol', label: 'Volume', min: 0, max: 100, step: 5, value: 42 },
{ type: 'slider', name: 'band', label: 'Band', min: 0, max: 100, range: true, value: [70, 30] },
{ type: 'slider', name: 'scale', label: 'Scale', min: 0, max: 100, majorTick: 50, tickTemplate: (v) => `${v}%`, inverse: true, value: 25 },
] });
const volValue = form.getValue().vol; // 40 - snapped onto the step-5 grid
const bandValue = form.getValue().band; // [30, 70] - the reversed pair is put in order
const thumb = form.getItem('vol').el.querySelector('.lat-form__slider-thumb');
const role = thumb.getAttribute('role'); // 'slider'
const valueNow = thumb.getAttribute('aria-valuenow'); // '40'
let changes = 0;
form.on('change', () => { changes += 1; });
thumb.dispatchEvent(new TestEvent('keydown', { bubbles: true, key: 'ArrowRight' }));
const afterKey = form.getValue().vol; // 45 - one step up, committed with one change
form.getItem('vol').setValue(500); // clamps to max
const clamped = form.getValue().vol; // 100
// majorTick draws a labelled mark every 50 units, formatted through tickTemplate.
const scaleLabels = Array.from(form.getItem('scale').el.querySelectorAll('.lat-form__slider-tick-label'))
.map((n) => n.textContent).sort().join(','); // '0%,100%,50%'
// inverse puts the minimum at the far end: value 25 of 0..100 sits at 75% along the track.
const inverseLeft = form.getItem('scale').el.querySelector('.lat-form__slider-thumb').style.left; // '75.0000%'
return [volValue, JSON.stringify(bandValue), role, valueNow, afterKey, clamped, changes, scaleLabels, inverseLeft].join('|');
Form groups
createFormGroup(forms?, options?) joins several forms - for example one mounted per cell of a shell layout - into one logical form that never renders anything. getValue() merges every member’s values in add order; setValue(values) routes each key to the member that owns that field (the first owner wins when two forms declare the same name, unknown keys are ignored); getItem(name) reaches the owning member’s item handle; validate() validates every member and returns one boolean, focusing the first invalid field in add order and scrolling it into view; and setReadOnly(bool)/setDisabled(bool)/clear()/reset()/isDirty() apply across the members. A member’s change or validated event re-emits on the group as { form, name, value } or { form, valid }, naming the member it came from, and on/off subscribe and detach. A member that is destroyed leaves the group by itself, and group.destroy() detaches the group’s listeners without destroying the forms. options.transform = { get, set } lets a host join the merged values on read and split them back on write.
A member’s visibleWhen, readOnlyWhen and requiredWhen conditions may watch a field of another member. A condition { name, equals | in | empty | fn } whose name the form does not own resolves against the member that owns that field, so a details form can show a field only while the header form’s plan is enterprise. A condition may instead pin the member by its group.add(form, { id }) id - { form: 'header', name: 'status', equals: 'open' } - and an unknown id reads empty with a once-per-id warning. Rules re-evaluate when the owning member’s value commits, on group.setValue(), and when members join or leave; a rule whose source member leaves the group reads an empty value, and a form outside any group behaves exactly as before.
Three forms, one per cell of a shell, joined as one logical form: the merged value is read, a key is
routed to its owner, a field in the third form is reached, the whole group validates, a cross-form
visibleWhen shows a details field once the header’s plan turns
enterprise, and a single Save button reads group.getValue() - run over the in-tree
DOM test double, with the focus and aria states asserted against real Chrome in
test/form-group-2207-browser.test.js.
const { createTestDom, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createShell } = await import('../packages/modules/shell/index.js');
const { createForm, createFormGroup } = await import('../packages/modules/form/index.js');
const { root, document: doc } = createTestDom();
const shell = createShell(root, { rows: [
{ id: 'header' }, { id: 'details' }, { id: 'notes' },
] });
const header = createForm(shell.getCell('header').el, { rows: [
{ type: 'input', name: 'name', label: 'Name', value: 'Ada' },
{ type: 'input', name: 'plan', label: 'Plan', value: 'team' },
] });
const details = createForm(shell.getCell('details').el, { rows: [
{ type: 'input', name: 'email', label: 'Email', value: 'ada@example.com' },
{ type: 'input', name: 'coupon', label: 'Coupon', visibleWhen: { name: 'plan', equals: 'enterprise' } },
] });
const notes = createForm(shell.getCell('notes').el, { rows: [
{ type: 'textarea', name: 'notes', label: 'Notes', value: 'hello' },
] });
const group = createFormGroup([header, details, notes]);
const keys = Object.keys(group.getValue()).join(','); // 'name,plan,email,coupon,notes' - merged
group.setValue({ email: 'grace@example.com' }); // routed to the details form
const routed = details.getItem('email').getValue(); // 'grace@example.com'
const found = group.getItem('notes') === notes.getItem('notes'); // true - the owner's handle
const valid = group.validate(); // true - every field filled
// A rule in the details form watches a field the header form owns.
const couponHidden = details.getItem('coupon').el.hidden; // true - plan is 'team'
group.setValue({ plan: 'enterprise' }); // the header's plan commits
const couponShown = !details.getItem('coupon').el.hidden; // true - now visible
// One Save button reads the whole group.
const saveHost = doc.createElement('div');
doc.body.appendChild(saveHost);
const save = createForm(saveHost, { rows: [
{ type: 'button', name: 'save', label: 'Save' },
] });
let saved = null;
save.on('click', () => { saved = group.getValue(); });
save.getItem('save').el.querySelector('.lat-button').dispatchEvent(new TestEvent('click', { bubbles: true }));
const savedValues = saved.name + '|' + saved.email + '|' + saved.notes;
group.destroy(); // detaches the group's listeners, not the forms
save.destroy();
shell.destroy();
return [keys, routed, found, valid, savedValues, couponHidden, couponShown].join('|');
Type reference
Generated from the type declarations, so it always matches the release. Each surface lists its properties, its methods and the events it raises as three tables; an option or value type lists its members once.
The form module
FormChipOption
One selectable option of a `chips` item.
| Property | Type | Description |
|---|---|---|
| value | unknown | The option's value, returned by `getValue()` when selected. |
| label | string | The text shown on the chip. |
| icon | string | An SVG path `d` string drawn as the chip's inline icon. (optional) |
| disabled | boolean | Start disabled: not clickable, skipped by the keyboard. (optional) |
FormToggleGroupOption
One option of a `togglegroup` item. The group's committed value is a `{ [id]: boolean }` map keyed by each visible option's `id`.
| Property | Type | Description |
|---|---|---|
| id | string | number | The option's key in the committed `{ [id]: boolean }` value; falls back to `value`, then the option's position. |
| value | string | number | The option's fallback key when `id` is omitted. (optional) |
| text | string | The pressed state's text; falls back to `id`. (optional) |
| offText | string | The unpressed state's text; falls back to `text`. (optional) |
| icon | string | Node | The pressed state's icon (an SVG path `d` string, a URL/data URI, or an element); hidden when omitted. (optional) |
| offIcon | string | Node | The unpressed state's icon; falls back to `icon`. (optional) |
| selected | boolean | Start pressed. In single mode only the first selected option wins. (optional) |
| disabled | boolean | Start disabled: not clickable, skipped by the arrow keys. (optional) |
| hidden | boolean | Not rendered and excluded from the value map. (optional) |
| full | boolean | Stretch this one button to fill the group. (optional) |
FormDateRangeValue
The committed value of a `daterange` item.
| Property | Type | Description |
|---|---|---|
| start | string | null | The range start, an ISO `YYYY-MM-DD` day (or `YYYY-MM` month in month mode) or null. |
| end | string | null | The range end, an ISO `YYYY-MM-DD` day (or `YYYY-MM` month in month mode) or null. |
FormTimeValue
The `object` form of a `time` item's committed value when `valueFormat: 'object'`.
| Property | Type | Description |
|---|---|---|
| hour | number | The hour: 0-23 in 24-hour form, or the display hour 1-12 with `AM` carrying the half of the day in 12-hour form. |
| minute | number | The minute, 0-59. |
| AM | boolean | True for the morning half of a 12-hour value; absent in 24-hour form. (optional) |
FormDateRangePreset
One preset of a `daterange` item's left-hand list.
| Property | Type | Description |
|---|---|---|
| label | string | The preset's label. |
| range | [string, string] | ((today: Date) => [string, string]) | The range as a literal `[start, end]` pair, or a function of the current `today` Date returning one. |
FormOption
One choice of a `select`, `radiogroup` or `checkboxgroup` item. A `select` option may also carry an icon, an avatar, a second line, a colour, a status dot and a disabled flag,,.
| Property | Type | Description |
|---|---|---|
| value | string | number | The option's committed value. |
| label | string | The option's display label; the value itself when omitted. (optional) |
| icon | string | The option's icon, drawn on the left in a `select`; `color` tints it. (optional) |
| avatar | string | An image URL (drawn round, falling back to the label's initials), or initials text (drawn round on a colour from `color` or a hash of the label). (optional) |
| color | string | The background colour for the initials avatar (a stable colour derived from the label when omitted) and the tint of the option's icon,. (optional) |
| dot | string | A colour that draws a small filled circle before the label instead of an icon or avatar, with no letter. (optional) |
| description | string | The option's second line, shown under the label in a `select`. (optional) |
| disabled | boolean | Whether the option is shown but not selectable. (optional) |
| group | string | The sticky group header a `listbox` item's `groupBy` buckets this option under. (optional) |
FormOptionGroup
A group of `select` options under one heading.
| Property | Type | Description |
|---|---|---|
| label | string | The group heading. |
| options | (string | FormOption | FormOptionGroup)[] | The group's options, nested groups allowed. |
FormStep
One wizard step: a labelled group of rows, shown one at a time.
| Property | Type | Description |
|---|---|---|
| id | string | The step id, for the indicator's accessible label; defaults to `step-<n>`. (optional) |
| label | string | The step label shown in the indicator. (optional) |
| rows | FormBlock[] | The step's blocks, stacked vertically. |
| css | Record<string, string | number> | string | Extra CSS on the step body. (optional) |
FormControlApi
The object a custom control's `create` receives to talk back to the form.
| Property | Type | Description |
|---|---|---|
| name | string | null | The item's name, or `null` for an unnamed item. (read-only) |
| item | FormItemConfig | The item's config. (read-only) |
| Method | Signature | Parameters | Returns | Description |
|---|---|---|---|---|
| getValue | (): unknown | - | unknown | Read the committed value. |
| setValue | (value: unknown): void | value: unknown | void | Write a committed value, silently (no event fires). |
| onChange | (value?: unknown): void | value?: unknown | void | Commit the current value through `beforeChange`/validation/`change`. |
| onInput | (value?: unknown): void | value?: unknown | void | Report a live (uncommitted) value. |
FormControlDefinition
A custom control type's definition.
| Method | Signature | Parameters | Returns | Description |
|---|---|---|---|---|
| create | (el: HTMLElement, item: FormItemConfig, api: FormControlApi): void | el: HTMLElementitem: FormItemConfigapi: FormControlApi | void | Build the control's DOM into `el` and capture what the other hooks need. |
| getValue | (el: HTMLElement): unknown | el: HTMLElement | unknown | Read the control's current value from the DOM it built. |
| setValue | (el: HTMLElement, value: unknown): void | el: HTMLElementvalue: unknown | void | Write a committed value into the control's DOM. |
| validate | (value: unknown, item: FormItemConfig, el: HTMLElement): boolean | string | Promise<boolean | string> | value: unknownitem: FormItemConfigel: HTMLElement | boolean | string | Promise<boolean | string> | Refuse a commit: `true` accepts, `false`/a message refuses, a Promise is awaited. (optional) |
| destroy | (el: HTMLElement): void | el: HTMLElement | void | Tear the control down on `form.destroy()`. (optional) |
FormFieldAddon
A round icon button (or a value-following avatar) attached to the right of a field.
| Property | Type | Description |
|---|---|---|
| icon | string | Node | A glyph name from the grid's icon set, or a DOM node, drawn inside the button. (optional) |
| ariaLabel | string | The button's accessible name (required for an icon-only addon). (optional) |
| tooltip | string | The button's hover title; the `ariaLabel` when omitted. (optional) |
| href | string | A URL that turns the addon into a link instead of a button. (optional) |
| avatar | boolean | string | ((value: unknown, item: FormItemConfig) => string) | Draw a round avatar beside the field (instead of an icon button): an image URL, initials text, `true` to derive it from the selected option's `avatar`/`label`, or `(value, item) => string`. It follows the field's value. (optional) |
| Method | Signature | Parameters | Returns | Description |
|---|---|---|---|---|
| onClick | (value: unknown, item: FormItemConfig) => void | value: unknownitem: FormItemConfig | => void | Fired with the field's committed value and its item when the addon is clicked. (optional) |
FormPanelAction
A round icon button in a panel section's header.
| Property | Type | Description |
|---|---|---|
| icon | string | Node | A glyph name from the grid's icon set, or a DOM node, drawn inside the button. (optional) |
| ariaLabel | string | The button's accessible name (required for an icon-only action). (optional) |
| Method | Signature | Parameters | Returns | Description |
|---|---|---|---|---|
| onClick | () => void | - | => void | Fired when the action is clicked. (optional) |
FormPanelConfig
A panel section: its own surface holding child blocks, with a title, subtitle, divider and header actions.
| Property | Type | Description |
|---|---|---|
| title | string | The panel's heading, drawn with heading semantics. (optional) |
| subtitle | string | A muted line under the title. (optional) |
| actions | FormPanelAction[] | Round icon buttons in the panel's header. (optional) |
| collapsible | boolean | Draw a collapse/expand toggle in the header that hides and shows the panel body (default false). (optional) |
FormItemConfig
One form item: a control (`input`, `number`, `textarea`, `checkbox`, `button`, `combo`, `select`, `radiogroup`, `checkboxgroup`, `toggle`, `datepicker`, `daterange`, `file`, `richtext`, `rating`, `stage`, `chips`, `otp`, `color`, `listbox`, `speeddial`, `avatar`) or the read-only `text` display, with the per-item options.
| Property | Type | Description |
|---|---|---|
| props | Record<string, unknown> | A control's own settings bag. A custom control registered with `registerControl` reads its settings from `item.props` in `create()`; any top-level key the form does not recognise joins the same bag. A `toggle` item's `labelPosition` - `'inside'` (default), `'before'` or `'after'` - lives here, because the top-level `labelPosition` already means the item label's side. (optional) |
| type | string | The control type - a built-in or a type registered with `registerControl`. Defaults to `input`. (optional) |
| name | string | The item's name, for `getItem(name)` and `getValue()`/`setValue()`. (optional) |
| label | string | The label text, associated to the control for screen readers. (optional) |
| labelPosition | FormLabelPosition 'top' | 'left' | 'hidden' | Where the label sits: `top` (default), `left`, or `hidden` (visually hidden but still the accessible name). (optional) |
| hiddenLabel | boolean | Keep the label as the control's accessible name without drawing it - a visually hidden `<label>` linked to the control - so the field takes the full row, whatever `labelPosition` says. (optional) |
| labelWidth | number | string | The label column width when `labelPosition` is `left`. (optional) |
| controlMinWidth | number | string | When `labelPosition` is `left`: the width, in pixels or a CSS length, below which the control is too narrow and the label switches to the top instead - measured as this item's own width minus the label column (`labelWidth`, or the label's natural width when unset) minus the gap between them. Inherited like `labelPosition` and `labelWidth` from a fieldset, a container or the form; an item's own value wins. Re-measured per item with a `ResizeObserver` (a shell splitter or a drawer resizing the host counts, not only the window), with a few pixels of hysteresis so a width sitting on the threshold never flickers. Unset, nothing switches. A checkbox or toggle item ignores this - its label sits beside it by design. (optional) |
| width | number | string | The item's width: a pixel number, a CSS length string such as `'12em'`, a percentage string such as `'33.3%'`, or `'content'` to size the item to its control's own content (the default for buttons and toggles) rather than filling its row. In a `cols` row a percentage is a share of the row's width *after* the gaps between its items, so items totalling 100% lay out on one line with the gaps intact and an unsized neighbour takes the remaining space; a px/rem width is a fixed flex basis. (optional) |
| height | number | string | The item's height, for every item type: a pixel number, a CSS length string, or `'content'` to size the control to its own content. A `listbox` item's `height` instead sets its viewport height in pixels, overriding `rows`; on a vertical `slider` item it sets the track's length (default 160). (optional) |
| padding | number | string | The space between the item's cell and its control - a pixel number or a CSS length - on items and on `rows`/`cols`/`items`/`fieldset`/`panel` containers. (optional) |
| placeholder | string | Placeholder text for a text-like control. (optional) |
| autocomplete | string | The native `autocomplete` token passed straight to an `input`, `number`, `combo`, `select`, `textarea` or `datepicker` item's element, winning over the defaults: a control that draws its own list defaults to `'off'` and a password `input` to `'new-password'`; `'on'` restores the browser's own behaviour, `'url'` or `'one-time-code'` name the kind of entry. (optional) |
| helpMessage | string | Help text shown under the control. (optional) |
| hidden | boolean | Start hidden. (optional) |
| disabled | boolean | Start disabled. (optional) |
| readOnly | boolean | Start read-only. (optional) |
| tooltip | string | boolean | Help text a "?" trigger after the label reveals on hover, focus, Enter and tap, linked to the control by `aria-describedby` - or, for a `slider` item, whether it shows the thumb's live value while dragging or focused (default `true`;. The two never collide: the "?" trigger only ever draws for a string value, so a slider's boolean never raises it. (optional) |
| lockIcon | boolean | Show the read-only lock inside a read-only field's right edge (default true); `false` hides it. (optional) |
| addons | FormFieldAddon[] | Round icon buttons (and avatar addons) attached to the right of the field, disabled with it. (optional) |
| value | unknown | The initial value. (optional) |
| required | boolean | An empty value fails validation. (optional) |
| requiredHint | boolean | string | The marker a required field with no visible label shows on its placeholder: `true` (the default) appends `" *"`, a string resolves through the message catalogue, and `false` shows nothing. (optional) |
| validation | FormValidationRule | A further rule: a built-in name, a RegExp, or a function `(value, item) => boolean | string | void`. (optional) |
| errorMessage | string | The text shown when the item fails, overriding the rule's default. (optional) |
| successMessage | string | The text shown when the item passes validation (after it has been validated). (optional) |
| preMessage | string | The hint shown before the first validation verdict. (optional) |
| validationMode | FormValidationMode 'change' | 'blur' | 'submit' | When the item re-checks itself: `change`, `blur`, or `submit` (default, on `validate()` only). (optional) |
| subtype | FormInputSubtype 'text' | 'email' | 'password' | 'url' | The native input subtype for an `input` item. (optional) |
| reveal | boolean | Show the reveal button inside a `password` input (default true); `false` turns it off. (optional) |
| length | number | The box count of an `otp` item (default 6). (optional) |
| mode | 'numeric' | 'alphanumeric' | FormPickerMode | FormColorMode | 'linear' | 'radial' | 'horizontal' | 'vertical' | The `otp` characters - `numeric` (default) or `alphanumeric` - the `datepicker` mode: `date`, `date-time` or `time` - the `color` item's opening popover view - the `speeddial` item's menu shape: `linear` (default) or `radial` - or a `slider` item's track direction: `horizontal` (default) or `vertical`. (optional) |
| mask | boolean | InputMaskPattern | On an `otp` item, `true` hides each box's glyph with the password disc. On an `input` item, a fixed input pattern the field is held to as it is typed: `9` is a digit, `A` a letter, `*` a letter or a digit, every other character a literal inserted as the caret reaches it, such as `'AA-9999'`. The value is the text as shown, literals included, and a partly filled value fails validation. The placeholder shows the pattern with `_` for slots. Not the display `mask` of a grid column format. (optional) |
| step | number | The number step, for a `number` item. (optional) |
| format | NumberFormat | string | The number format a `number` item displays when blurred, the same shape a grid number column takes - a `NumberFormat` spec (which may name `pattern`) or a bare pattern string like `'#,##0.00'`,. The value stays a number; only the display is formatted. (optional) |
| spinner | boolean | Draw two step buttons beside a `number` item's field (default false); the native spinner never appears either way. (optional) |
| system | string | Makes a `number` item a unit-aware field: which unit system it measures in - `'data'`, `'length'`, `'mass'`, `'pressure'` and the rest, plus anything registered with `registerUnitSystem`. (optional) |
| unit | string | The unit the `number` item's stored values are in, e.g. `'bar'`; defaults to the system's base unit. (optional) |
| binary | boolean | Use the power-of-two ladder for a `data` unit field. (optional) |
| decimals | number | Fixed decimal places for the unit display, setting both the minimum and maximum. (optional) |
| minDecimals | number | The fewest decimal places in a unit display. (optional) |
| maxDecimals | number | The most decimal places in a unit display. (optional) |
| display | string | Which unit the field renders in: a symbol from the system, or `'auto'` to pick the most readable rung. (optional) |
| group | boolean | Whether to group thousands in a unit display. (optional) |
| space | string | What sits between the number and the unit symbol. (optional) |
| placement | 'suffix' | 'prefix' | Whether the unit symbol goes after the number or before it. (optional) |
| compound | string[] | Render one stored number across an ordered subset of the system's units, e.g. `['ft', 'in']`. (optional) |
| significantFigures | number | Round the unit display to this many significant figures before the rung is chosen. (optional) |
| nullDisplay | string | Text for a null or non-finite unit value, empty by default. (optional) |
| scale | string | Makes a `number` item a temperature field, in this scale (`'C'`, `'F'`, `'K'` or `'R'`); conversion is affine, so `212 °F` into a Celsius field stores `100`. (optional) |
| unitPicker | boolean | Show a compact unit selector inside the field that changes only the display unit, never the committed value. (optional) |
| macFormat | 'colon' | 'colon-upper' | 'cisco' | 'hyphen' | The display spelling of a `mac` item: `'colon'` (default), `'colon-upper'`, `'cisco'` or `'hyphen'` - the committed value is always the lowercase colon form. A `mac`/`ipv4`/`ipv6`/`cidr`/`vlan` item parses, validates and normalises through the grid data type's own functions: it accepts every spelling the type parses while typing or pasting, and on commit (blur, Enter or submit) reformats to the canonical text, which becomes the item's value. A column-bound item (`bind.js`) takes these options from the column automatically. (optional) |
| vlanSingle | boolean | A `vlan` item that holds one ID only; `true` refuses a list or a range (`10,20-30`) with a message. (optional) |
| prefix | number | The prefix a `cidr` item gives a bare address with no `/n` of its own, default 32 - the same default the grid's `ipaddress` editor applies. (optional) |
| cidrNetwork | boolean | A `cidr` item that stores the network address rather than the address as typed: `10.1.2.3/24` commits as `10.1.2.0/24`, its host bits cleared. `false` by default. A column-bound item (`bind.js`) takes this from `column.typeOptions.cidrNetwork` automatically. (optional) |
| min | number | string | The minimum - a number for `number`, a multi `chips`/`listbox` selection count, an ISO string for `datepicker` and `daterange`. (optional) |
| max | number | string | The maximum - a number for `number`, a multi `chips`/`listbox` selection count, an ISO string for `datepicker` and `daterange`. (optional) |
| rows | number | The visible rows, for a `textarea` item, or a `listbox` item's viewport height in option rows (default 8). (optional) |
| options | (string | FormOption | FormOptionGroup | FormChipOption | FormToggleGroupOption)[] | The choices of a `select`, `radiogroup`, `checkboxgroup` or `listbox` item: strings, `{ value, label }` objects, or `{ label, options }` groups; or the selectable options of a `chips` item (`{ value, label, icon?, disabled? }` entries). (optional) |
| selection | 'single' | 'multiple' | 'checkbox' | A `listbox` item's selection mode: `'single'` (default), `'multiple'` (Ctrl/Shift and touch-tap selection) or `'checkbox'` (a box per row plus a select-all row). (optional) |
| filter | boolean | Add a search box to a `listbox` item that narrows its rows by label and description, without dropping an already-selected option it hides. (optional) |
| groupBy | boolean | Bucket a `listbox` item's options by their `group` field under sticky headers. (optional) |
| sort | 'asc' | 'desc' | false | Order a `listbox` item's options by label: `'asc'`, `'desc'`, or `false` (default) to keep the configured order. (optional) |
| reorder | boolean | Let a `listbox` item's rows be moved by drag, by Move up/down toolbar buttons and by Alt+Arrow; the committed value becomes the full, reordered item array. (optional) |
| valueAs | 'order' | With `reorder: true`, `'order'` makes a `listbox` item's committed value the ordered array of option values in every selection mode - the shape an editable ordered list wants even while `selection` is `'single'`, where the value would otherwise be just the one selected item. (optional) |
| connect | string | The name of another `listbox` item this one exchanges items with via drag and the Move selected/Move all toolbar buttons; each side's value is the items it currently holds. (optional) |
| dragHandle | boolean | Draw a drag grip on a `listbox` item's rows and drag only from it (a plain pointer drag, not native HTML5 drag-and-drop), and size rows to their content instead of a fixed height. (optional) |
| orientation | 'vertical' | 'horizontal' | Lay a `radiogroup` or `checkboxgroup`'s options out vertically (the default) or on one wrapping horizontal line. (optional) |
| columns | number | Lay a `radiogroup` or `checkboxgroup`'s options out in this many columns, read across then down. (optional) |
| native | boolean | Keep the native `<select>` element rather than the rendered trigger and listbox. (optional) |
| locale | string | The locale the `datepicker` formats month/weekday names in, and the `number` item's format and typed-input separators resolve against; the viewer's when omitted. (optional) |
| timeZone | string | The timeZone the `datepicker` reads a Date/epoch value in, like the grid's date columns. (optional) |
| granularity | FormDateRangeGranularity 'day' | 'month' | The `daterange` granularity: `day` (default) or `month` - a year-month range picker of two years of twelve month cells. (optional) |
| presets | false | FormDateRangePreset[] | The `daterange` presets drawn on the left of the popup: an explicit list, `false` to hide, or omitted for the defaults (today, yesterday, last 7 days, last 30 days, this month, last month). (optional) |
| minSpan | number | The `daterange` fewest days (or months in month mode) a range may span. (optional) |
| maxSpan | number | The `daterange` most days (or months in month mode) a range may span. (optional) |
| disabledDates | string[] | ((iso: string) => boolean) | The `datepicker`/`daterange` days (or `daterange` months) that may not be picked: an ISO string list or a function `(iso) => boolean`,. (optional) |
| weekNumbers | boolean | Add an ISO week-number column to the `daterange` grid (default false). (optional) |
| firstDay | number | The `daterange` first weekday column (0 = Sunday); the locale's week info when omitted. (optional) |
| applyButton | boolean | Show Apply/Cancel on the `daterange` popup so nothing commits until Apply (default true); `false` commits on the second pick. (optional) |
| text | string | Shorthand for a read-only `text` display. (optional) |
| visibleWhen | FormRule | A rule that hides the item when it evaluates false. (optional) |
| readOnlyWhen | FormRule | A rule that makes the item read-only when it evaluates true. (optional) |
| requiredWhen | FormRule | A rule that makes the item required when it evaluates true. (optional) |
| css | Record<string, string | number> | string | Extra CSS on the item wrapper. (optional) |
| accept | string[] | Extensions or MIME patterns a `file` item accepts (empty = anything), or the MIME patterns an `avatar` item's chooser accepts (default `['image/*']`). (optional) |
| maxSize | number | The maximum file size in bytes a `file` item admits, or an `avatar` item's chosen picture refuses. (optional) |
| maxFiles | number | The maximum number of files a `file` item admits. (optional) |
| multiple | boolean | Allow picking several files at once for a `file` item (default true), toggling several options for a `chips` item (default false, single-select), or a multi-select `select` whose committed value is an array. (optional) |
| multiselect | boolean | Toggle each `togglegroup` option independently; the default false keeps exactly one option pressed. (optional) |
| gap | number | The pixel space between `togglegroup` buttons (default 0). (optional) |
| full | boolean | Stretch a `togglegroup` to its item's full width. (optional) |
| dropText | string | Drop-zone text for a `file` item. (optional) |
| hint | string | A hint line under the drop zone of a `file` item. (optional) |
| browseText | string | Replaces the browse link's word in a `file` item's drop area and its aria-label. (optional) |
| circle | boolean | Round an `avatar` item's picture into a circle; otherwise it keeps the control's own rounded-square radius. (optional) |
| alt | string | The accessible `alt` text on an `avatar` item's picture. (optional) |
| preview | string | An image URL an `avatar` item shows while it has no value, ahead of `icon` and the `placeholder` text. (optional) |
| removeIcon | boolean | Show an `avatar` item's clear control once it has a value, setting it back to `null` (default true). (optional) |
| toolbar | string | string[] | The toolbar for a `richtext` item: a preset (`basic`/`html`/`rich`) or an item-name array. (optional) |
| minHeight | number | The minimum editor height in pixels for a `richtext` item. (optional) |
| maxHeight | number | The maximum editor height in pixels for a `richtext` item. (optional) |
| linkTarget | string | The link target for links created in a `richtext` item. (optional) |
| colors | string[] | The colour swatches for a `richtext` item's text-colour popover. (optional) |
| headings | Array<[string, string]> | The `[tag, label]` heading options for a `richtext` item. (optional) |
| allowedTags | Record<string, string[]> | An override whitelist of tags/attributes for a `richtext` item. It can only narrow the default whitelist: event handlers, `srcdoc`, `id`/`name`, the forbidden tags and `javascript:`/`vbscript:`/`data:` URLs are always stripped. (optional) |
| maxImageSize | number | The maximum image size in bytes a `richtext` item inserts. (optional) |
| sanitizePaste | boolean | Sanitise pasted HTML in a `richtext` item (default true). (optional) |
| allowHalf | boolean | Allow half steps for a `rating` item. (optional) |
| allowClear | boolean | Allow a second click to clear a `rating` item back to zero. (optional) |
| icon | string | Element | false | The icon of a `button` - a name from the grid's icon set, an image URL or data: URI, or an element - the glyph name of a `rating` item (`star` or `heart`), the drop-area icon of a `file` item - a glyph name from the file module's sprite set, an SVG markup string, an element, or `false` for none - the glyph name a `color` item's trailing toggle draws instead of its default chevron - a `time` item's toggle glyph, default the grid's clock - or an `avatar` item's fallback image URL (or element), shown with no value and no `preview`. (optional) |
| icons | { filled?: string; empty?: string } | The filled and empty glyph names for a `rating` item. (optional) |
| labels | string[] | One label per rating icon, for the `title` and the announced value. (optional) |
| showValue | boolean | Show the numeric value beside a `rating` item. (optional) |
| size | 'sm' | 'md' | 'lg' | 'small' | 'medium' | 'default' | 'large' | number | The size of a `rating` item or `button`: `sm`, `md` (default) or `lg` - a `toggle` item's `small`, `default` or `large` - or an `avatar` item's picture: `small`, `medium` (default, 64px), `large`, or a pixel number. (optional) |
| iconPosition | 'start' | 'end' | Where a `button`'s icon sits: `start` (default) or `end`. (optional) |
| variant | FormButtonVariant | 'round' | 'square' | 'slim' | A `button`'s visual weight: theme-token colours, light and dark. Defaults to `secondary` - or a `toggle` item's track shape: `round` (default), `square` or `slim`. (optional) |
| onLabel | string | A `toggle` item's ON-state label text, drawn inside the track or beside it per `props.labelPosition`. (optional) |
| offLabel | string | A `toggle` item's OFF-state label text. (optional) |
| fullWidth | boolean | Make a `button` span the full form width. (optional) |
| textTransform | 'none' | 'uppercase' | A `button`'s text case: `none` (default) or `uppercase`. (optional) |
| buttonType | 'button' | 'submit' | 'reset' | A `button`'s native type: `button`, `submit` (validates first, then fires `submit` with the values only when valid) or `reset` (clears the form). (optional) |
| loading | boolean | A `button`'s loading state: swaps its icon for a spinner, keeps the width, sets `aria-busy` and ignores clicks. Toggle live with `item.setLoading(bool)`. (optional) |
| href | string | A URL that turns a `button` into a link styled as a button. (optional) |
| ariaLabel | string | The accessible name of an icon-only `button` (icon with no label, required). (optional) |
| toggle | boolean | Make a `button` a two-state toggle: it flips `aria-pressed` and fires `change` with the new boolean state, and reads as pressed. Starts pressed when `value` is `true`. (optional) |
| focusableWhenDisabled | boolean | Keep a disabled `button` focusable and in the tab order: it reads `aria-disabled` instead of being natively disabled, and still ignores clicks. (optional) |
| align | FormButtonsAlign 'start' | 'end' | 'center' | 'stretch' | 'space-between' | How a `buttons` row lays its children out along the width: `start` (default), `end`, `center`, `stretch` or `space-between`. (optional) |
| items | FormItemConfig[] | The buttons of a `buttons` row; each child takes the same options as a `button` item. (optional) |
| stages | string[] | The step labels of a `stage` item, in order. (optional) |
| current | number | string | The initial selection of a `stage` item: an index or a label. (optional) |
| completed | number | string | The last done step of a `stage` item: an index or a label. (optional) |
| clickable | boolean | Whether clicking a `stage` step selects it (default true). (optional) |
| showIcons | boolean | Whether a `stage` item shows its check glyphs (default true). (optional) |
| allowEmpty | boolean | Allow a single-mode `chips` item to be left with nothing selected. (optional) |
| wrap | boolean | Wrap a `chips` item's pills onto several lines (default), or keep them on one scrolling row when false. (optional) |
| palette | string[][] | The rows of preset swatches a `color` item's palette view shows, replacing the shared default (ten hues in five shades). (optional) |
| grayShades | boolean | Show a `color` item's grey row under its palette (default true); `false` drops it. (optional) |
| customColors | string[] | A `color` item's custom-colours row to start with - extended, newest first and deduplicated to at most ten, by every colour picked in the picker view. (optional) |
| pickerOnly | boolean | Remove a `color` item's palette view, leaving only the picker. (optional) |
| editable | boolean | Let a `color` item's text part be typed into (default true); `false` makes it read-only, so only the popover sets the value - or a `time` item's field text (default false there, the popup sets it; `true` accepts typed `HH:MM`/`hh:MM AM`, committed on blur or Enter). (optional) |
| clearable | boolean | Show a clear control: on a `color` item it sets the value to `null`; on a `daterange` item a null/null pair; on a single-select `combo` it empties the value to `null`, and on a `select` item to its empty value `''`, with one `change`; on a `datepicker` item it empties the value to `null`, shown only while a value is held and not read only. An optional single-select combo is also emptied when its text is cleared and Enter is pressed or focus leaves. (optional) |
| timeFormat | 12 | 24 | The clock format of a `time` item: `24` (default, `HH:MM`) or `12` (`hh:MM` with an AM/PM segment in the popup and display). (optional) |
| valueFormat | 'string' | 'object' | How a `time` item stores its value: `'string'` (default, `'HH:MM'` or `'hh:MM AM'` in 12-hour) or `'object'` (`{ hour, minute, AM? }`). (optional) |
| controls | boolean | Add Close and Save buttons to a `time` item's popup so nothing commits until Save and Close discards (default false: the popup commits as the clock changes). (optional) |
| range | boolean | Make a `slider` item a two-thumb range: the committed value is then `[low, high]` and the thumbs cannot cross. (optional) |
| tick | number | Draw a `slider` tick mark every this many units; omitted, no tick marks are drawn. (optional) |
| majorTick | number | Draw a labelled, taller `slider` tick every this many units, formatted by `tickTemplate`; omitted, no major ticks are drawn. (optional) |
| inverse | boolean | Reverse which end of a `slider` track holds the minimum. (optional) |
| [key: string] | unknown | Extra per-control options, kept for later controls. |
| Method | Signature | Parameters | Returns | Description |
|---|---|---|---|---|
| render | (option: FormOption) => Node | string | option: FormOption | => Node | string | A custom row renderer for a `listbox`/`select`/`combo` option, returning a DOM node or an HTML string (sanitised before insertion). (optional) |
| upload | ((file: File, opts: { onProgress: (pct: number) => void; signal?: AbortSignal }) => void | Promise<void>) | FormAvatarUploadConfig | (file: File, opts: { onProgress: (pct: number) => void; signal?: AbortSignal }) => void | Promise<void> | | FormAvatarUploadConfig | The host upload callback for a `file` item (`(file, { onProgress, signal }) => void | Promise<void>`), or an `avatar` item's own upload config, posted as multipart form data. (optional) |
| onImage | (file: File) => Promise<string> | string | file: File | => Promise<string> | string | A host callback returning a source URL for an inserted image. (optional) |
| tickTemplate | (value: number) => string | value: number | => string | Format a `slider` tick's label and a thumb's `aria-valuetext`; the plain number when omitted. (optional) |
FormAvatarValue
The committed value of an `avatar` item: the picture, and - while a freshly chosen file is pending or uploading - its own file and progress.
| Property | Type | Description |
|---|---|---|
| src | string | The picture's source: a URL, or (before any upload completes) the data URL of a freshly chosen file. (optional) |
| file | File | The chosen file, present only while `status` is `'pending'`, `'uploading'` or `'failed'` (not yet, or not successfully, uploaded). (optional) |
| name | string | The chosen file's name. (optional) |
| size | number | The chosen file's size in bytes. (optional) |
| progress | number | The upload progress, 0 to 100, present while `status` is `'uploading'`. (optional) |
| status | 'pending' | 'uploading' | 'done' | 'failed' | The upload status, present only when the item has an `upload` config. (optional) |
| message | string | The failure message, present only while `status` is `'failed'`. (optional) |
| id | string | number | The response id, when `upload.updateFromResponse` read one back. (optional) |
FormAvatarUploadConfig
An `avatar` item's own upload config: posts the chosen file as multipart form data the moment it is admitted.
| Property | Type | Description |
|---|---|---|
| target | string | The URL the file is POSTed to. |
| fieldName | string | The multipart field name the file is sent under. Default `'file'`. (optional) |
| params | Record<string, string | number | boolean> | Extra form fields sent alongside the file. (optional) |
| headers | Record<string, string> | Extra request headers. (optional) |
| autosend | boolean | Upload the moment the file is admitted (default true); `false` leaves the picture `'pending'` and posts nothing. (optional) |
| updateFromResponse | boolean | Read `src`/`id` back from the JSON response once the upload completes (default true). (optional) |
AvatarItemConfig
The `type: 'avatar'` item options, documented here as their own shape: a profile picture with a preview, sizes, a placeholder, a remove control and an optional upload. Used inside a form the same way as every other item - `{ type: 'avatar', name, ...these options }` - with these fields typed on {@link FormItemConfig} itself (`value`, `size`, `icon`, `accept`, `maxSize`, `upload` are shared with other control types there; see each one's own doc for the `avatar` reading).
| Property | Type | Description |
|---|---|---|
| value | FormAvatarValue | null | The committed picture, or `null`/absent for none. (optional) |
| alt | string | The accessible `alt` text on the picture. (optional) |
| size | 'small' | 'medium' | 'large' | number | The display size: `small`, `medium` (default, 64px), `large`, or a pixel number. (optional) |
| circle | boolean | Round the picture into a circle (default false, a rounded square). (optional) |
| preview | string | An image URL shown while there is no value, ahead of `icon` and `placeholder`. (optional) |
| icon | string | Element | false | A fallback image URL (or element) shown while there is no value and no `preview`. (optional) |
| placeholder | string | Text shown while there is no value, no `preview` and no `icon`; defaults to the catalogue's "Add a photo". (optional) |
| accept | string[] | MIME patterns the file chooser accepts. Default `['image/*']`. (optional) |
| maxSize | number | The largest file size accepted, in bytes; a larger pick is refused with a message `validate()` surfaces. (optional) |
| removeIcon | boolean | Show the clear control once a picture is set (default true). (optional) |
| upload | FormAvatarUploadConfig | Upload the chosen file as multipart form data. (optional) |
| required | boolean | An empty picture fails validation. (optional) |
FormBlock
One block of a form layout: a container (`rows`/`cols`/`items`/`container`), a `fieldset`, a `spacer`, a `separator`, a panel section, or an item.
| Property | Type | Description |
|---|---|---|
| rows | FormBlock[] | A vertical stack of child blocks. (optional) |
| cols | FormBlock[] | A horizontal stack of child blocks. (optional) |
| items | FormItemConfig[] | A side-by-side run of form items. (optional) |
| spacing | number | string | The vertical gap between this container's or fieldset's own items - a px number or a CSS length, overriding the form's `spacing` for those items only. (optional) |
| wrap | boolean | On a `cols` block, resolve each item's percentage `width` against its own rendered line's gaps instead of the whole row's: a `100%` item fills its line alone, and a `50%`/`50%` pair shares one gap and sits side by side filling it exactly, instead of the pair's widths being shrunk by every gap in the row. Items that do not fit on a line wrap to the next one, as they already do; hiding an item frees its line slot (later items shift up and may join an earlier line), and showing it again restores the layout. The per-line pass measures a nested block's own `width` the same as an item's. Ignored on any other axis. Default `false`. (optional) |
| gap | number | string | On a `cols` block, the gap between items - a px number or a CSS length, both the rendered gap and the `wrap` per-line width maths. Sets both `columnGap` and `rowGap` unless one of them overrides it. Ignored on any other axis. Default `--lattice-space` (the theme's own gap). (optional) |
| columnGap | number | string | On a `cols` block, the gap between items on the same line - a px number or a CSS length, overriding `gap` for this axis only. Ignored on any other axis. (optional) |
| rowGap | number | string | On a `cols` block, the gap between wrapped lines - a px number or a CSS length, overriding `gap` for this axis only. Ignored on any other axis. (optional) |
| type | string | The control type, or `spacer`/`separator`. Defaults to `input`. (optional) |
| fieldset | string | FormBlock | A fieldset: `'Legend'` or `{ legend, rows, cols, items }`. (optional) |
| container | FormBlock | An explicit container, `{ rows | cols | items }`. (optional) |
| panel | FormPanelConfig | A panel section: its own surface holding this block's `rows`/`cols`/`items` children, with a title, subtitle, divider and header actions. (optional) |
| spacer | boolean | A flexible spacer. (optional) |
| separator | boolean | A horizontal rule; with `label`, the rule is split around the centred label. (optional) |
| legend | string | The fieldset legend, when written as a sibling of `fieldset`. (optional) |
| name | string | The item's name, or a fieldset's name - either way, what `getItem(name)` reads. (optional) |
| label | string | The item's label text, or a `separator`'s centred label (a literal or a catalogue key). (optional) |
| labelPosition | FormLabelPosition 'top' | 'left' | 'hidden' | Where the label sits: `top` (default), `left`, or `hidden`. On a container or fieldset this is the default its items inherit. (optional) |
| labelWidth | number | string | The label column width when `labelPosition` is `left`; on a container or fieldset this is the default its items inherit. (optional) |
| controlMinWidth | number | string | The width below which a `left` label switches to the top instead; on a container or fieldset this is the default its items inherit. See {@link FormItemConfig.controlMinWidth}. (optional) |
| width | number | string | The item's width; on a spacer, container, fieldset or panel block nested in a `cols` row, its own share of that row, applied exactly as an item's `width` is, with and without `wrap`,. (optional) |
| placeholder | string | Placeholder text. (optional) |
| helpMessage | string | Help text shown under the control. (optional) |
| hidden | boolean | Start hidden. (optional) |
| disabled | boolean | Start disabled. (optional) |
| readOnly | boolean | Start read-only. (optional) |
| value | unknown | The initial value. (optional) |
| subtype | FormInputSubtype 'text' | 'email' | 'password' | 'url' | The native input subtype. (optional) |
| visibleWhen | FormRule | A rule that hides the item when it evaluates false. (optional) |
| readOnlyWhen | FormRule | A rule that makes the item read-only when it evaluates true. (optional) |
| requiredWhen | FormRule | A rule that makes the item required when it evaluates true. (optional) |
| css | Record<string, string | number> | string | Extra CSS on the block. (optional) |
| [key: string] | unknown | Extra options. |
FormContainerItemConfig
The `type: 'container'` item: a content item, not a layout block - a place in the form that shows host HTML or hosts another Lattice view (a grid, chart, kanban, calendar, gantt or nested form), attached after creation through `form.getItem(name).attach()`. Carries no `value`: it is excluded from `getValue()`, `setValue()` and validation. A block that also names `rows`/`cols`/`items` stays the layout container regardless of `type`.
| Property | Type | Description |
|---|---|---|
| name | string | The item's name, for `getItem(name)`. (optional) |
| html | string | HTMLElement | Host content rendered inside the region: a string has every `<script>` element, `on*` attribute and `javascript:`-scheme value stripped - everything else, inline styles included, is kept; an `HTMLElement` is appended as is, with no sanitising. (optional) |
| label | string | The label text, set as the region's `aria-label` (and, like any item, drawn as an associated `<label>` beside it). (optional) |
| labelPosition | FormLabelPosition 'top' | 'left' | 'hidden' | Where the label sits: `top` (default), `left`, or `hidden`. (optional) |
| labelWidth | number | string | The label column width when `labelPosition` is `left`. (optional) |
| width | number | string | The item's width, applied once to its wrapper slot like any other item's: a pixel number, a CSS length, or a percentage such as `'40%'`, a share of the row's width after the gaps between its items. The region itself always fills that slot - unset (the default) gives it its default share of the row, the same as any other item. (optional) |
| height | number | string | The region's own height: a pixel number, a CSS length, or `'content'` to size to its own content (the default). Unlike `width`, this sizes the region directly, not the wrapper slot; a container with an explicit height still shrinks like its siblings when its column runs out of room. (optional) |
| padding | number | string | Inner padding: a pixel number or a CSS length. (optional) |
| css | Record<string, string | number> | string | Extra CSS on the item wrapper. (optional) |
| hidden | boolean | Start hidden. (optional) |
| disabled | boolean | Start disabled: the region carries `aria-disabled` and `inert`. (optional) |
| visibleWhen | FormRule | A rule that hides the item when it evaluates false. (optional) |
GridItemField
One mapped cell of a `grid` item: the row (by its `rowKey` value) and the column (by its field) whose value becomes a top-level property of the form value.
| Property | Type | Description |
|---|---|---|
| row | string | number | The `rowKey` value of the mapped row. |
| col | string | The field of the mapped column. |
GridItemTotals
The display-only totals of a `grid` item. A totals row is pinned beneath the body and a totals column is computed from each row; the grid does not store either, and neither is ever part of the form value.
| Property | Type | Description |
|---|---|---|
| row | boolean | GridItemTotalFn | { /** The function for every listed column (default `'sum'`). */ fn?: GridItemTotalFn; /** The columns to total: an array of fields, or a map of field to its function. Defaults to every number-typed column. */ columns?: string[] | Record<string, GridItemTotalFn>; /** The label shown on the row (default: the catalogue's "Total", localised). */ label?: string; /** The field that carries the label (default: the first column that is not totalled). */ labelColumn?: string; } | A totals row. `true` sums the number columns; a name or function applies to them; an object picks the columns (an array of fields, or a map of field to function) and the label. (optional) |
| column | boolean | GridItemTotalFn | { /** The function over the row's values (default `'sum'`). */ fn?: GridItemTotalFn; /** The fields to total across. Defaults to every number-typed column. */ columns?: string[]; /** The column heading (default: the catalogue's "Total", localised). */ title?: string; /** Extra column options for the totals column (`type`, `format`, `layout`, …). */ column?: object; } | A totals column, computed per row. `true` sums the number columns; a name or function applies to them; an object picks the columns, the heading and any extra column options (a `type`, a `format`, a `width`). (optional) |
GridItemConfig
The `type: 'grid'` item: a live, editable Lattice grid as a form field. Its rows are the item's value, `fields` maps single cells to further top-level form properties, and cell edits, row additions and row removals go through the form's `beforeChange`, `change`, `validate()`, reset and dirty tracking like any field. The grid factory is injected - `createGrid` on the item, or on the form config - so the form bundles no grid core.
| Property | Type | Description |
|---|---|---|
| name | string | The item's name, the key of its rows in `getValue()`. (optional) |
| columns | Array<string | object> | The grid's columns - every column option the grid accepts (`field`, `title`, `type`, `edit`, `validation`, …). The editable ones need `edit: true`. |
| rowKey | string | The field whose value identifies a row (default `'id'`). It is also how `fields` names a row. (optional) |
| value | Array<object | unknown[]> | The initial rows: objects, or arrays in column order. (optional) |
| valueAs | 'rows' | 'arrays' | The shape of the rows in the form value: `'rows'` (objects, default) or `'arrays'` (arrays in column order). (optional) |
| valueRows | boolean | `false` drops the rows array from `getValue()` and keeps only the mapped cells. Default `true`. (optional) |
| fields | Record<string, GridItemField> | Cells mapped to top-level form properties, by property name. Each is read and written like any field, fires its own `change`, and takes part in dirty tracking and data binding. (optional) |
| rowControls | boolean | Adds keyboard-operable add-row and delete-row buttons (off by default). Delete acts on the selected rows, else the row holding the focused cell. (optional) |
| newRow | object | ((rows: object[]) => object) | A new row's defaults, or a function `(rows) => row`, for the add-row control and `addRow()`. The `rowKey` is filled in when absent or taken. (optional) |
| totals | GridItemTotals | The display-only totals row and/or column. (optional) |
| gridOptions | object | Extra grid options laid under the item's own (`rowKey`, `columns`, `rows` and `density` always win). (optional) |
| height | number | string | The grid's height: a pixel number or a CSS length (default 240). (optional) |
| width | number | string | The item's width: a pixel number, a CSS length or a percentage. (optional) |
| label | string | The label text, set as the group's `aria-label` and drawn as the item's label. (optional) |
| labelPosition | FormLabelPosition 'top' | 'left' | 'hidden' | Where the label sits: `top` (default), `left`, or `hidden`. (optional) |
| labelWidth | number | string | The label column width when `labelPosition` is `left`. (optional) |
| helpMessage | string | Help text shown under the grid. (optional) |
| required | boolean | At least one row is required. (optional) |
| requiredWhen | FormRule | A rule that makes the item required when it evaluates true. (optional) |
| validationMode | FormValidationMode 'change' | 'blur' | 'submit' | When the item is validated: `change`, `blur` or `submit` (default). (optional) |
| hidden | boolean | Start hidden. (optional) |
| disabled | boolean | Start disabled: the grid is inert and excluded from validation. (optional) |
| readOnly | boolean | Start read-only: cells cannot be edited and the row controls are off. (optional) |
| visibleWhen | FormRule | A rule that hides the item when it evaluates false. (optional) |
| readOnlyWhen | FormRule | A rule that makes the item read-only when it evaluates true. (optional) |
| css | Record<string, string | number> | string | Extra CSS on the item wrapper. (optional) |
| Method | Signature | Parameters | Returns | Description |
|---|---|---|---|---|
| createGrid | (el: HTMLElement, config: object) => Grid | el: HTMLElementconfig: object | => Grid | The grid factory (`createGrid`); defaults to the form config's `createGrid`. (optional) |
FormBindGridConfig
A binding to a grid row: `{ grid, rowKey }`.
| Property | Type | Description |
|---|---|---|
| grid | Grid | The grid whose row provides the record. |
| rowKey | string | number | The row key of the bound row. |
FormBindRouterConfig
A binding to a data-router record: `{ router, route, key, onSave? }`,.
| Property | Type | Description |
|---|---|---|
| router | import('lattice-grid/modules/data-router').DataRouter | The data router whose route's keyed diffs carry the record. |
| route | import('lattice-grid/modules/data-router').RoutePredicate | The route (predicate, partition value or label) to subscribe to. |
| key | string | number | The row key of the bound record. |
| onSave | (changes: Record<string, unknown>, record: import('lattice-grid/modules/data-router').RouterRecord) => void | Promise<void> | Called after `save()` writes the record to the router, with the dirty changes and the full updated record. May be async: a rejection (or a thrown error) reverts the router record to its previous values and keeps the form dirty. (optional) |
FormConfig
The form config: the layout, the density, the binding, and the message catalogue.
| Property | Type | Description |
|---|---|---|
| rows | FormBlock[] | The top-level blocks, stacked vertically (the form reads top to bottom). (optional) |
| cols | FormBlock[] | The top-level blocks, stacked horizontally (used when `rows` is absent). (optional) |
| density | FormDensity 'compact' | 'standard' | 'comfortable' | The density level, `compact`/`standard`/`comfortable`. Default `standard`. (optional) |
| spacing | number | string | The vertical gap between items - a px number or a CSS length. Defaults to the density's own gap; a CSS theme may set `--lattice-form-item-gap` instead. (optional) |
| labelGap | number | string | The gap between an item's label and its field - a px number or a CSS length. Defaults to half the density's space; a CSS theme may set `--lattice-form-label-gap` instead. (optional) |
| labelPosition | FormLabelPosition 'top' | 'left' | 'hidden' | The default label position every item inherits: `top`, `left` or `hidden`. An item's own `labelPosition` wins. (optional) |
| labelWidth | number | string | The default label column width every item inherits when its label is `left`; an item's own `labelWidth` wins. (optional) |
| controlMinWidth | number | string | The default width below which a `left` label switches to the top instead, every item inherits; an item's own `controlMinWidth` wins. See {@link FormItemConfig.controlMinWidth}. (optional) |
| requiredHint | boolean | string | The default marker a required field with no visible label shows on its placeholder: `true` appends `" *"`, a string resolves through the message catalogue, `false` shows nothing. An item's own `requiredHint` wins. (optional) |
| colsBreakpoint | number | false | The width, in pixels, below which a `cols` container stacks its children into one column, or `false` (or `0`) to never stack. A positive number is used as-is. Default 480. (optional) |
| wrap | boolean | When the root axis is `cols` (no `rows`), resolve each item's percentage `width` against its own rendered line's gaps instead of the whole row's. See {@link FormBlock.wrap}. Default `false`. (optional) |
| gap | number | string | When the root axis is `cols` (no `rows`), the gap between items. See {@link FormBlock.gap}. (optional) |
| columnGap | number | string | When the root axis is `cols` (no `rows`), the gap between items on the same line, overriding `gap`. See {@link FormBlock.columnGap}. (optional) |
| rowGap | number | string | When the root axis is `cols` (no `rows`), the gap between wrapped lines, overriding `gap`. See {@link FormBlock.rowGap}. (optional) |
| bind | FormBind | Bind the form to a record. A grid row generates one item per column and saves through the grid's edit path; a routed record follows the route's keyed diffs; a plain object is initialised from and written back to. (optional) |
| css | Record<string, string | number> | string | Extra CSS on the form root. (optional) |
| steps | FormStep[] | Wizard steps: one labelled group of rows shown at a time. (optional) |
| stepOrientation | FormStepOrientation 'horizontal' | 'vertical' | The step indicator's orientation: `horizontal` (default) or `vertical`. (optional) |
| validateSteps | boolean | Whether a forward step move validates the current step first (`true`, the default). Set `false` to run `validate()` yourself and navigate unchecked. (optional) |
| messages | { t(key: string, params?: object): string } | A `t(key, params)` catalogue for the separator's accessible label. (optional) |
| Method | Signature | Parameters | Returns | Description |
|---|---|---|---|---|
| createGrid | (el: HTMLElement, config: object) => Grid | el: HTMLElementconfig: object | => Grid | The grid factory (`createGrid`) every `grid` item uses unless it names its own. (optional) |
ComboOptionObject
A combo option written as an object: `{ value, label, description, icon, avatar, color, dot, disabled }`,.
| Property | Type | Description |
|---|---|---|
| value | unknown | The option's value. (optional) |
| label | string | The display label. (optional) |
| description | string | The second line of a multi-line option. (optional) |
| avatar | string | An image URL (drawn round, falling back to the label's initials), or initials text (drawn round on a colour from `color` or a hash of the label). (optional) |
| icon | IconName | Node | A glyph name from the icon registry (see {@link IconName}), or a DOM node, drawn on the left when there is no avatar or dot; `color` tints it. (optional) |
| color | string | The background colour for the initials avatar (a stable colour derived from the label when omitted) and the tint of the option's icon. (optional) |
| dot | string | A colour that draws a small filled circle before the label instead of an icon or avatar, with no letter. (optional) |
| disabled | boolean | Whether the option is shown but not selectable. (optional) |
ComboLoadQuery
What a combo `load` is handed: the search, the page, and an abort signal.
| Property | Type | Description |
|---|---|---|
| search | string | The current search text (empty for the first page). |
| page | number | The zero-based page to fetch. |
| signal | AbortSignal | Abort this load when a newer search supersedes it. |
| pageSize | number | The page size handed to `load`. |
SelectConfig
The options `createSelect` takes: the form's `type: 'select'` item as a standalone control.
| Property | Type | Description |
|---|---|---|
| options | unknown[] | The option list: strings, `{ value, label }` objects, or groups. (optional) |
| multiple | boolean | Multi-select mode; the value is then an array. (optional) |
| value | unknown | The initial value (an array when `multiple`). (optional) |
| placeholder | string | The text the trigger shows while nothing is chosen. (optional) |
| ariaLabel | string | The accessible name of the trigger. (optional) |
| disabled | boolean | Start disabled. (optional) |
| readOnly | boolean | Start read-only. (optional) |
| doc | Document | The owner document, for a select mounted outside the main document. (optional) |
| Method | Signature | Parameters | Returns | Description |
|---|---|---|---|---|
| optionTemplate | (option: object) => unknown | option: object | => unknown | A custom renderer for one option in the list. (optional) |
| selectedTemplate | (option: object) => unknown | option: object | => unknown | A custom renderer for the chosen value a single select shows on its trigger. (optional) |
| t | (key: string, params?: object) => string | key: stringparams?: object | => string | A message resolver for the control's own strings. (optional) |
Select
The select instance {@link createSelect} returns. Picking an option dispatches a DOM `change` event on the host element.
Properties
| Property | Type | Description |
|---|---|---|
| el | HTMLElement | The host element the select mounted into. |
| root | HTMLElement | The select's root element. |
| trigger | HTMLElement | The trigger button. |
Methods
| Method | Signature | Parameters | Returns | Description |
|---|---|---|---|---|
| getValue | (): unknown | - | unknown | The committed value (an array when `multiple`). |
| setValue | (value: unknown): Select | value: unknown | Select | Write a committed value silently; no `change` fires. |
| setOptions | (options: unknown[]): Select | options: unknown[] | Select | Replace the option list, keeping a value still present. |
| setPlaceholder | (text: string | null | undefined): Select | text: string | null | undefined | Select | Replace the empty-trigger placeholder. |
| reload | (): Select | - | Select | Re-render the list. |
| open | (): Select | - | Select | Open the listbox. |
| close | (): Select | - | Select | Close the listbox. |
| focus | (): Select | - | Select | Focus the trigger. |
| blur | (): Select | - | Select | Blur the trigger. |
| setDisabled | (disabled: boolean): void | disabled: boolean | void | Enable or disable the control. |
| setReadOnly | (readOnly: boolean): void | readOnly: boolean | void | Mark the control read-only. |
| destroy | (): void | - | void | Remove the control and its listeners. |
Events
No events.
ComboConfig
| Property | Type | Description |
|---|---|---|
| options | ComboOption[] | A static option list, used when `load` is absent. (optional) |
| multiple | boolean | Multi-select mode: the value is an array and choices become chips. (optional) |
| value | unknown | The initial value (an array when `multiple`). (optional) |
| newOptions | boolean | { create(text: string): unknown } | Free entry: `true`, or `{ create(text) }` to build the new option. (optional) |
| selectAll | boolean | Show a select-all action over the loaded set (multi-select). (optional) |
| debounce | number | The search debounce, in milliseconds. Default 250. (optional) |
| pageSize | number | The page size handed to `load`. Default 20. (optional) |
| maxHeight | number | The chip area max height, in pixels. (optional) |
| chipPlacement | 'inside' | 'above' | 'below' | Where multi-select chips sit: 'inside' (default), 'above' or 'below' the control. (optional) |
| clearable | boolean | Show a clear control on a single-select combo while it holds a value; it empties the value to `null` with one `change`. (optional) |
| dependsOn | string[] | Parent item names that clear and reload this combo when they change. (optional) |
| Method | Signature | Parameters | Returns | Description |
|---|---|---|---|---|
| load | (query: ComboLoadQuery) => ComboLoadResult | Promise<ComboLoadResult> | query: ComboLoadQuery | => ComboLoadResult | Promise<ComboLoadResult> | The paging loader. Absent when `options` is used. (optional) |
| resolveLabels | (values: unknown[]) => ComboOption[] | Promise<ComboOption[]> | values: unknown[] | => ComboOption[] | Promise<ComboOption[]> | Labels for selected values that sit outside the loaded pages. (optional) |
| optionTemplate | (option: ComboOption) => unknown | option: ComboOption | => unknown | A custom option renderer, returning a string or a DOM node. A string is treated as HTML and sanitised before it is inserted. (optional) |
| selectedTemplate | (option: ComboOption) => unknown | option: ComboOption | => unknown | A custom renderer for the selected option - the multi-select chips and the single-select shown value - returning a string or a DOM node; a string is treated as HTML and sanitised. (optional) |
SpeedDialConfig
The `type: 'speeddial'` item options, and the standalone `createSpeedDial` options.
| Property | Type | Description |
|---|---|---|
| items | SpeedDialItem[] | The actions the menu shows. (optional) |
| position | FormSpeedDialPosition 'top-left' | 'top-center' | 'top-right' | 'middle-left' | 'middle-right' | 'bottom-left' | 'bottom-center' | 'bottom-right' | The corner or edge the FAB anchors to: `top-left`, `top-center`, `top-right`, `middle-left`, `middle-right`, `bottom-left`, `bottom-center`, `bottom-right`. Default `bottom-right`. (optional) |
| fixed | boolean | Anchor the FAB to the viewport instead of its container. (optional) |
| openOnHover | boolean | Open the menu on pointer hover and close it on leave. (optional) |
| direction | FormSpeedDialDirection 'up' | 'down' | 'left' | 'right' | 'auto' | The way the strip opens: `up`, `down`, `left`, `right`, or `auto` (default - into the container's room side). (optional) |
| mode | 'linear' | 'radial' | The menu shape: `linear` (default) or `radial`. (optional) |
| radial | { startAngle?: number; endAngle?: number; offset?: number } | The radial fan - its start and end angles (degrees, defaulting from `position`) and its radius `offset` in pixels. (optional) |
| modal | boolean | Paint a backdrop behind the open menu that swallows page clicks. (optional) |
| openIcon | IconName | string | Node | The FAB's closed-state icon (default `plus`). (optional) |
| closeIcon | IconName | string | Node | The FAB's open-state icon (default `close`). (optional) |
| text | string | An optional label on the FAB. (optional) |
| variant | FormSpeedDialVariant 'primary' | 'secondary' | 'outline' | 'info' | 'success' | 'warning' | 'danger' | The FAB's colour: `primary` (default), `secondary`, `outline`, `info`, `success`, `warning` or `danger`. (optional) |
| disabled | boolean | Start disabled. (optional) |
FormEventPayloads
What a handler receives, per form event.
| Property | Type | Description |
|---|---|---|
| beforeChange | FormBeforeChangeEvent | The commit about to happen, with `preventDefault` to refuse it. |
| change | FormValueEvent | The edit that was committed. |
| input | FormValueEvent | The live, uncommitted value. |
| click | FormClickEvent | The button click. |
| focus | FormFocusEvent | The item that took focus. |
| blur | FormFocusEvent | The item that lost focus. |
| validated | FormValidatedEvent | A validation run, item or whole form, with its failures. |
| complete | FormCompleteEvent | Every box of an `otp` item is now filled. |
| customColorsChange | FormColorCustomColorsEvent | A `color` item's custom-colours row, extended. |
| open | FormSpeedDialOpenEvent | A `speeddial` FAB's menu opened. |
| close | FormSpeedDialCloseEvent | A `speeddial` FAB's menu closed. |
| itemClick | FormSpeedDialItemClickEvent | FormListboxItemClickEvent | A `speeddial` menu action was activated, or a `listbox` row was clicked. |
| activate | FormListboxItemClickEvent | A `listbox` row was activated with Enter. |
FormEvent
The fields every form event carries.
| Property | Type | Description |
|---|---|---|
| type | string | Which event this is: one of the `FormEventName` names. |
| name | string | null | The item's name, or `null` for an unnamed item. |
| item | FormItemConfig | The item's config. |
FormValueEvent
A value event (`change`/`input`): the item and the value involved.
| Property | Type | Description |
|---|---|---|
| value | unknown | The value being reported (or committed). |
| previousValue | unknown | The previously committed value, on a `change` event. (optional) |
FormColorCustomColorsEvent
A `customColorsChange` payload: a `color` item's custom-colours row gained a newly picked colour.
| Property | Type | Description |
|---|---|---|
| colors | string[] | The custom-colours list after the addition - newest first, deduplicated, at most ten entries. |
FormSpeedDialItemClickEvent
An `itemClick` payload: a `speeddial` menu action was activated.
| Property | Type | Description |
|---|---|---|
| item | SpeedDialItem | The action that was activated. |
| index | number | The action's index in the `items` list. |
FormListboxItemClickEvent
An `itemClick`/`activate` payload: a `listbox` row was clicked (selected row included) or activated with Enter.
| Property | Type | Description |
|---|---|---|
| option | unknown | The option exactly as given - the same object `render(opt)` receives. |
| event | MouseEvent | KeyboardEvent | The triggering event: a `MouseEvent` for `itemClick`, a `KeyboardEvent` for `activate`. |
FormBeforeChangeEvent
A `beforeChange` payload. A handler refuses the commit by calling `preventDefault(reason?)` or returning `false` (or a Promise of either).
| Property | Type | Description |
|---|---|---|
| origin | 'user' | 'api' | Who asked for the change: `user` for an edit, `api` for a programmatic commit. |
| defaultPrevented | boolean | True once any handler cancelled the commit. (read-only) |
| reason | string | null | The reason given to `preventDefault`, or `null`. (read-only) |
| Method | Signature | Parameters | Returns | Description |
|---|---|---|---|---|
| preventDefault | (reason?: string): void | reason?: string | void | Cancel the commit. |
FormClickEvent
A `click` event payload: a button holds no value.
| Property | Type | Description |
|---|---|---|
| value | null | Always `null` - a button holds no value. |
FormValidationFailure
One failed item in a `validated` event's `failures` list.
| Property | Type | Description |
|---|---|---|
| name | string | null | The item's name. |
| rule | string | The rule that failed: `required`, a built-in name, `pattern` or `custom`. |
| message | string | The failure message shown on the item. |
FormValidatedEvent
A `validated` payload: the outcome of `form.validate()` or `item.validate()`. `name`/`item` name the one item for an item run, or are `null` when the whole form was validated; `failures` lists every invalid item in document order.
| Property | Type | Description |
|---|---|---|
| value | unknown | The value validated (an item run), or `undefined` for a whole-form run. |
| valid | boolean | True when nothing failed. |
| failures | FormValidationFailure[] | Every item that failed, in document order. |
FormItem
The item handle `getItem(name)` returns.
| Property | Type | Description |
|---|---|---|
| el | HTMLElement | The item's wrapper element. (read-only) |
| name | string | null | The item's name, or `null` for an unnamed item. (read-only) |
| labelEffectivePosition | FormLabelPosition 'top' | 'left' | 'hidden' | The label's current rendered position: `labelPosition` normally, or `top` when a `left` label with `controlMinWidth` has switched because its own width left the control too narrow. Mirrors the item's `data-label-effective` attribute. (read-only) |
| Method | Signature | Parameters | Returns | Description |
|---|---|---|---|---|
| getValue | (): unknown | - | unknown | The committed value. |
| setValue | (value: unknown): FormItem | value: unknown | FormItem | Write a committed value, silently (no event fires). |
| show | (): FormItem | - | FormItem | Show a hidden item. |
| hide | (): FormItem | - | FormItem | Hide the item. |
| isVisible | (): boolean | - | boolean | Whether the item is currently visible (not hidden). |
| disable | (): FormItem | - | FormItem | Disable the item's control. |
| enable | (): FormItem | - | FormItem | Enable a disabled item. |
| focus | (): FormItem | - | FormItem | Focus the item's control. |
| blur | (): FormItem | - | FormItem | Blur the item's control. |
| validate | (): boolean | - | boolean | Validate this one item, paint its verdict and report it through `validated`. |
| attach | (viewOrElement: Element | { el?: HTMLElement; root?: HTMLElement; element?: HTMLElement; destroy?(): void }, opts?: { keep?: boolean }): FormItem | viewOrElement: Element | { el?: HTMLElement; root?: HTMLElement; element?: HTMLElement; destroy?(): void }opts?: { keep?: boolean } | FormItem | A `container` item only: append an element, or a Lattice view's own element (`.el`, `.root` or `.element` - whichever it exposes), sized to the region (width 100%; height forced to the region's own configured height only when it set one). Replaces (and, unless kept, destroys) whatever was attached before; the attached view is destroyed by `form.destroy()` too, unless `keep: true`. (optional) |
| attachHTML | (html: string): FormItem | html: string | FormItem | A `container` item only: replace the region's content with sanitised host HTML, destroying whatever was attached before (unless it was kept). (optional) |
| getWidget | (): unknown | - | unknown | A `container` item only: the attached view or element, or `null`. (optional) |
| addRow | (row?: object): string | null | Promise<string | null> | row?: object | string | null | Promise<string | null> | A `grid` item only: add a row (a blank one when none is given) through `beforeChange` and one `change`. Returns the new row's key, or `null` when it was refused. (optional) |
| removeRows | (keys: string | string[]): string[] | keys: string | string[] | string[] | A `grid` item only: remove rows by key, each through `beforeChange` and one `change`. Returns the keys removed. (optional) |
| getGrid | (): Grid | null | - | Grid | null | A `grid` item only: the embedded Lattice grid, or `null` when no `createGrid` was supplied. (optional) |
| setOptions | (options: unknown[]): FormItem | options: unknown[] | FormItem | Replace a combo or select item's static options, re-rendering the list in place; a value still present is kept, one gone is cleared with one `change` event, and a changed label refreshes the shown value. |
| reload | (): FormItem | - | FormItem | Reload a `load`-backed combo - clear its cache and fetch the first page again; on a static combo or select this only re-renders. |
| getLabel | (): string | null | - | string | null | The item's current label - a field's label, a button's caption, or a fieldset's legend - or `null` when it carries none. |
| setLabel | (text: string): FormItem | text: string | FormItem the item, for chaining. | Change the item's visible label and its accessible name: a field's label, a button's caption, or (on a handle for a named fieldset) its legend; on a registered custom control, the frame's own label and the `label` the control's `item` object carries. A hidden label (`labelPosition: 'hidden'`) stays visually hidden but its accessible name still updates. The change survives `setDensity`, `setReadOnly`, `show()`/`hide()` and any re-render, and is what a later `getItem` reports. |
| setHelp | (text: string | null): FormItem | text: string | null | FormItem | Change the help line under the control; `null` removes it. Survives `setDensity`, `setReadOnly`, `show()`/`hide()` and any re-render, the same as `setLabel`. A thin wrapper over `set({ helpMessage: text })`. |
| getOptions | (): unknown[] | - | unknown[] | A `listbox` item's options in their current order, exactly as given, independent of selection. (optional) |
| addOption | (opt: unknown, index?: number): FormItem | opt: unknownindex?: number | FormItem | Insert one option into a `listbox` item, keeping selection and order consistent, and firing one `change`. Appended when `index` is omitted. (optional) |
| removeOption | (value: unknown): FormItem | value: unknown | FormItem | Remove a `listbox` item's option keyed by `value`, keeping selection and order consistent, and firing one `change`. (optional) |
| updateOption | (value: unknown, patch: Record<string, unknown>): FormItem | value: unknownpatch: Record<string, unknown> | FormItem | Merge `patch` over a `listbox` item's option keyed by `value`, in place, keeping selection and order consistent, and firing one `change`. (optional) |
| filter | (fn: ((opt: unknown) => boolean) | null): FormItem | fn: ((opt: unknown) => boolean) | null | FormItem | Show only the options of a `listbox` item that `fn` accepts, without touching its canonical order, selection or value; `null` clears the predicate. (optional) |
| remeasure | (): FormItem | - | FormItem | A `listbox` item only: drop every cached row height and lay the list out again from live measurements, keeping scroll position and selection. The first paint already measures and corrects itself once the form's root is attached; call this when a host changes the item's `render()` or its CSS after build. (optional) |
| set | (props: FormItemLiveProps): FormItem | props: FormItemLiveProps | FormItem the item, for chaining. | Apply a subset of the item's own config after build - see {@link FormItemLiveProps} for the props every item shares and which a control additionally documents as live. Re-renders only what changed; the control's own value is never touched, so a `min`/`max`/`options` change that makes the current value invalid is left for the next {@link FormItem#validate} to report. Keeps focus and the caret throughout. An unknown or non-live prop warns once (developer console) and is ignored. |
| get | (prop: string): unknown | prop: string | unknown | The effective value of one prop {@link FormItem#set} accepts, read from the item's own config rather than re-derived from the DOM. An unknown prop warns once and returns `undefined`. |
| getPlaceholder | (): string | null | - | string | null | The item's current placeholder, or `null` when it carries none - a shortcut for `get('placeholder')`. |
| setPlaceholder | (text: string | null): FormItem | text: string | null | FormItem the item, for chaining. | Change the item's placeholder live - a shortcut for `set({ placeholder: text })`. |
FormItemLiveProps
The props {@link FormItem#set} may change after build. Every item shares `label`, `labelPosition`, `labelWidth`, `helpMessage`, `required`, `readOnly`, `disabled`, `hidden`, `width`, `validation`, `errorMessage` and `css`. `placeholder` is live on `input`, `textarea`, `number`, `select`, `combo` and `datepicker`; `options` on `select` and `combo` (the same contract as `setOptions`); `min`/`max`/`step`/`format` on `number` and `slider`; `tick`/`majorTick` are additionally live on `slider`; `disabledDates` on `datepicker` and `daterange` (the open calendar's days are redrawn and a held value the new rule disables is reported by validation, never changed;. Any other key is a control's own documented live option (`item.props` at build); one that is neither common nor declared live warns once and is ignored.
| Property | Type | Description |
|---|---|---|
| label | string | The item's visible label and accessible name. (optional) |
| labelPosition | 'top' | 'left' | 'hidden' | Where the label sits: above, to the left, or visually hidden. (optional) |
| labelWidth | number | string | The label column's width, in a `labelPosition: 'left'` item. (optional) |
| helpMessage | string | null | The help line under the control; `null` removes it. (optional) |
| required | boolean | Whether the item must hold a value to pass `validate()`. (optional) |
| readOnly | boolean | Whether the item is read-only (focusable, but not editable). (optional) |
| disabled | boolean | Whether the item is disabled (out of the tab order, excluded from validation). (optional) |
| hidden | boolean | Whether the item is hidden, giving its space to its neighbours. (optional) |
| width | number | string | The item's width (a px number or a CSS length). (optional) |
| placeholder | string | null | The placeholder shown while the control is empty. (optional) |
| min | number | A `number` field's lower bound. (optional) |
| max | number | A `number` field's upper bound. (optional) |
| step | number | A `number` field's step. (optional) |
| format | unknown | A `number` field's `NumberFormat` spec. (optional) |
| options | unknown[] | A `select`/`combo` item's static options, the same as `setOptions`. (optional) |
| disabledDates | unknown | A `datepicker` or `daterange` item's disabled dates. (optional) |
| validation | FormItemConfig['validation'] | The item's validation rule. (optional) |
| errorMessage | string | The message shown when `validation` fails. (optional) |
| css | string | Record<string, string> | Extra inline CSS, merged onto the item's wrapper. (optional) |
| [prop: string] | unknown | Any other control-specific option the control itself documents as live. |
Form
The form instance {@link createForm} returns.
Properties
| Property | Type | Description |
|---|---|---|
| el | HTMLElement | null | The host element. (read-only) |
| config | FormConfig | The normalised config. (read-only) |
| steps | FormStep[] | The wizard's normalised steps, or an empty array when the form is not a wizard. (read-only) |
| activeStep | number | The index of the active step (0-based), or 0 when the form is not a wizard. (read-only) |
Methods
| Method | Signature | Parameters | Returns | Description |
|---|---|---|---|---|
| getItem | (name: string): FormItem | undefined | name: string | FormItem | undefined | The item handle for a name, or `undefined` when no item has that name. |
| getValue | (): Record<string, unknown> | - | Record<string, unknown> | Snapshot every named, value-holding item as `{ name: value }`. |
| setValue | (values: Record<string, unknown>): Form | values: Record<string, unknown> | Form | Write values into the matching named items, silently. |
| clear | (): Form | - | Form | Reset every user-editable item to its empty value. |
| validate | (): boolean | - | boolean | Validate every rule-bearing item, paint each verdict and report all failures through `validated`. |
| forEach | (fn: (item: FormItem) => void): void | fn: (item: FormItem) => void | void | Walk every item in document order, handing each handle to `fn`. |
| on | (name: FormEventName | '*', fn: (event: FormEventPayloads[FormEventName]) => void): () => void | name: FormEventName | '*'fn: (event: FormEventPayloads[FormEventName]) => void | () => void | Subscribe to a form event or to `'*'` for every past-tense event; returns an unsubscribe. |
| off | (name: FormEventName | '*', fn: (event: FormEventPayloads[FormEventName]) => void): void | name: FormEventName | '*'fn: (event: FormEventPayloads[FormEventName]) => void | void | Remove a handler registered with {@link Form#on}. |
| setDensity | (density: FormDensity): Form | density: FormDensity | Form | Change the form's density live, re-theming control heights without a re-render. |
| setSpacing | (spacing: number | string | null): Form | spacing: number | string | null | Form | Change the vertical gap between items live - a px number or a CSS length - re-theming every stacked container with one property write and no re-render. `null` removes the override so the gap returns to the density default. |
| setReadOnly | (readOnly: boolean): Form | readOnly: boolean | Form | Set every item read-only (or back to editable) in one call. A read-only item stays focusable, selectable and validated. |
| setDisabled | (disabled: boolean): Form | disabled: boolean | Form | Set every item disabled (or back to enabled) in one call. A disabled item leaves the tab order and is excluded from validation. |
| isDirty | (name?: string): boolean | name?: string | boolean | Whether an item (or, with no name, the whole form) holds an unsaved user edit. |
| isConflicted | (name?: string): boolean | name?: string | boolean | Whether an item (or the whole form) has an unsaved edit an external change also touched. |
| save | (): boolean | Promise<boolean> | - | boolean | Promise<boolean> | Save the dirty items through the binding; true when saved (or nothing to save). |
| revert | (): Form | - | Form | Restore every dirty item to its bound/committed value and clear the dirty flags. |
| next | (): Promise<boolean> | - | Promise<boolean> | Advance one step, validating the current step's items first. |
| back | (): Promise<boolean> | - | Promise<boolean> | Go back one step - always allowed, never validated. |
| goToStep | (index: number): Promise<boolean> | index: number | Promise<boolean> | Move to a step by index, validating the steps passed over on the way forward. |
| destroy | (): void | - | void | Empty the element and drop every item record, listener and handler. |
Events
| Event | When | Payload | Cancellable |
|---|---|---|---|
| beforeChange | An edit is about to be committed; cancellable. | FormBeforeChangeEvent | yes |
| change | An edit was committed. | FormValueEvent | no |
| input | The user typed (the value is live, not yet committed). | FormValueEvent | no |
| click | A button was clicked. | FormClickEvent | no |
| focus | An item's control took focus. | FormFocusEvent | - |
| blur | An item's control lost focus. | FormFocusEvent | - |
| validated | One or more items were validated, with the failures. | FormValidatedEvent | no |
| complete | Every box of an `otp` item is now filled. | FormCompleteEvent | - |
| customColorsChange | A `color` item's custom-colours row gained a newly picked colour. | FormColorCustomColorsEvent | no |
| open | A `speeddial` FAB's menu opened. | FormSpeedDialOpenEvent | - |
| close | A `speeddial` FAB's menu closed. | FormSpeedDialCloseEvent | - |
| itemClick | A `speeddial` menu action was activated, or a `listbox` row was clicked, selected row included. | FormSpeedDialItemClickEvent | FormListboxItemClickEvent | no |
| activate | A `listbox` row's Enter-key equivalent of a click. | FormListboxItemClickEvent | no |
FormGroupEventPayloads
What a handler receives, per group event.
| Property | Type | Description |
|---|---|---|
| change | FormGroupChangeEvent | The edit a member form committed. |
| validated | FormGroupValidatedEvent | A member form's validation verdict. |
FormGroupEvent
The fields every form-group event carries.
| Property | Type | Description |
|---|---|---|
| type | string | Which event this is: one of the `FormGroupEventName` names. |
| form | Form | The member form the event came from. |
FormGroupChangeEvent
A group `change` payload: the member form and the item/value it committed.
| Property | Type | Description |
|---|---|---|
| name | string | null | The item's name. |
| value | unknown | The value being reported. |
FormGroupValidatedEvent
A group `validated` payload: the member form and its verdict.
| Property | Type | Description |
|---|---|---|
| valid | boolean | True when nothing failed. |
FormGroupTransform
The value transform a group applies on read and write. `get` receives the merged member values and returns what `getValue()` returns; `set` receives whatever `setValue()` was handed and does the routing itself.
| Method | Signature | Parameters | Returns | Description |
|---|---|---|---|---|
| get | (values: Record<string, unknown>): unknown | values: Record<string, unknown> | unknown | Shape the merged values into the group's output. |
| set | (values: unknown): void | values: unknown | void | Route the written values into the members. |
FormGroupOptions
The options `createFormGroup` takes.
| Property | Type | Description |
|---|---|---|
| transform | FormGroupTransform | Join or split values on read and write. (optional) |
| bind | FormBind | Bind the whole group to one data-router record: every member fills with its own fields, and `save()` writes ONE router update and calls `onSave` once. (optional) |
FormGroup
The form group instance {@link createFormGroup} returns.
Properties
| Property | Type | Description |
|---|---|---|
| forms | Form[] | The member forms, in add order. (read-only) |
Methods
| Method | Signature | Parameters | Returns | Description |
|---|---|---|---|---|
| add | (form: Form, opts?: { id?: unknown }): FormGroup | form: Formopts?: { id?: unknown } | FormGroup | Add a form; `id` names the member for a pinned cross-form rule and router binding. |
| remove | (form: Form): FormGroup | form: Form | FormGroup | Remove a form; the group ignores a form that is not a member. |
| getValue | (): unknown | - | unknown | Merge every member's values in add order, through `transform.get` when set. |
| setValue | (values: Record<string, unknown>): FormGroup | values: Record<string, unknown> | FormGroup | Route each key to the member that owns it, through `transform.set` when set. |
| getItem | (name: string): FormItem | undefined | name: string | FormItem | undefined | The owning member's item handle for a name, or `undefined`. |
| validate | (): boolean | - | boolean | Validate every member and focus the first invalid field in add order. |
| setReadOnly | (readOnly: boolean): FormGroup | readOnly: boolean | FormGroup | Set every member read-only (or back to editable) in one call. |
| setDisabled | (disabled: boolean): FormGroup | disabled: boolean | FormGroup | Set every member disabled (or back to enabled) in one call. |
| clear | (): FormGroup | - | FormGroup | Clear every member to its empty values. |
| reset | (): FormGroup | - | FormGroup | Restore every member's dirty items to their bound/committed value. |
| save | (): boolean | Promise<boolean> | - | boolean | Promise<boolean> | Save every member's dirty items as ONE router update and call the group's `bind.onSave` once; `false` when unbound, true when saved or nothing dirty. |
| isDirty | (): boolean | - | boolean | Whether any member holds an unsaved user edit. |
| on | (name: FormGroupEventName | '*', fn: (event: FormGroupEventPayloads[FormGroupEventName]) => void): () => void | name: FormGroupEventName | '*'fn: (event: FormGroupEventPayloads[FormGroupEventName]) => void | () => void | Subscribe to `change` or `validated` (or `'*'` for both); returns an unsubscribe. |
| off | (name: FormGroupEventName | '*', fn: (event: FormGroupEventPayloads[FormGroupEventName]) => void): void | name: FormGroupEventName | '*'fn: (event: FormGroupEventPayloads[FormGroupEventName]) => void | void | Remove a handler registered with {@link FormGroup#on}. |
| destroy | (): void | - | void | Detach the group's listeners without destroying the forms. |
Events
| Event | When | Payload | Cancellable |
|---|---|---|---|
| change | A member form committed an edit. | FormGroupChangeEvent | no |
| validated | A member form was validated. | FormGroupValidatedEvent | no |
Combo
The combo instance {@link createCombo} returns.
Properties
| Property | Type | Description |
|---|---|---|
| el | HTMLElement | The host element. (read-only) |
| root | HTMLElement | The combo root element. (read-only) |
| input | HTMLInputElement | The search input (the combobox). (read-only) |
Methods
| Method | Signature | Parameters | Returns | Description |
|---|---|---|---|---|
| getValue | (): unknown | - | unknown | The committed value: a single value (or null), or an array when multi. |
| setValue | (value: unknown): Combo | value: unknown | Combo | Write a committed value silently (no event fires). |
| reload | (): Combo | - | Combo | Reload page 0 for the current search, dropping the cache. |
| clear | (): Combo | - | Combo | Clear the selection, firing `change`. |
| open | (): Combo | - | Combo | Open the popup. |
| close | (): Combo | - | Combo | Close the popup. |
| focus | (): Combo | - | Combo | Focus the search input. |
| blur | (): Combo | - | Combo | Blur the search input. |
| setDisabled | (disabled: boolean): void | disabled: boolean | void | Enable or disable the control. |
| setReadOnly | (readOnly: boolean): void | readOnly: boolean | void | Mark the control read-only. |
| destroy | (): void | - | void | Tear the combo down: abort loads, clear timers, detach listeners. |
Events
No events.
SpeedDial
The speed-dial instance {@link createSpeedDial} returns.
Properties
| Property | Type | Description |
|---|---|---|
| el | HTMLElement | The host element. (read-only) |
| fab | HTMLButtonElement | The FAB button. (read-only) |
| menu | HTMLElement | The menu element. (read-only) |
Methods
| Method | Signature | Parameters | Returns | Description |
|---|---|---|---|---|
| open | (): void | - | void | Open the menu. |
| close | (): void | - | void | Close the menu and return focus to the FAB. |
| toggle | (): void | - | void | Toggle the menu open/closed. |
| setItems | (items: SpeedDialItem[]): void | items: SpeedDialItem[] | void | Replace the action items and rebuild the menu. |
| destroy | (): void | - | void | Tear the speed dial down: close, detach listeners and empty the host. |
Events
No events.