UNPKG

@llselect/core

Version:

Low-level select: a minimal, flexible, framework-agnostic replacement for the native HTML select element.

309 lines • 15.9 kB
import { LLSelectBase, type LLSelectBaseSettings, type LLSelectBeforeChangeEvent, type LLSelectChangeMeta, type LLSelectSettingsInputOf } from './base.js'; /** * Context passed to {@link LLSelectSingleSettings.createTriggerContentElFn} * and {@link LLSelectSingleSettings.triggerContextToScreenReaderTextFn}. * @group Settings * @category Single */ export interface LLSelectSingleTriggerContext<T> { chosenItem: T | undefined; items: readonly T[]; } /** * Resolved (defaults applied) settings for {@link LLSelectSingle}: the base * settings plus the single-mode fields - the runtime type of `this.settings`, * one bag built complete in the constructor. * @group Settings * @category Single */ export interface LLSelectSingleSettings<T, GroupKey = string> extends LLSelectBaseSettings<T, GroupKey> { /** * Fired **after** the chosen item actually changed (compared via `compareFn`). * Receives the new value and the PREVIOUS one (the snapshot from before * this change); `undefined` means "no selection" on either side. Does NOT * fire on construction nor on `setChosenItem` with an equivalent item. * `null` (default) = no listener. * * > Pairs with `onBeforeChange`, which runs **before** a user change and can stop it. * * - `meta.source` says who initiated the change: `'user'` for a pointer or * keyboard interaction inside the select component, `'api'` for any programmatic * call. See {@link LLSelectChangeMeta}. * - `meta.reason` says what the change did: `'choose'` with the item in * `meta.item`, `'clear'` for an empty write, or `'items'` for a * `setItems` drop. See {@link LLSelectChangeReason}. * - Runs **after** the value changed and the trigger was updated. * - `getChosenItem()` already returns the new value. * - A setter may be called from inside it. The nested `onChange` then * reports `meta.source` `'api'`. * - A modal dialog may be opened, or focus moved, from inside it. * - Focus that already moved outside the select component is not reclaimed. * - Moving focus outside the select component closes the popup, as always. * - A pick closes the popup when the handler returns, if it is still open. * - Other changes leave the popup as it is. * @group Events */ onChange: ((chosenItem: T | undefined, previousChosenItem: T | undefined, meta: LLSelectChangeMeta<T>) => void) | null; /** * Fired **before** a user interaction changes the chosen item, with a way to * stop it. * * > Pairs with `onChange`, which runs **after** the change was written. * * - Fires for the library's own pointer and keyboard paths only: a pick in * the popup, and the clear button. Programmatic setters, the `setItems` * reconciliation and an action row's own setter calls never fire it. * - `nextChosenItem` is the value about to be set. `previousChosenItem` is * the current one. * - `event.preventDefault()` stops the change: nothing is written, nothing * re-renders, `onChange` does not fire. * - A vetoed pick still closes the popup, like any pick in single mode * while the popup is open. Only a pick does this. * - A vetoed clear leaves everything as it is. * - A pick of the already chosen item never fires it: nothing would change. * - Runs **after** the protected `onChosenChanging` hook. Both run, either may * cancel, and `event.defaultPrevented` shows the hook's decision. * - A setter called from inside the handler wins, `setItems` included: the * pending change is dropped. That change reports `meta.source` `'user'`, * as the first change of the interaction. * - For a confirmation dialog: call `event.preventDefault()`, open the * dialog, and call `setChosenItem` after the user agreed. That change * reports `meta.source` `'api'`. * - An error thrown by a handler propagates and the change does not * happen. If a pick threw, the popup does not close. * - `null` (default) = nothing is called; no user change is ever stopped * by it. * @group Events */ onBeforeChange: ((nextChosenItem: T | undefined, previousChosenItem: T | undefined, event: LLSelectBeforeChangeEvent<T>) => void) | null; /** * Render the trigger's content ELEMENT without subclassing - the setting * equivalent of overriding `renderTriggerContent`. Receives the chosen item * + items (same convention as `createPopupListItemContentElFn`): * - Called on **every** trigger content render (`renderTriggerContent`: every full trigger render, plus every `setItems`); nothing is kept for a later call. * - `HTMLElement` - inserted into the trigger as-is; you own it. Use this for * real markup (icon + text, etc.). * - fn returns `null` - use the default for this render: the chosen item's * `itemToString`, or the placeholder when nothing is chosen. * - setting is `null` (default) - always use that default rendering. * The DEFAULT `renderTriggerContent` checks it first; a subclass override * replaces that default entirely and may ignore the setting - override * wins, per DESIGN.md "Customization model". * @group Trigger */ createTriggerContentElFn: ((ctx: LLSelectSingleTriggerContext<T>) => HTMLElement | null) | null; /** * The text a screen reader reads as the trigger's value, never shown. * - Called on **every** trigger content render (`renderTriggerContent`: * every full trigger render, plus every `setItems`), once, after that * render, through `computeTriggerScreenReaderText`; nothing is kept for a * later call. * - Why a separate text: the trigger has `role="combobox"`, and WAI-ARIA * 1.2 gives a combobox that is not a text field the value of its * descendant content. The library hides the visible content from * assistive technology with `aria-hidden="true"` and puts this text in a * visually hidden span inside the trigger, so the screen reader reads * this text and nothing that only decorates the screen. * - Return a string, and the library writes it as plain text. * - `null`, returned or as the setting (the default), and a blank string * mean the default: the chosen item's `itemToString`, or the placeholder * when nothing is chosen. * - `createTriggerContentElFn` never changes this text: the library never * reads custom content. * @group Trigger */ triggerContextToScreenReaderTextFn: ((ctx: LLSelectSingleTriggerContext<T>) => string | null) | null; } /** * Constructor-time settings input for {@link LLSelectSingle}. * Every field is optional; missing fields use defaults. * @group Settings * @category Single */ export type LLSelectSingleSettingsInput<T, GroupKey = string> = LLSelectSettingsInputOf<LLSelectSingleSettings<T, GroupKey>>; /** * Single-selection select component. * Picking an item replaces any prior chosen item and closes the popup. * Use `setChosenItem(undefined)` to clear the selection. * * @typeParam T - item type. Supply your own `compareFn` for non-primitive `T`. * @typeParam GroupKey - group key type of `itemToGroupKeyFn`; see * {@link LLSelectBase}. * @typeParam S - resolved settings type, for subclasses extending the * settings bag; see {@link LLSelectBase}. * @group Select component classes */ export declare class LLSelectSingle<T = unknown, GroupKey = string, S extends LLSelectSingleSettings<T, GroupKey> = LLSelectSingleSettings<T, GroupKey>> extends LLSelectBase<T, GroupKey, S> { /** * Currently chosen item, or `undefined` if none. * @group State (protected) */ protected chosenItem: T | undefined; /** The item whose text the default screen-reader text is, for its `lang`; set by `computeTriggerScreenReaderText`, read once by `computeTriggerScreenReaderTextLang`. */ private screenReaderTextSource; /** * Build the control inside `targetEl`. * - Settings are resolved once here; missing fields get defaults. * - They are frozen afterwards, except `placeholder` and `uiTranslationPack`, * which have runtime setters; the rule is at {@link LLSelectBaseSettings}. * - This plain form infers `T` from a typed callback in `settings` whose * signature contains `T` (`itemToStringFn: (u: User) => ...`). With no * such callback, pass `T` explicitly: `new LLSelectSingle<string>(...)`. * @group Lifecycle */ constructor(targetEl: HTMLElement, settings?: LLSelectSingleSettingsInput<T, GroupKey>); /** * Subclass form. `subclassSettings` is the typed pass-through for subclasses * that extend the settings bag further; see `LLSelectBase`'s `S` param. * @group Lifecycle */ constructor(targetEl: HTMLElement, settings?: LLSelectSettingsInputOf<S>, subclassSettings?: Omit<S, keyof LLSelectSingleSettings<T, GroupKey>>); /** * Return the currently chosen item, or `undefined` if none. * @group Selection */ getChosenItem(): T | undefined; /** * Set the chosen item programmatically. * - `undefined` clears the choice. * - Fires `onChange` only when the item actually differs from the current * one (compared via `compareFn`). * - Accepts an item that is not (yet) in the items list, for async data * flows. If a later `setItems` does not include it, it is dropped * automatically. * - It does not check disabled state: a disabled item can be chosen * programmatically. Native `<select>` behaves the same. * @group Selection */ setChosenItem(item: T | undefined): void; /** * Orchestrator: composes `syncEmptyStateToDom` + `commitTriggerContentToDom` * to (re)build the trigger from state; touches no DOM directly. * - `createTriggerContentElFn` is tried first; if it returns `null` or is * unset, the default applies. * - The default is the chosen item's string, or the placeholder when * nothing is chosen. * @group Subclassing: rendering */ protected renderTriggerContent(): void; /** * The screen-reader text: the value assistive technology reads for the * trigger, never shown. See the base method for why it exists. * - The library calls it after every trigger content render. * - Default: the text of `triggerContextToScreenReaderTextFn`; when that * gives `null` or a blank string, the chosen item's `itemToString`, or * the placeholder while nothing is chosen. * @group Subclassing: semantics */ protected computeTriggerScreenReaderText(): string; /** * The chosen item's `lang` while the screen-reader text is that item's text. * @internal */ protected computeTriggerScreenReaderTextLang(text: string): string | null; /** * No selection iff `chosenItem` is unset. Drives the trigger wrapper's `data-empty`. * @group Subclassing: semantics */ protected isEmpty(): boolean; /** * Mark the chosen option `aria-selected="true"`, the rest `"false"` (APG select-only). * @group Subclassing: rendering */ protected createPopupListItemEl(item: T, index: number): HTMLElement; /** * Set this item as the chosen item **after** Enter on its row while it is the * active row, Space on it while the filter is inactive, or a click on it, * then close the popup. * * > No **before** counterpart: there is no `onPopupListItemActivating`. * * - Asks `onChosenChanging` and `onBeforeChange` first; a veto keeps the * current value. * - Closes the popup either way, unless a handler threw. * @group Subclassing: reactions */ protected onPopupListItemActivated(item: T): void; /** * Clear button empties the single selection to `undefined`, after asking * `onChosenChanging` and `onBeforeChange`. * @group Subclassing: semantics */ protected clearSelection(): void; /** * Subclass hook: called **before** a user interaction changes the chosen item, * with the way to stop it. Default no-op. * * > Pairs with `onChosenChanged`, which runs **after** the change was written. * * - Runs **before** the `onBeforeChange` setting. Both run, either may call * `event.preventDefault()`. * - The parameters are the setting's: the value about to be set, the * current one, the event. * @group Subclassing: reactions */ protected onChosenChanging(_nextChosenItem: T | undefined, _previousChosenItem: T | undefined, _event: LLSelectBeforeChangeEvent<T>): void; /** * The gate every user path to a change runs through: skips a no-op, asks the * hook and the setting, and says whether the setter may run. */ private requestUserChange; /** * Decide which row is active when the popup opens. * - The library calls it inside `open()`, once per open, after the rows * are built. You never call it. * - To pick another row, override it and set the row with * `setFocusedIndex`. * - `setFocusedIndex` takes an index into `getVisibleItems()`, which * counts item rows only; action rows have no index. * - To fall back to this method's choice, call `super.focusInitial()`, but * only when the override set no row. * - The active row is the `role="option"` row that `aria-activedescendant` * names on the `role="combobox"` element: the trigger, or the filter * input while the filter is active. * - "Focus" in the names `focusInitial` and `setFocusedIndex` means the * active row, not DOM focus. * - DOM focus never moves to the active row. While the filter is active, * the open moves DOM focus to the filter input. * - `open()` clears the active row before the call, so the popup opens * with no active row unless this method sets one. * - Visible items are the items in `getVisibleItems()`, the items that * have a row in the list. * - Makes the row of the chosen item active, if the chosen item is visible * and enabled. * - Otherwise makes the first enabled visible item the active row. * - Either step replaces any row set before this method runs. * - Does nothing when no visible item is enabled. * @group Subclassing: focus */ protected focusInitial(): void; /** * Closed-state typeahead searches relative to the CHOSEN item, like a * native `<select>`: typing its initial cycles to the next match. * - Returns `-1` when nothing is chosen, or the chosen item left the list; * the search then starts from the top. * @group Subclassing: focus */ protected computeTypeaheadClosedStartIndex(list: readonly T[]): number; /** * Re-match the chosen item against the new list **after** `setItems` installs it. * * > No **before** counterpart: there is no `onItemsChanging`. * * - If the list no longer holds it (by `compareFn`), it is dropped and * `onChange` fires. * - If the list holds a compareFn-equal but DIFFERENT object (`track by` * style reload: same key, fresh fields), the stored reference is swapped * to the list's object. The logical value did not change, so `onChange` * does not fire. * - The trigger content re-renders after every `setItems`, because a custom * `createTriggerContentElFn` receives `items`. * - The arrow re-renders only when the chosen item is dropped, because that * runs the whole trigger. * @group Subclassing: reactions */ protected onItemsChanged(): void; private areEqual; private fireChange; } //# sourceMappingURL=single.d.ts.map