@gridkitjs/forms-dom 0.0.0-dev-20261206092422 → 0.0.0-dev-20261206115313
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +261 -2
- package/dist/index.js +771 -22
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/announcer.ts","../src/form/attachFocusGroup.ts","../src/form/formControls.ts","../src/layout/attachFitCount.ts","../src/listbox/attachChecklist.ts","../src/overlay/overlayStack.ts","../src/overlay/placeOverlay.ts","../src/writingDirection.ts","../src/overlay/attachOverlay.ts","../src/rowVirtualizer.ts","../src/scheduleTimeout.ts","../src/step/attachHoldRepeat.ts","../src/step/attachStepKeys.ts","../src/text/attachAutoGrow.ts","../src/text/applyEdit.ts","../src/text/attachTextInput.ts","../src/toggle/attachToggle.ts","../src/segments/attachSegments.ts"],"sourcesContent":["/** A live region to report changes through. */\nexport interface LiveAnnouncer {\n /**\n * Has assistive technology read `text` out, politely — after whatever it is\n * already saying. The same text twice in a row is read twice.\n */\n readonly announce: (text: string) => void;\n /** Removes the live region. */\n readonly destroy: () => void;\n}\n\nexport interface LiveAnnouncerOptions {\n /**\n * The class on the live region, which the stylesheet clips to nothing\n * while leaving it in the accessibility tree. Defaults to\n * `\"gridkit-forms-sr-only\"`, which forms.css defines.\n */\n readonly className?: string | undefined;\n}\n\n/** Whitespace to a screen reader, but a change to the text it is watching. */\nconst NO_BREAK_SPACE = String.fromCodePoint(0xa0);\n\n/**\n * Creates a live region to report through — a reorder, a resize, a bulk\n * selection, anything no visual cue can carry to a screen reader — as the\n * last child of `container`.\n *\n * Polite rather than assertive, so an announcement waits for a pause instead\n * of cutting across what the user is already hearing. The element carries\n * `options.className`, a visually hidden class.\n *\n * A live region speaks only when its text changes, so a message identical to\n * the last would go unheard. A no-break space, added and dropped in turn,\n * makes the repeat a change without changing what is read.\n */\nexport function createLiveAnnouncer(\n container: HTMLElement = document.body,\n options: LiveAnnouncerOptions = {},\n): LiveAnnouncer {\n const region = document.createElement(\"div\");\n region.className = options.className ?? \"gridkit-forms-sr-only\";\n region.setAttribute(\"role\", \"status\");\n region.setAttribute(\"aria-live\", \"polite\");\n container.append(region);\n\n let last = \"\";\n let padded = false;\n\n return {\n announce(text) {\n padded = text === last && !padded;\n last = text;\n region.textContent = padded ? text + NO_BREAK_SPACE : text;\n },\n destroy() {\n region.remove();\n },\n };\n}\n","export interface FocusGroupOptions {\n /**\n * Focus left the group: by Tab or Shift+Tab (`\"tab\"`), or any other way\n * (`\"blur\"`), the window losing focus included.\n */\n readonly onLeave: (by: \"tab\" | \"blur\", nativeEvent: FocusEvent) => void;\n /**\n * Whether `node`, outside the group's root, still counts as inside the\n * group: a popup the input opened, portalled to the body. Focus moving\n * there is not a leave; focus moving on from there to anywhere that is\n * neither the root nor inside is.\n */\n readonly isInside?: ((node: Node) => boolean) | undefined;\n}\n\nexport interface AttachedFocusGroup {\n /** Replaces the options, from the next event on. */\n readonly setOptions: (options: FocusGroupOptions) => void;\n /** Removes every listener. */\n readonly detach: () => void;\n}\n\n/**\n * Tells focus moving between the controls inside `root` (the two ends of\n * a range) from focus leaving it, which a control's own blur cannot: a\n * `focusout` whose `relatedTarget` is outside `root`, or none, leaves the\n * group. A Tab that nothing prevented, pressed in the group just before,\n * makes it a leave by Tab.\n *\n * Focus moving to a node `isInside` names (a popup outside `root`) is not\n * a leave. While focus is out there, the group follows it on the document:\n * back into `root` it is home again, and anywhere else that is not inside\n * leaves the group.\n *\n * It holds whether the last key pressed in the group was such a Tab,\n * cleared by the next `focusout`, key or pointer press, and, while focus\n * is in a node `isInside` names, the document listeners that follow it.\n */\nexport function attachFocusGroup(\n root: HTMLElement,\n initialOptions: FocusGroupOptions,\n): AttachedFocusGroup {\n let options = initialOptions;\n let tabbing = false;\n let away: AbortController | null = null;\n const listeners = new AbortController();\n const { signal } = listeners;\n\n const isInside = (node: Node): boolean =>\n root.contains(node) || options.isInside?.(node) === true;\n\n function comeHome(): void {\n away?.abort();\n away = null;\n }\n\n function onKeyDown(event: KeyboardEvent): void {\n tabbing = event.key === \"Tab\" && !event.defaultPrevented;\n }\n\n function onPointerDown(): void {\n tabbing = false;\n }\n\n /** Focus has gone to a node `isInside` names, outside `root`: follow it. */\n function goAway(): void {\n if (away !== null) {\n return;\n }\n away = new AbortController();\n const document = root.ownerDocument;\n document.addEventListener(\n \"focusin\",\n (event) => {\n const { target } = event;\n if (!(target instanceof Node)) {\n return;\n }\n if (root.contains(target)) {\n comeHome();\n return;\n }\n if (isInside(target)) {\n return;\n }\n const by = tabbing ? \"tab\" : \"blur\";\n tabbing = false;\n comeHome();\n options.onLeave(by, event);\n },\n { signal: away.signal },\n );\n // Keys and presses in the popup tell a Tab out of it from any other leave.\n document.addEventListener(\n \"keydown\",\n (event) => {\n if (event.target instanceof Node && !root.contains(event.target)) {\n onKeyDown(event);\n }\n },\n { signal: away.signal },\n );\n document.addEventListener(\"pointerdown\", onPointerDown, {\n signal: away.signal,\n });\n }\n\n root.addEventListener(\"keydown\", onKeyDown, { signal });\n root.addEventListener(\"pointerdown\", onPointerDown, { signal });\n root.addEventListener(\n \"focusout\",\n (event) => {\n const by = tabbing ? \"tab\" : \"blur\";\n tabbing = false;\n const next = event.relatedTarget;\n if (next instanceof Node && root.contains(next)) {\n return;\n }\n if (next instanceof Node && isInside(next)) {\n goAway();\n return;\n }\n options.onLeave(by, event);\n },\n { signal },\n );\n\n return {\n setOptions: (next) => {\n options = next;\n },\n detach: () => {\n listeners.abort();\n comeHome();\n },\n };\n}\n","/** The form controls that take part in a form's validation and navigation. */\ntype FormControl = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;\n\n/** Input types Enter moves on from: single-line text, a checkbox, a switch. */\nconst ENTER_MOVES_FROM = new Set([\n \"text\",\n \"search\",\n \"email\",\n \"tel\",\n \"url\",\n \"password\",\n \"number\",\n \"checkbox\",\n]);\n\n/** Input types that hold no value a user types or picks. */\nconst NOT_EDITABLE = new Set([\"hidden\", \"button\", \"submit\", \"reset\", \"image\"]);\n\nfunction isFormControl(element: Element): element is FormControl {\n return (\n element.localName === \"input\" ||\n element.localName === \"select\" ||\n element.localName === \"textarea\"\n );\n}\n\n/** The controls of `form`, its `form`-attribute ones included, in document order. */\nfunction controlsOf(form: HTMLFormElement): FormControl[] {\n return [...form.elements].filter(isFormControl);\n}\n\n/**\n * The first control of `form`, in document order, that holds an invalid\n * value: a field showing an error, which forms sets as the control's\n * custom validity, or a native constraint of the app's own control such as\n * `required`. `null` when every control is valid. A disabled or read-only\n * control is never invalid, as for the browser's own validation.\n */\nexport function findFirstInvalidControl(\n form: HTMLFormElement,\n): HTMLElement | null {\n return (\n controlsOf(form).find(\n (control) => control.willValidate && !control.validity.valid,\n ) ?? null\n );\n}\n\n/**\n * The control a link to `target` should focus: `target` itself when it can\n * take focus, else the first control inside it, as for a group of inputs.\n */\nexport function focusTargetIn(target: HTMLElement): HTMLElement | null {\n if (isFormControl(target) || target.matches(\"button, [tabindex]\")) {\n return target;\n }\n return target.querySelector<HTMLElement>(\n \"input:not([type=hidden]), select, textarea, button, [tabindex]\",\n );\n}\n\n/** Whether a control can be moved to: enabled, editable and drawn. */\nfunction canMoveTo(control: FormControl): boolean {\n if (control instanceof HTMLInputElement && NOT_EDITABLE.has(control.type)) {\n return false;\n }\n const readOnly =\n (\"readOnly\" in control && control.readOnly) ||\n control.getAttribute(\"aria-readonly\") === \"true\";\n return !control.disabled && !readOnly && control.getClientRects().length > 0;\n}\n\n/**\n * Makes Enter in a single-line text field, a checkbox or a switch of\n * `form` move focus to the next control a user can change, in document\n * order, rather than submit the form. From the last one, Enter submits as\n * it would without this. Enter with a modifier, while an input method is\n * composing, or already handled (a field refusing its commit prevents it)\n * is left alone, as are a textarea, a select, a button and a link.\n * `detach` removes the listener.\n */\nexport function attachEnterNavigation(form: HTMLFormElement): {\n readonly detach: () => void;\n} {\n function onKeyDown(event: KeyboardEvent): void {\n const { target } = event;\n if (\n event.key !== \"Enter\" ||\n event.defaultPrevented ||\n event.isComposing ||\n event.altKey ||\n event.ctrlKey ||\n event.metaKey ||\n event.shiftKey ||\n !(target instanceof HTMLInputElement) ||\n !ENTER_MOVES_FROM.has(target.type)\n ) {\n return;\n }\n event.preventDefault();\n const controls = controlsOf(form);\n const next = controls\n .slice(controls.indexOf(target) + 1)\n .find((control) => canMoveTo(control));\n if (next === undefined) {\n form.requestSubmit();\n } else {\n next.focus();\n }\n }\n\n form.addEventListener(\"keydown\", onKeyDown);\n return {\n detach: () => {\n form.removeEventListener(\"keydown\", onKeyDown);\n },\n };\n}\n\n/**\n * Orders two elements as they come in the document, for sorting: negative\n * when `a` comes first.\n */\nexport function compareDocumentOrder(a: Node, b: Node): number {\n if (a === b) {\n return 0;\n }\n return a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING\n ? -1\n : 1;\n}\n","export interface FitCountOptions {\n /** The most items wanted side by side. */\n readonly max: number;\n /** Called with the count now, and again whenever it changes. */\n readonly onCount: (count: number) => void;\n}\n\nexport interface AttachedFitCount {\n /** Stops watching. */\n readonly detach: () => void;\n}\n\nfunction pixels(value: string): number {\n const parsed = Number.parseFloat(value);\n return Number.isNaN(parsed) ? 0 : parsed;\n}\n\n/**\n * Counts how many items as wide as `root`'s first child fit side by side\n * in the element around `root`, `root`'s column gap between them, from 1\n * to `max`: how many months a range calendar shows. It recounts whenever\n * that element or the item changes width (a `ResizeObserver`), and calls\n * `onCount` only when the count changes.\n *\n * It holds the observer and the last count; `detach` disconnects it.\n */\nexport function attachFitCount(\n root: HTMLElement,\n { max, onCount }: FitCountOptions,\n): AttachedFitCount {\n let count: number | null = null;\n const container = root.parentElement;\n\n function measure(): void {\n const item = root.firstElementChild;\n if (container === null || !(item instanceof HTMLElement)) {\n return;\n }\n const gap = pixels(getComputedStyle(root).columnGap);\n const room = container.clientWidth;\n const width = item.offsetWidth;\n const fits = width === 0 ? max : Math.floor((room + gap) / (width + gap));\n const next = Math.min(Math.max(fits, 1), max);\n if (next !== count) {\n count = next;\n onCount(next);\n }\n }\n\n const observer = new ResizeObserver(measure);\n if (container !== null) {\n observer.observe(container);\n }\n if (root.firstElementChild !== null) {\n observer.observe(root.firstElementChild);\n }\n measure();\n\n return {\n detach: () => {\n observer.disconnect();\n },\n };\n}\n","export interface ChecklistOptions {\n /**\n * The item at `index` — its place in the whole list — asks to be checked\n * or unchecked: Space on it, or a click. The caller flips it in its own\n * state and draws the new `aria-checked`.\n */\n readonly onToggle: (index: number) => void;\n /** Focus moved to the item at `index`, by a key, a click or a script. */\n readonly onFocusChange?: ((index: number) => void) | undefined;\n /**\n * Bring the item at `index` into view, mounting it if the list's window\n * does not hold it. A virtualized renderer forwards this to its\n * virtualizer's `scrollToIndex`, with `{ block: \"nearest\" }` so a move of\n * one item scrolls by one item.\n */\n readonly scrollToIndex: (index: number) => void;\n}\n\nexport interface AttachedChecklist {\n /**\n * How many items the whole list holds, mounted or not. Starts at 0, so a\n * renderer calls this straight after attaching, and again whenever the\n * list changes — a search narrowing it, say. A focused place past the new\n * end moves back to the last item, and so does a move still waiting for\n * an item past it.\n */\n readonly setCount: (count: number) => void;\n /**\n * Focuses the item at `index`, clamped to the list, scrolling to it first.\n * An item outside the mounted window is focused once it mounts.\n */\n readonly focusItem: (index: number) => void;\n /**\n * Removes every listener and observer. The list and its items keep their\n * `tabindex`.\n * After it, `setCount` and `focusItem` do nothing: they neither scroll\n * nor focus, and a move still waiting for its item is dropped.\n */\n readonly detach: () => void;\n}\n\nconst ITEM = \"[data-gridkit-checklist-item]\";\nconst INDEX = \"data-gridkit-checklist-index\";\n\n/**\n * Where focus is going besides the focused place: nowhere, to an item a move\n * is waiting to see mounted, or nowhere ever again once detached.\n */\ntype ChecklistState =\n | { readonly kind: \"settled\" }\n | { readonly kind: \"awaiting-item\"; readonly index: number }\n | { readonly kind: \"detached\" };\n\nconst SETTLED: ChecklistState = { kind: \"settled\" };\nconst DETACHED: ChecklistState = { kind: \"detached\" };\n\nfunction indexOf(item: Element): number {\n return Number(item.getAttribute(INDEX));\n}\n\n/**\n * Makes `list` — a `role=\"listbox\"` the renderer drew, usually virtualized\n * so that only a window of a long list is mounted — behave as a\n * multi-select checklist with one tab stop: the arrow keys, Home, End,\n * PageUp and PageDown move focus among its items, and Space or a click asks\n * for the focused item to be toggled. It decides; the caller is told through\n * the callbacks and draws the outcome, `aria-checked` included.\n *\n * Items are the list's descendants with `data-gridkit-checklist-item` and a\n * `data-gridkit-checklist-index`: their place in the whole list rather than\n * in the window, since an item's place is all that survives it being\n * unmounted and mounted again. The list is the element that scrolls: PageUp\n * and PageDown move by as many items as it shows whole.\n *\n * One item at a time has `tabindex=\"0\"` — the focused one, or the first\n * mounted while the focused one is scrolled away — and the rest `-1`, kept\n * so as items mount by an observer of the list's children rather than by\n * the renderer. The list itself gets `tabindex=\"-1\"`: a browser may make an\n * element that scrolls a tab stop of its own, as Firefox does, which would\n * put a second stop before the items' one, on an element the keys do not\n * move from. A move to an item outside the window asks `scrollToIndex`\n * for it and focuses it once it mounts, unless focus has gone somewhere\n * else in the meantime.\n *\n * Enter is not handled, so a form around the list hears it and applies;\n * Escape is the overlay stack's.\n */\nexport function attachChecklist(\n list: HTMLElement,\n options: ChecklistOptions,\n): AttachedChecklist {\n let count = 0;\n /** The focused place in the whole list: the tab stop, mounted or not. */\n let active = 0;\n let state: ChecklistState = SETTLED;\n\n function items(): HTMLElement[] {\n return Array.from(list.querySelectorAll<HTMLElement>(ITEM));\n }\n\n function itemAt(index: number): HTMLElement | null {\n return list.querySelector<HTMLElement>(\n `${ITEM}[${INDEX}=\"${String(index)}\"]`,\n );\n }\n\n function itemOf(target: EventTarget | null): HTMLElement | null {\n const item =\n target instanceof Element ? target.closest<HTMLElement>(ITEM) : null;\n return item !== null && list.contains(item) ? item : null;\n }\n\n function setTabStop(): void {\n const all = items();\n const stop = all.find((item) => indexOf(item) === active) ?? all[0];\n for (const item of all) {\n item.tabIndex = item === stop ? 0 : -1;\n }\n }\n\n function makeActive(index: number): void {\n if (index !== active) {\n active = index;\n options.onFocusChange?.(index);\n }\n }\n\n function moveTo(index: number): void {\n if (state.kind === \"detached\" || count === 0) {\n return;\n }\n const target = Math.max(0, Math.min(index, count - 1));\n makeActive(target);\n setTabStop();\n options.scrollToIndex(target);\n const item = itemAt(target);\n if (item === null) {\n state = { kind: \"awaiting-item\", index: target };\n } else {\n state = SETTLED;\n item.focus({ preventScroll: true });\n }\n }\n\n /** How many items the list shows whole, for PageUp and PageDown. */\n function pageSize(): number {\n const top = list.getBoundingClientRect().top + list.clientTop;\n const bottom = top + list.clientHeight;\n const whole = items().filter((item) => {\n const box = item.getBoundingClientRect();\n return box.top >= top && box.bottom <= bottom;\n }).length;\n return Math.max(1, whole);\n }\n\n // Every key it acts on is taken, so the list does not also scroll by\n // itself. A modified key is left for whatever shortcut it is. Moves count\n // from the focused place rather than the focused element, which lags\n // behind while a move waits for its item to mount.\n function onKeyDown(event: KeyboardEvent): void {\n const item = itemOf(event.target);\n if (\n item === null ||\n event.isComposing ||\n event.altKey ||\n event.ctrlKey ||\n event.metaKey ||\n event.shiftKey\n ) {\n return;\n }\n switch (event.key) {\n case \"ArrowDown\":\n moveTo(active + 1);\n break;\n case \"ArrowUp\":\n moveTo(active - 1);\n break;\n case \"Home\":\n moveTo(0);\n break;\n case \"End\":\n moveTo(count - 1);\n break;\n case \"PageDown\":\n moveTo(active + pageSize());\n break;\n case \"PageUp\":\n moveTo(active - pageSize());\n break;\n case \" \":\n // Held down, Space toggles once, as a checkbox does.\n if (!event.repeat) {\n options.onToggle(indexOf(item));\n }\n break;\n default:\n return;\n }\n event.preventDefault();\n }\n\n // However focus arrived — Tab, a click, a script — the tab stop follows it,\n // and a move still waiting for its item gives way.\n function onFocusIn(event: FocusEvent): void {\n const item = itemOf(event.target);\n if (item !== null) {\n state = SETTLED;\n makeActive(indexOf(item));\n setTabStop();\n }\n }\n\n function onClick(event: MouseEvent): void {\n const item = itemOf(event.target);\n if (item !== null) {\n options.onToggle(indexOf(item));\n item.focus({ preventScroll: true });\n }\n }\n\n // The item a move waits for takes focus only if focus is still in the\n // list, or dropped to nothing when the item it was on unmounted.\n function focusAwaitedItemIfMounted(): void {\n const item = state.kind === \"awaiting-item\" ? itemAt(state.index) : null;\n if (item === null) {\n return;\n }\n state = SETTLED;\n const focused = document.activeElement;\n if (\n focused === null ||\n focused === document.body ||\n list.contains(focused)\n ) {\n item.focus({ preventScroll: true });\n }\n }\n\n // Items mount and unmount as the window moves, and a kept element can take\n // another place when the list changes under it.\n const observer = new MutationObserver(() => {\n setTabStop();\n focusAwaitedItemIfMounted();\n });\n observer.observe(list, {\n childList: true,\n subtree: true,\n attributeFilter: [INDEX],\n });\n\n list.tabIndex = -1;\n setTabStop();\n list.addEventListener(\"keydown\", onKeyDown);\n list.addEventListener(\"focusin\", onFocusIn);\n list.addEventListener(\"click\", onClick);\n\n return {\n setCount(next) {\n if (state.kind === \"detached\") {\n return;\n }\n count = next;\n active = Math.max(0, Math.min(active, count - 1));\n if (state.kind === \"awaiting-item\") {\n state =\n count === 0\n ? SETTLED\n : {\n kind: \"awaiting-item\",\n index: Math.min(state.index, count - 1),\n };\n }\n setTabStop();\n focusAwaitedItemIfMounted();\n },\n focusItem: moveTo,\n detach() {\n state = DETACHED;\n observer.disconnect();\n list.removeEventListener(\"keydown\", onKeyDown);\n list.removeEventListener(\"focusin\", onFocusIn);\n list.removeEventListener(\"click\", onClick);\n },\n };\n}\n","/** What the stack needs of an attached overlay. */\nexport interface StackedOverlay {\n readonly panel: HTMLElement;\n /** Escape was pressed while this was the topmost overlay. */\n readonly onEscape: () => void;\n /** An overlay below this one detached, so this one has to go too. */\n readonly onParentDetached: () => void;\n}\n\n/** The stack and the one Escape listener that serves it. */\ninterface OverlayStack {\n /**\n * Every attached overlay, in the order it attached: a submenu opened from\n * a menu sits above it.\n */\n readonly overlays: StackedOverlay[];\n readonly onKeyDown: (event: KeyboardEvent) => void;\n}\n\nconst STACK_KEY = Symbol.for(\"@gridkitjs/overlay-stack\");\n\n/*\n * One listener for the whole stack, on `window` in the capture phase: the\n * first place a key event reaches, so neither React's root listener nor a\n * page's own Escape handler hears an Escape the topmost overlay took. An\n * Escape that ends an IME composition is the input method's, not ours.\n */\nfunction createStack(): OverlayStack {\n const overlays: StackedOverlay[] = [];\n return {\n overlays,\n onKeyDown: (event) => {\n const topmost = overlays.at(-1);\n if (\n event.key !== \"Escape\" ||\n event.isComposing ||\n topmost === undefined\n ) {\n return;\n }\n event.preventDefault();\n event.stopPropagation();\n topmost.onEscape();\n },\n };\n}\n\n/**\n * The page's one stack, made on first use. On `globalThis` because overlays\n * from separately bundled packages must nest.\n */\nfunction pageStack(): OverlayStack {\n const holder = globalThis as Partial<Record<symbol, OverlayStack>>;\n const stack = holder[STACK_KEY] ?? createStack();\n holder[STACK_KEY] = stack;\n return stack;\n}\n\n/** Puts `overlay` on top of the stack. */\nexport function pushOverlay(overlay: StackedOverlay): void {\n const { overlays, onKeyDown } = pageStack();\n if (overlays.length === 0) {\n window.addEventListener(\"keydown\", onKeyDown, true);\n }\n overlays.push(overlay);\n}\n\n/**\n * Takes `overlay` off the stack, and every overlay above it with it — each\n * told through `onParentDetached`, topmost first, so a submenu never outlives\n * the menu it opened from. Does nothing for an overlay no longer on it.\n */\nexport function removeOverlay(overlay: StackedOverlay): void {\n const { overlays, onKeyDown } = pageStack();\n const index = overlays.indexOf(overlay);\n if (index === -1) {\n return;\n }\n const above = overlays.splice(index).slice(1).reverse();\n for (const child of above) {\n child.onParentDetached();\n }\n if (overlays.length === 0) {\n window.removeEventListener(\"keydown\", onKeyDown, true);\n }\n}\n\n/** Whether `target` is inside an overlay that sits above `overlay`. */\nexport function isInsideOverlayAbove(\n overlay: StackedOverlay,\n target: Node,\n): boolean {\n const { overlays } = pageStack();\n const index = overlays.indexOf(overlay);\n return (\n index !== -1 &&\n overlays.slice(index + 1).some((above) => above.panel.contains(target))\n );\n}\n","import type { WritingDirection } from \"@gridkitjs/forms-core\";\n\n/** Which side of its anchor an overlay opens on. */\nexport type OverlaySide = \"top\" | \"bottom\" | \"left\" | \"right\";\n\n/**\n * Which edge of the anchor the overlay lines up with along that side: its\n * left edge (`start`) or right edge (`end`) for `top`/`bottom`, its top or\n * bottom edge for `left`/`right`.\n */\nexport type OverlayAlign = \"start\" | \"end\";\n\nexport type OverlayPlacement = `${OverlaySide}-${OverlayAlign}`;\n\n/** A box in viewport coordinates, as `getBoundingClientRect` reports one. */\nexport interface OverlayRect {\n readonly top: number;\n readonly left: number;\n readonly width: number;\n readonly height: number;\n}\n\nexport interface OverlaySize {\n readonly width: number;\n readonly height: number;\n}\n\nexport interface OverlayPlacementOptions {\n /** Where the overlay would rather open. Defaults to `\"bottom-start\"`. */\n readonly placement?: OverlayPlacement | undefined;\n /** Space between the anchor and the overlay, in pixels. Defaults to `0`. */\n readonly gap?: number | undefined;\n /**\n * Pixels to shift the overlay along the anchor's edge — down beside a\n * `left`/`right` side, right beside `top`/`bottom`; negative goes the other\n * way. A submenu opened `right-start` takes its own top padding, negated,\n * so its first item lines up with the item that opened it. The overlay is\n * still kept on screen. Defaults to `0`.\n */\n readonly offset?: number | undefined;\n /**\n * The writing direction the placement is read in. `\"rtl\"` mirrors it, as\n * a right-to-left page is mirrored: `left` and `right` swap, `start` and\n * `end` beside `top` or `bottom` are the anchor's right and left edges, an\n * `offset` along those sides runs leftward, and an overlay wider than the\n * viewport keeps its right edge in view. The placement it ends up with is\n * reported in the same mirrored terms, so `\"bottom-start\"` lines up with\n * the anchor's inline start and `\"right-start\"` opens a submenu toward\n * the inline end in either direction. Defaults to `\"ltr\"`.\n */\n readonly direction?: WritingDirection | undefined;\n}\n\n/** Where an overlay goes: its top-left corner, and the placement it ended up with. */\nexport interface OverlayPosition {\n readonly top: number;\n readonly left: number;\n readonly placement: OverlayPlacement;\n}\n\nconst OPPOSITE_SIDE: Readonly<Record<OverlaySide, OverlaySide>> = {\n top: \"bottom\",\n bottom: \"top\",\n left: \"right\",\n right: \"left\",\n};\n\nfunction isVertical(side: OverlaySide): boolean {\n return side === \"top\" || side === \"bottom\";\n}\n\n/** How much room `side` of `anchor` leaves before the viewport's edge. */\nfunction roomBeside(\n side: OverlaySide,\n anchor: OverlayRect,\n viewport: OverlaySize,\n): number {\n switch (side) {\n case \"top\":\n return anchor.top;\n case \"bottom\":\n return viewport.height - (anchor.top + anchor.height);\n case \"left\":\n return anchor.left;\n case \"right\":\n return viewport.width - (anchor.left + anchor.width);\n }\n}\n\n/**\n * The preferred side if the overlay fits there, the opposite one if it fits\n * there instead, and otherwise whichever has more room — a menu too tall for\n * either still shows as much of itself as it can.\n */\nfunction chooseSide(\n preferred: OverlaySide,\n needed: number,\n anchor: OverlayRect,\n viewport: OverlaySize,\n): OverlaySide {\n const opposite = OPPOSITE_SIDE[preferred];\n const room = roomBeside(preferred, anchor, viewport);\n const oppositeRoom = roomBeside(opposite, anchor, viewport);\n if (room >= needed) {\n return preferred;\n }\n return oppositeRoom >= needed || oppositeRoom > room ? opposite : preferred;\n}\n\n/** The preferred edge unless only the other one keeps the overlay on screen. */\nfunction chooseAlign(\n preferred: OverlayAlign,\n fitsAtStart: boolean,\n fitsAtEnd: boolean,\n): OverlayAlign {\n if (preferred === \"start\") {\n return fitsAtStart || !fitsAtEnd ? \"start\" : \"end\";\n }\n return fitsAtEnd || !fitsAtStart ? \"end\" : \"start\";\n}\n\n/** The overlay's offset away from the anchor: its top for `top`/`bottom`, its left otherwise. */\nfunction offsetBeside(\n side: OverlaySide,\n anchor: OverlayRect,\n panel: OverlaySize,\n gap: number,\n): number {\n switch (side) {\n case \"top\":\n return anchor.top - gap - panel.height;\n case \"bottom\":\n return anchor.top + anchor.height + gap;\n case \"left\":\n return anchor.left - gap - panel.width;\n case \"right\":\n return anchor.left + anchor.width + gap;\n }\n}\n\n/** Keeps `value` within `[0, limit]`, pinning to `0` when even that fails. */\nfunction clampIntoView(value: number, limit: number): number {\n return Math.max(0, Math.min(value, limit));\n}\n\n/**\n * Where an overlay of size `panel` goes beside `anchor` so that it stays in\n * `viewport`: on the preferred side unless only the opposite one has room,\n * lined up with the preferred edge unless that runs it off screen and the\n * other edge does not, and finally pushed back inside if it still overflows.\n * Pure, so the rules are testable without a browser; `attachOverlay` feeds it\n * the measurements.\n *\n * A point — a context menu opened where the pointer is — is an anchor with\n * no width or height, which is what makes `start`/`end` mean \"after\" and\n * \"before\" it.\n *\n * In `\"rtl\"` the anchor is mirrored across the viewport, placed as in\n * left-to-right, and the result mirrored back, so every rule above holds\n * with left and right exchanged.\n */\nexport function placeOverlay(\n anchor: OverlayRect,\n panel: OverlaySize,\n viewport: OverlaySize,\n options: OverlayPlacementOptions = {},\n): OverlayPosition {\n if (options.direction !== \"rtl\") {\n return placeLeftToRight(anchor, panel, viewport, options);\n }\n const mirrored = placeLeftToRight(\n { ...anchor, left: viewport.width - anchor.left - anchor.width },\n panel,\n viewport,\n options,\n );\n return {\n ...mirrored,\n left: viewport.width - mirrored.left - panel.width,\n };\n}\n\nfunction placeLeftToRight(\n anchor: OverlayRect,\n panel: OverlaySize,\n viewport: OverlaySize,\n options: OverlayPlacementOptions,\n): OverlayPosition {\n const [preferredSide, preferredAlign] = (\n options.placement ?? \"bottom-start\"\n ).split(\"-\") as [OverlaySide, OverlayAlign];\n const gap = options.gap ?? 0;\n const offset = options.offset ?? 0;\n const vertical = isVertical(preferredSide);\n\n const side = chooseSide(\n preferredSide,\n (vertical ? panel.height : panel.width) + gap,\n anchor,\n viewport,\n );\n\n // The axis the overlay runs along beside the anchor, shifted by the offset\n // before an edge is chosen, so the shifted overlay is what has to fit.\n const anchorStart = (vertical ? anchor.left : anchor.top) + offset;\n const anchorEnd = anchorStart + (vertical ? anchor.width : anchor.height);\n const extent = vertical ? panel.width : panel.height;\n const room = vertical ? viewport.width : viewport.height;\n const align = chooseAlign(\n preferredAlign,\n anchorStart + extent <= room,\n anchorEnd - extent >= 0,\n );\n const along = align === \"start\" ? anchorStart : anchorEnd - extent;\n const away = offsetBeside(side, anchor, panel, gap);\n\n return {\n top: clampIntoView(vertical ? away : along, viewport.height - panel.height),\n left: clampIntoView(vertical ? along : away, viewport.width - panel.width),\n placement: `${side}-${align}`,\n };\n}\n","import type { WritingDirection } from \"@gridkitjs/forms-core\";\n\n/**\n * The way `element`'s lines run, from its computed `direction`: what it\n * inherits from a `dir` attribute on it or an ancestor, or from the CSS\n * `direction` property. Read afresh on every call, never kept, so a page\n * whose direction changes is followed from the next key press, gesture or\n * overlay on.\n */\nexport function writingDirection(element: Element): WritingDirection {\n return getComputedStyle(element).direction === \"rtl\" ? \"rtl\" : \"ltr\";\n}\n","import {\n isInsideOverlayAbove,\n pushOverlay,\n removeOverlay,\n type StackedOverlay,\n} from \"./overlayStack\";\nimport {\n placeOverlay,\n type OverlayPlacementOptions,\n type OverlayRect,\n} from \"./placeOverlay\";\nimport { writingDirection } from \"../writingDirection\";\n\n/** What an overlay opens beside: an element, or a point in viewport coordinates. */\nexport type OverlayAnchor =\n Element | { readonly x: number; readonly y: number };\n\n/**\n * Where focus goes when an overlay attaches: its first focusable descendant,\n * the panel itself, nowhere — focus stays where it was — or a given element.\n */\nexport type OverlayInitialFocus = \"first\" | \"panel\" | \"none\" | HTMLElement;\n\n/** Why an overlay asked to close. */\nexport type OverlayDismissReason =\n \"escape\" | \"outside\" | \"scroll\" | \"resize\" | \"blur\" | \"parent\";\n\nexport interface OverlayOptions extends OverlayPlacementOptions {\n /**\n * The overlay asks to close: Escape was pressed while it was the topmost\n * overlay, a pointer went down outside it, something outside it scrolled,\n * the window resized or lost focus, focus moved outside it, or the overlay\n * it was opened above detached. The caller closes it — removes the panel\n * and detaches — or keeps it open by doing nothing, except after\n * `\"parent\"`, which detaches it regardless.\n */\n readonly onDismiss: (reason: OverlayDismissReason) => void;\n /**\n * Where focus goes on attaching. Defaults to `\"first\"`: a menu focuses its\n * first item. A panel whose first control is not where the user starts — a\n * filter editor's operator picker before its value box — passes that\n * element, or `\"panel\"` to land on the panel itself; `\"none\"` leaves focus\n * where it was, as a suggestion list does while typing goes on in the\n * field that opened it.\n */\n readonly initialFocus?: OverlayInitialFocus | undefined;\n /**\n * Where focus goes when the overlay detaches. Defaults to the element that\n * had focus when it attached; `null` leaves focus alone, unless\n * `returnFocusFallback` names somewhere.\n */\n readonly returnFocusTo?: HTMLElement | null | undefined;\n /**\n * Where focus goes when there is nothing to return it to as the overlay\n * detaches: `returnFocusTo` is `null`, or has left the page — the button a\n * menu opened from, taken away by what the menu ran. Called then, so it\n * can name what is on the page by that time; returning `null` leaves focus\n * alone. Like the return itself, it applies only while focus is still in\n * the panel, in an overlay above it, or nowhere.\n */\n readonly returnFocusFallback?: (() => HTMLElement | null) | undefined;\n /**\n * Whether a scroll outside the panel just after input inside it — an\n * `input` or `change` event, in the two animation frames that follow it —\n * leaves it open. A panel whose controls change the page under it opts\n * in: a column chooser hiding a column narrows the grid it opened from,\n * and the browser scrolls that grid back within its narrower content.\n * Defaults to `false`, where every scroll outside the panel dismisses it.\n */\n readonly ignoreScrollAfterInput?: boolean | undefined;\n /**\n * Whether Tab and Shift+Tab stay inside the panel: from its last tabbable\n * element Tab moves to its first, and Shift+Tab from its first to its last,\n * as a dialog keeps them. Defaults to `false`, where tabbing out of the\n * panel moves focus outside it, which dismisses it with `\"blur\"`. Only\n * the keys are kept: a pointer down outside still dismisses it, and so\n * does focus moved out by any other route.\n */\n readonly trapFocus?: boolean | undefined;\n}\n\n/** Everything focusable by script, so a menu's `tabindex=\"-1\"` items count. */\nconst FOCUSABLE =\n \"a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]\";\n\n/**\n * What Tab stops on in `panel`, in document order: what is focusable without\n * a negative `tabindex`, enabled and shown.\n */\nfunction tabbables(panel: HTMLElement): HTMLElement[] {\n return Array.from(panel.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(\n (element) =>\n element.tabIndex >= 0 &&\n !element.matches(\":disabled\") &&\n element.checkVisibility({ visibilityProperty: true }),\n );\n}\n\nfunction anchorRect(anchor: OverlayAnchor): OverlayRect {\n if (anchor instanceof Element) {\n const { top, left, width, height } = anchor.getBoundingClientRect();\n return { top, left, width, height };\n }\n return { top: anchor.y, left: anchor.x, width: 0, height: 0 };\n}\n\n/**\n * The element `initialFocus` names, or `null` for none. The panel stands in\n * for a first focusable descendant it does not have, given `tabindex=\"-1\"`\n * when it has no `tabindex` of its own so that it can take focus.\n */\nfunction initialFocusTarget(\n panel: HTMLElement,\n initialFocus: OverlayInitialFocus,\n): HTMLElement | null {\n if (initialFocus === \"none\") {\n return null;\n }\n if (initialFocus instanceof HTMLElement) {\n return initialFocus;\n }\n const first =\n initialFocus === \"first\"\n ? panel.querySelector<HTMLElement>(FOCUSABLE)\n : null;\n if (first !== null) {\n return first;\n }\n if (!panel.hasAttribute(\"tabindex\")) {\n panel.tabIndex = -1;\n }\n return panel;\n}\n\n/**\n * Shows `panel` as an overlay beside `anchor` — a menu, a popover, a filter\n * editor — and returns the function that ends it. The caller renders the\n * panel, usually as a child of `document.body` so no scrolling ancestor clips\n * it; this positions it, moves focus into it, and reports through\n * `onDismiss` when the user is done with it.\n *\n * The panel is positioned `fixed`, at the place `placeOverlay` picks from the\n * anchor's and the panel's measured boxes, and carries that placement in\n * `data-gridkit-placement` (`\"top-start\"` once flipped above, say) for a\n * stylesheet to point an arrow by. Whenever the panel's size changes — a list\n * that shrinks under a search — it is placed again beside the anchor, so a\n * panel flipped above its anchor keeps its bottom edge there — or beside\n * where the anchor was, once it has left the page. Focus moves\n * where `initialFocus` says.\n *\n * The placement is read in the panel's own writing direction unless\n * `direction` names one, so a panel laid out right to left — given\n * `dir=\"rtl\"`, or rendered into a right-to-left page — opens toward the\n * inline end of what it is drawn in. A renderer portalling the panel out of\n * a right-to-left grid in a left-to-right page sets `dir` on it from the\n * grid, which mirrors its content and its placement together.\n *\n * Nothing that happens on or in the anchor dismisses the overlay, so a button\n * that toggles it can close it with its own click rather than having the\n * overlay close and the click reopen it.\n *\n * Overlays stack in the order they attach. Escape belongs to the topmost\n * alone, which takes it: it closes a submenu without closing the menu under\n * it, and nothing else on the page — a grid that clears its selection on\n * Escape — hears it. An overlay counts everything in the overlays above it\n * as inside itself, so a click in a submenu keeps its menu open while a click\n * elsewhere in the menu closes only the submenu.\n *\n * Detaching removes every listener and returns focus, but only when focus is\n * still in the panel, in an overlay above it, or nowhere — a click that\n * dismissed it by landing on another control leaves focus on that control.\n * Focus goes to `returnFocusFallback` instead when the element it would\n * return to has left the page.\n * Any overlay still above it is dismissed with `\"parent\"` and detached first.\n */\nexport function attachOverlay(\n anchor: OverlayAnchor,\n panel: HTMLElement,\n options: OverlayOptions,\n): () => void {\n const { onDismiss } = options;\n const returnFocusTo =\n options.returnFocusTo === undefined\n ? document.activeElement instanceof HTMLElement\n ? document.activeElement\n : null\n : options.returnFocusTo;\n\n const stacked: StackedOverlay = {\n panel,\n onEscape: () => {\n onDismiss(\"escape\");\n },\n onParentDetached: () => {\n onDismiss(\"parent\");\n detach();\n },\n };\n\n /** In the panel, or in an overlay opened above it. */\n function inside(target: EventTarget | null): boolean {\n return (\n target instanceof Node &&\n (panel.contains(target) || isInsideOverlayAbove(stacked, target))\n );\n }\n\n function belongs(target: EventTarget | null): boolean {\n return (\n inside(target) ||\n (anchor instanceof Element &&\n target instanceof Node &&\n anchor.contains(target))\n );\n }\n\n function onPointerDown(event: PointerEvent): void {\n if (!belongs(event.target)) {\n onDismiss(\"outside\");\n }\n }\n\n // Set from input in the panel until two frames have passed: the scroll an\n // input causes is dispatched by the frame after its layout, which may\n // itself wait for the next frame.\n let settlingFrame: number | null = null;\n function onInput(): void {\n if (settlingFrame !== null) {\n cancelAnimationFrame(settlingFrame);\n }\n settlingFrame = requestAnimationFrame(() => {\n settlingFrame = requestAnimationFrame(() => {\n settlingFrame = null;\n });\n });\n }\n\n // The overlay is placed in viewport coordinates, so a scroll that moves\n // its anchor leaves it behind — except a scroll inside the panel itself,\n // or one the panel's own input caused, when it asks for that. Only the\n // document or a scroller holding an element anchor moves it: a log\n // elsewhere on the page following its newest line does not.\n function movesAnchor(target: EventTarget | null): boolean {\n return (\n !(anchor instanceof Element) ||\n !(target instanceof Node) ||\n target.nodeType === Node.DOCUMENT_NODE ||\n target.contains(anchor)\n );\n }\n function onScroll(event: Event): void {\n if (\n !inside(event.target) &&\n settlingFrame === null &&\n movesAnchor(event.target)\n ) {\n onDismiss(\"scroll\");\n }\n }\n\n function onResize(): void {\n onDismiss(\"resize\");\n }\n\n // Only a move to somewhere definite counts: focus dropping to nothing, as\n // when the focused item re-renders away, is not the user leaving.\n function onFocusOut(event: FocusEvent): void {\n if (event.relatedTarget !== null && !belongs(event.relatedTarget)) {\n onDismiss(\"blur\");\n }\n }\n\n // Only the moves that would leave the panel are made here — Tab with\n // nothing tabbable after the focused element, Shift+Tab with nothing before\n // it — and every other Tab is the browser's own, in its own order. What is\n // tabbable is read on each key, so controls drawn since attaching count; an\n // overlay above that sits inside the panel keeps its own Tab.\n function onTrapKeyDown(event: KeyboardEvent): void {\n if (\n event.key !== \"Tab\" ||\n event.defaultPrevented ||\n event.altKey ||\n event.ctrlKey ||\n event.metaKey ||\n !(event.target instanceof Node) ||\n isInsideOverlayAbove(stacked, event.target)\n ) {\n return;\n }\n const stops = tabbables(panel).filter(\n (element) => !isInsideOverlayAbove(stacked, element),\n );\n const first = stops[0];\n const last = stops.at(-1);\n if (first === undefined || last === undefined) {\n event.preventDefault();\n return;\n }\n const position = event.target.compareDocumentPosition(\n event.shiftKey ? first : last,\n );\n const leaving = event.shiftKey\n ? (position & Node.DOCUMENT_POSITION_PRECEDING) === 0\n : (position & Node.DOCUMENT_POSITION_FOLLOWING) === 0;\n if (leaving) {\n event.preventDefault();\n (event.shiftKey ? last : first).focus();\n }\n }\n\n function onWindowBlur(): void {\n onDismiss(\"blur\");\n }\n\n // An anchor taken out of the page has no box to read — the header of a\n // column the panel itself just hid — so the panel goes on being placed\n // beside where it last was, rather than in the viewport's corner.\n let lastAnchorBox: OverlayRect | null = null;\n function anchorBox(): OverlayRect {\n if (\n lastAnchorBox === null ||\n !(anchor instanceof Element) ||\n anchor.isConnected\n ) {\n lastAnchorBox = anchorRect(anchor);\n }\n return lastAnchorBox;\n }\n\n // Measured fixed at the viewport's top-left corner, shrink-wrapped and with\n // the whole viewport to grow into — in normal flow a block panel would\n // report the full width of the page — and from that corner every time, so\n // placing it again measures it the way the first placing did.\n function place(): void {\n panel.style.top = \"0px\";\n panel.style.left = \"0px\";\n const { width, height } = panel.getBoundingClientRect();\n const position = placeOverlay(\n anchorBox(),\n { width, height },\n {\n width: document.documentElement.clientWidth,\n height: document.documentElement.clientHeight,\n },\n { ...options, direction: options.direction ?? writingDirection(panel) },\n );\n panel.style.top = `${String(position.top)}px`;\n panel.style.left = `${String(position.left)}px`;\n panel.setAttribute(\"data-gridkit-placement\", position.placement);\n }\n\n panel.style.position = \"fixed\";\n place();\n const resizeObserver = new ResizeObserver(place);\n resizeObserver.observe(panel);\n\n // On the stack before focus moves in, so the overlay below sees the focus\n // leaving it land inside an overlay above it rather than outside.\n pushOverlay(stacked);\n initialFocusTarget(panel, options.initialFocus ?? \"first\")?.focus({\n preventScroll: true,\n });\n\n document.addEventListener(\"pointerdown\", onPointerDown, true);\n window.addEventListener(\"scroll\", onScroll, { capture: true, passive: true });\n window.addEventListener(\"resize\", onResize);\n window.addEventListener(\"blur\", onWindowBlur);\n panel.addEventListener(\"focusout\", onFocusOut);\n if (options.trapFocus === true) {\n panel.addEventListener(\"keydown\", onTrapKeyDown);\n }\n if (options.ignoreScrollAfterInput === true) {\n panel.addEventListener(\"input\", onInput);\n panel.addEventListener(\"change\", onInput);\n }\n\n let attached = true;\n function detach(): void {\n if (!attached) {\n return;\n }\n attached = false;\n // Read before the overlays above close and hand focus back to wherever\n // they took it from, which may already have left the page with this panel.\n const active = document.activeElement;\n const focusInside =\n active === null || active === document.body || inside(active);\n removeOverlay(stacked);\n resizeObserver.disconnect();\n document.removeEventListener(\"pointerdown\", onPointerDown, true);\n window.removeEventListener(\"scroll\", onScroll, { capture: true });\n window.removeEventListener(\"resize\", onResize);\n window.removeEventListener(\"blur\", onWindowBlur);\n panel.removeEventListener(\"focusout\", onFocusOut);\n panel.removeEventListener(\"keydown\", onTrapKeyDown);\n panel.removeEventListener(\"input\", onInput);\n panel.removeEventListener(\"change\", onInput);\n if (settlingFrame !== null) {\n cancelAnimationFrame(settlingFrame);\n }\n\n if (!focusInside) {\n return;\n }\n const target =\n returnFocusTo?.isConnected === true\n ? returnFocusTo\n : options.returnFocusFallback?.();\n target?.focus({ preventScroll: true });\n }\n return detach;\n}\n","import { visibleRange, type VisibleRange } from \"@gridkitjs/forms-core\";\n\nexport interface RowVirtualizerOptions {\n /** The height assumed for a row not yet measured. */\n readonly estimatedRowHeight: number;\n /** Rows rendered beyond each edge of the visible area. */\n readonly overscan: number;\n /**\n * The window of rows to render moved: called whenever a scroll, a resize\n * of the scroll element, a measured row height or a change of rows moves\n * it, and never with a window equal to the last.\n */\n readonly onRange: (range: VisibleRange) => void;\n}\n\nexport interface RowVirtualizer {\n /** How many rows there are. Measured heights of the rows that remain are kept. */\n readonly setRowCount: (count: number) => void;\n /**\n * Forgets every measured height, for rows that are no longer the ones\n * measured. A `scrollToIndex` still waiting for its row is dropped too:\n * the row it asked for is no longer at that index.\n */\n readonly resetHeights: () => void;\n /**\n * A ref callback for the element of row `index` (its place among all the\n * rows, not among those rendered): measured while mounted, forgotten once\n * called with `null`. The same function for the same index every time, so\n * a renderer re-attaching it on every render costs nothing.\n */\n readonly measureRow: (index: number) => (element: HTMLElement | null) => void;\n /**\n * Reads the heights of rows already laid out, each paired with its index\n * among all the rows, and works out the window once for all of them: for\n * rows drawn before this virtualizer existed, so its first window is the\n * one on screen rather than one placed by `estimatedRowHeight`. Indices\n * past the row count are skipped. It does not observe the rows;\n * `measureRow` does that once the renderer hands them over.\n */\n readonly measureRows: (\n rows: Iterable<readonly [index: number, element: Element]>,\n ) => void;\n /**\n * Scrolls so row `index` is in view. A mounted row is scrolled to directly;\n * one outside the window is jumped to at its estimated offset, then\n * scrolled to properly once it mounts and can be measured. A later call\n * replaces one still waiting for its row; a row count that no longer holds\n * that row, or `resetHeights`, drops it.\n */\n readonly scrollToIndex: (\n index: number,\n options?: ScrollIntoViewOptions,\n ) => void;\n /**\n * Stops listening, measuring and scrolling, for good: every method does\n * nothing after it.\n */\n readonly destroy: () => void;\n}\n\n/**\n * Where the virtualizer is in its life: `ready`, `awaiting-row` while a\n * `scrollToIndex` waits for its row to mount to scroll to it properly, and\n * `destroyed` for good.\n */\ntype VirtualizerPhase =\n | { readonly kind: \"ready\" }\n | {\n readonly kind: \"awaiting-row\";\n readonly index: number;\n readonly options: ScrollIntoViewOptions | undefined;\n }\n | { readonly kind: \"destroyed\" };\n\nconst READY: VirtualizerPhase = { kind: \"ready\" };\n\nfunction sameRange(a: VisibleRange, b: VisibleRange): boolean {\n return (\n a.startIndex === b.startIndex &&\n a.endIndex === b.endIndex &&\n a.offsetBefore === b.offsetBefore &&\n a.offsetAfter === b.offsetAfter\n );\n}\n\n/**\n * Windows a long list of rows inside `scrollElement` down to those near its\n * scroll position, measuring each rendered row's real height rather than\n * assuming a uniform one — rows are not uniform (`.is-wrapped` cells, group\n * header and summary rows), so a fixed-height virtualizer would either break\n * wrapping or rule it out. The renderer draws `onRange`'s window, with\n * spacers of `offsetBefore`/`offsetAfter` around it, and hands each row's\n * element to `measureRow`.\n *\n * The heights are a mutable array, not a structure rebuilt per measurement:\n * one can arrive many times a second while scrolling. The pure arithmetic\n * over them is `@gridkitjs/core`'s `visibleRange`; this owns only the\n * mutability around it and the listeners that feed it — the scroll position,\n * the scroll element's height, and one `ResizeObserver` shared by every\n * mounted row.\n */\nexport function createRowVirtualizer(\n scrollElement: HTMLElement,\n options: RowVirtualizerOptions,\n): RowVirtualizer {\n const { estimatedRowHeight, overscan, onRange } = options;\n\n let heights: (number | undefined)[] = [];\n let scrollTop = scrollElement.scrollTop;\n let viewportHeight = scrollElement.clientHeight;\n let range: VisibleRange | null = null;\n let phase: VirtualizerPhase = READY;\n\n const elements = new Map<number, HTMLElement>();\n const indexByElement = new Map<Element, number>();\n const refCallbacks = new Map<number, (element: HTMLElement | null) => void>();\n\n function recompute(): void {\n if (phase.kind === \"destroyed\") {\n return;\n }\n const next = visibleRange(\n heights,\n estimatedRowHeight,\n scrollTop,\n viewportHeight,\n overscan,\n );\n if (range !== null && sameRange(range, next)) {\n return;\n }\n range = next;\n onRange(next);\n }\n\n const rowObserver = new ResizeObserver((entries) => {\n let changed = false;\n for (const entry of entries) {\n const index = indexByElement.get(entry.target);\n if (index === undefined) continue;\n const height = entry.target.getBoundingClientRect().height;\n if (heights[index] !== height) {\n heights[index] = height;\n changed = true;\n }\n }\n if (changed) {\n recompute();\n }\n });\n\n // Kept current here rather than read on each recompute: a scroll can fire\n // many times a second, and each one only needs to feed the next window.\n const viewportObserver = new ResizeObserver(() => {\n viewportHeight = scrollElement.clientHeight;\n recompute();\n });\n viewportObserver.observe(scrollElement);\n\n function handleScroll(): void {\n scrollTop = scrollElement.scrollTop;\n recompute();\n }\n scrollElement.addEventListener(\"scroll\", handleScroll, { passive: true });\n\n function estimateOffsetBefore(index: number): number {\n let total = 0;\n for (let current = 0; current < index; current++) {\n total += heights[current] ?? estimatedRowHeight;\n }\n return total;\n }\n\n recompute();\n\n return {\n setRowCount(count) {\n if (phase.kind === \"awaiting-row\" && phase.index >= count) {\n phase = READY;\n }\n heights = Array.from({ length: count }, (_, index) => heights[index]);\n recompute();\n },\n resetHeights() {\n if (phase.kind === \"awaiting-row\") {\n phase = READY;\n }\n heights = new Array<number | undefined>(heights.length).fill(undefined);\n recompute();\n },\n measureRow(index) {\n let callback = refCallbacks.get(index);\n if (callback === undefined) {\n callback = (element) => {\n const previous = elements.get(index);\n if (previous !== undefined) {\n rowObserver.unobserve(previous);\n indexByElement.delete(previous);\n elements.delete(index);\n }\n if (element === null || phase.kind === \"destroyed\") {\n return;\n }\n elements.set(index, element);\n indexByElement.set(element, index);\n rowObserver.observe(element);\n if (phase.kind === \"awaiting-row\" && phase.index === index) {\n element.scrollIntoView(phase.options);\n phase = READY;\n }\n };\n refCallbacks.set(index, callback);\n }\n return callback;\n },\n measureRows(rows) {\n if (phase.kind === \"destroyed\") {\n return;\n }\n for (const [index, element] of rows) {\n if (index >= 0 && index < heights.length) {\n heights[index] = element.getBoundingClientRect().height;\n }\n }\n recompute();\n },\n scrollToIndex(index, scrollOptions) {\n if (phase.kind === \"destroyed\" || heights.length === 0) {\n return;\n }\n const clamped = Math.max(0, Math.min(index, heights.length - 1));\n const mounted = elements.get(clamped);\n if (mounted !== undefined) {\n phase = READY;\n mounted.scrollIntoView(scrollOptions);\n return;\n }\n phase = { kind: \"awaiting-row\", index: clamped, options: scrollOptions };\n scrollElement.scrollTop = estimateOffsetBefore(clamped);\n },\n destroy() {\n phase = { kind: \"destroyed\" };\n scrollElement.removeEventListener(\"scroll\", handleScroll);\n viewportObserver.disconnect();\n rowObserver.disconnect();\n elements.clear();\n indexByElement.clear();\n },\n };\n}\n","import type { Schedule } from \"@gridkitjs/forms-core\";\n\n/**\n * The browser's timers as a forms-core `Schedule`: runs `callback` once\n * after `delay` milliseconds, and the function it returns clears the timer.\n * Clearing after the callback has run does nothing.\n */\nexport const scheduleTimeout: Schedule = (callback, delay) => {\n const timer = setTimeout(callback, delay);\n return () => {\n clearTimeout(timer);\n };\n};\n","import { scheduleTimeout } from \"../scheduleTimeout\";\n\nexport interface HoldRepeatOptions {\n /** One step; false when it changed nothing (a limit), which ends the hold. */\n readonly onRepeat: (nativeEvent: PointerEvent) => boolean;\n /** Milliseconds from the press to the first repeat; 400 by default. */\n readonly delay?: number | undefined;\n /** Milliseconds between repeats; 60 by default. */\n readonly interval?: number | undefined;\n /** Milliseconds between repeats once `fastAfter` have been taken; 30 by default. */\n readonly fastInterval?: number | undefined;\n /** Repeats before they speed up; 20 by default. */\n readonly fastAfter?: number | undefined;\n}\n\nexport interface AttachedHoldRepeat {\n /** Replaces the options, from the next step on. */\n readonly setOptions: (options: HoldRepeatOptions) => void;\n /** Ends a hold in progress, as letting go would. */\n readonly cancel: () => void;\n /** Ends a hold in progress and removes every listener. */\n readonly detach: () => void;\n}\n\n/**\n * Where a press of the button is:\n *\n * - `idle`: not pressed.\n * - `waiting`: pressed, one step taken, waiting `delay` to repeat.\n * - `repeating`: stepping every `interval`, then every `fastInterval`.\n * - `detached`: every listener is gone.\n *\n * `waiting` and `repeating` hold the pointer's capture and a timer, which\n * every way out of them releases.\n */\nexport type HoldRepeatState =\n | { readonly kind: \"idle\" }\n | {\n readonly kind: \"waiting\";\n readonly pointerId: number;\n readonly press: PointerEvent;\n readonly cancel: () => void;\n }\n | {\n readonly kind: \"repeating\";\n readonly pointerId: number;\n readonly press: PointerEvent;\n readonly count: number;\n readonly cancel: () => void;\n }\n | { readonly kind: \"detached\" };\n\nconst IDLE: HoldRepeatState = { kind: \"idle\" };\nconst DETACHED: HoldRepeatState = { kind: \"detached\" };\n\nconst DELAY = 400;\nconst INTERVAL = 60;\nconst FAST_INTERVAL = 30;\nconst FAST_AFTER = 20;\n\n/**\n * Makes a stepper button step once when pressed and repeat while held: after\n * `delay` it steps every `interval`, and faster once `fastAfter` steps have\n * been taken. The hold ends when the pointer is let go or cancelled, loses\n * capture or leaves the button, when a step changes nothing, on `cancel`\n * and on `detach`, and every end clears the timer and releases the\n * pointer's capture.\n *\n * Only the primary button of a mouse, or a touch or pen, presses it. A long\n * touch opens no context menu. The renderer keeps focus where it is (on a\n * `mousedown`, so a tap still clicks) and draws the button's disabled\n * state; `onRepeat` returning false when it cannot step ends the hold.\n */\nexport function attachHoldRepeat(\n button: HTMLElement,\n initialOptions: HoldRepeatOptions,\n): AttachedHoldRepeat {\n let options = initialOptions;\n let state: HoldRepeatState = IDLE;\n const listeners = new AbortController();\n const { signal } = listeners;\n\n /** Leaves `waiting` or `repeating` for `next`, releasing the timer and the capture. */\n function release(next: HoldRepeatState): void {\n if (state.kind === \"waiting\" || state.kind === \"repeating\") {\n state.cancel();\n const { pointerId } = state;\n state = next;\n if (button.hasPointerCapture(pointerId)) {\n button.releasePointerCapture(pointerId);\n }\n return;\n }\n if (state.kind !== \"detached\") {\n state = next;\n }\n }\n\n function repeat(press: PointerEvent, count: number): void {\n if (!options.onRepeat(press)) {\n release(IDLE);\n return;\n }\n const taken = count + 1;\n const interval =\n taken >= (options.fastAfter ?? FAST_AFTER)\n ? (options.fastInterval ?? FAST_INTERVAL)\n : (options.interval ?? INTERVAL);\n state = {\n kind: \"repeating\",\n pointerId: press.pointerId,\n press,\n count: taken,\n cancel: scheduleTimeout(() => {\n repeat(press, taken);\n }, interval),\n };\n }\n\n function onPointerDown(event: PointerEvent): void {\n if (state.kind !== \"idle\" || event.button !== 0) {\n return;\n }\n if (!options.onRepeat(event)) {\n return;\n }\n // Capture keeps the press's moves and its end here wherever the\n // pointer goes; a touch is captured already.\n try {\n button.setPointerCapture(event.pointerId);\n } catch {\n // A pointer the browser has already let go of cannot be captured.\n }\n state = {\n kind: \"waiting\",\n pointerId: event.pointerId,\n press: event,\n cancel: scheduleTimeout(() => {\n repeat(event, 0);\n }, options.delay ?? DELAY),\n };\n }\n\n function onPointerMove(event: PointerEvent): void {\n if (\n (state.kind !== \"waiting\" && state.kind !== \"repeating\") ||\n event.pointerId !== state.pointerId\n ) {\n return;\n }\n const box = button.getBoundingClientRect();\n if (\n event.clientX < box.left ||\n event.clientX > box.right ||\n event.clientY < box.top ||\n event.clientY > box.bottom\n ) {\n release(IDLE);\n }\n }\n\n function onEnd(event: PointerEvent): void {\n if (\n (state.kind === \"waiting\" || state.kind === \"repeating\") &&\n event.pointerId === state.pointerId\n ) {\n release(IDLE);\n }\n }\n\n button.addEventListener(\"pointerdown\", onPointerDown, { signal });\n button.addEventListener(\"pointermove\", onPointerMove, { signal });\n button.addEventListener(\"pointerup\", onEnd, { signal });\n button.addEventListener(\"pointercancel\", onEnd, { signal });\n button.addEventListener(\"lostpointercapture\", onEnd, { signal });\n button.addEventListener(\n \"contextmenu\",\n (event) => {\n event.preventDefault();\n },\n { signal },\n );\n\n return {\n setOptions: (next) => {\n options = next;\n },\n cancel: () => {\n release(IDLE);\n },\n detach: () => {\n release(DETACHED);\n listeners.abort();\n },\n };\n}\n","import type { StepDirection, StepSize } from \"@gridkitjs/forms-core\";\n\nexport interface StepKeysOptions {\n /** A key or a wheel tick asked for a step. */\n readonly onStep: (\n direction: StepDirection,\n size: StepSize,\n nativeEvent: KeyboardEvent | WheelEvent,\n ) => void;\n /** Home and End step to an edge only when that limit is set; otherwise they move the caret. */\n readonly edges?: { readonly min: boolean; readonly max: boolean } | undefined;\n /** The wheel steps while the control has focus and the pointer is over it. */\n readonly wheel?: boolean | undefined;\n}\n\nexport interface AttachedStepKeys {\n /** Replaces the options, from the next event on. */\n readonly setOptions: (options: StepKeysOptions) => void;\n /** Removes every listener. */\n readonly detach: () => void;\n}\n\n/** The wheel's travel, in pixels, that makes one step. */\nconst WHEEL_STEP_PIXELS = 50;\n\n/** `keyCode` 229: WebKit's only sign that a key went to an input method. */\ninterface LegacyKeyboardEvent {\n readonly keyCode: number;\n}\n\n/** The step a key asks for, by the spinbutton pattern. */\nfunction keyStep(\n key: string,\n edges: StepKeysOptions[\"edges\"],\n): readonly [StepDirection, StepSize] | null {\n switch (key) {\n case \"ArrowUp\":\n return [\"up\", \"step\"];\n case \"ArrowDown\":\n return [\"down\", \"step\"];\n case \"PageUp\":\n return [\"up\", \"large\"];\n case \"PageDown\":\n return [\"down\", \"large\"];\n case \"Home\":\n return edges?.min === true ? [\"down\", \"edge\"] : null;\n case \"End\":\n return edges?.max === true ? [\"up\", \"edge\"] : null;\n default:\n return null;\n }\n}\n\nfunction hasFocus(control: HTMLElement): boolean {\n const root = control.getRootNode();\n return (\n (root instanceof Document || root instanceof ShadowRoot) &&\n root.activeElement === control\n );\n}\n\n/**\n * Steps a number control from the keyboard, as the WAI-ARIA spinbutton\n * pattern does: ArrowUp and ArrowDown one step, PageUp and PageDown a\n * large step, Home and End to a limit that is set. With `options.wheel`,\n * the mouse wheel steps too while the control has focus and the pointer is\n * over it, one step per 50 pixels of travel (or per line or page), and\n * the page does not scroll meanwhile.\n *\n * Keys it steps on are taken (`preventDefault`); keys held with Ctrl, Alt\n * or Meta, keys an input method is using and keys another listener took\n * are left alone. A held arrow repeats by the keyboard's own repeat. It\n * holds its listeners and the wheel travel not yet stepped on; `detach`\n * removes them.\n */\nexport function attachStepKeys(\n control: HTMLInputElement,\n initialOptions: StepKeysOptions,\n): AttachedStepKeys {\n let options = initialOptions;\n // Travel the wheel has made toward the next step, up being negative.\n let wheelTravel = 0;\n const listeners = new AbortController();\n const { signal } = listeners;\n\n control.addEventListener(\n \"keydown\",\n (event) => {\n const legacy: LegacyKeyboardEvent = event;\n if (\n event.defaultPrevented ||\n event.isComposing ||\n legacy.keyCode === 229 ||\n event.ctrlKey ||\n event.altKey ||\n event.metaKey\n ) {\n return;\n }\n const step = keyStep(event.key, options.edges);\n if (step === null) {\n return;\n }\n event.preventDefault();\n options.onStep(step[0], step[1], event);\n },\n { signal },\n );\n\n control.addEventListener(\n \"wheel\",\n (event) => {\n if (options.wheel !== true || !hasFocus(control)) {\n wheelTravel = 0;\n return;\n }\n event.preventDefault();\n const unit =\n event.deltaMode === WheelEvent.DOM_DELTA_PIXEL ? 1 : WHEEL_STEP_PIXELS;\n wheelTravel += event.deltaY * unit;\n while (Math.abs(wheelTravel) >= WHEEL_STEP_PIXELS) {\n const direction = wheelTravel < 0 ? \"up\" : \"down\";\n wheelTravel -= Math.sign(wheelTravel) * WHEEL_STEP_PIXELS;\n options.onStep(direction, \"step\", event);\n }\n },\n { signal, passive: false },\n );\n\n control.addEventListener(\n \"blur\",\n () => {\n wheelTravel = 0;\n },\n { signal },\n );\n\n return {\n setOptions: (next) => {\n options = next;\n },\n detach: () => {\n listeners.abort();\n },\n };\n}\n","/** How many lines of text a growing `<textarea>` shows. */\nexport interface AutoGrowOptions {\n /** The lines it shows when empty. */\n readonly minRows: number;\n /** The lines it grows to, before it scrolls. */\n readonly maxRows: number;\n}\n\nexport interface AttachedAutoGrow {\n /**\n * Sets the height for the text there is now. The renderer calls it after\n * it writes text from code, which fires no `input`.\n */\n readonly update: () => void;\n /** Replaces the row range, and sets the height for it. */\n readonly setOptions: (options: AutoGrowOptions) => void;\n /** Stops listening, and leaves the height as it is. */\n readonly detach: () => void;\n}\n\nfunction pixels(value: string): number {\n const parsed = Number.parseFloat(value);\n return Number.isNaN(parsed) ? 0 : parsed;\n}\n\n/** `normal` line height, as browsers draw it for most fonts. */\nconst NORMAL_LINE_HEIGHT = 1.2;\n\n/**\n * Grows a `<textarea>` with its text, from `minRows` lines to `maxRows`,\n * then lets it scroll. The height follows every `input` and every change\n * of the textarea's width, which rewraps the text (a `ResizeObserver`),\n * and is worked out from `scrollHeight`, the computed line height,\n * padding and borders. CSS `field-sizing: content` would do this, but not\n * every browser the forms support has it.\n */\nexport function attachAutoGrow(\n textarea: HTMLTextAreaElement,\n initialOptions: AutoGrowOptions,\n): AttachedAutoGrow {\n let options = initialOptions;\n let width = -1;\n let detached = false;\n let frame = 0;\n const listeners = new AbortController();\n\n function update(): void {\n if (detached) {\n return;\n }\n const style = getComputedStyle(textarea);\n const lineHeight =\n style.lineHeight === \"normal\"\n ? pixels(style.fontSize) * NORMAL_LINE_HEIGHT\n : pixels(style.lineHeight);\n const padding = pixels(style.paddingTop) + pixels(style.paddingBottom);\n const border =\n pixels(style.borderTopWidth) + pixels(style.borderBottomWidth);\n const min = Math.max(1, options.minRows) * lineHeight;\n const max = Math.max(options.minRows, options.maxRows) * lineHeight;\n\n // With no height of its own the textarea's scroll height is its text's.\n textarea.style.height = \"0px\";\n const content = textarea.scrollHeight - padding;\n const inner = Math.min(Math.max(content, min), max);\n const outer =\n style.boxSizing === \"border-box\" ? inner + padding + border : inner;\n textarea.style.height = `${String(outer)}px`;\n textarea.style.overflowY = content > max + 1 ? \"auto\" : \"hidden\";\n }\n\n const resizes = new ResizeObserver(([entry]) => {\n // Only a new width rewraps the text; the height is this behaviour's own.\n const next = entry?.contentRect.width ?? width;\n if (next !== width) {\n width = next;\n // Set the height in the next frame: setting it inside the callback\n // resizes the observed element again in the same frame, which WebKit\n // reports as a \"ResizeObserver loop\" error.\n cancelAnimationFrame(frame);\n frame = requestAnimationFrame(() => {\n frame = 0;\n update();\n });\n }\n });\n resizes.observe(textarea);\n textarea.addEventListener(\"input\", update, { signal: listeners.signal });\n update();\n\n return {\n update,\n setOptions: (next) => {\n options = next;\n update();\n },\n detach: () => {\n detached = true;\n listeners.abort();\n resizes.disconnect();\n cancelAnimationFrame(frame);\n },\n };\n}\n","/** A stretch of a control's text, counted in UTF-16 code units as `selectionStart` is. */\nexport interface TextRange {\n readonly start: number;\n readonly end: number;\n}\n\nlet graphemes: Intl.Segmenter | undefined;\n\n/** Characters as a reader sees them: an emoji or a letter with its accents is one. */\nfunction graphemeSegmenter(): Intl.Segmenter {\n graphemes ??= new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n return graphemes;\n}\n\nfunction graphemeStartBefore(text: string, index: number): number {\n let start = index;\n for (const segment of graphemeSegmenter().segment(text.slice(0, index))) {\n start = segment.index;\n }\n return start;\n}\n\nfunction graphemeEndAfter(text: string, index: number): number {\n const segments = graphemeSegmenter().segment(text.slice(index));\n const first = segments[Symbol.iterator]().next();\n return first.done ? index : index + first.value.segment.length;\n}\n\n/** Back over spaces, then over the word before them, as Ctrl+Backspace deletes. */\nfunction wordStartBefore(text: string, index: number): number {\n const word = /\\S*\\s*$/u.exec(text.slice(0, index))?.[0] ?? \"\";\n return index - word.length;\n}\n\nfunction wordEndAfter(text: string, index: number): number {\n const word = /^\\s*\\S*/u.exec(text.slice(index))?.[0] ?? \"\";\n return index + word.length;\n}\n\nfunction lineStartBefore(text: string, index: number): number {\n return text.lastIndexOf(\"\\n\", index - 1) + 1;\n}\n\nfunction lineEndAfter(text: string, index: number): number {\n const end = text.indexOf(\"\\n\", index);\n return end === -1 ? text.length : end;\n}\n\n/** What a deletion with nothing selected removes around `caret`. */\nfunction deletedAround(\n text: string,\n caret: number,\n inputType: string,\n): TextRange {\n switch (inputType) {\n case \"deleteContentBackward\":\n return { start: graphemeStartBefore(text, caret), end: caret };\n case \"deleteContentForward\":\n return { start: caret, end: graphemeEndAfter(text, caret) };\n case \"deleteWordBackward\":\n return { start: wordStartBefore(text, caret), end: caret };\n case \"deleteWordForward\":\n return { start: caret, end: wordEndAfter(text, caret) };\n case \"deleteSoftLineBackward\":\n case \"deleteHardLineBackward\":\n return { start: lineStartBefore(text, caret), end: caret };\n case \"deleteSoftLineForward\":\n case \"deleteHardLineForward\":\n return { start: caret, end: lineEndAfter(text, caret) };\n case \"deleteEntireSoftLine\":\n return {\n start: lineStartBefore(text, caret),\n end: lineEndAfter(text, caret),\n };\n default:\n return { start: caret, end: caret };\n }\n}\n\nfunction splice(text: string, { start, end }: TextRange, insert: string) {\n return text.slice(0, start) + insert + text.slice(end);\n}\n\n/**\n * The text a browser edit will leave, worked out before the browser makes\n * it: `text` with `range` (the selection, or the text an input method is\n * composing) edited as the `beforeinput` event's `inputType` says,\n * inserting `data`. A deletion with nothing selected removes a character,\n * a word or a line around the caret, as its type says; a word ends at\n * white space.\n *\n * `null` for an edit only the browser can work out: undo and redo, a\n * spelling correction (it replaces a word the event does not locate),\n * swapping two characters, and any type it does not know.\n */\nexport function applyEdit(\n text: string,\n range: TextRange,\n inputType: string,\n data: string | null,\n): string | null {\n switch (inputType) {\n case \"insertLineBreak\":\n case \"insertParagraph\":\n return splice(text, range, \"\\n\");\n case \"insertReplacementText\":\n case \"insertTranspose\":\n return null;\n }\n if (inputType.startsWith(\"insert\")) {\n return splice(text, range, data ?? \"\");\n }\n if (inputType.startsWith(\"delete\")) {\n return splice(\n text,\n range.start === range.end\n ? deletedAround(text, range.start, inputType)\n : range,\n \"\",\n );\n }\n return null;\n}\n","import type {\n ChangeSource,\n FieldController,\n FieldMessage,\n InputFilterDecision,\n TextEdit,\n TextInputDetails,\n} from \"@gridkitjs/forms-core\";\nimport { applyEdit, type TextRange } from \"./applyEdit\";\n\n/** The native controls a text input draws. */\nexport type TextControl = HTMLInputElement | HTMLTextAreaElement;\n\n/**\n * What `attachTextInput` asks of the field it drives: a forms-core\n * `FieldController`, or one part of a composite input.\n */\nexport type TextInputController<V, D extends object> = Pick<\n FieldController<V, D, Event>,\n | \"getState\"\n | \"getText\"\n | \"getMessages\"\n | \"subscribe\"\n | \"beforeInput\"\n | \"input\"\n | \"endComposition\"\n | \"filterComposition\"\n | \"focus\"\n | \"commit\"\n | \"blur\"\n | \"revert\"\n | \"clear\"\n | \"reset\"\n>;\n\n/** What a renderer can change about the pipeline while it is attached. */\nexport interface TextInputOptions {\n /**\n * Selects all the text when the control gains focus from the keyboard or\n * from code. A press of a pointer places the caret as usual.\n */\n readonly selectOnFocus?: boolean | undefined;\n /**\n * What Escape does: puts back the last committed text (`\"revert\"`, the\n * default), empties the field (`\"clear\"`, for a search box), or nothing.\n * It takes the key only when it changed something.\n */\n readonly escape?: \"revert\" | \"clear\" | \"none\" | undefined;\n /** Called just before Escape empties the field, for the renderer's `onClear`. */\n readonly onClear?: ((nativeEvent: Event) => void) | undefined;\n /**\n * Where the caret goes when the field's text is written into the focused\n * control: given the text before, the caret in it and the text after.\n * By default it keeps its distance from the end of the text.\n */\n readonly mapCaret?:\n | ((previousText: string, caret: number, nextText: string) => number)\n | undefined;\n /**\n * What the keypad's decimal key types, whatever the keyboard layout\n * gives: a number field's decimal separator, so the keypad \".\" of a US\n * keyboard types \",\" in a German field.\n */\n readonly decimalKey?: string | undefined;\n /**\n * The furthest a click may leave the caret in the text: a mask's first\n * empty slot. A click that places the caret past it moves it there; a\n * selection is left alone.\n */\n readonly lastCaret?: ((text: string) => number) | undefined;\n /**\n * Who starts and ends the edit. `\"own\"` (the default): the control's\n * focus and blur do, and Tab commits. `\"group\"`: the control is one of\n * several that edit one field (a segmented date's free-text box), so the\n * group around it does, and the control calls neither `focus` nor `blur`\n * and leaves Tab alone.\n */\n readonly focus?: \"own\" | \"group\" | undefined;\n}\n\nexport interface AttachedTextInput {\n /** Replaces the options, from the next event on. */\n readonly setOptions: (options: TextInputOptions) => void;\n /**\n * Removes every listener and clears the control's custom validity. The\n * controller is left as it is, so another control can be attached to it.\n */\n readonly detach: () => void;\n}\n\n/** The text and selection before an edit, which a refused change puts back. */\ninterface TextSnapshot {\n readonly text: string;\n readonly selectionStart: number | null;\n readonly selectionEnd: number | null;\n readonly selectionDirection: \"forward\" | \"backward\" | \"none\" | null;\n}\n\n/**\n * What the pipeline is in the middle of:\n *\n * - `ready`: nothing.\n * - `editing`: the browser is making an edit `onBeforeInput` allowed;\n * `before` is the text and selection it started from.\n * - `composing`: an input method owns the text between `start` and the\n * last `suffixLength` code units, in place of what lay there in\n * `before`, the text when it began. Writes to the control wait for it.\n * - `rewriting`: inserting the data `onBeforeInput` gave in place of the\n * browser's edit, or the whole text the field's filter replaced it\n * with, which is reported once inserted; the events the insert itself\n * fires are ignored. `before` is as for `editing`.\n * - `detached`: every listener is gone.\n */\ntype TextPipelineState =\n | { readonly kind: \"ready\" }\n | { readonly kind: \"editing\"; readonly before: TextSnapshot }\n | {\n readonly kind: \"composing\";\n readonly start: number;\n readonly suffixLength: number;\n readonly before: string;\n }\n | { readonly kind: \"rewriting\"; readonly before: TextSnapshot }\n | { readonly kind: \"detached\" };\n\nconst READY: TextPipelineState = { kind: \"ready\" };\nconst DETACHED: TextPipelineState = { kind: \"detached\" };\n\n/**\n * The one legacy call. `document.execCommand` is deprecated, but inserting\n * text through it is still the only way the browser's undo history keeps\n * an insert made from code.\n */\ninterface EditingDocument {\n execCommand(\n commandId: \"insertText\" | \"delete\",\n showUI: boolean,\n value?: string,\n ): boolean;\n}\n\n/**\n * `keyCode` is deprecated, but 229 is the only sign WebKit gives that the\n * Enter ending a composition went to the input method: it fires that\n * keydown after `compositionend`, with `isComposing` false.\n */\ninterface LegacyKeyboardEvent {\n readonly keyCode: number;\n}\n\n/** Where a browser edit came from, by its `inputType`. */\nfunction sourceOf(inputType: string | null): ChangeSource {\n if (inputType === null) {\n return \"typing\";\n }\n if (inputType.startsWith(\"insertFromPaste\")) {\n return \"paste\";\n }\n if (inputType === \"insertFromDrop\" || inputType === \"deleteByDrag\") {\n return \"drop\";\n }\n return inputType.startsWith(\"history\") ? \"undo\" : \"typing\";\n}\n\nfunction hasFocus(control: TextControl): boolean {\n const root = control.getRootNode();\n return (\n (root instanceof Document || root instanceof ShadowRoot) &&\n root.activeElement === control\n );\n}\n\nfunction snapshot(control: TextControl): TextSnapshot {\n return {\n text: control.value,\n selectionStart: control.selectionStart,\n selectionEnd: control.selectionEnd,\n selectionDirection: control.selectionDirection,\n };\n}\n\n/** The default caret rule: the same distance from the end of the text. */\nfunction caretFromEnd(\n previousText: string,\n caret: number,\n nextText: string,\n): number {\n return Math.max(0, nextText.length - (previousText.length - caret));\n}\n\nfunction errorText(messages: readonly FieldMessage[]): string {\n return messages.find((message) => message.severity === \"error\")?.text ?? \"\";\n}\n\n/**\n * Connects a native text control to a forms-core field controller, so the\n * controller decides what the control's text means and the control shows\n * what the controller holds. The renderer draws the control and calls\n * this once it is in the page.\n *\n * Reads the control's events into the controller's requests, each with the\n * browser event as its `nativeEvent`:\n *\n * - `focus` and `blur` start and end the edit; the blur commits it, unless\n * Tab did. With `options.focus` set to `\"group\"`, the group around the\n * control does all three instead.\n * - `beforeinput` asks `onBeforeInput`, then the field's own\n * `filterInput`, with the text the edit would leave, then lets the edit\n * happen, prevents it, inserts the handler's data in its place, or\n * replaces the whole text and places the caret as the filter says.\n * `input` reports the text the edit left. Where it came from (`typing`,\n * `paste`, `drop`, `undo`) is read from its `inputType`; text that\n * changes while the field is not being edited is `autofill`.\n * - With `options.decimalKey`, the keypad's decimal key types that text,\n * judged as any other typing, in place of what the layout gives.\n * - While an input method composes, every `input` reports `isComposing`\n * and the text is read once `compositionend` arrives. Then the field's\n * `filterInput` judges the composed text as one insert over the range\n * the composition replaced (`filterComposition`), and its replacement,\n * rewrite or refusal is written as for any edit.\n * - With `options.lastCaret`, a click that leaves the caret past it moves\n * the caret there.\n * - Enter commits (in a `<textarea>`, Ctrl+Enter or Cmd+Enter, since Enter\n * is a new line); Tab commits and, when `onBeforeCommit` refuses at once,\n * keeps focus by preventing the key; Escape puts back the last committed\n * text, or empties the field, as `options.escape` says, and takes the key\n * when it changed something. Keys an input method is using, and keys\n * another listener prevented, are left alone.\n * - With `options.selectOnFocus`, focus from the keyboard or from code\n * selects all the text.\n * - A `reset` of the control's form that nobody prevented resets the\n * field, with `source: \"api\"`.\n *\n * After every change of the field it writes the controller's text into\n * the control when the two differ, never while an input method composes.\n * On a focused control a refused change is put back with the selection it\n * had before the edit, and any other write places the selection by\n * `options.mapCaret`, by default at its distance from the end of the\n * text, so separators a formatter adds before the caret do not move it. A\n * write to an unfocused control leaves the selection alone. The control's\n * custom validity holds the field's first error, shown or not yet, so a\n * plain `<form>` refuses to submit it.\n *\n * Inserting the handler's data, and replacing the text, go through the\n * browser's editing commands where the browser allows it, so they can be\n * undone; elsewhere the text is set directly. Setting the text from code\n * (a refused change put back, a commit normalizing the text, a value from\n * the app) cannot be undone.\n */\nexport function attachTextInput<V, D extends object>(\n control: TextControl,\n controller: TextInputController<V, D>,\n initialOptions: TextInputOptions = {},\n): AttachedTextInput {\n let options = initialOptions;\n let state: TextPipelineState = READY;\n let customValidity = \"\";\n // A pointer pressed on the unfocused control: the focus that follows\n // places the caret, so it selects nothing. That focus, or the press's\n // click where focus comes later (a touch), clears it.\n let pointerFocus = false;\n const listeners = new AbortController();\n const { signal } = listeners;\n\n function selection(): TextRange | null {\n const { selectionStart, selectionEnd } = control;\n if (state.kind === \"composing\") {\n return {\n start: state.start,\n end: control.value.length - state.suffixLength,\n };\n }\n return selectionStart === null || selectionEnd === null\n ? null\n : { start: selectionStart, end: selectionEnd };\n }\n\n function details(event: Event): TextInputDetails | null {\n if (!(event instanceof InputEvent)) {\n return null;\n }\n return {\n inputType: event.inputType === \"\" ? null : event.inputType,\n data: event.data,\n selectionStart: control.selectionStart,\n selectionEnd: control.selectionEnd,\n isComposing: event.isComposing,\n };\n }\n\n /** Puts `text` in the control, keeping the selection by the caret rule. */\n function writeText(text: string): void {\n if (!hasFocus(control)) {\n control.value = text;\n return;\n }\n const before =\n state.kind === \"editing\" || state.kind === \"rewriting\"\n ? state.before\n : null;\n if (before?.text === text) {\n control.value = text;\n if (before.selectionStart !== null && before.selectionEnd !== null) {\n control.setSelectionRange(\n before.selectionStart,\n before.selectionEnd,\n before.selectionDirection ?? undefined,\n );\n }\n return;\n }\n const { selectionStart, selectionEnd, selectionDirection } = control;\n const previous = control.value;\n control.value = text;\n if (selectionStart !== null && selectionEnd !== null) {\n const map = options.mapCaret ?? caretFromEnd;\n control.setSelectionRange(\n map(previous, selectionStart, text),\n map(previous, selectionEnd, text),\n selectionDirection ?? undefined,\n );\n }\n }\n\n /** Shows what the controller holds: its text, and its first error as the custom validity. */\n function render(): void {\n if (state.kind === \"composing\" || state.kind === \"detached\") {\n return;\n }\n const text = controller.getText();\n if (control.value !== text) {\n writeText(text);\n }\n const validity = errorText(controller.getMessages());\n if (validity !== customValidity) {\n customValidity = validity;\n control.setCustomValidity(validity);\n }\n }\n\n /** Inserts `data` where the browser was about to edit, as the edit `cause` describes. */\n function rewrite(cause: TextEdit<Event>, data: string): void {\n const range = selection();\n state = { kind: \"rewriting\", before: snapshot(control) };\n const editing: EditingDocument = control.ownerDocument;\n if (!editing.execCommand(\"insertText\", false, data) && range !== null) {\n control.setRangeText(data, range.start, range.end, \"end\");\n }\n controller.input({ ...cause, text: control.value });\n state = READY;\n }\n\n /** Chromium fires a line break's `beforeinput` for Enter in an `<input>`, which takes no line breaks. */\n function editsNothing(inputType: string | null): boolean {\n return (\n control instanceof HTMLInputElement &&\n (inputType === \"insertLineBreak\" || inputType === \"insertParagraph\")\n );\n }\n\n /**\n * Replaces the whole text with `text`, as the field's own filter asked,\n * and puts the caret at `caret`. Text that stays the same only moves the\n * caret.\n */\n function replace(cause: TextEdit<Event>, text: string, caret: number): void {\n if (control.value !== text) {\n state = { kind: \"rewriting\", before: snapshot(control) };\n control.setSelectionRange(0, control.value.length);\n const editing: EditingDocument = control.ownerDocument;\n const inserted =\n text === \"\"\n ? editing.execCommand(\"delete\", false)\n : editing.execCommand(\"insertText\", false, text);\n if (!inserted || control.value !== text) {\n control.value = text;\n }\n controller.input({ ...cause, text: control.value });\n state = READY;\n }\n if (control.value === text) {\n control.setSelectionRange(caret, caret);\n }\n }\n\n /** What the app and the field's filter decide about an edit the browser is about to make. */\n function decide(\n inputType: string | null,\n data: string | null,\n nativeEvent: Event,\n cancelable: boolean,\n composing: boolean,\n ): {\n readonly edit: TextEdit<Event>;\n readonly decision: InputFilterDecision;\n } {\n const range = selection();\n const proposed =\n range === null || inputType === null\n ? null\n : applyEdit(control.value, range, inputType, data);\n const input: TextInputDetails = {\n inputType,\n data,\n selectionStart: range?.start ?? null,\n selectionEnd: range?.end ?? null,\n isComposing: composing,\n };\n const edit: TextEdit<Event> = {\n text: proposed ?? control.value,\n source: sourceOf(inputType),\n input,\n nativeEvent,\n };\n const decision = controller.beforeInput({\n ...edit,\n cancelable: cancelable && !composing,\n });\n return { edit, decision };\n }\n\n /** Inserts the data of a rewrite, or replaces the text, as `decision` says. */\n function applyOwn(\n edit: TextEdit<Event>,\n decision: InputFilterDecision,\n ): void {\n if (decision.kind === \"rewrite\") {\n rewrite(\n {\n ...edit,\n input: edit.input && { ...edit.input, data: decision.data },\n },\n decision.data,\n );\n } else if (decision.kind === \"replace\") {\n replace(edit, decision.text, decision.caret);\n }\n }\n\n function onBeforeInput(event: InputEvent): void {\n const inputType = event.inputType === \"\" ? null : event.inputType;\n if (state.kind === \"rewriting\" || editsNothing(inputType)) {\n return;\n }\n const { edit, decision } = decide(\n inputType,\n event.data,\n event,\n event.cancelable,\n event.isComposing || state.kind === \"composing\",\n );\n if (decision.kind === \"allow\") {\n if (state.kind !== \"composing\") {\n state = { kind: \"editing\", before: snapshot(control) };\n }\n return;\n }\n event.preventDefault();\n applyOwn(edit, decision);\n }\n\n /**\n * Types `data` as though the keyboard had: the app and the filter judge\n * it, then it is inserted. For a key whose own text is replaced, such as\n * the keypad's decimal key.\n */\n function typeText(data: string, nativeEvent: KeyboardEvent): void {\n const { edit, decision } = decide(\n \"insertText\",\n data,\n nativeEvent,\n true,\n false,\n );\n applyOwn(\n edit,\n decision.kind === \"allow\" ? { kind: \"rewrite\", data } : decision,\n );\n }\n\n function onInput(event: Event): void {\n if (state.kind === \"rewriting\") {\n return;\n }\n const input = details(event);\n controller.input({\n text: control.value,\n source:\n controller.getState().phase.kind === \"idle\"\n ? \"autofill\"\n : sourceOf(input?.inputType ?? null),\n input,\n nativeEvent: event,\n });\n if (state.kind === \"editing\") {\n state = READY;\n }\n }\n\n function onCompositionStart(): void {\n const range = selection() ?? { start: 0, end: control.value.length };\n state = {\n kind: \"composing\",\n start: range.start,\n suffixLength: control.value.length - range.end,\n before: control.value,\n };\n }\n\n /**\n * Asks the field's filter about the text a composition left, as one\n * insert over the range it replaced, and writes what the filter decides:\n * its text, the composed text rewritten, or, when it refuses, the text\n * from before the composition.\n */\n function filterComposed(\n composition: Extract<TextPipelineState, { kind: \"composing\" }>,\n nativeEvent: CompositionEvent,\n ): void {\n const { start, suffixLength, before } = composition;\n const data = control.value.slice(\n start,\n control.value.length - suffixLength,\n );\n const replacedEnd = before.length - suffixLength;\n if (data === \"\" || replacedEnd < start) {\n return;\n }\n const edit: TextEdit<Event> = {\n text: control.value,\n source: \"typing\",\n input: {\n inputType: \"insertCompositionText\",\n data,\n selectionStart: start,\n selectionEnd: replacedEnd,\n isComposing: false,\n },\n nativeEvent,\n };\n const decision = controller.filterComposition(edit, before);\n switch (decision.kind) {\n case \"allow\":\n return;\n case \"prevent\":\n replace(edit, before, start);\n return;\n case \"rewrite\":\n replace(\n edit,\n before.slice(0, start) + decision.data + before.slice(replacedEnd),\n start + decision.data.length,\n );\n return;\n case \"replace\":\n replace(edit, decision.text, decision.caret);\n return;\n }\n }\n\n function onCompositionEnd(event: CompositionEvent): void {\n const composition = state.kind === \"composing\" ? state : null;\n // Firefox ends a composition committed in one step before the `input`\n // that reports its text, so the text is reported here; otherwise the\n // render below would write the old text over it. That late `input`\n // then finds nothing new.\n if (control.value !== controller.getText()) {\n controller.input({\n text: control.value,\n source: \"typing\",\n input: {\n inputType: \"insertCompositionText\",\n data: event.data,\n selectionStart: control.selectionStart,\n selectionEnd: control.selectionEnd,\n isComposing: true,\n },\n nativeEvent: event,\n });\n }\n state = READY;\n if (composition !== null) {\n filterComposed(composition, event);\n }\n controller.endComposition(event);\n render();\n }\n\n function isComposing(event: KeyboardEvent): boolean {\n const legacy: LegacyKeyboardEvent = event;\n return (\n event.isComposing || state.kind === \"composing\" || legacy.keyCode === 229\n );\n }\n\n function commitsOnEnter(event: KeyboardEvent): boolean {\n return control instanceof HTMLTextAreaElement\n ? event.ctrlKey || event.metaKey\n : true;\n }\n\n function onKeyDown(event: KeyboardEvent): void {\n if (event.defaultPrevented || isComposing(event)) {\n return;\n }\n const modified = event.ctrlKey || event.altKey || event.metaKey;\n // With Num Lock off the key is Delete, and stays one.\n if (\n event.code === \"NumpadDecimal\" &&\n event.key.length === 1 &&\n options.decimalKey !== undefined &&\n !modified &&\n !control.readOnly &&\n !control.disabled\n ) {\n event.preventDefault();\n typeText(options.decimalKey, event);\n return;\n }\n switch (event.key) {\n case \"Enter\":\n if (commitsOnEnter(event)) {\n controller.commit(\"enter\", event);\n }\n return;\n case \"Tab\":\n if (\n !modified &&\n !inGroup() &&\n controller.commit(\"tab\", event).kind === \"refused\"\n ) {\n event.preventDefault();\n }\n return;\n case \"Escape\":\n if (!modified && !event.shiftKey && escape(event)) {\n event.preventDefault();\n }\n return;\n }\n }\n\n /** Does what Escape does, and says whether it changed anything. */\n function escape(event: KeyboardEvent): boolean {\n switch (options.escape ?? \"revert\") {\n case \"revert\":\n return controller.revert(event);\n case \"clear\":\n if (control.readOnly || controller.getText() === \"\") {\n return false;\n }\n options.onClear?.(event);\n controller.clear(event);\n return true;\n case \"none\":\n return false;\n }\n }\n\n function inGroup(): boolean {\n return options.focus === \"group\";\n }\n\n function onFocus(event: FocusEvent): void {\n if (!inGroup()) {\n controller.focus(event);\n }\n if (options.selectOnFocus === true && !pointerFocus) {\n control.select();\n }\n pointerFocus = false;\n }\n\n /** Moves a caret a click left past `options.lastCaret` back to it. */\n function limitCaret(): void {\n const { lastCaret } = options;\n const { selectionStart, selectionEnd } = control;\n if (\n lastCaret === undefined ||\n selectionStart === null ||\n selectionStart !== selectionEnd ||\n !hasFocus(control)\n ) {\n return;\n }\n const last = lastCaret(control.value);\n if (selectionStart > last) {\n control.setSelectionRange(last, last);\n }\n }\n\n // On the document, so the app's own listeners have had their say first.\n function onReset(event: Event): void {\n if (event.defaultPrevented || event.target !== control.form) {\n return;\n }\n controller.reset();\n // The browser's reset, which follows this event, puts back this text.\n control.defaultValue = controller.getText();\n }\n\n // A union of the two controls loses the event map, so listen through one type.\n const element: HTMLElement = control;\n element.addEventListener(\"focus\", onFocus, { signal });\n element.addEventListener(\n \"pointerdown\",\n () => {\n pointerFocus = !hasFocus(control);\n },\n { signal },\n );\n element.addEventListener(\n \"click\",\n () => {\n pointerFocus = false;\n limitCaret();\n },\n { signal },\n );\n element.addEventListener(\n \"blur\",\n (event) => {\n if (!inGroup()) {\n controller.blur(event);\n }\n },\n { signal },\n );\n element.addEventListener(\"beforeinput\", onBeforeInput, { signal });\n element.addEventListener(\"input\", onInput, { signal });\n element.addEventListener(\"compositionstart\", onCompositionStart, { signal });\n element.addEventListener(\"compositionend\", onCompositionEnd, { signal });\n element.addEventListener(\"keydown\", onKeyDown, { signal });\n control.ownerDocument.addEventListener(\"reset\", onReset, { signal });\n const unsubscribe = controller.subscribe(render);\n\n // A control focused before it was attached (`autofocus`) starts its edit now.\n if (hasFocus(control) && !inGroup()) {\n controller.focus(null);\n }\n render();\n\n return {\n setOptions: (next) => {\n options = next;\n },\n detach: () => {\n if (state.kind === \"detached\") {\n return;\n }\n state = DETACHED;\n listeners.abort();\n unsubscribe();\n control.setCustomValidity(\"\");\n },\n };\n}\n","import {\n nextCheckedValue,\n type FieldController,\n type FieldMessage,\n} from \"@gridkitjs/forms-core\";\n\n/** What a renderer can change about a toggle while it is attached. */\nexport interface ToggleOptions {\n /** A flip can set `null` (indeterminate): `false` → `true` → `null` → `false`. */\n readonly threeState?: boolean | undefined;\n /**\n * Refuses every flip and stays focusable. A native checkbox ignores the\n * `readonly` attribute, so the renderer says so here.\n */\n readonly readOnly?: boolean | undefined;\n}\n\nexport interface AttachedToggle {\n /** Replaces the options, from the next event on. */\n readonly setOptions: (options: ToggleOptions) => void;\n /**\n * Removes every listener and clears the control's custom validity. The\n * controller is left as it is, so another control can be attached to it.\n */\n readonly detach: () => void;\n}\n\nfunction hasFocus(control: HTMLElement): boolean {\n const root = control.getRootNode();\n return (\n (root instanceof Document || root instanceof ShadowRoot) &&\n root.activeElement === control\n );\n}\n\nfunction errorText(messages: readonly FieldMessage[]): string {\n return messages.find((message) => message.severity === \"error\")?.text ?? \"\";\n}\n\n/**\n * Connects a native `<input type=\"checkbox\">`, a checkbox or a\n * `role=\"switch\"`, to a forms-core field controller holding a boolean, so\n * the controller decides what each flip means and the control shows what\n * the controller holds.\n *\n * - The browser's `click`, from a pointer, a label or <kbd>Space</kbd>,\n * flips the field to `nextCheckedValue` of what it holds, through\n * `controller.pick` with `source` and `trigger` `\"toggle\"`: the change\n * events, then the commit. A flip by Space carries the Space `keydown`\n * as its `nativeEvent`, a press the `click`.\n * - With `options.readOnly` the click is prevented, so nothing changes.\n * - `focus` and `blur` start and end the edit; leaving commits nothing\n * more, so the controller should have `commitOnLeave: false`.\n * - A `reset` of the control's form that nobody prevented resets the\n * field, with `source: \"api\"`.\n *\n * After every change of the field it writes `checked` (the value is\n * `true`) and `indeterminate` (it is `null`), over whatever the browser\n * did with the click, and holds the field's first error as the control's\n * custom validity, so a plain `<form>` refuses to submit it.\n */\nexport function attachToggle<D extends object>(\n control: HTMLInputElement,\n controller: FieldController<boolean, D, Event>,\n initialOptions: ToggleOptions = {},\n): AttachedToggle {\n let options = initialOptions;\n let attached = true;\n let customValidity = \"\";\n // The Space keydown whose click is coming: the flip reports the key.\n let spaceKey: KeyboardEvent | null = null;\n const listeners = new AbortController();\n const { signal } = listeners;\n\n function render(): void {\n if (!attached) {\n return;\n }\n const { value } = controller.getState();\n control.checked = value === true;\n control.indeterminate = value === null;\n const validity = errorText(controller.getMessages());\n if (validity !== customValidity) {\n customValidity = validity;\n control.setCustomValidity(validity);\n }\n }\n\n function onClick(event: MouseEvent): void {\n const nativeEvent = spaceKey ?? event;\n spaceKey = null;\n if (options.readOnly === true) {\n event.preventDefault();\n return;\n }\n const next = nextCheckedValue(\n controller.getState().value,\n options.threeState === true,\n );\n controller.pick(next, \"toggle\", \"toggle\", nativeEvent);\n render();\n }\n\n function onKeyDown(event: KeyboardEvent): void {\n spaceKey = event.key === \" \" && !event.defaultPrevented ? event : null;\n }\n\n // On the document, so the app's own listeners have had their say first.\n function onReset(event: Event): void {\n if (event.defaultPrevented || event.target !== control.form) {\n return;\n }\n controller.reset();\n // The browser's reset, which follows this event, puts back this state.\n control.defaultChecked = controller.getState().value === true;\n }\n\n control.addEventListener(\"click\", onClick, { signal });\n control.addEventListener(\"keydown\", onKeyDown, { signal });\n control.addEventListener(\n \"pointerdown\",\n () => {\n spaceKey = null;\n },\n { signal },\n );\n control.addEventListener(\n \"focus\",\n (event) => {\n controller.focus(event);\n },\n { signal },\n );\n control.addEventListener(\n \"blur\",\n (event) => {\n spaceKey = null;\n controller.blur(event);\n },\n { signal },\n );\n control.ownerDocument.addEventListener(\"reset\", onReset, { signal });\n const unsubscribe = controller.subscribe(render);\n\n // A control focused before it was attached (`autofocus`) starts its edit now.\n if (hasFocus(control)) {\n controller.focus(null);\n }\n render();\n\n return {\n setOptions: (next) => {\n options = next;\n },\n detach: () => {\n if (!attached) {\n return;\n }\n attached = false;\n listeners.abort();\n unsubscribe();\n control.setCustomValidity(\"\");\n },\n };\n}\n","import {\n idleSegments,\n segmentAria,\n segmentReducer,\n segmentSpans,\n splitSegments,\n type ChangeSource,\n type FormsMessages,\n type SegmentAction,\n type SegmentContext,\n type SegmentEntry,\n type SegmentState,\n type SegmentStep,\n type TextEdit,\n} from \"@gridkitjs/forms-core\";\nimport { attachFocusGroup } from \"../form/attachFocusGroup\";\nimport {\n attachTextInput,\n type TextInputController,\n} from \"../text/attachTextInput\";\n\n/** What `attachSegments` asks of the field it drives: a controller, or a part of a composite. */\nexport type SegmentsController<V, D extends object> = TextInputController<V, D>;\n\n/** What a renderer can change about the segments while they are attached. */\nexport interface SegmentsOptions {\n /** The field's layout and how it reads, for the segment reducer. */\n readonly context: SegmentContext;\n /** The locale a month's name is read in, for its `aria-valuetext`. */\n readonly locale: Intl.LocalesArgument;\n /** For an empty segment's `aria-valuetext`. */\n readonly messages: FormsMessages;\n /** What Escape in a segment does: puts back the last committed value (`\"revert\"`, the default), or nothing. */\n readonly escape?: \"revert\" | \"none\" | undefined;\n /**\n * Whether `node`, outside the group, counts as inside the field: the\n * picker popup it opened, so focus moving there neither commits nor\n * blurs the field.\n */\n readonly isInside?: ((node: Node) => boolean) | undefined;\n /** F4 or Alt+ArrowDown in a segment: the renderer opens its picker. */\n readonly onOpenPicker?: ((nativeEvent: KeyboardEvent) => void) | undefined;\n}\n\nexport interface AttachedSegments {\n /** Replaces the options, from the next event on, and redraws the segments. */\n readonly setOptions: (options: SegmentsOptions) => void;\n /** Focuses a segment, or the first empty one (the free-text box while it shows), as a click in the box does. */\n readonly focus: (segment?: number | \"firstEmpty\") => void;\n /** Where typing stands (the segment typed in, or the free-text box with the segments' text it opened over) and the text it holds. */\n readonly getState: () => SegmentState;\n /** Removes every listener, the free-text box's pipeline included. */\n readonly detach: () => void;\n}\n\n/** What a reported edit came from: the browser's event and what it typed. */\ninterface EditCause {\n readonly nativeEvent: Event | null;\n readonly inputType: string | null;\n readonly data: string | null;\n /** In place of the reducer's source: a drop is a paste to the reducer. */\n readonly source?: ChangeSource | undefined;\n}\n\nconst NO_CAUSE: EditCause = { nativeEvent: null, inputType: null, data: null };\n\n/**\n * `keyCode` is deprecated, but 229 is the only sign some engines give that\n * a key went to an input method, Android keyboards among them.\n */\ninterface LegacyKeyboardEvent {\n readonly keyCode: number;\n}\n\n/** The segment typing is in, or `null`. */\nfunction segmentOf(entry: SegmentEntry): number | null {\n return entry.kind === \"active\" ||\n entry.kind === \"typing\" ||\n entry.kind === \"composing\"\n ? entry.segment\n : null;\n}\n\n/** Edits a segment's `beforeinput` reports that empty it. */\nconst EMPTYING = new Set([\n \"deleteContentForward\",\n \"deleteWordBackward\",\n \"deleteWordForward\",\n \"deleteSoftLineBackward\",\n \"deleteSoftLineForward\",\n \"deleteHardLineBackward\",\n \"deleteHardLineForward\",\n \"deleteByCut\",\n \"deleteContent\",\n]);\n\n/**\n * Drives a segmented date, time or date-time field: one native input per\n * segment (each marked `data-gridkit-forms-segment`, in typing order)\n * inside `group`, the segments' wrapper marked\n * `data-gridkit-forms-segments`, and a free-text box marked\n * `data-gridkit-forms-segment-text` for shortcuts and text that is not\n * segments. forms-core's `segmentReducer` decides every transition; this\n * turns the browser's events into its actions and applies what it returns:\n *\n * - `beforeinput` on a segment (typing, Android's keys, a cut, a drop),\n * its `paste` and its composition events are actions. Every cancelable\n * edit is prevented and each segment's text is written here, so a\n * segment never holds what the reducer did not put there.\n * - Backspace and Delete, the arrows, PageUp and PageDown, Home and End are\n * read from `keydown`. ArrowLeft and ArrowRight move by the segments'\n * order on screen, so they follow a right-to-left field.\n * - A text change is reported to the controller as an edit: `onBeforeInput`\n * first (refused, nothing changes), then `onInput` with the segment's\n * place in the field's text as the edit's selection, from which the\n * field's `details` names the segment. Steps report `source: \"step\"`.\n * - Focus entering the group starts the edit; moving between segments and\n * the free-text box fires nothing; leaving finishes the segment (pads it,\n * pivots a short year) and blurs the field, which commits. Enter\n * finishes and commits; Tab finishes and commits, kept in the field when\n * `onBeforeCommit` refuses; Escape reverts, or in the free-text box goes\n * back to the segments.\n * - A press in the box outside a segment focuses the first empty segment;\n * a press on the focused day period flips it.\n * - The free-text box runs forms-dom's text pipeline in group focus mode;\n * its edits go through the reducer, which applies a one-letter shortcut\n * at once and goes back to the segments when the box is emptied.\n *\n * After every change of the field it writes each segment's text, its\n * `aria-valuenow`, `aria-valuemin`, `aria-valuemax` and `aria-valuetext`,\n * and, while focus is outside the group, shows the free-text box in place\n * of the segments when the text is not segments.\n *\n * It holds the reducer's `SegmentEntry`, its listeners (one\n * `AbortController`), the focus group and the free-text box's pipeline;\n * `detach` releases all of them.\n */\nexport function attachSegments<V, D extends object>(\n group: HTMLElement,\n controller: SegmentsController<V, D>,\n initialOptions: SegmentsOptions,\n): AttachedSegments {\n let options = initialOptions;\n let state: SegmentState = idleSegments(controller.getText());\n // The segment a pointer pressed while it had focus: its click flips a\n // day period.\n let pressedFocused: HTMLInputElement | null = null;\n const listeners = new AbortController();\n const { signal } = listeners;\n\n function segmentInputs(): HTMLInputElement[] {\n return Array.from(\n group.querySelectorAll<HTMLInputElement>(\n \"input[data-gridkit-forms-segment]\",\n ),\n );\n }\n\n function textBox(): HTMLInputElement | null {\n return group.querySelector<HTMLInputElement>(\n \"input[data-gridkit-forms-segment-text]\",\n );\n }\n\n function segmentsWrapper(): HTMLElement | null {\n return group.querySelector<HTMLElement>(\"[data-gridkit-forms-segments]\");\n }\n\n function activeElement(): Element | null {\n const root = group.getRootNode();\n return root instanceof Document || root instanceof ShadowRoot\n ? root.activeElement\n : null;\n }\n\n function focusWithin(): boolean {\n const active = activeElement();\n return active !== null && group.contains(active);\n }\n\n function caretToEnd(input: HTMLInputElement): void {\n input.setSelectionRange(input.value.length, input.value.length);\n }\n\n /** Moves focus where a step says, showing the segments or the free-text box first and hiding the other after. */\n function place(focus: SegmentStep[\"focus\"]): void {\n if (focus === null) {\n return;\n }\n const box = textBox();\n const wrapper = segmentsWrapper();\n if (focus === \"text\") {\n if (box === null) {\n return;\n }\n box.hidden = false;\n if (activeElement() !== box) {\n box.focus();\n }\n caretToEnd(box);\n if (wrapper !== null) {\n wrapper.hidden = true;\n }\n return;\n }\n const input = segmentInputs()[focus];\n if (input === undefined) {\n return;\n }\n if (wrapper !== null) {\n wrapper.hidden = false;\n }\n if (activeElement() !== input) {\n input.focus();\n }\n caretToEnd(input);\n if (box !== null) {\n box.hidden = true;\n }\n }\n\n /**\n * The state, caught up with the controller's text when that changed from\n * outside (a controlled value, a revert, a clear, a commit), moving focus\n * between the segments and the free-text box when the change takes it\n * from one to the other.\n */\n function held(): SegmentState {\n const text = controller.getText();\n if (text !== state.text) {\n const step = segmentReducer(\n state,\n { type: \"outside\", text },\n options.context,\n );\n const moved =\n (state.entry.kind === \"text\") !== (step.state.entry.kind === \"text\");\n state = step.state;\n if (moved && focusWithin()) {\n place(step.focus);\n }\n }\n return state;\n }\n\n function setAttribute(\n element: Element,\n name: string,\n value: string | null,\n ): void {\n if (value === null) {\n element.removeAttribute(name);\n } else if (element.getAttribute(name) !== value) {\n element.setAttribute(name, value);\n }\n }\n\n /** Writes each segment's text and value attributes, and which face shows while focus is elsewhere. */\n function render(): void {\n const current = held();\n const { layout } = options.context;\n const texts = splitSegments(layout, current.text);\n const shown = texts ?? layout.segments.map(() => \"\");\n const active = activeElement();\n segmentInputs().forEach((input, index) => {\n const text = shown[index] ?? \"\";\n if (input.value !== text) {\n input.value = text;\n if (input === active) {\n caretToEnd(input);\n }\n }\n const aria = segmentAria(\n layout,\n index,\n shown,\n options.locale,\n options.messages,\n );\n setAttribute(\n input,\n \"aria-valuenow\",\n aria.valueNow === null ? null : String(aria.valueNow),\n );\n setAttribute(input, \"aria-valuemin\", String(aria.valueMin));\n setAttribute(input, \"aria-valuemax\", String(aria.valueMax));\n setAttribute(input, \"aria-valuetext\", aria.valueText);\n });\n if (!focusWithin()) {\n const free = current.entry.kind === \"text\" || texts === null;\n const box = textBox();\n const wrapper = segmentsWrapper();\n if (box !== null) {\n box.hidden = !free;\n }\n if (wrapper !== null) {\n wrapper.hidden = free;\n }\n }\n }\n\n /** The edit a step reports: the segment it was in as the selection, in the text it leaves. */\n function editFor(\n before: SegmentState,\n step: SegmentStep,\n cause: EditCause,\n ): TextEdit<Event> {\n const edited = segmentOf(before.entry);\n const span =\n edited === null\n ? undefined\n : segmentSpans(options.context.layout, step.state.text)?.[edited];\n return {\n text: step.state.text,\n source: cause.source ?? step.source ?? \"typing\",\n nativeEvent: cause.nativeEvent,\n input: {\n inputType: cause.inputType,\n data: cause.data,\n selectionStart: span?.[0] ?? null,\n selectionEnd: span?.[1] ?? null,\n isComposing: false,\n },\n };\n }\n\n /**\n * Applies a step: a text change goes to the app's `onBeforeInput`, which\n * may refuse it or type other text in its place, and then to the\n * controller; focus moves where the step says.\n */\n function apply(\n before: SegmentState,\n proposed: SegmentStep,\n cause: EditCause,\n ): void {\n let step = proposed;\n let { data } = cause;\n if (step.source !== null) {\n const verdict = controller.beforeInput({\n ...editFor(before, step, cause),\n cancelable: true,\n });\n if (verdict.kind === \"prevent\") {\n render();\n return;\n }\n if (verdict.kind === \"rewrite\") {\n step = segmentReducer(\n before,\n { type: \"key\", text: verdict.data },\n options.context,\n );\n data = verdict.data;\n }\n }\n if (step.source === null) {\n state = step.state;\n } else {\n report(before, step, editFor(before, step, { ...cause, data }));\n }\n place(step.focus);\n render();\n }\n\n /**\n * Reports a step's text to the controller. A shortcut applied at once is\n * reported first as the free text typed, so the events it fires name the\n * shortcut, and then as the segments it gave.\n */\n function report(\n before: SegmentState,\n step: SegmentStep,\n edit: TextEdit<Event>,\n ): void {\n if (step.applied !== undefined) {\n state = {\n entry:\n before.entry.kind === \"text\"\n ? before.entry\n : { kind: \"text\", before: before.text },\n text: step.applied,\n };\n controller.input({\n ...edit,\n text: step.applied,\n input: withoutPlace(edit),\n });\n }\n state = step.state;\n controller.input(edit);\n }\n\n /** An edit's input details with no place in the text: text that is not segments names no segment. */\n function withoutPlace(edit: TextEdit<Event>): TextEdit<Event>[\"input\"] {\n return (\n edit.input && { ...edit.input, selectionStart: null, selectionEnd: null }\n );\n }\n\n function run(action: SegmentAction, cause: EditCause = NO_CAUSE): void {\n const before = held();\n apply(before, segmentReducer(before, action, options.context), cause);\n }\n\n /** Finishes the segment typed in, as Enter, Tab and leaving do before the field commits. */\n function finish(nativeEvent: Event): void {\n run({ type: \"finish\" }, { ...NO_CAUSE, nativeEvent });\n }\n\n function isComposing(event: KeyboardEvent): boolean {\n const legacy: LegacyKeyboardEvent = event;\n return (\n event.isComposing ||\n state.entry.kind === \"composing\" ||\n legacy.keyCode === 229\n );\n }\n\n /** ArrowLeft or ArrowRight from segment `index`: its neighbour on screen, or `null` at the edge. */\n function neighbourOnScreen(index: number, key: string): number | null {\n const inputs = segmentInputs();\n const byPosition = inputs\n .map((input, at) => ({ at, left: input.getBoundingClientRect().left }))\n .sort((a, b) => a.left - b.left);\n const position = byPosition.findIndex((entry) => entry.at === index);\n const next = byPosition[position + (key === \"ArrowRight\" ? 1 : -1)];\n return next?.at ?? null;\n }\n\n function onSegmentKey(\n event: KeyboardEvent,\n input: HTMLInputElement,\n index: number,\n ): void {\n const editable = !input.readOnly;\n const step = (\n direction: \"up\" | \"down\",\n size: \"step\" | \"large\" | \"edge\",\n ) => {\n event.preventDefault();\n if (editable) {\n run(\n { type: \"step\", direction, size },\n { nativeEvent: event, inputType: null, data: null },\n );\n }\n };\n switch (event.key) {\n case \"Enter\":\n finish(event);\n controller.commit(\"enter\", event);\n return;\n case \"Backspace\":\n case \"Delete\":\n event.preventDefault();\n if (editable) {\n run(\n { type: event.key === \"Backspace\" ? \"backspace\" : \"delete\" },\n {\n nativeEvent: event,\n inputType:\n event.key === \"Backspace\"\n ? \"deleteContentBackward\"\n : \"deleteContentForward\",\n data: null,\n },\n );\n }\n return;\n case \"ArrowUp\":\n step(\"up\", \"step\");\n return;\n case \"ArrowDown\":\n step(\"down\", \"step\");\n return;\n case \"PageUp\":\n step(\"up\", \"large\");\n return;\n case \"PageDown\":\n step(\"down\", \"large\");\n return;\n case \"Home\":\n step(\"down\", \"edge\");\n return;\n case \"End\":\n step(\"up\", \"edge\");\n return;\n case \"ArrowLeft\":\n case \"ArrowRight\": {\n event.preventDefault();\n const to = neighbourOnScreen(index, event.key);\n if (to !== null) {\n run(\n { type: \"focus\", segment: to },\n { ...NO_CAUSE, nativeEvent: event },\n );\n }\n return;\n }\n }\n }\n\n function onKeyDown(event: KeyboardEvent): void {\n if (event.defaultPrevented || isComposing(event)) {\n return;\n }\n const { target } = event;\n const inputs = segmentInputs();\n const index =\n target instanceof HTMLInputElement ? inputs.indexOf(target) : -1;\n const box = textBox();\n const inBox = target !== null && target === box;\n const input = inputs[index];\n if (!inBox && input === undefined) {\n return;\n }\n const modified = event.ctrlKey || event.altKey || event.metaKey;\n if (\n input !== undefined &&\n options.onOpenPicker !== undefined &&\n ((event.key === \"F4\" && !modified) ||\n (event.altKey && event.key === \"ArrowDown\"))\n ) {\n event.preventDefault();\n options.onOpenPicker(event);\n return;\n }\n switch (event.key) {\n case \"Tab\":\n if (modified) {\n return;\n }\n finish(event);\n if (controller.commit(\"tab\", event).kind === \"refused\") {\n event.preventDefault();\n }\n return;\n case \"Escape\":\n if (modified || event.shiftKey) {\n return;\n }\n if (inBox && state.entry.kind === \"text\") {\n event.preventDefault();\n run(\n { type: \"textEdit\", text: \"\" },\n { ...NO_CAUSE, nativeEvent: event },\n );\n } else if (\n (options.escape ?? \"revert\") === \"revert\" &&\n controller.revert(event)\n ) {\n event.preventDefault();\n }\n return;\n }\n if (input !== undefined && !modified) {\n onSegmentKey(event, input, index);\n }\n }\n\n function onBeforeInput(event: InputEvent): void {\n const { target } = event;\n if (!(target instanceof HTMLInputElement)) {\n return;\n }\n const index = segmentInputs().indexOf(target);\n // An input method's text is not cancelable: it runs, and is read at its end.\n if (index < 0 || !event.cancelable || event.isComposing) {\n return;\n }\n event.preventDefault();\n if (target.readOnly) {\n return;\n }\n const inputType = event.inputType;\n const cause: EditCause = {\n nativeEvent: event,\n inputType,\n data: event.data,\n };\n if (inputType === \"insertText\" || inputType === \"insertReplacementText\") {\n run({ type: \"key\", text: event.data ?? \"\" }, cause);\n } else if (\n inputType === \"insertFromPaste\" ||\n inputType === \"insertFromDrop\"\n ) {\n const text = event.dataTransfer?.getData(\"text/plain\") ?? event.data;\n run(\n { type: \"paste\", text: text ?? \"\" },\n {\n ...cause,\n data: text,\n source: inputType === \"insertFromDrop\" ? \"drop\" : \"paste\",\n },\n );\n } else if (inputType === \"deleteContentBackward\") {\n run({ type: \"backspace\" }, cause);\n } else if (EMPTYING.has(inputType)) {\n run({ type: \"delete\" }, cause);\n }\n }\n\n /**\n * A paste on a segment: read whole, or typed into the segment when it\n * fits there. Read from the clipboard event, which every engine fills;\n * a drop arrives as its `beforeinput`.\n */\n function onPaste(event: ClipboardEvent): void {\n const { target } = event;\n if (\n !(target instanceof HTMLInputElement) ||\n !segmentInputs().includes(target)\n ) {\n return;\n }\n event.preventDefault();\n if (target.readOnly) {\n return;\n }\n const text = event.clipboardData?.getData(\"text/plain\") ?? \"\";\n run(\n { type: \"paste\", text },\n {\n nativeEvent: event,\n inputType: \"insertFromPaste\",\n data: text,\n source: \"paste\",\n },\n );\n }\n\n function onCompositionStart(event: CompositionEvent): void {\n if (\n event.target instanceof HTMLInputElement &&\n segmentInputs().includes(event.target)\n ) {\n run({ type: \"compositionStart\" });\n }\n }\n\n function onCompositionEnd(event: CompositionEvent): void {\n const { target } = event;\n if (\n !(target instanceof HTMLInputElement) ||\n state.entry.kind !== \"composing\"\n ) {\n return;\n }\n // The input method wrote into the segment; the reducer types what it\n // composed from the segment's text before it began.\n const before = splitSegments(options.context.layout, state.text);\n target.value = before?.[state.entry.segment] ?? \"\";\n run(\n { type: \"compositionEnd\", text: event.data },\n {\n nativeEvent: event,\n inputType: \"insertCompositionText\",\n data: event.data,\n },\n );\n }\n\n /** An edit that slipped past `beforeinput` is undone: the segments show only what the reducer wrote. */\n function onInput(event: Event): void {\n if (\n event.target instanceof HTMLInputElement &&\n segmentInputs().includes(event.target) &&\n state.entry.kind !== \"composing\"\n ) {\n render();\n }\n }\n\n function onFocusIn(event: FocusEvent): void {\n const { target } = event;\n const box = textBox();\n const index =\n target instanceof HTMLInputElement ? segmentInputs().indexOf(target) : -1;\n const inBox = target !== null && target === box;\n if (index < 0 && !inBox) {\n return;\n }\n const current = held();\n if (current.entry.kind === \"idle\") {\n controller.focus(event);\n }\n if (inBox) {\n if (state.entry.kind !== \"text\") {\n run({ type: \"focus\", segment: 0 }, { ...NO_CAUSE, nativeEvent: event });\n }\n return;\n }\n if (segmentOf(state.entry) !== index) {\n run(\n { type: \"focus\", segment: index },\n { ...NO_CAUSE, nativeEvent: event },\n );\n }\n }\n\n /**\n * Focus left the group: the segment typed in is finished and reported\n * while the field still knows where typing stood, then the field blurs,\n * which commits it.\n */\n function leave(nativeEvent: FocusEvent): void {\n const before = held();\n if (before.entry.kind === \"idle\") {\n return;\n }\n const step = segmentReducer(before, { type: \"leave\" }, options.context);\n if (step.source !== null) {\n const edit = editFor(before, step, { ...NO_CAUSE, nativeEvent });\n const verdict = controller.beforeInput({ ...edit, cancelable: true });\n if (verdict.kind !== \"prevent\") {\n state = { entry: before.entry, text: step.state.text };\n controller.input(edit);\n }\n }\n controller.blur(nativeEvent);\n state = idleSegments(controller.getText());\n render();\n }\n\n function focusSegment(segment: number | \"firstEmpty\" = \"firstEmpty\"): void {\n const current = held();\n const { layout } = options.context;\n const texts = splitSegments(layout, current.text);\n if (texts === null || current.entry.kind === \"text\") {\n const box = textBox();\n if (box !== null) {\n box.hidden = false;\n box.focus();\n }\n return;\n }\n const index =\n segment === \"firstEmpty\"\n ? Math.max(\n texts.findIndex((text) => text === \"\"),\n 0,\n )\n : segment;\n segmentInputs()[index]?.focus();\n }\n\n function isOwnControl(target: EventTarget | null): boolean {\n return (\n target instanceof Element &&\n target.closest(\"input, button, select, textarea, a, label\") !== null\n );\n }\n\n group.addEventListener(\"keydown\", onKeyDown, { signal });\n group.addEventListener(\"beforeinput\", onBeforeInput, { signal });\n group.addEventListener(\"input\", onInput, { signal });\n group.addEventListener(\"paste\", onPaste, { signal });\n group.addEventListener(\"compositionstart\", onCompositionStart, { signal });\n group.addEventListener(\"compositionend\", onCompositionEnd, { signal });\n group.addEventListener(\"focusin\", onFocusIn, { signal });\n // A press on the box around the segments keeps focus where it is, rather\n // than blurring the field, and the click that follows focuses a segment.\n group.addEventListener(\n \"mousedown\",\n (event) => {\n if (!isOwnControl(event.target) && focusWithin()) {\n event.preventDefault();\n }\n },\n { signal },\n );\n group.addEventListener(\n \"pointerdown\",\n (event) => {\n const { target } = event;\n pressedFocused =\n target instanceof HTMLInputElement &&\n target === activeElement() &&\n segmentInputs().includes(target)\n ? target\n : null;\n },\n { signal },\n );\n group.addEventListener(\n \"click\",\n (event) => {\n const { target } = event;\n const inputs = segmentInputs();\n const disabled = inputs.every((input) => input.disabled);\n if (!isOwnControl(target)) {\n if (!disabled) {\n focusSegment(\"firstEmpty\");\n }\n return;\n }\n const index =\n target instanceof HTMLInputElement ? inputs.indexOf(target) : -1;\n const pressed = pressedFocused;\n pressedFocused = null;\n if (\n index >= 0 &&\n pressed !== null &&\n pressed === target &&\n !pressed.readOnly &&\n options.context.layout.segments[index]?.type === \"dayPeriod\"\n ) {\n run(\n { type: \"step\", direction: \"up\", size: \"step\" },\n { nativeEvent: event, inputType: null, data: null },\n );\n }\n },\n { signal },\n );\n\n const focusGroup = attachFocusGroup(group, {\n onLeave: (_by, nativeEvent) => {\n leave(nativeEvent);\n },\n isInside: (node) => options.isInside?.(node) === true,\n });\n\n // The free-text box edits the field through the reducer, which applies a\n // one-letter shortcut at once and goes back to the segments when the box\n // is emptied.\n const boxController: TextInputController<V, D> = {\n ...controller,\n input: (edit) => {\n if (edit.input?.isComposing === true || held().entry.kind !== \"text\") {\n controller.input(edit);\n return;\n }\n const before = state;\n const step = segmentReducer(\n before,\n { type: \"textEdit\", text: edit.text, source: edit.source },\n options.context,\n );\n // A shortcut applied at once leaves segments, where the box's caret\n // names no segment.\n report(\n before,\n step,\n step.state.text === edit.text\n ? edit\n : { ...edit, text: step.state.text, input: withoutPlace(edit) },\n );\n place(step.focus);\n render();\n },\n };\n const box = textBox();\n const boxPipeline =\n box === null\n ? null\n : attachTextInput(box, boxController, { focus: \"group\", escape: \"none\" });\n\n const unsubscribe = controller.subscribe(render);\n\n // A segment focused before it was attached (`autofocus`) starts its edit now.\n const focused = activeElement();\n if (focused instanceof HTMLInputElement) {\n const index = segmentInputs().indexOf(focused);\n if (index >= 0) {\n controller.focus(null);\n run({ type: \"focus\", segment: index });\n }\n }\n render();\n\n return {\n setOptions: (next) => {\n options = next;\n render();\n },\n focus: focusSegment,\n getState: () => state,\n detach: () => {\n listeners.abort();\n focusGroup.detach();\n boxPipeline?.detach();\n unsubscribe();\n },\n };\n}\n"],"mappings":";AAqBA,IAAM,iBAAiB,OAAO,cAAc,GAAI;AAezC,SAAS,oBACd,YAAyB,SAAS,MAClC,UAAgC,CAAC,GAClB;AACf,QAAM,SAAS,SAAS,cAAc,KAAK;AAC3C,SAAO,YAAY,QAAQ,aAAa;AACxC,SAAO,aAAa,QAAQ,QAAQ;AACpC,SAAO,aAAa,aAAa,QAAQ;AACzC,YAAU,OAAO,MAAM;AAEvB,MAAI,OAAO;AACX,MAAI,SAAS;AAEb,SAAO;AAAA,IACL,SAAS,MAAM;AACb,eAAS,SAAS,QAAQ,CAAC;AAC3B,aAAO;AACP,aAAO,cAAc,SAAS,OAAO,iBAAiB;AAAA,IACxD;AAAA,IACA,UAAU;AACR,aAAO,OAAO;AAAA,IAChB;AAAA,EACF;AACF;;;ACrBO,SAAS,iBACd,MACA,gBACoB;AACpB,MAAI,UAAU;AACd,MAAI,UAAU;AACd,MAAI,OAA+B;AACnC,QAAM,YAAY,IAAI,gBAAgB;AACtC,QAAM,EAAE,OAAO,IAAI;AAEnB,QAAM,W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A,EAAE,GAAG,MAAM,MAAM,KAAK,MAAM,MAAM,OAAO,aAAa,IAAI,EAAE;AAAA,MAClE;AACA,YAAM,KAAK,KAAK;AAChB,aAAO;AAAA,IACT;AAAA,EACF;AACA,QAAM,MAAM,QAAQ;AACpB,QAAM,cACJ,QAAQ,OACJ,OACA,gBAAgB,KAAK,eAAe,EAAE,OAAO,SAAS,QAAQ,OAAO,CAAC;AAE5E,QAAM,cAAc,WAAW,UAAU,MAAM;AAG/C,QAAM,UAAU,cAAc;AAC9B,MAAI,mBAAmB,kBAAkB;AACvC,UAAM,QAAQ,cAAc,EAAE,QAAQ,OAAO;AAC7C,QAAI,SAAS,GAAG;AACd,iBAAW,MAAM,IAAI;AACrB,UAAI,EAAE,MAAM,SAAS,SAAS,MAAM,CAAC;AAAA,IACvC;AAAA,EACF;AACA,SAAO;AAEP,SAAO;AAAA,IACL,YAAY,CAAC,SAAS;AACpB,gBAAU;AACV,aAAO;AAAA,IACT;AAAA,IACA,OAAO;AAAA,IACP,UAAU,MAAM;AAAA,IAChB,QAAQ,MAAM;AACZ,gBAAU,MAAM;AAChB,iBAAW,OAAO;AAClB,mBAAa,OAAO;AACpB,kBAAY;AAAA,IACd;AAAA,EACF;AACF;","names":["document","DETACHED","pixels","READY","DETACHED","hasFocus","hasFocus","errorText","box"]}
|
|
1
|
+
{"version":3,"sources":["../src/abortSignals.ts","../src/announcer.ts","../src/form/attachFocusGroup.ts","../src/form/formControls.ts","../src/layout/attachFitCount.ts","../src/listbox/attachChecklist.ts","../src/writingDirection.ts","../src/listbox/attachCombobox.ts","../src/listbox/attachListbox.ts","../src/scheduleTimeout.ts","../src/listbox/choiceAnnouncer.ts","../src/overlay/overlayStack.ts","../src/overlay/placeOverlay.ts","../src/overlay/attachOverlay.ts","../src/rowVirtualizer.ts","../src/step/attachHoldRepeat.ts","../src/step/attachStepKeys.ts","../src/text/attachAutoGrow.ts","../src/text/applyEdit.ts","../src/text/attachTextInput.ts","../src/toggle/attachToggle.ts","../src/segments/attachSegments.ts"],"sourcesContent":["import type { AbortFactory } from \"@gridkitjs/forms-core\";\n\n/**\n * The browser's `AbortController` as a forms-core `AbortFactory`: each call\n * makes a fresh signal and the function that aborts it, for an option\n * source controller to hand each request.\n */\nexport const abortSignals: AbortFactory<AbortSignal> = () => {\n const controller = new AbortController();\n return {\n signal: controller.signal,\n abort: () => {\n controller.abort();\n },\n };\n};\n","/** A live region to report changes through. */\nexport interface LiveAnnouncer {\n /**\n * Has assistive technology read `text` out, politely — after whatever it is\n * already saying. The same text twice in a row is read twice.\n */\n readonly announce: (text: string) => void;\n /** Removes the live region. */\n readonly destroy: () => void;\n}\n\nexport interface LiveAnnouncerOptions {\n /**\n * The class on the live region, which the stylesheet clips to nothing\n * while leaving it in the accessibility tree. Defaults to\n * `\"gridkit-forms-sr-only\"`, which forms.css defines.\n */\n readonly className?: string | undefined;\n}\n\n/** Whitespace to a screen reader, but a change to the text it is watching. */\nconst NO_BREAK_SPACE = String.fromCodePoint(0xa0);\n\n/**\n * Creates a live region to report through — a reorder, a resize, a bulk\n * selection, anything no visual cue can carry to a screen reader — as the\n * last child of `container`.\n *\n * Polite rather than assertive, so an announcement waits for a pause instead\n * of cutting across what the user is already hearing. The element carries\n * `options.className`, a visually hidden class.\n *\n * A live region speaks only when its text changes, so a message identical to\n * the last would go unheard. A no-break space, added and dropped in turn,\n * makes the repeat a change without changing what is read.\n */\nexport function createLiveAnnouncer(\n container: HTMLElement = document.body,\n options: LiveAnnouncerOptions = {},\n): LiveAnnouncer {\n const region = document.createElement(\"div\");\n region.className = options.className ?? \"gridkit-forms-sr-only\";\n region.setAttribute(\"role\", \"status\");\n region.setAttribute(\"aria-live\", \"polite\");\n container.append(region);\n\n let last = \"\";\n let padded = false;\n\n return {\n announce(text) {\n padded = text === last && !padded;\n last = text;\n region.textContent = padded ? text + NO_BREAK_SPACE : text;\n },\n destroy() {\n region.remove();\n },\n };\n}\n","export interface FocusGroupOptions {\n /**\n * Focus left the group: by Tab or Shift+Tab (`\"tab\"`), or any other way\n * (`\"blur\"`), the window losing focus included.\n */\n readonly onLeave: (by: \"tab\" | \"blur\", nativeEvent: FocusEvent) => void;\n /**\n * Whether `node`, outside the group's root, still counts as inside the\n * group: a popup the input opened, portalled to the body. Focus moving\n * there is not a leave; focus moving on from there to anywhere that is\n * neither the root nor inside is.\n */\n readonly isInside?: ((node: Node) => boolean) | undefined;\n}\n\nexport interface AttachedFocusGroup {\n /** Replaces the options, from the next event on. */\n readonly setOptions: (options: FocusGroupOptions) => void;\n /** Removes every listener. */\n readonly detach: () => void;\n}\n\n/**\n * Tells focus moving between the controls inside `root` (the two ends of\n * a range) from focus leaving it, which a control's own blur cannot: a\n * `focusout` whose `relatedTarget` is outside `root`, or none, leaves the\n * group. A Tab that nothing prevented, pressed in the group just before,\n * makes it a leave by Tab.\n *\n * Focus moving to a node `isInside` names (a popup outside `root`) is not\n * a leave. While focus is out there, the group follows it on the document:\n * back into `root` it is home again, and anywhere else that is not inside\n * leaves the group.\n *\n * It holds whether the last key pressed in the group was such a Tab,\n * cleared by the next `focusout`, key or pointer press, and, while focus\n * is in a node `isInside` names, the document listeners that follow it.\n */\nexport function attachFocusGroup(\n root: HTMLElement,\n initialOptions: FocusGroupOptions,\n): AttachedFocusGroup {\n let options = initialOptions;\n let tabbing = false;\n let away: AbortController | null = null;\n const listeners = new AbortController();\n const { signal } = listeners;\n\n const isInside = (node: Node): boolean =>\n root.contains(node) || options.isInside?.(node) === true;\n\n function comeHome(): void {\n away?.abort();\n away = null;\n }\n\n function onKeyDown(event: KeyboardEvent): void {\n tabbing = event.key === \"Tab\" && !event.defaultPrevented;\n }\n\n function onPointerDown(): void {\n tabbing = false;\n }\n\n /** Focus has gone to a node `isInside` names, outside `root`: follow it. */\n function goAway(): void {\n if (away !== null) {\n return;\n }\n away = new AbortController();\n const document = root.ownerDocument;\n document.addEventListener(\n \"focusin\",\n (event) => {\n const { target } = event;\n if (!(target instanceof Node)) {\n return;\n }\n if (root.contains(target)) {\n comeHome();\n return;\n }\n if (isInside(target)) {\n return;\n }\n const by = tabbing ? \"tab\" : \"blur\";\n tabbing = false;\n comeHome();\n options.onLeave(by, event);\n },\n { signal: away.signal },\n );\n // Keys and presses in the popup tell a Tab out of it from any other leave.\n document.addEventListener(\n \"keydown\",\n (event) => {\n if (event.target instanceof Node && !root.contains(event.target)) {\n onKeyDown(event);\n }\n },\n { signal: away.signal },\n );\n document.addEventListener(\"pointerdown\", onPointerDown, {\n signal: away.signal,\n });\n }\n\n root.addEventListener(\"keydown\", onKeyDown, { signal });\n root.addEventListener(\"pointerdown\", onPointerDown, { signal });\n root.addEventListener(\n \"focusout\",\n (event) => {\n const by = tabbing ? \"tab\" : \"blur\";\n tabbing = false;\n const next = event.relatedTarget;\n if (next instanceof Node && root.contains(next)) {\n return;\n }\n if (next instanceof Node && isInside(next)) {\n goAway();\n return;\n }\n options.onLeave(by, event);\n },\n { signal },\n );\n\n return {\n setOptions: (next) => {\n options = next;\n },\n detach: () => {\n listeners.abort();\n comeHome();\n },\n };\n}\n","/** The form controls that take part in a form's validation and navigation. */\ntype FormControl = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;\n\n/** Input types Enter moves on from: single-line text, a checkbox, a switch. */\nconst ENTER_MOVES_FROM = new Set([\n \"text\",\n \"search\",\n \"email\",\n \"tel\",\n \"url\",\n \"password\",\n \"number\",\n \"checkbox\",\n]);\n\n/** Input types that hold no value a user types or picks. */\nconst NOT_EDITABLE = new Set([\"hidden\", \"button\", \"submit\", \"reset\", \"image\"]);\n\nfunction isFormControl(element: Element): element is FormControl {\n return (\n element.localName === \"input\" ||\n element.localName === \"select\" ||\n element.localName === \"textarea\"\n );\n}\n\n/** The controls of `form`, its `form`-attribute ones included, in document order. */\nfunction controlsOf(form: HTMLFormElement): FormControl[] {\n return [...form.elements].filter(isFormControl);\n}\n\n/**\n * The first control of `form`, in document order, that holds an invalid\n * value: a field showing an error, which forms sets as the control's\n * custom validity, or a native constraint of the app's own control such as\n * `required`. `null` when every control is valid. A disabled or read-only\n * control is never invalid, as for the browser's own validation.\n */\nexport function findFirstInvalidControl(\n form: HTMLFormElement,\n): HTMLElement | null {\n return (\n controlsOf(form).find(\n (control) => control.willValidate && !control.validity.valid,\n ) ?? null\n );\n}\n\n/**\n * The control a link to `target` should focus: `target` itself when it can\n * take focus, else the first control inside it, as for a group of inputs.\n */\nexport function focusTargetIn(target: HTMLElement): HTMLElement | null {\n if (isFormControl(target) || target.matches(\"button, [tabindex]\")) {\n return target;\n }\n return target.querySelector<HTMLElement>(\n \"input:not([type=hidden]), select, textarea, button, [tabindex]\",\n );\n}\n\n/** Whether a control can be moved to: enabled, editable and drawn. */\nfunction canMoveTo(control: FormControl): boolean {\n if (control instanceof HTMLInputElement && NOT_EDITABLE.has(control.type)) {\n return false;\n }\n const readOnly =\n (\"readOnly\" in control && control.readOnly) ||\n control.getAttribute(\"aria-readonly\") === \"true\";\n return !control.disabled && !readOnly && control.getClientRects().length > 0;\n}\n\n/**\n * Makes Enter in a single-line text field, a checkbox or a switch of\n * `form` move focus to the next control a user can change, in document\n * order, rather than submit the form. From the last one, Enter submits as\n * it would without this. Enter with a modifier, while an input method is\n * composing, or already handled (a field refusing its commit prevents it)\n * is left alone, as are a textarea, a select, a button and a link.\n * `detach` removes the listener.\n */\nexport function attachEnterNavigation(form: HTMLFormElement): {\n readonly detach: () => void;\n} {\n function onKeyDown(event: KeyboardEvent): void {\n const { target } = event;\n if (\n event.key !== \"Enter\" ||\n event.defaultPrevented ||\n event.isComposing ||\n event.altKey ||\n event.ctrlKey ||\n event.metaKey ||\n event.shiftKey ||\n !(target instanceof HTMLInputElement) ||\n !ENTER_MOVES_FROM.has(target.type)\n ) {\n return;\n }\n event.preventDefault();\n const controls = controlsOf(form);\n const next = controls\n .slice(controls.indexOf(target) + 1)\n .find((control) => canMoveTo(control));\n if (next === undefined) {\n form.requestSubmit();\n } else {\n next.focus();\n }\n }\n\n form.addEventListener(\"keydown\", onKeyDown);\n return {\n detach: () => {\n form.removeEventListener(\"keydown\", onKeyDown);\n },\n };\n}\n\n/**\n * Orders two elements as they come in the document, for sorting: negative\n * when `a` comes first.\n */\nexport function compareDocumentOrder(a: Node, b: Node): number {\n if (a === b) {\n return 0;\n }\n return a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING\n ? -1\n : 1;\n}\n","export interface FitCountOptions {\n /** The most items wanted side by side. */\n readonly max: number;\n /** Called with the count now, and again whenever it changes. */\n readonly onCount: (count: number) => void;\n}\n\nexport interface AttachedFitCount {\n /** Stops watching. */\n readonly detach: () => void;\n}\n\nfunction pixels(value: string): number {\n const parsed = Number.parseFloat(value);\n return Number.isNaN(parsed) ? 0 : parsed;\n}\n\n/**\n * Counts how many items as wide as `root`'s first child fit side by side\n * in the element around `root`, `root`'s column gap between them, from 1\n * to `max`: how many months a range calendar shows. It recounts whenever\n * that element or the item changes width (a `ResizeObserver`), and calls\n * `onCount` only when the count changes.\n *\n * It holds the observer and the last count; `detach` disconnects it.\n */\nexport function attachFitCount(\n root: HTMLElement,\n { max, onCount }: FitCountOptions,\n): AttachedFitCount {\n let count: number | null = null;\n const container = root.parentElement;\n\n function measure(): void {\n const item = root.firstElementChild;\n if (container === null || !(item instanceof HTMLElement)) {\n return;\n }\n const gap = pixels(getComputedStyle(root).columnGap);\n const room = container.clientWidth;\n const width = item.offsetWidth;\n const fits = width === 0 ? max : Math.floor((room + gap) / (width + gap));\n const next = Math.min(Math.max(fits, 1), max);\n if (next !== count) {\n count = next;\n onCount(next);\n }\n }\n\n const observer = new ResizeObserver(measure);\n if (container !== null) {\n observer.observe(container);\n }\n if (root.firstElementChild !== null) {\n observer.observe(root.firstElementChild);\n }\n measure();\n\n return {\n detach: () => {\n observer.disconnect();\n },\n };\n}\n","export interface ChecklistOptions {\n /**\n * The item at `index` — its place in the whole list — asks to be checked\n * or unchecked: Space on it, or a click. The caller flips it in its own\n * state and draws the new `aria-checked`.\n */\n readonly onToggle: (index: number) => void;\n /** Focus moved to the item at `index`, by a key, a click or a script. */\n readonly onFocusChange?: ((index: number) => void) | undefined;\n /**\n * Bring the item at `index` into view, mounting it if the list's window\n * does not hold it. A virtualized renderer forwards this to its\n * virtualizer's `scrollToIndex`, with `{ block: \"nearest\" }` so a move of\n * one item scrolls by one item.\n */\n readonly scrollToIndex: (index: number) => void;\n}\n\nexport interface AttachedChecklist {\n /**\n * How many items the whole list holds, mounted or not. Starts at 0, so a\n * renderer calls this straight after attaching, and again whenever the\n * list changes — a search narrowing it, say. A focused place past the new\n * end moves back to the last item, and so does a move still waiting for\n * an item past it.\n */\n readonly setCount: (count: number) => void;\n /**\n * Focuses the item at `index`, clamped to the list, scrolling to it first.\n * An item outside the mounted window is focused once it mounts.\n */\n readonly focusItem: (index: number) => void;\n /**\n * Removes every listener and observer. The list and its items keep their\n * `tabindex`.\n * After it, `setCount` and `focusItem` do nothing: they neither scroll\n * nor focus, and a move still waiting for its item is dropped.\n */\n readonly detach: () => void;\n}\n\nconst ITEM = \"[data-gridkit-checklist-item]\";\nconst INDEX = \"data-gridkit-checklist-index\";\n\n/**\n * Where focus is going besides the focused place: nowhere, to an item a move\n * is waiting to see mounted, or nowhere ever again once detached.\n */\ntype ChecklistState =\n | { readonly kind: \"settled\" }\n | { readonly kind: \"awaiting-item\"; readonly index: number }\n | { readonly kind: \"detached\" };\n\nconst SETTLED: ChecklistState = { kind: \"settled\" };\nconst DETACHED: ChecklistState = { kind: \"detached\" };\n\nfunction indexOf(item: Element): number {\n return Number(item.getAttribute(INDEX));\n}\n\n/**\n * Makes `list` — a `role=\"listbox\"` the renderer drew, usually virtualized\n * so that only a window of a long list is mounted — behave as a\n * multi-select checklist with one tab stop: the arrow keys, Home, End,\n * PageUp and PageDown move focus among its items, and Space or a click asks\n * for the focused item to be toggled. It decides; the caller is told through\n * the callbacks and draws the outcome, `aria-checked` included.\n *\n * Items are the list's descendants with `data-gridkit-checklist-item` and a\n * `data-gridkit-checklist-index`: their place in the whole list rather than\n * in the window, since an item's place is all that survives it being\n * unmounted and mounted again. The list is the element that scrolls: PageUp\n * and PageDown move by as many items as it shows whole.\n *\n * One item at a time has `tabindex=\"0\"` — the focused one, or the first\n * mounted while the focused one is scrolled away — and the rest `-1`, kept\n * so as items mount by an observer of the list's children rather than by\n * the renderer. The list itself gets `tabindex=\"-1\"`: a browser may make an\n * element that scrolls a tab stop of its own, as Firefox does, which would\n * put a second stop before the items' one, on an element the keys do not\n * move from. A move to an item outside the window asks `scrollToIndex`\n * for it and focuses it once it mounts, unless focus has gone somewhere\n * else in the meantime.\n *\n * Enter is not handled, so a form around the list hears it and applies;\n * Escape is the overlay stack's.\n */\nexport function attachChecklist(\n list: HTMLElement,\n options: ChecklistOptions,\n): AttachedChecklist {\n let count = 0;\n /** The focused place in the whole list: the tab stop, mounted or not. */\n let active = 0;\n let state: ChecklistState = SETTLED;\n\n function items(): HTMLElement[] {\n return Array.from(list.querySelectorAll<HTMLElement>(ITEM));\n }\n\n function itemAt(index: number): HTMLElement | null {\n return list.querySelector<HTMLElement>(\n `${ITEM}[${INDEX}=\"${String(index)}\"]`,\n );\n }\n\n function itemOf(target: EventTarget | null): HTMLElement | null {\n const item =\n target instanceof Element ? target.closest<HTMLElement>(ITEM) : null;\n return item !== null && list.contains(item) ? item : null;\n }\n\n function setTabStop(): void {\n const all = items();\n const stop = all.find((item) => indexOf(item) === active) ?? all[0];\n for (const item of all) {\n item.tabIndex = item === stop ? 0 : -1;\n }\n }\n\n function makeActive(index: number): void {\n if (index !== active) {\n active = index;\n options.onFocusChange?.(index);\n }\n }\n\n function moveTo(index: number): void {\n if (state.kind === \"detached\" || count === 0) {\n return;\n }\n const target = Math.max(0, Math.min(index, count - 1));\n makeActive(target);\n setTabStop();\n options.scrollToIndex(target);\n const item = itemAt(target);\n if (item === null) {\n state = { kind: \"awaiting-item\", index: target };\n } else {\n state = SETTLED;\n item.focus({ preventScroll: true });\n }\n }\n\n /** How many items the list shows whole, for PageUp and PageDown. */\n function pageSize(): number {\n const top = list.getBoundingClientRect().top + list.clientTop;\n const bottom = top + list.clientHeight;\n const whole = items().filter((item) => {\n const box = item.getBoundingClientRect();\n return box.top >= top && box.bottom <= bottom;\n }).length;\n return Math.max(1, whole);\n }\n\n // Every key it acts on is taken, so the list does not also scroll by\n // itself. A modified key is left for whatever shortcut it is. Moves count\n // from the focused place rather than the focused element, which lags\n // behind while a move waits for its item to mount.\n function onKeyDown(event: KeyboardEvent): void {\n const item = itemOf(event.target);\n if (\n item === null ||\n event.isComposing ||\n event.altKey ||\n event.ctrlKey ||\n event.metaKey ||\n event.shiftKey\n ) {\n return;\n }\n switch (event.key) {\n case \"ArrowDown\":\n moveTo(active + 1);\n break;\n case \"ArrowUp\":\n moveTo(active - 1);\n break;\n case \"Home\":\n moveTo(0);\n break;\n case \"End\":\n moveTo(count - 1);\n break;\n case \"PageDown\":\n moveTo(active + pageSize());\n break;\n case \"PageUp\":\n moveTo(active - pageSize());\n break;\n case \" \":\n // Held down, Space toggles once, as a checkbox does.\n if (!event.repeat) {\n options.onToggle(indexOf(item));\n }\n break;\n default:\n return;\n }\n event.preventDefault();\n }\n\n // However focus arrived — Tab, a click, a script — the tab stop follows it,\n // and a move still waiting for its item gives way.\n function onFocusIn(event: FocusEvent): void {\n const item = itemOf(event.target);\n if (item !== null) {\n state = SETTLED;\n makeActive(indexOf(item));\n setTabStop();\n }\n }\n\n function onClick(event: MouseEvent): void {\n const item = itemOf(event.target);\n if (item !== null) {\n options.onToggle(indexOf(item));\n item.focus({ preventScroll: true });\n }\n }\n\n // The item a move waits for takes focus only if focus is still in the\n // list, or dropped to nothing when the item it was on unmounted.\n function focusAwaitedItemIfMounted(): void {\n const item = state.kind === \"awaiting-item\" ? itemAt(state.index) : null;\n if (item === null) {\n return;\n }\n state = SETTLED;\n const focused = document.activeElement;\n if (\n focused === null ||\n focused === document.body ||\n list.contains(focused)\n ) {\n item.focus({ preventScroll: true });\n }\n }\n\n // Items mount and unmount as the window moves, and a kept element can take\n // another place when the list changes under it.\n const observer = new MutationObserver(() => {\n setTabStop();\n focusAwaitedItemIfMounted();\n });\n observer.observe(list, {\n childList: true,\n subtree: true,\n attributeFilter: [INDEX],\n });\n\n list.tabIndex = -1;\n setTabStop();\n list.addEventListener(\"keydown\", onKeyDown);\n list.addEventListener(\"focusin\", onFocusIn);\n list.addEventListener(\"click\", onClick);\n\n return {\n setCount(next) {\n if (state.kind === \"detached\") {\n return;\n }\n count = next;\n active = Math.max(0, Math.min(active, count - 1));\n if (state.kind === \"awaiting-item\") {\n state =\n count === 0\n ? SETTLED\n : {\n kind: \"awaiting-item\",\n index: Math.min(state.index, count - 1),\n };\n }\n setTabStop();\n focusAwaitedItemIfMounted();\n },\n focusItem: moveTo,\n detach() {\n state = DETACHED;\n observer.disconnect();\n list.removeEventListener(\"keydown\", onKeyDown);\n list.removeEventListener(\"focusin\", onFocusIn);\n list.removeEventListener(\"click\", onClick);\n },\n };\n}\n","import type { WritingDirection } from \"@gridkitjs/forms-core\";\n\n/**\n * The way `element`'s lines run, from its computed `direction`: what it\n * inherits from a `dir` attribute on it or an ancestor, or from the CSS\n * `direction` property. Read afresh on every call, never kept, so a page\n * whose direction changes is followed from the next key press, gesture or\n * overlay on.\n */\nexport function writingDirection(element: Element): WritingDirection {\n return getComputedStyle(element).direction === \"rtl\" ? \"rtl\" : \"ltr\";\n}\n","import type {\n FieldController,\n PopupCloseReason,\n PopupOpenReason,\n} from \"@gridkitjs/forms-core\";\nimport { writingDirection } from \"../writingDirection\";\nimport type { AttachedListbox } from \"./attachListbox\";\n\n/**\n * What `attachCombobox` asks of the field: a select-only control has no\n * text pipeline, so it starts, commits, ends and reverts the edit itself.\n */\nexport type ComboboxController<V, D extends object> = Pick<\n FieldController<V, D, Event>,\n \"focus\" | \"blur\" | \"commit\" | \"revert\"\n>;\n\n/** What a renderer can change about a combobox while it is attached. */\nexport interface ComboboxOptions {\n /** The open popup's listbox, attached in `\"active-descendant\"` mode; `null` while closed. */\n readonly listbox: AttachedListbox | null;\n /** The popup panel while open, so a press in it leaves focus in the control. */\n readonly panel: HTMLElement | null;\n /**\n * A text box (a searchable select, an autocomplete, a tag input), which\n * `attachTextInput` drives and keeps its typing, Home, End and Space; or\n * a select-only button, whose keys all go to the list.\n */\n readonly editable: boolean;\n /** Several values: Shift with the arrows and Ctrl+A reach a select-only list. */\n readonly multiple: boolean;\n /** Tab with the popup open chooses the active row, with one value. */\n readonly tabChooses: boolean;\n /** Nothing opens the popup. */\n readonly readOnly: boolean;\n readonly onOpenRequest: (reason: PopupOpenReason, nativeEvent: Event) => void;\n readonly onCloseRequest: (\n reason: PopupCloseReason,\n nativeEvent: Event,\n ) => void;\n /**\n * The chips before the text: the key toward them (←, or → right to left)\n * at the start of the text, or Backspace with no text.\n */\n readonly onChipKey?:\n | ((key: \"previous\" | \"remove-last\", nativeEvent: KeyboardEvent) => void)\n | undefined;\n}\n\nexport interface AttachedCombobox {\n /** Replaces the options: the latest listbox and panel, after each open and close. */\n readonly setOptions: (options: ComboboxOptions) => void;\n /**\n * Removes every listener and the `aria-controls` and\n * `aria-activedescendant` it wrote. The controller is left as it is.\n */\n readonly detach: () => void;\n}\n\n/** Keys that open a closed popup from any combobox. */\nconst OPEN_KEYS = new Set([\"ArrowDown\", \"ArrowUp\", \"F4\"]);\n\n/** Keys that also open a closed select-only popup. */\nconst SELECT_ONLY_OPEN_KEYS = new Set([\"Enter\", \" \", \"Home\", \"End\"]);\n\nfunction hasFocus(control: HTMLElement): boolean {\n const root = control.getRootNode();\n return (\n (root instanceof Document || root instanceof ShadowRoot) &&\n root.activeElement === control\n );\n}\n\nfunction isPrintable(event: KeyboardEvent): boolean {\n return (\n !event.ctrlKey &&\n !event.metaKey &&\n !event.altKey &&\n Array.from(event.key).length === 1\n );\n}\n\n/** The text box's caret is at its very start, with nothing selected. */\nfunction caretAtStart(control: HTMLElement): boolean {\n return (\n (control instanceof HTMLInputElement ||\n control instanceof HTMLTextAreaElement) &&\n control.selectionStart === 0 &&\n control.selectionEnd === 0\n );\n}\n\nfunction textOf(control: HTMLElement): string {\n return control instanceof HTMLInputElement ||\n control instanceof HTMLTextAreaElement\n ? control.value\n : \"\";\n}\n\n/**\n * Makes `control`, a `role=\"combobox\"` the renderer drew (a text box or a\n * select-only button), drive the popup listbox of the WAI-ARIA combobox:\n * focus stays in the control, and its keys open the popup, move the list's\n * active row and choose.\n *\n * - Closed, ↓, ↑, F4 and Alt+↓ ask to open it (`\"keyboard\"`); a\n * select-only control also opens on Enter, Space, Home and End, and on a\n * printable key (`\"typing\"`), which goes on to the list's type-ahead\n * once it is open. A text box opens as it is typed in (`\"typing\"`), and\n * either opens on a press (`\"button\"`).\n * - Open, the keys go to `listbox.handleKey`: in a text box only ↓, ↑,\n * PageDown, PageUp and Enter (Home and End move the caret and clear the\n * active row, as the WAI-ARIA editable combobox does). Escape asks to\n * close (`\"escape\"`), F4 and Alt+↑ too (`\"button\"`), and so does a press\n * on a select-only control. Tab leaves, choosing the active row first\n * with `tabChooses`, and asks to close (`\"blur\"`), as leaving does.\n * - It listens in the capture phase, so a key it takes is prevented before\n * `attachTextInput` sees it and skips it.\n * - A select-only control calls the controller's `focus` and `blur`,\n * commits on Tab (staying when the commit is refused), and reverts on\n * Escape while closed. A text box leaves those to `attachTextInput`.\n * - It prevents `mousedown` on the panel, which keeps focus in the control\n * and still lets the click through (WebKit sends no click after a tap\n * whose `pointerdown` was prevented).\n *\n * It writes `aria-expanded`, `aria-controls` (the listbox's `id`) and\n * `aria-activedescendant` (the active row's `id` while it is mounted) on\n * the control.\n */\nexport function attachCombobox<V, D extends object>(\n control: HTMLElement,\n controller: ComboboxController<V, D>,\n initialOptions: ComboboxOptions,\n): AttachedCombobox {\n let options = initialOptions;\n let attached = true;\n /**\n * Printable keys typed on a closed select-only control, for the list's\n * type-ahead once the popup they opened has its list.\n */\n let pendingKeys: KeyboardEvent[] = [];\n let unsubscribe: (() => void) | null = null;\n let panelEvents: AbortController | null = null;\n const events = new AbortController();\n const { signal } = events;\n\n const isOpen = (): boolean => options.listbox !== null;\n\n function writeAria(): void {\n if (!attached) {\n return;\n }\n const { listbox } = options;\n control.setAttribute(\"aria-expanded\", String(listbox !== null));\n const listId = listbox?.element.id ?? \"\";\n if (listId === \"\") {\n control.removeAttribute(\"aria-controls\");\n } else {\n control.setAttribute(\"aria-controls\", listId);\n }\n const activeId = listbox?.activeId() ?? null;\n if (activeId === null) {\n control.removeAttribute(\"aria-activedescendant\");\n } else {\n control.setAttribute(\"aria-activedescendant\", activeId);\n }\n }\n\n function connect(\n next: ComboboxOptions,\n previous: ComboboxOptions | null,\n ): void {\n if (next.listbox !== previous?.listbox) {\n unsubscribe?.();\n unsubscribe = next.listbox?.subscribe(writeAria) ?? null;\n }\n if (next.panel !== previous?.panel) {\n panelEvents?.abort();\n panelEvents = null;\n if (next.panel !== null) {\n panelEvents = new AbortController();\n next.panel.addEventListener(\n \"mousedown\",\n (event) => {\n event.preventDefault();\n },\n { signal: panelEvents.signal },\n );\n }\n }\n }\n\n function requestOpen(reason: PopupOpenReason, event: Event): void {\n if (!options.readOnly) {\n options.onOpenRequest(reason, event);\n }\n }\n\n /** Hands the keys that opened the popup to the list, once there is one. */\n function forwardPendingKeys(): void {\n const { listbox } = options;\n if (listbox === null) {\n return;\n }\n const keys = pendingKeys;\n pendingKeys = [];\n for (const key of keys) {\n listbox.handleKey(key);\n }\n }\n\n function onChipKey(event: KeyboardEvent): boolean {\n const { onChipKey: handler } = options;\n if (\n handler === undefined ||\n event.ctrlKey ||\n event.metaKey ||\n event.altKey\n ) {\n return false;\n }\n const previousKey =\n writingDirection(control) === \"rtl\" ? \"ArrowRight\" : \"ArrowLeft\";\n if (\n event.key === previousKey &&\n !event.shiftKey &&\n (!options.editable || caretAtStart(control))\n ) {\n handler(\"previous\", event);\n return true;\n }\n if (event.key === \"Backspace\" && textOf(control) === \"\") {\n handler(\"remove-last\", event);\n return true;\n }\n return false;\n }\n\n function onClosedKey(event: KeyboardEvent): boolean {\n const { editable } = options;\n if (event.key === \"Escape\") {\n return !editable && controller.revert(event);\n }\n if (event.ctrlKey || event.metaKey) {\n return false;\n }\n if (\n (OPEN_KEYS.has(event.key) &&\n (!event.altKey || event.key === \"ArrowDown\")) ||\n (!editable && !event.altKey && SELECT_ONLY_OPEN_KEYS.has(event.key))\n ) {\n requestOpen(\"keyboard\", event);\n return true;\n }\n if (!editable && isPrintable(event) && !options.readOnly) {\n pendingKeys.push(event);\n requestOpen(\"typing\", event);\n forwardPendingKeys();\n return true;\n }\n return onChipKey(event);\n }\n\n /** Keys a select-only list takes but a text box keeps. */\n function textBoxKeeps(event: KeyboardEvent): boolean {\n return (\n event.key === \"Home\" ||\n event.key === \"End\" ||\n event.key === \" \" ||\n isPrintable(event) ||\n ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === \"a\") ||\n (event.shiftKey && (event.key === \"ArrowDown\" || event.key === \"ArrowUp\"))\n );\n }\n\n function onOpenKey(event: KeyboardEvent, listbox: AttachedListbox): boolean {\n switch (event.key) {\n case \"Escape\":\n options.onCloseRequest(\"escape\", event);\n return true;\n case \"F4\":\n options.onCloseRequest(\"button\", event);\n return true;\n }\n if (event.altKey) {\n if (event.key === \"ArrowUp\") {\n options.onCloseRequest(\"button\", event);\n return true;\n }\n return false;\n }\n if (options.editable && textBoxKeeps(event)) {\n if (event.key === \"Home\" || event.key === \"End\") {\n listbox.activate(null, \"keyboard\");\n }\n return false;\n }\n if (listbox.handleKey(event)) {\n return true;\n }\n return onChipKey(event);\n }\n\n /** Tab always leaves; it is prevented only when a select-only commit is refused. */\n function onTab(event: KeyboardEvent): void {\n if (event.ctrlKey || event.altKey || event.metaKey) {\n return;\n }\n const { listbox } = options;\n if (\n listbox !== null &&\n options.tabChooses &&\n !options.multiple &&\n !event.shiftKey\n ) {\n listbox.chooseActive(event);\n }\n // A choice may have closed the popup already.\n if (isOpen()) {\n options.onCloseRequest(\"blur\", event);\n }\n // A select-only control commits here, as the text pipeline does for a\n // text box, so leaving does not commit again.\n if (\n !options.editable &&\n controller.commit(\"tab\", event).kind === \"refused\"\n ) {\n event.preventDefault();\n }\n }\n\n function onKeyDown(event: KeyboardEvent): void {\n if (event.defaultPrevented || event.isComposing) {\n return;\n }\n if (event.key === \"Tab\") {\n onTab(event);\n return;\n }\n const { listbox } = options;\n const taken =\n listbox === null ? onClosedKey(event) : onOpenKey(event, listbox);\n if (taken) {\n event.preventDefault();\n }\n }\n\n function onInput(event: Event): void {\n if (options.editable && !isOpen()) {\n requestOpen(\"typing\", event);\n }\n }\n\n function onClick(event: MouseEvent): void {\n if (!isOpen()) {\n requestOpen(\"button\", event);\n } else if (!options.editable) {\n options.onCloseRequest(\"button\", event);\n }\n }\n\n function onFocus(event: FocusEvent): void {\n if (!options.editable) {\n controller.focus(event);\n }\n }\n\n function onBlur(event: FocusEvent): void {\n pendingKeys = [];\n if (isOpen()) {\n options.onCloseRequest(\"blur\", event);\n }\n if (!options.editable) {\n controller.blur(event);\n }\n }\n\n control.addEventListener(\"keydown\", onKeyDown, { signal, capture: true });\n control.addEventListener(\"input\", onInput, { signal });\n control.addEventListener(\"click\", onClick, { signal });\n control.addEventListener(\"focus\", onFocus, { signal });\n control.addEventListener(\"blur\", onBlur, { signal });\n connect(options, null);\n writeAria();\n\n // A control focused before it was attached (`autofocus`) starts its edit now.\n if (!options.editable && hasFocus(control)) {\n controller.focus(null);\n }\n\n return {\n setOptions(next) {\n if (!attached) {\n return;\n }\n const previous = options;\n options = next;\n connect(next, previous);\n if (previous.listbox !== null && next.listbox === null) {\n pendingKeys = [];\n }\n writeAria();\n forwardPendingKeys();\n },\n detach() {\n if (!attached) {\n return;\n }\n attached = false;\n events.abort();\n panelEvents?.abort();\n unsubscribe?.();\n pendingKeys = [];\n control.removeAttribute(\"aria-controls\");\n control.removeAttribute(\"aria-activedescendant\");\n },\n };\n}\n","import {\n isLandingRow,\n moveActive,\n typeaheadRow,\n type ActiveMove,\n type DisabledOptions,\n type TypeaheadRow,\n} from \"@gridkitjs/forms-core\";\n\n/**\n * How the active row is shown to assistive technology:\n * `\"active-descendant\"` keeps focus on a combobox, whose\n * `aria-activedescendant` points at the row; `\"roving\"` gives the active\n * row focus, the list's one tab stop.\n */\nexport type ListboxFocus = \"active-descendant\" | \"roving\";\n\n/** What the listbox needs of each row, mounted or not. */\nexport interface ListboxRow extends TypeaheadRow {\n /**\n * What identifies the row across changes of the list: an option's key\n * as text, or the action's kind. The active row is kept by it.\n */\n readonly key: string;\n}\n\n/** What a choice asks for. */\nexport type ListboxChoice =\n /** Enter or a click with one value; Space in a popup or with one value. */\n | { readonly kind: \"one\" }\n /** Enter, Space or a click with several values; Ctrl or Cmd with a click. */\n | { readonly kind: \"toggle\" }\n /** Several values: every row from `anchor` to the chosen one. */\n | { readonly kind: \"range\"; readonly anchor: number }\n /** Ctrl+A with several values. */\n | { readonly kind: \"all\" };\n\n/**\n * What made a row active: a key, the mouse, the renderer as the search\n * text changed (`\"typing\"`) or as the popup opened (`\"open\"`), or the list\n * changing under the active row (`\"list\"`).\n */\nexport type ListboxActivation =\n \"keyboard\" | \"pointer\" | \"typing\" | \"open\" | \"list\";\n\n/** How a row is brought into view: by as little as it takes, or to the middle. */\nexport type ListboxAlign = \"nearest\" | \"center\";\n\nexport interface ListboxOptions {\n readonly focus: ListboxFocus;\n /** Several values: Space and clicks toggle, Shift ranges, Ctrl+A chooses all. */\n readonly multiple: boolean;\n /** Printable keys find a row by its label; off where a text box takes them. */\n readonly typeahead: boolean;\n /** The locale the typed text is folded in, as the rows' `typeahead` was. */\n readonly locale?: Intl.LocalesArgument;\n /** Whether the keys reach disabled options. Default `\"skip\"`. */\n readonly disabledOptions?: DisabledOptions | undefined;\n /** With one value, a key that moves the active row also chooses it. */\n readonly selectionFollowsFocus?: boolean | undefined;\n readonly onActiveChange: (\n index: number | null,\n by: ListboxActivation,\n ) => void;\n /** A row is chosen. Never a header or a disabled row. */\n readonly onChoose: (\n index: number,\n choice: ListboxChoice,\n nativeEvent: Event,\n ) => void;\n /**\n * Brings row `index` into view, mounting it if the list's window does\n * not hold it: a virtualized renderer forwards this to its virtualizer's\n * `scrollToIndex` with `block` set to `align`.\n */\n readonly scrollToIndex: (index: number, align: ListboxAlign) => void;\n /**\n * One of the last five rows mounted or became active: time to load the\n * next page. Called once for each length of the list.\n */\n readonly onNearEnd?: (() => void) | undefined;\n}\n\nexport interface AttachedListbox {\n /** The list element it was attached to. */\n readonly element: HTMLElement;\n /**\n * Every row, mounted or not; call after each change of the list. The\n * active row is kept by `key`, else it moves to the nearest row it can\n * land on, and `onActiveChange` hears it with `\"list\"`.\n */\n readonly setRows: (rows: readonly ListboxRow[]) => void;\n /** Replaces the options, from the next event on. */\n readonly setOptions: (options: ListboxOptions) => void;\n /**\n * Makes row `index` active and scrolls to it (to the middle when `by` is\n * `\"open\"`, not at all when it is `\"pointer\"`); in roving mode it also\n * takes focus, once mounted. `null` clears the active row.\n */\n readonly activate: (index: number | null, by: ListboxActivation) => void;\n /**\n * Active-descendant mode: a key pressed in the combobox. True when the\n * listbox acted on it, and then the key is prevented.\n */\n readonly handleKey: (event: KeyboardEvent) => boolean;\n /** Chooses the active row as Enter with one value would; false when none can be. */\n readonly chooseActive: (nativeEvent: Event) => boolean;\n readonly getActive: () => number | null;\n /** The active row's `id` while it is mounted, else `null`: what `aria-activedescendant` holds. */\n readonly activeId: () => string | null;\n /** Calls `listener` whenever `activeId()` may have changed. */\n readonly subscribe: (listener: () => void) => () => void;\n /**\n * Removes every listener, the observer and the type-ahead timer; every\n * method does nothing after it. The rows keep their `tabindex`.\n */\n readonly detach: () => void;\n}\n\nconst ROW_ATTRIBUTE = \"data-gridkit-forms-row\";\nconst ROW = `[${ROW_ATTRIBUTE}]`;\n\n/** How long typing must pause before type-ahead starts a new word. */\nconst TYPEAHEAD_RESET = 500;\n\n/** How close to the end a row must be for `onNearEnd`. */\nconst NEAR_END = 5;\n\n/**\n * Where the active row is: nowhere, on a row, on a row whose focus waits\n * for it to mount (roving mode, scrolled out of the window), or nowhere\n * ever again once detached.\n */\ntype ListboxState =\n | { readonly kind: \"inactive\" }\n | { readonly kind: \"active\"; readonly index: number }\n | { readonly kind: \"awaiting\"; readonly index: number }\n | { readonly kind: \"detached\" };\n\nconst INACTIVE: ListboxState = { kind: \"inactive\" };\n\nfunction rowIndex(row: Element): number {\n return Number(row.getAttribute(ROW_ATTRIBUTE));\n}\n\n/** The landing row nearest `from`: at or after it, else before it. */\nfunction nearestLanding(\n rows: readonly ListboxRow[],\n from: number,\n disabledOptions: DisabledOptions,\n): number | null {\n for (let index = Math.max(from, 0); index < rows.length; index++) {\n const row = rows[index];\n if (row !== undefined && isLandingRow(row, disabledOptions)) {\n return index;\n }\n }\n for (let index = Math.min(from, rows.length) - 1; index >= 0; index--) {\n const row = rows[index];\n if (row !== undefined && isLandingRow(row, disabledOptions)) {\n return index;\n }\n }\n return null;\n}\n\n/** A printable key: one character, typed without Ctrl, Cmd or Alt. */\nfunction isPrintable(event: KeyboardEvent): boolean {\n return (\n !event.ctrlKey &&\n !event.metaKey &&\n !event.altKey &&\n Array.from(event.key).length === 1\n );\n}\n\n/**\n * Makes `list`, a `role=\"listbox\"` the renderer drew (usually virtualized,\n * so only a window of a long list is mounted), behave as the WAI-ARIA\n * listbox: the arrow keys, Home, End, PageUp and PageDown move the active\n * row, stopping at the ends; printable keys find a row by its label; Enter,\n * Space and clicks choose; with several values Shift ranges and Ctrl+A\n * chooses all. It decides; the renderer is told through the callbacks and\n * draws the outcome, `aria-selected` or `aria-checked` included.\n *\n * Rows are the list's descendants with `data-gridkit-forms-row` holding\n * their place in the whole list, which is all that survives a row being\n * unmounted and mounted again; `setRows` describes every row, mounted or\n * not. Headers are never active, and disabled options only with\n * `disabledOptions: \"focus\"`; neither is ever chosen. The list is the\n * element that scrolls: PageUp and PageDown move by as many rows as it\n * shows whole.\n *\n * In `\"active-descendant\"` mode focus stays in a combobox, which hands its\n * keys to `handleKey` (`attachCombobox` does) and points\n * `aria-activedescendant` at `activeId()`, so rows need an `id`. The mouse\n * moving over a row makes it active (a touch does not, so nothing lights\n * up before a tap), and a click chooses. A move key while the active row\n * is scrolled out of the window first scrolls back to it.\n *\n * In `\"roving\"` mode the active row holds focus and is the one row with\n * `tabindex=\"0\"` (the first mounted row it can land on while none is\n * active or the active one is scrolled away), kept so by an observer as\n * rows mount. Enter is left for a form around the list. A click chooses\n * and focuses, Ctrl or Cmd with a click toggles, Shift with a click\n * ranges.\n *\n * The list itself gets `tabindex=\"-1\"` in both modes: a browser may make\n * an element that scrolls a tab stop of its own, as Firefox does.\n */\nexport function attachListbox(\n list: HTMLElement,\n initialOptions: ListboxOptions,\n): AttachedListbox {\n let options = initialOptions;\n let rows: readonly ListboxRow[] = [];\n let state: ListboxState = INACTIVE;\n /** The row a range starts from, by key: the last one chosen alone. */\n let anchorKey: string | null = null;\n let typed = \"\";\n let typeaheadTimer: ReturnType<typeof setTimeout> | undefined;\n /** The list length `onNearEnd` was last called for. */\n let nearEndFor = -1;\n /** A pointer is pressed, so the focus it brings is the pointer's. */\n let pointerPressed = false;\n const listeners = new Set<() => void>();\n const events = new AbortController();\n const { signal } = events;\n\n const disabledOptions = (): DisabledOptions =>\n options.disabledOptions ?? \"skip\";\n const roving = (): boolean => options.focus === \"roving\";\n\n function activeIndex(): number | null {\n return state.kind === \"active\" || state.kind === \"awaiting\"\n ? state.index\n : null;\n }\n\n function rowElement(index: number): HTMLElement | null {\n return list.querySelector<HTMLElement>(\n `[${ROW_ATTRIBUTE}=\"${String(index)}\"]`,\n );\n }\n\n function rowOf(target: EventTarget | null): HTMLElement | null {\n const row =\n target instanceof Element ? target.closest<HTMLElement>(ROW) : null;\n return row !== null && list.contains(row) ? row : null;\n }\n\n function notify(): void {\n for (const listener of [...listeners]) {\n listener();\n }\n }\n\n function setTabStop(): void {\n if (!roving()) {\n return;\n }\n const mounted = Array.from(list.querySelectorAll<HTMLElement>(ROW));\n const active = activeIndex();\n const stop =\n mounted.find((row) => rowIndex(row) === active) ??\n mounted.find((row) => {\n const described = rows[rowIndex(row)];\n return (\n described !== undefined && isLandingRow(described, disabledOptions())\n );\n });\n for (const row of mounted) {\n row.tabIndex = row === stop ? 0 : -1;\n }\n }\n\n function checkNearEnd(): void {\n if (options.onNearEnd === undefined || nearEndFor === rows.length) {\n return;\n }\n const threshold = rows.length - NEAR_END;\n const active = activeIndex();\n const last = Array.from(list.querySelectorAll(ROW)).at(-1);\n if (\n (active !== null && active >= threshold) ||\n (last !== undefined && rowIndex(last) >= threshold)\n ) {\n nearEndFor = rows.length;\n options.onNearEnd();\n }\n }\n\n /** Brings the state's focus to its row in roving mode, once mounted. */\n function focusActiveRow(): void {\n if (!roving() || (state.kind !== \"active\" && state.kind !== \"awaiting\")) {\n return;\n }\n const row = rowElement(state.index);\n if (row === null) {\n state = { kind: \"awaiting\", index: state.index };\n } else {\n state = { kind: \"active\", index: state.index };\n row.focus({ preventScroll: true });\n }\n }\n\n function setActive(\n index: number | null,\n by: ListboxActivation,\n align: ListboxAlign | null,\n ): void {\n if (state.kind === \"detached\") {\n return;\n }\n const previous = activeIndex();\n if (index === null || rows[index] === undefined) {\n state = INACTIVE;\n } else {\n state = { kind: \"active\", index };\n if (align !== null) {\n options.scrollToIndex(index, align);\n }\n focusActiveRow();\n }\n const next = activeIndex();\n if (next !== previous) {\n options.onActiveChange(next, by);\n }\n setTabStop();\n notify();\n checkNearEnd();\n }\n\n function anchorFor(fallback: number): number {\n const index =\n anchorKey === null ? -1 : rows.findIndex((row) => row.key === anchorKey);\n if (index !== -1) {\n return index;\n }\n anchorKey = rows[fallback]?.key ?? null;\n return fallback;\n }\n\n /** Chooses row `index`; false when it cannot be chosen. */\n function choose(index: number, choice: ListboxChoice, event: Event): boolean {\n const row = rows[index];\n if (row === undefined || row.kind === \"header\") {\n return false;\n }\n if (choice.kind !== \"all\" && row.disabled) {\n return false;\n }\n if (choice.kind === \"one\" || choice.kind === \"toggle\") {\n anchorKey = row.key;\n }\n options.onChoose(index, choice, event);\n return true;\n }\n\n function chooseAlone(index: number, event: Event): void {\n choose(index, { kind: options.multiple ? \"toggle\" : \"one\" }, event);\n }\n\n /** How many rows the list shows whole, for PageUp and PageDown. */\n function pageSize(): number {\n const top = list.getBoundingClientRect().top + list.clientTop;\n const bottom = top + list.clientHeight;\n const whole = Array.from(list.querySelectorAll(ROW)).filter((row) => {\n const box = row.getBoundingClientRect();\n return box.top >= top && box.bottom <= bottom;\n }).length;\n return Math.max(1, whole);\n }\n\n function move(step: ActiveMove, event: KeyboardEvent): boolean {\n const from = activeIndex();\n const relative = step.kind !== \"first\" && step.kind !== \"last\";\n if (relative && from !== null && !roving() && rowElement(from) === null) {\n options.scrollToIndex(from, \"nearest\");\n return true;\n }\n const to = moveActive(rows, from, step, disabledOptions());\n if (to === null) {\n return true;\n }\n const ranging = event.shiftKey && options.multiple;\n const anchor = ranging ? anchorFor(from ?? to) : null;\n setActive(to, \"keyboard\", \"nearest\");\n if (to === from) {\n return true;\n }\n if (anchor !== null) {\n choose(to, { kind: \"range\", anchor }, event);\n } else if (options.selectionFollowsFocus === true && !options.multiple) {\n choose(to, { kind: \"one\" }, event);\n }\n return true;\n }\n\n function typeahead(event: KeyboardEvent): boolean {\n if (!options.typeahead || !isPrintable(event)) {\n return false;\n }\n // Space types only within a word, so on its own it still chooses.\n if (event.key === \" \" && typed === \"\") {\n return false;\n }\n typed += event.key;\n clearTimeout(typeaheadTimer);\n typeaheadTimer = setTimeout(() => {\n typed = \"\";\n }, TYPEAHEAD_RESET);\n const from = activeIndex();\n const to = typeaheadRow(\n rows,\n from,\n typed,\n options.locale,\n disabledOptions(),\n );\n if (to !== null && to !== from) {\n setActive(to, \"keyboard\", \"nearest\");\n if (options.selectionFollowsFocus === true && !options.multiple) {\n choose(to, { kind: \"one\" }, event);\n }\n }\n return true;\n }\n\n function space(event: KeyboardEvent): boolean {\n const active = activeIndex();\n if (active === null) {\n return false;\n }\n // Held down, Space chooses once.\n if (event.repeat) {\n return true;\n }\n if (!roving()) {\n chooseAlone(active, event);\n } else if (options.multiple && event.shiftKey) {\n choose(active, { kind: \"range\", anchor: anchorFor(active) }, event);\n } else {\n chooseAlone(active, event);\n }\n return true;\n }\n\n function onKey(event: KeyboardEvent): boolean {\n if (state.kind === \"detached\" || event.isComposing || event.altKey) {\n return false;\n }\n const modified = event.ctrlKey || event.metaKey;\n if (typeahead(event)) {\n return true;\n }\n switch (event.key) {\n case \"ArrowDown\":\n return !modified && move({ kind: \"next\" }, event);\n case \"ArrowUp\":\n return !modified && move({ kind: \"previous\" }, event);\n case \"PageDown\":\n return !modified && move({ kind: \"pageDown\", rows: pageSize() }, event);\n case \"PageUp\":\n return !modified && move({ kind: \"pageUp\", rows: pageSize() }, event);\n // Ctrl+Shift+Home and End range as Shift+Home and End do.\n case \"Home\":\n return (!modified || event.shiftKey) && move({ kind: \"first\" }, event);\n case \"End\":\n return (!modified || event.shiftKey) && move({ kind: \"last\" }, event);\n case \"Enter\": {\n const active = activeIndex();\n if (roving() || active === null) {\n return false;\n }\n chooseAlone(active, event);\n return true;\n }\n case \" \":\n return !modified && space(event);\n case \"a\":\n case \"A\": {\n if (!modified || !options.multiple) {\n return false;\n }\n const target =\n activeIndex() ?? nearestLanding(rows, 0, disabledOptions());\n return target !== null && choose(target, { kind: \"all\" }, event);\n }\n default:\n return false;\n }\n }\n\n function onKeyDown(event: KeyboardEvent): void {\n if (roving() && onKey(event)) {\n event.preventDefault();\n }\n }\n\n function onFocusIn(event: FocusEvent): void {\n const row = rowOf(event.target);\n if (!roving() || row === null || state.kind === \"detached\") {\n return;\n }\n const index = rowIndex(row);\n const previous = activeIndex();\n state = { kind: \"active\", index };\n if (index !== previous) {\n options.onActiveChange(index, pointerPressed ? \"pointer\" : \"keyboard\");\n }\n setTabStop();\n notify();\n checkNearEnd();\n }\n\n function onPointerMove(event: PointerEvent): void {\n if (roving() || event.pointerType !== \"mouse\") {\n return;\n }\n const row = rowOf(event.target);\n if (row === null) {\n return;\n }\n const index = rowIndex(row);\n const described = rows[index];\n if (\n index !== activeIndex() &&\n described !== undefined &&\n isLandingRow(described, disabledOptions())\n ) {\n setActive(index, \"pointer\", null);\n }\n }\n\n function onClick(event: MouseEvent): void {\n const row = rowOf(event.target);\n const index = row === null ? -1 : rowIndex(row);\n const described = rows[index];\n if (\n row === null ||\n state.kind === \"detached\" ||\n described === undefined ||\n !isLandingRow(described, disabledOptions())\n ) {\n return;\n }\n setActive(index, \"pointer\", null);\n if (roving() && options.multiple && event.shiftKey) {\n choose(index, { kind: \"range\", anchor: anchorFor(index) }, event);\n } else if (roving() && (event.ctrlKey || event.metaKey)) {\n choose(index, { kind: \"toggle\" }, event);\n } else {\n chooseAlone(index, event);\n }\n }\n\n // Rows mount and unmount as the window moves, and a kept element can take\n // another place when the list changes under it.\n const observer = new MutationObserver(() => {\n setTabStop();\n if (state.kind === \"awaiting\") {\n const row = rowElement(state.index);\n const focused = document.activeElement;\n if (row !== null) {\n state = { kind: \"active\", index: state.index };\n // Focus has gone elsewhere in the meantime: leave it there.\n if (\n focused === null ||\n focused === document.body ||\n list.contains(focused)\n ) {\n row.focus({ preventScroll: true });\n }\n }\n }\n notify();\n checkNearEnd();\n });\n observer.observe(list, {\n childList: true,\n subtree: true,\n attributeFilter: [ROW_ATTRIBUTE],\n });\n\n list.tabIndex = -1;\n list.addEventListener(\"keydown\", onKeyDown, { signal });\n list.addEventListener(\"focusin\", onFocusIn, { signal });\n list.addEventListener(\"pointermove\", onPointerMove, { signal });\n list.addEventListener(\"click\", onClick, { signal });\n list.addEventListener(\n \"pointerdown\",\n () => {\n pointerPressed = true;\n },\n { signal },\n );\n list.ownerDocument.addEventListener(\n \"pointerup\",\n () => {\n pointerPressed = false;\n },\n { signal, capture: true },\n );\n\n return {\n element: list,\n setRows(next) {\n if (state.kind === \"detached\") {\n return;\n }\n const previous = activeIndex();\n const previousKey = previous === null ? undefined : rows[previous]?.key;\n rows = next;\n if (state.kind === \"active\" || state.kind === \"awaiting\") {\n const kept =\n previousKey === undefined\n ? -1\n : next.findIndex((row) => row.key === previousKey);\n const index =\n kept !== -1\n ? kept\n : nearestLanding(\n next,\n Math.min(state.index, next.length - 1),\n disabledOptions(),\n );\n state = index === null ? INACTIVE : { kind: state.kind, index };\n if (index !== previous) {\n options.onActiveChange(index, \"list\");\n }\n }\n setTabStop();\n notify();\n checkNearEnd();\n },\n setOptions(next) {\n options = next;\n setTabStop();\n },\n activate(index, by) {\n setActive(\n index,\n by,\n by === \"pointer\" ? null : by === \"open\" ? \"center\" : \"nearest\",\n );\n },\n handleKey(event) {\n if (roving() || !onKey(event)) {\n return false;\n }\n event.preventDefault();\n return true;\n },\n chooseActive(nativeEvent) {\n const active = activeIndex();\n return (\n state.kind !== \"detached\" &&\n active !== null &&\n choose(active, { kind: \"one\" }, nativeEvent)\n );\n },\n getActive: activeIndex,\n activeId() {\n const active = activeIndex();\n const row = active === null ? null : rowElement(active);\n return row === null || row.id === \"\" ? null : row.id;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n detach() {\n if (state.kind === \"detached\") {\n return;\n }\n state = { kind: \"detached\" };\n observer.disconnect();\n events.abort();\n clearTimeout(typeaheadTimer);\n listeners.clear();\n },\n };\n}\n","import type { Schedule } from \"@gridkitjs/forms-core\";\n\n/**\n * The browser's timers as a forms-core `Schedule`: runs `callback` once\n * after `delay` milliseconds, and the function it returns clears the timer.\n * Clearing after the callback has run does nothing.\n */\nexport const scheduleTimeout: Schedule = (callback, delay) => {\n const timer = setTimeout(callback, delay);\n return () => {\n clearTimeout(timer);\n };\n};\n","import type { FormsMessages } from \"@gridkitjs/forms-core\";\nimport { createLiveAnnouncer } from \"../announcer\";\nimport { scheduleTimeout } from \"../scheduleTimeout\";\n\nexport interface ChoiceAnnouncerOptions {\n /** Where `resultCount`, `noMatches` and `selectedCount` come from. */\n readonly messages: Pick<\n FormsMessages,\n \"resultCount\" | \"noMatches\" | \"selectedCount\"\n >;\n /**\n * Milliseconds the results must stay unchanged before they are read,\n * so typing hears one count when it pauses, not one per key. Default 500.\n */\n readonly settleDelay?: number | undefined;\n /** The live region's class, `\"gridkit-forms-sr-only\"` by default. */\n readonly className?: string | undefined;\n}\n\nexport interface ChoiceAnnouncer {\n /**\n * The list shows `count` options for `query`: read as `resultCount` or\n * `noMatches` once it has stayed so for `settleDelay`, unless it is\n * what was read last for the same query.\n */\n readonly results: (query: string, count: number) => void;\n /** An option was ticked or unticked: `selectedCount`, read at once. */\n readonly selected: (count: number) => void;\n /** Any other text, read at once. */\n readonly announce: (text: string) => void;\n /**\n * The list closed: drops results still settling, and forgets the last\n * read, so the next open reads its count again.\n */\n readonly cancel: () => void;\n /** Replaces the options, from the next call on. */\n readonly setOptions: (options: ChoiceAnnouncerOptions) => void;\n /** Drops what is settling and removes the live region. */\n readonly destroy: () => void;\n}\n\n/** What a choice list has read out, and what waits to be. */\ntype ResultAnnouncement =\n | { readonly kind: \"quiet\"; readonly last: string | null }\n | {\n readonly kind: \"settling\";\n readonly last: string | null;\n readonly cancel: () => void;\n }\n | { readonly kind: \"destroyed\" };\n\nconst DEFAULT_SETTLE_DELAY = 500;\n\n/**\n * A polite live region in `container` for what a choice list says that no\n * visual cue carries to a screen reader: how many options a search found,\n * how many are ticked. The active option is not announced: the screen\n * reader reads it from `aria-activedescendant` or focus.\n */\nexport function createChoiceAnnouncer(\n container: HTMLElement,\n initialOptions: ChoiceAnnouncerOptions,\n): ChoiceAnnouncer {\n let options = initialOptions;\n const region = createLiveAnnouncer(container, {\n className: options.className,\n });\n let state: ResultAnnouncement = { kind: \"quiet\", last: null };\n\n function settle(last: string | null): void {\n if (state.kind === \"settling\") {\n state.cancel();\n }\n state = { kind: \"quiet\", last };\n }\n\n return {\n results(query, count) {\n if (state.kind === \"destroyed\") {\n return;\n }\n const key = JSON.stringify([query, count]);\n const { last } = state;\n settle(last);\n if (key === last) {\n return;\n }\n const cancel = scheduleTimeout(() => {\n state = { kind: \"quiet\", last: key };\n const { messages } = options;\n region.announce(\n count === 0 ? messages.noMatches(query) : messages.resultCount(count),\n );\n }, options.settleDelay ?? DEFAULT_SETTLE_DELAY);\n state = { kind: \"settling\", last, cancel };\n },\n selected(count) {\n if (state.kind !== \"destroyed\") {\n region.announce(options.messages.selectedCount(count));\n }\n },\n announce(text) {\n if (state.kind !== \"destroyed\") {\n region.announce(text);\n }\n },\n cancel() {\n if (state.kind !== \"destroyed\") {\n settle(null);\n }\n },\n setOptions(next) {\n options = next;\n },\n destroy() {\n if (state.kind === \"destroyed\") {\n return;\n }\n settle(null);\n state = { kind: \"destroyed\" };\n region.destroy();\n },\n };\n}\n","/** What the stack needs of an attached overlay. */\nexport interface StackedOverlay {\n readonly panel: HTMLElement;\n /** Escape was pressed while this was the topmost overlay. */\n readonly onEscape: () => void;\n /** An overlay below this one detached, so this one has to go too. */\n readonly onParentDetached: () => void;\n}\n\n/** The stack and the one Escape listener that serves it. */\ninterface OverlayStack {\n /**\n * Every attached overlay, in the order it attached: a submenu opened from\n * a menu sits above it.\n */\n readonly overlays: StackedOverlay[];\n readonly onKeyDown: (event: KeyboardEvent) => void;\n}\n\nconst STACK_KEY = Symbol.for(\"@gridkitjs/overlay-stack\");\n\n/*\n * One listener for the whole stack, on `window` in the capture phase: the\n * first place a key event reaches, so neither React's root listener nor a\n * page's own Escape handler hears an Escape the topmost overlay took. An\n * Escape that ends an IME composition is the input method's, not ours.\n */\nfunction createStack(): OverlayStack {\n const overlays: StackedOverlay[] = [];\n return {\n overlays,\n onKeyDown: (event) => {\n const topmost = overlays.at(-1);\n if (\n event.key !== \"Escape\" ||\n event.isComposing ||\n topmost === undefined\n ) {\n return;\n }\n event.preventDefault();\n event.stopPropagation();\n topmost.onEscape();\n },\n };\n}\n\n/**\n * The page's one stack, made on first use. On `globalThis` because overlays\n * from separately bundled packages must nest.\n */\nfunction pageStack(): OverlayStack {\n const holder = globalThis as Partial<Record<symbol, OverlayStack>>;\n const stack = holder[STACK_KEY] ?? createStack();\n holder[STACK_KEY] = stack;\n return stack;\n}\n\n/** Puts `overlay` on top of the stack. */\nexport function pushOverlay(overlay: StackedOverlay): void {\n const { overlays, onKeyDown } = pageStack();\n if (overlays.length === 0) {\n window.addEventListener(\"keydown\", onKeyDown, true);\n }\n overlays.push(overlay);\n}\n\n/**\n * Takes `overlay` off the stack, and every overlay above it with it — each\n * told through `onParentDetached`, topmost first, so a submenu never outlives\n * the menu it opened from. Does nothing for an overlay no longer on it.\n */\nexport function removeOverlay(overlay: StackedOverlay): void {\n const { overlays, onKeyDown } = pageStack();\n const index = overlays.indexOf(overlay);\n if (index === -1) {\n return;\n }\n const above = overlays.splice(index).slice(1).reverse();\n for (const child of above) {\n child.onParentDetached();\n }\n if (overlays.length === 0) {\n window.removeEventListener(\"keydown\", onKeyDown, true);\n }\n}\n\n/** Whether `target` is inside an overlay that sits above `overlay`. */\nexport function isInsideOverlayAbove(\n overlay: StackedOverlay,\n target: Node,\n): boolean {\n const { overlays } = pageStack();\n const index = overlays.indexOf(overlay);\n return (\n index !== -1 &&\n overlays.slice(index + 1).some((above) => above.panel.contains(target))\n );\n}\n","import type { WritingDirection } from \"@gridkitjs/forms-core\";\n\n/** Which side of its anchor an overlay opens on. */\nexport type OverlaySide = \"top\" | \"bottom\" | \"left\" | \"right\";\n\n/**\n * Which edge of the anchor the overlay lines up with along that side: its\n * left edge (`start`) or right edge (`end`) for `top`/`bottom`, its top or\n * bottom edge for `left`/`right`.\n */\nexport type OverlayAlign = \"start\" | \"end\";\n\nexport type OverlayPlacement = `${OverlaySide}-${OverlayAlign}`;\n\n/** A box in viewport coordinates, as `getBoundingClientRect` reports one. */\nexport interface OverlayRect {\n readonly top: number;\n readonly left: number;\n readonly width: number;\n readonly height: number;\n}\n\nexport interface OverlaySize {\n readonly width: number;\n readonly height: number;\n}\n\nexport interface OverlayPlacementOptions {\n /** Where the overlay would rather open. Defaults to `\"bottom-start\"`. */\n readonly placement?: OverlayPlacement | undefined;\n /** Space between the anchor and the overlay, in pixels. Defaults to `0`. */\n readonly gap?: number | undefined;\n /**\n * Pixels to shift the overlay along the anchor's edge — down beside a\n * `left`/`right` side, right beside `top`/`bottom`; negative goes the other\n * way. A submenu opened `right-start` takes its own top padding, negated,\n * so its first item lines up with the item that opened it. The overlay is\n * still kept on screen. Defaults to `0`.\n */\n readonly offset?: number | undefined;\n /**\n * The writing direction the placement is read in. `\"rtl\"` mirrors it, as\n * a right-to-left page is mirrored: `left` and `right` swap, `start` and\n * `end` beside `top` or `bottom` are the anchor's right and left edges, an\n * `offset` along those sides runs leftward, and an overlay wider than the\n * viewport keeps its right edge in view. The placement it ends up with is\n * reported in the same mirrored terms, so `\"bottom-start\"` lines up with\n * the anchor's inline start and `\"right-start\"` opens a submenu toward\n * the inline end in either direction. Defaults to `\"ltr\"`.\n */\n readonly direction?: WritingDirection | undefined;\n}\n\n/** Where an overlay goes: its top-left corner, and the placement it ended up with. */\nexport interface OverlayPosition {\n readonly top: number;\n readonly left: number;\n readonly placement: OverlayPlacement;\n}\n\nconst OPPOSITE_SIDE: Readonly<Record<OverlaySide, OverlaySide>> = {\n top: \"bottom\",\n bottom: \"top\",\n left: \"right\",\n right: \"left\",\n};\n\nfunction isVertical(side: OverlaySide): boolean {\n return side === \"top\" || side === \"bottom\";\n}\n\n/** How much room `side` of `anchor` leaves before the viewport's edge. */\nfunction roomBeside(\n side: OverlaySide,\n anchor: OverlayRect,\n viewport: OverlaySize,\n): number {\n switch (side) {\n case \"top\":\n return anchor.top;\n case \"bottom\":\n return viewport.height - (anchor.top + anchor.height);\n case \"left\":\n return anchor.left;\n case \"right\":\n return viewport.width - (anchor.left + anchor.width);\n }\n}\n\n/**\n * The preferred side if the overlay fits there, the opposite one if it fits\n * there instead, and otherwise whichever has more room — a menu too tall for\n * either still shows as much of itself as it can.\n */\nfunction chooseSide(\n preferred: OverlaySide,\n needed: number,\n anchor: OverlayRect,\n viewport: OverlaySize,\n): OverlaySide {\n const opposite = OPPOSITE_SIDE[preferred];\n const room = roomBeside(preferred, anchor, viewport);\n const oppositeRoom = roomBeside(opposite, anchor, viewport);\n if (room >= needed) {\n return preferred;\n }\n return oppositeRoom >= needed || oppositeRoom > room ? opposite : preferred;\n}\n\n/** The preferred edge unless only the other one keeps the overlay on screen. */\nfunction chooseAlign(\n preferred: OverlayAlign,\n fitsAtStart: boolean,\n fitsAtEnd: boolean,\n): OverlayAlign {\n if (preferred === \"start\") {\n return fitsAtStart || !fitsAtEnd ? \"start\" : \"end\";\n }\n return fitsAtEnd || !fitsAtStart ? \"end\" : \"start\";\n}\n\n/** The overlay's offset away from the anchor: its top for `top`/`bottom`, its left otherwise. */\nfunction offsetBeside(\n side: OverlaySide,\n anchor: OverlayRect,\n panel: OverlaySize,\n gap: number,\n): number {\n switch (side) {\n case \"top\":\n return anchor.top - gap - panel.height;\n case \"bottom\":\n return anchor.top + anchor.height + gap;\n case \"left\":\n return anchor.left - gap - panel.width;\n case \"right\":\n return anchor.left + anchor.width + gap;\n }\n}\n\n/** Keeps `value` within `[0, limit]`, pinning to `0` when even that fails. */\nfunction clampIntoView(value: number, limit: number): number {\n return Math.max(0, Math.min(value, limit));\n}\n\n/**\n * Where an overlay of size `panel` goes beside `anchor` so that it stays in\n * `viewport`: on the preferred side unless only the opposite one has room,\n * lined up with the preferred edge unless that runs it off screen and the\n * other edge does not, and finally pushed back inside if it still overflows.\n * Pure, so the rules are testable without a browser; `attachOverlay` feeds it\n * the measurements.\n *\n * A point — a context menu opened where the pointer is — is an anchor with\n * no width or height, which is what makes `start`/`end` mean \"after\" and\n * \"before\" it.\n *\n * In `\"rtl\"` the anchor is mirrored across the viewport, placed as in\n * left-to-right, and the result mirrored back, so every rule above holds\n * with left and right exchanged.\n */\nexport function placeOverlay(\n anchor: OverlayRect,\n panel: OverlaySize,\n viewport: OverlaySize,\n options: OverlayPlacementOptions = {},\n): OverlayPosition {\n if (options.direction !== \"rtl\") {\n return placeLeftToRight(anchor, panel, viewport, options);\n }\n const mirrored = placeLeftToRight(\n { ...anchor, left: viewport.width - anchor.left - anchor.width },\n panel,\n viewport,\n options,\n );\n return {\n ...mirrored,\n left: viewport.width - mirrored.left - panel.width,\n };\n}\n\nfunction placeLeftToRight(\n anchor: OverlayRect,\n panel: OverlaySize,\n viewport: OverlaySize,\n options: OverlayPlacementOptions,\n): OverlayPosition {\n const [preferredSide, preferredAlign] = (\n options.placement ?? \"bottom-start\"\n ).split(\"-\") as [OverlaySide, OverlayAlign];\n const gap = options.gap ?? 0;\n const offset = options.offset ?? 0;\n const vertical = isVertical(preferredSide);\n\n const side = chooseSide(\n preferredSide,\n (vertical ? panel.height : panel.width) + gap,\n anchor,\n viewport,\n );\n\n // The axis the overlay runs along beside the anchor, shifted by the offset\n // before an edge is chosen, so the shifted overlay is what has to fit.\n const anchorStart = (vertical ? anchor.left : anchor.top) + offset;\n const anchorEnd = anchorStart + (vertical ? anchor.width : anchor.height);\n const extent = vertical ? panel.width : panel.height;\n const room = vertical ? viewport.width : viewport.height;\n const align = chooseAlign(\n preferredAlign,\n anchorStart + extent <= room,\n anchorEnd - extent >= 0,\n );\n const along = align === \"start\" ? anchorStart : anchorEnd - extent;\n const away = offsetBeside(side, anchor, panel, gap);\n\n return {\n top: clampIntoView(vertical ? away : along, viewport.height - panel.height),\n left: clampIntoView(vertical ? along : away, viewport.width - panel.width),\n placement: `${side}-${align}`,\n };\n}\n","import {\n isInsideOverlayAbove,\n pushOverlay,\n removeOverlay,\n type StackedOverlay,\n} from \"./overlayStack\";\nimport {\n placeOverlay,\n type OverlayPlacementOptions,\n type OverlayRect,\n} from \"./placeOverlay\";\nimport { writingDirection } from \"../writingDirection\";\n\n/** What an overlay opens beside: an element, or a point in viewport coordinates. */\nexport type OverlayAnchor =\n Element | { readonly x: number; readonly y: number };\n\n/**\n * Where focus goes when an overlay attaches: its first focusable descendant,\n * the panel itself, nowhere — focus stays where it was — or a given element.\n */\nexport type OverlayInitialFocus = \"first\" | \"panel\" | \"none\" | HTMLElement;\n\n/** Why an overlay asked to close. */\nexport type OverlayDismissReason =\n \"escape\" | \"outside\" | \"scroll\" | \"resize\" | \"blur\" | \"parent\";\n\nexport interface OverlayOptions extends OverlayPlacementOptions {\n /**\n * The overlay asks to close: Escape was pressed while it was the topmost\n * overlay, a pointer went down outside it, something outside it scrolled,\n * the window resized or lost focus, focus moved outside it, or the overlay\n * it was opened above detached. The caller closes it — removes the panel\n * and detaches — or keeps it open by doing nothing, except after\n * `\"parent\"`, which detaches it regardless.\n */\n readonly onDismiss: (reason: OverlayDismissReason) => void;\n /**\n * Where focus goes on attaching. Defaults to `\"first\"`: a menu focuses its\n * first item. A panel whose first control is not where the user starts — a\n * filter editor's operator picker before its value box — passes that\n * element, or `\"panel\"` to land on the panel itself; `\"none\"` leaves focus\n * where it was, as a suggestion list does while typing goes on in the\n * field that opened it.\n */\n readonly initialFocus?: OverlayInitialFocus | undefined;\n /**\n * Where focus goes when the overlay detaches. Defaults to the element that\n * had focus when it attached; `null` leaves focus alone, unless\n * `returnFocusFallback` names somewhere.\n */\n readonly returnFocusTo?: HTMLElement | null | undefined;\n /**\n * Where focus goes when there is nothing to return it to as the overlay\n * detaches: `returnFocusTo` is `null`, or has left the page — the button a\n * menu opened from, taken away by what the menu ran. Called then, so it\n * can name what is on the page by that time; returning `null` leaves focus\n * alone. Like the return itself, it applies only while focus is still in\n * the panel, in an overlay above it, or nowhere.\n */\n readonly returnFocusFallback?: (() => HTMLElement | null) | undefined;\n /**\n * Whether a scroll outside the panel just after input inside it — an\n * `input` or `change` event, in the two animation frames that follow it —\n * leaves it open. A panel whose controls change the page under it opts\n * in: a column chooser hiding a column narrows the grid it opened from,\n * and the browser scrolls that grid back within its narrower content.\n * Defaults to `false`, where every scroll outside the panel dismisses it.\n */\n readonly ignoreScrollAfterInput?: boolean | undefined;\n /**\n * Whether Tab and Shift+Tab stay inside the panel: from its last tabbable\n * element Tab moves to its first, and Shift+Tab from its first to its last,\n * as a dialog keeps them. Defaults to `false`, where tabbing out of the\n * panel moves focus outside it, which dismisses it with `\"blur\"`. Only\n * the keys are kept: a pointer down outside still dismisses it, and so\n * does focus moved out by any other route.\n */\n readonly trapFocus?: boolean | undefined;\n}\n\n/** Everything focusable by script, so a menu's `tabindex=\"-1\"` items count. */\nconst FOCUSABLE =\n \"a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]\";\n\n/**\n * What Tab stops on in `panel`, in document order: what is focusable without\n * a negative `tabindex`, enabled and shown.\n */\nfunction tabbables(panel: HTMLElement): HTMLElement[] {\n return Array.from(panel.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(\n (element) =>\n element.tabIndex >= 0 &&\n !element.matches(\":disabled\") &&\n element.checkVisibility({ visibilityProperty: true }),\n );\n}\n\nfunction anchorRect(anchor: OverlayAnchor): OverlayRect {\n if (anchor instanceof Element) {\n const { top, left, width, height } = anchor.getBoundingClientRect();\n return { top, left, width, height };\n }\n return { top: anchor.y, left: anchor.x, width: 0, height: 0 };\n}\n\n/**\n * The element `initialFocus` names, or `null` for none. The panel stands in\n * for a first focusable descendant it does not have, given `tabindex=\"-1\"`\n * when it has no `tabindex` of its own so that it can take focus.\n */\nfunction initialFocusTarget(\n panel: HTMLElement,\n initialFocus: OverlayInitialFocus,\n): HTMLElement | null {\n if (initialFocus === \"none\") {\n return null;\n }\n if (initialFocus instanceof HTMLElement) {\n return initialFocus;\n }\n const first =\n initialFocus === \"first\"\n ? panel.querySelector<HTMLElement>(FOCUSABLE)\n : null;\n if (first !== null) {\n return first;\n }\n if (!panel.hasAttribute(\"tabindex\")) {\n panel.tabIndex = -1;\n }\n return panel;\n}\n\n/**\n * Shows `panel` as an overlay beside `anchor` — a menu, a popover, a filter\n * editor — and returns the function that ends it. The caller renders the\n * panel, usually as a child of `document.body` so no scrolling ancestor clips\n * it; this positions it, moves focus into it, and reports through\n * `onDismiss` when the user is done with it.\n *\n * The panel is positioned `fixed`, at the place `placeOverlay` picks from the\n * anchor's and the panel's measured boxes, and carries that placement in\n * `data-gridkit-placement` (`\"top-start\"` once flipped above, say) for a\n * stylesheet to point an arrow by. Whenever the panel's size changes — a list\n * that shrinks under a search — it is placed again beside the anchor, so a\n * panel flipped above its anchor keeps its bottom edge there — or beside\n * where the anchor was, once it has left the page. Focus moves\n * where `initialFocus` says.\n *\n * The placement is read in the panel's own writing direction unless\n * `direction` names one, so a panel laid out right to left — given\n * `dir=\"rtl\"`, or rendered into a right-to-left page — opens toward the\n * inline end of what it is drawn in. A renderer portalling the panel out of\n * a right-to-left grid in a left-to-right page sets `dir` on it from the\n * grid, which mirrors its content and its placement together.\n *\n * Nothing that happens on or in the anchor dismisses the overlay, so a button\n * that toggles it can close it with its own click rather than having the\n * overlay close and the click reopen it.\n *\n * Overlays stack in the order they attach. Escape belongs to the topmost\n * alone, which takes it: it closes a submenu without closing the menu under\n * it, and nothing else on the page — a grid that clears its selection on\n * Escape — hears it. An overlay counts everything in the overlays above it\n * as inside itself, so a click in a submenu keeps its menu open while a click\n * elsewhere in the menu closes only the submenu.\n *\n * Detaching removes every listener and returns focus, but only when focus is\n * still in the panel, in an overlay above it, or nowhere — a click that\n * dismissed it by landing on another control leaves focus on that control.\n * Focus goes to `returnFocusFallback` instead when the element it would\n * return to has left the page.\n * Any overlay still above it is dismissed with `\"parent\"` and detached first.\n */\nexport function attachOverlay(\n anchor: OverlayAnchor,\n panel: HTMLElement,\n options: OverlayOptions,\n): () => void {\n const { onDismiss } = options;\n const returnFocusTo =\n options.returnFocusTo === undefined\n ? document.activeElement instanceof HTMLElement\n ? document.activeElement\n : null\n : options.returnFocusTo;\n\n const stacked: StackedOverlay = {\n panel,\n onEscape: () => {\n onDismiss(\"escape\");\n },\n onParentDetached: () => {\n onDismiss(\"parent\");\n detach();\n },\n };\n\n /** In the panel, or in an overlay opened above it. */\n function inside(target: EventTarget | null): boolean {\n return (\n target instanceof Node &&\n (panel.contains(target) || isInsideOverlayAbove(stacked, target))\n );\n }\n\n function belongs(target: EventTarget | null): boolean {\n return (\n inside(target) ||\n (anchor instanceof Element &&\n target instanceof Node &&\n anchor.contains(target))\n );\n }\n\n function onPointerDown(event: PointerEvent): void {\n if (!belongs(event.target)) {\n onDismiss(\"outside\");\n }\n }\n\n // Set from input in the panel until two frames have passed: the scroll an\n // input causes is dispatched by the frame after its layout, which may\n // itself wait for the next frame.\n let settlingFrame: number | null = null;\n function onInput(): void {\n if (settlingFrame !== null) {\n cancelAnimationFrame(settlingFrame);\n }\n settlingFrame = requestAnimationFrame(() => {\n settlingFrame = requestAnimationFrame(() => {\n settlingFrame = null;\n });\n });\n }\n\n // The overlay is placed in viewport coordinates, so a scroll that moves\n // its anchor leaves it behind — except a scroll inside the panel itself,\n // or one the panel's own input caused, when it asks for that. Only the\n // document or a scroller holding an element anchor moves it: a log\n // elsewhere on the page following its newest line does not.\n function movesAnchor(target: EventTarget | null): boolean {\n return (\n !(anchor instanceof Element) ||\n !(target instanceof Node) ||\n target.nodeType === Node.DOCUMENT_NODE ||\n target.contains(anchor)\n );\n }\n function onScroll(event: Event): void {\n if (\n !inside(event.target) &&\n settlingFrame === null &&\n movesAnchor(event.target)\n ) {\n onDismiss(\"scroll\");\n }\n }\n\n function onResize(): void {\n onDismiss(\"resize\");\n }\n\n // Only a move to somewhere definite counts: focus dropping to nothing, as\n // when the focused item re-renders away, is not the user leaving.\n function onFocusOut(event: FocusEvent): void {\n if (event.relatedTarget !== null && !belongs(event.relatedTarget)) {\n onDismiss(\"blur\");\n }\n }\n\n // Only the moves that would leave the panel are made here — Tab with\n // nothing tabbable after the focused element, Shift+Tab with nothing before\n // it — and every other Tab is the browser's own, in its own order. What is\n // tabbable is read on each key, so controls drawn since attaching count; an\n // overlay above that sits inside the panel keeps its own Tab.\n function onTrapKeyDown(event: KeyboardEvent): void {\n if (\n event.key !== \"Tab\" ||\n event.defaultPrevented ||\n event.altKey ||\n event.ctrlKey ||\n event.metaKey ||\n !(event.target instanceof Node) ||\n isInsideOverlayAbove(stacked, event.target)\n ) {\n return;\n }\n const stops = tabbables(panel).filter(\n (element) => !isInsideOverlayAbove(stacked, element),\n );\n const first = stops[0];\n const last = stops.at(-1);\n if (first === undefined || last === undefined) {\n event.preventDefault();\n return;\n }\n const position = event.target.compareDocumentPosition(\n event.shiftKey ? first : last,\n );\n const leaving = event.shiftKey\n ? (position & Node.DOCUMENT_POSITION_PRECEDING) === 0\n : (position & Node.DOCUMENT_POSITION_FOLLOWING) === 0;\n if (leaving) {\n event.preventDefault();\n (event.shiftKey ? last : first).focus();\n }\n }\n\n function onWindowBlur(): void {\n onDismiss(\"blur\");\n }\n\n // An anchor taken out of the page has no box to read — the header of a\n // column the panel itself just hid — so the panel goes on being placed\n // beside where it last was, rather than in the viewport's corner.\n let lastAnchorBox: OverlayRect | null = null;\n function anchorBox(): OverlayRect {\n if (\n lastAnchorBox === null ||\n !(anchor instanceof Element) ||\n anchor.isConnected\n ) {\n lastAnchorBox = anchorRect(anchor);\n }\n return lastAnchorBox;\n }\n\n // Measured fixed at the viewport's top-left corner, shrink-wrapped and with\n // the whole viewport to grow into — in normal flow a block panel would\n // report the full width of the page — and from that corner every time, so\n // placing it again measures it the way the first placing did.\n function place(): void {\n panel.style.top = \"0px\";\n panel.style.left = \"0px\";\n const { width, height } = panel.getBoundingClientRect();\n const position = placeOverlay(\n anchorBox(),\n { width, height },\n {\n width: document.documentElement.clientWidth,\n height: document.documentElement.clientHeight,\n },\n { ...options, direction: options.direction ?? writingDirection(panel) },\n );\n panel.style.top = `${String(position.top)}px`;\n panel.style.left = `${String(position.left)}px`;\n panel.setAttribute(\"data-gridkit-placement\", position.placement);\n }\n\n panel.style.position = \"fixed\";\n place();\n const resizeObserver = new ResizeObserver(place);\n resizeObserver.observe(panel);\n\n // On the stack before focus moves in, so the overlay below sees the focus\n // leaving it land inside an overlay above it rather than outside.\n pushOverlay(stacked);\n initialFocusTarget(panel, options.initialFocus ?? \"first\")?.focus({\n preventScroll: true,\n });\n\n document.addEventListener(\"pointerdown\", onPointerDown, true);\n window.addEventListener(\"scroll\", onScroll, { capture: true, passive: true });\n window.addEventListener(\"resize\", onResize);\n window.addEventListener(\"blur\", onWindowBlur);\n panel.addEventListener(\"focusout\", onFocusOut);\n if (options.trapFocus === true) {\n panel.addEventListener(\"keydown\", onTrapKeyDown);\n }\n if (options.ignoreScrollAfterInput === true) {\n panel.addEventListener(\"input\", onInput);\n panel.addEventListener(\"change\", onInput);\n }\n\n let attached = true;\n function detach(): void {\n if (!attached) {\n return;\n }\n attached = false;\n // Read before the overlays above close and hand focus back to wherever\n // they took it from, which may already have left the page with this panel.\n const active = document.activeElement;\n const focusInside =\n active === null || active === document.body || inside(active);\n removeOverlay(stacked);\n resizeObserver.disconnect();\n document.removeEventListener(\"pointerdown\", onPointerDown, true);\n window.removeEventListener(\"scroll\", onScroll, { capture: true });\n window.removeEventListener(\"resize\", onResize);\n window.removeEventListener(\"blur\", onWindowBlur);\n panel.removeEventListener(\"focusout\", onFocusOut);\n panel.removeEventListener(\"keydown\", onTrapKeyDown);\n panel.removeEventListener(\"input\", onInput);\n panel.removeEventListener(\"change\", onInput);\n if (settlingFrame !== null) {\n cancelAnimationFrame(settlingFrame);\n }\n\n if (!focusInside) {\n return;\n }\n const target =\n returnFocusTo?.isConnected === true\n ? returnFocusTo\n : options.returnFocusFallback?.();\n target?.focus({ preventScroll: true });\n }\n return detach;\n}\n","import { visibleRange, type VisibleRange } from \"@gridkitjs/forms-core\";\n\nexport interface RowVirtualizerOptions {\n /** The height assumed for a row not yet measured. */\n readonly estimatedRowHeight: number;\n /** Rows rendered beyond each edge of the visible area. */\n readonly overscan: number;\n /**\n * The window of rows to render moved: called whenever a scroll, a resize\n * of the scroll element, a measured row height or a change of rows moves\n * it, and never with a window equal to the last.\n */\n readonly onRange: (range: VisibleRange) => void;\n}\n\nexport interface RowVirtualizer {\n /** How many rows there are. Measured heights of the rows that remain are kept. */\n readonly setRowCount: (count: number) => void;\n /**\n * Forgets every measured height, for rows that are no longer the ones\n * measured. A `scrollToIndex` still waiting for its row is dropped too:\n * the row it asked for is no longer at that index.\n */\n readonly resetHeights: () => void;\n /**\n * A ref callback for the element of row `index` (its place among all the\n * rows, not among those rendered): measured while mounted, forgotten once\n * called with `null`. The same function for the same index every time, so\n * a renderer re-attaching it on every render costs nothing.\n */\n readonly measureRow: (index: number) => (element: HTMLElement | null) => void;\n /**\n * Reads the heights of rows already laid out, each paired with its index\n * among all the rows, and works out the window once for all of them: for\n * rows drawn before this virtualizer existed, so its first window is the\n * one on screen rather than one placed by `estimatedRowHeight`. Indices\n * past the row count are skipped. It does not observe the rows;\n * `measureRow` does that once the renderer hands them over.\n */\n readonly measureRows: (\n rows: Iterable<readonly [index: number, element: Element]>,\n ) => void;\n /**\n * Scrolls so row `index` is in view. A mounted row is scrolled to directly;\n * one outside the window is jumped to at its estimated offset, then\n * scrolled to properly once it mounts and can be measured. A later call\n * replaces one still waiting for its row; a row count that no longer holds\n * that row, or `resetHeights`, drops it.\n */\n readonly scrollToIndex: (\n index: number,\n options?: ScrollIntoViewOptions,\n ) => void;\n /**\n * Stops listening, measuring and scrolling, for good: every method does\n * nothing after it.\n */\n readonly destroy: () => void;\n}\n\n/**\n * Where the virtualizer is in its life: `ready`, `awaiting-row` while a\n * `scrollToIndex` waits for its row to mount to scroll to it properly, and\n * `destroyed` for good.\n */\ntype VirtualizerPhase =\n | { readonly kind: \"ready\" }\n | {\n readonly kind: \"awaiting-row\";\n readonly index: number;\n readonly options: ScrollIntoViewOptions | undefined;\n }\n | { readonly kind: \"destroyed\" };\n\nconst READY: VirtualizerPhase = { kind: \"ready\" };\n\nfunction sameRange(a: VisibleRange, b: VisibleRange): boolean {\n return (\n a.startIndex === b.startIndex &&\n a.endIndex === b.endIndex &&\n a.offsetBefore === b.offsetBefore &&\n a.offsetAfter === b.offsetAfter\n );\n}\n\n/**\n * Windows a long list of rows inside `scrollElement` down to those near its\n * scroll position, measuring each rendered row's real height rather than\n * assuming a uniform one — rows are not uniform (`.is-wrapped` cells, group\n * header and summary rows), so a fixed-height virtualizer would either break\n * wrapping or rule it out. The renderer draws `onRange`'s window, with\n * spacers of `offsetBefore`/`offsetAfter` around it, and hands each row's\n * element to `measureRow`.\n *\n * The heights are a mutable array, not a structure rebuilt per measurement:\n * one can arrive many times a second while scrolling. The pure arithmetic\n * over them is `@gridkitjs/core`'s `visibleRange`; this owns only the\n * mutability around it and the listeners that feed it — the scroll position,\n * the scroll element's height, and one `ResizeObserver` shared by every\n * mounted row.\n */\nexport function createRowVirtualizer(\n scrollElement: HTMLElement,\n options: RowVirtualizerOptions,\n): RowVirtualizer {\n const { estimatedRowHeight, overscan, onRange } = options;\n\n let heights: (number | undefined)[] = [];\n let scrollTop = scrollElement.scrollTop;\n let viewportHeight = scrollElement.clientHeight;\n let range: VisibleRange | null = null;\n let phase: VirtualizerPhase = READY;\n\n const elements = new Map<number, HTMLElement>();\n const indexByElement = new Map<Element, number>();\n const refCallbacks = new Map<number, (element: HTMLElement | null) => void>();\n\n function recompute(): void {\n if (phase.kind === \"destroyed\") {\n return;\n }\n const next = visibleRange(\n heights,\n estimatedRowHeight,\n scrollTop,\n viewportHeight,\n overscan,\n );\n if (range !== null && sameRange(range, next)) {\n return;\n }\n range = next;\n onRange(next);\n }\n\n const rowObserver = new ResizeObserver((entries) => {\n let changed = false;\n for (const entry of entries) {\n const index = indexByElement.get(entry.target);\n if (index === undefined) continue;\n const height = entry.target.getBoundingClientRect().height;\n if (heights[index] !== height) {\n heights[index] = height;\n changed = true;\n }\n }\n if (changed) {\n recompute();\n }\n });\n\n // Kept current here rather than read on each recompute: a scroll can fire\n // many times a second, and each one only needs to feed the next window.\n const viewportObserver = new ResizeObserver(() => {\n viewportHeight = scrollElement.clientHeight;\n recompute();\n });\n viewportObserver.observe(scrollElement);\n\n function handleScroll(): void {\n scrollTop = scrollElement.scrollTop;\n recompute();\n }\n scrollElement.addEventListener(\"scroll\", handleScroll, { passive: true });\n\n function estimateOffsetBefore(index: number): number {\n let total = 0;\n for (let current = 0; current < index; current++) {\n total += heights[current] ?? estimatedRowHeight;\n }\n return total;\n }\n\n recompute();\n\n return {\n setRowCount(count) {\n if (phase.kind === \"awaiting-row\" && phase.index >= count) {\n phase = READY;\n }\n heights = Array.from({ length: count }, (_, index) => heights[index]);\n recompute();\n },\n resetHeights() {\n if (phase.kind === \"awaiting-row\") {\n phase = READY;\n }\n heights = new Array<number | undefined>(heights.length).fill(undefined);\n recompute();\n },\n measureRow(index) {\n let callback = refCallbacks.get(index);\n if (callback === undefined) {\n callback = (element) => {\n const previous = elements.get(index);\n if (previous !== undefined) {\n rowObserver.unobserve(previous);\n indexByElement.delete(previous);\n elements.delete(index);\n }\n if (element === null || phase.kind === \"destroyed\") {\n return;\n }\n elements.set(index, element);\n indexByElement.set(element, index);\n rowObserver.observe(element);\n if (phase.kind === \"awaiting-row\" && phase.index === index) {\n element.scrollIntoView(phase.options);\n phase = READY;\n }\n };\n refCallbacks.set(index, callback);\n }\n return callback;\n },\n measureRows(rows) {\n if (phase.kind === \"destroyed\") {\n return;\n }\n for (const [index, element] of rows) {\n if (index >= 0 && index < heights.length) {\n heights[index] = element.getBoundingClientRect().height;\n }\n }\n recompute();\n },\n scrollToIndex(index, scrollOptions) {\n if (phase.kind === \"destroyed\" || heights.length === 0) {\n return;\n }\n const clamped = Math.max(0, Math.min(index, heights.length - 1));\n const mounted = elements.get(clamped);\n if (mounted !== undefined) {\n phase = READY;\n mounted.scrollIntoView(scrollOptions);\n return;\n }\n phase = { kind: \"awaiting-row\", index: clamped, options: scrollOptions };\n scrollElement.scrollTop = estimateOffsetBefore(clamped);\n },\n destroy() {\n phase = { kind: \"destroyed\" };\n scrollElement.removeEventListener(\"scroll\", handleScroll);\n viewportObserver.disconnect();\n rowObserver.disconnect();\n elements.clear();\n indexByElement.clear();\n },\n };\n}\n","import { scheduleTimeout } from \"../scheduleTimeout\";\n\nexport interface HoldRepeatOptions {\n /** One step; false when it changed nothing (a limit), which ends the hold. */\n readonly onRepeat: (nativeEvent: PointerEvent) => boolean;\n /** Milliseconds from the press to the first repeat; 400 by default. */\n readonly delay?: number | undefined;\n /** Milliseconds between repeats; 60 by default. */\n readonly interval?: number | undefined;\n /** Milliseconds between repeats once `fastAfter` have been taken; 30 by default. */\n readonly fastInterval?: number | undefined;\n /** Repeats before they speed up; 20 by default. */\n readonly fastAfter?: number | undefined;\n}\n\nexport interface AttachedHoldRepeat {\n /** Replaces the options, from the next step on. */\n readonly setOptions: (options: HoldRepeatOptions) => void;\n /** Ends a hold in progress, as letting go would. */\n readonly cancel: () => void;\n /** Ends a hold in progress and removes every listener. */\n readonly detach: () => void;\n}\n\n/**\n * Where a press of the button is:\n *\n * - `idle`: not pressed.\n * - `waiting`: pressed, one step taken, waiting `delay` to repeat.\n * - `repeating`: stepping every `interval`, then every `fastInterval`.\n * - `detached`: every listener is gone.\n *\n * `waiting` and `repeating` hold the pointer's capture and a timer, which\n * every way out of them releases.\n */\nexport type HoldRepeatState =\n | { readonly kind: \"idle\" }\n | {\n readonly kind: \"waiting\";\n readonly pointerId: number;\n readonly press: PointerEvent;\n readonly cancel: () => void;\n }\n | {\n readonly kind: \"repeating\";\n readonly pointerId: number;\n readonly press: PointerEvent;\n readonly count: number;\n readonly cancel: () => void;\n }\n | { readonly kind: \"detached\" };\n\nconst IDLE: HoldRepeatState = { kind: \"idle\" };\nconst DETACHED: HoldRepeatState = { kind: \"detached\" };\n\nconst DELAY = 400;\nconst INTERVAL = 60;\nconst FAST_INTERVAL = 30;\nconst FAST_AFTER = 20;\n\n/**\n * Makes a stepper button step once when pressed and repeat while held: after\n * `delay` it steps every `interval`, and faster once `fastAfter` steps have\n * been taken. The hold ends when the pointer is let go or cancelled, loses\n * capture or leaves the button, when a step changes nothing, on `cancel`\n * and on `detach`, and every end clears the timer and releases the\n * pointer's capture.\n *\n * Only the primary button of a mouse, or a touch or pen, presses it. A long\n * touch opens no context menu. The renderer keeps focus where it is (on a\n * `mousedown`, so a tap still clicks) and draws the button's disabled\n * state; `onRepeat` returning false when it cannot step ends the hold.\n */\nexport function attachHoldRepeat(\n button: HTMLElement,\n initialOptions: HoldRepeatOptions,\n): AttachedHoldRepeat {\n let options = initialOptions;\n let state: HoldRepeatState = IDLE;\n const listeners = new AbortController();\n const { signal } = listeners;\n\n /** Leaves `waiting` or `repeating` for `next`, releasing the timer and the capture. */\n function release(next: HoldRepeatState): void {\n if (state.kind === \"waiting\" || state.kind === \"repeating\") {\n state.cancel();\n const { pointerId } = state;\n state = next;\n if (button.hasPointerCapture(pointerId)) {\n button.releasePointerCapture(pointerId);\n }\n return;\n }\n if (state.kind !== \"detached\") {\n state = next;\n }\n }\n\n function repeat(press: PointerEvent, count: number): void {\n if (!options.onRepeat(press)) {\n release(IDLE);\n return;\n }\n const taken = count + 1;\n const interval =\n taken >= (options.fastAfter ?? FAST_AFTER)\n ? (options.fastInterval ?? FAST_INTERVAL)\n : (options.interval ?? INTERVAL);\n state = {\n kind: \"repeating\",\n pointerId: press.pointerId,\n press,\n count: taken,\n cancel: scheduleTimeout(() => {\n repeat(press, taken);\n }, interval),\n };\n }\n\n function onPointerDown(event: PointerEvent): void {\n if (state.kind !== \"idle\" || event.button !== 0) {\n return;\n }\n if (!options.onRepeat(event)) {\n return;\n }\n // Capture keeps the press's moves and its end here wherever the\n // pointer goes; a touch is captured already.\n try {\n button.setPointerCapture(event.pointerId);\n } catch {\n // A pointer the browser has already let go of cannot be captured.\n }\n state = {\n kind: \"waiting\",\n pointerId: event.pointerId,\n press: event,\n cancel: scheduleTimeout(() => {\n repeat(event, 0);\n }, options.delay ?? DELAY),\n };\n }\n\n function onPointerMove(event: PointerEvent): void {\n if (\n (state.kind !== \"waiting\" && state.kind !== \"repeating\") ||\n event.pointerId !== state.pointerId\n ) {\n return;\n }\n const box = button.getBoundingClientRect();\n if (\n event.clientX < box.left ||\n event.clientX > box.right ||\n event.clientY < box.top ||\n event.clientY > box.bottom\n ) {\n release(IDLE);\n }\n }\n\n function onEnd(event: PointerEvent): void {\n if (\n (state.kind === \"waiting\" || state.kind === \"repeating\") &&\n event.pointerId === state.pointerId\n ) {\n release(IDLE);\n }\n }\n\n button.addEventListener(\"pointerdown\", onPointerDown, { signal });\n button.addEventListener(\"pointermove\", onPointerMove, { signal });\n button.addEventListener(\"pointerup\", onEnd, { signal });\n button.addEventListener(\"pointercancel\", onEnd, { signal });\n button.addEventListener(\"lostpointercapture\", onEnd, { signal });\n button.addEventListener(\n \"contextmenu\",\n (event) => {\n event.preventDefault();\n },\n { signal },\n );\n\n return {\n setOptions: (next) => {\n options = next;\n },\n cancel: () => {\n release(IDLE);\n },\n detach: () => {\n release(DETACHED);\n listeners.abort();\n },\n };\n}\n","import type { StepDirection, StepSize } from \"@gridkitjs/forms-core\";\n\nexport interface StepKeysOptions {\n /** A key or a wheel tick asked for a step. */\n readonly onStep: (\n direction: StepDirection,\n size: StepSize,\n nativeEvent: KeyboardEvent | WheelEvent,\n ) => void;\n /** Home and End step to an edge only when that limit is set; otherwise they move the caret. */\n readonly edges?: { readonly min: boolean; readonly max: boolean } | undefined;\n /** The wheel steps while the control has focus and the pointer is over it. */\n readonly wheel?: boolean | undefined;\n}\n\nexport interface AttachedStepKeys {\n /** Replaces the options, from the next event on. */\n readonly setOptions: (options: StepKeysOptions) => void;\n /** Removes every listener. */\n readonly detach: () => void;\n}\n\n/** The wheel's travel, in pixels, that makes one step. */\nconst WHEEL_STEP_PIXELS = 50;\n\n/** `keyCode` 229: WebKit's only sign that a key went to an input method. */\ninterface LegacyKeyboardEvent {\n readonly keyCode: number;\n}\n\n/** The step a key asks for, by the spinbutton pattern. */\nfunction keyStep(\n key: string,\n edges: StepKeysOptions[\"edges\"],\n): readonly [StepDirection, StepSize] | null {\n switch (key) {\n case \"ArrowUp\":\n return [\"up\", \"step\"];\n case \"ArrowDown\":\n return [\"down\", \"step\"];\n case \"PageUp\":\n return [\"up\", \"large\"];\n case \"PageDown\":\n return [\"down\", \"large\"];\n case \"Home\":\n return edges?.min === true ? [\"down\", \"edge\"] : null;\n case \"End\":\n return edges?.max === true ? [\"up\", \"edge\"] : null;\n default:\n return null;\n }\n}\n\nfunction hasFocus(control: HTMLElement): boolean {\n const root = control.getRootNode();\n return (\n (root instanceof Document || root instanceof ShadowRoot) &&\n root.activeElement === control\n );\n}\n\n/**\n * Steps a number control from the keyboard, as the WAI-ARIA spinbutton\n * pattern does: ArrowUp and ArrowDown one step, PageUp and PageDown a\n * large step, Home and End to a limit that is set. With `options.wheel`,\n * the mouse wheel steps too while the control has focus and the pointer is\n * over it, one step per 50 pixels of travel (or per line or page), and\n * the page does not scroll meanwhile.\n *\n * Keys it steps on are taken (`preventDefault`); keys held with Ctrl, Alt\n * or Meta, keys an input method is using and keys another listener took\n * are left alone. A held arrow repeats by the keyboard's own repeat. It\n * holds its listeners and the wheel travel not yet stepped on; `detach`\n * removes them.\n */\nexport function attachStepKeys(\n control: HTMLInputElement,\n initialOptions: StepKeysOptions,\n): AttachedStepKeys {\n let options = initialOptions;\n // Travel the wheel has made toward the next step, up being negative.\n let wheelTravel = 0;\n const listeners = new AbortController();\n const { signal } = listeners;\n\n control.addEventListener(\n \"keydown\",\n (event) => {\n const legacy: LegacyKeyboardEvent = event;\n if (\n event.defaultPrevented ||\n event.isComposing ||\n legacy.keyCode === 229 ||\n event.ctrlKey ||\n event.altKey ||\n event.metaKey\n ) {\n return;\n }\n const step = keyStep(event.key, options.edges);\n if (step === null) {\n return;\n }\n event.preventDefault();\n options.onStep(step[0], step[1], event);\n },\n { signal },\n );\n\n control.addEventListener(\n \"wheel\",\n (event) => {\n if (options.wheel !== true || !hasFocus(control)) {\n wheelTravel = 0;\n return;\n }\n event.preventDefault();\n const unit =\n event.deltaMode === WheelEvent.DOM_DELTA_PIXEL ? 1 : WHEEL_STEP_PIXELS;\n wheelTravel += event.deltaY * unit;\n while (Math.abs(wheelTravel) >= WHEEL_STEP_PIXELS) {\n const direction = wheelTravel < 0 ? \"up\" : \"down\";\n wheelTravel -= Math.sign(wheelTravel) * WHEEL_STEP_PIXELS;\n options.onStep(direction, \"step\", event);\n }\n },\n { signal, passive: false },\n );\n\n control.addEventListener(\n \"blur\",\n () => {\n wheelTravel = 0;\n },\n { signal },\n );\n\n return {\n setOptions: (next) => {\n options = next;\n },\n detach: () => {\n listeners.abort();\n },\n };\n}\n","/** How many lines of text a growing `<textarea>` shows. */\nexport interface AutoGrowOptions {\n /** The lines it shows when empty. */\n readonly minRows: number;\n /** The lines it grows to, before it scrolls. */\n readonly maxRows: number;\n}\n\nexport interface AttachedAutoGrow {\n /**\n * Sets the height for the text there is now. The renderer calls it after\n * it writes text from code, which fires no `input`.\n */\n readonly update: () => void;\n /** Replaces the row range, and sets the height for it. */\n readonly setOptions: (options: AutoGrowOptions) => void;\n /** Stops listening, and leaves the height as it is. */\n readonly detach: () => void;\n}\n\nfunction pixels(value: string): number {\n const parsed = Number.parseFloat(value);\n return Number.isNaN(parsed) ? 0 : parsed;\n}\n\n/** `normal` line height, as browsers draw it for most fonts. */\nconst NORMAL_LINE_HEIGHT = 1.2;\n\n/**\n * Grows a `<textarea>` with its text, from `minRows` lines to `maxRows`,\n * then lets it scroll. The height follows every `input` and every change\n * of the textarea's width, which rewraps the text (a `ResizeObserver`),\n * and is worked out from `scrollHeight`, the computed line height,\n * padding and borders. CSS `field-sizing: content` would do this, but not\n * every browser the forms support has it.\n */\nexport function attachAutoGrow(\n textarea: HTMLTextAreaElement,\n initialOptions: AutoGrowOptions,\n): AttachedAutoGrow {\n let options = initialOptions;\n let width = -1;\n let detached = false;\n let frame = 0;\n const listeners = new AbortController();\n\n function update(): void {\n if (detached) {\n return;\n }\n const style = getComputedStyle(textarea);\n const lineHeight =\n style.lineHeight === \"normal\"\n ? pixels(style.fontSize) * NORMAL_LINE_HEIGHT\n : pixels(style.lineHeight);\n const padding = pixels(style.paddingTop) + pixels(style.paddingBottom);\n const border =\n pixels(style.borderTopWidth) + pixels(style.borderBottomWidth);\n const min = Math.max(1, options.minRows) * lineHeight;\n const max = Math.max(options.minRows, options.maxRows) * lineHeight;\n\n // With no height of its own the textarea's scroll height is its text's.\n textarea.style.height = \"0px\";\n const content = textarea.scrollHeight - padding;\n const inner = Math.min(Math.max(content, min), max);\n const outer =\n style.boxSizing === \"border-box\" ? inner + padding + border : inner;\n textarea.style.height = `${String(outer)}px`;\n textarea.style.overflowY = content > max + 1 ? \"auto\" : \"hidden\";\n }\n\n const resizes = new ResizeObserver(([entry]) => {\n // Only a new width rewraps the text; the height is this behaviour's own.\n const next = entry?.contentRect.width ?? width;\n if (next !== width) {\n width = next;\n // Set the height in the next frame: setting it inside the callback\n // resizes the observed element again in the same frame, which WebKit\n // reports as a \"ResizeObserver loop\" error.\n cancelAnimationFrame(frame);\n frame = requestAnimationFrame(() => {\n frame = 0;\n update();\n });\n }\n });\n resizes.observe(textarea);\n textarea.addEventListener(\"input\", update, { signal: listeners.signal });\n update();\n\n return {\n update,\n setOptions: (next) => {\n options = next;\n update();\n },\n detach: () => {\n detached = true;\n listeners.abort();\n resizes.disconnect();\n cancelAnimationFrame(frame);\n },\n };\n}\n","/** A stretch of a control's text, counted in UTF-16 code units as `selectionStart` is. */\nexport interface TextRange {\n readonly start: number;\n readonly end: number;\n}\n\nlet graphemes: Intl.Segmenter | undefined;\n\n/** Characters as a reader sees them: an emoji or a letter with its accents is one. */\nfunction graphemeSegmenter(): Intl.Segmenter {\n graphemes ??= new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n return graphemes;\n}\n\nfunction graphemeStartBefore(text: string, index: number): number {\n let start = index;\n for (const segment of graphemeSegmenter().segment(text.slice(0, index))) {\n start = segment.index;\n }\n return start;\n}\n\nfunction graphemeEndAfter(text: string, index: number): number {\n const segments = graphemeSegmenter().segment(text.slice(index));\n const first = segments[Symbol.iterator]().next();\n return first.done ? index : index + first.value.segment.length;\n}\n\n/** Back over spaces, then over the word before them, as Ctrl+Backspace deletes. */\nfunction wordStartBefore(text: string, index: number): number {\n const word = /\\S*\\s*$/u.exec(text.slice(0, index))?.[0] ?? \"\";\n return index - word.length;\n}\n\nfunction wordEndAfter(text: string, index: number): number {\n const word = /^\\s*\\S*/u.exec(text.slice(index))?.[0] ?? \"\";\n return index + word.length;\n}\n\nfunction lineStartBefore(text: string, index: number): number {\n return text.lastIndexOf(\"\\n\", index - 1) + 1;\n}\n\nfunction lineEndAfter(text: string, index: number): number {\n const end = text.indexOf(\"\\n\", index);\n return end === -1 ? text.length : end;\n}\n\n/** What a deletion with nothing selected removes around `caret`. */\nfunction deletedAround(\n text: string,\n caret: number,\n inputType: string,\n): TextRange {\n switch (inputType) {\n case \"deleteContentBackward\":\n return { start: graphemeStartBefore(text, caret), end: caret };\n case \"deleteContentForward\":\n return { start: caret, end: graphemeEndAfter(text, caret) };\n case \"deleteWordBackward\":\n return { start: wordStartBefore(text, caret), end: caret };\n case \"deleteWordForward\":\n return { start: caret, end: wordEndAfter(text, caret) };\n case \"deleteSoftLineBackward\":\n case \"deleteHardLineBackward\":\n return { start: lineStartBefore(text, caret), end: caret };\n case \"deleteSoftLineForward\":\n case \"deleteHardLineForward\":\n return { start: caret, end: lineEndAfter(text, caret) };\n case \"deleteEntireSoftLine\":\n return {\n start: lineStartBefore(text, caret),\n end: lineEndAfter(text, caret),\n };\n default:\n return { start: caret, end: caret };\n }\n}\n\nfunction splice(text: string, { start, end }: TextRange, insert: string) {\n return text.slice(0, start) + insert + text.slice(end);\n}\n\n/**\n * The text a browser edit will leave, worked out before the browser makes\n * it: `text` with `range` (the selection, or the text an input method is\n * composing) edited as the `beforeinput` event's `inputType` says,\n * inserting `data`. A deletion with nothing selected removes a character,\n * a word or a line around the caret, as its type says; a word ends at\n * white space.\n *\n * `null` for an edit only the browser can work out: undo and redo, a\n * spelling correction (it replaces a word the event does not locate),\n * swapping two characters, and any type it does not know.\n */\nexport function applyEdit(\n text: string,\n range: TextRange,\n inputType: string,\n data: string | null,\n): string | null {\n switch (inputType) {\n case \"insertLineBreak\":\n case \"insertParagraph\":\n return splice(text, range, \"\\n\");\n case \"insertReplacementText\":\n case \"insertTranspose\":\n return null;\n }\n if (inputType.startsWith(\"insert\")) {\n return splice(text, range, data ?? \"\");\n }\n if (inputType.startsWith(\"delete\")) {\n return splice(\n text,\n range.start === range.end\n ? deletedAround(text, range.start, inputType)\n : range,\n \"\",\n );\n }\n return null;\n}\n","import type {\n ChangeSource,\n FieldController,\n FieldMessage,\n InputFilterDecision,\n TextEdit,\n TextInputDetails,\n} from \"@gridkitjs/forms-core\";\nimport { applyEdit, type TextRange } from \"./applyEdit\";\n\n/** The native controls a text input draws. */\nexport type TextControl = HTMLInputElement | HTMLTextAreaElement;\n\n/**\n * What `attachTextInput` asks of the field it drives: a forms-core\n * `FieldController`, or one part of a composite input.\n */\nexport type TextInputController<V, D extends object> = Pick<\n FieldController<V, D, Event>,\n | \"getState\"\n | \"getText\"\n | \"getMessages\"\n | \"subscribe\"\n | \"beforeInput\"\n | \"input\"\n | \"endComposition\"\n | \"filterComposition\"\n | \"focus\"\n | \"commit\"\n | \"blur\"\n | \"revert\"\n | \"clear\"\n | \"reset\"\n>;\n\n/** What a renderer can change about the pipeline while it is attached. */\nexport interface TextInputOptions {\n /**\n * Selects all the text when the control gains focus from the keyboard or\n * from code. A press of a pointer places the caret as usual.\n */\n readonly selectOnFocus?: boolean | undefined;\n /**\n * What Escape does: puts back the last committed text (`\"revert\"`, the\n * default), empties the field (`\"clear\"`, for a search box), or nothing.\n * It takes the key only when it changed something.\n */\n readonly escape?: \"revert\" | \"clear\" | \"none\" | undefined;\n /** Called just before Escape empties the field, for the renderer's `onClear`. */\n readonly onClear?: ((nativeEvent: Event) => void) | undefined;\n /**\n * Where the caret goes when the field's text is written into the focused\n * control: given the text before, the caret in it and the text after.\n * By default it keeps its distance from the end of the text.\n */\n readonly mapCaret?:\n | ((previousText: string, caret: number, nextText: string) => number)\n | undefined;\n /**\n * What the keypad's decimal key types, whatever the keyboard layout\n * gives: a number field's decimal separator, so the keypad \".\" of a US\n * keyboard types \",\" in a German field.\n */\n readonly decimalKey?: string | undefined;\n /**\n * The furthest a click may leave the caret in the text: a mask's first\n * empty slot. A click that places the caret past it moves it there; a\n * selection is left alone.\n */\n readonly lastCaret?: ((text: string) => number) | undefined;\n /**\n * Who starts and ends the edit. `\"own\"` (the default): the control's\n * focus and blur do, and Tab commits. `\"group\"`: the control is one of\n * several that edit one field (a segmented date's free-text box), so the\n * group around it does, and the control calls neither `focus` nor `blur`\n * and leaves Tab alone.\n */\n readonly focus?: \"own\" | \"group\" | undefined;\n}\n\nexport interface AttachedTextInput {\n /** Replaces the options, from the next event on. */\n readonly setOptions: (options: TextInputOptions) => void;\n /**\n * Removes every listener and clears the control's custom validity. The\n * controller is left as it is, so another control can be attached to it.\n */\n readonly detach: () => void;\n}\n\n/** The text and selection before an edit, which a refused change puts back. */\ninterface TextSnapshot {\n readonly text: string;\n readonly selectionStart: number | null;\n readonly selectionEnd: number | null;\n readonly selectionDirection: \"forward\" | \"backward\" | \"none\" | null;\n}\n\n/**\n * What the pipeline is in the middle of:\n *\n * - `ready`: nothing.\n * - `editing`: the browser is making an edit `onBeforeInput` allowed;\n * `before` is the text and selection it started from.\n * - `composing`: an input method owns the text between `start` and the\n * last `suffixLength` code units, in place of what lay there in\n * `before`, the text when it began. Writes to the control wait for it.\n * - `rewriting`: inserting the data `onBeforeInput` gave in place of the\n * browser's edit, or the whole text the field's filter replaced it\n * with, which is reported once inserted; the events the insert itself\n * fires are ignored. `before` is as for `editing`.\n * - `detached`: every listener is gone.\n */\ntype TextPipelineState =\n | { readonly kind: \"ready\" }\n | { readonly kind: \"editing\"; readonly before: TextSnapshot }\n | {\n readonly kind: \"composing\";\n readonly start: number;\n readonly suffixLength: number;\n readonly before: string;\n }\n | { readonly kind: \"rewriting\"; readonly before: TextSnapshot }\n | { readonly kind: \"detached\" };\n\nconst READY: TextPipelineState = { kind: \"ready\" };\nconst DETACHED: TextPipelineState = { kind: \"detached\" };\n\n/**\n * The one legacy call. `document.execCommand` is deprecated, but inserting\n * text through it is still the only way the browser's undo history keeps\n * an insert made from code.\n */\ninterface EditingDocument {\n execCommand(\n commandId: \"insertText\" | \"delete\",\n showUI: boolean,\n value?: string,\n ): boolean;\n}\n\n/**\n * `keyCode` is deprecated, but 229 is the only sign WebKit gives that the\n * Enter ending a composition went to the input method: it fires that\n * keydown after `compositionend`, with `isComposing` false.\n */\ninterface LegacyKeyboardEvent {\n readonly keyCode: number;\n}\n\n/** Where a browser edit came from, by its `inputType`. */\nfunction sourceOf(inputType: string | null): ChangeSource {\n if (inputType === null) {\n return \"typing\";\n }\n if (inputType.startsWith(\"insertFromPaste\")) {\n return \"paste\";\n }\n if (inputType === \"insertFromDrop\" || inputType === \"deleteByDrag\") {\n return \"drop\";\n }\n return inputType.startsWith(\"history\") ? \"undo\" : \"typing\";\n}\n\nfunction hasFocus(control: TextControl): boolean {\n const root = control.getRootNode();\n return (\n (root instanceof Document || root instanceof ShadowRoot) &&\n root.activeElement === control\n );\n}\n\nfunction snapshot(control: TextControl): TextSnapshot {\n return {\n text: control.value,\n selectionStart: control.selectionStart,\n selectionEnd: control.selectionEnd,\n selectionDirection: control.selectionDirection,\n };\n}\n\n/** The default caret rule: the same distance from the end of the text. */\nfunction caretFromEnd(\n previousText: string,\n caret: number,\n nextText: string,\n): number {\n return Math.max(0, nextText.length - (previousText.length - caret));\n}\n\nfunction errorText(messages: readonly FieldMessage[]): string {\n return messages.find((message) => message.severity === \"error\")?.text ?? \"\";\n}\n\n/**\n * Connects a native text control to a forms-core field controller, so the\n * controller decides what the control's text means and the control shows\n * what the controller holds. The renderer draws the control and calls\n * this once it is in the page.\n *\n * Reads the control's events into the controller's requests, each with the\n * browser event as its `nativeEvent`:\n *\n * - `focus` and `blur` start and end the edit; the blur commits it, unless\n * Tab did. With `options.focus` set to `\"group\"`, the group around the\n * control does all three instead.\n * - `beforeinput` asks `onBeforeInput`, then the field's own\n * `filterInput`, with the text the edit would leave, then lets the edit\n * happen, prevents it, inserts the handler's data in its place, or\n * replaces the whole text and places the caret as the filter says.\n * `input` reports the text the edit left. Where it came from (`typing`,\n * `paste`, `drop`, `undo`) is read from its `inputType`; text that\n * changes while the field is not being edited is `autofill`.\n * - With `options.decimalKey`, the keypad's decimal key types that text,\n * judged as any other typing, in place of what the layout gives.\n * - While an input method composes, every `input` reports `isComposing`\n * and the text is read once `compositionend` arrives. Then the field's\n * `filterInput` judges the composed text as one insert over the range\n * the composition replaced (`filterComposition`), and its replacement,\n * rewrite or refusal is written as for any edit.\n * - With `options.lastCaret`, a click that leaves the caret past it moves\n * the caret there.\n * - Enter commits (in a `<textarea>`, Ctrl+Enter or Cmd+Enter, since Enter\n * is a new line); Tab commits and, when `onBeforeCommit` refuses at once,\n * keeps focus by preventing the key; Escape puts back the last committed\n * text, or empties the field, as `options.escape` says, and takes the key\n * when it changed something. Keys an input method is using, and keys\n * another listener prevented, are left alone.\n * - With `options.selectOnFocus`, focus from the keyboard or from code\n * selects all the text.\n * - A `reset` of the control's form that nobody prevented resets the\n * field, with `source: \"api\"`.\n *\n * After every change of the field it writes the controller's text into\n * the control when the two differ, never while an input method composes.\n * On a focused control a refused change is put back with the selection it\n * had before the edit, and any other write places the selection by\n * `options.mapCaret`, by default at its distance from the end of the\n * text, so separators a formatter adds before the caret do not move it. A\n * write to an unfocused control leaves the selection alone. The control's\n * custom validity holds the field's first error, shown or not yet, so a\n * plain `<form>` refuses to submit it.\n *\n * Inserting the handler's data, and replacing the text, go through the\n * browser's editing commands where the browser allows it, so they can be\n * undone; elsewhere the text is set directly. Setting the text from code\n * (a refused change put back, a commit normalizing the text, a value from\n * the app) cannot be undone.\n */\nexport function attachTextInput<V, D extends object>(\n control: TextControl,\n controller: TextInputController<V, D>,\n initialOptions: TextInputOptions = {},\n): AttachedTextInput {\n let options = initialOptions;\n let state: TextPipelineState = READY;\n let customValidity = \"\";\n // A pointer pressed on the unfocused control: the focus that follows\n // places the caret, so it selects nothing. That focus, or the press's\n // click where focus comes later (a touch), clears it.\n let pointerFocus = false;\n const listeners = new AbortController();\n const { signal } = listeners;\n\n function selection(): TextRange | null {\n const { selectionStart, selectionEnd } = control;\n if (state.kind === \"composing\") {\n return {\n start: state.start,\n end: control.value.length - state.suffixLength,\n };\n }\n return selectionStart === null || selectionEnd === null\n ? null\n : { start: selectionStart, end: selectionEnd };\n }\n\n function details(event: Event): TextInputDetails | null {\n if (!(event instanceof InputEvent)) {\n return null;\n }\n return {\n inputType: event.inputType === \"\" ? null : event.inputType,\n data: event.data,\n selectionStart: control.selectionStart,\n selectionEnd: control.selectionEnd,\n isComposing: event.isComposing,\n };\n }\n\n /** Puts `text` in the control, keeping the selection by the caret rule. */\n function writeText(text: string): void {\n if (!hasFocus(control)) {\n control.value = text;\n return;\n }\n const before =\n state.kind === \"editing\" || state.kind === \"rewriting\"\n ? state.before\n : null;\n if (before?.text === text) {\n control.value = text;\n if (before.selectionStart !== null && before.selectionEnd !== null) {\n control.setSelectionRange(\n before.selectionStart,\n before.selectionEnd,\n before.selectionDirection ?? undefined,\n );\n }\n return;\n }\n const { selectionStart, selectionEnd, selectionDirection } = control;\n const previous = control.value;\n control.value = text;\n if (selectionStart !== null && selectionEnd !== null) {\n const map = options.mapCaret ?? caretFromEnd;\n control.setSelectionRange(\n map(previous, selectionStart, text),\n map(previous, selectionEnd, text),\n selectionDirection ?? undefined,\n );\n }\n }\n\n /** Shows what the controller holds: its text, and its first error as the custom validity. */\n function render(): void {\n if (state.kind === \"composing\" || state.kind === \"detached\") {\n return;\n }\n const text = controller.getText();\n if (control.value !== text) {\n writeText(text);\n }\n const validity = errorText(controller.getMessages());\n if (validity !== customValidity) {\n customValidity = validity;\n control.setCustomValidity(validity);\n }\n }\n\n /** Inserts `data` where the browser was about to edit, as the edit `cause` describes. */\n function rewrite(cause: TextEdit<Event>, data: string): void {\n const range = selection();\n state = { kind: \"rewriting\", before: snapshot(control) };\n const editing: EditingDocument = control.ownerDocument;\n if (!editing.execCommand(\"insertText\", false, data) && range !== null) {\n control.setRangeText(data, range.start, range.end, \"end\");\n }\n controller.input({ ...cause, text: control.value });\n state = READY;\n }\n\n /** Chromium fires a line break's `beforeinput` for Enter in an `<input>`, which takes no line breaks. */\n function editsNothing(inputType: string | null): boolean {\n return (\n control instanceof HTMLInputElement &&\n (inputType === \"insertLineBreak\" || inputType === \"insertParagraph\")\n );\n }\n\n /**\n * Replaces the whole text with `text`, as the field's own filter asked,\n * and puts the caret at `caret`. Text that stays the same only moves the\n * caret.\n */\n function replace(cause: TextEdit<Event>, text: string, caret: number): void {\n if (control.value !== text) {\n state = { kind: \"rewriting\", before: snapshot(control) };\n control.setSelectionRange(0, control.value.length);\n const editing: EditingDocument = control.ownerDocument;\n const inserted =\n text === \"\"\n ? editing.execCommand(\"delete\", false)\n : editing.execCommand(\"insertText\", false, text);\n if (!inserted || control.value !== text) {\n control.value = text;\n }\n controller.input({ ...cause, text: control.value });\n state = READY;\n }\n if (control.value === text) {\n control.setSelectionRange(caret, caret);\n }\n }\n\n /** What the app and the field's filter decide about an edit the browser is about to make. */\n function decide(\n inputType: string | null,\n data: string | null,\n nativeEvent: Event,\n cancelable: boolean,\n composing: boolean,\n ): {\n readonly edit: TextEdit<Event>;\n readonly decision: InputFilterDecision;\n } {\n const range = selection();\n const proposed =\n range === null || inputType === null\n ? null\n : applyEdit(control.value, range, inputType, data);\n const input: TextInputDetails = {\n inputType,\n data,\n selectionStart: range?.start ?? null,\n selectionEnd: range?.end ?? null,\n isComposing: composing,\n };\n const edit: TextEdit<Event> = {\n text: proposed ?? control.value,\n source: sourceOf(inputType),\n input,\n nativeEvent,\n };\n const decision = controller.beforeInput({\n ...edit,\n cancelable: cancelable && !composing,\n });\n return { edit, decision };\n }\n\n /** Inserts the data of a rewrite, or replaces the text, as `decision` says. */\n function applyOwn(\n edit: TextEdit<Event>,\n decision: InputFilterDecision,\n ): void {\n if (decision.kind === \"rewrite\") {\n rewrite(\n {\n ...edit,\n input: edit.input && { ...edit.input, data: decision.data },\n },\n decision.data,\n );\n } else if (decision.kind === \"replace\") {\n replace(edit, decision.text, decision.caret);\n }\n }\n\n function onBeforeInput(event: InputEvent): void {\n const inputType = event.inputType === \"\" ? null : event.inputType;\n if (state.kind === \"rewriting\" || editsNothing(inputType)) {\n return;\n }\n const { edit, decision } = decide(\n inputType,\n event.data,\n event,\n event.cancelable,\n event.isComposing || state.kind === \"composing\",\n );\n if (decision.kind === \"allow\") {\n if (state.kind !== \"composing\") {\n state = { kind: \"editing\", before: snapshot(control) };\n }\n return;\n }\n event.preventDefault();\n applyOwn(edit, decision);\n }\n\n /**\n * Types `data` as though the keyboard had: the app and the filter judge\n * it, then it is inserted. For a key whose own text is replaced, such as\n * the keypad's decimal key.\n */\n function typeText(data: string, nativeEvent: KeyboardEvent): void {\n const { edit, decision } = decide(\n \"insertText\",\n data,\n nativeEvent,\n true,\n false,\n );\n applyOwn(\n edit,\n decision.kind === \"allow\" ? { kind: \"rewrite\", data } : decision,\n );\n }\n\n function onInput(event: Event): void {\n if (state.kind === \"rewriting\") {\n return;\n }\n const input = details(event);\n controller.input({\n text: control.value,\n source:\n controller.getState().phase.kind === \"idle\"\n ? \"autofill\"\n : sourceOf(input?.inputType ?? null),\n input,\n nativeEvent: event,\n });\n if (state.kind === \"editing\") {\n state = READY;\n }\n }\n\n function onCompositionStart(): void {\n const range = selection() ?? { start: 0, end: control.value.length };\n state = {\n kind: \"composing\",\n start: range.start,\n suffixLength: control.value.length - range.end,\n before: control.value,\n };\n }\n\n /**\n * Asks the field's filter about the text a composition left, as one\n * insert over the range it replaced, and writes what the filter decides:\n * its text, the composed text rewritten, or, when it refuses, the text\n * from before the composition.\n */\n function filterComposed(\n composition: Extract<TextPipelineState, { kind: \"composing\" }>,\n nativeEvent: CompositionEvent,\n ): void {\n const { start, suffixLength, before } = composition;\n const data = control.value.slice(\n start,\n control.value.length - suffixLength,\n );\n const replacedEnd = before.length - suffixLength;\n if (data === \"\" || replacedEnd < start) {\n return;\n }\n const edit: TextEdit<Event> = {\n text: control.value,\n source: \"typing\",\n input: {\n inputType: \"insertCompositionText\",\n data,\n selectionStart: start,\n selectionEnd: replacedEnd,\n isComposing: false,\n },\n nativeEvent,\n };\n const decision = controller.filterComposition(edit, before);\n switch (decision.kind) {\n case \"allow\":\n return;\n case \"prevent\":\n replace(edit, before, start);\n return;\n case \"rewrite\":\n replace(\n edit,\n before.slice(0, start) + decision.data + before.slice(replacedEnd),\n start + decision.data.length,\n );\n return;\n case \"replace\":\n replace(edit, decision.text, decision.caret);\n return;\n }\n }\n\n function onCompositionEnd(event: CompositionEvent): void {\n const composition = state.kind === \"composing\" ? state : null;\n // Firefox ends a composition committed in one step before the `input`\n // that reports its text, so the text is reported here; otherwise the\n // render below would write the old text over it. That late `input`\n // then finds nothing new.\n if (control.value !== controller.getText()) {\n controller.input({\n text: control.value,\n source: \"typing\",\n input: {\n inputType: \"insertCompositionText\",\n data: event.data,\n selectionStart: control.selectionStart,\n selectionEnd: control.selectionEnd,\n isComposing: true,\n },\n nativeEvent: event,\n });\n }\n state = READY;\n if (composition !== null) {\n filterComposed(composition, event);\n }\n controller.endComposition(event);\n render();\n }\n\n function isComposing(event: KeyboardEvent): boolean {\n const legacy: LegacyKeyboardEvent = event;\n return (\n event.isComposing || state.kind === \"composing\" || legacy.keyCode === 229\n );\n }\n\n function commitsOnEnter(event: KeyboardEvent): boolean {\n return control instanceof HTMLTextAreaElement\n ? event.ctrlKey || event.metaKey\n : true;\n }\n\n function onKeyDown(event: KeyboardEvent): void {\n if (event.defaultPrevented || isComposing(event)) {\n return;\n }\n const modified = event.ctrlKey || event.altKey || event.metaKey;\n // With Num Lock off the key is Delete, and stays one.\n if (\n event.code === \"NumpadDecimal\" &&\n event.key.length === 1 &&\n options.decimalKey !== undefined &&\n !modified &&\n !control.readOnly &&\n !control.disabled\n ) {\n event.preventDefault();\n typeText(options.decimalKey, event);\n return;\n }\n switch (event.key) {\n case \"Enter\":\n if (commitsOnEnter(event)) {\n controller.commit(\"enter\", event);\n }\n return;\n case \"Tab\":\n if (\n !modified &&\n !inGroup() &&\n controller.commit(\"tab\", event).kind === \"refused\"\n ) {\n event.preventDefault();\n }\n return;\n case \"Escape\":\n if (!modified && !event.shiftKey && escape(event)) {\n event.preventDefault();\n }\n return;\n }\n }\n\n /** Does what Escape does, and says whether it changed anything. */\n function escape(event: KeyboardEvent): boolean {\n switch (options.escape ?? \"revert\") {\n case \"revert\":\n return controller.revert(event);\n case \"clear\":\n if (control.readOnly || controller.getText() === \"\") {\n return false;\n }\n options.onClear?.(event);\n controller.clear(event);\n return true;\n case \"none\":\n return false;\n }\n }\n\n function inGroup(): boolean {\n return options.focus === \"group\";\n }\n\n function onFocus(event: FocusEvent): void {\n if (!inGroup()) {\n controller.focus(event);\n }\n if (options.selectOnFocus === true && !pointerFocus) {\n control.select();\n }\n pointerFocus = false;\n }\n\n /** Moves a caret a click left past `options.lastCaret` back to it. */\n function limitCaret(): void {\n const { lastCaret } = options;\n const { selectionStart, selectionEnd } = control;\n if (\n lastCaret === undefined ||\n selectionStart === null ||\n selectionStart !== selectionEnd ||\n !hasFocus(control)\n ) {\n return;\n }\n const last = lastCaret(control.value);\n if (selectionStart > last) {\n control.setSelectionRange(last, last);\n }\n }\n\n // On the document, so the app's own listeners have had their say first.\n function onReset(event: Event): void {\n if (event.defaultPrevented || event.target !== control.form) {\n return;\n }\n controller.reset();\n // The browser's reset, which follows this event, puts back this text.\n control.defaultValue = controller.getText();\n }\n\n // A union of the two controls loses the event map, so listen through one type.\n const element: HTMLElement = control;\n element.addEventListener(\"focus\", onFocus, { signal });\n element.addEventListener(\n \"pointerdown\",\n () => {\n pointerFocus = !hasFocus(control);\n },\n { signal },\n );\n element.addEventListener(\n \"click\",\n () => {\n pointerFocus = false;\n limitCaret();\n },\n { signal },\n );\n element.addEventListener(\n \"blur\",\n (event) => {\n if (!inGroup()) {\n controller.blur(event);\n }\n },\n { signal },\n );\n element.addEventListener(\"beforeinput\", onBeforeInput, { signal });\n element.addEventListener(\"input\", onInput, { signal });\n element.addEventListener(\"compositionstart\", onCompositionStart, { signal });\n element.addEventListener(\"compositionend\", onCompositionEnd, { signal });\n element.addEventListener(\"keydown\", onKeyDown, { signal });\n control.ownerDocument.addEventListener(\"reset\", onReset, { signal });\n const unsubscribe = controller.subscribe(render);\n\n // A control focused before it was attached (`autofocus`) starts its edit now.\n if (hasFocus(control) && !inGroup()) {\n controller.focus(null);\n }\n render();\n\n return {\n setOptions: (next) => {\n options = next;\n },\n detach: () => {\n if (state.kind === \"detached\") {\n return;\n }\n state = DETACHED;\n listeners.abort();\n unsubscribe();\n control.setCustomValidity(\"\");\n },\n };\n}\n","import {\n nextCheckedValue,\n type FieldController,\n type FieldMessage,\n} from \"@gridkitjs/forms-core\";\n\n/** What a renderer can change about a toggle while it is attached. */\nexport interface ToggleOptions {\n /** A flip can set `null` (indeterminate): `false` → `true` → `null` → `false`. */\n readonly threeState?: boolean | undefined;\n /**\n * Refuses every flip and stays focusable. A native checkbox ignores the\n * `readonly` attribute, so the renderer says so here.\n */\n readonly readOnly?: boolean | undefined;\n}\n\nexport interface AttachedToggle {\n /** Replaces the options, from the next event on. */\n readonly setOptions: (options: ToggleOptions) => void;\n /**\n * Removes every listener and clears the control's custom validity. The\n * controller is left as it is, so another control can be attached to it.\n */\n readonly detach: () => void;\n}\n\nfunction hasFocus(control: HTMLElement): boolean {\n const root = control.getRootNode();\n return (\n (root instanceof Document || root instanceof ShadowRoot) &&\n root.activeElement === control\n );\n}\n\nfunction errorText(messages: readonly FieldMessage[]): string {\n return messages.find((message) => message.severity === \"error\")?.text ?? \"\";\n}\n\n/**\n * Connects a native `<input type=\"checkbox\">`, a checkbox or a\n * `role=\"switch\"`, to a forms-core field controller holding a boolean, so\n * the controller decides what each flip means and the control shows what\n * the controller holds.\n *\n * - The browser's `click`, from a pointer, a label or <kbd>Space</kbd>,\n * flips the field to `nextCheckedValue` of what it holds, through\n * `controller.pick` with `source` and `trigger` `\"toggle\"`: the change\n * events, then the commit. A flip by Space carries the Space `keydown`\n * as its `nativeEvent`, a press the `click`.\n * - With `options.readOnly` the click is prevented, so nothing changes.\n * - `focus` and `blur` start and end the edit; leaving commits nothing\n * more, so the controller should have `commitOnLeave: false`.\n * - A `reset` of the control's form that nobody prevented resets the\n * field, with `source: \"api\"`.\n *\n * After every change of the field it writes `checked` (the value is\n * `true`) and `indeterminate` (it is `null`), over whatever the browser\n * did with the click, and holds the field's first error as the control's\n * custom validity, so a plain `<form>` refuses to submit it.\n */\nexport function attachToggle<D extends object>(\n control: HTMLInputElement,\n controller: FieldController<boolean, D, Event>,\n initialOptions: ToggleOptions = {},\n): AttachedToggle {\n let options = initialOptions;\n let attached = true;\n let customValidity = \"\";\n // The Space keydown whose click is coming: the flip reports the key.\n let spaceKey: KeyboardEvent | null = null;\n const listeners = new AbortController();\n const { signal } = listeners;\n\n function render(): void {\n if (!attached) {\n return;\n }\n const { value } = controller.getState();\n control.checked = value === true;\n control.indeterminate = value === null;\n const validity = errorText(controller.getMessages());\n if (validity !== customValidity) {\n customValidity = validity;\n control.setCustomValidity(validity);\n }\n }\n\n function onClick(event: MouseEvent): void {\n const nativeEvent = spaceKey ?? event;\n spaceKey = null;\n if (options.readOnly === true) {\n event.preventDefault();\n return;\n }\n const next = nextCheckedValue(\n controller.getState().value,\n options.threeState === true,\n );\n controller.pick(next, \"toggle\", \"toggle\", nativeEvent);\n render();\n }\n\n function onKeyDown(event: KeyboardEvent): void {\n spaceKey = event.key === \" \" && !event.defaultPrevented ? event : null;\n }\n\n // On the document, so the app's own listeners have had their say first.\n function onReset(event: Event): void {\n if (event.defaultPrevented || event.target !== control.form) {\n return;\n }\n controller.reset();\n // The browser's reset, which follows this event, puts back this state.\n control.defaultChecked = controller.getState().value === true;\n }\n\n control.addEventListener(\"click\", onClick, { signal });\n control.addEventListener(\"keydown\", onKeyDown, { signal });\n control.addEventListener(\n \"pointerdown\",\n () => {\n spaceKey = null;\n },\n { signal },\n );\n control.addEventListener(\n \"focus\",\n (event) => {\n controller.focus(event);\n },\n { signal },\n );\n control.addEventListener(\n \"blur\",\n (event) => {\n spaceKey = null;\n controller.blur(event);\n },\n { signal },\n );\n control.ownerDocument.addEventListener(\"reset\", onReset, { signal });\n const unsubscribe = controller.subscribe(render);\n\n // A control focused before it was attached (`autofocus`) starts its edit now.\n if (hasFocus(control)) {\n controller.focus(null);\n }\n render();\n\n return {\n setOptions: (next) => {\n options = next;\n },\n detach: () => {\n if (!attached) {\n return;\n }\n attached = false;\n listeners.abort();\n unsubscribe();\n control.setCustomValidity(\"\");\n },\n };\n}\n","import {\n idleSegments,\n segmentAria,\n segmentReducer,\n segmentSpans,\n splitSegments,\n type ChangeSource,\n type FormsMessages,\n type SegmentAction,\n type SegmentContext,\n type SegmentEntry,\n type SegmentState,\n type SegmentStep,\n type TextEdit,\n} from \"@gridkitjs/forms-core\";\nimport { attachFocusGroup } from \"../form/attachFocusGroup\";\nimport {\n attachTextInput,\n type TextInputController,\n} from \"../text/attachTextInput\";\n\n/** What `attachSegments` asks of the field it drives: a controller, or a part of a composite. */\nexport type SegmentsController<V, D extends object> = TextInputController<V, D>;\n\n/** What a renderer can change about the segments while they are attached. */\nexport interface SegmentsOptions {\n /** The field's layout and how it reads, for the segment reducer. */\n readonly context: SegmentContext;\n /** The locale a month's name is read in, for its `aria-valuetext`. */\n readonly locale: Intl.LocalesArgument;\n /** For an empty segment's `aria-valuetext`. */\n readonly messages: FormsMessages;\n /** What Escape in a segment does: puts back the last committed value (`\"revert\"`, the default), or nothing. */\n readonly escape?: \"revert\" | \"none\" | undefined;\n /**\n * Whether `node`, outside the group, counts as inside the field: the\n * picker popup it opened, so focus moving there neither commits nor\n * blurs the field.\n */\n readonly isInside?: ((node: Node) => boolean) | undefined;\n /** F4 or Alt+ArrowDown in a segment: the renderer opens its picker. */\n readonly onOpenPicker?: ((nativeEvent: KeyboardEvent) => void) | undefined;\n}\n\nexport interface AttachedSegments {\n /** Replaces the options, from the next event on, and redraws the segments. */\n readonly setOptions: (options: SegmentsOptions) => void;\n /** Focuses a segment, or the first empty one (the free-text box while it shows), as a click in the box does. */\n readonly focus: (segment?: number | \"firstEmpty\") => void;\n /** Where typing stands (the segment typed in, or the free-text box with the segments' text it opened over) and the text it holds. */\n readonly getState: () => SegmentState;\n /** Removes every listener, the free-text box's pipeline included. */\n readonly detach: () => void;\n}\n\n/** What a reported edit came from: the browser's event and what it typed. */\ninterface EditCause {\n readonly nativeEvent: Event | null;\n readonly inputType: string | null;\n readonly data: string | null;\n /** In place of the reducer's source: a drop is a paste to the reducer. */\n readonly source?: ChangeSource | undefined;\n}\n\nconst NO_CAUSE: EditCause = { nativeEvent: null, inputType: null, data: null };\n\n/**\n * `keyCode` is deprecated, but 229 is the only sign some engines give that\n * a key went to an input method, Android keyboards among them.\n */\ninterface LegacyKeyboardEvent {\n readonly keyCode: number;\n}\n\n/** The segment typing is in, or `null`. */\nfunction segmentOf(entry: SegmentEntry): number | null {\n return entry.kind === \"active\" ||\n entry.kind === \"typing\" ||\n entry.kind === \"composing\"\n ? entry.segment\n : null;\n}\n\n/** Edits a segment's `beforeinput` reports that empty it. */\nconst EMPTYING = new Set([\n \"deleteContentForward\",\n \"deleteWordBackward\",\n \"deleteWordForward\",\n \"deleteSoftLineBackward\",\n \"deleteSoftLineForward\",\n \"deleteHardLineBackward\",\n \"deleteHardLineForward\",\n \"deleteByCut\",\n \"deleteContent\",\n]);\n\n/**\n * Drives a segmented date, time or date-time field: one native input per\n * segment (each marked `data-gridkit-forms-segment`, in typing order)\n * inside `group`, the segments' wrapper marked\n * `data-gridkit-forms-segments`, and a free-text box marked\n * `data-gridkit-forms-segment-text` for shortcuts and text that is not\n * segments. forms-core's `segmentReducer` decides every transition; this\n * turns the browser's events into its actions and applies what it returns:\n *\n * - `beforeinput` on a segment (typing, Android's keys, a cut, a drop),\n * its `paste` and its composition events are actions. Every cancelable\n * edit is prevented and each segment's text is written here, so a\n * segment never holds what the reducer did not put there.\n * - Backspace and Delete, the arrows, PageUp and PageDown, Home and End are\n * read from `keydown`. ArrowLeft and ArrowRight move by the segments'\n * order on screen, so they follow a right-to-left field.\n * - A text change is reported to the controller as an edit: `onBeforeInput`\n * first (refused, nothing changes), then `onInput` with the segment's\n * place in the field's text as the edit's selection, from which the\n * field's `details` names the segment. Steps report `source: \"step\"`.\n * - Focus entering the group starts the edit; moving between segments and\n * the free-text box fires nothing; leaving finishes the segment (pads it,\n * pivots a short year) and blurs the field, which commits. Enter\n * finishes and commits; Tab finishes and commits, kept in the field when\n * `onBeforeCommit` refuses; Escape reverts, or in the free-text box goes\n * back to the segments.\n * - A press in the box outside a segment focuses the first empty segment;\n * a press on the focused day period flips it.\n * - The free-text box runs forms-dom's text pipeline in group focus mode;\n * its edits go through the reducer, which applies a one-letter shortcut\n * at once and goes back to the segments when the box is emptied.\n *\n * After every change of the field it writes each segment's text, its\n * `aria-valuenow`, `aria-valuemin`, `aria-valuemax` and `aria-valuetext`,\n * and, while focus is outside the group, shows the free-text box in place\n * of the segments when the text is not segments.\n *\n * It holds the reducer's `SegmentEntry`, its listeners (one\n * `AbortController`), the focus group and the free-text box's pipeline;\n * `detach` releases all of them.\n */\nexport function attachSegments<V, D extends object>(\n group: HTMLElement,\n controller: SegmentsController<V, D>,\n initialOptions: SegmentsOptions,\n): AttachedSegments {\n let options = initialOptions;\n let state: SegmentState = idleSegments(controller.getText());\n // The segment a pointer pressed while it had focus: its click flips a\n // day period.\n let pressedFocused: HTMLInputElement | null = null;\n const listeners = new AbortController();\n const { signal } = listeners;\n\n function segmentInputs(): HTMLInputElement[] {\n return Array.from(\n group.querySelectorAll<HTMLInputElement>(\n \"input[data-gridkit-forms-segment]\",\n ),\n );\n }\n\n function textBox(): HTMLInputElement | null {\n return group.querySelector<HTMLInputElement>(\n \"input[data-gridkit-forms-segment-text]\",\n );\n }\n\n function segmentsWrapper(): HTMLElement | null {\n return group.querySelector<HTMLElement>(\"[data-gridkit-forms-segments]\");\n }\n\n function activeElement(): Element | null {\n const root = group.getRootNode();\n return root instanceof Document || root instanceof ShadowRoot\n ? root.activeElement\n : null;\n }\n\n function focusWithin(): boolean {\n const active = activeElement();\n return active !== null && group.contains(active);\n }\n\n function caretToEnd(input: HTMLInputElement): void {\n input.setSelectionRange(input.value.length, input.value.length);\n }\n\n /** Moves focus where a step says, showing the segments or the free-text box first and hiding the other after. */\n function place(focus: SegmentStep[\"focus\"]): void {\n if (focus === null) {\n return;\n }\n const box = textBox();\n const wrapper = segmentsWrapper();\n if (focus === \"text\") {\n if (box === null) {\n return;\n }\n box.hidden = false;\n if (activeElement() !== box) {\n box.focus();\n }\n caretToEnd(box);\n if (wrapper !== null) {\n wrapper.hidden = true;\n }\n return;\n }\n const input = segmentInputs()[focus];\n if (input === undefined) {\n return;\n }\n if (wrapper !== null) {\n wrapper.hidden = false;\n }\n if (activeElement() !== input) {\n input.focus();\n }\n caretToEnd(input);\n if (box !== null) {\n box.hidden = true;\n }\n }\n\n /**\n * The state, caught up with the controller's text when that changed from\n * outside (a controlled value, a revert, a clear, a commit), moving focus\n * between the segments and the free-text box when the change takes it\n * from one to the other.\n */\n function held(): SegmentState {\n const text = controller.getText();\n if (text !== state.text) {\n const step = segmentReducer(\n state,\n { type: \"outside\", text },\n options.context,\n );\n const moved =\n (state.entry.kind === \"text\") !== (step.state.entry.kind === \"text\");\n state = step.state;\n if (moved && focusWithin()) {\n place(step.focus);\n }\n }\n return state;\n }\n\n function setAttribute(\n element: Element,\n name: string,\n value: string | null,\n ): void {\n if (value === null) {\n element.removeAttribute(name);\n } else if (element.getAttribute(name) !== value) {\n element.setAttribute(name, value);\n }\n }\n\n /** Writes each segment's text and value attributes, and which face shows while focus is elsewhere. */\n function render(): void {\n const current = held();\n const { layout } = options.context;\n const texts = splitSegments(layout, current.text);\n const shown = texts ?? layout.segments.map(() => \"\");\n const active = activeElement();\n segmentInputs().forEach((input, index) => {\n const text = shown[index] ?? \"\";\n if (input.value !== text) {\n input.value = text;\n if (input === active) {\n caretToEnd(input);\n }\n }\n const aria = segmentAria(\n layout,\n index,\n shown,\n options.locale,\n options.messages,\n );\n setAttribute(\n input,\n \"aria-valuenow\",\n aria.valueNow === null ? null : String(aria.valueNow),\n );\n setAttribute(input, \"aria-valuemin\", String(aria.valueMin));\n setAttribute(input, \"aria-valuemax\", String(aria.valueMax));\n setAttribute(input, \"aria-valuetext\", aria.valueText);\n });\n if (!focusWithin()) {\n const free = current.entry.kind === \"text\" || texts === null;\n const box = textBox();\n const wrapper = segmentsWrapper();\n if (box !== null) {\n box.hidden = !free;\n }\n if (wrapper !== null) {\n wrapper.hidden = free;\n }\n }\n }\n\n /** The edit a step reports: the segment it was in as the selection, in the text it leaves. */\n function editFor(\n before: SegmentState,\n step: SegmentStep,\n cause: EditCause,\n ): TextEdit<Event> {\n const edited = segmentOf(before.entry);\n const span =\n edited === null\n ? undefined\n : segmentSpans(options.context.layout, step.state.text)?.[edited];\n return {\n text: step.state.text,\n source: cause.source ?? step.source ?? \"typing\",\n nativeEvent: cause.nativeEvent,\n input: {\n inputType: cause.inputType,\n data: cause.data,\n selectionStart: span?.[0] ?? null,\n selectionEnd: span?.[1] ?? null,\n isComposing: false,\n },\n };\n }\n\n /**\n * Applies a step: a text change goes to the app's `onBeforeInput`, which\n * may refuse it or type other text in its place, and then to the\n * controller; focus moves where the step says.\n */\n function apply(\n before: SegmentState,\n proposed: SegmentStep,\n cause: EditCause,\n ): void {\n let step = proposed;\n let { data } = cause;\n if (step.source !== null) {\n const verdict = controller.beforeInput({\n ...editFor(before, step, cause),\n cancelable: true,\n });\n if (verdict.kind === \"prevent\") {\n render();\n return;\n }\n if (verdict.kind === \"rewrite\") {\n step = segmentReducer(\n before,\n { type: \"key\", text: verdict.data },\n options.context,\n );\n data = verdict.data;\n }\n }\n if (step.source === null) {\n state = step.state;\n } else {\n report(before, step, editFor(before, step, { ...cause, data }));\n }\n place(step.focus);\n render();\n }\n\n /**\n * Reports a step's text to the controller. A shortcut applied at once is\n * reported first as the free text typed, so the events it fires name the\n * shortcut, and then as the segments it gave.\n */\n function report(\n before: SegmentState,\n step: SegmentStep,\n edit: TextEdit<Event>,\n ): void {\n if (step.applied !== undefined) {\n state = {\n entry:\n before.entry.kind === \"text\"\n ? before.entry\n : { kind: \"text\", before: before.text },\n text: step.applied,\n };\n controller.input({\n ...edit,\n text: step.applied,\n input: withoutPlace(edit),\n });\n }\n state = step.state;\n controller.input(edit);\n }\n\n /** An edit's input details with no place in the text: text that is not segments names no segment. */\n function withoutPlace(edit: TextEdit<Event>): TextEdit<Event>[\"input\"] {\n return (\n edit.input && { ...edit.input, selectionStart: null, selectionEnd: null }\n );\n }\n\n function run(action: SegmentAction, cause: EditCause = NO_CAUSE): void {\n const before = held();\n apply(before, segmentReducer(before, action, options.context), cause);\n }\n\n /** Finishes the segment typed in, as Enter, Tab and leaving do before the field commits. */\n function finish(nativeEvent: Event): void {\n run({ type: \"finish\" }, { ...NO_CAUSE, nativeEvent });\n }\n\n function isComposing(event: KeyboardEvent): boolean {\n const legacy: LegacyKeyboardEvent = event;\n return (\n event.isComposing ||\n state.entry.kind === \"composing\" ||\n legacy.keyCode === 229\n );\n }\n\n /** ArrowLeft or ArrowRight from segment `index`: its neighbour on screen, or `null` at the edge. */\n function neighbourOnScreen(index: number, key: string): number | null {\n const inputs = segmentInputs();\n const byPosition = inputs\n .map((input, at) => ({ at, left: input.getBoundingClientRect().left }))\n .sort((a, b) => a.left - b.left);\n const position = byPosition.findIndex((entry) => entry.at === index);\n const next = byPosition[position + (key === \"ArrowRight\" ? 1 : -1)];\n return next?.at ?? null;\n }\n\n function onSegmentKey(\n event: KeyboardEvent,\n input: HTMLInputElement,\n index: number,\n ): void {\n const editable = !input.readOnly;\n const step = (\n direction: \"up\" | \"down\",\n size: \"step\" | \"large\" | \"edge\",\n ) => {\n event.preventDefault();\n if (editable) {\n run(\n { type: \"step\", direction, size },\n { nativeEvent: event, inputType: null, data: null },\n );\n }\n };\n switch (event.key) {\n case \"Enter\":\n finish(event);\n controller.commit(\"enter\", event);\n return;\n case \"Backspace\":\n case \"Delete\":\n event.preventDefault();\n if (editable) {\n run(\n { type: event.key === \"Backspace\" ? \"backspace\" : \"delete\" },\n {\n nativeEvent: event,\n inputType:\n event.key === \"Backspace\"\n ? \"deleteContentBackward\"\n : \"deleteContentForward\",\n data: null,\n },\n );\n }\n return;\n case \"ArrowUp\":\n step(\"up\", \"step\");\n return;\n case \"ArrowDown\":\n step(\"down\", \"step\");\n return;\n case \"PageUp\":\n step(\"up\", \"large\");\n return;\n case \"PageDown\":\n step(\"down\", \"large\");\n return;\n case \"Home\":\n step(\"down\", \"edge\");\n return;\n case \"End\":\n step(\"up\", \"edge\");\n return;\n case \"ArrowLeft\":\n case \"ArrowRight\": {\n event.preventDefault();\n const to = neighbourOnScreen(index, event.key);\n if (to !== null) {\n run(\n { type: \"focus\", segment: to },\n { ...NO_CAUSE, nativeEvent: event },\n );\n }\n return;\n }\n }\n }\n\n function onKeyDown(event: KeyboardEvent): void {\n if (event.defaultPrevented || isComposing(event)) {\n return;\n }\n const { target } = event;\n const inputs = segmentInputs();\n const index =\n target instanceof HTMLInputElement ? inputs.indexOf(target) : -1;\n const box = textBox();\n const inBox = target !== null && target === box;\n const input = inputs[index];\n if (!inBox && input === undefined) {\n return;\n }\n const modified = event.ctrlKey || event.altKey || event.metaKey;\n if (\n input !== undefined &&\n options.onOpenPicker !== undefined &&\n ((event.key === \"F4\" && !modified) ||\n (event.altKey && event.key === \"ArrowDown\"))\n ) {\n event.preventDefault();\n options.onOpenPicker(event);\n return;\n }\n switch (event.key) {\n case \"Tab\":\n if (modified) {\n return;\n }\n finish(event);\n if (controller.commit(\"tab\", event).kind === \"refused\") {\n event.preventDefault();\n }\n return;\n case \"Escape\":\n if (modified || event.shiftKey) {\n return;\n }\n if (inBox && state.entry.kind === \"text\") {\n event.preventDefault();\n run(\n { type: \"textEdit\", text: \"\" },\n { ...NO_CAUSE, nativeEvent: event },\n );\n } else if (\n (options.escape ?? \"revert\") === \"revert\" &&\n controller.revert(event)\n ) {\n event.preventDefault();\n }\n return;\n }\n if (input !== undefined && !modified) {\n onSegmentKey(event, input, index);\n }\n }\n\n function onBeforeInput(event: InputEvent): void {\n const { target } = event;\n if (!(target instanceof HTMLInputElement)) {\n return;\n }\n const index = segmentInputs().indexOf(target);\n // An input method's text is not cancelable: it runs, and is read at its end.\n if (index < 0 || !event.cancelable || event.isComposing) {\n return;\n }\n event.preventDefault();\n if (target.readOnly) {\n return;\n }\n const inputType = event.inputType;\n const cause: EditCause = {\n nativeEvent: event,\n inputType,\n data: event.data,\n };\n if (inputType === \"insertText\" || inputType === \"insertReplacementText\") {\n run({ type: \"key\", text: event.data ?? \"\" }, cause);\n } else if (\n inputType === \"insertFromPaste\" ||\n inputType === \"insertFromDrop\"\n ) {\n const text = event.dataTransfer?.getData(\"text/plain\") ?? event.data;\n run(\n { type: \"paste\", text: text ?? \"\" },\n {\n ...cause,\n data: text,\n source: inputType === \"insertFromDrop\" ? \"drop\" : \"paste\",\n },\n );\n } else if (inputType === \"deleteContentBackward\") {\n run({ type: \"backspace\" }, cause);\n } else if (EMPTYING.has(inputType)) {\n run({ type: \"delete\" }, cause);\n }\n }\n\n /**\n * A paste on a segment: read whole, or typed into the segment when it\n * fits there. Read from the clipboard event, which every engine fills;\n * a drop arrives as its `beforeinput`.\n */\n function onPaste(event: ClipboardEvent): void {\n const { target } = event;\n if (\n !(target instanceof HTMLInputElement) ||\n !segmentInputs().includes(target)\n ) {\n return;\n }\n event.preventDefault();\n if (target.readOnly) {\n return;\n }\n const text = event.clipboardData?.getData(\"text/plain\") ?? \"\";\n run(\n { type: \"paste\", text },\n {\n nativeEvent: event,\n inputType: \"insertFromPaste\",\n data: text,\n source: \"paste\",\n },\n );\n }\n\n function onCompositionStart(event: CompositionEvent): void {\n if (\n event.target instanceof HTMLInputElement &&\n segmentInputs().includes(event.target)\n ) {\n run({ type: \"compositionStart\" });\n }\n }\n\n function onCompositionEnd(event: CompositionEvent): void {\n const { target } = event;\n if (\n !(target instanceof HTMLInputElement) ||\n state.entry.kind !== \"composing\"\n ) {\n return;\n }\n // The input method wrote into the segment; the reducer types what it\n // composed from the segment's text before it began.\n const before = splitSegments(options.context.layout, state.text);\n target.value = before?.[state.entry.segment] ?? \"\";\n run(\n { type: \"compositionEnd\", text: event.data },\n {\n nativeEvent: event,\n inputType: \"insertCompositionText\",\n data: event.data,\n },\n );\n }\n\n /** An edit that slipped past `beforeinput` is undone: the segments show only what the reducer wrote. */\n function onInput(event: Event): void {\n if (\n event.target instanceof HTMLInputElement &&\n segmentInputs().includes(event.target) &&\n state.entry.kind !== \"composing\"\n ) {\n render();\n }\n }\n\n function onFocusIn(event: FocusEvent): void {\n const { target } = event;\n const box = textBox();\n const index =\n target instanceof HTMLInputElement ? segmentInputs().indexOf(target) : -1;\n const inBox = target !== null && target === box;\n if (index < 0 && !inBox) {\n return;\n }\n const current = held();\n if (current.entry.kind === \"idle\") {\n controller.focus(event);\n }\n if (inBox) {\n if (state.entry.kind !== \"text\") {\n run({ type: \"focus\", segment: 0 }, { ...NO_CAUSE, nativeEvent: event });\n }\n return;\n }\n if (segmentOf(state.entry) !== index) {\n run(\n { type: \"focus\", segment: index },\n { ...NO_CAUSE, nativeEvent: event },\n );\n }\n }\n\n /**\n * Focus left the group: the segment typed in is finished and reported\n * while the field still knows where typing stood, then the field blurs,\n * which commits it.\n */\n function leave(nativeEvent: FocusEvent): void {\n const before = held();\n if (before.entry.kind === \"idle\") {\n return;\n }\n const step = segmentReducer(before, { type: \"leave\" }, options.context);\n if (step.source !== null) {\n const edit = editFor(before, step, { ...NO_CAUSE, nativeEvent });\n const verdict = controller.beforeInput({ ...edit, cancelable: true });\n if (verdict.kind !== \"prevent\") {\n state = { entry: before.entry, text: step.state.text };\n controller.input(edit);\n }\n }\n controller.blur(nativeEvent);\n state = idleSegments(controller.getText());\n render();\n }\n\n function focusSegment(segment: number | \"firstEmpty\" = \"firstEmpty\"): void {\n const current = held();\n const { layout } = options.context;\n const texts = splitSegments(layout, current.text);\n if (texts === null || current.entry.kind === \"text\") {\n const box = textBox();\n if (box !== null) {\n box.hidden = false;\n box.focus();\n }\n return;\n }\n const index =\n segment === \"firstEmpty\"\n ? Math.max(\n texts.findIndex((text) => text === \"\"),\n 0,\n )\n : segment;\n segmentInputs()[index]?.focus();\n }\n\n function isOwnControl(target: EventTarget | null): boolean {\n return (\n target instanceof Element &&\n target.closest(\"input, button, select, textarea, a, label\") !== null\n );\n }\n\n group.addEventListener(\"keydown\", onKeyDown, { signal });\n group.addEventListener(\"beforeinput\", onBeforeInput, { signal });\n group.addEventListener(\"input\", onInput, { signal });\n group.addEventListener(\"paste\", onPaste, { signal });\n group.addEventListener(\"compositionstart\", onCompositionStart, { signal });\n group.addEventListener(\"compositionend\", onCompositionEnd, { signal });\n group.addEventListener(\"focusin\", onFocusIn, { signal });\n // A press on the box around the segments keeps focus where it is, rather\n // than blurring the field, and the click that follows focuses a segment.\n group.addEventListener(\n \"mousedown\",\n (event) => {\n if (!isOwnControl(event.target) && focusWithin()) {\n event.preventDefault();\n }\n },\n { signal },\n );\n group.addEventListener(\n \"pointerdown\",\n (event) => {\n const { target } = event;\n pressedFocused =\n target instanceof HTMLInputElement &&\n target === activeElement() &&\n segmentInputs().includes(target)\n ? target\n : null;\n },\n { signal },\n );\n group.addEventListener(\n \"click\",\n (event) => {\n const { target } = event;\n const inputs = segmentInputs();\n const disabled = inputs.every((input) => input.disabled);\n if (!isOwnControl(target)) {\n if (!disabled) {\n focusSegment(\"firstEmpty\");\n }\n return;\n }\n const index =\n target instanceof HTMLInputElement ? inputs.indexOf(target) : -1;\n const pressed = pressedFocused;\n pressedFocused = null;\n if (\n index >= 0 &&\n pressed !== null &&\n pressed === target &&\n !pressed.readOnly &&\n options.context.layout.segments[index]?.type === \"dayPeriod\"\n ) {\n run(\n { type: \"step\", direction: \"up\", size: \"step\" },\n { nativeEvent: event, inputType: null, data: null },\n );\n }\n },\n { signal },\n );\n\n const focusGroup = attachFocusGroup(group, {\n onLeave: (_by, nativeEvent) => {\n leave(nativeEvent);\n },\n isInside: (node) => options.isInside?.(node) === true,\n });\n\n // The free-text box edits the field through the reducer, which applies a\n // one-letter shortcut at once and goes back to the segments when the box\n // is emptied.\n const boxController: TextInputController<V, D> = {\n ...controller,\n input: (edit) => {\n if (edit.input?.isComposing === true || held().entry.kind !== \"text\") {\n controller.input(edit);\n return;\n }\n const before = state;\n const step = segmentReducer(\n before,\n { type: \"textEdit\", text: edit.text, source: edit.source },\n options.context,\n );\n // A shortcut applied at once leaves segments, where the box's caret\n // names no segment.\n report(\n before,\n step,\n step.state.text === edit.text\n ? edit\n : { ...edit, text: step.state.text, input: withoutPlace(edit) },\n );\n place(step.focus);\n render();\n },\n };\n const box = textBox();\n const boxPipeline =\n box === null\n ? null\n : attachTextInput(box, boxController, { focus: \"group\", escape: \"none\" });\n\n const unsubscribe = controller.subscribe(render);\n\n // A segment focused before it was attached (`autofocus`) starts its edit now.\n const focused = activeElement();\n if (focused instanceof HTMLInputElement) {\n const index = segmentInputs().indexOf(focused);\n if (index >= 0) {\n controller.focus(null);\n run({ type: \"focus\", segment: index });\n }\n }\n render();\n\n return {\n setOptions: (next) => {\n options = next;\n render();\n },\n focus: focusSegment,\n getState: () => state,\n detach: () => {\n listeners.abort();\n focusGroup.detach();\n boxPipeline?.detach();\n unsubscribe();\n },\n };\n}\n"],"mappings":";AAOO,IAAM,eAA0C,MAAM;AAC3D,QAAM,aAAa,IAAI,gBAAgB;AACvC,SAAO;AAAA,IACL,QAAQ,WAAW;AAAA,IACnB,OAAO,MAAM;AACX,iBAAW,MAAM;AAAA,IACnB;AAAA,EACF;AACF;;;ACMA,IAAM,iBAAiB,OAAO,cAAc,GAAI;AAezC,SAAS,oBACd,YAAyB,SAAS,MAClC,UAAgC,CAAC,GAClB;AACf,QAAM,SAAS,SAAS,cAAc,KAAK;AAC3C,SAAO,YAAY,QAAQ,aAAa;AACxC,SAAO,aAAa,QAAQ,QAAQ;AACpC,SAAO,aAAa,aAAa,QAAQ;AACzC,YAAU,OAAO,MAAM;AAEvB,MAAI,OAAO;AACX,MAAI,SAAS;AAEb,SAAO;AA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C,GAAG;AAAA,IACH,OAAO,CAAC,SAAS;AACf,UAAI,KAAK,OAAO,gBAAgB,QAAQ,KAAK,EAAE,MAAM,SAAS,QAAQ;AACpE,mBAAW,MAAM,IAAI;AACrB;AAAA,MACF;AACA,YAAM,SAAS;AACf,YAAM,OAAO;AAAA,QACX;AAAA,QACA,EAAE,MAAM,YAAY,MAAM,KAAK,MAAM,QAAQ,KAAK,OAAO;AAAA,QACzD,QAAQ;AAAA,MACV;AAGA;AAAA,QACE;AAAA,QACA;AAAA,QACA,KAAK,MAAM,SAAS,KAAK,OACrB,OACA,EAAE,GAAG,MAAM,MAAM,KAAK,MAAM,MAAM,OAAO,aAAa,IAAI,EAAE;AAAA,MAClE;AACA,YAAM,KAAK,KAAK;AAChB,aAAO;AAAA,IACT;AAAA,EACF;AACA,QAAM,MAAM,QAAQ;AACpB,QAAM,cACJ,QAAQ,OACJ,OACA,gBAAgB,KAAK,eAAe,EAAE,OAAO,SAAS,QAAQ,OAAO,CAAC;AAE5E,QAAM,cAAc,WAAW,UAAU,MAAM;AAG/C,QAAM,UAAU,cAAc;AAC9B,MAAI,mBAAmB,kBAAkB;AACvC,UAAM,QAAQ,cAAc,EAAE,QAAQ,OAAO;AAC7C,QAAI,SAAS,GAAG;AACd,iBAAW,MAAM,IAAI;AACrB,UAAI,EAAE,MAAM,SAAS,SAAS,MAAM,CAAC;AAAA,IACvC;AAAA,EACF;AACA,SAAO;AAEP,SAAO;AAAA,IACL,YAAY,CAAC,SAAS;AACpB,gBAAU;AACV,aAAO;AAAA,IACT;AAAA,IACA,OAAO;AAAA,IACP,UAAU,MAAM;AAAA,IAChB,QAAQ,MAAM;AACZ,gBAAU,MAAM;AAChB,iBAAW,OAAO;AAClB,mBAAa,OAAO;AACpB,kBAAY;AAAA,IACd;AAAA,EACF;AACF;","names":["document","isPrintable","DETACHED","hasFocus","pixels","READY","DETACHED","hasFocus","hasFocus","errorText","box"]}
|