forty-cdk 0.44.0 → 0.45.0
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/accordion/README.md +16 -3
- package/combobox/README.md +15 -4
- package/disclosure/README.md +15 -3
- package/fesm2022/forty-cdk-accordion.mjs +64 -17
- package/fesm2022/forty-cdk-accordion.mjs.map +1 -1
- package/fesm2022/forty-cdk-combobox.mjs +2 -2
- package/fesm2022/forty-cdk-combobox.mjs.map +1 -1
- package/fesm2022/forty-cdk-core.mjs +39 -6
- package/fesm2022/forty-cdk-core.mjs.map +1 -1
- package/fesm2022/forty-cdk-defaults.mjs.map +1 -1
- package/fesm2022/forty-cdk-disclosure.mjs +69 -15
- package/fesm2022/forty-cdk-disclosure.mjs.map +1 -1
- package/fesm2022/forty-cdk-table.mjs +45 -1
- package/fesm2022/forty-cdk-table.mjs.map +1 -1
- package/package.json +1 -1
- package/radio-group/README.md +2 -2
- package/table/README.md +2 -0
- package/toggle/README.md +2 -2
- package/types/forty-cdk-accordion.d.ts +27 -4
- package/types/forty-cdk-combobox.d.ts +6 -6
- package/types/forty-cdk-core.d.ts +16 -1
- package/types/forty-cdk-defaults.d.ts +4 -3
- package/types/forty-cdk-disclosure.d.ts +37 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"forty-cdk-core.mjs","names":["DIGITS","owners"],"sources":["../../../projects/forty-cdk/core/src/accessible-text/accessible-text.ts","../../../projects/forty-cdk/core/src/after-next-render-cancellable/after-next-render-cancellable.ts","../../../projects/forty-cdk/core/src/collection/collection.ts","../../../projects/forty-cdk/core/src/keyboard-navigation/modifier-chord.ts","../../../projects/forty-cdk/core/src/keyboard-navigation/keyboard-navigation.ts","../../../projects/forty-cdk/core/src/collection/enabled-handle-navigation.ts","../../../projects/forty-cdk/core/src/selection/selection.ts","../../../projects/forty-cdk/core/src/errors/errors.ts","../../../projects/forty-cdk/core/src/unset-input/unset-input.ts","../../../projects/forty-cdk/core/src/collection/label-cache.ts","../../../projects/forty-cdk/core/src/id-generator/id-generator.ts","../../../projects/forty-cdk/core/src/host-attributes/host-id.ts","../../../projects/forty-cdk/core/src/collection/register-handle.ts","../../../projects/forty-cdk/core/src/collection/single-slot.ts","../../../projects/forty-cdk/core/src/collection/rooted-registry.ts","../../../projects/forty-cdk/core/src/composed-tree/composed-tree.ts","../../../projects/forty-cdk/core/src/datetime/date-adapter.ts","../../../projects/forty-cdk/core/src/datetime/hour-cycle.ts","../../../projects/forty-cdk/core/src/datetime/locale-digits.ts","../../../projects/forty-cdk/core/src/datetime/segment-editor.ts","../../../projects/forty-cdk/core/src/datetime/field-engine-base.ts","../../../projects/forty-cdk/core/src/datetime/date-segments.ts","../../../projects/forty-cdk/core/src/datetime/serialize.ts","../../../projects/forty-cdk/core/src/datetime/date-field-engine.ts","../../../projects/forty-cdk/core/src/datetime/literal-directive.ts","../../../projects/forty-cdk/core/src/datetime/picker-source-host.ts","../../../projects/forty-cdk/core/src/keyed-flag/keyed-flag.ts","../../../projects/forty-cdk/core/src/roving-tabindex/roving-focus-yield.ts","../../../projects/forty-cdk/core/src/roving-tabindex/roving-tabindex.ts","../../../projects/forty-cdk/core/src/datetime/range-field-composer.ts","../../../projects/forty-cdk/core/src/keyboard-navigation/ime-composition.ts","../../../projects/forty-cdk/core/src/datetime/editable-content.ts","../../../projects/forty-cdk/core/src/datetime/unicode-digit.ts","../../../projects/forty-cdk/core/src/datetime/segment-directive.ts","../../../projects/forty-cdk/core/src/datetime/segmented-field-host.ts","../../../projects/forty-cdk/core/src/datetime/time-segments.ts","../../../projects/forty-cdk/core/src/datetime/time-field-engine.ts","../../../projects/forty-cdk/core/src/datetime/time-value-source.ts","../../../projects/forty-cdk/core/src/defaults/localizable-text.ts","../../../projects/forty-cdk/core/src/drag-session/clamp-preview.ts","../../../projects/forty-cdk/core/src/drag-session/drag-geometry.ts","../../../projects/forty-cdk/core/src/drag-session/drag-announcement-label.ts","../../../projects/forty-cdk/core/src/drag-session/drag-announcer.ts","../../../projects/forty-cdk/core/src/swipe-dismiss/scroll-boundary.ts","../../../projects/forty-cdk/core/src/drag-session/drag-touch-action.ts","../../../projects/forty-cdk/core/src/drag-session/drag-item-hosts.ts","../../../projects/forty-cdk/core/src/text-direction/text-direction.ts","../../../projects/forty-cdk/core/src/drag-session/transform-transition.ts","../../../projects/forty-cdk/core/src/drag-session/drag-preview.ts","../../../projects/forty-cdk/core/src/drag-session/focus-when-mounted.ts","../../../projects/forty-cdk/core/src/drag-session/keyboard-drag-keys.ts","../../../projects/forty-cdk/core/src/drag-session/keyboard-drag-mediator.ts","../../../projects/forty-cdk/core/src/drag-session/lift-arbitration.ts","../../../projects/forty-cdk/core/src/drag-session/pointer-session.ts","../../../projects/forty-cdk/core/src/drag-session/placeholder-slot.ts","../../../projects/forty-cdk/core/src/drag-session/pressed-drag-item.ts","../../../projects/forty-cdk/core/src/drag-session/preview-controller.ts","../../../projects/forty-cdk/core/src/drag-session/window-index-map.ts","../../../projects/forty-cdk/core/src/element-size/element-size.ts","../../../projects/forty-cdk/core/src/errors/orphan-context.ts","../../../projects/forty-cdk/core/src/field/field-anchor.ts","../../../projects/forty-cdk/core/src/host-attributes/described-by-owner.ts","../../../projects/forty-cdk/core/src/host-attributes/replaced-attribute-owner.ts","../../../projects/forty-cdk/core/src/field/field-wiring.ts","../../../projects/forty-cdk/core/src/field/fieldset-context.ts","../../../projects/forty-cdk/core/src/focus-trap/focusable-candidate.ts","../../../projects/forty-cdk/core/src/host-attributes/modal-attributes.ts","../../../projects/forty-cdk/core/src/focus-trap/focus-trap.ts","../../../projects/forty-cdk/core/src/focus-trap/focusable-content.ts","../../../projects/forty-cdk/core/src/focus-trap/return-focus.ts","../../../projects/forty-cdk/core/src/form-ui-control/form-ui-control-base.ts","../../../projects/forty-cdk/core/src/visually-hidden/visually-hidden.ts","../../../projects/forty-cdk/core/src/form-ui-control/hidden-input.ts","../../../projects/forty-cdk/core/src/form-ui-control/native-form-reset.ts","../../../projects/forty-cdk/core/src/host-attributes/disabled-reflection.ts","../../../projects/forty-cdk/core/src/host-attributes/required-reflection.ts","../../../projects/forty-cdk/core/src/form-ui-control/value-mirror.ts","../../../projects/forty-cdk/core/src/form-ui-control/text-value-control-base.ts","../../../projects/forty-cdk/core/src/form-ui-control/touch-timing.ts","../../../projects/forty-cdk/core/src/host-attributes/config-class.ts","../../../projects/forty-cdk/core/src/host-attributes/host-aria.ts","../../../projects/forty-cdk/core/src/host-attributes/host-static-attribute.ts","../../../projects/forty-cdk/core/src/host-attributes/host-type.ts","../../../projects/forty-cdk/core/src/escape-arbiter/escape-arbiter.ts","../../../projects/forty-cdk/core/src/modal-owned-regions/modal-owned-regions.ts","../../../projects/forty-cdk/core/src/live-announcer/live-announcer.ts","../../../projects/forty-cdk/core/src/media-query/media-query.ts","../../../projects/forty-cdk/core/src/numeric-step/numeric-step.ts","../../../projects/forty-cdk/core/src/pausable/visibility-pause.ts","../../../projects/forty-cdk/core/src/pausable/pause-controller.ts","../../../projects/forty-cdk/core/src/pointer/pointer-capability.ts","../../../projects/forty-cdk/core/src/pointer/pointer-focus.ts","../../../projects/forty-cdk/core/src/pointer/pointer-suppression.ts","../../../projects/forty-cdk/core/src/pointer/stationary-pointer-moves.ts","../../../projects/forty-cdk/core/src/pointer/pointer-highlight.ts","../../../projects/forty-cdk/core/src/portal/portal.ts","../../../projects/forty-cdk/core/src/root-context/root-context.ts","../../../projects/forty-cdk/core/src/roving-tabindex/host-roving-context.ts","../../../projects/forty-cdk/core/src/roving-tabindex/roving-focus-restore.ts","../../../projects/forty-cdk/core/src/roving-tabindex/roving-list-navigation.ts","../../../projects/forty-cdk/core/src/selection/range-selection-engine.ts","../../../projects/forty-cdk/core/src/swipe-dismiss/swipe-dismiss.ts","../../../projects/forty-cdk/core/src/swipe-dismiss/swipe-motion.ts","../../../projects/forty-cdk/core/src/synthetic-activation/disabled-click-guard.ts","../../../projects/forty-cdk/core/src/synthetic-activation/synthetic-activation.ts","../../../projects/forty-cdk/core/src/table-registration/table-registration.ts","../../../projects/forty-cdk/core/src/typeahead/match-options.ts","../../../projects/forty-cdk/core/src/typeahead/list-typeahead.ts","../../../projects/forty-cdk/core/src/typeahead/typeahead.ts","../../../projects/forty-cdk/core/src/vetoable-event/vetoable-event.ts","../../../projects/forty-cdk/core/src/virtualized-navigator/virtualized-committed-position.ts","../../../projects/forty-cdk/core/src/virtualized-navigator/virtualized-navigator.ts","../../../projects/forty-cdk/core/src/virtualized-navigator/virtualized-navigator-bridge.ts","../../../projects/forty-cdk/core/src/virtualized-navigator/virtualized-resume.ts"],"sourcesContent":["/**\n * Concatenate the accessible text of a DOM node, excluding any subtree marked\n * `aria-hidden=\"true\"`. Mirrors how assistive technology derives an accessible\n * name from text content: an `aria-hidden` element (a decorative indicator\n * glyph, badge, icon, …) contributes nothing, while visually-hidden but\n * announced content (`hidden` / `display:none` are NOT skipped here) is kept.\n *\n * This is the definition the library itself reasons about: the label a\n * `[forSelectOption]` / `[forComboboxOption]` reports, the text its typeahead\n * matches on, and the name a reorder announcement uses. Read it through this\n * function rather than through `textContent` so a decorative glyph inside an\n * option cannot make the two disagree.\n *\n * The result is returned untrimmed, so apply your own `.trim()` when comparing.\n * SSR-safe: it touches no `document` / `window` and branches on the node's own\n * `nodeType` constants.\n *\n * @param node The DOM node whose accessible text to read (typically an option host).\n * @returns The concatenated text of all non-`aria-hidden` descendant text nodes.\n */\nexport function accessibleTextContent(node: Node): string {\n let text = '';\n node.childNodes.forEach((child) => {\n if (child.nodeType === child.TEXT_NODE) {\n text += child.nodeValue ?? '';\n return;\n }\n if (child.nodeType === child.ELEMENT_NODE) {\n if ((child as Element).getAttribute('aria-hidden') === 'true') {\n return;\n }\n text += accessibleTextContent(child);\n }\n });\n return text;\n}\n","import { afterNextRender, DestroyRef, inject } from '@angular/core';\n\n/**\n * `afterNextRender` whose queued callback is cancelled on destroy. Solves the\n * destroy-before-first-render hazard that both overlay shells\n * (`forty-cdk/core-overlay`'s modal shell, `forty-cdk/core-anchored`'s\n * overlay shell) share: a directive torn down between construction\n * and the next render (synchronous open/close test paths, fast SPA\n * mount+unmount), where the queued render callback\n * would otherwise still activate a global side effect with no hook left to\n * undo it (body inert + scroll lock + a document keydown listener for the\n * modal shell, a permanent topmost dismissible-layer entry for the overlay\n * shell).\n *\n * The helper:\n *\n * 1. Captures the `AfterRenderRef` returned by `afterNextRender` and calls\n * `.destroy()` from the `DestroyRef.onDestroy` hook, so a callback still\n * genuinely pending at teardown (true async path — the render flush comes\n * after destroy) is cancelled and never runs.\n * 2. Sets a `destroyed` flag the wrapper re-checks before invoking `fn`, in\n * case the callback interleaves before `.destroy()` takes effect.\n *\n * Teardown before the render flush therefore never runs `fn`. When the render\n * flushes first, `fn` has run, and undoing its side effect is the adopter's own\n * `DestroyRef.onDestroy` (portal removes the element, the modal shell\n * deactivates inert / scroll lock / focus trap, the overlay shell deactivates\n * its dismissible layer). Either way no global side effect survives teardown.\n *\n * Must be called from an injection context (typically a directive constructor\n * or an `inject`-based helper). SSR-safe: `afterNextRender` never runs on the\n * server, so the callback simply never fires.\n *\n * @param fn The render callback. Runs once after the first render unless the\n * injection context is destroyed before the queued render flushes.\n */\nexport function afterNextRenderCancellable(fn: () => void): void {\n const destroyRef = inject(DestroyRef);\n\n let destroyed = false;\n\n const ref = afterNextRender(() => {\n if (destroyed) return;\n fn();\n });\n\n destroyRef.onDestroy(() => {\n destroyed = true;\n ref.destroy();\n });\n}\n","import { computed, DestroyRef, inject, signal, type Signal } from '@angular/core';\n\n/**\n * Minimal contract every `Collection` entry must satisfy: it carries the DOM\n * node that positions the handle, so the collection can order handles by\n * document position and consumers can correlate a handle with a node\n * (`findByHost`, `indexOfHost`).\n *\n * The node is typed `Node`, not `HTMLElement`, because that is everything the\n * collection reads on it — `isConnected`, `compareDocumentPosition`,\n * `parentNode`, and identity. A handle anchored on a comment node therefore\n * satisfies the contract honestly: a piece declared on an `<ng-container>` or\n * an `<ng-template>` has a comment node for its `ElementRef.nativeElement`, and\n * `forty-cdk/table`'s def registry orders exactly those.\n *\n * A handle whose host is focused, scrolled or measured declares\n * `readonly host: HTMLElement` on its own interface rather than inheriting the\n * assumption from here — `DisableableHandle` and `HostRovingItemHandle` are the\n * shared ones.\n */\nexport interface CollectionHandle {\n readonly host: Node;\n}\n\nfunction sameSequence<T>(a: readonly T[], b: readonly T[]): boolean {\n if (a === b) {\n return true;\n }\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Generic, signal-backed registry of handles for a primitive's children\n * (e.g. tab triggers, radios, listbox options, dialog titles). Items are\n * exposed in **DOM document order**, resolved from each handle's `host` node\n * regardless of the order children registered in.\n *\n * Document order rather than registration order is what keeps `items()` and `indexOfHost` correct\n * under a template that reorders its list at runtime: `@for (…; track id)` moves existing DOM nodes\n * without re-running child constructors, so registration order would freeze and corrupt\n * `aria-posinset` / `aria-setsize` and the keyboard navigation order. An internal\n * `MutationObserver` re-orders the exposed array when nodes move.\n *\n * The observer watches `childList` on every node from each host's direct parent up to the deepest\n * common ancestor of all registered hosts, so a reorder applied at an intermediate wrapper — moving\n * `<li>` elements inside a `<ul>` without touching any host's own parent — is still seen, while a\n * mutation confined to a sibling subtree does not invalidate the collection.\n *\n * Must be constructed in an injection context: it registers `destroy()` with the ambient\n * `DestroyRef`, so the observer is disconnected with the owner even if children never unregister.\n * Call `register` / `unregister` from each child's constructor and `DestroyRef.onDestroy`.\n *\n * Reads are memoized — `items()` returns the same array reference until membership or DOM order\n * changes, and `findByHost` / `indexOfHost` resolve through a companion index instead of scanning.\n */\nexport class Collection<H extends CollectionHandle> {\n readonly #membersSet = new Set<H>();\n readonly #membersEpoch = signal(0);\n readonly #domEpoch = signal(0);\n\n #observer: MutationObserver | null = null;\n readonly #observedNodes = new Set<Node>();\n #destroyed = false;\n #syncScheduled = false;\n\n constructor() {\n inject(DestroyRef).onDestroy(() => this.destroy());\n }\n\n /**\n * All registered handles, in DOM document order.\n *\n * Order is resolved from each handle's `host` via `compareDocumentPosition`\n * and refreshed reactively when membership changes or a node on the hosts'\n * common-ancestor chain reorders its children, so it stays correct under\n * runtime reordering (`@for` sort / drag-reorder), not just under static\n * `@for` / `@if`.\n * Handles whose host is detached (or shares an exact position with another)\n * keep a stable relative order at the end.\n *\n * The contract is type-level: the `readonly H[]` return type is what stops a\n * caller sorting or splicing in place. It is enforced at compile time rather\n * than by freezing the array, because the returned reference is the memoized\n * cache backing this `computed` and freezing it would cost a pass over every\n * recomputation for a guarantee the type already gives. Copy before sorting.\n */\n readonly items: Signal<readonly H[]> = computed(\n () => {\n this.#membersEpoch();\n this.#domEpoch();\n return this.#sortByDomOrder([...this.#membersSet]);\n },\n { equal: sameSequence },\n );\n\n register(handle: H): void {\n if (this.#destroyed || this.#membersSet.has(handle)) {\n return;\n }\n this.#membersSet.add(handle);\n this.#membersEpoch.update((e) => e + 1);\n this.#scheduleSync();\n }\n\n unregister(handle: H): void {\n if (!this.#membersSet.has(handle)) {\n return;\n }\n this.#membersSet.delete(handle);\n this.#membersEpoch.update((e) => e + 1);\n this.#scheduleSync();\n }\n\n /**\n * Position of each registered host in {@link items}, keyed by node.\n *\n * Derived from `items` rather than from the member set so it inherits the\n * `sameSequence` equality — a DOM-epoch bump that resolves to the same order\n * does not rebuild it. It is lazy like any `computed`, so a collection whose\n * consumers never look a host up never pays for the map.\n *\n * Two handles may share a host (a piece composed onto the same element\n * twice); the first in document order wins, matching the `find` /\n * `findIndex` scan this replaced.\n */\n readonly #indexByHost = computed(() => {\n const index = new Map<Node, number>();\n const ordered = this.items();\n for (let i = 0; i < ordered.length; i++) {\n const host = ordered[i]!.host;\n if (!index.has(host)) {\n index.set(host, i);\n }\n }\n return index;\n });\n\n /** Lookup by host node. Returns `undefined` if no handle has that host. */\n findByHost(node: Node): H | undefined {\n const index = this.#indexByHost().get(node);\n return index === undefined ? undefined : this.items()[index];\n }\n\n /** Index in DOM document order, or -1 if not registered. */\n indexOfHost(node: Node): number {\n return this.#indexByHost().get(node) ?? -1;\n }\n\n /**\n * Disconnects the `MutationObserver` and clears membership. Idempotent and\n * safe to call from a `DestroyRef.onDestroy` hook — which the constructor\n * wires automatically. After `destroy()`, further `register` calls are\n * ignored.\n */\n destroy(): void {\n this.#destroyed = true;\n this.#syncScheduled = false;\n this.#observer?.disconnect();\n this.#observer = null;\n this.#observedNodes.clear();\n if (this.#membersSet.size > 0) {\n this.#membersSet.clear();\n this.#membersEpoch.update((e) => e + 1);\n }\n }\n\n #sortByDomOrder(handles: H[]): readonly H[] {\n if (handles.length < 2) {\n return handles;\n }\n const position = new Map<H, number>(handles.map((h, i) => [h, i]));\n const indexOrder = (a: H, b: H): number => position.get(a)! - position.get(b)!;\n return handles.sort((a, b) => {\n if (a.host === b.host) {\n return indexOrder(a, b);\n }\n const aConnected = a.host.isConnected;\n const bConnected = b.host.isConnected;\n if (aConnected !== bConnected) {\n return aConnected ? -1 : 1;\n }\n if (!aConnected) {\n return indexOrder(a, b);\n }\n const rel = a.host.compareDocumentPosition(b.host);\n if ((rel & Node.DOCUMENT_POSITION_FOLLOWING) !== 0) {\n return -1;\n }\n if ((rel & Node.DOCUMENT_POSITION_PRECEDING) !== 0) {\n return 1;\n }\n return indexOrder(a, b);\n });\n }\n\n #scheduleSync(): void {\n if (this.#syncScheduled || this.#destroyed) {\n return;\n }\n this.#syncScheduled = true;\n queueMicrotask(() => {\n this.#syncScheduled = false;\n if (this.#destroyed) {\n return;\n }\n this.#syncObserver();\n });\n }\n\n #syncObserver(): void {\n if (typeof MutationObserver === 'undefined' || this.#destroyed) {\n return;\n }\n const nodes = this.#resolveObservedNodes();\n if (this.#sameNodes(nodes)) {\n return;\n }\n this.#observer ??= new MutationObserver(() => {\n this.#domEpoch.update((e) => e + 1);\n this.#scheduleSync();\n });\n this.#observer.disconnect();\n this.#observedNodes.clear();\n for (const node of nodes) {\n this.#observer.observe(node, { childList: true });\n this.#observedNodes.add(node);\n }\n }\n\n #resolveObservedNodes(): Set<Node> {\n const hosts: Node[] = [];\n for (const member of this.#membersSet) {\n if (member.host.isConnected) {\n hosts.push(member.host);\n }\n }\n const nodes = new Set<Node>();\n if (hosts.length === 0) {\n return nodes;\n }\n if (hosts.length === 1) {\n const parent = hosts[0]!.parentNode;\n if (parent) {\n nodes.add(parent);\n }\n return nodes;\n }\n const commonAncestor = this.#commonAncestor(hosts);\n for (const host of hosts) {\n for (let node: Node | null = host.parentNode; node; node = node.parentNode) {\n nodes.add(node);\n if (node === commonAncestor) {\n break;\n }\n }\n }\n return nodes;\n }\n\n #commonAncestor(hosts: Node[]): Node | null {\n const chain: Node[] = [];\n const chainIndex = new Map<Node, number>();\n for (let node: Node | null = hosts[0]!; node; node = node.parentNode) {\n chainIndex.set(node, chain.length);\n chain.push(node);\n }\n let ancestorIndex = 0;\n for (let i = 1; i < hosts.length; i++) {\n let node: Node | null = hosts[i]!;\n while (node && !chainIndex.has(node)) {\n node = node.parentNode;\n }\n if (!node) {\n return null;\n }\n const index = chainIndex.get(node)!;\n if (index > ancestorIndex) {\n ancestorIndex = index;\n }\n }\n return chain[ancestorIndex]!;\n }\n\n #sameNodes(nodes: Set<Node>): boolean {\n if (nodes.size !== this.#observedNodes.size) {\n return false;\n }\n for (const node of nodes) {\n if (!this.#observedNodes.has(node)) {\n return false;\n }\n }\n return true;\n }\n}\n","export function isHistoryChord(event: KeyboardEvent): boolean {\n return event.altKey || event.metaKey;\n}\n\nexport function isShortcutChord(event: KeyboardEvent): boolean {\n if (event.metaKey) {\n return true;\n }\n if (event.getModifierState?.('AltGraph')) {\n return false;\n }\n if (event.ctrlKey) {\n return true;\n }\n return event.altKey && event.key.length === 1 && event.key.charCodeAt(0) < 0x80;\n}\n","/**\n * Pure helpers that translate keyboard events into navigation intents and\n * compute the resulting index for 1D lists and 2D grids. No DOM access, no\n * DI, no state — primitives compose them inside their own keydown handlers.\n *\n * Pair with `RovingTabindex` to actually move focus.\n */\n\nimport { isHistoryChord } from './modifier-chord';\n\nexport type ListOrientation = 'horizontal' | 'vertical' | 'both' | 'mixed';\nexport type WritingDirection = 'ltr' | 'rtl';\n\nexport type ListNavigationAction = 'next' | 'prev' | 'first' | 'last';\n\nexport interface ListNavigationOptions {\n orientation: ListOrientation;\n /** Reading direction. RTL swaps ArrowLeft/ArrowRight. Default `'ltr'`. */\n dir?: WritingDirection;\n /**\n * When true, PageUp / PageDown map to `first` / `last`. Default `false` —\n * controls that handle paging themselves should keep this off.\n */\n pageKeys?: boolean;\n}\n\n/**\n * Maps a keyboard event to a 1D navigation action, or `null` if the key is\n * not handled by the configured orientation or is held with Alt or Meta, which\n * leaves the browser its history shortcuts. `'both'` and `'mixed'` accept\n * every arrow direction and map each to a linear `next` / `previous` step —\n * `'mixed'` models a visually-wrapped grid as a 1D DOM sequence, so there is no\n * separate row/column keyboard step.\n */\nexport function resolveListNavigation(\n event: KeyboardEvent,\n options: ListNavigationOptions,\n): ListNavigationAction | null {\n if (isHistoryChord(event)) {\n return null;\n }\n const { orientation, dir = 'ltr', pageKeys = false } = options;\n const acceptsBothAxes = orientation === 'both' || orientation === 'mixed';\n const acceptsVertical = orientation === 'vertical' || acceptsBothAxes;\n const acceptsHorizontal = orientation === 'horizontal' || acceptsBothAxes;\n\n switch (event.key) {\n case 'Home':\n return 'first';\n case 'End':\n return 'last';\n case 'PageUp':\n return pageKeys ? 'first' : null;\n case 'PageDown':\n return pageKeys ? 'last' : null;\n case 'ArrowUp':\n return acceptsVertical ? 'prev' : null;\n case 'ArrowDown':\n return acceptsVertical ? 'next' : null;\n case 'ArrowLeft':\n return acceptsHorizontal ? (dir === 'rtl' ? 'next' : 'prev') : null;\n case 'ArrowRight':\n return acceptsHorizontal ? (dir === 'rtl' ? 'prev' : 'next') : null;\n default:\n return null;\n }\n}\n\nexport type GridNavigationAction =\n | 'next'\n | 'prev'\n | 'next-row'\n | 'prev-row'\n | 'first'\n | 'last'\n | 'first-in-row'\n | 'last-in-row'\n | 'page-up'\n | 'page-down';\n\nexport interface GridNavigationOptions {\n /** Number of columns in the grid. Required. */\n cols: number;\n /** Reading direction. RTL swaps ArrowLeft/ArrowRight. Default `'ltr'`. */\n dir?: WritingDirection;\n /**\n * PageUp / PageDown map to `page-up` / `page-down` when true. Default `false`.\n * APG grid semantics move focus by one page of rows while keeping the current\n * column, unlike a 1D list where paging jumps to the ends.\n */\n pageKeys?: boolean;\n}\n\n/**\n * Maps a keyboard event to a 2D grid navigation action.\n *\n * APG: `Ctrl+Home` / `Ctrl+End` jump to the first / last cell of the entire\n * grid, with `Cmd` accepted as the macOS alias for `Ctrl`. Plain `Home` / `End`\n * go to the first / last cell of the current row.\n * `PageUp` / `PageDown` (when `pageKeys` is enabled) page up / down by whole\n * rows while preserving the current column — they do not jump to the grid ends.\n * Any key held with Alt, and an arrow held with Meta, resolve to `null` so the\n * browser keeps its history shortcuts.\n */\nexport function resolveGridNavigation(\n event: KeyboardEvent,\n options: GridNavigationOptions,\n): GridNavigationAction | null {\n if (event.altKey || (isHistoryChord(event) && event.key.startsWith('Arrow'))) {\n return null;\n }\n const { dir = 'ltr', pageKeys = false } = options;\n\n switch (event.key) {\n case 'ArrowUp':\n return 'prev-row';\n case 'ArrowDown':\n return 'next-row';\n case 'ArrowLeft':\n return dir === 'rtl' ? 'next' : 'prev';\n case 'ArrowRight':\n return dir === 'rtl' ? 'prev' : 'next';\n case 'Home':\n return event.ctrlKey || event.metaKey ? 'first' : 'first-in-row';\n case 'End':\n return event.ctrlKey || event.metaKey ? 'last' : 'last-in-row';\n case 'PageUp':\n return pageKeys ? 'page-up' : null;\n case 'PageDown':\n return pageKeys ? 'page-down' : null;\n default:\n return null;\n }\n}\n\nexport interface MoveIndexOptions {\n /** Wrap around at the ends. Default `false`. */\n loop?: boolean;\n /** Predicate to skip indices (e.g. disabled items). */\n isDisabled?: (index: number) => boolean;\n}\n\n/**\n * Computes the resulting index for a 1D navigation action, respecting `loop`\n * and skipping disabled items. Returns `null` when no enabled target exists\n * in the requested direction.\n */\nexport function moveIndex(\n current: number,\n count: number,\n action: ListNavigationAction,\n options: MoveIndexOptions = {},\n): number | null {\n if (count <= 0) {\n return null;\n }\n const { loop = false, isDisabled } = options;\n\n if (action === 'first') {\n return scanFirstEnabled(0, count, 1, isDisabled);\n }\n if (action === 'last') {\n return scanFirstEnabled(count - 1, count, -1, isDisabled);\n }\n\n const step = action === 'next' ? 1 : -1;\n return scanNextEnabled(current, count, step, loop, isDisabled);\n}\n\nexport interface MoveGridIndexOptions extends MoveIndexOptions {\n cols: number;\n /**\n * Number of rows a `page-up` / `page-down` action moves. Required for those\n * actions; ignored otherwise. Values below `1` are treated as `1`.\n */\n pageSize?: number;\n}\n\n/**\n * Computes the resulting index for a 2D grid navigation action.\n *\n * - `next` / `prev`: steps forward / backward by one cell within the current\n * row, skipping disabled cells. The move stops at the row edge and never\n * crosses into an adjacent row; when `loop=true` it wraps to the other end of\n * the same row instead.\n * - `next-row` / `prev-row`: moves to the cell in the same column one row down /\n * up. If that cell is disabled, keeps moving in the same direction one row at\n * a time until an enabled cell is found, so navigation never lands on a\n * disabled cell. The last row may be incomplete; if the column doesn't exist\n * there, falls back to the last filled cell of that row. When `loop=true` the\n * row index wraps top-to-bottom; otherwise the search stops at the grid edge.\n * - `page-up` / `page-down`: moves up / down by `pageSize` rows in the same\n * column, clamped to the first / last row (no loop). If the landing cell is\n * disabled, keeps stepping toward the grid edge one row at a time until an\n * enabled cell is found.\n * - `first` / `last`: first / last enabled cell overall.\n * - `first-in-row` / `last-in-row`: row extremes.\n *\n * Returns `null` when no enabled target exists for the requested action.\n */\nexport function moveGridIndex(\n current: number,\n count: number,\n action: GridNavigationAction,\n options: MoveGridIndexOptions,\n): number | null {\n if (count <= 0 || options.cols <= 0) {\n return null;\n }\n const { cols, loop = false, isDisabled } = options;\n const rowOf = (i: number) => Math.floor(i / cols);\n const colOf = (i: number) => i % cols;\n const totalRows = Math.ceil(count / cols);\n\n switch (action) {\n case 'first':\n return scanFirstEnabled(0, count, 1, isDisabled);\n case 'last':\n return scanFirstEnabled(count - 1, count, -1, isDisabled);\n case 'page-up':\n case 'page-down': {\n const direction = action === 'page-down' ? 1 : -1;\n const pageSize = Math.max(1, Math.floor(options.pageSize ?? 1));\n const col = colOf(current);\n const currentRow = rowOf(current);\n const edgeRow = direction === 1 ? totalRows - 1 : 0;\n let row = currentRow + direction * pageSize;\n row = Math.min(totalRows - 1, Math.max(0, row));\n for (;;) {\n const rowStart = row * cols;\n const rowEnd = Math.min(rowStart + cols, count);\n const target = rowStart + col < rowEnd ? rowStart + col : rowEnd - 1;\n if (target === current) {\n return null;\n }\n if (!isDisabled || !isDisabled(target)) {\n return target;\n }\n if (row === edgeRow) {\n return null;\n }\n row += direction;\n }\n }\n case 'first-in-row': {\n const row = rowOf(current);\n const start = row * cols;\n const end = Math.min(start + cols, count);\n return scanFirstEnabledInRange(start, end, 1, isDisabled);\n }\n case 'last-in-row': {\n const row = rowOf(current);\n const start = row * cols;\n const end = Math.min(start + cols, count);\n return scanFirstEnabledInRange(end - 1, start - 1, -1, isDisabled);\n }\n case 'next':\n case 'prev': {\n const start = rowOf(current) * cols;\n const end = Math.min(start + cols, count);\n const target = scanNextEnabled(\n current - start,\n end - start,\n action === 'next' ? 1 : -1,\n loop,\n isDisabled && ((i) => isDisabled(start + i)),\n );\n return target === null ? null : start + target;\n }\n case 'next-row':\n case 'prev-row': {\n const direction = action === 'next-row' ? 1 : -1;\n const col = colOf(current);\n let row = rowOf(current) + direction;\n for (let visited = 0; visited < totalRows; visited++) {\n if (row < 0 || row >= totalRows) {\n if (!loop) {\n return null;\n }\n row = ((row % totalRows) + totalRows) % totalRows;\n }\n const candidateRowStart = row * cols;\n const candidateRowEnd = Math.min(candidateRowStart + cols, count);\n // Try the same column; if missing in last partial row, fall back to row's last cell.\n const target =\n candidateRowStart + col < candidateRowEnd ? candidateRowStart + col : candidateRowEnd - 1;\n if (target === current) {\n return null;\n }\n if (!isDisabled || !isDisabled(target)) {\n return target;\n }\n row += direction;\n }\n return null;\n }\n default:\n return null;\n }\n}\n\n/** A horizontal-arrow intent to expand or collapse a treegrid parent row. */\nexport type ExpandCollapseAction = 'expand' | 'collapse';\n\n/**\n * Maps a horizontal arrow keydown to an expand/collapse intent for a treegrid,\n * RTL-mirrored: ArrowRight expands (collapses in `rtl`), ArrowLeft collapses\n * (expands in `rtl`). Returns `null` for any other key, and for an arrow held\n * with Alt or Meta. The caller decides whether the intent actually applies (row\n * is an expandable parent in the right open/closed state) and otherwise falls\n * through to grid navigation.\n */\nexport function resolveTreegridExpandCollapse(\n event: KeyboardEvent,\n dir: WritingDirection = 'ltr',\n): ExpandCollapseAction | null {\n if (isHistoryChord(event)) {\n return null;\n }\n if (event.key === 'ArrowRight') {\n return dir === 'rtl' ? 'collapse' : 'expand';\n }\n if (event.key === 'ArrowLeft') {\n return dir === 'rtl' ? 'expand' : 'collapse';\n }\n return null;\n}\n\nexport interface TreeExpandCollapseOptions {\n /** Navigation axis of the tree. */\n orientation: ListOrientation;\n /** Reading direction. RTL swaps ArrowLeft/ArrowRight. Default `'ltr'`. */\n dir?: WritingDirection;\n}\n\n/**\n * Maps an arrow keydown to an expand/collapse intent for a `tree` (APG Tree\n * View), spanning both orientations. In a vertical tree the horizontal arrows\n * drive expansion (RTL-mirrored via {@link resolveTreegridExpandCollapse}); in\n * a horizontal tree ArrowDown expands and ArrowUp collapses. Returns `null` for\n * any other key, and for an arrow held with Alt or Meta. The caller decides\n * whether the intent actually applies (the focused node is an expandable parent\n * in the right open/closed state) and otherwise falls through to list\n * navigation.\n */\nexport function resolveTreeExpandCollapse(\n event: KeyboardEvent,\n options: TreeExpandCollapseOptions,\n): ExpandCollapseAction | null {\n if (isHistoryChord(event)) {\n return null;\n }\n const { orientation, dir = 'ltr' } = options;\n if (orientation === 'vertical') {\n return resolveTreegridExpandCollapse(event, dir);\n }\n if (event.key === 'ArrowDown') {\n return 'expand';\n }\n if (event.key === 'ArrowUp') {\n return 'collapse';\n }\n return null;\n}\n\nfunction scanFirstEnabled(\n start: number,\n count: number,\n step: number,\n isDisabled: ((i: number) => boolean) | undefined,\n): number | null {\n for (let i = start; i >= 0 && i < count; i += step) {\n if (!isDisabled || !isDisabled(i)) {\n return i;\n }\n }\n return null;\n}\n\nfunction scanFirstEnabledInRange(\n start: number,\n end: number,\n step: number,\n isDisabled: ((i: number) => boolean) | undefined,\n): number | null {\n for (let i = start; step > 0 ? i < end : i > end; i += step) {\n if (!isDisabled || !isDisabled(i)) {\n return i;\n }\n }\n return null;\n}\n\nfunction scanNextEnabled(\n current: number,\n count: number,\n step: number,\n loop: boolean,\n isDisabled: ((i: number) => boolean) | undefined,\n): number | null {\n if (loop && current < 0 && step < 0) {\n current = count;\n }\n for (let visited = 1; visited <= count; visited++) {\n let candidate = current + step * visited;\n if (candidate < 0 || candidate >= count) {\n if (!loop) {\n return null;\n }\n candidate = ((candidate % count) + count) % count;\n }\n if (candidate === current) {\n return null;\n }\n if (!isDisabled || !isDisabled(candidate)) {\n return candidate;\n }\n }\n return null;\n}\n","import type { Signal } from '@angular/core';\n\nimport { type ListNavigationAction, moveIndex } from '../keyboard-navigation/keyboard-navigation';\nimport type { CollectionHandle } from './collection';\n\n/**\n * Collection handle that also exposes a `disabled` signal. Required input\n * shape for {@link firstEnabledHandle}, {@link lastEnabledHandle} and\n * {@link nextEnabledHandle}.\n */\nexport interface DisableableHandle extends CollectionHandle {\n /**\n * Narrowed from {@link CollectionHandle}'s `Node`: the navigators here hand\n * the host back to callers that focus it and compare it against\n * `document.activeElement`, so a disableable handle owes an element.\n */\n readonly host: HTMLElement;\n readonly disabled: Signal<boolean>;\n}\n\n/**\n * Returns the first non-disabled handle in `items`, or `null` if every handle\n * is disabled (or the list is empty). Iteration follows the order of the input\n * array — pass `Collection.items()` to get DOM document order.\n *\n * Callers that only need the element take {@link firstEnabledHost}; this one is\n * for the callers that act on the handle itself (the menu item list arms the\n * item's one-shot highlight suppression before focusing it).\n */\nexport function firstEnabledHandle<H extends DisableableHandle>(items: readonly H[]): H | null {\n for (const item of items) {\n if (!item.disabled()) {\n return item;\n }\n }\n return null;\n}\n\n/**\n * Returns the last non-disabled handle in `items`, or `null` if every handle is\n * disabled (or the list is empty). The reverse twin of\n * {@link firstEnabledHandle}, scanning from the end of the input array.\n */\nexport function lastEnabledHandle<H extends DisableableHandle>(items: readonly H[]): H | null {\n for (let i = items.length - 1; i >= 0; i--) {\n const item = items[i];\n if (item && !item.disabled()) {\n return item;\n }\n }\n return null;\n}\n\n/**\n * Returns the host element of the first non-disabled handle in `items`, or\n * `null` if every handle is disabled (or the list is empty). Iteration\n * follows the order of the input array — pass `Collection.items()` to get\n * DOM document order.\n *\n * Used by primitives that pick a roving-tabindex entry point: when there's\n * no selection, the first enabled child becomes the tab stop.\n */\nexport function firstEnabledHost<H extends DisableableHandle>(\n items: readonly H[],\n): HTMLElement | null {\n return firstEnabledHandle(items)?.host ?? null;\n}\n\n/**\n * Returns the host element of the last non-disabled handle in `items`, or\n * `null` if every handle is disabled (or the list is empty). The reverse twin\n * of {@link firstEnabledHost}, for the overlays whose End / `'last'` initial\n * focus lands on the bottom of the collection.\n */\nexport function lastEnabledHost<H extends DisableableHandle>(\n items: readonly H[],\n): HTMLElement | null {\n return lastEnabledHandle(items)?.host ?? null;\n}\n\n/** Options for {@link nextEnabledHandle}. */\nexport interface NextEnabledHandleOptions {\n /** Wrap around at the ends. Default `false`. */\n loop?: boolean;\n}\n\n/**\n * Resolves the handle a 1D list-navigation action lands on, skipping disabled\n * items. Generalizes the \"find the current index → `moveIndex` → bail →\n * resolve the handle\" walk that every roving / activedescendant list navigator\n * repeats verbatim, so each caller keeps only its own focus-vs-activedescendant\n * tail.\n *\n * `current` may be the currently focused/active host element or an explicit\n * index. When a host is passed it is located via its `host` property; a host\n * not present in `items` is treated as index `0` (navigation starts from the\n * top), matching the `currentIndex < 0 ? 0 : currentIndex` clamp the call\n * sites used. When an index is passed it is used verbatim (no clamp), so\n * callers that compute the index themselves — e.g. an activedescendant lookup\n * by id, or a value-based lookup — keep full control, including a deliberate\n * `-1` for \"nothing active yet\".\n *\n * Returns the resolved handle, or `null` when the list is empty or no enabled\n * target exists in the requested direction.\n */\nexport function nextEnabledHandle<H extends DisableableHandle>(\n items: readonly H[],\n current: HTMLElement | number,\n action: ListNavigationAction,\n options: NextEnabledHandleOptions = {},\n): H | null {\n if (items.length === 0) {\n return null;\n }\n let currentIndex: number;\n if (typeof current === 'number') {\n currentIndex = current;\n } else {\n const found = items.findIndex((item) => item.host === current);\n currentIndex = found < 0 ? 0 : found;\n }\n const next = moveIndex(currentIndex, items.length, action, {\n loop: options.loop ?? false,\n isDisabled: (i) => items[i]!.disabled(),\n });\n return next === null ? null : (items[next] ?? null);\n}\n","import { computed, type Signal } from '@angular/core';\n\n/**\n * Pure helpers backing the array-modeled selection contract of `Select`,\n * `Listbox`, and `Combobox` — the form-value selection primitives whose value\n * is a generic `readonly T[]` with equality-aware membership. They encode the\n * shape those three share: equality-aware membership, an immutable\n * multi-toggle, the default form-value serializer, and the single-mode derived\n * view. No DOM access, no DI, no state — those primitives compose them inside\n * their own selection logic, and the shared definition keeps a fix from\n * drifting across the three copies.\n *\n * Scope note: these helpers are NOT a universal selection contract. `ForTree`\n * composes the two membership helpers but keeps its own select / expand /\n * extend-by-arrow logic. `Accordion` and `ToggleGroup` manage their arrays\n * directly, because their value semantics (string keys, no equality comparator,\n * no single-mode `T | null` view) differ.\n */\n\nexport const defaultCompareWith = <T>(a: T, b: T): boolean => a === b;\n\nexport function membership<T>(\n values: readonly T[],\n equals: (a: T, b: T) => boolean,\n): (value: T) => boolean {\n if (equals === defaultCompareWith) {\n const hashed = new Set(values);\n return (value) => hashed.has(value);\n }\n return (value) => values.some((candidate) => equals(candidate, value));\n}\n\nexport function selectionMembership<T>(\n value: Signal<readonly T[]>,\n compareWith: Signal<(a: T, b: T) => boolean>,\n): Signal<(value: T) => boolean> {\n return computed(() => membership(value(), compareWith()));\n}\n\nexport function lookupByValue<E, T>(\n entries: readonly E[],\n valueOf: (entry: E) => T,\n equals: (a: T, b: T) => boolean,\n): (value: T) => E | undefined {\n if (equals === defaultCompareWith) {\n const byValue = new Map<T, E>();\n for (const entry of entries) {\n const value = valueOf(entry);\n if (!byValue.has(value)) {\n byValue.set(value, entry);\n }\n }\n return (value) => byValue.get(value);\n }\n return (value) => entries.find((entry) => equals(valueOf(entry), value));\n}\n\nexport function appendMissing<T>(\n current: readonly T[],\n added: readonly T[],\n equals: (a: T, b: T) => boolean,\n): T[] {\n const next = [...current];\n if (equals === defaultCompareWith) {\n const seen = new Set(current);\n for (const value of added) {\n if (!seen.has(value)) {\n seen.add(value);\n next.push(value);\n }\n }\n return next;\n }\n for (const value of added) {\n if (!next.some((candidate) => equals(candidate, value))) {\n next.push(value);\n }\n }\n return next;\n}\n\nexport function dedupeValues<T>(values: readonly T[], equals: (a: T, b: T) => boolean): T[] {\n return appendMissing([], values, equals);\n}\n\n/**\n * Returns `true` when `current` contains an element equal to `v` under the\n * supplied `equals` comparator. Backs each primitive's `isSelected(v)`.\n */\nexport function isInArray<T>(\n current: readonly T[],\n v: T,\n equals: (a: T, b: T) => boolean,\n): boolean {\n return current.some((x) => equals(x, v));\n}\n\n/**\n * Immutable multi-select toggle: returns a new array with `v` removed when an\n * equal element is already present, otherwise appended. Never mutates\n * `current`, so the result is safe to `set()` straight into a\n * `model<readonly T[]>`. Backs the multi-mode branch of each primitive's\n * `activate()`.\n */\nexport function toggleInArray<T>(\n current: readonly T[],\n v: T,\n equals: (a: T, b: T) => boolean,\n): T[] {\n return current.some((x) => equals(x, v)) ? current.filter((x) => !equals(x, v)) : [...current, v];\n}\n\n/**\n * Default `itemToFormValue` serializer for the hidden input that participates\n * in native form submission: identity for strings, `JSON.stringify` for any\n * other item so the primitive round-trips objects out of the box. Consumers\n * override per primitive when the backend expects a specific wire format.\n */\nexport function defaultItemToFormValue<T>(item: T): string {\n return typeof item === 'string' ? item : JSON.stringify(item);\n}\n\n/**\n * Builds the read-only single-select convenience view derived from an\n * array-backed value signal. Returns the sole element when exactly one is\n * selected (regardless of `multiple`), otherwise `null` (zero, or 2+\n * selected). A pure `computed()` — the array model stays the source of truth.\n * Backs `ForSelect.selected` / `ForListbox.selected` and\n * `ForCombobox.selectedItem`.\n */\nexport function singleSelected<T>(value: Signal<readonly T[]>): Signal<T | null> {\n return computed<T | null>(() => {\n const values = value();\n return values.length === 1 ? values[0]! : null;\n });\n}\n","const CODE_PREFIX = 'FORCDK-';\n\n/**\n * The four pieces every developer-facing message in the library is built from.\n *\n * `code` is the stable identity; `scope` only ever differs from the area the\n * code carries when a shared helper reports on behalf of a primitive it\n * resolves at runtime.\n */\nexport interface FortyMessageSpec {\n /**\n * Stable `FORCDK-<AREA>-<NNN>` identifier. Never reused for a second meaning:\n * a code names one concrete failure for as long as that failure exists.\n */\n readonly code: string;\n /** What is wrong, in one sentence, in the consumer's vocabulary. */\n readonly message: string;\n /** Why it happens — omitted when the message already says it. */\n readonly cause?: string;\n /** The concrete action that resolves it — omitted when there is no single action. */\n readonly fix?: string;\n /**\n * Entry-point name for the `[forty-cdk/<scope>]` prefix. Derived from\n * `code`'s area when omitted, which is what every call site outside\n * `forty-cdk/core` wants.\n */\n readonly scope?: string;\n}\n\n/** The entry-point name a code's area spells, e.g. `FORCDK-DATE-PICKER-001` → `date-picker`. */\nfunction scopeOf(code: string): string {\n const end = code.lastIndexOf('-');\n if (!code.startsWith(CODE_PREFIX) || end <= CODE_PREFIX.length) {\n return 'core';\n }\n return code.slice(CODE_PREFIX.length, end).toLowerCase();\n}\n\n/**\n * Renders a {@link FortyMessageSpec} into the library's one message layout:\n *\n * ```text\n * [forty-cdk/dialog] FORCDK-DIALOG-001: ForDialogTitle must be used inside a [forDialog] element.\n *\n * Cause: No FOR_DIALOG_CONTEXT provider is visible from ForDialogTitle.\n *\n * Fix: Move ForDialogTitle inside a [forDialog] element.\n * ```\n *\n * The first line is self-sufficient — prefix, code and what went wrong — so a\n * consumer skimming a stack trace, and a search for the code, both land on it.\n * `Cause` and `Fix` are appended only when supplied.\n *\n * The layout {@link fortyError}, {@link fortyWarn} and the shape helpers in\n * `orphan-context.ts` all build on. Module-local to `forty-cdk/core`: no\n * caller outside this entry point formats a message itself.\n */\nexport function formatFortyMessage(spec: FortyMessageSpec): string {\n const scope = spec.scope ?? scopeOf(spec.code);\n let out = `[forty-cdk/${scope}] ${spec.code}: ${spec.message}`;\n if (spec.cause) {\n out += `\\n\\nCause: ${spec.cause}`;\n }\n if (spec.fix) {\n out += `\\n\\nFix: ${spec.fix}`;\n }\n return out;\n}\n\n/**\n * Builds the `Error` a primitive throws for a developer mistake. Call sites\n * keep the `throw` so the control flow stays visible to a reader and to\n * TypeScript's reachability analysis:\n *\n * ```ts\n * throw fortyError({ code: 'FORCDK-DRAWER-004', message: '…', fix: '…' });\n * ```\n *\n * This helper does **not** gate on dev mode. Whether a given check is\n * dev-only is a property of the check, not of the formatting — an orphan\n * context would fail with a bare `TypeError` one line later in production, so\n * those throw unconditionally, while a pure assertion gates inside its own\n * `assert*` / `throw*` helper as `.claude/rules/conventions.md` requires.\n */\nexport function fortyError(spec: FortyMessageSpec): Error {\n return new Error(formatFortyMessage(spec));\n}\n\n/**\n * Reports a developer mistake the library can recover from, in the same layout\n * as {@link fortyError}. Dev mode only — a warning's whole audience is the\n * developer, so the gate travels with the report and no call site can forget it.\n */\nexport function fortyWarn(spec: FortyMessageSpec): void {\n if (typeof ngDevMode !== 'undefined' && !ngDevMode) {\n return;\n }\n console.warn(formatFortyMessage(spec));\n}\n","import { effect, type Signal } from '@angular/core';\nimport { fortyError } from '../errors/errors';\n\nconst UNSET: unique symbol = Symbol('forty-cdk:unset-input');\n\n/**\n * The type of the {@link unsetInput} sentinel. A signal typed `T | Unset`\n * belongs to a piece whose binding may not be written yet; narrow it with\n * {@link isUnset} before the value is used as a `T`.\n */\nexport type Unset = typeof UNSET;\n\n/**\n * The sentinel a piece seeds an otherwise-required input with, typed\n * `T | Unset` so every read site has to narrow with {@link isUnset} before it\n * uses the value.\n *\n * A piece registers with its parent during the content view's *creation* pass\n * and has its binding written in that view's *update* pass, so any parent\n * lookup running in between reads a value the consumer has not supplied yet.\n * `input.required` answers that read by throwing, which forced every such\n * lookup through a `try` / `catch` keyed on an Angular error code; seeding a\n * plain `input()` with this sentinel answers it with a value instead, and the\n * lookup becomes an identity comparison ({@link isUnset}).\n *\n * The sentinel is a module-private `symbol`, so it can never collide with a\n * consumer value — which `undefined` can, on the roots generic over an\n * unconstrained `T`. Never let the sentinel reach a consumer callback\n * (`compareWith`, `itemToLabel`, …): guard with {@link isUnset} before the\n * value leaves the read site.\n *\n * The read is still tracked — Angular's input signal registers itself as a\n * producer before it resolves a value — so the binding's write marks the\n * reader dirty and the piece folds in on the run that follows.\n *\n * @example\n * ```ts\n * readonly value: InputSignal<T | Unset> = input(unsetInput<T>());\n * ```\n */\nexport function unsetInput<T>(): T | Unset {\n return UNSET;\n}\n\n/**\n * Whether `value` is the {@link unsetInput} sentinel — i.e. the piece's binding\n * has not been written yet. Compare before the value leaves the read site; a\n * `false` result means the value is a genuine `T`, including `null`,\n * `undefined`, or any other value a consumer's domain may contain.\n */\nexport function isUnset(value: unknown): value is Unset {\n return value === UNSET;\n}\n\n/** A handle paired with the value read from it, known not to be {@link Unset}. */\nexport interface BoundEntry<H, T> {\n readonly handle: H;\n readonly value: T;\n}\n\n/**\n * The handles whose binding is written, each paired with the value that was\n * read to decide it. A fold downstream of the filter reads `entry.value` as a\n * `T` instead of calling the signal again, which the compiler cannot narrow.\n */\nexport function boundEntries<H, T>(\n handles: readonly H[],\n valueOf: (handle: H) => T | Unset,\n): BoundEntry<H, T>[] {\n const entries: BoundEntry<H, T>[] = [];\n for (const handle of handles) {\n const value = valueOf(handle);\n if (!isUnset(value)) {\n entries.push({ handle, value });\n }\n }\n return entries;\n}\n\n/**\n * Dev-mode guard that a piece seeded with {@link unsetInput} actually had its\n * binding written. Call it from the piece's constructor.\n *\n * Seeding the sentinel makes the input optional to Angular's template type\n * checker, so a consumer who omits the binding no longer gets a compile-time\n * error — and, because every parent lookup now skips an unset piece instead of\n * throwing, the piece would otherwise stay silently invisible to its parent.\n * This restores the loud failure, in the library's own vocabulary and naming\n * both the piece and the input.\n *\n * The check runs in an `effect`, which is the first point at which the update\n * pass has written the binding, and only in dev mode — a production build\n * creates no reactive node per piece.\n *\n * @param value The piece's input signal.\n * @param primitive Entry-point name for the error prefix, e.g. `'listbox'`.\n * @param piece Selector of the piece the error names, e.g. `'[forListboxOption]'`.\n * @param inputName Name of the unbound input, e.g. `'value'`.\n */\nexport function assertInputBound<T>(\n value: Signal<T>,\n primitive: string,\n piece: string,\n inputName: string,\n): void {\n if (typeof ngDevMode !== 'undefined' && !ngDevMode) {\n return;\n }\n effect(() => {\n if (isUnset(value())) {\n throw fortyError({\n code: 'FORCDK-CORE-010',\n scope: primitive,\n message: `${piece} has no [${inputName}] binding.`,\n cause:\n 'The input is declared optional so the parent can skip a piece whose binding is not ' +\n 'written yet, which means a permanently unbound piece never joins its parent instead ' +\n 'of failing to compile.',\n fix: `Bind [${inputName}] on every ${piece}.`,\n });\n }\n });\n}\n","import { computed, linkedSignal, type Signal } from '@angular/core';\n\nimport { lookupByValue } from '../selection/selection';\nimport { isUnset, type Unset } from '../unset-input/unset-input';\n\n/**\n * Minimal option-handle shape a {@link LabelCache} reads. Every member is a\n * `Signal` so the cache never peeks at `textContent` — a handle carrying extra\n * members (`posInSet`, `host`, …) satisfies it structurally.\n */\nexport interface LabelCacheHandle<T> {\n /** Stable host `id` — the activedescendant target in the virtualized path. */\n readonly id: Signal<string>;\n /** The option's underlying value, or {@link Unset} before its binding is written. */\n readonly value: Signal<T | Unset>;\n /** The option's resolved display label. */\n readonly label: Signal<string>;\n /** The option's typeahead override, `''` when unset. Absent on a handle that never carries one. */\n readonly textValue?: Signal<string>;\n /** Whether the option is disabled. */\n readonly disabled: Signal<boolean>;\n}\n\n/**\n * One cached option tuple. The superset both consumers need: the stable id\n * (activedescendant / off-window resolution), the underlying value, the resolved\n * label string, and the `disabled` flag so inline autocomplete can skip disabled\n * options that are no longer rendered.\n */\nexport interface LabelCacheEntry<T> {\n readonly id: string;\n readonly value: T;\n readonly label: string;\n /** The handle's typeahead override when it carries one, so a closed-state matcher can prefer it. */\n readonly textValue?: string;\n readonly disabled: boolean;\n}\n\n/** Tracked source of the window store: the live handles and the key fn. */\ninterface WindowSource<T> {\n readonly items: readonly LabelCacheHandle<T>[];\n readonly toFormValue: (item: T) => string;\n}\n\n/** Tracked source of the selection store: the window store, the selection, and the comparator. */\ninterface SelectionSource<T> {\n readonly window: readonly LabelCacheEntry<T>[];\n readonly value: readonly T[];\n readonly compareWith: (a: T, b: T) => boolean;\n}\n\n/**\n * Dependencies of a {@link LabelCache}. Plain signals — the cache never injects\n * a primitive's context token, so both roots construct it from their own\n * registries.\n */\nexport interface LabelCacheDeps<T> {\n /** Live registered option handles. The same signal the root exposes. */\n readonly items: Signal<readonly LabelCacheHandle<T>[]>;\n /** The root's selection model, so selected labels survive an unmount. */\n readonly value: Signal<readonly T[]>;\n /** Serializes an item to the key the window store is de-duplicated by. */\n readonly itemToFormValue: Signal<(item: T) => string>;\n /** The root's equality comparator, which matches a selected value to its cached entry. */\n readonly compareWith: Signal<(a: T, b: T) => boolean>;\n}\n\nconst EMPTY_WINDOW = new Map<string, LabelCacheEntry<never>>();\n\n/**\n * Bounded option-label cache shared by `[forSelect]` and `[forCombobox]`. Both roots must resolve\n * labels for options that are not mounted, since the live registry is empty whenever the consumer's\n * `@if` unmounts the listbox, and neither may retain every option it has ever seen.\n *\n * Two projections, each bounded by a different quantity:\n *\n * - {@link selectedEntries} carries the currently selected values, so the select value, the\n * combobox chips and the combobox input label keep resolving after the options unmount. A value\n * that leaves the selection leaves the cache with it.\n * - {@link windowEntries} carries the most recent non-empty option window, replaced rather than\n * merged, and backs the closed-state typeahead and inline completion matchers. Because it is\n * replaced, an option removed while the listbox was open is gone from the next window.\n *\n * They are separate `linkedSignal`s so a commit of `value` rebuilds the selection map alone instead\n * of re-reading every handle in the window.\n *\n * Replacing rather than merging bounds the window to the rendered slice, so a virtualized\n * closed-state match only sees the last window. Neither projection consults a virtualized position\n * map: a value entering the selection while its option sits outside the current window resolves\n * only if an earlier window cached it, and the caller owns that fallback.\n *\n * Constructed once per root. Never surfaced on a primitive's public context.\n */\nexport class LabelCache<T> {\n readonly #windowByKey: Signal<ReadonlyMap<string, LabelCacheEntry<T>>>;\n\n readonly #selectedEntries: Signal<readonly LabelCacheEntry<T>[]>;\n\n readonly #windowEntries: Signal<readonly LabelCacheEntry<T>[]>;\n\n constructor(deps: LabelCacheDeps<T>) {\n this.#windowByKey = linkedSignal<WindowSource<T>, ReadonlyMap<string, LabelCacheEntry<T>>>({\n source: () => ({ items: deps.items(), toFormValue: deps.itemToFormValue() }),\n computation: ({ items, toFormValue }, prev) =>\n items.length === 0 ? (prev?.value ?? EMPTY_WINDOW) : readWindow(items, toFormValue),\n });\n this.#windowEntries = computed(() => [...this.#windowByKey().values()]);\n this.#selectedEntries = linkedSignal<SelectionSource<T>, readonly LabelCacheEntry<T>[]>({\n source: () => ({\n window: this.#windowEntries(),\n value: deps.value(),\n compareWith: deps.compareWith(),\n }),\n computation: ({ window, value, compareWith }, prev) => {\n const inWindow = lookupByValue(window, (entry) => entry.value, compareWith);\n const carried = lookupByValue(prev?.value ?? [], (entry) => entry.value, compareWith);\n const selected: LabelCacheEntry<T>[] = [];\n for (const item of value) {\n const entry = inWindow(item) ?? carried(item);\n if (entry !== undefined) {\n selected.push(entry);\n }\n }\n return selected;\n },\n });\n }\n\n /**\n * Pull both stores so they observe the mounted options. Called from a\n * dedicated read-only effect on the root, never from one that also writes:\n * pulling the cache tracks the selection, and an effect that writes\n * activedescendant must not re-run on every commit of `value`.\n *\n * This read is the one thing the cache cannot derive for itself: the option\n * window is transient, and a lazy computation only ever sees the source as it\n * stands when something reads it. `selectedEntries` is pulled naturally — by\n * whatever renders the selected label — but the window store has no such\n * reader during the open cycle, so a consumer who renders no selected label\n * (or none yet) would leave it empty and the closed-state matchers with\n * nothing to match against. The selection store is pulled here too so its\n * carried-over entries are captured while the option that owns each selected\n * value is still in the window. A read, not a write: forcing a lazy derivation\n * to run is a side effect, not state propagation.\n */\n prime(): void {\n this.#windowByKey();\n this.#selectedEntries();\n }\n\n /**\n * Cached entries for the currently selected values, in selection order. A\n * selected value with no cached entry is absent rather than represented — the\n * caller owns the fallback (a consumer `itemToLabel`, else the serialized\n * value).\n */\n selectedEntries(): readonly LabelCacheEntry<T>[] {\n return this.#selectedEntries();\n }\n\n /**\n * The most recent non-empty option window, in DOM order and de-duplicated by\n * serialized form value. Drives the closed-state matchers; empty until the\n * first window is observed.\n */\n windowEntries(): readonly LabelCacheEntry<T>[] {\n return this.#windowEntries();\n }\n}\n\nfunction readWindow<T>(\n items: readonly LabelCacheHandle<T>[],\n toFormValue: (item: T) => string,\n): ReadonlyMap<string, LabelCacheEntry<T>> {\n const byKey = new Map<string, LabelCacheEntry<T>>();\n for (const item of items) {\n const id = item.id();\n const value = item.value();\n if (isUnset(value)) {\n continue;\n }\n byKey.set(toFormValue(value), {\n id,\n value,\n label: item.label(),\n textValue: item.textValue?.(),\n disabled: item.disabled(),\n });\n }\n return byKey;\n}\n","import { Injectable, inject } from '@angular/core';\n\nimport { FOR_ID_SALT } from 'forty-cdk/id-salt';\n\nimport { fortyError } from '../errors/errors';\n\n/**\n * Generates unique string IDs scoped to the application instance.\n *\n * Backs the `aria-controls` / `aria-labelledby` wiring between a primitive's pieces. Ids are stable\n * for the lifetime of the instance that minted them.\n *\n * Scoped to the application injector, so each bootstrap — and each SSR request — starts a fresh\n * counter. Ids are salted with {@link FOR_ID_SALT}, defaulting to `APP_ID`, so a server and client\n * render of the same order produce identical strings.\n *\n * Because the counter is monotonic, that agreement is a property of the render order rather than of\n * any single id. Ordinary hydration replays the server's order; incremental hydration does not, so\n * an id minted by a deferred root for a piece that is still dehydrated can keep a drifted value.\n * Keeping a primitive's pieces in one hydration unit avoids it, and is documented for consumers\n * under \"Incremental hydration\" in the `forty-cdk/shared` README.\n *\n * Mounting several apps on one page requires a distinct salt per app via `provideForIdSalt`,\n * or they emit colliding ids.\n */\n@Injectable({ providedIn: 'root' })\nexport class IdGenerator {\n readonly #salt = inject(FOR_ID_SALT);\n #counter = 0;\n\n /**\n * Returns a fresh, unique ID with the given prefix. In dev mode, throws when the salt contains\n * whitespace.\n *\n * @param prefix Optional prefix for the generated ID. Defaults to `for`.\n */\n next(prefix = 'for'): string {\n assertIdSalt(this.#salt);\n return `${prefix}-${this.#salt}-${++this.#counter}`;\n }\n}\n\nfunction assertIdSalt(salt: string): void {\n if ((typeof ngDevMode === 'undefined' || ngDevMode) && /\\s/.test(salt)) {\n throw fortyError({\n code: 'FORCDK-CORE-012',\n message: `The id salt \"${salt}\" contains whitespace.`,\n cause:\n 'Generated ids are referenced from aria-labelledby, aria-controls and aria-describedby, ' +\n 'which are space-separated id lists, so an id with a space in it resolves to two ids ' +\n 'that do not exist.',\n fix: 'Pass provideForIdSalt() (or FOR_ID_SALT) a salt without whitespace, e.g. \"admin-panel\".',\n });\n }\n}\n","import { ElementRef, inject, signal, type Signal, type WritableSignal } from '@angular/core';\n\nimport { IdGenerator } from '../id-generator/id-generator';\n\n/**\n * Resolves the id a piece should expose: the host element's pre-existing\n * **static** `id` when present, else a freshly generated `<prefix>-*` id.\n *\n * The generated id is always produced (advancing the {@link IdGenerator}\n * counter) even when a host id is adopted, so the per-app id sequence stays\n * deterministic across renders regardless of which hosts carry a consumer id —\n * a server and client render of the same template adopt identically, so\n * hydration still agrees.\n *\n * Only **static** ids (written in the template, present on the element at\n * directive construction) are visible here. A consumer `[id]=\"expr\"` property\n * binding evaluates after construction, so it is not adopted — and still\n * fights the `[id]` host binding.\n *\n * Must be invoked in an injection context.\n *\n * @param host The directive's host element, or `null` to always generate (e.g.\n * when the owning helper resolved `ElementRef` optionally and found none).\n * @param prefix Prefix for the generated fallback id.\n */\nexport function resolveHostId(host: HTMLElement | null, prefix: string): string {\n const generated = inject(IdGenerator).next(prefix);\n return host?.getAttribute('id') || generated;\n}\n\n/**\n * Adopt a host element's pre-existing **static** `id` into `idSignal`. A no-op\n * when the host has no `id`, leaving the signal's generated fallback in place.\n *\n * The canonical shape for the \"context-owned id\" pieces (overlay\n * trigger / content, form-field control): the owning root seeds `idSignal`\n * with a generated id at construction, then calls this from its\n * `register…(el)` method so a consumer-set `id` on the registered host is\n * preserved and re-emitted by the `[id]` host binding — external references\n * (anchors, `aria-labelledby`, label `for`, test hooks) keep resolving.\n *\n * Only **static** ids are adopted; see {@link resolveHostId} for the\n * static-only boundary.\n *\n * @param host The element whose static `id` should be adopted.\n * @param idSignal The writable id signal to adopt into.\n */\nexport function adoptHostId(host: HTMLElement, idSignal: WritableSignal<string>): void {\n const existing = host.getAttribute('id');\n if (existing) {\n idSignal.set(existing);\n }\n}\n\nexport function staticHostId(host: HTMLElement): string | null {\n return host.getAttribute('id') || null;\n}\n\n/**\n * Convenience for the \"piece owns its own id\" pieces: seeds a read-only id\n * signal from the host element's pre-existing static `id`, falling back to a\n * freshly generated `<prefix>-*` id.\n *\n * The piece's `[id]` host binding therefore re-emits a consumer-set static id\n * instead of clobbering it. Must be invoked in an injection context.\n *\n * @param prefix Prefix for the generated fallback id.\n */\nexport function hostId(prefix: string): Signal<string> {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n return signal(resolveHostId(host, prefix)).asReadonly();\n}\n","import { afterNextRender, DestroyRef, ElementRef, inject } from '@angular/core';\n\nimport { resolveHostId } from '../host-attributes/host-id';\n\n/**\n * Scheduling for the `register` call.\n *\n * - `'sync'` (default) — register inside the directive's constructor, at\n * directive-construction time. Matches what most callsites do today.\n * - `'afterNextRender'` — defer the `register` call to `afterNextRender`, so the parent's lookups\n * can read the handle's mandatory signals without hitting an unbound `input.required`.\n *\n * The hook never fires in a server render, so a deferred registration is invisible to SSR. Prefer\n * `'sync'` with `unsetInput` seeding and an `isUnset`-guarded lookup whenever the registration\n * drives markup the pre-hydration DOM needs; `'afterNextRender'` is only safe for a piece that\n * emits no registration-derived markup.\n *\n * `unregister` always runs eagerly via `DestroyRef.onDestroy`, so destroy-before-register is a safe\n * no-op as long as it is reference-based.\n */\nexport type RegistrationScheduling = 'sync' | 'afterNextRender';\n\n/**\n * Registers `target` with an owning parent on construction and unregisters it on destroy.\n *\n * Works for any target shape — object handles, raw elements, id strings — since it only hands the\n * value back to the supplied callbacks.\n *\n * Must be invoked in an injection context.\n *\n * @param target The value to register. Passed verbatim to both callbacks.\n * @param register Registers the target with the owning parent.\n * @param unregister Called from `DestroyRef.onDestroy`. Must be reference-based and tolerant of\n * running before `register` ever did, which happens when a deferred registration is destroyed\n * before its render fires.\n * @param scheduling When the `register` callback runs. Defaults to `'sync'`.\n */\nexport function registerHandle<T>(\n target: T,\n register: (target: T) => void,\n unregister: (target: T) => void,\n scheduling: RegistrationScheduling = 'sync',\n): void {\n if (scheduling === 'afterNextRender') {\n afterNextRender(() => register(target));\n } else {\n register(target);\n }\n inject(DestroyRef).onDestroy(() => unregister(target));\n}\n\n/**\n * Owner contract for {@link registerA11yName}. The owner is typically the\n * primitive's context object (e.g. `injectDialogContext('ForDialogTitle')`)\n * or the parent directive instance — duck-typed so cross-primitive code\n * reuse doesn't force a shared base type.\n */\nexport interface A11yLabelOwner {\n registerLabel(id: string): void;\n unregisterLabel(id: string): void;\n}\n\n/**\n * Owner contract for {@link registerA11yDescription}. See\n * {@link A11yLabelOwner} for the rationale.\n */\nexport interface A11yDescriptionOwner {\n registerDescription(id: string): void;\n unregisterDescription(id: string): void;\n}\n\n/**\n * Resolves a stable `id` for the host element and registers it with the owner's `aria-labelledby`\n * collection. Returns a plain `string` — the id never changes — for host-binding as `'[id]': 'id'`.\n *\n * A consumer-set static `id` is adopted rather than clobbered; see {@link resolveHostId} for the\n * static-only boundary. The host element is read optionally, so the helper falls back to a\n * generated id when invoked outside a directive host context.\n *\n * Must be invoked in an injection context.\n */\nexport function registerA11yName(owner: A11yLabelOwner, prefix: string): string {\n const host =\n inject<ElementRef<HTMLElement>>(ElementRef, { optional: true })?.nativeElement ?? null;\n const id = resolveHostId(host, prefix);\n registerHandle(\n id,\n (myId) => owner.registerLabel(myId),\n (myId) => owner.unregisterLabel(myId),\n );\n return id;\n}\n\n/**\n * Counterpart to {@link registerA11yName} for `aria-describedby`. See that\n * function for the rationale and usage — including the consumer-set static\n * `id` adoption.\n */\nexport function registerA11yDescription(owner: A11yDescriptionOwner, prefix: string): string {\n const host =\n inject<ElementRef<HTMLElement>>(ElementRef, { optional: true })?.nativeElement ?? null;\n const id = resolveHostId(host, prefix);\n registerHandle(\n id,\n (myId) => owner.registerDescription(myId),\n (myId) => owner.unregisterDescription(myId),\n );\n return id;\n}\n","import { computed, effect, type Signal, signal } from '@angular/core';\nimport { fortyWarn } from '../errors/errors';\n\n/**\n * Identifies a {@link SingleSlot} in its dev-mode duplicate-registration\n * warning. All three fields are literals from the adopting primitive, never\n * runtime values.\n */\nexport interface SingleSlotConfig {\n /** Entry-point name used in the `[forty-cdk/<primitive>]` warning prefix (e.g. `'search'`). */\n readonly primitive: string;\n /** Selector of the directive that owns the slot (e.g. `'[forSearchGroup]'`). */\n readonly owner: string;\n /** Selector of the directive that registers into the slot (e.g. `'[forSearch]'`). */\n readonly claimant: string;\n}\n\n/**\n * A registry for a coordination seam that supports exactly one occupant: a\n * root or group directive that must reach a single sibling piece which cannot\n * be its DOM descendant (a void `<input>` next to its buttons, the native file\n * input next to its drop zone).\n *\n * Registrations are **stacked** rather than overwritten, mirroring\n * `ForField`'s counted label / description / error slots: the newest\n * registration is the coordinated one, a duplicate emits a dev-mode warning,\n * and unregistering the newest restores the previous survivor instead of\n * emptying the slot while a piece is still mounted.\n *\n * The warning reads the occupant count once the change-detection pass has\n * settled, so a structural swap that mounts the replacement before destroying\n * the outgoing piece (two sibling `@if` blocks under one owner) is not\n * reported. It fires once each time the slot becomes duplicated, not on every\n * further registration.\n *\n * The helper owns no teardown of its own — pair `register` / `unregister` with\n * the core `registerHandle` helper at the claimant's construction so the\n * claimant's own `DestroyRef` drives unregistration.\n *\n * @typeParam T The occupant type — a context interface, a handle, or a raw\n * element.\n */\nexport interface SingleSlot<T> {\n /**\n * The coordinated occupant: the most recently registered one, or `null`\n * while the slot is empty.\n */\n readonly value: Signal<T | null>;\n /**\n * Register an occupant, making it the coordinated one. A second occupant\n * still registered once the pass settles means the owner's single\n * coordination surface is ambiguous, and warns in dev mode.\n */\n register(occupant: T): void;\n /**\n * Remove a previously registered occupant. A no-op when it never registered,\n * and — because registrations are stacked — a late teardown of a stale\n * occupant never clears a newer one.\n */\n unregister(occupant: T): void;\n}\n\nexport function warnOnDuplicateRegistration(count: () => number, config: SingleSlotConfig): void {\n if (typeof ngDevMode !== 'undefined' && !ngDevMode) {\n return;\n }\n let warned = false;\n effect(() => {\n const registered = count();\n if (registered <= 1) {\n warned = false;\n } else if (!warned) {\n warned = true;\n fortyWarn({\n code: 'FORCDK-CORE-005',\n scope: config.primitive,\n message: `A ${config.owner} coordinates a single ${config.claimant}, but ${registered} are registered.`,\n cause: 'Only the most recently registered one is coordinated; the rest are inert.',\n fix: `Keep one ${config.claimant} per ${config.owner}.`,\n });\n }\n });\n}\n\n/**\n * Creates a {@link SingleSlot}. Must be called in an injection context, which a\n * directive field initializer is, because the dev-mode duplicate warning runs\n * on an `effect`. Safe under SSR.\n */\nexport function createSingleSlot<T>(config: SingleSlotConfig): SingleSlot<T> {\n const occupants = signal<readonly T[]>([]);\n const value = computed<T | null>(() => occupants().at(-1) ?? null);\n\n warnOnDuplicateRegistration(() => occupants().length, config);\n\n return {\n value,\n register(occupant: T): void {\n occupants.set([...occupants(), occupant]);\n },\n unregister(occupant: T): void {\n const current = occupants();\n const index = current.lastIndexOf(occupant);\n if (index < 0) {\n return;\n }\n occupants.set([...current.slice(0, index), ...current.slice(index + 1)]);\n },\n };\n}\n","import { computed, type Signal, signal } from '@angular/core';\n\nexport interface RootedHandle<R> {\n readonly root: Signal<R | null>;\n}\n\nconst NONE: readonly never[] = [];\n\nexport class RootedRegistry<R extends object, H extends RootedHandle<R>> {\n /** Every registered handle, in registration order. Mutated in place; `#version` tracks it. */\n readonly #handles = new Set<H>();\n\n readonly #version = signal(0);\n\n readonly #byRoot = computed(() => {\n this.#version();\n const index = new WeakMap<R, H[]>();\n for (const handle of this.#handles) {\n const root = handle.root();\n if (typeof root !== 'object' || root === null) {\n continue;\n }\n const bucket = index.get(root);\n if (bucket) {\n bucket.push(handle);\n } else {\n index.set(root, [handle]);\n }\n }\n return index;\n });\n\n add(handle: H): void {\n if (!this.#handles.has(handle)) {\n this.#handles.add(handle);\n this.#version.update((version) => version + 1);\n }\n }\n\n remove(handle: H): void {\n if (this.#handles.delete(handle)) {\n this.#version.update((version) => version + 1);\n }\n }\n\n of(root: R): Signal<readonly H[]> {\n return computed(() => this.#byRoot().get(root) ?? NONE, { equal: sameHandles });\n }\n}\n\nfunction sameHandles<H>(a: readonly H[], b: readonly H[]): boolean {\n return a.length === b.length && a.every((handle, index) => handle === b[index]);\n}\n","/**\n * Resolves the element that actually holds focus, descending through open\n * shadow roots.\n *\n * `document.activeElement` reports the shadow **host** while focus sits inside\n * a shadow tree, so any check that compares it against a specific descendant —\n * the focus trap's first / last tabbable, an \"is focus still mine?\" guard —\n * answers about the host instead of about the focused control.\n *\n * A closed shadow root exposes no `activeElement`, so the walk stops at its\n * host: the library resolves through open shadow roots only.\n */\nexport function resolveActiveElement(root: DocumentOrShadowRoot): Element | null {\n let active = root.activeElement;\n while (active?.shadowRoot?.activeElement) {\n active = active.shadowRoot.activeElement;\n }\n return active;\n}\n\n/**\n * Resolves the effective target of an interaction event for containment\n * checks. Prefers `composedPath()[0]` so a pointer-down / focus inside a shadow\n * tree reports the real originating node rather than the shadow host the event\n * was retargeted to. Falls back to `event.target` in environments without\n * `composedPath`.\n */\nexport function resolveEventTarget(event: Event): Node | null {\n const path = event.composedPath?.();\n const first = path && path.length > 0 ? path[0] : null;\n return (first ?? event.target) as Node | null;\n}\n\n/**\n * Whether `node` sits inside `container` in the composed tree: native\n * `contains`, plus a walk up through every open shadow boundary between the\n * two.\n *\n * `Node.contains` answers within a single node tree, so it reports `false` for\n * a node inside a shadow root nested in `container` — which is what makes\n * {@link resolveEventTarget} unsafe on its own: the deep target it resolves is\n * exactly the one plain containment then disowns, turning a press on a web\n * component inside an overlay into an outside-dismissal.\n */\nexport function composedContains(container: Node, node: Node | null): boolean {\n let current = node;\n while (current) {\n if (container.contains(current)) {\n return true;\n }\n current = shadowHostOf(current);\n }\n return false;\n}\n\n/**\n * The element `node` hangs from in the composed tree: its `parentElement`, or\n * the host of the shadow root it is a top-level child of. Bounded ancestor\n * walks use this so a shadow boundary continues the walk instead of silently\n * ending it one element short of the root they were bounded by.\n */\nexport function composedParentElement(node: Node): HTMLElement | null {\n const parent = node.parentNode;\n if (parent !== null && isShadowRoot(parent)) {\n return parent.host as HTMLElement;\n }\n return node.parentElement;\n}\n\n/**\n * The nearest inclusive ancestor of `node` matching `selector`, searching\n * across every open shadow boundary above it.\n *\n * The composed-tree counterpart of `Element.closest`, which — like\n * `querySelectorAll` and `Node.contains` — answers within a single node tree\n * and returns `null` for a match that lives above a shadow host. It pairs with\n * {@link resolveActiveElement}: resolving the deep active element and then\n * asking plain `closest` about it is the same half-applied posture\n * {@link composedContains} exists to prevent — the resolution hands over a node\n * from inside the shadow tree, which is exactly the one the un-composed walk\n * cannot climb out of.\n *\n * Each level delegates to the native `closest`, so the fast path inside a tree\n * stays the engine's; only the hop to the next host is done here.\n */\nexport function composedClosest(node: Element, selector: string): HTMLElement | null {\n let current: Element | null = node;\n while (current) {\n const match = current.closest<HTMLElement>(selector);\n if (match) {\n return match;\n }\n current = shadowHostOf(current);\n }\n return null;\n}\n\n/**\n * Whether `a` comes before `b` in composed-tree order, where an ancestor precedes its descendants\n * and a shadow host's shadow contents precede its light children — the order\n * `queryFocusableCandidates` enumerates in.\n *\n * `Node.compareDocumentPosition` reports two nodes on opposite sides of a shadow boundary as\n * disconnected, with an arbitrary order bit; this lifts each to its host in the lowest tree scope\n * the two share before comparing. Reports `false` for the same node, and for nodes with no shared\n * tree scope.\n */\nexport function composedPrecedes(a: Node, b: Node): boolean {\n const chainB = hostChainOf(b);\n for (const x of hostChainOf(a)) {\n const scope = x.getRootNode();\n const y = chainB.find((node) => node.getRootNode() === scope);\n if (y === undefined) {\n continue;\n }\n if (x === y) {\n return x === a && y !== b;\n }\n return (x.compareDocumentPosition(y) & x.DOCUMENT_POSITION_FOLLOWING) !== 0;\n }\n return false;\n}\n\nfunction hostChainOf(node: Node): Node[] {\n const chain: Node[] = [node];\n let host = shadowHostOf(node);\n while (host) {\n chain.push(host);\n host = shadowHostOf(host);\n }\n return chain;\n}\n\nfunction shadowHostOf(node: Node): Element | null {\n if (typeof node.getRootNode !== 'function') {\n return null;\n }\n const root = node.getRootNode();\n return root !== node && isShadowRoot(root) ? root.host : null;\n}\n\n/**\n * Narrows to an open shadow root. The `nodeType` half is load-bearing: `host`\n * alone is also a property of `<a>` / `<area>` / `<link>` (the URL's host), so\n * a duck-type on the name alone reads an anchor ancestor as a shadow boundary\n * and returns a string where an element belongs. Reading the constant off the\n * instance keeps the check free of the `Node` global, so it costs nothing on a\n * server.\n */\nfunction isShadowRoot(node: Node): node is ShadowRoot {\n return node.nodeType === node.DOCUMENT_FRAGMENT_NODE && 'host' in node;\n}\n","import { inject } from '@angular/core';\n\nimport {\n type DateAdapter,\n FOR_DATE_ADAPTER,\n type TimeCapableDateAdapter,\n} from 'forty-cdk/date-adapter';\nimport { fortyError } from '../errors/errors';\n\n/**\n * Day-only comparison for `adapter`, honouring its optional\n * {@link DateAdapter.compareDate} when implemented and otherwise deriving the\n * ordering from the `getYear` / `getMonth` / `getDate` getters. Returns a\n * negative number when `a`'s calendar day is before `b`'s, `0` when they fall\n * on the same day, and a positive number when `a`'s day is after `b`'s.\n *\n * Use this for day-granular availability and bounds (e.g. the calendar grid),\n * where the boundary day of a date-time `min`/`max` must stay selectable on\n * every adapter. For full-instant ordering — including any time component —\n * call {@link DateAdapter.compare} directly.\n *\n * @typeParam D The adapter's immutable date representation.\n * @param adapter The active date adapter.\n * @param a The first date.\n * @param b The second date.\n */\nexport function compareDateOf<D>(adapter: DateAdapter<D>, a: D, b: D): number {\n if (adapter.compareDate) {\n return adapter.compareDate(a, b);\n }\n const ay = adapter.getYear(a);\n const by = adapter.getYear(b);\n if (ay !== by) {\n return ay - by;\n }\n const am = adapter.getMonth(a);\n const bm = adapter.getMonth(b);\n if (am !== bm) {\n return am - bm;\n }\n return adapter.getDate(a) - adapter.getDate(b);\n}\n\n/**\n * Injects the active {@link DateAdapter}, throwing a descriptive,\n * primitive-prefixed error when no adapter has been provided.\n *\n * @param piece Name of the calling directive, used in the error message.\n * @param options `scope` is the entry point the error reports under, e.g.\n * `'date-field'`. Omit it from shared machinery that does not know one — the\n * check then reports under `[forty-cdk/core]` and `piece` carries the\n * attribution alone. The type stays inline on purpose: a named interface here\n * would be a core symbol reached from a blessed public signature, so it would\n * have to be published from `forty-cdk/shared` and carry that guarantee\n * forever, for one optional string.\n */\nexport function injectDateAdapter<D>(\n piece: string,\n options?: { readonly scope?: string },\n): DateAdapter<D> {\n const adapter = inject(FOR_DATE_ADAPTER, { optional: true });\n if (!adapter) {\n throw fortyError({\n code: 'FORCDK-CORE-002',\n scope: options?.scope,\n message: `${piece} requires a DateAdapter, and none is provided.`,\n fix:\n 'Add provideNativeDateAdapter() or provideInternationalizedDateAdapter() to your ' +\n 'application or component providers.',\n });\n }\n return adapter as DateAdapter<D>;\n}\n\n/**\n * Asserts that `adapter` implements the optional time accessors, returning it\n * narrowed to {@link TimeCapableDateAdapter}. Throws a descriptive,\n * primitive-prefixed error when the active adapter is day-only — the\n * zero-dependency `provideNativeDateAdapter()` is time-capable, as is\n * `provideInternationalizedDateTimeAdapter()`, but the day-pure\n * `provideInternationalizedDateAdapter()` (`CalendarDate`) is not.\n *\n * @param adapter The active adapter, typically from {@link injectDateAdapter}.\n * @param piece Name of the calling directive, used in the error message.\n * @param options `scope` is the entry point the error reports under — same\n * contract, and same inline-type reasoning, as {@link injectDateAdapter}.\n */\nexport function assertTimeCapable<D>(\n adapter: DateAdapter<D>,\n piece: string,\n options?: { readonly scope?: string },\n): TimeCapableDateAdapter<D> {\n if (\n typeof adapter.getHours !== 'function' ||\n typeof adapter.getMinutes !== 'function' ||\n typeof adapter.getSeconds !== 'function' ||\n typeof adapter.setTime !== 'function'\n ) {\n throw fortyError({\n code: 'FORCDK-CORE-003',\n scope: options?.scope,\n message: `${piece} requires a time-capable DateAdapter, and the active one is day-only.`,\n cause:\n 'provideInternationalizedDateAdapter() supplies CalendarDate values, which carry no time ' +\n 'of day, so the adapter implements none of the time accessors.',\n fix:\n 'Switch to provideNativeDateAdapter() or provideInternationalizedDateTimeAdapter() in the ' +\n 'providers that reach this piece.',\n });\n }\n return adapter as TimeCapableDateAdapter<D>;\n}\n","/**\n * Resolves the effective hour cycle. An explicit `12` / `24` always wins;\n * otherwise the runtime locale's preference is read from\n * `Intl.DateTimeFormat(...).resolvedOptions().hourCycle` (`h11` / `h12` → 12,\n * `h23` / `h24` → 24).\n *\n * @param locale BCP 47 locale, or `undefined` for the runtime default.\n * @param override The `hourCycle` input, or `null` to derive from the locale.\n */\nexport function resolveHourCycle(locale: string | undefined, override: 12 | 24 | null): 12 | 24 {\n if (override !== null) {\n return override;\n }\n const cycle = new Intl.DateTimeFormat(locale, {\n calendar: 'gregory',\n hour: 'numeric',\n }).resolvedOptions().hourCycle;\n return cycle === 'h11' || cycle === 'h12' ? 12 : 24;\n}\n\n/**\n * Maps a 0-23 hour to its 12-hour display value and AM/PM period.\n *\n * @param hour The 0-23 hour.\n * @param min The lowest display hour: `1` counts 1-12 (`h12`), `0` counts 0-11 (`h11`).\n */\nexport function to12(hour: number, min: 0 | 1 = 1): { h12: number; pm: boolean } {\n const h12 = hour % 12;\n return { h12: h12 < min ? h12 + 12 : h12, pm: hour >= 12 };\n}\n\n/**\n * The lowest hour a 12-hour clock displays in `locale`: `0` where the locale\n * counts 0-11 (`h11`, e.g. `ja-JP`, where 12:30 reads 午後0:30), `1` where it\n * counts 1-12 (`h12`). Pure.\n *\n * @param locale BCP 47 locale, or `undefined` for the runtime default.\n */\nexport function twelveHourMin(locale: string | undefined): 0 | 1 {\n const cycle = new Intl.DateTimeFormat(locale, {\n calendar: 'gregory',\n hour: 'numeric',\n hour12: true,\n }).resolvedOptions().hourCycle;\n return cycle === 'h11' ? 0 : 1;\n}\n\n/** Combines a 0-12 display hour and an AM/PM period back into a 0-23 hour. */\nexport function from12(h12: number, pm: boolean): number {\n const base = h12 % 12;\n return pm ? base + 12 : base;\n}\n\n/**\n * Reads the localized AM / PM strings for a locale (e.g. `AM` / `PM`,\n * `a.m.` / `p.m.`, `午前` / `午後`). Pure.\n *\n * @param locale BCP 47 locale, or `undefined` for the runtime default.\n */\nexport function dayPeriodNames(locale: string | undefined): { am: string; pm: string } {\n const fmt = new Intl.DateTimeFormat(locale, {\n calendar: 'gregory',\n hour: 'numeric',\n hour12: true,\n });\n const read = (date: Date): string =>\n fmt.formatToParts(date).find((part) => part.type === 'dayPeriod')?.value ?? '';\n return {\n am: read(new Date(2000, 0, 1, 1)) || 'AM',\n pm: read(new Date(2000, 0, 1, 13)) || 'PM',\n };\n}\n\nfunction firstDifferingIndex(a: string, b: string): number {\n const length = Math.min(a.length, b.length);\n for (let i = 0; i < length; i++) {\n if (a[i] !== b[i]) {\n return i;\n }\n }\n return -1;\n}\n\n/**\n * Resolves a single typed character to an AM / PM period for the `dayPeriod`\n * segment, so localized fields accept the locale's own day-period key (e.g.\n * `前` / `後` for `午前` / `午後`, `ص` / `م`) rather than only Latin `a` / `p`.\n *\n * The key is matched against the first character at which the two localized\n * names (`names.am` / `names.pm`) differ — this disambiguates locales whose\n * names share a leading character (`午前` / `午後`, `오전` / `오후`) while\n * coinciding with the first character for English. A Latin `a` / `p` fallback\n * always applies, since AM/PM is universal and many users lack an IME for the\n * native character. Returns `null` for a multi-character key or an unrecognized\n * character. Pure.\n *\n * @param key The typed character (`event.key`).\n * @param names The localized AM / PM strings, as read by {@link dayPeriodNames}.\n */\nexport function matchDayPeriod(key: string, names: { am: string; pm: string }): 'am' | 'pm' | null {\n if (key.length !== 1) {\n return null;\n }\n const lowerKey = key.toLowerCase();\n const am = names.am.toLowerCase();\n const pm = names.pm.toLowerCase();\n const index = firstDifferingIndex(am, pm);\n if (index !== -1) {\n if (lowerKey === am[index]) {\n return 'am';\n }\n if (lowerKey === pm[index]) {\n return 'pm';\n }\n }\n if (lowerKey === 'a') {\n return 'am';\n }\n if (lowerKey === 'p') {\n return 'pm';\n }\n return null;\n}\n","const formatters = new Map<string, Intl.NumberFormat>();\n\n/**\n * Renders a non-negative date or time part (a day, a month, a year, an hour)\n * as the text a piece displays, in the numbering system `locale` formats its\n * dates with: Arabic-Indic digits for `ar-EG`, Persian digits for `fa-IR`,\n * Devanagari for `hi-IN-u-nu-deva`, Latin digits for `en-US`. Never grouped,\n * and zero-padded to `minimumIntegerDigits`.\n *\n * The numbering system is read off a Gregorian `Intl.DateTimeFormat` for the\n * same locale, so the digits match what the date adapters' `format` renders\n * beside them. Formatters are cached per `(locale, minimumIntegerDigits)`.\n *\n * @param value The part's number.\n * @param minimumIntegerDigits The width to zero-pad to (`1` for no padding).\n * @param locale BCP 47 locale, or `undefined` for the runtime default.\n */\nexport function formatLocaleDigits(\n value: number,\n minimumIntegerDigits: number,\n locale: string | undefined,\n): string {\n const key = `${locale ?? ''}|${minimumIntegerDigits}`;\n let formatter = formatters.get(key);\n if (formatter === undefined) {\n const { numberingSystem } = new Intl.DateTimeFormat(locale, {\n calendar: 'gregory',\n }).resolvedOptions();\n formatter = new Intl.NumberFormat(locale, {\n numberingSystem,\n useGrouping: false,\n minimumIntegerDigits,\n });\n formatters.set(key, formatter);\n }\n return formatter.format(value);\n}\n","import { computed, signal, type Signal } from '@angular/core';\n\nimport type { RovingTabindex } from '../roving-tabindex/roving-tabindex';\nimport { from12, matchDayPeriod, to12 } from './hour-cycle';\nimport { formatLocaleDigits } from './locale-digits';\nimport type { TimeSegmentType } from './segment-types';\n\n/** Which calendar part an editable date segment edits. */\nexport type DateSegmentType = 'day' | 'month' | 'year';\n\n/**\n * Every editable part a date(-time) or time field can render — the date parts\n * plus the time parts (`hour` / `minute` / `second` / the AM·PM `dayPeriod`).\n */\nexport type SegmentType = DateSegmentType | TimeSegmentType;\n\n/** Spec for a single editable spinbutton segment. */\nexport interface EditableSpec {\n readonly kind: 'editable';\n /** The date or time part this segment edits. */\n readonly type: SegmentType;\n /** Maximum number of digits the segment accepts before it is full (`0` for the AM/PM toggle). */\n readonly digits: number;\n}\n\n/** Spec for a non-editable separator rendered between segments. */\nexport interface LiteralSpec {\n readonly kind: 'literal';\n /** The separator characters (`/`, `.`, `-`, `:`, a space, …) for the runtime locale. */\n readonly literal: string;\n}\n\n/** A single entry in the locale-ordered segment list. */\nexport type FieldSpec = EditableSpec | LiteralSpec;\n\n/** Per-part entered state: the entered value for each editable segment, hour as 0-23. */\nexport type SegmentParts = Partial<Record<SegmentType, number | null>>;\n\n/**\n * A rendered segment descriptor for the consumer's `@for`. Covers both editable\n * spinbutton segments and the decorative literal separators between them.\n *\n * @typeParam T The segment-type union the owning field renders (the date field\n * carries the full {@link SegmentType}; the time field narrows to its\n * `TimeSegmentType`).\n */\nexport interface FieldSegment<T extends SegmentType = SegmentType> {\n /** Stable key for `@for` tracking. */\n readonly id: string;\n /** `true` for a separator; `false` for an editable segment. */\n readonly isLiteral: boolean;\n /** The part an editable segment edits; `null` for a literal. */\n readonly type: T | null;\n /**\n * Text to render: the formatted value when the segment is filled, the\n * placeholder while empty, or the literal separator.\n */\n readonly text: string;\n}\n\n/** Handle a segment directive registers with the editor for focus moves. */\nexport interface SegmentHandle<T extends SegmentType = SegmentType> {\n /** The segment's host element. */\n readonly host: HTMLElement;\n /** The part the segment edits. */\n readonly type: Signal<T>;\n}\n\n/**\n * The per-segment accessor and behavior surface a date / time field engine\n * exposes to its segment children. It is the non-signal half of a\n * {@link import('./segment-directive').SegmentEditorContext}: segments read the\n * reactive accessors for their ARIA / display bindings and call the behavior\n * methods to type, step, clear, and move focus. `DateFieldEngine` and\n * `TimeFieldEngine` both satisfy it, so one segment directive drives either\n * flavour of field and one composer coordinates either flavour of endpoint.\n */\nexport interface SegmentEditorDelegate {\n /** Current display value of `type`, or `null` while empty. */\n segmentValue(type: SegmentType): number | null;\n /** Lowest accepted display value for `type`. */\n segmentMin(type: SegmentType): number;\n /** Highest accepted display value for `type`. */\n segmentMax(type: SegmentType): number;\n /** Field-specific `aria-valuetext` for `type`, or `null` for the numeric reading. */\n segmentValueText(type: SegmentType): string | null;\n /** Text to render for `type`: the formatted value, the placeholder, or the typing buffer. */\n segmentDisplayText(type: SegmentType): string;\n /** Whether `type` currently holds no entered value. */\n isSegmentEmpty(type: SegmentType): boolean;\n /** Whether `type` is the first editable segment in locale order. */\n isFirstSegmentType(type: SegmentType): boolean;\n\n /** Registers a segment handle for focus moves. */\n registerSegment(handle: SegmentHandle): void;\n /** Removes a previously registered segment handle. */\n unregisterSegment(handle: SegmentHandle): void;\n\n /** Moves the roving tab stop to `type` and clears the typing buffer. */\n focusSegment(type: SegmentType): void;\n /** Types a digit into `type` (fill + auto-advance). */\n typeDigit(type: SegmentType, digit: number): void;\n /** Steps `type` by `delta` (arrow keys), wrapping / clamping per part. */\n step(type: SegmentType, delta: number): void;\n /** Jumps `type` to its minimum or maximum (Home / End). */\n goToBound(type: SegmentType, bound: 'min' | 'max'): void;\n /** Sets the AM / PM period. */\n setDayPeriod(period: 'am' | 'pm'): void;\n /** Sets AM/PM from a typed character; returns whether the key was recognized. */\n setDayPeriodFromKey(key: string): boolean;\n /** Clears `type` back to empty (Delete). */\n clear(type: SegmentType): void;\n /** Removes the last entered digit of `type` (whole clear when the last digit goes). */\n backspace(type: SegmentType): void;\n /** Moves focus to the sibling segment in the given direction. */\n focusSibling(type: SegmentType, step: -1 | 1): void;\n /**\n * Flushes any mid-typing transient and clears the typing buffer (blur). When\n * `next`, the element receiving focus, is not one of the field's segments, the\n * field settles: its segments re-read the committed value, clamp included.\n */\n endTyping(next?: EventTarget | null): void;\n}\n\n/**\n * The field-specific surface a date / time root supplies to its\n * {@link SegmentEditor}. The editor owns the spin-button state machine (typing\n * buffer, step / clear / Home-End, digit auto-advance, RTL focus moves, the\n * segment registry); the host supplies only what differs between a date field\n * and a time field: the reactive specs / cycle / locale data, the per-segment\n * bounds, the empty-segment seed, the placeholder, the extra `aria-valuetext`,\n * and how a committed parts record is composed into the value.\n *\n * @typeParam P The host's parts shape (a subtype of {@link SegmentParts}).\n */\nexport interface SegmentEditorHost<P extends SegmentParts> {\n /** Whether the field is disabled. */\n readonly disabled: Signal<boolean>;\n /** Whether the field is read-only. */\n readonly readonly: Signal<boolean>;\n /** Shared roving-tabindex tracker: one segment owns `tabindex=0` at a time. */\n readonly roving: RovingTabindex;\n /** Resolved hour cycle (`12` shows AM/PM, `24` does not). */\n readonly cycle: Signal<12 | 24>;\n /** The ordered, locale-derived spec list (editable + literals). */\n readonly specs: Signal<readonly FieldSpec[]>;\n /** The editable parts in their locale order — the navigation / auto-advance order. */\n readonly editableOrder: Signal<readonly SegmentType[]>;\n /** Localized AM / PM strings for the `dayPeriod` segment. */\n readonly periodNames: Signal<{ am: string; pm: string }>;\n /** The resolved locale the segment digits render in, `undefined` for the runtime default. */\n readonly locale: Signal<string | undefined>;\n\n /** Current entered parts. */\n parts(): P;\n /** Lowest accepted display value for `type`. */\n segmentMin(type: SegmentType): number;\n /** Highest accepted display value for `type`. */\n segmentMax(type: SegmentType): number;\n /** Base value for stepping an empty `type` on first step. */\n seed(type: SegmentType): number;\n /** Placeholder shown while `type` is empty. */\n placeholderFor(type: SegmentType): string;\n /**\n * Field-specific `aria-valuetext` for a filled `type` (e.g. the month name),\n * or `null` to fall back to the default numeric reading.\n */\n valueText(type: SegmentType): string | null;\n /**\n * Records the next parts for the field.\n *\n * `transient` is `true` for a mid-typing digit whose segment buffer has not\n * yet settled (a non-final keystroke): the host updates its live segment\n * display only and does **not** emit the composed value, so an intermediate\n * keystroke composition is never observable through the field value. A\n * settled commit (`false`: a completed digit / auto-advance, a step, a\n * Home/End jump, a day-period toggle, a clear, or a blur flush) clamps to the\n * bounds and emits the composed value.\n */\n commit(next: P, transient: boolean): void;\n /** Re-reads the entered parts from the committed value once focus leaves the segments. */\n settle(): void;\n /**\n * Whether `parts` name a wall-clock time the day skips (a DST gap), so a step\n * of `type` passes over it.\n */\n nonexistent(type: SegmentType, parts: P): boolean;\n}\n\n/**\n * The shared spin-button editor backing `ForDateField` and `ForTimeField`.\n *\n * It owns everything that was duplicated ~95% between the two roots: the\n * ephemeral digit-typing buffer, `typeDigit` (digit fill + auto-advance), `step`\n * (with the 12/24-hour-aware hour stepping), `goToBound`, `setDayPeriod`,\n * `clear`, the RTL-mirrored `focusSibling` / `focusSegment`, the\n * `registerSegment` / `unregisterSegment` `Map`, and the reactive per-part\n * accessors (`segmentValue` / `segmentDisplayText` / `segmentValueText` /\n * `isSegmentEmpty` / `isFirstSegmentType`) plus the rendered `segments` list.\n *\n * Constructed directly (`new SegmentEditor(host)`); it holds no injection\n * context. The host (a date or time root) supplies the field-specific bits\n * through {@link SegmentEditorHost}.\n *\n * @typeParam P The host's parts shape.\n * @typeParam T The segment-type union the owning field renders.\n */\nexport class SegmentEditor<P extends SegmentParts, T extends SegmentType = SegmentType> {\n readonly #host: SegmentEditorHost<P>;\n readonly #segments = new Map<SegmentType, SegmentHandle>();\n\n /** Ephemeral type-to-fill buffer for the segment currently being typed into. */\n readonly #typing = signal<{ type: SegmentType; buffer: string } | null>(null);\n\n #pendingSettle = false;\n\n /**\n * The ordered, locale-derived segments (editable + literals) to render. Each\n * entry carries the text to display: the formatted value when filled, the\n * placeholder while empty, or the literal separator.\n */\n readonly segments: Signal<readonly FieldSegment<T>[]>;\n\n /** `true` while every editable segment is empty — the field shows no entered digits. */\n readonly empty: Signal<boolean>;\n\n constructor(host: SegmentEditorHost<P>) {\n this.#host = host;\n this.segments = computed<readonly FieldSegment<T>[]>(() => {\n let literalIndex = 0;\n return this.#host.specs().map((spec): FieldSegment<T> => {\n if (spec.kind === 'literal') {\n return {\n id: `literal-${literalIndex++}`,\n isLiteral: true,\n type: null,\n text: spec.literal,\n };\n }\n return {\n id: spec.type,\n isLiteral: false,\n type: spec.type as T,\n text: this.segmentDisplayText(spec.type),\n };\n });\n });\n this.empty = computed(() =>\n this.#host.editableOrder().every((type) => this.isSegmentEmpty(type)),\n );\n }\n\n segmentValue(type: SegmentType): number | null {\n const parts = this.#host.parts();\n if (type === 'dayPeriod') {\n return parts.dayPeriod ?? null;\n }\n if (type === 'hour') {\n const hour = parts.hour;\n if (hour == null) {\n return null;\n }\n return this.#host.cycle() === 12 ? to12(hour, this.#twelveHourMin()).h12 : hour;\n }\n return parts[type] ?? null;\n }\n\n segmentValueText(type: SegmentType): string | null {\n if (type === 'dayPeriod') {\n const dayPeriod = this.#host.parts().dayPeriod;\n if (dayPeriod == null) {\n return this.#host.valueText(type);\n }\n const names = this.#host.periodNames();\n return dayPeriod === 1 ? names.pm : names.am;\n }\n return this.#host.valueText(type);\n }\n\n segmentDisplayText(type: SegmentType): string {\n const typing = this.#typing();\n if (typing && typing.type === type) {\n return formatLocaleDigits(Number(typing.buffer), typing.buffer.length, this.#host.locale());\n }\n if (type === 'dayPeriod') {\n const dayPeriod = this.#host.parts().dayPeriod;\n if (dayPeriod == null) {\n return this.#host.placeholderFor(type);\n }\n const names = this.#host.periodNames();\n return dayPeriod === 1 ? names.pm : names.am;\n }\n const value = this.segmentValue(type);\n if (value === null) {\n return this.#host.placeholderFor(type);\n }\n return formatLocaleDigits(value, type === 'year' ? 4 : 2, this.#host.locale());\n }\n\n isSegmentEmpty(type: SegmentType): boolean {\n return this.#host.parts()[type] == null;\n }\n\n isFirstSegmentType(type: SegmentType): boolean {\n return this.#host.editableOrder()[0] === type;\n }\n\n registerSegment(handle: SegmentHandle): void {\n this.#segments.set(handle.type(), handle);\n }\n\n unregisterSegment(handle: SegmentHandle): void {\n if (this.#segments.get(handle.type()) === handle) {\n this.#segments.delete(handle.type());\n }\n this.#host.roving.unregister(handle.host);\n }\n\n focusSegment(type: SegmentType): void {\n const handle = this.#segments.get(type);\n if (handle) {\n this.#host.roving.setActive(handle.host);\n }\n this.#typing.set(null);\n }\n\n /**\n * Clears the ephemeral type-to-fill buffer so a partially typed, uncommitted\n * digit is not left painted once the segment loses focus. The segment repaints\n * from its committed value (zero-padded, or the placeholder when empty).\n *\n * A blur is a settle event: when a mid-typing transient is still pending, it\n * is flushed as a settled commit of the current parts before the buffer is\n * cleared, so leaving a partially typed segment settles (and clamps) its value.\n * When focus moves anywhere but another of this field's segments, the host\n * settles too.\n */\n endTyping(next?: EventTarget | null): void {\n if (this.#pendingSettle) {\n this.#commit(this.#host.parts(), false);\n }\n this.#typing.set(null);\n if (!this.#ownsSegment(next)) {\n this.#host.settle();\n }\n }\n\n /** Drops the typing buffer and any pending transient without committing it. */\n resetTyping(): void {\n this.#pendingSettle = false;\n this.#typing.set(null);\n }\n\n #ownsSegment(target: EventTarget | null | undefined): boolean {\n if (!target) {\n return false;\n }\n for (const handle of this.#segments.values()) {\n if (handle.host === target) {\n return true;\n }\n }\n return false;\n }\n\n #commit(next: P, transient: boolean): void {\n this.#pendingSettle = transient;\n this.#host.commit(next, transient);\n }\n\n typeDigit(type: SegmentType, digit: number): void {\n if (this.#host.disabled() || this.#host.readonly() || type === 'dayPeriod') {\n return;\n }\n const spec = this.#editableSpec(type);\n const min = this.#host.segmentMin(type);\n const max = this.#host.segmentMax(type);\n const previous = this.#typing();\n let buffer = (previous?.type === type ? previous.buffer : '') + String(digit);\n if (Number(buffer) > max || buffer.length > spec.digits) {\n buffer = String(digit);\n }\n const num = Number(buffer);\n const valid = num >= min && num <= max;\n const full = valid && (buffer.length >= spec.digits || num * 10 > max);\n this.#typing.set({ type, buffer });\n this.#commit(this.#withPart(type, valid ? this.#toInternal(type, num) : null), !full);\n if (full) {\n this.#typing.set(null);\n this.focusSibling(type, 1);\n }\n }\n\n step(type: SegmentType, delta: number): void {\n if (this.#host.disabled() || this.#host.readonly()) {\n return;\n }\n this.#typing.set(null);\n if (type === 'dayPeriod') {\n const period = this.#host.parts().dayPeriod;\n this.setDayPeriod(period == null ? (delta > 0 ? 'pm' : 'am') : period === 1 ? 'am' : 'pm');\n return;\n }\n const parts = this.#host.parts();\n const current = parts[type];\n if (current == null) {\n this.#commit(this.#withPart(type, this.#host.seed(type)), false);\n return;\n }\n let next = this.#stepValue(type, current, delta);\n let skips = this.#host.segmentMax(type) - this.#host.segmentMin(type);\n while (skips-- > 0 && this.#host.nonexistent(type, this.#withPart(type, next))) {\n next = this.#stepValue(type, next, delta);\n }\n this.#commit(this.#withPart(type, next), false);\n }\n\n #stepValue(type: SegmentType, current: number, delta: number): number {\n if (type === 'hour') {\n return this.#stepHour(current, delta);\n }\n if (type === 'minute' || type === 'second') {\n return (((current + delta) % 60) + 60) % 60;\n }\n if (type === 'year') {\n return Math.min(\n this.#host.segmentMax(type),\n Math.max(this.#host.segmentMin(type), current + delta),\n );\n }\n const min = this.#host.segmentMin(type);\n const range = this.#host.segmentMax(type) - min + 1;\n return min + ((((current - min + delta) % range) + range) % range);\n }\n\n goToBound(type: SegmentType, bound: 'min' | 'max'): void {\n if (this.#host.disabled() || this.#host.readonly()) {\n return;\n }\n this.#typing.set(null);\n if (type === 'dayPeriod') {\n this.setDayPeriod(bound === 'min' ? 'am' : 'pm');\n return;\n }\n const display = bound === 'min' ? this.#host.segmentMin(type) : this.#host.segmentMax(type);\n this.#commit(this.#withPart(type, this.#toInternal(type, display)), false);\n }\n\n setDayPeriod(period: 'am' | 'pm'): void {\n if (this.#host.disabled() || this.#host.readonly()) {\n return;\n }\n this.#typing.set(null);\n const parts = this.#host.parts();\n const pm = period === 'pm';\n const hour = parts.hour ?? null;\n const nextHour = hour === null ? null : from12(to12(hour).h12, pm);\n this.#commit({ ...parts, dayPeriod: pm ? 1 : 0, hour: nextHour } as P, false);\n }\n\n /**\n * Sets the AM / PM period from a single typed character on the `dayPeriod`\n * segment, matched against the localized day-period names (with a Latin\n * `a` / `p` fallback) via {@link matchDayPeriod}. Returns `true` when `key`\n * is a recognized period character — regardless of disabled / read-only, so\n * the caller can `preventDefault` on a known key even when no commit\n * occurs — and `false` when it is not.\n */\n setDayPeriodFromKey(key: string): boolean {\n const period = matchDayPeriod(key, this.#host.periodNames());\n if (period === null) {\n return false;\n }\n this.setDayPeriod(period);\n return true;\n }\n\n clear(type: SegmentType): void {\n if (this.#host.disabled() || this.#host.readonly() || type === 'dayPeriod') {\n return;\n }\n this.#typing.set(null);\n this.#commit(this.#withPart(type, null), false);\n }\n\n /**\n * Removes the last entered digit of a numeric segment (the mirror of\n * {@link typeDigit}). It pops one display digit off the active typing buffer,\n * or off the committed display value when nothing is being typed, then\n * re-commits the shortened buffer as a mid-typing transient — so a partial\n * value is not clamped or rehydrated. When the last digit is removed the\n * segment settles to empty (a settled `null` commit, identical to\n * {@link clear}). No-op on the `dayPeriod` toggle and while disabled /\n * read-only.\n */\n backspace(type: SegmentType): void {\n if (this.#host.disabled() || this.#host.readonly() || type === 'dayPeriod') {\n return;\n }\n const previous = this.#typing();\n const source = previous?.type === type ? previous.buffer : this.#currentDigits(type);\n const buffer = source.slice(0, -1);\n if (buffer === '') {\n this.#typing.set(null);\n this.#commit(this.#withPart(type, null), false);\n return;\n }\n const num = Number(buffer);\n const valid = num >= this.#host.segmentMin(type) && num <= this.#host.segmentMax(type);\n this.#typing.set({ type, buffer });\n this.#commit(this.#withPart(type, valid ? this.#toInternal(type, num) : null), true);\n }\n\n focusSibling(type: SegmentType, step: -1 | 1): void {\n const order = this.#host.editableOrder();\n const targetType = order[order.indexOf(type) + step];\n if (targetType === undefined) {\n return;\n }\n const handle = this.#segments.get(targetType);\n if (!handle) {\n return;\n }\n this.#host.roving.setActive(handle.host);\n handle.host.focus();\n }\n\n /**\n * Move focus to the first editable segment in locale order — the entry point\n * a field's `FormValueControl.focus` targets so Signal Forms' focus-on-error\n * lands on a real spinbutton rather than the non-focusable `role=\"group\"`\n * host. No-op when no segment has registered yet.\n */\n focusFirstSegment(options?: FocusOptions): void {\n const first = this.#host.editableOrder()[0];\n if (first === undefined) {\n return;\n }\n const handle = this.#segments.get(first);\n if (!handle) {\n return;\n }\n this.#host.roving.setActive(handle.host);\n handle.host.focus(options);\n }\n\n #currentDigits(type: SegmentType): string {\n const value = this.segmentValue(type);\n return value === null ? '' : String(value);\n }\n\n /** Converts a displayed segment value to its internal representation (hour: 12h→24h). */\n #toInternal(type: SegmentType, display: number): number {\n if (type !== 'hour' || this.#host.cycle() === 24) {\n return display;\n }\n const parts = this.#host.parts();\n const pm =\n parts.dayPeriod != null ? parts.dayPeriod === 1 : parts.hour != null && parts.hour >= 12;\n return from12(display, pm);\n }\n\n #stepHour(current: number, delta: number): number {\n if (this.#host.cycle() === 24) {\n return (((current + delta) % 24) + 24) % 24;\n }\n const min = this.#twelveHourMin();\n const { h12, pm } = to12(current, min);\n return from12(min + ((((h12 - min + delta) % 12) + 12) % 12), pm);\n }\n\n #twelveHourMin(): 0 | 1 {\n return this.#host.segmentMin('hour') === 0 ? 0 : 1;\n }\n\n #editableSpec(type: SegmentType): EditableSpec {\n return this.#host\n .specs()\n .find((spec): spec is EditableSpec => spec.kind === 'editable' && spec.type === type)!;\n }\n\n /**\n * Returns the current parts with `type` set to `value`. `type` is always a key\n * the host's parts record carries, so the computed-key spread is a genuine `P`\n * at runtime; the assertion narrows the object-literal index type back to `P`.\n */\n #withPart(type: SegmentType, value: number | null): P {\n return { ...this.#host.parts(), [type]: value } as P;\n }\n}\n","import { computed, linkedSignal, type Signal, untracked, type WritableSignal } from '@angular/core';\n\nimport type { RovingTabindex } from '../roving-tabindex/roving-tabindex';\nimport type { DateAdapter } from 'forty-cdk/date-adapter';\nimport { dayPeriodNames, resolveHourCycle, twelveHourMin } from './hour-cycle';\nimport {\n type FieldSegment,\n type FieldSpec,\n SegmentEditor,\n type SegmentHandle,\n type SegmentParts,\n type SegmentType,\n} from './segment-editor';\n\n/**\n * The reactive configuration shared by every segmented date / time field engine:\n * the disabled / read-only flags, the roving tracker, the hour-cycle / locale\n * inputs that drive the resolved cycle, the empty-segment text, the\n * authoritative `source` value, and the `onCommit` sink. Each concrete engine's\n * config extends this with its adapter, granularity, placeholder, and bounds.\n *\n * @typeParam D The adapter's immutable date (or date-time) type.\n */\nexport interface BaseFieldEngineConfig<D> {\n /** The active date adapter; its `locale()` backs an unset {@link locale}. */\n readonly adapter: DateAdapter<D>;\n /** Whether editing is disabled (the field's effective disabled). */\n readonly disabled: Signal<boolean>;\n /** Whether editing is read-only. */\n readonly readonly: Signal<boolean>;\n /** Shared roving-tabindex tracker for this field's segments. */\n readonly roving: RovingTabindex;\n /** 12- / 24-hour override, or `null` to derive from the locale. */\n readonly hourCycle: Signal<12 | 24 | null>;\n /**\n * BCP 47 locale driving segment order, separators, and AM/PM names, or `null`\n * for the adapter's `locale()`, then the runtime default.\n */\n readonly locale: Signal<string | null>;\n /** Accessible `aria-valuetext` announced for an empty editable segment. */\n readonly emptySegmentText: Signal<string>;\n /** Authoritative current value the entered parts rehydrate from. */\n readonly source: Signal<D | null>;\n /** Sink called with the composed value (or `null` while incomplete) on every edit. */\n readonly onCommit: (value: D | null) => void;\n}\n\n/**\n * The shared base backing `DateFieldEngine` and `TimeFieldEngine`. It owns\n * everything the two engines duplicated on top of the generic\n * {@link SegmentEditor}: the resolved hour cycle, the editable-order / period-name\n * derivations, the rendered `segments` / `empty` / `composed` signals, the editor\n * wiring, the segment-behavior forwarding, and the settle-vs-transient commit\n * skeleton. Each concrete engine supplies only what differs between a date field\n * and a time field: the locale-ordered `specs`, the entered `parts`, the\n * per-segment bounds / seed / placeholder / `aria-valuetext`, and how a parts\n * record composes into the value.\n *\n * Constructed by the concrete subclass, which must assign {@link specs} and\n * {@link parts} and then call {@link initEditor} at the end of its constructor:\n * the editor captures `specs` / `parts`, so building it in a base field\n * initializer (which runs before the subclass assigns them) would capture\n * `undefined`.\n *\n * @typeParam D The adapter's immutable date (or date-time) type.\n * @typeParam P The engine's parts shape (a subtype of {@link SegmentParts}).\n * @typeParam T The segment-type union the owning field renders.\n */\nexport abstract class DateTimeFieldEngineBase<\n D,\n P extends SegmentParts,\n T extends SegmentType = SegmentType,\n> {\n private readonly config: BaseFieldEngineConfig<D>;\n\n /** The effective locale: the field's own, then the adapter's, then the runtime default. */\n protected readonly locale = computed<string | undefined>(\n () => this.config.locale() ?? this.config.adapter.locale?.() ?? undefined,\n );\n\n protected readonly cycle = computed(() =>\n resolveHourCycle(this.locale(), this.config.hourCycle()),\n );\n\n /** The lowest display hour: `0` in 24-hour and in an `h11` 12-hour locale, `1` otherwise. */\n protected readonly hourMin = computed<0 | 1>(() =>\n this.cycle() === 12 ? twelveHourMin(this.locale()) : 0,\n );\n\n /** The ordered, locale-derived spec list (editable + literals). */\n protected abstract readonly specs: Signal<readonly FieldSpec[]>;\n\n /** The entered parts, rehydrated from `source` and updated on every commit. */\n protected abstract readonly parts: WritableSignal<P>;\n\n private readonly editableOrder = computed<readonly SegmentType[]>(() =>\n this.specs()\n .filter((spec): spec is Extract<FieldSpec, { kind: 'editable' }> => spec.kind === 'editable')\n .map((spec) => spec.type),\n );\n\n private readonly periodNames = computed(() => dayPeriodNames(this.locale()));\n\n private editor!: SegmentEditor<P, T>;\n\n #ownCommit: { readonly source: D | null; readonly rehydrate: boolean } | null = null;\n\n readonly #retainedAnchor = linkedSignal<D | null, D | null>({\n source: () => this.config.source(),\n computation: () => null,\n });\n\n protected readonly anchor = computed<D | null>(\n () => this.config.source() ?? this.#retainedAnchor(),\n );\n\n #committing = false;\n\n #adopted: { readonly source: D } | null = null;\n\n /**\n * The ordered, locale-derived segments (editable + literals) to render. Each\n * entry carries the text to display: the formatted value when filled, the\n * placeholder while empty, or the literal separator.\n */\n readonly segments: Signal<readonly FieldSegment<T>[]> = computed(() => this.editor.segments());\n\n /** `true` while every editable segment is empty — no digits are entered. */\n readonly empty: Signal<boolean> = computed(() => this.editor.empty());\n\n /** The composed value of the entered parts, or `null` while any segment is empty. */\n readonly composed = computed<D | null>(() => this.composeFrom(this.parts()));\n\n constructor(config: BaseFieldEngineConfig<D>) {\n this.config = config;\n }\n\n /**\n * Builds the shared {@link SegmentEditor} and wires it to this engine's specs,\n * parts, bounds, and commit. The concrete subclass calls this at the very end\n * of its constructor, after it has assigned {@link specs} and {@link parts}.\n */\n protected initEditor(): void {\n this.editor = new SegmentEditor<P, T>({\n disabled: this.config.disabled,\n readonly: this.config.readonly,\n roving: this.config.roving,\n cycle: this.cycle,\n specs: this.specs,\n editableOrder: this.editableOrder,\n periodNames: this.periodNames,\n locale: this.locale,\n parts: () => this.parts(),\n segmentMin: (type) => this.segmentMin(type),\n segmentMax: (type) => this.segmentMax(type),\n seed: (type) => this.seed(type),\n placeholderFor: (type) => this.placeholderFor(type),\n valueText: (type) => this.valueText(type),\n commit: (next, transient) => this.commitParts(next, transient),\n settle: () => this.settle(),\n nonexistent: (type, parts) =>\n (type === 'hour' || type === 'minute') && this.wallClockShifts(parts),\n });\n }\n\n segmentValue(type: SegmentType): number | null {\n return this.editor.segmentValue(type);\n }\n\n segmentValueText(type: SegmentType): string | null {\n return this.editor.segmentValueText(type);\n }\n\n segmentDisplayText(type: SegmentType): string {\n return this.editor.segmentDisplayText(type);\n }\n\n isSegmentEmpty(type: SegmentType): boolean {\n return this.editor.isSegmentEmpty(type);\n }\n\n isFirstSegmentType(type: SegmentType): boolean {\n return this.editor.isFirstSegmentType(type);\n }\n\n registerSegment(handle: SegmentHandle): void {\n this.editor.registerSegment(handle);\n }\n\n unregisterSegment(handle: SegmentHandle): void {\n this.editor.unregisterSegment(handle);\n }\n\n focusSegment(type: SegmentType): void {\n this.editor.focusSegment(type);\n }\n\n /** Move focus to the first editable segment — the field's focus-on-error target. */\n focusFirstSegment(options?: FocusOptions): void {\n this.editor.focusFirstSegment(options);\n }\n\n typeDigit(type: SegmentType, digit: number): void {\n this.editor.typeDigit(type, digit);\n }\n\n step(type: SegmentType, delta: number): void {\n this.editor.step(type, delta);\n }\n\n goToBound(type: SegmentType, bound: 'min' | 'max'): void {\n this.editor.goToBound(type, bound);\n }\n\n setDayPeriod(period: 'am' | 'pm'): void {\n this.editor.setDayPeriod(period);\n }\n\n setDayPeriodFromKey(key: string): boolean {\n return this.editor.setDayPeriodFromKey(key);\n }\n\n clear(type: SegmentType): void {\n this.editor.clear(type);\n }\n\n backspace(type: SegmentType): void {\n this.editor.backspace(type);\n }\n\n focusSibling(type: SegmentType, step: -1 | 1): void {\n this.editor.focusSibling(type, step);\n }\n\n endTyping(next?: EventTarget | null): void {\n this.editor.endTyping(next);\n }\n\n /**\n * Discards whatever the segments hold that the value cannot represent — a\n * partly typed entry, an in-progress typing buffer, or parts held back from\n * a commit — and rehydrates them from the current `source`: its parts when\n * it holds a value, every segment empty when it is `null`.\n */\n reset(): void {\n this.#ownCommit = null;\n this.#retainedAnchor.set(null);\n this.editor.resetTyping();\n const source = untracked(this.config.source);\n this.parts.set(source === null ? this.emptyParts() : this.partsFrom(source));\n }\n\n /** Lowest accepted display value for `type`. */\n abstract segmentMin(type: SegmentType): number;\n\n /** Highest accepted display value for `type`. */\n abstract segmentMax(type: SegmentType): number;\n\n /** Base value for stepping an empty `type` on first step. */\n protected abstract seed(type: SegmentType): number;\n\n /** Placeholder shown while `type` is empty. */\n protected abstract placeholderFor(type: SegmentType): string;\n\n /** Field-specific `aria-valuetext` for `type`, or `null` for the numeric reading. */\n protected abstract valueText(type: SegmentType): string | null;\n\n /** Composes a parts record into the value, clamped to the bounds, or `null` while incomplete. */\n protected abstract composeFrom(parts: P): D | null;\n\n protected abstract partsFrom(value: D): P;\n\n /** A parts record with every segment empty. */\n protected abstract emptyParts(): P;\n\n protected abstract wallClockShifts(parts: P): boolean;\n\n protected someEditableEmpty(parts: P): boolean {\n return this.editableOrder().some((type) => parts[type] == null);\n }\n\n protected heldParts(current: D | null, previous: { readonly value: P } | undefined): P | null {\n if (previous && this.#ownCommit !== null && current === this.#ownCommit.source) {\n return previous.value;\n }\n this.#ownCommit = null;\n return null;\n }\n\n private settle(): void {\n const commit = this.#ownCommit;\n this.#ownCommit = null;\n if (commit?.rehydrate) {\n this.parts.set(this.partsFrom(commit.source!));\n }\n }\n\n /**\n * Finalizes the parts recorded by a commit before they are stored. The default\n * is the identity; the date engine overrides it to re-clamp the day on a\n * settled commit.\n */\n protected finalizeCommitParts(next: P, _transient: boolean): P {\n return next;\n }\n\n private commitParts(rawNext: P, transient: boolean): void {\n const next = this.finalizeCommitParts(rawNext, transient);\n this.parts.set(next);\n if (transient) {\n return;\n }\n const composed = this.composeFrom(next);\n const anchor = untracked(this.anchor);\n this.#adopted = null;\n this.#committing = true;\n try {\n this.config.onCommit(composed);\n } finally {\n this.#committing = false;\n }\n const source = untracked(this.config.source);\n if (source === null && anchor !== null) {\n this.#retainedAnchor.set(anchor);\n }\n const adopted = this.#takeAdopted();\n this.#ownCommit = adopted\n ? { source: adopted.source, rehydrate: true }\n : {\n source,\n rehydrate:\n source !== null &&\n composed !== null &&\n this.config.adapter.compare(source, composed) === 0,\n };\n }\n\n #takeAdopted(): { readonly source: D } | null {\n const adopted = this.#adopted;\n this.#adopted = null;\n return adopted;\n }\n\n /**\n * Records `value` as what the commit in progress resolved to, for a host that\n * normalises the commit (grafts it onto its own day, clamps it to its own\n * bounds) and hands the result back through `source`. The segments then keep\n * what was typed until the field settles, as they do when the engine clamps a\n * commit itself. Ignored outside `onCommit`.\n */\n adoptCommit(value: D): void {\n if (this.#committing) {\n this.#adopted = { source: value };\n }\n }\n}\n","import { type FieldSpec, type SegmentType } from './segment-editor';\n\n/** Date-time precision of a date field; `'day'` keeps it date-only. */\nexport type FieldGranularity = 'day' | 'hour' | 'minute' | 'second';\n\nconst DIGITS: Record<SegmentType, number> = {\n day: 2,\n month: 2,\n year: 4,\n hour: 2,\n minute: 2,\n second: 2,\n dayPeriod: 0,\n};\n\n/**\n * 1 Feb 2000: distinct day and month, so a locale that reuses a digit cannot\n * mask the part order. Only the `type` of each formatted part is read.\n */\nfunction referenceDate(): Date {\n return new Date(2000, 1, 1);\n}\n\n/**\n * 1 Feb 2000, 1:23:45 PM: distinct day / month and hour / minute / second, in\n * the afternoon so the `dayPeriod` part is present to read back.\n */\nfunction referenceDateTime(): Date {\n return new Date(2000, 1, 1, 13, 23, 45);\n}\n\n/**\n * Derives the ordered segment list for a day-granularity date field from the\n * runtime locale, using `Intl.DateTimeFormat(...).formatToParts`. The visible\n * order of day / month / year (and the separator characters between them)\n * follows the locale — `MM/DD/YYYY` for `en-US`, `DD.MM.YYYY` for `de-DE`,\n * `YYYY/MM/DD` for `ja-JP` — so the field never has to parse ambiguous\n * free text.\n *\n * Pure: the same `locale` always yields the same list, and it touches no\n * signals or DOM. A fixed reference date with distinct day / month values is\n * formatted purely to read back the part order; its actual value never\n * surfaces.\n *\n * @param locale BCP 47 locale, or `undefined` for the runtime default.\n */\nexport function buildSegments(locale: string | undefined): readonly FieldSpec[] {\n const parts = new Intl.DateTimeFormat(locale, {\n calendar: 'gregory',\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n }).formatToParts(referenceDate());\n\n const segments: FieldSpec[] = [];\n for (const part of parts) {\n switch (part.type) {\n case 'day':\n case 'month':\n case 'year':\n segments.push({ kind: 'editable', type: part.type, digits: DIGITS[part.type] });\n break;\n case 'literal':\n segments.push({ kind: 'literal', literal: part.value });\n break;\n default:\n break;\n }\n }\n return segments;\n}\n\n/**\n * Derives the ordered segment list for a date(-time) field. At\n * `granularity === 'day'` this is exactly {@link buildSegments} (date-only,\n * byte-for-byte). At a finer granularity it appends the locale-ordered time\n * segments (and the date↔time separator) by formatting a reference date-time\n * with both date and time options in a single `Intl.DateTimeFormat` pass, so\n * the order of every part — and whether an AM/PM `dayPeriod` is present —\n * follows the locale and the resolved hour cycle.\n *\n * Pure: the same arguments always yield the same list.\n *\n * @param locale BCP 47 locale, or `undefined` for the runtime default.\n * @param granularity Smallest editable unit; `'day'` stays date-only.\n * @param hourCycle Resolved hour cycle (`12` shows AM/PM, `24` does not).\n */\nexport function buildDateTimeSegments(\n locale: string | undefined,\n granularity: FieldGranularity,\n hourCycle: 12 | 24,\n): readonly FieldSpec[] {\n if (granularity === 'day') {\n return buildSegments(locale);\n }\n const options: Intl.DateTimeFormatOptions = {\n calendar: 'gregory',\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n hour12: hourCycle === 12,\n };\n if (granularity !== 'hour') {\n options.minute = '2-digit';\n }\n if (granularity === 'second') {\n options.second = '2-digit';\n }\n\n const parts = new Intl.DateTimeFormat(locale, options).formatToParts(referenceDateTime());\n const segments: FieldSpec[] = [];\n for (const part of parts) {\n switch (part.type) {\n case 'day':\n case 'month':\n case 'year':\n case 'hour':\n case 'minute':\n case 'second':\n case 'dayPeriod':\n segments.push({ kind: 'editable', type: part.type, digits: DIGITS[part.type] });\n break;\n case 'literal':\n segments.push({ kind: 'literal', literal: part.value });\n break;\n default:\n break;\n }\n }\n return segments;\n}\n","import type { DateAdapter, TimeCapableDateAdapter } from 'forty-cdk/date-adapter';\nimport { assertTimeCapable, compareDateOf } from './date-adapter';\n\n/**\n * The granularity at which a date control serializes its value: a bare calendar\n * day, or a day plus a wall-clock time down to the hour, minute, or second.\n */\nexport type DateSerializeGranularity = 'day' | 'hour' | 'minute' | 'second';\n\n/**\n * The granularity at which a time control serializes its value: a bare hour, or\n * an hour plus minutes, or down to the second.\n */\nexport type TimeSerializeGranularity = 'hour' | 'minute' | 'second';\n\n/**\n * Clamps `date` into the inclusive `[min, max]` range, returning the nearer\n * bound when `date` falls outside and `date` itself when it is within (or both\n * bounds are `null`). Comparison defaults to {@link DateAdapter.compare} (the\n * full instant); pass `compare` to clamp on a different ordering — the calendar\n * grid clamps day-granularly via `compareDateOf`, the form controls clamp on the\n * full instant via `adapter.compare`.\n *\n * @typeParam D The adapter's immutable date representation.\n * @param adapter The active date adapter (supplies the default comparator).\n * @param date The date to clamp.\n * @param min The lower bound (inclusive), or `null` for unbounded.\n * @param max The upper bound (inclusive), or `null` for unbounded.\n * @param compare Comparator returning `< 0` / `0` / `> 0`; defaults to\n * `adapter.compare`.\n */\nexport function clampToBounds<D>(\n adapter: DateAdapter<D>,\n date: D,\n min: D | null,\n max: D | null,\n compare: (a: D, b: D) => number = (a, b) => adapter.compare(a, b),\n): D {\n if (min !== null && compare(date, min) < 0) {\n return min;\n }\n if (max !== null && compare(date, max) > 0) {\n return max;\n }\n return date;\n}\n\n/**\n * The day a date-time picker grafts a committed time onto: its current `value`,\n * or, before any day is picked, today clamped day-granularly into `[min, max]` —\n * the day the projected calendar focuses when the value is empty. The caller\n * still clamps the composed instant, so a time outside the bounds on the\n * boundary day is clamped to the bound.\n *\n * @typeParam D The adapter's immutable date representation.\n * @param adapter The active date adapter.\n * @param value The picker's current value, or `null` when no day is picked.\n * @param min The lower bound (inclusive), or `null` for unbounded.\n * @param max The upper bound (inclusive), or `null` for unbounded.\n */\nexport function timeGraftBaseDay<D>(\n adapter: DateAdapter<D>,\n value: D | null,\n min: D | null,\n max: D | null,\n): D {\n return (\n value ??\n clampToBounds(adapter, adapter.today(), min, max, (a, b) => compareDateOf(adapter, a, b))\n );\n}\n\n/**\n * Serializes `date` to the ISO 8601 string the date controls write into their\n * native hidden input: `YYYY-MM-DD` at day granularity, `YYYY-MM-DDTHH:mm` at\n * hour / minute granularity, and `YYYY-MM-DDTHH:mm:ss` at second granularity.\n * At any non-day granularity the adapter must be time-capable; a day-only\n * adapter throws via {@link assertTimeCapable} with `piece` in the message,\n * reported under `scope`.\n *\n * @typeParam D The adapter's immutable date representation.\n * @param adapter The active date adapter.\n * @param date The value to serialize.\n * @param granularity The serialization granularity.\n * @param piece Name of the calling directive, used in the time-capability error.\n * @param options `scope` is the caller's entry point, which the time-capability\n * error reports under. It is required because this branch can be the first\n * report a consumer reads: a picker in the trigger anatomy has no projected\n * field to reject the adapter earlier.\n */\nexport function serializeISODate<D>(\n adapter: DateAdapter<D>,\n date: D,\n granularity: DateSerializeGranularity,\n piece: string,\n options: { readonly scope: string },\n): string {\n const year = String(adapter.getYear(date)).padStart(4, '0');\n const month = String(adapter.getMonth(date)).padStart(2, '0');\n const day = String(adapter.getDate(date)).padStart(2, '0');\n const isoDate = `${year}-${month}-${day}`;\n if (granularity === 'day') {\n return isoDate;\n }\n const time = assertTimeCapable(adapter, piece, options);\n const hour = String(time.getHours(date)).padStart(2, '0');\n const minute = String(time.getMinutes(date)).padStart(2, '0');\n if (granularity === 'second') {\n const second = String(time.getSeconds(date)).padStart(2, '0');\n return `${isoDate}T${hour}:${minute}:${second}`;\n }\n return `${isoDate}T${hour}:${minute}`;\n}\n\n/**\n * Serializes the wall-clock time of `date` to the ISO 8601 partial-time string\n * the time controls write into their native hidden input: `HH` at hour\n * granularity, `HH:mm` at minute granularity, and `HH:mm:ss` at second\n * granularity.\n *\n * @typeParam D The adapter's immutable date-time representation.\n * @param adapter The active time-capable date adapter.\n * @param date The value whose time-of-day is serialized.\n * @param granularity The serialization granularity.\n */\nexport function serializeISOTime<D>(\n adapter: TimeCapableDateAdapter<D>,\n date: D,\n granularity: TimeSerializeGranularity,\n): string {\n const hour = String(adapter.getHours(date)).padStart(2, '0');\n if (granularity === 'hour') {\n return hour;\n }\n const minute = String(adapter.getMinutes(date)).padStart(2, '0');\n if (granularity === 'minute') {\n return `${hour}:${minute}`;\n }\n const second = String(adapter.getSeconds(date)).padStart(2, '0');\n return `${hour}:${minute}:${second}`;\n}\n\n/**\n * Grafts the wall-clock time of `source` onto the calendar day of `day`,\n * returning a fresh date that keeps `day`'s date and carries `source`'s\n * hour / minute / second. Used when composing a date selection with a separately\n * edited time-of-day.\n *\n * @typeParam D The adapter's immutable date-time representation.\n * @param adapter The active time-capable date adapter.\n * @param day The date contributing the calendar day.\n * @param source The date contributing the wall-clock time.\n */\nexport function composeWithTime<D>(adapter: TimeCapableDateAdapter<D>, day: D, source: D): D {\n return adapter.setTime(\n day,\n adapter.getHours(source),\n adapter.getMinutes(source),\n adapter.getSeconds(source),\n );\n}\n\n/**\n * Whether `hours:minutes` on `day` is a wall-clock time the day skips, such as\n * the hour a spring-forward DST transition removes: the adapter normalizes it to\n * a different time.\n *\n * @typeParam D The adapter's immutable date-time representation.\n * @param adapter The active time-capable date adapter.\n * @param day The calendar day the time falls on.\n * @param hours The wall-clock hour (0-23).\n * @param minutes The wall-clock minute.\n */\nexport function shiftsWallClock<D>(\n adapter: TimeCapableDateAdapter<D>,\n day: D,\n hours: number,\n minutes: number,\n): boolean {\n const probe = adapter.setTime(day, hours, minutes, 0);\n return adapter.getHours(probe) !== hours || adapter.getMinutes(probe) !== minutes;\n}\n\n/**\n * The fixed, DST-stable sentinel date (`2000-01-01`) a time control anchors a\n * wall-clock time to when it has no committed date of its own, so a time always\n * round-trips through the adapter without an ambiguous-hour DST shift.\n *\n * @typeParam D The adapter's immutable date representation.\n * @param adapter The active date adapter.\n */\nexport function timeSentinel<D>(adapter: DateAdapter<D>): D {\n return adapter.createDate(2000, 1, 1);\n}\n\n/**\n * Reduces the wall-clock time of `date` to seconds-of-day (`hours * 3600 +\n * minutes * 60 + seconds`), ignoring the calendar day. Used to compare or clamp\n * two dates by their time-of-day alone.\n *\n * @typeParam D The adapter's immutable date-time representation.\n * @param adapter The active time-capable date adapter.\n * @param date The value whose time-of-day is reduced.\n */\nexport function secondsOfDay<D>(adapter: TimeCapableDateAdapter<D>, date: D): number {\n return adapter.getHours(date) * 3600 + adapter.getMinutes(date) * 60 + adapter.getSeconds(date);\n}\n","import { computed, linkedSignal, type Signal } from '@angular/core';\n\nimport type { DateAdapter, TimeCapableDateAdapter } from 'forty-cdk/date-adapter';\nimport { assertTimeCapable } from './date-adapter';\nimport { type BaseFieldEngineConfig, DateTimeFieldEngineBase } from './field-engine-base';\nimport { buildDateTimeSegments, type FieldGranularity } from './date-segments';\nimport { type FieldSpec, type SegmentType } from './segment-editor';\nimport { clampToBounds, composeWithTime, shiftsWallClock } from './serialize';\n\n/** Internal per-part state: the entered value for each editable segment, hour as 0-23. */\nexport interface DateTimeParts {\n day: number | null;\n month: number | null;\n year: number | null;\n hour: number | null;\n minute: number | null;\n second: number | null;\n dayPeriod: number | null;\n}\n\n/**\n * The reactive configuration a segmented date(-time) field supplies to its\n * {@link DateFieldEngine}. The shared `signal`-driven inputs (granularity,\n * hour cycle, locale, placeholder, bounds, disabled / read-only) plus the\n * authoritative `source` value and the `onCommit` sink let the engine derive\n * the locale-ordered segments, the entered parts, and the composed value\n * without owning any directive of its own.\n *\n * @typeParam D The adapter's immutable date (or date-time) type.\n */\nexport interface DateFieldEngineConfig<D> extends BaseFieldEngineConfig<D> {\n /** The active date adapter (shared with `ForCalendar`). */\n readonly adapter: DateAdapter<D>;\n /** Date-time precision; `'day'` keeps the field date-only. */\n readonly granularity: Signal<FieldGranularity>;\n /** Per-segment placeholder overrides shown while empty. */\n readonly placeholder: Signal<Partial<Record<SegmentType, string>>>;\n /** Minimum selectable date (inclusive), or `null` for unbounded. */\n readonly minDate: Signal<D | null>;\n /** Maximum selectable date (inclusive), or `null` for unbounded. */\n readonly maxDate: Signal<D | null>;\n /** Name of the owning directive, used in the time-capability error message. */\n readonly piece: string;\n /**\n * Entry point that error reports under, e.g. `'date-field'`. The engine is\n * shared, but the consumer who combined a time `granularity` with a day-only\n * adapter wrote a field, so the prefix must name theirs.\n */\n readonly scope: string;\n}\n\n/**\n * Year used to resolve day ranges (Feb length) while the year segment is empty.\n * A leap year so an empty-year February admits day 29: the day\n * segment reports `aria-valuemax=\"29\"`, and February 29 can be typed in the\n * natural year-last locale order (`M/d/y`, `d.M.y`) before the year settles. The\n * clamp down to 28 happens only once an actually-non-leap year is committed.\n */\nconst RESOLVER_YEAR = 2000;\n\n/**\n * The shared date(-time) field engine backing `ForDateField` and each endpoint\n * of `ForDateRangeField`. It owns everything a segmented date field needs on\n * top of the generic {@link SegmentEditor}: the locale-ordered spec list, the\n * resolved hour cycle, the entered {@link DateTimeParts} (rehydrated from the\n * configured `source`), the date-specific segment bounds / today-seed / month\n * `aria-valuetext` / day re-clamp, and the create-and-clamp compose. The owning\n * directive supplies the reactive {@link DateFieldEngineConfig} and decides what\n * to do with each composed value through `onCommit` (a single field writes its\n * own `value`; the range field reports the endpoint up to the root).\n *\n * Constructed directly (`new DateFieldEngine(config)`); it holds no injection\n * context, mirroring how {@link SegmentEditor} and `CalendarRangeSelection` are\n * lifted out of their roots.\n *\n * @typeParam D The adapter's immutable date (or date-time) type.\n */\nexport class DateFieldEngine<D> extends DateTimeFieldEngineBase<D, DateTimeParts> {\n readonly #config: DateFieldEngineConfig<D>;\n\n /**\n * The locale-ordered segment specs. A granularity finer than a day builds\n * hour / minute / second segments, so a day-only adapter throws here — at the\n * derivation that asked for a time segment, not from a scheduler callback.\n */\n protected readonly specs = computed<readonly FieldSpec[]>(() => {\n const granularity = this.#config.granularity();\n if (granularity !== 'day') {\n assertTimeCapable(this.#config.adapter, this.#config.piece, { scope: this.#config.scope });\n }\n return buildDateTimeSegments(this.locale(), granularity, this.cycle());\n });\n\n /**\n * The entered parts. A `linkedSignal` keyed on `source`: a non-null write\n * (consumer, `[formField]`, or a settled field) rehydrates the segments from\n * the date, while the value the field itself just committed keeps the parts\n * as entered until focus leaves its segments, so a clamped intermediate never\n * rewrites the segments still being edited. A `null` transition is\n * disambiguated by the prior parts: an *internal* edit clearing one segment\n * always leaves the others, so `previous` still carries a filled part and is\n * preserved (clearing the day never wipes the month / year); an *external*\n * reset of a complete value leaves `previous` fully filled, so the field\n * clears.\n */\n protected readonly parts = linkedSignal<D | null, DateTimeParts>({\n source: () => this.#config.source(),\n computation: (current, previous) => {\n const held = this.heldParts(current, previous);\n if (held !== null) {\n return held;\n }\n if (current !== null) {\n return this.partsFrom(current);\n }\n const prior = previous?.value;\n if (prior && this.someEditableEmpty(prior)) {\n return prior;\n }\n return this.emptyParts();\n },\n });\n\n constructor(config: DateFieldEngineConfig<D>) {\n super(config);\n this.#config = config;\n this.initEditor();\n }\n\n segmentMin(type: SegmentType): number {\n if (type === 'hour') {\n return this.hourMin();\n }\n if (type === 'minute' || type === 'second' || type === 'dayPeriod') {\n return 0;\n }\n return 1;\n }\n\n segmentMax(type: SegmentType): number {\n switch (type) {\n case 'month':\n return 12;\n case 'year':\n return 9999;\n case 'hour':\n return this.cycle() === 12 ? this.hourMin() + 11 : 23;\n case 'minute':\n case 'second':\n return 59;\n case 'dayPeriod':\n return 1;\n default: {\n const parts = this.parts();\n const probe = this.#config.adapter.createDate(\n parts.year ?? RESOLVER_YEAR,\n parts.month ?? 1,\n 1,\n );\n return this.#config.adapter.getDaysInMonth(probe);\n }\n }\n }\n\n /** The active adapter, narrowed to a time-capable one; throws when it is day-only. */\n #time(): TimeCapableDateAdapter<D> {\n return assertTimeCapable(this.#config.adapter, this.#config.piece, {\n scope: this.#config.scope,\n });\n }\n\n #preserveSourceTime(day: D): D {\n const anchor = this.anchor();\n if (anchor === null || this.#config.adapter.supportsTime?.() !== true) {\n return day;\n }\n return composeWithTime(\n assertTimeCapable(this.#config.adapter, this.#config.piece, { scope: this.#config.scope }),\n day,\n anchor,\n );\n }\n\n /** Field-specific `aria-valuetext`: the empty marker or the localized month name. */\n protected valueText(type: SegmentType): string | null {\n if (this.isSegmentEmpty(type)) {\n return this.#config.emptySegmentText();\n }\n if (type !== 'month') {\n return null;\n }\n const month = this.parts().month;\n if (month === null) {\n return null;\n }\n // Route the month name through the adapter's `format` so it tracks the\n // adapter's calendar system rather than assuming Gregorian month numbering.\n // A probe date built with `createDate` maps the 1-12 number to a localized\n // long name without involving the entered value.\n return this.#config.adapter.format(\n this.#config.adapter.createDate(RESOLVER_YEAR, month, 1),\n { month: 'long' },\n this.locale(),\n );\n }\n\n /** Base value for stepping an empty segment: date parts from today, time parts from their minimum. */\n protected seed(type: SegmentType): number {\n if (type === 'hour') {\n return this.#toInternalHour(this.segmentMin('hour'));\n }\n if (type === 'minute' || type === 'second' || type === 'dayPeriod') {\n return 0;\n }\n const adapter = this.#config.adapter;\n const today = adapter.today();\n const base =\n type === 'day'\n ? adapter.getDate(today)\n : type === 'month'\n ? adapter.getMonth(today)\n : adapter.getYear(today);\n return Math.min(this.segmentMax(type), Math.max(this.segmentMin(type), base));\n }\n\n /** Converts a 12-hour display hour to a 0-23 hour, preserving the entered AM/PM. */\n #toInternalHour(display: number): number {\n if (this.cycle() === 24) {\n return display;\n }\n const parts = this.parts();\n const pm =\n parts.dayPeriod !== null ? parts.dayPeriod === 1 : parts.hour !== null && parts.hour >= 12;\n const base = display % 12;\n return pm ? base + 12 : base;\n }\n\n protected placeholderFor(type: SegmentType): string {\n const override = this.#config.placeholder()[type];\n if (override) {\n return override;\n }\n switch (type) {\n case 'day':\n return 'dd';\n case 'month':\n return 'mm';\n case 'year':\n return 'yyyy';\n case 'hour':\n return 'hh';\n case 'minute':\n return 'mm';\n case 'second':\n return 'ss';\n default:\n return '--';\n }\n }\n\n protected partsFrom(value: D): DateTimeParts {\n const adapter = this.#config.adapter;\n const parts: DateTimeParts = {\n day: adapter.getDate(value),\n month: adapter.getMonth(value),\n year: adapter.getYear(value),\n hour: null,\n minute: null,\n second: null,\n dayPeriod: null,\n };\n if (this.#config.granularity() !== 'day') {\n const time = this.#time();\n parts.hour = time.getHours(value);\n parts.minute = time.getMinutes(value);\n parts.second = time.getSeconds(value);\n parts.dayPeriod = time.getHours(value) >= 12 ? 1 : 0;\n }\n return parts;\n }\n\n protected emptyParts(): DateTimeParts {\n return {\n day: null,\n month: null,\n year: null,\n hour: null,\n minute: null,\n second: null,\n dayPeriod: null,\n };\n }\n\n protected wallClockShifts(parts: DateTimeParts): boolean {\n if (parts.hour === null || parts.day === null || parts.month === null || parts.year === null) {\n return false;\n }\n const day = this.#config.adapter.createDate(parts.year, parts.month, parts.day);\n return shiftsWallClock(this.#time(), day, parts.hour, parts.minute ?? 0);\n }\n\n /**\n * Re-clamps `day` to the resolved month/year length so the day segment's\n * `aria-valuenow` never exceeds its `aria-valuemax` after stepping the month\n * or year (e.g. day 31 + step to February → 28/29). Only ever shrinks the\n * day; an empty day is left untouched.\n */\n #clampDay(parts: DateTimeParts): DateTimeParts {\n if (parts.day === null) {\n return parts;\n }\n const adapter = this.#config.adapter;\n const probe = adapter.createDate(parts.year ?? RESOLVER_YEAR, parts.month ?? 1, 1);\n const maxDay = adapter.getDaysInMonth(probe);\n if (parts.day <= maxDay) {\n return parts;\n }\n return { ...parts, day: maxDay };\n }\n\n /**\n * Composes a parts record into the value, clamped to the bounds, or `null`\n * while any visible segment, the AM/PM one included, is empty.\n */\n protected composeFrom(parts: DateTimeParts): D | null {\n if (this.someEditableEmpty(parts)) {\n return null;\n }\n const granularity = this.#config.granularity();\n const needHour = granularity !== 'day';\n const needMinute = granularity === 'minute' || granularity === 'second';\n const needSecond = granularity === 'second';\n let created = this.#config.adapter.createDate(parts.year!, parts.month!, parts.day!);\n if (needHour) {\n created = this.#time().setTime(\n created,\n parts.hour!,\n needMinute ? parts.minute! : 0,\n needSecond ? parts.second! : 0,\n );\n } else {\n created = this.#preserveSourceTime(created);\n }\n return clampToBounds(\n this.#config.adapter,\n created,\n this.#config.minDate(),\n this.#config.maxDate(),\n );\n }\n\n protected override finalizeCommitParts(next: DateTimeParts, transient: boolean): DateTimeParts {\n return transient ? next : this.#clampDay(next);\n }\n}\n","import { Directive } from '@angular/core';\n\n/**\n * Shared base for the decorative separator directives `[forDateFieldLiteral]`\n * and `[forTimeFieldLiteral]`. It marks the host `aria-hidden` and keeps it out\n * of the tab order, so assistive tech reads only the spinbutton segments. The\n * separator characters come from the root's locale-ordered `segments()` list.\n *\n * `@Directive` without a `selector` so the public subclasses declare the\n * concrete `[forXxxFieldLiteral]` selector and `exportAs`; the `aria-hidden`\n * host binding is inherited.\n */\n@Directive({\n host: {\n 'aria-hidden': 'true',\n },\n})\nexport abstract class ForDateTimeLiteralBase {}\n","import { InjectionToken, type Signal } from '@angular/core';\n\n/**\n * The picker every source projected into it defers to: a `[forCalendar]`, a\n * `[forTimeField]` or a `[forTimePicker]` is read-only or disabled whenever its\n * picker is, on top of its own inputs.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\nexport interface PickerSourceHost {\n /** The picker's effective disabled state. */\n readonly effectiveDisabled: Signal<boolean>;\n /** The picker's read-only state. */\n readonly readonly: Signal<boolean>;\n}\n\n/**\n * Token `[forDatePicker]` and `[forDateRangePicker]` provide so the calendar and\n * the time source projected into them can find them.\n */\nexport const FOR_PICKER_SOURCE_HOST = new InjectionToken<PickerSourceHost>(\n 'FOR_PICKER_SOURCE_HOST',\n);\n","import { signal, type WritableSignal } from '@angular/core';\n\n/**\n * Marks at most one key at a time, read per key: {@link has} is reactive, and\n * {@link move} notifies only the reads of the key losing the mark and of the\n * key gaining it, so a group of N items that each read their own key pays O(1)\n * per move instead of O(N).\n *\n * Internal core tier — used by the roving and pointer trackers, with no semver\n * guarantee.\n */\nexport class KeyedFlag<K extends object> {\n readonly #slots = new WeakMap<K, WritableSignal<boolean>>();\n\n #current: K | null = null;\n\n /** The marked key, or `null`. Not reactive. */\n get current(): K | null {\n return this.#current;\n }\n\n /** Whether `key` holds the mark. Reactive per key. */\n has(key: K): boolean {\n return this.#slot(key)();\n }\n\n /** Hand the mark to `next`, or clear it with `null`. */\n move(next: K | null): void {\n const previous = this.#current;\n if (previous === next) {\n return;\n }\n this.#current = next;\n if (previous !== null) {\n this.#slot(previous).set(false);\n }\n if (next !== null) {\n this.#slot(next).set(true);\n }\n }\n\n #slot(key: K): WritableSignal<boolean> {\n let slot = this.#slots.get(key);\n if (slot === undefined) {\n slot = signal(this.#current === key);\n this.#slots.set(key, slot);\n }\n return slot;\n }\n}\n","import { computed, type Signal, signal, untracked } from '@angular/core';\n\nimport type { HostRovingItemHandle } from './host-roving-context';\n\n/**\n * Whether a disabled item of a roving group holds DOM focus, the state in which\n * every item of the group yields its tab stop so `Tab` and `Shift+Tab` leave\n * the group from that item. Fed through {@link noteFocus}.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\nexport class RovingFocusYield {\n /** The element last reported to {@link noteFocus}; a plain field so a focus move notifies nothing. */\n #focused: Element | null = null;\n\n /**\n * Set by the first {@link noteFocus} naming an element. Until then\n * {@link yields} does not track the items, so a group focus never entered\n * never reads its item list.\n */\n #tracksItems = false;\n\n /** Bumped by a {@link noteFocus} that changes {@link yields}, the only way a focus move reaches it. */\n readonly #epoch = signal(0);\n\n readonly #items: () => readonly HostRovingItemHandle[];\n\n /**\n * `true` while the element last reported to {@link noteFocus} is a disabled\n * item. Notifies its readers only when that answer changes, not on every\n * focus move inside the group.\n */\n readonly yields: Signal<boolean>;\n\n constructor(items: () => readonly HostRovingItemHandle[]) {\n this.#items = items;\n this.yields = computed(() => {\n this.#epoch();\n if (this.#tracksItems) {\n for (const item of items()) {\n item.disabled();\n }\n }\n return untracked(() => this.#holdsDisabled());\n });\n }\n\n /** Report the element holding DOM focus inside the group, or `null` once focus left it. */\n noteFocus(el: Element | null): void {\n untracked(() => {\n if (this.#focused === el) {\n return;\n }\n const before = this.yields();\n this.#focused = el;\n const subscribes = el !== null && !this.#tracksItems;\n if (subscribes) {\n this.#tracksItems = true;\n }\n if (subscribes || this.#holdsDisabled() !== before) {\n this.#epoch.update((epoch) => epoch + 1);\n }\n });\n }\n\n #holdsDisabled(): boolean {\n const focused = this.#focused;\n return (\n focused !== null && this.#items().some((item) => item.host === focused && item.disabled())\n );\n }\n}\n","import { computed, linkedSignal, type Signal, signal, untracked } from '@angular/core';\n\nimport { KeyedFlag } from '../keyed-flag/keyed-flag';\nimport type { HostRovingItemHandle } from './host-roving-context';\nimport { RovingFocusYield } from './roving-focus-yield';\n\n/**\n * Tracks the single \"active\" element of a roving-tabindex group: the one\n * with `tabindex=0`, while every other registered item gets `tabindex=-1`.\n * The active item is the entry point for `Tab` into the group; arrow-key\n * navigation moves it (the consumer wires this with `KeyboardNavigation`).\n *\n * The utility does not handle key events. Its job is to expose\n * a reactive `tabindexFor(el)` for host bindings on each item, plus\n * `setActive` / `focusActive` for the consumer.\n *\n * The active pointer is **self-healing** on read: a stale active element —\n * one that has detached from the document, or carries `disabled` /\n * `aria-disabled` (every primitive reflects its disabled state to one of\n * those attributes) — is discounted by every call to `hasActive` /\n * `tabindexFor`, so the consumer's first-enabled fallback re-engages and the\n * group keeps exactly one tab stop even before reconciliation settles. A\n * reactive read (a `computed`, a host binding) re-runs only when a signal it\n * read changes, and detaching an element changes none, so a container calls\n * {@link unregister} when an item leaves the group.\n *\n * When constructed with an `items` producer, the active pointer is also\n * **reconciled reactively**: whenever the active host leaves the group's\n * usable set (unregisters, becomes disabled, or detaches), `active()` is\n * re-seeded. The `fallback` option chooses how: `'none'` (default) nulls it\n * so each item's first-enabled fallback re-engages (pull-based, for a\n * container whose item tabindex derives from {@link hasActive}), while\n * `'nearest'` promotes the closest usable handle before the departed one in\n * the previous item order, else the closest after it, else the first enabled\n * (push-based, for a container whose item tabindex reads {@link active} and\n * needs a concrete owner rather than a null pointer, e.g. Tree). Under\n * `'nearest'` the departed pointer is kept, so a host that is re-enabled\n * reclaims the tab stop. Omitting `items` yields a pass-through of the raw\n * pointer for consumers that own no roving collection (date-field /\n * time-field).\n *\n * While a disabled item of the `items` producer holds DOM focus, as reported\n * through {@link noteFocus}, every item **yields**: {@link tabindexFor} is `-1`\n * for all of them and {@link hasActive} reports that the tracker owns the tab\n * stop, so the group holds none and `Tab` / `Shift+Tab` leave it.\n *\n * The per-item reads, {@link isActive}, {@link tabindexFor} and {@link hasActive},\n * cost O(1) per move: moving the active element between two usable items\n * notifies only the reads for those two items, so a group of N items does not\n * re-evaluate N item bindings per arrow key. {@link active} stays a group-wide\n * read for the container's own handlers.\n *\n * Construct directly with `new RovingTabindex()` — there is no internal\n * state requiring an injection context or `DestroyRef` cleanup.\n */\nexport class RovingTabindex {\n readonly #rawActive = signal<HTMLElement | null>(null);\n\n /** Marks the element {@link setActive} last named, read per item by {@link isActive}. */\n readonly #raw = new KeyedFlag<HTMLElement>();\n\n /**\n * Bumped by a write that changes {@link #settled}'s answer, the only way a\n * change of the raw pointer reaches it, so a move that leaves the answer as\n * it was notifies none of its readers.\n */\n readonly #epoch = signal(0);\n\n /**\n * Set by the first write naming an element. Until then {@link #settled} does\n * not track the items, so a group nothing has been focused in never reads\n * its item list.\n */\n #tracksItems = false;\n\n /**\n * The group-wide facts every item reads: whether the tracker owns the tab\n * stop, and the element promoted in place of an unusable raw pointer. Tracks\n * the items and their `disabled` state, which can move the reconciled\n * pointer without a write, and reads the raw pointer untracked.\n */\n readonly #settled: Signal<Settled>;\n\n readonly #keepsDeparted: boolean;\n\n readonly #focusYield: RovingFocusYield | null;\n\n readonly #active: Signal<HTMLElement | null>;\n\n /**\n * The active element, or `null`. Follows the last {@link setActive} call,\n * reconciled away from a host that has left the usable set when an `items`\n * producer is supplied (otherwise verbatim). Use it for \"is this the\n * focused candidate\" styling (`data-highlighted`). For the tab-stop gate,\n * prefer {@link hasActive}, which additionally discounts a stale active on\n * read.\n */\n readonly active: Signal<HTMLElement | null>;\n\n constructor(\n items?: () => readonly HostRovingItemHandle[],\n options: { fallback?: 'none' | 'nearest' } = {},\n ) {\n const fallback = options.fallback ?? 'none';\n this.#keepsDeparted = fallback === 'nearest';\n this.#active = linkedSignal<ActiveSource, HTMLElement | null>({\n source: () => {\n const raw = this.#rawActive();\n return { items: items && raw !== null ? items() : null, raw };\n },\n computation: ({ items: list, raw }, previous) => {\n if (list === null || raw === null) {\n return raw;\n }\n const handle = list.find((item) => item.host === raw);\n if (handle && !handle.disabled() && raw.isConnected) {\n return raw;\n }\n if (fallback === 'none') {\n return null;\n }\n const anchor = previous?.source.raw === raw ? (previous.value ?? raw) : raw;\n return nearestUsable(list, previous?.source.items ?? null, anchor);\n },\n });\n this.active = this.#active;\n this.#focusYield = items ? new RovingFocusYield(items) : null;\n this.#settled = computed(\n () => {\n this.#epoch();\n if (items && this.#tracksItems) {\n for (const item of items()) {\n item.disabled();\n }\n }\n return untracked(() => this.#settle());\n },\n { equal: sameSettled },\n );\n }\n\n /**\n * Whether `el` is the active element, as {@link active} reports it. Reactive\n * per element: a move notifies only the reads for the element losing the\n * pointer and the element gaining it.\n */\n isActive(el: HTMLElement): boolean {\n if (this.#raw.has(el)) {\n return this.#active() === el;\n }\n return this.#settled().promoted === el;\n }\n\n /**\n * Whether the tracker currently owns the tab stop: a usable active element\n * does, and so does a group whose items yield while a disabled item holds\n * focus. `false` when nothing is active **or** the active element is stale\n * (detached / disabled) at the time of the call, signalling the consumer to\n * fall back to its first-enabled entry point. Reactive — wire the per-item\n * `tabindex` gate to this rather than `active() !== null`.\n */\n hasActive(): boolean {\n if (this.#focusYield?.yields() === true) {\n return true;\n }\n if (!this.#settled().owns) {\n return false;\n }\n const el = untracked(this.#active);\n return el !== null && !isStale(el);\n }\n\n /**\n * Whether {@link active} is non-null, without {@link hasActive}'s discount of\n * a stale element. Notifies its readers only when that answer changes.\n */\n holdsActive(): boolean {\n return this.#settled().present;\n }\n\n /**\n * Returns the tabindex value for `el`: `0` if it is the active element,\n * `-1` otherwise. Reactive — wire into a host binding.\n *\n * If no element is active yet (or the active element is stale), or the items\n * yield to a focused disabled item, returns `-1` for everything. The container directive is responsible for promoting\n * one item (typically the first enabled one) to active on init.\n */\n tabindexFor(el: HTMLElement): 0 | -1 {\n if (this.#focusYield?.yields() === true) {\n return -1;\n }\n return this.isActive(el) && !isStale(el) ? 0 : -1;\n }\n\n /**\n * Report the element holding DOM focus inside the group, or `null` once focus\n * has left it. Call it from the group host's `focusin` and `focusout`; while\n * it names a disabled item, every item yields the tab stop.\n */\n noteFocus(el: Element | null): void {\n this.#focusYield?.noteFocus(el);\n }\n\n setActive(el: HTMLElement | null): void {\n this.#write(el);\n }\n\n /**\n * Drop `el` as the active element if it currently is, resetting the tracker\n * to \"no active\" so the first-enabled fallback reclaims the tab stop.\n * No-op when `el` is not the active element. Containers call this when an\n * item unregisters (`DestroyRef.onDestroy`) so a removed host never lingers\n * as the entry point. No-op under `fallback: 'nearest'`, which re-seeds from\n * the position the removed host held instead.\n */\n unregister(el: HTMLElement): void {\n if (!this.#keepsDeparted && this.#active() === el) {\n this.#write(null);\n }\n }\n\n /**\n * Move active to `el` and immediately focus it. Convenience for arrow-key\n * handlers.\n */\n focusActive(el?: HTMLElement | null): void {\n const target = el ?? this.#active();\n if (!target) {\n return;\n }\n if (target !== this.#active()) {\n this.#write(target);\n }\n target.focus();\n }\n\n #write(next: HTMLElement | null): void {\n untracked(() => {\n if (this.#rawActive() === next) {\n return;\n }\n const before = this.#settled();\n this.#raw.move(next);\n this.#rawActive.set(next);\n const after = this.#settle();\n const subscribes = next !== null && !this.#tracksItems;\n if (subscribes) {\n this.#tracksItems = true;\n }\n if (subscribes || !sameSettled(before, after)) {\n this.#epoch.update((epoch) => epoch + 1);\n }\n });\n }\n\n #settle(): Settled {\n const raw = this.#rawActive();\n const active = this.#active();\n return {\n present: active !== null,\n owns: active !== null && !isStale(active),\n promoted: active === raw ? null : active,\n };\n }\n}\n\ninterface Settled {\n readonly present: boolean;\n readonly owns: boolean;\n readonly promoted: HTMLElement | null;\n}\n\nfunction sameSettled(a: Settled, b: Settled): boolean {\n return a.present === b.present && a.owns === b.owns && a.promoted === b.promoted;\n}\n\ninterface ActiveSource {\n readonly items: readonly HostRovingItemHandle[] | null;\n readonly raw: HTMLElement | null;\n}\n\nfunction nearestUsable(\n list: readonly HostRovingItemHandle[],\n order: readonly HostRovingItemHandle[] | null,\n anchor: HTMLElement,\n): HTMLElement | null {\n const usable = new Set(\n list.filter((item) => !item.disabled() && item.host.isConnected).map((item) => item.host),\n );\n if (usable.has(anchor)) {\n return anchor;\n }\n const at = order?.findIndex((item) => item.host === anchor) ?? -1;\n if (order !== null && at >= 0) {\n for (let i = at - 1; i >= 0; i--) {\n if (usable.has(order[i]!.host)) {\n return order[i]!.host;\n }\n }\n for (let i = at + 1; i < order.length; i++) {\n if (usable.has(order[i]!.host)) {\n return order[i]!.host;\n }\n }\n }\n return list.find((item) => usable.has(item.host))?.host ?? null;\n}\n\nfunction isStale(el: HTMLElement): boolean {\n return (\n !el.isConnected || el.hasAttribute('disabled') || el.getAttribute('aria-disabled') === 'true'\n );\n}\n","import {\n computed,\n linkedSignal,\n type Signal,\n signal,\n untracked,\n type WritableSignal,\n} from '@angular/core';\n\nimport { type DateRange } from './date-range';\nimport type { WritingDirection } from '../keyboard-navigation/keyboard-navigation';\nimport { RovingTabindex } from '../roving-tabindex/roving-tabindex';\nimport { type SegmentEditorDelegate } from './segment-editor';\nimport { type SegmentEditorContext } from './segment-directive';\n\n/** Which endpoint of a range field — the composer keys its two sources on this. */\nexport type RangeFieldEndpoint = 'start' | 'end';\n\n/**\n * The date / time field engine surface the composer provides as an endpoint's\n * {@link SegmentEditorContext} delegate: the per-segment accessors and behavior\n * methods. Both `DateFieldEngine` and `TimeFieldEngine` satisfy it structurally,\n * so one composer coordinates either flavour of endpoint. Alias of\n * {@link SegmentEditorDelegate}.\n */\nexport type RangeFieldEndpointEngine = SegmentEditorDelegate;\n\n/**\n * The engine surface {@link RangeFieldComposer.commitEndpoint} hands a held\n * endpoint's composed value back through. Both `DateFieldEngine` and\n * `TimeFieldEngine` satisfy it structurally.\n */\nexport interface RangeFieldCommitTarget<D> {\n adoptCommit(value: D): void;\n}\n\n/** The committed range paired with the generation of its last internal write. */\ninterface CommittedRange<D> {\n range: DateRange<D> | null;\n generation: number;\n}\n\n/**\n * The reactive configuration a range field root supplies to its\n * {@link RangeFieldComposer}. The shared `value` model plus the field-level\n * `effectiveDisabled` / `readonly` / `dir` signals wire the endpoint contexts;\n * the `composedStart` / `composedEnd` thunks read each engine's composed value\n * (lazy, so the engines can be built *after* the composer); and the `compose` /\n * `disordered` / `normalizeEndpointSource` policies are the only behaviour that\n * differs between a date range and a time range.\n *\n * @typeParam D The adapter's immutable date (or date-time) type.\n */\nexport interface RangeFieldComposerConfig<D> {\n /** The field's committed range model — the composer's sole write target. */\n readonly value: WritableSignal<DateRange<D> | null>;\n /** The field's effective disabled (own input OR a surrounding disabled `[forFieldset]`). */\n readonly effectiveDisabled: Signal<boolean>;\n /** Whether the field is read-only. */\n readonly readonly: Signal<boolean>;\n /** Resolved writing direction, mirrored onto each endpoint context. */\n readonly dir: Signal<WritingDirection>;\n /** Reads the start endpoint's composed value (or `null` while incomplete). */\n readonly composedStart: () => D | null;\n /** Reads the end endpoint's composed value (or `null` while incomplete). */\n readonly composedEnd: () => D | null;\n /**\n * Builds the committed range from two complete, non-null endpoints, or returns\n * `null` when they cannot form a valid range. A date range commits `{ start,\n * end }` only when ordered; a time range additionally maps a `start > end`\n * entry to a midnight-crossing range under `allowOvernight`.\n */\n readonly compose: (start: D, end: D) => DateRange<D> | null;\n /**\n * Whether two complete, non-null endpoints are an unorderable, error range\n * (reflected as `aria-invalid`). Distinct from {@link compose} because a time\n * range in overnight mode composes a `start > end` entry into a valid range\n * yet is never flagged.\n */\n readonly disordered: (start: D, end: D) => boolean;\n /**\n * Normalizes an endpoint pulled from a committed range before it seeds the\n * engine's source. Omitted (identity) for a date range; a time range in\n * overnight mode re-anchors each endpoint on the DST-stable sentinel so the\n * engine composes purely on time-of-day.\n */\n readonly normalizeEndpointSource?: (value: D) => D;\n}\n\n/**\n * The shared range-composition core backing `ForDateRangeField` and\n * `ForTimeRangeField`. It owns everything the two roots duplicated line for\n * line: the per-endpoint roving trackers, the generation-tagged committed value,\n * the two rehydration sources (with the internal-vs-external `null`\n * disambiguation), the `disordered` signal, the `recompose` commit, and the\n * per-endpoint {@link SegmentEditorContext} construction. The field-specific\n * ordering / overnight / sentinel policies enter through\n * {@link RangeFieldComposerConfig}.\n *\n * Constructed directly (`new RangeFieldComposer(config)`); it holds no injection\n * context, mirroring how `DateFieldEngine` / `TimeFieldEngine` and\n * `SegmentEditor` are lifted out of their roots. The `composedStart` /\n * `composedEnd` config thunks are read lazily, so a root can build its engines\n * from {@link startSource} / {@link endSource} *after* constructing the composer.\n *\n * @typeParam D The adapter's immutable date (or date-time) type.\n */\nexport class RangeFieldComposer<D> {\n readonly #config: RangeFieldComposerConfig<D>;\n\n /** Shared roving-tabindex tracker for the start endpoint's segments. */\n readonly startRoving = new RovingTabindex();\n /** Shared roving-tabindex tracker for the end endpoint's segments. */\n readonly endRoving = new RovingTabindex();\n\n /**\n * Monotonic generation bumped by {@link recompose} on every value it writes.\n * It tags each *internal* commit so an endpoint source can tell a `null` the\n * field itself produced (one endpoint mid-edit or the two out of order) from a\n * `null` an external reset wrote — the two are indistinguishable by the\n * `value` alone, since `null === null`.\n */\n readonly #commitGeneration = signal(0);\n\n readonly #committedValue = computed<CommittedRange<D>>(() => ({\n range: this.#config.value(),\n generation: this.#commitGeneration(),\n }));\n\n /**\n * The start endpoint's rehydration source. A `linkedSignal` keyed on the\n * committed range tagged with the commit generation: a non-null `value`\n * (external write or our own commit) drives the endpoint from `range.start`; a\n * `null` `value` is disambiguated by the generation — an **internal** null\n * (the generation advanced since the last computation, because *either*\n * endpoint is mid-edit or the two are out of order) **preserves** the prior\n * endpoint value so a complete endpoint isn't wiped while its sibling is\n * incomplete; an **external** null over a non-null range (a Signal Forms\n * reset or a consumer `[(value)]=\"null\"`, where the generation is unchanged)\n * **clears** the endpoint. An external null over an internal one changes no\n * signal, so it reaches the endpoint only through {@link reset}. Each\n * endpoint reads its own `previous`, so there is no cross-endpoint race.\n */\n readonly startSource = linkedSignal<CommittedRange<D>, D | null>({\n source: this.#committedValue,\n computation: (committed, previous) => this.#rehydrate(committed, previous, 'start'),\n });\n /** The end endpoint's rehydration source; mirror of {@link startSource} for `range.end`. */\n readonly endSource = linkedSignal<CommittedRange<D>, D | null>({\n source: this.#committedValue,\n computation: (committed, previous) => this.#rehydrate(committed, previous, 'end'),\n });\n\n /**\n * Both endpoints complete but they cannot form a valid range — reflected as\n * `aria-invalid` by the root. `false` whenever either endpoint is still\n * incomplete, then delegated to the config's {@link RangeFieldComposerConfig.disordered}\n * policy.\n */\n readonly disordered = computed(() => {\n const start = this.#config.composedStart();\n const end = this.#config.composedEnd();\n if (start === null || end === null) {\n return false;\n }\n return this.#config.disordered(start, end);\n });\n\n constructor(config: RangeFieldComposerConfig<D>) {\n this.#config = config;\n }\n\n /**\n * Re-assembles the committed range from both endpoints' composed values and\n * writes it to `value`. Emits the config's composed range when both endpoints\n * are complete, otherwise clears to `null` while preserving each endpoint's\n * typed segments (their parts survive an internal `null` value). Every write\n * bumps the commit generation so the endpoint sources mark the resulting\n * `null` as internal.\n */\n recompose(): void {\n const start = this.#config.composedStart();\n const end = this.#config.composedEnd();\n this.#commitGeneration.update((generation) => generation + 1);\n if (start === null || end === null) {\n this.#config.value.set(null);\n return;\n }\n this.#config.value.set(this.#config.compose(start, end));\n }\n\n /**\n * The `onCommit` sink of an endpoint engine: {@link recompose}s the range and,\n * while the range is held at an internal `null` (the other endpoint incomplete,\n * or the two out of order), hands the endpoint's composed value back to its\n * engine through `adoptCommit`. The engine then shows that value once focus\n * leaves the endpoint, so an entry clamped to the bounds displays clamped\n * without waiting for the other endpoint, as it does in a complete range.\n *\n * @param engine The engine whose commit is in progress.\n * @param composed The value it composed, clamped to its bounds, or `null` while incomplete.\n */\n commitEndpoint(engine: RangeFieldCommitTarget<D>, composed: D | null): void {\n this.recompose();\n if (composed !== null && untracked(this.#config.value) === null) {\n engine.adoptCommit(composed);\n }\n }\n\n /**\n * Re-seeds both endpoint sources from the current `value`, dropping an\n * endpoint preserved across an internal `null`. The root resets each\n * endpoint's engine right after, so their segments follow.\n */\n reset(): void {\n const range = untracked(this.#config.value);\n this.startSource.set(range === null ? null : this.#endpointOf(range, 'start'));\n this.endSource.set(range === null ? null : this.#endpointOf(range, 'end'));\n }\n\n /**\n * Builds the {@link SegmentEditorContext} an endpoint group provides to its\n * segment / literal children: the field-level `effectiveDisabled` / `readonly`\n * / `dir` plus that endpoint's roving tracker, with `engine` as the\n * per-segment accessor / behavior delegate.\n *\n * @param engine The endpoint's date / time field engine.\n * @param which Which endpoint, selecting its roving tracker.\n */\n makeEndpointContext(\n engine: RangeFieldEndpointEngine,\n which: RangeFieldEndpoint,\n ): SegmentEditorContext {\n return {\n effectiveDisabled: this.#config.effectiveDisabled,\n readonly: this.#config.readonly,\n dir: this.#config.dir,\n roving: which === 'start' ? this.startRoving : this.endRoving,\n delegate: engine,\n };\n }\n\n #rehydrate(\n committed: CommittedRange<D>,\n previous: { source: CommittedRange<D>; value: D | null } | undefined,\n which: RangeFieldEndpoint,\n ): D | null {\n if (committed.range !== null) {\n return this.#endpointOf(committed.range, which);\n }\n if (previous && committed.generation !== previous.source.generation) {\n return previous.value;\n }\n return null;\n }\n\n #endpointOf(range: DateRange<D>, which: RangeFieldEndpoint): D {\n const endpoint = range[which];\n return this.#config.normalizeEndpointSource\n ? this.#config.normalizeEndpointSource(endpoint)\n : endpoint;\n }\n}\n","/**\n * Whether `event` belongs to an IME composition rather than to the page.\n *\n * True while a composition is in progress (`isComposing`), and for the keydown an engine reports\n * with `keyCode` 229 — WebKit's keydown for the key that commits or cancels a composition arrives\n * after `compositionend` with `isComposing` already `false`. An Escape that cancels a CJK\n * conversion is one of these, so a handler that closes or clears on Escape returns early on it and\n * leaves the key to the IME.\n */\nexport function isImeComposing(event: KeyboardEvent): boolean {\n return event.isComposing || event.keyCode === 229;\n}\n","export function captureContent(host: HTMLElement): () => void {\n const parents: (readonly [Node, readonly ChildNode[]])[] = [];\n const texts: (readonly [ChildNode, string | null])[] = [];\n const visit = (node: Node): void => {\n const children = Array.from(node.childNodes);\n parents.push([node, children]);\n for (const child of children) {\n if (child.nodeType === child.TEXT_NODE) {\n texts.push([child, child.nodeValue]);\n } else {\n visit(child);\n }\n }\n };\n visit(host);\n return () => {\n for (const [parent, children] of parents) {\n const current = parent.childNodes;\n if (current.length !== children.length || children.some((child, i) => current[i] !== child)) {\n (parent as ParentNode).replaceChildren(...children);\n }\n }\n for (const [text, value] of texts) {\n if (text.nodeValue !== value) {\n text.nodeValue = value;\n }\n }\n };\n}\n","const DECIMAL_DIGIT = /^\\p{Nd}$/u;\n\n/**\n * Maps a single Unicode decimal digit character (General_Category `Nd`) to its\n * numeric value `0`–`9`, regardless of numbering system — ASCII `'0'`–`'9'`,\n * Arabic-Indic, Devanagari, Bengali, Thai, fullwidth, and so on. Returns `null`\n * for anything that is not exactly one decimal digit, including multi-character\n * keys (`'Enter'`, `'ArrowUp'`), the empty string, and non-digit characters.\n */\nexport function unicodeDigitValue(char: string): number | null {\n if (!DECIMAL_DIGIT.test(char)) {\n return null;\n }\n const code = char.codePointAt(0)!;\n if (code >= 0x30 && code <= 0x39) {\n return code - 0x30;\n }\n let start = code;\n while (DECIMAL_DIGIT.test(String.fromCodePoint(start - 1))) {\n start--;\n }\n return (code - start) % 10;\n}\n","import { computed, Directive, ElementRef, inject, type Signal } from '@angular/core';\n\nimport { registerHandle } from '../collection/register-handle';\nimport { isImeComposing } from '../keyboard-navigation/ime-composition';\nimport { isHistoryChord, isShortcutChord } from '../keyboard-navigation/modifier-chord';\nimport type { WritingDirection } from '../keyboard-navigation/keyboard-navigation';\nimport type { RovingTabindex } from '../roving-tabindex/roving-tabindex';\nimport { captureContent } from './editable-content';\nimport type { SegmentEditorDelegate, SegmentType } from './segment-editor';\nimport { unicodeDigitValue } from './unicode-digit';\n\n/**\n * The coordination surface a date / time root exposes to its segment children,\n * as consumed by the shared {@link ForDateTimeSegmentBase}. The field-level\n * `effectiveDisabled` / `readonly` / `dir` / `roving` signals come off the root\n * directly; every per-part accessor and behavior method lives on the\n * {@link SegmentEditorDelegate} (the field engine itself), reached through\n * `delegate`.\n */\nexport interface SegmentEditorContext {\n /**\n * The field's effective disabled — its own `disabled` input OR'd with a\n * surrounding disabled `[forFieldset]`. Segments read this so a disabled field\n * (or fieldset) is inert and exposes `aria-disabled`.\n */\n readonly effectiveDisabled: Signal<boolean>;\n /** Whether the field is read-only. */\n readonly readonly: Signal<boolean>;\n /** Resolved writing direction (mirrors ArrowLeft / ArrowRight navigation). */\n readonly dir: Signal<WritingDirection>;\n /** Shared roving-tabindex tracker: one segment owns `tabindex=0` at a time. */\n readonly roving: RovingTabindex;\n /** The field engine backing the per-segment accessors and behavior methods. */\n readonly delegate: SegmentEditorDelegate;\n}\n\n/**\n * The shared spinbutton segment directive backing `[forDateFieldSegment]` and\n * `[forTimeFieldSegment]`. It owns `role=\"spinbutton\"`, the `aria-value*`\n * reflection, the roving tabindex, the digit / arrow / Home-End / Backspace\n * (pop last digit) / Delete (clear whole segment) keyboard map (RTL-mirrored\n * ArrowLeft / ArrowRight), and the segment\n * registration. While the field is neither disabled nor read-only the host is a\n * `contenteditable=\"plaintext-only\"` editing host, so a touch device opens its\n * on-screen keyboard; text the browser would insert goes through the same digit /\n * AM·PM handling as a key press and never reaches the DOM. All state lives on the\n * root via {@link SegmentEditorContext}; the segment only reads it and forwards\n * intents.\n *\n * `@Directive` without a `selector` so the public subclasses\n * (`ForDateFieldSegment` / `ForTimeFieldSegment`) declare the concrete\n * `[forXxxFieldSegment]` selector, `exportAs`, and the `segment` /\n * `ariaLabel` inputs. The host block and behavior are inherited.\n */\n@Directive({\n host: {\n role: 'spinbutton',\n '[attr.tabindex]': 'tabindex()',\n '[attr.contenteditable]': 'editable() ? \"plaintext-only\" : null',\n '[attr.inputmode]': 'inputmode()',\n '[attr.autocorrect]': 'editable() ? \"off\" : null',\n '[attr.spellcheck]': 'editable() ? \"false\" : null',\n '[attr.aria-valuemin]': 'ctx.delegate.segmentMin(segment())',\n '[attr.aria-valuemax]': 'ctx.delegate.segmentMax(segment())',\n '[attr.aria-valuenow]': 'valueNow()',\n '[attr.aria-valuetext]': 'ctx.delegate.segmentValueText(segment())',\n '[attr.aria-label]': 'resolvedAriaLabel()',\n '[attr.aria-disabled]': 'ctx.effectiveDisabled() ? \"true\" : null',\n '[attr.aria-readonly]': 'ctx.readonly() ? \"true\" : null',\n '[attr.data-highlighted]': 'highlighted() ? \"\" : null',\n '[attr.data-placeholder]': 'ctx.delegate.isSegmentEmpty(segment()) ? \"\" : null',\n '[attr.data-disabled]': 'ctx.effectiveDisabled() ? \"\" : null',\n '[attr.data-readonly]': 'ctx.readonly() ? \"\" : null',\n '(keydown)': 'onKeyDown($event)',\n '(beforeinput)': 'onBeforeInput($event)',\n '(input)': 'onInput($event)',\n '(compositionend)': 'onCompositionEnd($event)',\n '(focus)': 'onFocus()',\n '(blur)': 'onBlur($event)',\n },\n})\nexport abstract class ForDateTimeSegmentBase {\n /** The coordination surface of the surrounding date / time root. */\n protected abstract readonly ctx: SegmentEditorContext;\n\n /** Which date or time part this segment edits. */\n abstract readonly segment: Signal<SegmentType>;\n\n /** Accessible name for this segment. Falls back to the segment type when unset. */\n abstract readonly ariaLabel: Signal<string | null>;\n\n private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);\n\n /**\n * The accessible name bound to `aria-label`. Defaults to the explicit\n * `ariaLabel` input, falling back to the raw segment type; the concrete\n * subclasses override this to source localized, injector-scoped defaults.\n */\n protected readonly resolvedAriaLabel: Signal<string> = computed(\n () => this.ariaLabel() ?? this.segment(),\n );\n\n private readonly valueNow = computed(() => this.ctx.delegate.segmentValue(this.segment()));\n\n private readonly editable = computed(() => !this.ctx.effectiveDisabled() && !this.ctx.readonly());\n\n private readonly inputmode = computed<'numeric' | null>(() =>\n this.editable() && this.segment() !== 'dayPeriod' ? 'numeric' : null,\n );\n\n #restoreContent: (() => void) | null = null;\n\n private readonly highlighted = computed(() => this.ctx.roving.isActive(this.host.nativeElement));\n\n /**\n * APG tabindex: the user-focused segment owns `tabindex=0` (tracked by the\n * shared `RovingTabindex`). Before any interaction the first segment in the\n * locale order is the field's single tab entry; disabled fields are skipped.\n */\n private readonly tabindex = computed<-1 | 0>(() => {\n if (this.ctx.effectiveDisabled()) {\n return -1;\n }\n if (this.ctx.roving.hasActive()) {\n return this.ctx.roving.tabindexFor(this.host.nativeElement);\n }\n return this.ctx.delegate.isFirstSegmentType(this.segment()) ? 0 : -1;\n });\n\n protected registerSegment(): void {\n const handle = { host: this.host.nativeElement, type: this.segment };\n registerHandle(\n handle,\n (h) => this.ctx.delegate.registerSegment(h),\n (h) => this.ctx.delegate.unregisterSegment(h),\n 'afterNextRender',\n );\n }\n\n private onFocus(): void {\n this.ctx.delegate.focusSegment(this.segment());\n if (this.editable()) {\n const host = this.host.nativeElement;\n host.ownerDocument.getSelection()?.collapse(host, 0);\n }\n }\n\n private onBlur(event: FocusEvent): void {\n this.ctx.delegate.endTyping(event.relatedTarget);\n }\n\n private onBeforeInput(event: InputEvent): void {\n if (!event.cancelable) {\n this.#restoreContent ??= captureContent(this.host.nativeElement);\n return;\n }\n event.preventDefault();\n if (!this.editable()) {\n return;\n }\n const type = this.segment();\n switch (event.inputType) {\n case 'deleteContentBackward':\n this.ctx.delegate.backspace(type);\n return;\n case 'deleteContentForward':\n this.ctx.delegate.clear(type);\n return;\n case 'insertCompositionText':\n case 'insertFromComposition':\n case 'deleteCompositionText':\n return;\n default:\n if (event.data !== null) {\n this.#typeText(type, event.data);\n }\n }\n }\n\n private onInput(event: InputEvent): void {\n const restore = this.#restoreContent;\n this.#restoreContent = null;\n restore?.();\n const type = this.segment();\n if (\n event.inputType === 'insertCompositionText' &&\n event.data &&\n type === 'dayPeriod' &&\n this.editable()\n ) {\n this.ctx.delegate.setDayPeriodFromKey(event.data.charAt(0));\n }\n }\n\n private onCompositionEnd(event: CompositionEvent): void {\n if (event.data && this.editable()) {\n this.#typeText(this.segment(), event.data);\n }\n }\n\n #typeText(type: SegmentType, text: string): void {\n const host = this.host.nativeElement;\n const chars = Array.from(text);\n for (let i = 0; i < chars.length; i++) {\n this.#typeCharacter(type, chars[i]!);\n const next = this.ctx.roving.active();\n if (next !== null && next !== host && i < chars.length - 1) {\n next.dispatchEvent(\n new InputEvent('beforeinput', {\n inputType: 'insertText',\n data: chars.slice(i + 1).join(''),\n cancelable: true,\n }),\n );\n return;\n }\n }\n }\n\n #typeCharacter(type: SegmentType, char: string): boolean {\n const digit = unicodeDigitValue(char);\n if (digit !== null) {\n this.ctx.delegate.typeDigit(type, digit);\n return true;\n }\n return type === 'dayPeriod' && this.ctx.delegate.setDayPeriodFromKey(char);\n }\n\n private onKeyDown(event: KeyboardEvent): void {\n if (this.ctx.effectiveDisabled() || isImeComposing(event)) {\n return;\n }\n const type = this.segment();\n const key = event.key;\n if (!isShortcutChord(event) && this.#typeCharacter(type, key)) {\n event.preventDefault();\n return;\n }\n if (isHistoryChord(event) && isSegmentNavigationKey(key)) {\n return;\n }\n const rtl = this.ctx.dir() === 'rtl';\n switch (key) {\n case 'ArrowUp':\n event.preventDefault();\n this.ctx.delegate.step(type, 1);\n return;\n case 'ArrowDown':\n event.preventDefault();\n this.ctx.delegate.step(type, -1);\n return;\n case 'ArrowRight':\n event.preventDefault();\n this.ctx.delegate.focusSibling(type, rtl ? -1 : 1);\n return;\n case 'ArrowLeft':\n event.preventDefault();\n this.ctx.delegate.focusSibling(type, rtl ? 1 : -1);\n return;\n case 'Home':\n event.preventDefault();\n this.ctx.delegate.goToBound(type, 'min');\n return;\n case 'End':\n event.preventDefault();\n this.ctx.delegate.goToBound(type, 'max');\n return;\n case 'Backspace':\n event.preventDefault();\n this.ctx.delegate.backspace(type);\n return;\n case 'Delete':\n event.preventDefault();\n this.ctx.delegate.clear(type);\n return;\n default:\n return;\n }\n }\n}\n\nfunction isSegmentNavigationKey(key: string): boolean {\n return key.startsWith('Arrow') || key === 'Home' || key === 'End';\n}\n","import { computed, InjectionToken, type Signal } from '@angular/core';\n\nimport type { DateAdapter } from 'forty-cdk/date-adapter';\nimport type { FieldGranularity } from './date-segments';\nimport type { PickerSourceHost } from './picker-source-host';\nimport type { SegmentEditorContext } from './segment-directive';\nimport type { TimeGranularity } from './time-segments';\n\n/**\n * What a segmented field registers with the picker that adopts it: the element\n * the picker names through a surrounding `[forField]`, and the focus and reset\n * entry points the picker's own `focus()` / `reset()` delegate to.\n */\nexport interface AdoptedField {\n /** The field's `role=\"group\"` host. */\n readonly element: HTMLElement;\n /** Moves focus to the field's first editable segment. */\n focus(options?: FocusOptions): void;\n /** Discards a partly typed entry and redisplays the picker's value. */\n reset(): void;\n /**\n * Records `value` as what the field's commit in progress resolved to once a\n * picker downstream normalised it, so the typed segments survive it.\n */\n adoptCommit(value: unknown): void;\n}\n\n/**\n * The picker a segmented field defers to while the picker's `anatomy` is\n * `'field'`. The picker is the form control: the field reads its value and\n * state from here and writes its commits back through {@link commitFieldValue}.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n *\n * @typeParam D The adapter's immutable date (or date-time) type.\n */\nexport interface SegmentedFieldHost<D> {\n /** The picker's date adapter; the field must resolve the same one. */\n readonly adapter: DateAdapter<D>;\n /** Whether the picker currently adopts its projected field. */\n readonly adoptsField: Signal<boolean>;\n /** The picker's value, which the adopted field displays and edits. */\n readonly value: Signal<D | null>;\n /** The picker's effective disabled state. */\n readonly effectiveDisabled: Signal<boolean>;\n /** The picker's read-only state. */\n readonly readonly: Signal<boolean>;\n /** The picker's required state. */\n readonly required: Signal<boolean>;\n /** The picker's invalid state. */\n readonly invalid: Signal<boolean>;\n /** The picker's pending state, which the adopted field reflects as `aria-busy`. */\n readonly pending: Signal<boolean>;\n /** The picker's hour cycle after its scope defaults, or `null` to let the field resolve its own. */\n readonly resolvedHourCycle: Signal<12 | 24 | null>;\n /** The picker's locale, or `null` to let the field resolve its own. */\n readonly locale: Signal<string | null>;\n /** Registers the projected field. */\n registerField(field: AdoptedField): void;\n /** Removes a previously registered field. */\n unregisterField(field: AdoptedField): void;\n /** Writes a value the adopted field composed into the picker. */\n commitFieldValue(value: D | null): void;\n /** Marks the picker touched. */\n markTouched(): void;\n /**\n * The elements that make up the picker as one control: its root and its open\n * surface. A focus move between them does not mark the picker touched.\n */\n touchBoundaries(): readonly (Node | null)[];\n}\n\n/**\n * {@link SegmentedFieldHost} provided by `[forDatePicker]` for a projected\n * `[forDateField]`.\n *\n * @typeParam D The adapter's immutable date (or date-time) type.\n */\nexport interface DateFieldHost<D> extends SegmentedFieldHost<D> {\n /** The picker's minimum date. */\n readonly minDate: Signal<D | null>;\n /** The picker's maximum date. */\n readonly maxDate: Signal<D | null>;\n /** The picker's date-time precision. */\n readonly granularity: Signal<FieldGranularity>;\n}\n\n/**\n * {@link SegmentedFieldHost} provided by `[forTimePicker]` for a projected\n * `[forTimeField]`.\n *\n * @typeParam D The adapter's immutable date-time type.\n */\nexport interface TimeFieldHost<D> extends SegmentedFieldHost<D> {\n /** The picker's earliest time of day. */\n readonly minTime: Signal<D | null>;\n /** The picker's latest time of day. */\n readonly maxTime: Signal<D | null>;\n /** The picker's smallest time unit. */\n readonly granularity: Signal<TimeGranularity>;\n}\n\n/** Token `[forDatePicker]` provides so a projected `[forDateField]` can find it. */\nexport const FOR_DATE_FIELD_HOST = new InjectionToken<DateFieldHost<unknown>>(\n 'FOR_DATE_FIELD_HOST',\n);\n\n/** Token `[forTimePicker]` provides so a projected `[forTimeField]` can find it. */\nexport const FOR_TIME_FIELD_HOST = new InjectionToken<TimeFieldHost<unknown>>(\n 'FOR_TIME_FIELD_HOST',\n);\n\n/**\n * The segment-facing view of a field's context with the disabled and read-only\n * states folded in of an adopting picker and of a picker the field is projected\n * into as a time source, so a segment's `aria-disabled` / `aria-readonly` match\n * what the field's engine enforces. Returns `ctx` itself when neither is\n * reachable.\n *\n * @param ctx The field's own coordination context.\n * @param host The picker that may adopt the field, or `null`.\n * @param source The picker the field is projected into as a source, or `null`.\n */\nexport function adoptedSegmentContext(\n ctx: SegmentEditorContext,\n host: SegmentedFieldHost<unknown> | null,\n source: PickerSourceHost | null = null,\n): SegmentEditorContext {\n if (host === null && source === null) {\n return ctx;\n }\n return {\n effectiveDisabled: computed(\n () =>\n ctx.effectiveDisabled() ||\n (host?.adoptsField() === true && host.effectiveDisabled()) ||\n (source?.effectiveDisabled() ?? false),\n ),\n readonly: computed(\n () =>\n ctx.readonly() ||\n (host?.adoptsField() === true && host.readonly()) ||\n (source?.readonly() ?? false),\n ),\n dir: ctx.dir,\n roving: ctx.roving,\n delegate: ctx.delegate,\n };\n}\n","import { type FieldSpec } from './segment-editor';\nimport { type TimeSegmentType } from './segment-types';\n\n/** Smallest editable time unit; controls which segments are rendered. */\nexport type TimeGranularity = 'hour' | 'minute' | 'second';\n\nconst DIGITS: Record<TimeSegmentType, number> = {\n hour: 2,\n minute: 2,\n second: 2,\n dayPeriod: 0,\n};\n\n/**\n * 1:23:45 PM: distinct hour / minute / second values, in the afternoon so the\n * `dayPeriod` part is present to read back. Only each part's `type` and the\n * separators are read.\n */\nfunction referenceTime(): Date {\n return new Date(2000, 0, 1, 13, 23, 45);\n}\n\n/**\n * Derives the ordered segment list for a time field from the runtime locale,\n * the resolved hour cycle, and the granularity, using\n * `Intl.DateTimeFormat(...).formatToParts`. The visible order of the segments\n * (and the separators between them), and whether an AM/PM `dayPeriod` segment\n * is present, follow the locale and the 12-/24-hour cycle.\n *\n * Pure: the same arguments always yield the same list, touching no signals or\n * DOM.\n *\n * @param locale BCP 47 locale, or `undefined` for the runtime default.\n * @param hourCycle Resolved hour cycle (`12` shows AM/PM, `24` does not).\n * @param granularity Smallest editable unit; trims minute / second segments.\n */\nexport function buildTimeSegments(\n locale: string | undefined,\n hourCycle: 12 | 24,\n granularity: TimeGranularity,\n): readonly FieldSpec[] {\n const options: Intl.DateTimeFormatOptions = {\n calendar: 'gregory',\n hour: '2-digit',\n hour12: hourCycle === 12,\n };\n if (granularity !== 'hour') {\n options.minute = '2-digit';\n }\n if (granularity === 'second') {\n options.second = '2-digit';\n }\n\n const parts = new Intl.DateTimeFormat(locale, options).formatToParts(referenceTime());\n const segments: FieldSpec[] = [];\n for (const part of parts) {\n switch (part.type) {\n case 'hour':\n case 'minute':\n case 'second':\n case 'dayPeriod':\n segments.push({ kind: 'editable', type: part.type, digits: DIGITS[part.type] });\n break;\n case 'literal':\n segments.push({ kind: 'literal', literal: part.value });\n break;\n default:\n break;\n }\n }\n return segments;\n}\n","import { computed, linkedSignal, type Signal } from '@angular/core';\n\nimport type { TimeCapableDateAdapter } from 'forty-cdk/date-adapter';\nimport { type BaseFieldEngineConfig, DateTimeFieldEngineBase } from './field-engine-base';\nimport { type FieldSpec, type SegmentType } from './segment-editor';\nimport { type TimeSegmentType } from './segment-types';\nimport { composeWithTime, secondsOfDay, shiftsWallClock, timeSentinel } from './serialize';\nimport { buildTimeSegments, type TimeGranularity } from './time-segments';\n\n/** Internal per-part state: the entered value for each editable time segment, hour as 0-23. */\nexport interface TimeParts {\n hour: number | null;\n minute: number | null;\n second: number | null;\n dayPeriod: number | null;\n}\n\n/**\n * The reactive configuration a segmented time-of-day field supplies to its\n * {@link TimeFieldEngine}. The shared `signal`-driven inputs (granularity, hour\n * cycle, locale, placeholder, bounds, disabled / read-only) plus the\n * authoritative `source` value and the `onCommit` sink let the engine derive the\n * locale-ordered segments, the entered parts, and the composed value without\n * owning any directive of its own.\n *\n * @typeParam D The adapter's immutable, time-capable date-time type.\n */\nexport interface TimeFieldEngineConfig<D> extends BaseFieldEngineConfig<D> {\n /** The active, time-capable date adapter (shared with `ForCalendar`). */\n readonly adapter: TimeCapableDateAdapter<D>;\n /** Smallest editable unit (`'hour'` / `'minute'` / `'second'`). */\n readonly granularity: Signal<TimeGranularity>;\n /** Per-segment placeholder overrides shown while empty. */\n readonly placeholder: Signal<Partial<Record<TimeSegmentType, string>>>;\n /** Earliest selectable time-of-day (inclusive), or `null` for unbounded. */\n readonly minTime: Signal<D | null>;\n /** Latest selectable time-of-day (inclusive), or `null` for unbounded. */\n readonly maxTime: Signal<D | null>;\n}\n\n/**\n * The shared time-of-day field engine backing `ForTimeField` and each endpoint\n * of `ForTimeRangeField`. It owns everything a segmented time field needs on top\n * of the generic {@link SegmentEditor}: the locale-ordered spec list, the\n * resolved hour cycle, the entered {@link TimeParts} (rehydrated from the\n * configured `source`), the time-specific segment bounds / min-hour seed / empty\n * `aria-valuetext`, and the sentinel-anchored setTime/clamp compose. The owning\n * directive supplies the reactive {@link TimeFieldEngineConfig} and decides what\n * to do with each composed value through `onCommit` (a single field writes its\n * own `value`; the range field reports the endpoint up to the root).\n *\n * Constructed directly (`new TimeFieldEngine(config)`); it holds no injection\n * context, mirroring how {@link SegmentEditor} and `DateFieldEngine` are lifted\n * out of their roots.\n *\n * @typeParam D The adapter's immutable, time-capable date-time type.\n */\nexport class TimeFieldEngine<D> extends DateTimeFieldEngineBase<D, TimeParts, TimeSegmentType> {\n readonly #config: TimeFieldEngineConfig<D>;\n\n protected readonly specs = computed<readonly FieldSpec[]>(() =>\n buildTimeSegments(this.locale(), this.cycle(), this.#config.granularity()),\n );\n\n /**\n * The entered parts. A `linkedSignal` keyed on `source`: a non-null write\n * (consumer, `[formField]`, or a settled field) rehydrates the segments from\n * the date-time, while the value the field itself just committed keeps the\n * parts as entered until focus leaves its segments, so a clamped intermediate\n * never rewrites the segments still being edited. A `null` transition is\n * disambiguated by the prior parts: an *internal* edit clearing one segment\n * leaves the others, so `previous` still carries a filled part and is\n * preserved; an *external* reset of a complete value leaves `previous` fully\n * filled, so the field clears.\n */\n protected readonly parts = linkedSignal<D | null, TimeParts>({\n source: () => this.#config.source(),\n computation: (current, previous) => {\n const held = this.heldParts(current, previous);\n if (held !== null) {\n return held;\n }\n if (current !== null) {\n return this.partsFrom(current);\n }\n const prior = previous?.value;\n if (prior && this.someEditableEmpty(prior)) {\n return prior;\n }\n return this.emptyParts();\n },\n });\n\n constructor(config: TimeFieldEngineConfig<D>) {\n super(config);\n this.#config = config;\n this.initEditor();\n }\n\n segmentMin(type: SegmentType): number {\n if (type === 'hour') {\n return this.hourMin();\n }\n return 0;\n }\n\n segmentMax(type: SegmentType): number {\n if (type === 'hour') {\n return this.cycle() === 12 ? this.hourMin() + 11 : 23;\n }\n if (type === 'dayPeriod') {\n return 1;\n }\n return 59;\n }\n\n /** Field-specific `aria-valuetext`: only the empty marker; numeric otherwise. */\n protected valueText(type: SegmentType): string | null {\n return this.isSegmentEmpty(type) ? this.#config.emptySegmentText() : null;\n }\n\n /** Base value for stepping an empty segment: the hour from its minimum (midnight in 24-hour and `h11`, 1 AM in `h12`), minute and second 0. */\n protected seed(type: SegmentType): number {\n if (type !== 'hour') {\n return 0;\n }\n const display = this.segmentMin('hour');\n if (this.cycle() === 24) {\n return display;\n }\n const parts = this.parts();\n const pm =\n parts.dayPeriod !== null ? parts.dayPeriod === 1 : parts.hour !== null && parts.hour >= 12;\n const base = display % 12;\n return pm ? base + 12 : base;\n }\n\n protected placeholderFor(type: SegmentType): string {\n if (type === 'hour' || type === 'minute' || type === 'second' || type === 'dayPeriod') {\n const override = this.#config.placeholder()[type];\n if (override) {\n return override;\n }\n }\n switch (type) {\n case 'hour':\n return 'hh';\n case 'minute':\n return 'mm';\n case 'second':\n return 'ss';\n default:\n return '--';\n }\n }\n\n /**\n * Composes a parts record into the value, clamped to the bounds, or `null`\n * while any visible segment, the AM/PM one included, is empty.\n */\n protected composeFrom(parts: TimeParts): D | null {\n if (this.someEditableEmpty(parts)) {\n return null;\n }\n const granularity = this.#config.granularity();\n const needMinute = granularity !== 'hour';\n const needSecond = granularity === 'second';\n const base = this.#base();\n const composed = this.#config.adapter.setTime(\n base,\n parts.hour!,\n needMinute ? parts.minute! : 0,\n needSecond ? parts.second! : 0,\n );\n return this.#clampToBounds(composed);\n }\n\n protected partsFrom(value: D): TimeParts {\n const adapter = this.#config.adapter;\n return {\n hour: adapter.getHours(value),\n minute: adapter.getMinutes(value),\n second: adapter.getSeconds(value),\n dayPeriod: adapter.getHours(value) >= 12 ? 1 : 0,\n };\n }\n\n protected emptyParts(): TimeParts {\n return { hour: null, minute: null, second: null, dayPeriod: null };\n }\n\n protected wallClockShifts(parts: TimeParts): boolean {\n if (parts.hour === null) {\n return false;\n }\n return shiftsWallClock(this.#config.adapter, this.#base(), parts.hour, parts.minute ?? 0);\n }\n\n #base(): D {\n return this.anchor() ?? timeSentinel(this.#config.adapter);\n }\n\n #clampToBounds(date: D): D {\n const adapter = this.#config.adapter;\n const min = this.#config.minTime();\n if (min !== null && secondsOfDay(adapter, date) < secondsOfDay(adapter, min)) {\n return composeWithTime(adapter, date, min);\n }\n const max = this.#config.maxTime();\n if (max !== null && secondsOfDay(adapter, date) > secondsOfDay(adapter, max)) {\n return composeWithTime(adapter, date, max);\n }\n return date;\n }\n}\n","import { InjectionToken, type ModelSignal } from '@angular/core';\nimport type { DateAdapter } from 'forty-cdk/date-adapter';\n\n/**\n * Shared contract implemented by both `ForTimeField` and `ForTimePicker`. The\n * `ForDatePicker` time bridge queries this token via `contentChild` so it can\n * observe whichever time-editing primitive the consumer projects — without a\n * hard import of either, keeping date-picker tree-shaking intact.\n *\n * @typeParam D The adapter's date-time type.\n */\nexport interface TimeValueSource<D> {\n readonly value: ModelSignal<D | null>;\n readonly adapter: DateAdapter<D>;\n /**\n * Records `value` as what the source's commit in progress resolved to in the\n * picker, which grafts it onto its day and clamps it to its bounds before\n * handing it back through the one-way `[value]` binding. Called synchronously\n * from the picker's `valueChange` subscription; a source with no typed\n * segments ignores it.\n */\n adoptCommit(value: D): void;\n /**\n * Discards a partly typed time the source holds and redisplays its value.\n * The picker forwards its own `FormUiControl.reset` here, so a Signal Forms\n * reset reaches a draft the picker's value cannot represent.\n */\n reset(): void;\n}\n\n/**\n * Token provided by `ForTimeField` and `ForTimePicker`. `ForDatePicker`\n * queries descendants for this token to locate the projected time source.\n */\nexport const FOR_TIME_VALUE_SOURCE = new InjectionToken<TimeValueSource<unknown>>(\n 'FOR_TIME_VALUE_SOURCE',\n);\n","/**\n * Text a defaults key holds: a plain string, or a function returning the\n * current string. The library calls the function each time it reads the\n * text, from inside the reactive context that renders or announces it, so a\n * function that reads a signal (the active language, say) keeps the text\n * current as that signal changes.\n *\n * @example\n * ```ts\n * provideForComboboxDefaults(() => {\n * const i18n = inject(AppI18n);\n * return { clearAriaLabel: () => i18n.t('combobox.clear') };\n * });\n * ```\n */\nexport type LocalizableText = string | (() => string);\n\nexport function resolveText(text: LocalizableText): string {\n return typeof text === 'function' ? text() : text;\n}\n\nexport function resolveTextInput(\n own: string | null | undefined,\n fallback: LocalizableText,\n): string | null {\n return own === undefined ? resolveText(fallback) : own;\n}\n\nexport function resolveTextRecord<K extends string>(\n scope: Partial<Record<K, LocalizableText>>,\n own: Partial<Record<K, string>>,\n): Partial<Record<K, string>> {\n const result: Partial<Record<K, string>> = {};\n for (const key of Object.keys(scope) as K[]) {\n const text = scope[key];\n if (text !== undefined) {\n result[key] = resolveText(text);\n }\n }\n for (const key of Object.keys(own) as K[]) {\n const text = own[key];\n if (text !== undefined) {\n result[key] = text;\n }\n }\n return result;\n}\n","import { type DragRect } from './drag-geometry';\n\n/** A point in viewport coordinates (the preview's top-left). */\nexport interface PreviewPoint {\n readonly x: number;\n readonly y: number;\n}\n\n/** The preview box's measured size. */\nexport interface PreviewSize {\n readonly width: number;\n readonly height: number;\n}\n\n/**\n * Constrains a drag preview's desired top-left position.\n *\n * Applies, in order:\n * - **axis lock** — when `lockAxis` is `'x'` the preview moves along the x axis only, so its\n * `y` is held at `origin.y`; when `'y'` it moves along the y axis only, so its `x` is held at\n * `origin.x`; `null` leaves both free.\n * - **boundary clamp** — when `boundary` is non-null, the resulting top-left is clamped so the\n * preview box (`size`) stays fully inside the boundary rect. When the boundary is smaller than\n * the preview on an axis, the preview is pinned to the boundary's start edge on that axis.\n *\n * Pure: takes already-measured rects/sizes, performs no DOM reads. `origin` is the preview's\n * desired top-left at lift time (the axis-lock anchor).\n */\nexport function clampPreviewPosition(\n desired: PreviewPoint,\n size: PreviewSize,\n boundary: DragRect | null,\n lockAxis: 'x' | 'y' | null,\n origin: PreviewPoint,\n): PreviewPoint {\n let x = lockAxis === 'y' ? origin.x : desired.x;\n let y = lockAxis === 'x' ? origin.y : desired.y;\n if (boundary) {\n x = Math.max(boundary.left, Math.min(x, boundary.right - size.width));\n y = Math.max(boundary.top, Math.min(y, boundary.bottom - size.height));\n }\n return { x, y };\n}\n\n/**\n * Resolves a drag `boundary` input into the element that confines the movement.\n *\n * `null` is unbounded and yields `null`; an `HTMLElement` is returned as-is; a string is treated as\n * a selector resolved with `host.closest(...)`, so it matches the host itself or the nearest\n * matching ancestor and yields `null` when nothing matches.\n *\n * Unlike {@link clampPreviewPosition} this reads the DOM, so the caller decides *when* the lookup\n * happens: `[forDropList]` resolves once at lift time and hands the element to\n * `PreviewController`; `[forFreeDrag]` re-resolves on every move.\n */\nexport function resolveBoundaryElement(\n host: HTMLElement,\n boundary: HTMLElement | string | null,\n): HTMLElement | null {\n if (boundary === null) {\n return null;\n }\n return typeof boundary === 'string' ? host.closest<HTMLElement>(boundary) : boundary;\n}\n","/** Minimal rectangle shape (structurally satisfied by `DOMRect`). */\nexport interface DragRect {\n readonly left: number;\n readonly top: number;\n readonly right: number;\n readonly bottom: number;\n}\n\n/** A drop container's live geometry: its own rect plus the rects of its non-lifted items. */\nexport interface DropContainerGeometry {\n readonly rect: DragRect;\n /** Item rects in DOM order, EXCLUDING the lifted item. */\n readonly itemRects: readonly DragRect[];\n /**\n * This container's own layout axis — the insertion index is resolved against it. `'mixed'` is\n * 2D resolution for wrapping grids of uniformly-sized items, considering both axes; it reduces\n * to the single-axis result when the items form a single row or a single column.\n */\n readonly orientation: 'horizontal' | 'vertical' | 'mixed';\n /** This container's own resolved writing direction. */\n readonly dir: 'ltr' | 'rtl';\n readonly clip?: DragRect;\n}\n\n/** A resolved pointer drop target: a container plus the insertion index within it. */\nexport interface DropTarget {\n /** Index into the `[source, ...connected]` container array (0 = source). */\n readonly containerIndex: number;\n /** Insertion index within that container. */\n readonly index: number;\n}\n\nfunction rectContains(rect: DragRect, x: number, y: number): boolean {\n return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;\n}\n\nfunction visibleRect(container: DropContainerGeometry): DragRect {\n const { rect, clip } = container;\n if (!clip) {\n return rect;\n }\n return {\n left: Math.max(rect.left, clip.left),\n top: Math.max(rect.top, clip.top),\n right: Math.min(rect.right, clip.right),\n bottom: Math.min(rect.bottom, clip.bottom),\n };\n}\n\nfunction isEmptyRect(rect: DragRect): boolean {\n return rect.left > rect.right || rect.top > rect.bottom;\n}\n\nfunction nearestContainer(rects: readonly DragRect[], x: number, y: number): number {\n let nearest = -1;\n let minDist = Infinity;\n for (let i = 0; i < rects.length; i++) {\n const rect = rects[i]!;\n if (isEmptyRect(rect)) {\n continue;\n }\n const d = clampedDistance(rect, x, y);\n if (d < minDist) {\n minDist = d;\n nearest = i;\n }\n }\n return nearest;\n}\n\nfunction clampedDistance(rect: DragRect, x: number, y: number): number {\n const cx = Math.max(rect.left, Math.min(rect.right, x));\n const cy = Math.max(rect.top, Math.min(rect.bottom, y));\n return Math.hypot(x - cx, y - cy);\n}\n\nfunction insertionIndex(\n itemRects: readonly DragRect[],\n x: number,\n y: number,\n orientation: 'horizontal' | 'vertical' | 'mixed',\n dir: 'ltr' | 'rtl',\n): number {\n if (orientation === 'mixed') {\n return mixedInsertionIndex(itemRects, x, y, dir);\n }\n for (let i = 0; i < itemRects.length; i++) {\n const r = itemRects[i]!;\n const past =\n orientation === 'vertical'\n ? y < (r.top + r.bottom) / 2\n : dir === 'rtl'\n ? x > (r.left + r.right) / 2\n : x < (r.left + r.right) / 2;\n if (past) {\n return i;\n }\n }\n return itemRects.length;\n}\n\nfunction mixedInsertionIndex(\n itemRects: readonly DragRect[],\n x: number,\n y: number,\n dir: 'ltr' | 'rtl',\n): number {\n if (isSingleRow(itemRects)) {\n return insertionIndex(itemRects, x, y, 'horizontal', dir);\n }\n if (isSingleColumn(itemRects)) {\n return insertionIndex(itemRects, x, y, 'vertical', dir);\n }\n for (let i = 0; i < itemRects.length; i++) {\n const r = itemRects[i]!;\n const beforeRow = y < r.top;\n const withinRow = y <= r.bottom;\n const pastColumn = dir === 'rtl' ? x > (r.left + r.right) / 2 : x < (r.left + r.right) / 2;\n if (beforeRow || (withinRow && pastColumn)) {\n return i;\n }\n }\n return itemRects.length;\n}\n\nfunction isSingleRow(itemRects: readonly DragRect[]): boolean {\n let maxTop = -Infinity;\n let minBottom = Infinity;\n for (const r of itemRects) {\n maxTop = Math.max(maxTop, r.top);\n minBottom = Math.min(minBottom, r.bottom);\n }\n return maxTop < minBottom;\n}\n\nfunction isSingleColumn(itemRects: readonly DragRect[]): boolean {\n let maxLeft = -Infinity;\n let minRight = Infinity;\n for (const r of itemRects) {\n maxLeft = Math.max(maxLeft, r.left);\n minRight = Math.min(minRight, r.right);\n }\n return maxLeft < minRight;\n}\n\n/**\n * Resolves the drop target container and insertion index from a pointer position.\n *\n * Each container carries its own `orientation` / `dir`, and the insertion index is resolved\n * against the axis of the container that won the selection — so a transfer into a connected\n * container whose orientation or writing direction differs from the source's resolves the index\n * on the TARGET's axis.\n *\n * @param point Viewport pointer coordinates.\n * @param containers Ordered `[source, ...connected]` container geometries.\n * @returns The resolved `DropTarget`, or `null` when `containers` is empty.\n */\nexport function resolveDropTarget(\n point: { readonly x: number; readonly y: number },\n containers: readonly DropContainerGeometry[],\n): DropTarget | null {\n if (containers.length === 0) {\n return null;\n }\n\n const visible = containers.map(visibleRect);\n let containerIndex = visible.findIndex((rect) => rectContains(rect, point.x, point.y));\n\n if (containerIndex < 0) {\n containerIndex = nearestContainer(visible, point.x, point.y);\n }\n if (containerIndex < 0) {\n containerIndex = nearestContainer(\n containers.map((c) => c.rect),\n point.x,\n point.y,\n );\n }\n\n const container = containers[containerIndex]!;\n const index = insertionIndex(\n container.itemRects,\n point.x,\n point.y,\n container.orientation,\n container.dir,\n );\n\n return { containerIndex, index };\n}\n","/**\n * The name every drag and reorder announcement calls an item by, resolved like an accessible\n * name: a non-empty `override` (a `[textValue]`), else the text of the elements the node's\n * `aria-labelledby` references, else its `aria-label`, else its descendant text. Descendant text\n * skips any `aria-hidden` subtree such as a decorative `[forDragHandle]` glyph, keeps\n * visually-hidden but announced content, reads a descendant's own `aria-label` in place of its\n * content, and puts a space between element children so adjacent elements are not run together.\n * Whitespace is collapsed and trimmed. SSR-safe: it reads no global `document`.\n */\nexport function dragAnnouncementLabel(node: Element, override?: string | null): string {\n const explicit = override?.trim();\n if (explicit) {\n return explicit;\n }\n return dragElementName(node) || collapse(spacedText(node));\n}\n\n/**\n * The name `node` is given by `aria-labelledby` (the referenced elements' text, joined with\n * spaces) or, failing that, by `aria-label`; `''` when it declares neither. It never falls back\n * to descendant text, so a drop list is not named after the items it holds.\n */\nexport function dragElementName(node: Element): string {\n const ids = node.getAttribute('aria-labelledby')?.split(/\\s+/).filter(Boolean) ?? [];\n const referenced = collapse(\n ids\n .map((id) => referencedElement(node, id))\n .map((el) => (el === null ? '' : (explicitLabel(el) ?? spacedText(el))))\n .join(' '),\n );\n return referenced || (explicitLabel(node) ?? '');\n}\n\nfunction referencedElement(node: Element, id: string): Element | null {\n const root = node.getRootNode();\n const scope = 'getElementById' in root ? (root as Document | DocumentFragment) : null;\n return (scope ?? node.ownerDocument).getElementById(id);\n}\n\nfunction explicitLabel(el: Element): string | null {\n const label = el.getAttribute('aria-label')?.trim();\n return label ? label : null;\n}\n\nfunction spacedText(node: Node): string {\n let text = '';\n node.childNodes.forEach((child) => {\n if (child.nodeType === child.TEXT_NODE) {\n text += child.nodeValue ?? '';\n return;\n }\n if (child.nodeType !== child.ELEMENT_NODE) {\n return;\n }\n const el = child as Element;\n if (el.getAttribute('aria-hidden') === 'true') {\n return;\n }\n text += ` ${explicitLabel(el) ?? spacedText(el)} `;\n });\n return text;\n}\n\nfunction collapse(text: string): string {\n return text.replace(/\\s+/g, ' ').trim();\n}\n","import type { LiveAnnouncer } from '../live-announcer/live-announcer';\n\nimport { dragAnnouncementLabel, dragElementName } from './drag-announcement-label';\n\n/** What a positional announcement says about the list its position belongs to. */\nexport interface DragAnnouncementContext {\n /** The list's accessible name from `aria-labelledby` / `aria-label`, or `''`. */\n readonly list: string;\n /** Whether that list is not the one the item was lifted from. */\n readonly transfer: boolean;\n}\n\n/** A positional announcement builder: 1-based `index` of `total` valid positions. */\nexport type PositionalDragAnnouncement = (\n label: string,\n index: number,\n total: number,\n context: DragAnnouncementContext,\n) => string;\n\n/** The four builders a reorder coordinator announces a drag with. */\nexport interface DragAnnouncementText {\n readonly lift: PositionalDragAnnouncement;\n readonly move: PositionalDragAnnouncement;\n readonly drop: PositionalDragAnnouncement;\n readonly cancel: (label: string) => string;\n}\n\n/**\n * The dragged item: its host, plus the `[textValue]` override naming it when it has one. A\n * `null` host, read after the session it belonged to ended, names the item `''`.\n */\nexport interface DragAnnouncedItem {\n readonly host: Element | null;\n readonly textValue?: string | null;\n}\n\n/** A position an announcement describes. */\nexport interface DragAnnouncedPosition {\n /** 0-based position within `list`. */\n readonly index: number;\n /** Number of valid drop positions in `list`. */\n readonly total: number;\n /** Host of the list the position belongs to. */\n readonly list: Element;\n /** Host of the list the item was lifted from. */\n readonly source: Element;\n}\n\n/**\n * The one place a reorder coordinator turns a drag into live-region text. It names the item\n * through {@link dragAnnouncementLabel}, names the list a position belongs to and whether that\n * list is a transfer target, and hands both to the coordinator's builders. Lift, drop and cancel\n * are announced assertively and a move politely unless the caller asks otherwise.\n */\nexport class DragAnnouncer {\n readonly #announcer: LiveAnnouncer;\n readonly #text: () => DragAnnouncementText;\n\n constructor(announcer: LiveAnnouncer, text: () => DragAnnouncementText) {\n this.#announcer = announcer;\n this.#text = text;\n }\n\n lift(item: DragAnnouncedItem, at: DragAnnouncedPosition): void {\n this.#positional(this.#text().lift, item, at, 'assertive');\n }\n\n move(\n item: DragAnnouncedItem,\n at: DragAnnouncedPosition,\n politeness: 'polite' | 'assertive' = 'polite',\n ): void {\n this.#positional(this.#text().move, item, at, politeness);\n }\n\n drop(item: DragAnnouncedItem, at: DragAnnouncedPosition): void {\n this.#positional(this.#text().drop, item, at, 'assertive');\n }\n\n cancel(item: DragAnnouncedItem): void {\n this.#announcer.announce(this.#text().cancel(itemName(item)), 'assertive');\n }\n\n #positional(\n build: PositionalDragAnnouncement,\n item: DragAnnouncedItem,\n at: DragAnnouncedPosition,\n politeness: 'polite' | 'assertive',\n ): void {\n const context = { list: dragElementName(at.list), transfer: at.list !== at.source };\n this.#announcer.announce(build(itemName(item), at.index + 1, at.total, context), politeness);\n }\n}\n\nfunction itemName(item: DragAnnouncedItem): string {\n return item.host === null ? '' : dragAnnouncementLabel(item.host, item.textValue);\n}\n\n/** `index` clamped to the positions `[0, count - 1]`; `0` when there are none. */\nexport function clampDragIndex(index: number, count: number): number {\n return Math.max(0, Math.min(count - 1, index));\n}\n\n/**\n * The position a keyboard step from `current` towards `requested` lands on, clamped to\n * `[0, count - 1]`, or `null` when it lands on `current`. A coordinator applies a step only when\n * this is non-null, so a key pressed at a boundary neither announces nor scrolls.\n */\nexport function stepDragTarget(current: number, requested: number, count: number): number | null {\n const next = clampDragIndex(requested, count);\n return next === current ? null : next;\n}\n","import { composedParentElement } from '../composed-tree/composed-tree';\nimport type { SwipeDirection } from './swipe-dismiss';\n\nconst EDGE_TOLERANCE_PX = 1;\n\n/** Whether a computed `overflow-x` / `overflow-y` value makes its element a scroll container. */\nexport function overflowScrolls(overflow: string): boolean {\n return overflow === 'auto' || overflow === 'scroll' || overflow === 'overlay';\n}\n\n/**\n * Returns true when `target` is inside a scrollable ancestor that has not\n * yet reached its edge along the gesture direction — meaning the gesture\n * should be left to scroll the inner content rather than starting a swipe\n * on the outer drawer. Stops walking at `boundary` (typically the drawer\n * root) so unrelated ancestors above it don't affect the decision; the walk\n * crosses open shadow boundaries. With `includeBoundary` set, the boundary\n * itself is checked too, for a surface that is its own scroll container.\n *\n * Direction semantics match {@link SwipeDirection}: `'down'` means a\n * pointer-travel-down gesture (which on a scrollable scrolls the content\n * up; we therefore care whether there is room above). Mirrored for the\n * other three, and the horizontal room is read in the scroller's own\n * writing direction.\n *\n * Conservative: an element with `overflow: hidden` is treated as\n * non-scrollable; an element within 1px of its edge along the gesture\n * direction returns `false` (i.e. the gesture is fair game for the swipe).\n */\nexport function isScrollableAtEdge(\n target: Element | null,\n direction: SwipeDirection,\n boundary?: Element | null,\n includeBoundary = false,\n): boolean {\n let cur: Element | null = target;\n while (cur) {\n const atBoundary = cur === boundary;\n if (atBoundary && !includeBoundary) {\n return false;\n }\n if (cur instanceof HTMLElement && hasRoomAgainst(cur, direction)) {\n return true;\n }\n if (atBoundary) {\n return false;\n }\n cur = composedParentElement(cur);\n }\n return false;\n}\n\nfunction hasRoomAgainst(el: HTMLElement, direction: SwipeDirection): boolean {\n const style = el.ownerDocument.defaultView?.getComputedStyle(el);\n if (direction === 'up' || direction === 'down') {\n if (!overflowScrolls(style?.overflowY ?? '') || el.scrollHeight <= el.clientHeight) {\n return false;\n }\n const room =\n direction === 'down' ? el.scrollTop : el.scrollHeight - el.clientHeight - el.scrollTop;\n return room > EDGE_TOLERANCE_PX;\n }\n if (!overflowScrolls(style?.overflowX ?? '') || el.scrollWidth <= el.clientWidth) {\n return false;\n }\n const max = el.scrollWidth - el.clientWidth;\n const rtl = style?.direction === 'rtl';\n const roomLeft = rtl ? max + el.scrollLeft : el.scrollLeft;\n const roomRight = rtl ? -el.scrollLeft : max - el.scrollLeft;\n return (direction === 'right' ? roomLeft : roomRight) > EDGE_TOLERANCE_PX;\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n afterNextRender,\n DestroyRef,\n inject,\n PLATFORM_ID,\n type Signal,\n signal,\n} from '@angular/core';\n\nimport { overflowScrolls } from '../swipe-dismiss/scroll-boundary';\n\n/** A `touch-action` value a drag surface or handle binds; `null` leaves the browser default. */\nexport type DragTouchAction = 'none' | 'pan-x' | 'pan-y' | null;\n\n/** One flag per axis. */\nexport interface DragAxes {\n /** The horizontal axis. */\n readonly x: boolean;\n /** The vertical axis. */\n readonly y: boolean;\n}\n\n/** Both axes set: a free drag, or a reorder whose list may lie either way. */\nexport const BOTH_DRAG_AXES: DragAxes = { x: true, y: true };\n\n/** Neither axis set: a host that scrolls on no axis. */\nexport const NO_DRAG_AXES: DragAxes = { x: false, y: false };\n\n/** The inputs every drag surface's `touch-action` is computed from. */\nexport interface DragSurfaceTouchActionInput {\n /** Whether a press on the surface can currently arm the drag. */\n readonly armable: boolean;\n /** Whether handles are registered, so the drag arms only from a handle and never from the surface. */\n readonly handles: boolean;\n /** The axes the gesture moves along, on which the browser must not pan. */\n readonly axes: DragAxes;\n /** The axes on which the host itself is a scroll container that currently overflows. */\n readonly hostScrolls: DragAxes;\n}\n\n/**\n * The `touch-action` a drag surface binds. The browser keeps panning on every axis the gesture does\n * not move along, and on every axis the host scrolls on by itself, so a scroll container that is\n * also a drag surface still scrolls by touch. `null` while the surface cannot arm, or while handles\n * are registered, since each handle then carries {@link dragHandleTouchAction}.\n */\nexport function dragSurfaceTouchAction(input: DragSurfaceTouchActionInput): DragTouchAction {\n if (!input.armable || input.handles) {\n return null;\n }\n const x = input.axes.x && !input.hostScrolls.x;\n const y = input.axes.y && !input.hostScrolls.y;\n if (x && y) {\n return 'none';\n }\n if (x) {\n return 'pan-y';\n }\n return y ? 'pan-x' : null;\n}\n\n/**\n * The `touch-action` a drag handle binds: `'none'` while the drag can arm, so a touch drag on the\n * handle is not taken by the page's scrolling, else `null`.\n */\nexport function dragHandleTouchAction(armable: boolean): 'none' | null {\n return armable ? 'none' : null;\n}\n\nfunction measureScrollAxes(host: HTMLElement): DragAxes {\n const style = host.ownerDocument.defaultView?.getComputedStyle(host);\n return {\n x: overflowScrolls(style?.overflowX ?? '') && host.scrollWidth > host.clientWidth,\n y: overflowScrolls(style?.overflowY ?? '') && host.scrollHeight > host.clientHeight,\n };\n}\n\n/**\n * The axes on which `host` is a scroll container whose content overflows it, kept current while\n * the host or one of its children resizes and while children are added or removed. The browser\n * fixes a touch's `touch-action` when the touch starts, so a surface reads this ahead of the press\n * rather than measuring at `pointerdown`. A change to the host's `overflow` style with no resize is\n * seen on the next resize. {@link NO_DRAG_AXES} on the server and until the first render.\n *\n * Call from an injection context.\n */\nexport function injectHostScrollAxes(host: HTMLElement): Signal<DragAxes> {\n const out = signal<DragAxes>(NO_DRAG_AXES);\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n return out.asReadonly();\n }\n\n let prev = NO_DRAG_AXES;\n const sync = (): void => {\n const next = measureScrollAxes(host);\n if (next.x !== prev.x || next.y !== prev.y) {\n prev = next;\n out.set(next);\n }\n };\n\n let resize: ResizeObserver | null = null;\n let mutation: MutationObserver | null = null;\n const observeChildren = (): void => {\n if (!resize) {\n return;\n }\n resize.disconnect();\n resize.observe(host);\n for (const child of Array.from(host.children)) {\n resize.observe(child);\n }\n };\n\n afterNextRender(() => {\n sync();\n if (typeof ResizeObserver !== 'undefined') {\n resize = new ResizeObserver(sync);\n observeChildren();\n }\n if (typeof MutationObserver !== 'undefined') {\n mutation = new MutationObserver(() => {\n observeChildren();\n sync();\n });\n mutation.observe(host, { childList: true });\n }\n });\n\n inject(DestroyRef).onDestroy(() => {\n resize?.disconnect();\n mutation?.disconnect();\n });\n\n return out.asReadonly();\n}\n","import {\n computed,\n DestroyRef,\n inject,\n Injectable,\n type Signal,\n signal,\n type WritableSignal,\n} from '@angular/core';\n\n/**\n * The elements a drag item (`[forDraggable]`, `[forFreeDrag]`) is mounted on, so a piece sharing\n * one of them can tell it is co-located with a draggable without importing `forty-cdk/drag-drop`.\n * The draggable marks its host from its constructor, which a subclass inherits and a\n * `hostDirectives` wrapper runs, so every wrapping shape is seen; a selector attribute is rendered\n * for neither.\n */\n@Injectable({ providedIn: 'root' })\nexport class DragItemHosts {\n /** Per host, how many drag items are mounted on it. Created by whichever side asks first. */\n readonly #counts = new WeakMap<HTMLElement, WritableSignal<number>>();\n\n /** Records a drag item on `host`; the returned function removes it again. */\n mark(host: HTMLElement): () => void {\n const count = this.#count(host);\n count.update((n) => n + 1);\n return () => count.update((n) => n - 1);\n }\n\n /** Whether a drag item is mounted on `host`, tracking a draggable constructed after the reader. */\n carries(host: HTMLElement): Signal<boolean> {\n const count = this.#count(host);\n return computed(() => count() > 0);\n }\n\n #count(host: HTMLElement): WritableSignal<number> {\n let count = this.#counts.get(host);\n if (count === undefined) {\n count = signal(0);\n this.#counts.set(host, count);\n }\n return count;\n }\n}\n\n/**\n * Marks `host` as carrying a drag item until the calling directive is destroyed. Call from the\n * drag item's constructor.\n */\nexport function markDragItemHost(host: HTMLElement): void {\n const unmark = inject(DragItemHosts).mark(host);\n inject(DestroyRef).onDestroy(unmark);\n}\n\n/**\n * Whether a drag item shares `host` with the calling piece. Call from an injection context; the\n * signal turns `true` once the draggable on `host` is constructed, whichever is constructed first.\n */\nexport function injectHostCarriesDragItem(host: HTMLElement): Signal<boolean> {\n return inject(DragItemHosts).carries(host);\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n computed,\n DOCUMENT,\n DestroyRef,\n ElementRef,\n Injectable,\n inject,\n PLATFORM_ID,\n signal,\n type Signal,\n} from '@angular/core';\n\nimport { composedClosest, composedParentElement } from '../composed-tree/composed-tree';\nimport type { WritingDirection } from '../keyboard-navigation/keyboard-navigation';\n\n/**\n * Normalise an arbitrary `dir` attribute value to a concrete writing\n * direction. Only `'rtl'` (case-insensitive) maps to RTL; everything else —\n * including `'auto'`, the empty string, and unknown tokens — resolves to\n * `'ltr'`, matching the spec's behaviour that a non-`rtl` enumerated value is\n * treated as the default direction.\n */\nfunction normalizeDir(value: string | null | undefined): WritingDirection {\n return value?.toLowerCase() === 'rtl' ? 'rtl' : 'ltr';\n}\n\n/**\n * Owns the single application-wide `MutationObserver` watching `dir` attribute changes across the\n * document, exposed as a monotonically increasing `revision` tick.\n *\n * One observer covers every primitive: each host derives its ambient direction from a `computed`\n * keyed on `revision`, so N primitives mounting at once collapse into one batched callback rather\n * than N per-instance observers.\n *\n * `revision` bumps only for a `dir` write that changes the direction some element declares to its\n * descendants: its own normalised `dir` when it carries one, otherwise what its parent declares. A\n * write repeating what the element already inherits — a root reflecting its ambient direction, a\n * portal stamp under `<html dir>` — leaves every resolution as it was and is ignored. A flip that\n * does change a declared direction invalidates every dir-aware primitive, each re-walking its own\n * ancestor chain through open shadow roots. The observer does not reach into shadow roots, so a\n * `dir` changed inside one is picked up on the next document-level change that bumps `revision`.\n *\n * SSR-safe: off-browser no observer is created and `revision` stays `0`.\n */\n@Injectable({ providedIn: 'root' })\nclass AmbientDirection {\n readonly #doc = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n readonly #destroyRef = inject(DestroyRef);\n\n readonly #revision = signal(0);\n\n /**\n * Bumps whenever a `dir` attribute change alters the direction an element declares to its\n * descendants. Stays `0` on the server.\n */\n readonly revision = this.#revision.asReadonly();\n\n constructor() {\n if (!this.#isBrowser) {\n return;\n }\n\n const win = this.#doc.defaultView;\n if (win && typeof win.MutationObserver === 'function') {\n const observer = new win.MutationObserver((records) => {\n if (records.some((record) => changesDeclaredDirection(record, this.#doc))) {\n this.#revision.update((v) => v + 1);\n }\n });\n observer.observe(this.#doc.documentElement, {\n attributes: true,\n attributeFilter: ['dir'],\n attributeOldValue: true,\n subtree: true,\n });\n this.#destroyRef.onDestroy(() => observer.disconnect());\n }\n }\n}\n\n/**\n * Whether a `dir` mutation changed what its target declares to its descendants. Before the write\n * that is the record's old `dir`, or the parent's declared direction when there was none; after it,\n * the current `dir`, or the parent's declared direction once it is gone. Equal values mean no\n * descendant's resolution changed.\n */\nfunction changesDeclaredDirection(record: MutationRecord, doc: Document): boolean {\n const target = record.target as Element;\n const inherited = (): WritingDirection | null =>\n target === doc.documentElement\n ? null\n : resolveAttributeDirection(composedParentElement(target), doc);\n const before = record.oldValue === null ? inherited() : normalizeDir(record.oldValue);\n const after = target.hasAttribute('dir') ? normalizeDir(target.getAttribute('dir')) : inherited();\n return before !== after;\n}\n\n/**\n * Resolves the effective writing direction for the host element, reactive to\n * runtime changes.\n *\n * An explicit `[dir]` always wins. When it is `null` the value falls back to the nearest ancestor\n * carrying a `dir` attribute — the host itself is skipped, since it carries\n * {@link injectReflectedDirection} — then to `<html dir>`, defaulting to `'ltr'`. The ancestor walk crosses open shadow roots,\n * so a primitive rendered inside a `ViewEncapsulation.ShadowDom` component follows a `dir` set\n * above its host.\n *\n * Direction is read from the semantic `dir` attribute, never from CSS `direction`, so consumers set\n * `dir` on an ancestor rather than styling it.\n *\n * A runtime `dir` change on an ancestor recomputes the signal. SSR-safe: the ancestor walk runs\n * server-side too, so a server-rendered RTL app resolves `'rtl'` and hydration matches.\n *\n * Limitation: only `dir` attribute mutations in the document are observed, not `childList`, and not\n * mutations inside a shadow root. Moving the host into a different-`dir` subtree, or changing a\n * `dir` inside a shadow root, does not recompute the ambient until a `dir` change elsewhere in the\n * document alters a declared direction; set an explicit `[dir]` on the element if that happens.\n *\n * Must be called from an injection context.\n */\nexport function injectTextDirection(\n explicitDir: Signal<WritingDirection | null>,\n): Signal<WritingDirection> {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const ambient = injectAmbientDirection(() => composedParentElement(host));\n\n return computed(() => explicitDir() ?? ambient());\n}\n\n/**\n * The `dir` value a direction-aware root reflects onto its own host: the explicit `[dir]` when set,\n * otherwise the direction declared above the host (the nearest ancestor carrying a `dir`\n * attribute, across open shadow roots, then `<html dir>`), otherwise `null`.\n *\n * Bind it as `'[attr.dir]'` in place of the resolved {@link injectTextDirection} value. A root with\n * no direction declared anywhere then carries no `dir` attribute, so its subtree keeps inheriting\n * CSS `direction` and a surface portaled out of it is not stamped with a default nobody declared.\n * Omit `explicitDir` on a piece that only mirrors the direction declared above it.\n *\n * Must be called from an injection context.\n */\nexport function injectReflectedDirection(\n explicitDir?: Signal<WritingDirection | null>,\n): Signal<WritingDirection | null> {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const declared = injectDeclaredDirection(() => composedParentElement(host));\n\n return explicitDir ? computed(() => explicitDir() ?? declared()) : declared;\n}\n\n/**\n * Resolves the writing direction in effect at `origin`: the nearest element carrying a `dir`\n * attribute, `origin` itself included and open shadow roots crossed, then `<html dir>`, defaulting\n * to `'ltr'`. Recomputes on any runtime `dir` attribute change in the document, and on `origin`\n * when it reads a signal.\n *\n * Must be called from an injection context.\n */\nexport function injectAmbientDirection(\n origin: () => Element | null | undefined,\n): Signal<WritingDirection> {\n const declared = injectDeclaredDirection(origin);\n return computed(() => declared() ?? 'ltr');\n}\n\nexport function injectDeclaredDirection(\n origin: () => Element | null | undefined,\n): Signal<WritingDirection | null> {\n const doc = inject(DOCUMENT);\n const direction = inject(AmbientDirection);\n\n return computed(() => {\n direction.revision();\n return resolveAttributeDirection(origin() ?? null, doc);\n });\n}\n\nfunction resolveAttributeDirection(origin: Element | null, doc: Document): WritingDirection | null {\n const declared = (origin ? composedClosest(origin, '[dir]') : null) ?? htmlWithDir(doc);\n return declared ? normalizeDir(declared.getAttribute('dir')) : null;\n}\n\nexport function stampAmbientDirection(el: Element, origin: Element | null): void {\n if (el.hasAttribute('dir')) {\n return;\n }\n const dir = resolveAttributeDirection(origin, el.ownerDocument);\n if (dir !== null) {\n el.setAttribute('dir', dir);\n }\n}\n\nfunction htmlWithDir(doc: Document): Element | null {\n const html = doc.documentElement as Element | null;\n return html?.hasAttribute('dir') ? html : null;\n}\n","const TRANSITION_END_SAFETY_MS = 50;\n\nfunction parseTimeMs(segment: string): number {\n const value = parseFloat(segment);\n if (!Number.isFinite(value)) {\n return 0;\n }\n return segment.endsWith('ms') ? value : value * 1000;\n}\n\nfunction splitList(value: string | undefined): string[] {\n return value ? value.split(',').map((segment) => segment.trim()) : [];\n}\n\n/**\n * The delay plus duration (ms) of the computed transition on `transform` (or `all`), or of the\n * longest configured transition when none animates `transform`; `0` when none is configured.\n */\nfunction transformTransitionEndMs(style: CSSStyleDeclaration): number {\n const durations = splitList(style.transitionDuration);\n if (durations.length === 0) {\n return 0;\n }\n const delays = splitList(style.transitionDelay);\n const properties = splitList(style.transitionProperty);\n let transformEnd = 0;\n let longestEnd = 0;\n (properties.length > 0 ? properties : ['all']).forEach((property, i) => {\n if (property === 'none') {\n return;\n }\n const duration = parseTimeMs(durations[i % durations.length] ?? '');\n const delay = delays.length > 0 ? parseTimeMs(delays[i % delays.length] ?? '') : 0;\n const end = duration > 0 ? Math.max(0, duration + delay) : 0;\n longestEnd = Math.max(longestEnd, end);\n if (property === 'transform' || property === 'all') {\n transformEnd = end;\n }\n });\n return transformEnd || longestEnd;\n}\n\n/**\n * Calls `onDone` exactly once, when the `transform` transition of `el` itself ends: on a\n * `transitionend` whose target is `el` and whose property is `transform`, or, if none arrives, once\n * the delay plus duration of the computed transition on `transform` (or `all`, or of the longest\n * configured transition when none animates `transform`) and a small safety margin have elapsed.\n * A `transitionend` of another property, or one bubbling up from a descendant, is ignored. Calls\n * `onDone` synchronously when `el` has no transition configured.\n *\n * Reads the computed style of `el` once, so call it after the styling hook that configures the\n * transition is in place.\n */\nexport function awaitTransformTransition(el: HTMLElement, win: Window, onDone: () => void): void {\n const endMs = transformTransitionEndMs(win.getComputedStyle(el));\n if (endMs === 0) {\n onDone();\n return;\n }\n let done = false;\n const controller = new AbortController();\n const finish = (): void => {\n if (done) {\n return;\n }\n done = true;\n controller.abort();\n onDone();\n };\n el.addEventListener(\n 'transitionend',\n (event: TransitionEvent): void => {\n if (event.target !== el || (event.propertyName && event.propertyName !== 'transform')) {\n return;\n }\n finish();\n },\n { signal: controller.signal },\n );\n win.setTimeout(finish, endMs + TRANSITION_END_SAFETY_MS);\n}\n","import { stampAmbientDirection } from '../text-direction/text-direction';\nimport { awaitTransformTransition } from './transform-transition';\n\n/** A floating clone of the dragged element that follows the pointer. */\nexport interface DragPreview {\n /**\n * The element that floats under the pointer. When present, a boundary clamp keeps this\n * element's box inside the boundary; when absent, it keeps the dragged item's box inside.\n */\n readonly element?: HTMLElement;\n /** Position the preview's top-left at `(x, y)` in viewport coordinates. */\n moveTo(x: number, y: number): void;\n /**\n * Transition the preview's top-left to `(x, y)`, then `destroy()` it once its own `transform`\n * transition ends; a transition of another property, or of a descendant, does not end it.\n * Marks the element `data-settling` so a consumer CSS rule keyed on it governs duration /\n * easing. A fallback timeout covers a `transitionend` that never arrives:\n * it waits for the delay plus duration of the computed transition on `transform` (or `all`),\n * or of the longest configured transition when none animates `transform`, plus a small safety\n * margin. If no transition is configured, destroys immediately. Caller must pass the browser\n * `Window`.\n */\n settle(x: number, y: number, win: Window): void;\n /** Remove the preview from the DOM. Idempotent. */\n destroy(): void;\n}\n\nfunction attachSettle(target: HTMLElement, destroyFn: () => void): DragPreview['settle'] {\n return (x: number, y: number, win: Window): void => {\n target.setAttribute('data-settling', '');\n void target.offsetWidth;\n awaitTransformTransition(target, win, destroyFn);\n target.style.transform = `translate(${x}px, ${y}px)`;\n };\n}\n\n/**\n * Wraps a minimal preview (with only `moveTo` and `destroy`) into a full `DragPreview`.\n * The `settle` implementation falls back to an immediate `destroy` call since the wrapped\n * object carries no DOM element to animate. Used when a caller-supplied preview does not yet\n * implement `settle`.\n */\nexport function wrapPreview(preview: {\n moveTo(x: number, y: number): void;\n destroy(): void;\n}): DragPreview {\n return {\n moveTo: (x, y) => preview.moveTo(x, y),\n settle: (_x, _y, _win) => {\n preview.destroy();\n },\n destroy: () => preview.destroy(),\n };\n}\n\nconst IDENTITY_HOOKS = ['id', 'data-testid'];\n\nconst LIVE_ATTRIBUTES = ['name', 'form', 'autofocus', 'autoplay'];\n\nconst EMBEDDED_CONTENT = 'iframe, object, embed';\n\nfunction selfAndDescendants(root: HTMLElement, selector: string): HTMLElement[] {\n const descendants = Array.from(root.querySelectorAll<HTMLElement>(selector));\n return root.matches(selector) ? [root, ...descendants] : descendants;\n}\n\nfunction stripAttributes(root: HTMLElement, names: readonly string[]): void {\n for (const el of selfAndDescendants(root, names.map((name) => `[${name}]`).join(', '))) {\n for (const name of names) {\n el.removeAttribute(name);\n }\n }\n}\n\nfunction replaceEmbeddedContent(clone: HTMLElement, source: HTMLElement, doc: Document): void {\n const originals = source.querySelectorAll(EMBEDDED_CONTENT);\n clone.querySelectorAll(EMBEDDED_CONTENT).forEach((embedded, i) => {\n const rect = originals[i]?.getBoundingClientRect();\n const box = doc.createElement('div');\n box.style.display = 'inline-block';\n box.style.width = `${rect?.width ?? 0}px`;\n box.style.height = `${rect?.height ?? 0}px`;\n embedded.replaceWith(box);\n });\n}\n\n/**\n * Creates a default drag preview: a fixed-position clone of `source` appended to `doc.body`, sized to the\n * source's current bounding box, non-interactive, and hidden from assistive tech. The clone carries the\n * writing direction declared at `source`, so it keeps the alignment and bidi ordering of the item it\n * floats away from. Caller must gate on a browser platform.\n *\n * `id` and `data-testid` are stripped from the clone root and from every descendant carrying one, so the\n * preview is never reachable through a hook that identifies a single element: duplicating an `id` while the\n * preview lives makes the document invalid (and `getElementById` ambiguous) regardless of `aria-hidden`.\n * The clone still answers the source's own attribute selectors — a directive selector such as\n * `[forDraggable]`, plus `data-index` where the source carries one — so code enumerating items by selector\n * during a drag must exclude `[data-for-drag-preview]`.\n *\n * The clone's live content is made inert before it joins the document: `name` and `form` are stripped so a\n * cloned control never joins the source's radio group or form (a checked radio would otherwise uncheck the\n * source's), `autofocus` and `autoplay` are stripped, and every `iframe`, `object` and `embed` is replaced by\n * an empty box the size of the source's, so nothing reloads or plays.\n */\nexport function createDragPreview(source: HTMLElement, doc: Document): DragPreview {\n const rect = source.getBoundingClientRect();\n const clone = source.cloneNode(true) as HTMLElement;\n\n clone.style.position = 'fixed';\n clone.style.top = '0';\n clone.style.left = '0';\n clone.style.width = `${rect.width}px`;\n clone.style.height = `${rect.height}px`;\n clone.style.margin = '0';\n clone.style.pointerEvents = 'none';\n clone.style.boxSizing = 'border-box';\n clone.style.zIndex = '2147483647';\n\n clone.setAttribute('data-for-drag-preview', '');\n clone.setAttribute('aria-hidden', 'true');\n stripAttributes(clone, IDENTITY_HOOKS);\n stripAttributes(clone, LIVE_ATTRIBUTES);\n replaceEmbeddedContent(clone, source, doc);\n\n stampAmbientDirection(clone, source);\n doc.body.appendChild(clone);\n\n const destroy = (): void => {\n clone.remove();\n };\n\n return {\n element: clone,\n moveTo(x: number, y: number): void {\n clone.style.transform = `translate(${x}px, ${y}px)`;\n },\n settle: attachSettle(clone, destroy),\n destroy,\n };\n}\n\n/**\n * Creates a drag preview from caller-supplied root nodes (e.g. an Angular embedded view's\n * `rootNodes`): wraps them in a fixed-position, non-interactive, assistive-tech-hidden container\n * appended to `doc.body`. `onDestroy` runs on teardown (before the wrapper is removed) so the\n * caller can dispose the backing view. The wrapper carries the writing direction declared at\n * `source`, the dragged item's host. Caller must gate on a browser platform.\n */\nexport function createTemplatePreview(\n nodes: readonly Node[],\n source: Element,\n doc: Document,\n onDestroy: () => void,\n): DragPreview {\n const wrapper = doc.createElement('div');\n wrapper.style.position = 'fixed';\n wrapper.style.top = '0';\n wrapper.style.left = '0';\n wrapper.style.margin = '0';\n wrapper.style.pointerEvents = 'none';\n wrapper.style.zIndex = '2147483647';\n wrapper.setAttribute('data-for-drag-preview', '');\n wrapper.setAttribute('aria-hidden', 'true');\n\n for (const node of nodes) {\n wrapper.appendChild(node);\n }\n stampAmbientDirection(wrapper, source);\n doc.body.appendChild(wrapper);\n\n const destroy = (): void => {\n onDestroy();\n wrapper.remove();\n };\n\n return {\n element: wrapper,\n moveTo(x: number, y: number): void {\n wrapper.style.transform = `translate(${x}px, ${y}px)`;\n },\n settle: attachSettle(wrapper, destroy),\n destroy,\n };\n}\n","import { afterEveryRender, type Injector } from '@angular/core';\n\nimport { composedContains, resolveActiveElement } from '../composed-tree/composed-tree';\n\nconst MAX_RENDERS = 10;\n\n/** A focus target: anything `focus()` can be called on. */\nexport type FocusWhenMountedTarget = HTMLElement | SVGElement;\n\n/** Wiring for {@link focusWhenMounted}. */\nexport interface FocusWhenMountedOptions {\n /** Injector the render hook registers against; the hook is torn down with it. */\n readonly injector: Injector;\n /** The document focus is read from. */\n readonly document: Document;\n /**\n * The element focus must be on or inside when the step starts — the lifted item, or the\n * focused row. The step does nothing when focus is anywhere else.\n */\n readonly from: Element;\n /**\n * Resolves the element to focus among what is rendered, or `null` while it is not mounted\n * yet. Receives the element that held focus when the step started.\n */\n readonly target: (origin: FocusWhenMountedTarget) => FocusWhenMountedTarget | null;\n /** Brings the target into the rendered set. Runs once, synchronously, before any render. */\n readonly reveal?: () => void;\n /**\n * Runs once when the step ends, whether it moved focus, yielded to a focus move made\n * elsewhere, or gave up on a target that never mounted. Not called by `cancel()`.\n */\n readonly release?: () => void;\n}\n\n/** Handle on a pending {@link focusWhenMounted} step. */\nexport interface FocusWhenMountedRef {\n /** Abandon the step without moving focus and without calling `release`. */\n cancel(): void;\n}\n\nconst NOOP_REF: FocusWhenMountedRef = { cancel: () => undefined };\n\n/**\n * Moves focus to an element that may not be rendered yet, once a render has mounted it: the\n * step a keyboard drop or a dataset-wide jump owes the keyboard user when the element they\n * were on is moved, recycled or destroyed by the re-render that follows.\n *\n * It starts only when focus is on or inside `from`, and remembers that element as the origin.\n * `reveal` then runs synchronously (scroll the target into the window, pin it), and after each\n * render the step resolves `target`. Focus moves when it resolves and focus is still on the\n * origin or was lost to `<body>`; a focus move made elsewhere in the meantime wins, and so does\n * a target that is still unmounted after a bounded number of renders. Every one of those ends\n * calls `release` once.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own entry points, with\n * no semver guarantee.\n */\nexport function focusWhenMounted(options: FocusWhenMountedOptions): FocusWhenMountedRef {\n const { document } = options;\n const active = resolveActiveElement(document);\n if (\n active === null ||\n !composedContains(options.from, active) ||\n !(active instanceof HTMLElement || active instanceof SVGElement)\n ) {\n return NOOP_REF;\n }\n const origin = active;\n let renders = 0;\n let done = false;\n\n options.reveal?.();\n\n const hook = afterEveryRender(\n () => {\n if (done) {\n return;\n }\n renders++;\n const current = resolveActiveElement(document);\n const lost =\n current === null || current === document.body || current === document.documentElement;\n if (!lost && current !== origin) {\n end();\n return;\n }\n const target = options.target(origin);\n if (target !== null) {\n if (current !== target) {\n target.focus();\n }\n end();\n return;\n }\n if (renders >= MAX_RENDERS) {\n end();\n }\n },\n { injector: options.injector },\n );\n\n function stop(): void {\n done = true;\n hook.destroy();\n }\n\n function end(): void {\n stop();\n options.release?.();\n }\n\n return {\n cancel: () => {\n if (!done) {\n stop();\n }\n },\n };\n}\n","import { isImeComposing } from '../keyboard-navigation/ime-composition';\n\n/**\n * Shared keyboard resolvers for container-level drag-reorder coordinators\n * (`ForTreeNodeDrag`, `ForListboxReorder`, `ForTableRowReorder`). Framework-free\n * and unit-testable in isolation. Not part of the public API.\n *\n * A coordinator that lives next to a roving / selectable collection cannot reuse\n * the plain Space / Enter lift the drag-drop primitive uses on a `[forDraggable]`\n * item — those keys already activate / select the focused item. The convention\n * across these coordinators is therefore a dedicated **lift binding**, read from\n * `ForDragDropDefaults.liftKey` so a consumer can rebind it per scope, plus a\n * shared commit / cancel vocabulary while a node is lifted.\n */\n\n/**\n * Whether a key press lifts the focused item into a keyboard drag: the scope's\n * `liftKey` binding accepts it and it does not belong to an IME composition.\n *\n * @param event The keydown fired while no item is lifted.\n * @param liftKey The resolved `ForDragDropDefaults.liftKey` of the coordinator's scope.\n */\nexport function isDragLiftKey(\n event: KeyboardEvent,\n liftKey: (event: KeyboardEvent) => boolean,\n): boolean {\n return !isImeComposing(event) && liftKey(event);\n}\n\n/**\n * Resolves the commit / cancel control common to every lifted keyboard drag:\n * `Escape` / `Tab` cancel, `Space` / `Enter` commit. Returns `null` for keys\n * with no control meaning, leaving the caller to resolve its own movement keys\n * (sibling steps, depth changes, etc.).\n *\n * @param event The keydown event fired while an item is lifted.\n */\nexport function resolveLiftedDragControl(event: KeyboardEvent): 'cancel' | 'commit' | null {\n if ((event.key === 'Escape' && !isImeComposing(event)) || event.key === 'Tab') {\n return 'cancel';\n }\n if (event.key === ' ' || event.key === 'Enter') {\n return 'commit';\n }\n return null;\n}\n","import type { DestroyRef } from '@angular/core';\n\nimport { composedContains, resolveActiveElement } from '../composed-tree/composed-tree';\n\n/**\n * Configuration for {@link createKeyboardDragMediator}.\n *\n * The mediator owns the listener *lifecycle* plus the one DOM fact it is positioned to answer\n * (\"did focus leave the host?\"); the caller owns every *domain* decision. `isLifted` is read on\n * each keydown to route the event and again before a deferred focus leave is reported, the two\n * keydown callbacks carry the caller's key semantics, and `onFocusLeave` carries the consequence\n * of a leave.\n */\nexport interface KeyboardDragMediatorConfig {\n /** Element the capture-phase `keydown` / `focusout` listeners attach to (the coordinator host). */\n readonly host: HTMLElement;\n /**\n * The host's document. Its active element, resolved through open shadow roots, decides a\n * `focusout` that reports no destination.\n */\n readonly document: Document;\n /** Whether code runs in a browser. The mediator no-ops entirely on the server. */\n readonly isBrowser: boolean;\n /** The owner's `DestroyRef`; the mediator removes its listeners on destroy. */\n readonly destroyRef: DestroyRef;\n /** `true` while a keyboard drag is in progress. Read on every keydown to route the event. */\n isLifted(): boolean;\n /**\n * A keydown fired while no keyboard drag is in progress. The caller decides whether it starts\n * a lift (and whether to `preventDefault` / `stopPropagation`). Keys with no lift meaning must\n * be left untouched so they fall through to the underlying collection's own handlers.\n */\n onIdleKeydown(event: KeyboardEvent): void;\n /**\n * A keydown fired while a keyboard drag is in progress. The caller resolves it to a move /\n * commit / cancel and consumes the event (`preventDefault` + `stopPropagation`) so the\n * underlying collection never sees the navigation / activation key. A key it maps to no action\n * goes through `consumeUnmappedLiftedKey`, so no key reaches the collection while lifted.\n */\n onLiftedKeydown(event: KeyboardEvent): void;\n /**\n * Focus has genuinely left the host while a keyboard drag was in progress — the mediator has\n * already resolved containment, so there is nothing left to re-check here. The caller decides\n * the *consequence*, which in every coordinator today is cancelling the in-flight drag.\n *\n * It fires at most once per `focusout`, never while `isLifted()` reports `false`, and never\n * after the owner is destroyed.\n */\n onFocusLeave(): void;\n}\n\n/**\n * Wires the capture-phase keyboard mediation shared by container-level drag-reorder\n * coordinators (`ForTreeNodeDrag`, `ForTableRowReorder`, `ForListboxReorder`,\n * `ForVirtualReorder`).\n *\n * Each of those coordinators lives on a container whose children own their own roving\n * tabindex / selection, so the coordinator must intercept keys in the **capture phase** —\n * before they reach the focused child — and `stopPropagation` the ones it consumes, leaving\n * untouched keys to fall through. This function owns the error-prone half of that contract:\n * the SSR gate, the `{ capture: true }` `keydown` listener and its paired `focusout` listener,\n * the lifted-vs-idle routing decision, and teardown via `DestroyRef`. Both listeners share one\n * `AbortController`, so a single `abort()` drops them and a `capture` flag can no longer be\n * mismatched between an add and its removal. Domain behavior — what lifts, what each key does,\n * what a focus leave costs — stays with the caller through the callbacks.\n *\n * **Resolving a focus leave is the mediator's job, not the caller's.** A `focusout` whose\n * `relatedTarget` is a node reports where focus landed, so containment against the host answers it\n * outright. A\n * `focusout` reporting `relatedTarget: null` says nothing about *where* focus went — focus may\n * have left the document, landed on a non-focusable area, or simply been dropped by a re-render\n * detaching the focused element — so the decision is deferred one microtask and taken against\n * the active element, resolved through open shadow roots, once the focus update has settled, the same resolution\n * `[forNavigationMenu]` applies to its own leave channel. Only then does `onFocusLeave` fire.\n * Before this was folded in, the four callers answered it three different ways and a consumer\n * re-render mid-gesture announced a cancel the user never asked for.\n *\n * The caller keeps ownership of its pointer session and of cancelling an in-flight drag on\n * destroy (those differ per coordinator); this mediator removes only the keyboard / focus\n * listeners it installed.\n */\nexport function createKeyboardDragMediator(config: KeyboardDragMediatorConfig): void {\n if (!config.isBrowser) {\n return;\n }\n const { host } = config;\n let destroyed = false;\n const onKeydown = (event: KeyboardEvent): void => {\n if (config.isLifted()) {\n config.onLiftedKeydown(event);\n } else {\n config.onIdleKeydown(event);\n }\n };\n const reportLeaveIfFocusIsOutside = (): void => {\n if (destroyed || !config.isLifted()) {\n return;\n }\n const active = resolveActiveElement(config.document);\n if (active !== null && composedContains(host, active)) {\n return;\n }\n config.onFocusLeave();\n };\n const onFocusOut = (event: FocusEvent): void => {\n if (!config.isLifted()) {\n return;\n }\n const related = event.relatedTarget;\n if (related instanceof Node) {\n if (!host.contains(related)) {\n config.onFocusLeave();\n }\n return;\n }\n queueMicrotask(reportLeaveIfFocusIsOutside);\n };\n\n const controller = new AbortController();\n host.addEventListener('keydown', onKeydown, { capture: true, signal: controller.signal });\n host.addEventListener('focusout', onFocusOut, { signal: controller.signal });\n\n config.destroyRef.onDestroy(() => {\n destroyed = true;\n controller.abort();\n });\n}\n","import { isImeComposing } from '../keyboard-navigation/ime-composition';\n\n/** A pointer press arriving at a reorder coordinator, read against its keyboard lift. */\nexport interface LiftPress {\n /** Whether a keyboard lift is live. */\n readonly keyboardLifted: boolean;\n /** The item the keyboard lift holds, `null` when none is held. */\n readonly liftedHost: HTMLElement | null;\n /** The item the press landed on, `null` when it landed on no item. */\n readonly pressedHost: HTMLElement | null;\n /** Ends the live keyboard lift through the owner's announced cancel path. */\n cancelKeyboardLift(): void;\n}\n\n/**\n * Arbitrates a pointer press against a live keyboard lift, so the two never run at once. Every\n * keyboard-drop owner calls it from its pointer `canStart`, before writing any pointer state.\n *\n * With no keyboard lift live the press is free. A press on another item cancels the lift first,\n * so the pointer gesture that may follow starts from a clean session. A press on the lifted item,\n * or on no item, is refused and the lift continues.\n *\n * @returns Whether the press may go on to start a pointer gesture.\n */\nexport function arbitrateLiftPress(press: LiftPress): boolean {\n if (!press.keyboardLifted) {\n return true;\n }\n if (press.pressedHost === null || press.pressedHost === press.liftedHost) {\n return false;\n }\n press.cancelKeyboardLift();\n return true;\n}\n\n/**\n * Whether a key keeps its browser default while an item is lifted: a Ctrl / Cmd / Alt chord, a\n * function key, or a key belonging to an IME composition.\n *\n * @param event The keydown event fired while an item is lifted.\n */\nexport function isLiftedPassthroughKey(event: KeyboardEvent): boolean {\n return (\n isImeComposing(event) ||\n event.ctrlKey ||\n event.metaKey ||\n event.altKey ||\n /^F\\d{1,2}$/.test(event.key)\n );\n}\n\n/**\n * Consumes a keydown the lifted drag maps to no action. The event never reaches the collection\n * under the coordinator, and its browser default is cancelled unless\n * {@link isLiftedPassthroughKey} keeps it.\n *\n * @param event The keydown event fired while an item is lifted.\n */\nexport function consumeUnmappedLiftedKey(event: KeyboardEvent): void {\n event.stopPropagation();\n if (!isLiftedPassthroughKey(event)) {\n event.preventDefault();\n }\n}\n","import { isImeComposing } from '../keyboard-navigation/ime-composition';\n\n/**\n * Framework-free pointer-drag session transport.\n *\n * Owns the parts of a pointer drag that have nothing to do with any one primitive's\n * domain model: the host `pointerdown` capture listener, the document-level\n * `pointermove` / `pointerup` / `pointercancel` capture listeners, the arm threshold\n * (a drag is not \"lifted\" until the pointer travels past `armThreshold` from the start\n * point), the post-drag click suppression that stops the release from triggering a\n * stray `click` on whatever sat under the pointer, and — when `capturePointer` is set —\n * pointer capture on the host (which also suppresses the browser's native drag behaviours,\n * e.g. text-selection auto-scroll near a scroll-container edge).\n *\n * The session keeps no Angular DI surface — it's a plain function that returns a cleanup\n * handle. Callers wire it through the directive's `DestroyRef`. Domain decisions stay with\n * the caller through callbacks:\n *\n * - `canStart(event)` runs on `pointerdown`. Return `true` to begin tracking (the start\n * point is recorded), `false` to ignore the press. All primitive-specific guards\n * (disabled state, hit-testing the grabbed element, handle constraints, mouse button)\n * live here.\n * - `onLift(event, start)` fires on the first move that crosses `armThreshold`, before the\n * session arms or captures the pointer, with `start` the recorded press point. Return `false`\n * to abort the session in flight (e.g. the grabbed element has since vanished): the document\n * listeners are torn down and no further callback fires. Return `'skip'` to decline arming for now while keeping the press tracked\n * and unarmed — `onLift` is re-consulted on every subsequent move still past `armThreshold`,\n * with the delta and dominant axis recomputed from the fixed start point each time. Returning\n * `true` or `void` arms the session, captures the pointer when `capturePointer` is set, and\n * lets the move flow through to `onMove`.\n * - `onMove(event)` fires on every armed move after the lift.\n * - `onCommit(event)` fires on `pointerup` while armed.\n * - `onCancel(event?)` fires on `pointercancel`, on `Escape` when `cancelOnEscape` is set, and on an\n * imperative `session.cancel(event?)`. It receives the triggering `PointerEvent` when one exists\n * (`pointercancel` or the event handed to `cancel`), `undefined` for an `Escape` abort.\n *\n * The returned handle also exposes `cancel(event?)`: an imperative abort that tears the in-flight\n * drag down and fires `onCancel(event)` while keeping the host listener alive for the next press.\n * A caller layering its own reactive guards on top of the transport (e.g. `attachSwipeDismiss`\n * re-reading its allowed directions mid-gesture) uses it to cancel from inside `onMove`.\n *\n * **Escape.** With `cancelOnEscape`, a document `keydown` listener alive only while a press is\n * tracked aborts an armed drag, tearing the session down and firing `onCancel` like a\n * `pointercancel`. It is opt-in, so callers owning their own keyboard-drag mode stay unaffected.\n * While armed it consumes the event in the capture phase, so cancelling a drag inside an overlay\n * does not also dismiss the surrounding dialog or popover. A non-armed press stays transparent.\n *\n * **Click suppression.** A `pointerup` ending an armed drag records the release point and installs\n * a capture-phase `click` listener. Only a click landing at those coordinates — the synthetic click\n * the release itself generates — is swallowed; a click elsewhere reaches its target untouched. The\n * listener removes itself after the first click, with a `suppressClickTimeoutMs` fallback if none\n * follows.\n *\n * **Native drag.** While a press accepted through `canStart` is tracked, a capture-phase `dragstart`\n * listener on the host cancels the browser's own HTML5 drag. An image, a link or selected text\n * starts one at about 4px, before most arm thresholds, and the `pointercancel` that follows it\n * would abort the session. A press a nested control opted out of (below) is left alone.\n *\n * **Nested-control opt-out.** When the originating `pointerdown` was `defaultPrevented` by a\n * descendant owning the same gesture, the session stands down on the first move instead of arming.\n * The check is deferred to `pointermove` because the descendant's `preventDefault()` runs in the\n * bubble phase, after this capture-phase listener.\n *\n * **Self-prevention.** A `canStart` calling `preventDefault()` is signalling *ancestor* sessions to\n * stand down, not itself, so the session snapshots `defaultPrevented` around the call and skips its\n * own stand-down check when `canStart` flipped it. A nested handle therefore still arms while its\n * ancestors stand down.\n */\n\n/** A live pointer-drag session. Call `destroy()` to remove every listener. */\nexport interface PointerDragSession {\n /**\n * Remove the host listener, any active document listeners, and any pending click trap.\n * With `cancelOnDestroy` set, an in-flight (tracked) drag is first aborted through the\n * cancel path (`onCancel` fires) before teardown; otherwise `destroy()` fires no callback.\n */\n destroy(): void;\n /**\n * Abort an in-flight drag imperatively, as if a `pointercancel` had arrived: release capture,\n * tear down the active document listeners, and fire `onCancel(event)`. The host `pointerdown`\n * listener stays attached, so a fresh press can still start a new session. A no-op when no\n * press is currently tracked. `event`, when supplied, is forwarded to `onCancel` so the caller\n * can build an event-accurate payload (e.g. the `pointermove` that triggered the abort).\n */\n cancel(event?: PointerEvent): void;\n}\n\n/**\n * The {@link PointerDragSessionOptions.armThreshold} a pointer-driven **resize**\n * gesture uses: the travel a press must cover before it starts mutating the\n * value it resizes.\n *\n * Shared by `[forPaneResizer]` and `[forTableColumnResizer]` so both arm at the same distance. The\n * drag-drop family arms on its own `POINTER_ARM_THRESHOLD_PX`, and Slider arms at `0` because a\n * press on its track commits immediately.\n */\nexport const DRAG_DEAD_ZONE_PX = 3;\n\n/** Configuration for {@link createPointerDragSession}. */\nexport interface PointerDragSessionOptions {\n /** Element whose `pointerdown` (capture) starts a potential session. */\n readonly host: HTMLElement;\n /** The document owning the move/up/cancel/click listeners (injected for SSR/testing). */\n readonly document: Document;\n /** Distance in CSS pixels the pointer must travel before the drag arms (lifts). */\n readonly armThreshold: number;\n /**\n * Runs on `pointerdown`. Return `true` to begin tracking the press as a potential drag,\n * `false` to ignore it. Houses all primitive-specific start guards.\n */\n readonly canStart: (event: PointerEvent) => boolean;\n /**\n * Fires on the first move past `armThreshold`, before the session arms or captures the\n * pointer. `start` is the `pointerdown` point: a drag measures its travel from it, so the\n * distance covered before arming is not lost. Return `false` to abort the session in flight\n * (the grabbed element vanished, etc.); the session tears its listeners down and fires no\n * further callback. Return `'skip'` to\n * decline arming for now while keeping the press tracked and unarmed: `onLift` is re-consulted\n * on every subsequent move still past `armThreshold`, with the delta and dominant axis\n * recomputed from the fixed start point each time. Returning `true` or `void` arms the session\n * and lets the move flow through to `onMove`.\n */\n readonly onLift: (\n event: PointerEvent,\n start: { readonly x: number; readonly y: number },\n ) => boolean | 'skip' | void;\n /** Fires on every armed move after the lift. */\n readonly onMove: (event: PointerEvent) => void;\n /** Fires on `pointerup` while armed. */\n readonly onCommit: (event: PointerEvent) => void;\n /**\n * Fires on `pointercancel`, on `Escape` while armed when {@link cancelOnEscape} is set, and on\n * an imperative {@link PointerDragSession.cancel}. Receives the triggering `PointerEvent` when\n * one exists (`pointercancel`, or the event passed to `cancel`); `undefined` for an `Escape`\n * abort, which has no pointer event.\n */\n readonly onCancel: (event?: PointerEvent) => void;\n /**\n * When `true`, an `Escape` keydown aborts an armed drag (tears the session down and fires\n * `onCancel`). Defaults to `false` so callers owning their own `Escape` handling are unaffected.\n */\n readonly cancelOnEscape?: boolean;\n /**\n * When `true`, `destroy()` aborts an in-flight (tracked) drag through the same path as\n * `cancel()` / `pointercancel` — `resetTracking()` then `onCancel(undefined)` — before removing\n * listeners. Defaults to `false`, so `destroy()` is a pure teardown that fires no callback. Opt in\n * when the owning directive must revert transient drag state on unmount (e.g. a column resizer\n * restoring its pre-drag width).\n */\n readonly cancelOnDestroy?: boolean;\n /**\n * When `true`, the host captures the pointer once the drag arms and releases it on\n * commit / cancel / teardown. Capture also suppresses the browser's native drag behaviours\n * (notably text-selection auto-scroll when the pointer reaches a scroll-container edge).\n * Defaults to `false`; capture is no-op'd in environments without `PointerCapture` (jsdom).\n */\n readonly capturePointer?: boolean;\n /** Fallback timeout (ms) that drops the click trap if no click follows the release. */\n readonly suppressClickTimeoutMs?: number;\n}\n\nconst DEFAULT_SUPPRESS_CLICK_TIMEOUT_MS = 500;\nconst CLICK_SUPPRESS_TOLERANCE_PX = 2;\n\n/**\n * Attach a pointer-drag session to `opts.host`. Returns a {@link PointerDragSession} whose\n * `destroy()` removes every listener and any pending click trap.\n */\nexport function createPointerDragSession(opts: PointerDragSessionOptions): PointerDragSession {\n const { host, document } = opts;\n const suppressTimeout = opts.suppressClickTimeoutMs ?? DEFAULT_SUPPRESS_CLICK_TIMEOUT_MS;\n\n let start: { x: number; y: number } | null = null;\n let armed = false;\n let selfPrevented = false;\n let pointerId: number | null = null;\n let downEvent: PointerEvent | null = null;\n\n let pressListeners: AbortController | null = null;\n let clickTrap: AbortController | null = null;\n\n const removeDocumentListeners = (): void => {\n pressListeners?.abort();\n pressListeners = null;\n };\n\n const removeClickTrap = (): void => {\n clickTrap?.abort();\n clickTrap = null;\n };\n\n const releaseCapture = (): void => {\n if (pointerId === null) {\n return;\n }\n try {\n if (host.hasPointerCapture?.(pointerId)) {\n host.releasePointerCapture?.(pointerId);\n }\n } catch {\n // Some environments (jsdom) reject release on detached nodes.\n }\n };\n\n const resetTracking = (): void => {\n releaseCapture();\n start = null;\n armed = false;\n selfPrevented = false;\n pointerId = null;\n downEvent = null;\n removeDocumentListeners();\n };\n\n const move = (event: PointerEvent): void => {\n if (!start || event.pointerId !== pointerId) {\n return;\n }\n if (!armed) {\n const dx = event.clientX - start.x;\n const dy = event.clientY - start.y;\n if (Math.hypot(dx, dy) < opts.armThreshold) {\n return;\n }\n if (downEvent?.defaultPrevented && !selfPrevented) {\n resetTracking();\n return;\n }\n const lift = opts.onLift(event, start);\n if (lift === false) {\n resetTracking();\n return;\n }\n if (lift === 'skip') {\n return;\n }\n armed = true;\n if (opts.capturePointer && pointerId !== null) {\n try {\n host.setPointerCapture?.(pointerId);\n } catch {\n // Some environments (jsdom) reject capture on detached nodes.\n }\n }\n }\n opts.onMove(event);\n };\n\n const installClickTrap = (release: { x: number; y: number }): void => {\n removeClickTrap();\n const controller = new AbortController();\n const trap = (event: MouseEvent): void => {\n if (\n Math.abs(event.clientX - release.x) <= CLICK_SUPPRESS_TOLERANCE_PX &&\n Math.abs(event.clientY - release.y) <= CLICK_SUPPRESS_TOLERANCE_PX\n ) {\n event.stopPropagation();\n event.preventDefault();\n }\n controller.abort();\n if (clickTrap === controller) {\n clickTrap = null;\n }\n };\n clickTrap = controller;\n document.addEventListener('click', trap, { capture: true, signal: controller.signal });\n setTimeout(() => {\n if (clickTrap === controller) {\n removeClickTrap();\n }\n }, suppressTimeout);\n };\n\n const up = (event: PointerEvent): void => {\n if (event.pointerId !== pointerId) {\n return;\n }\n const wasArmed = armed;\n if (wasArmed) {\n installClickTrap({ x: event.clientX, y: event.clientY });\n }\n resetTracking();\n if (wasArmed) {\n opts.onCommit(event);\n }\n };\n\n const abort = (event?: PointerEvent): void => {\n resetTracking();\n opts.onCancel(event);\n };\n\n const cancel = (event: PointerEvent): void => {\n if (event.pointerId !== pointerId) {\n return;\n }\n abort(event);\n };\n\n const down = (event: PointerEvent): void => {\n if (start !== null) {\n return;\n }\n const preventedBefore = event.defaultPrevented;\n if (!opts.canStart(event)) {\n return;\n }\n selfPrevented = !preventedBefore && event.defaultPrevented;\n start = { x: event.clientX, y: event.clientY };\n armed = false;\n pointerId = event.pointerId;\n downEvent = event;\n\n pressListeners = new AbortController();\n const options = { capture: true, signal: pressListeners.signal };\n document.addEventListener('pointermove', move, options);\n document.addEventListener('pointerup', up, options);\n document.addEventListener('pointercancel', cancel, options);\n\n if (opts.cancelOnEscape) {\n const escape = (event: KeyboardEvent): void => {\n if (armed && event.key === 'Escape' && !isImeComposing(event)) {\n event.preventDefault();\n event.stopPropagation();\n abort();\n }\n };\n document.addEventListener('keydown', escape, options);\n }\n };\n\n const nativeDrag = (event: Event): void => {\n if (start !== null && !(downEvent?.defaultPrevented && !selfPrevented)) {\n event.preventDefault();\n }\n };\n\n const hostListener = new AbortController();\n host.addEventListener('pointerdown', down, { capture: true, signal: hostListener.signal });\n host.addEventListener('dragstart', nativeDrag, { capture: true, signal: hostListener.signal });\n\n return {\n destroy(): void {\n if (opts.cancelOnDestroy && start !== null) {\n abort();\n }\n hostListener.abort();\n releaseCapture();\n removeDocumentListeners();\n removeClickTrap();\n },\n cancel(event?: PointerEvent): void {\n if (start === null) {\n return;\n }\n abort(event);\n },\n };\n}\n","const SLOT_LAYOUT_PROPERTIES = [\n 'position',\n 'top',\n 'right',\n 'bottom',\n 'left',\n 'inset-block-start',\n 'inset-block-end',\n 'inset-inline-start',\n 'inset-inline-end',\n 'width',\n 'height',\n 'transform',\n 'translate',\n] as const;\n\n/**\n * Places the `[forDragPlaceholder]` root nodes in the slot of the out-of-flow `lifted` item by\n * copying each inline position, inset, size and transform declaration the item carries. A\n * declaration the item leaves unset keeps the placeholder's own value, so a template that sizes\n * itself keeps its height. Non-element nodes are skipped.\n */\nexport function layoutPlaceholderInSlot(nodes: readonly Node[], lifted: HTMLElement): void {\n for (const node of nodes) {\n if (!(node instanceof HTMLElement)) {\n continue;\n }\n for (const property of SLOT_LAYOUT_PROPERTIES) {\n const value = lifted.style.getPropertyValue(property);\n if (value !== '') {\n node.style.setProperty(property, value);\n }\n }\n }\n}\n","/** A registered element a press can land in: a drag item, a table row. */\nexport interface PressTarget {\n readonly host: HTMLElement;\n}\n\n/** The part of a registered drag item {@link resolvePressedDragItem} reads. */\nexport interface PressableDragItem extends PressTarget {\n /** Whether the item cannot be lifted. */\n disabled(): boolean;\n /**\n * Whether a pointer press on `target` may start a drag of this item: `false` for a press inside\n * a draggable nested in it, or outside its drag handles when it has any. Has no side effects.\n */\n acceptsPointerStart(target: EventTarget | null): boolean;\n}\n\n/**\n * The entry of `items` whose `host` is `target` or contains it, else `null`. When several do, the\n * innermost wins. Resolves through the registered hosts rather than a selector attribute, so a\n * host that received its directive through `hostDirectives` or a subclass is found like any other.\n */\nexport function findPressedDragItem<T extends PressTarget>(\n items: readonly T[],\n target: EventTarget | null,\n): T | null {\n if (!(target instanceof Node)) {\n return null;\n }\n let pressed: T | null = null;\n for (const item of items) {\n if (item.host.contains(target) && (pressed === null || pressed.host.contains(item.host))) {\n pressed = item;\n }\n }\n return pressed;\n}\n\n/**\n * The drag item a pointer press on `target` would start a drag of: the entry of `items` that\n * {@link findPressedDragItem} resolves, provided it is enabled and accepts a pointer start from\n * `target` (see {@link PressableDragItem.acceptsPointerStart}). `null` otherwise, so a coordinator\n * arms nothing for a press its item's own guard refuses.\n */\nexport function resolvePressedDragItem<T extends PressableDragItem>(\n items: readonly T[],\n target: EventTarget | null,\n): T | null {\n const pressed = findPressedDragItem(items, target);\n if (pressed === null || pressed.disabled() || !pressed.acceptsPointerStart(target)) {\n return null;\n }\n return pressed;\n}\n","import { clampPreviewPosition, type PreviewPoint } from './clamp-preview';\nimport { createDragPreview, wrapPreview, type DragPreview } from './drag-preview';\n\n/** Options handed to {@link PreviewController} at lift time. */\nexport interface PreviewControllerOptions {\n /** The lifted item's host element (the clone source for the default preview). */\n readonly source: HTMLElement;\n /** The lift-time pointer position, used to seed the grab offset and lock origin. */\n readonly point: PreviewPoint;\n /**\n * The floating preview supplied by the draggable (a consumer `[forDragPreview]` template),\n * the minimal `{ moveTo, destroy }` legacy shape, or `null`/`undefined` to let the controller\n * clone the source into the default preview.\n */\n readonly preview?: DragPreview | { moveTo(x: number, y: number): void; destroy(): void } | null;\n /** The owning document (the clone is appended to its body). */\n readonly doc: Document;\n /** The resolved boundary element confining the preview, or `null` for unbounded movement. */\n readonly boundary: HTMLElement | null;\n /** Reactive axis lock read live on every move (`'x'` / `'y'` / `null`). */\n readonly lockAxis: () => 'x' | 'y' | null;\n}\n\n/**\n * Owns a single pointer drag's floating preview and the geometry it carries: the grab offset,\n * the preview size measured at lift (the supplied preview's `element` box, else the source's),\n * the resolved boundary, the axis-lock origin, and the boundary/axis-lock clamp applied on every\n * move.\n *\n * Created once per pointer drag at lift time and disposed via {@link destroy} / {@link settle} at\n * teardown. Shared by both `ForDropList` (drag-drop) and `ForTreeNodeDrag` (tree). The supplied\n * preview may be either a full `DragPreview` or the minimal `{ moveTo, destroy }` shape.\n * Callers with no boundary or axis lock pass `boundary: null` and\n * `lockAxis: () => null` (tree's case), leaving the preview to follow the pointer at the grab\n * offset.\n *\n * Constructed directly (`new PreviewController(options)`); it holds no injection context. The\n * caller gates construction on a browser platform.\n */\nexport class PreviewController {\n readonly #preview: DragPreview;\n readonly #grabOffsetX: number;\n readonly #grabOffsetY: number;\n readonly #previewSize: { width: number; height: number };\n readonly #lockOrigin: { x: number; y: number };\n readonly #boundaryEl: HTMLElement | null;\n readonly #lockAxis: () => 'x' | 'y' | null;\n\n constructor(options: PreviewControllerOptions) {\n const { source, point, preview, doc, boundary, lockAxis } = options;\n const rect = source.getBoundingClientRect();\n this.#grabOffsetX = point.x - rect.left;\n this.#grabOffsetY = point.y - rect.top;\n this.#lockOrigin = { x: point.x - this.#grabOffsetX, y: point.y - this.#grabOffsetY };\n this.#boundaryEl = boundary;\n this.#lockAxis = lockAxis;\n const supplied = preview ? ('settle' in preview ? preview : wrapPreview(preview)) : null;\n this.#preview = supplied ?? createDragPreview(source, doc);\n const box = supplied?.element?.getBoundingClientRect() ?? rect;\n this.#previewSize = { width: box.width, height: box.height };\n const topLeft = this.#clampedTopLeft(point);\n this.#preview.moveTo(topLeft.x, topLeft.y);\n }\n\n /** Position the preview at the clamped top-left for `point`. */\n moveTo(point: PreviewPoint): void {\n const topLeft = this.#clampedTopLeft(point);\n this.#preview.moveTo(topLeft.x, topLeft.y);\n }\n\n /** The boundary/axis-lock-clamped top-left the preview would occupy for `point`. */\n #clampedTopLeft(point: PreviewPoint): PreviewPoint {\n const desired = { x: point.x - this.#grabOffsetX, y: point.y - this.#grabOffsetY };\n const boundaryRect = this.#boundaryEl?.getBoundingClientRect() ?? null;\n return clampPreviewPosition(\n desired,\n this.#previewSize,\n boundaryRect,\n this.#lockAxis(),\n this.#lockOrigin,\n );\n }\n\n /** The underlying preview, for drop-settle animation handoff. */\n get preview(): DragPreview {\n return this.#preview;\n }\n\n /** Remove the preview from the DOM. */\n destroy(): void {\n this.#preview.destroy();\n }\n}\n","/** Previous and new absolute (dataset) index of a reordered windowed row. */\nexport interface WindowReorderResult {\n /** Previous absolute (dataset) index of the lifted row (0-based). */\n readonly from: number;\n /** New absolute (dataset) index the lifted row moves to (0-based). */\n readonly to: number;\n}\n\n/**\n * Absolute index of `value` once the lifted row at `from` has been removed from\n * the dataset: every index above `from` shifts down by one to close the gap the\n * removal opened. The single post-removal shift both insertion branches of\n * {@link translateWindowReorder} share, so the `> from ? 1 : 0` surgery lives in one place rather\n * than being re-derived per branch.\n */\nfunction indexAfterRemoval(value: number, from: number): number {\n return value - (value > from ? 1 : 0);\n}\n\n/**\n * Translates a windowed list's window-relative `previousIndex` / `currentIndex`\n * into absolute dataset indices, so a virtualized list's consumer can apply\n * `moveItemInArray` over the **full** array. `windowIndices` holds the absolute\n * index of every rendered draggable row, in DOM (ascending) order — its length\n * is the rendered window size; `previousIndex` is the lifted row's position in\n * that window and `currentIndex` the resolved insertion index (post-removal\n * space, `0..windowIndices.length - 1`). Reduces to the identity when the window\n * spans the whole dataset, so a non-virtualized list is unaffected.\n */\nexport function translateWindowReorder(\n windowIndices: readonly number[],\n previousIndex: number,\n currentIndex: number,\n): WindowReorderResult {\n const from = windowIndices[previousIndex] ?? previousIndex;\n const rest = windowIndices.filter((_, i) => i !== previousIndex);\n if (currentIndex >= rest.length) {\n const last = rest[rest.length - 1];\n if (last === undefined) {\n return { from, to: from };\n }\n return { from, to: indexAfterRemoval(last + 1, from) };\n }\n const target = rest[currentIndex]!;\n return { from, to: indexAfterRemoval(target, from) };\n}\n\n/** Geometry and state for {@link resolveScrubReorder}. */\nexport interface ScrubReorderParams {\n /**\n * Whether the windowed-scrub affordance is engaged for this gesture (e.g. a\n * modifier key held during a pointer drag). When `false`, scrubbing is off and\n * the resolver returns `null` so the caller falls back to mounted-rect drop\n * resolution.\n */\n readonly engaged: boolean;\n /** Pointer position along the scroll axis, in client pixels. */\n readonly pointer: number;\n /** Scroll viewport's start edge along the scroll axis, in client pixels (top when vertical). */\n readonly viewportStart: number;\n /** Scroll viewport's end edge along the scroll axis, in client pixels (bottom when vertical). */\n readonly viewportEnd: number;\n /** Absolute (dataset) index of the lifted row. */\n readonly from: number;\n /** Total number of items in the full (non-windowed) dataset. */\n readonly count: number;\n}\n\n/**\n * Resolves a **windowed-scrub** drop: maps the pointer's position over the scroll\n * viewport to an absolute dataset index, so a single gesture can drop a lifted row\n * at an arbitrary far target without auto-scroll having to mount it first. The\n * viewport's main-axis extent maps linearly onto the final positions of the whole\n * dataset — the start edge lands the row at index `0`, the end edge at the last\n * index — independent of which rows are currently rendered, so a concurrent\n * auto-scroll never desyncs the result.\n *\n * Returns `null` when scrubbing is not engaged or the geometry is degenerate\n * (zero-height viewport, empty dataset); the caller then uses its normal\n * mounted-rect resolution, leaving the in-window path unchanged. Otherwise returns\n * the `from` / `to` pair with `to` as the row's final index (matching\n * {@link translateWindowReorder}), so `moveItemInArray` over the full array moves\n * the right row to the right place.\n */\nexport function resolveScrubReorder(params: ScrubReorderParams): WindowReorderResult | null {\n if (!params.engaged || params.count <= 0) {\n return null;\n }\n const span = params.viewportEnd - params.viewportStart;\n if (span <= 0) {\n return null;\n }\n const fraction = Math.min(1, Math.max(0, (params.pointer - params.viewportStart) / span));\n return { from: params.from, to: Math.round(fraction * (params.count - 1)) };\n}\n\n/** Inputs for {@link resolveWindowedReorder}. */\nexport interface WindowedReorderParams {\n /**\n * Absolute index of every rendered row in DOM order, or `null` when a rendered row carries\n * none — the list is then not windowed and the window-relative pair is reported unchanged.\n */\n readonly windowIndices: readonly number[] | null;\n /** The lifted row's position in the rendered window. */\n readonly previousIndex: number;\n /** The resolved insertion index in the rendered window (post-removal space). */\n readonly currentIndex: number;\n /**\n * Windowed-scrub geometry for {@link resolveScrubReorder}, without the `from` this resolver\n * derives itself, or `null` when the list offers no scrub.\n */\n readonly scrub: Omit<ScrubReorderParams, 'from'> | null;\n}\n\n/**\n * The dataset-absolute `from` / `to` pair a windowed reorder coordinator reports for one\n * window-relative reorder: the windowed-scrub target when scrub is engaged, else the\n * {@link translateWindowReorder} translation of the window pair. Every announcement and every\n * emitted descriptor of the gesture resolves through it, so what a screen reader hears is\n * where the item lands.\n */\nexport function resolveWindowedReorder(params: WindowedReorderParams): WindowReorderResult {\n const { windowIndices, previousIndex, currentIndex, scrub } = params;\n if (windowIndices === null) {\n return { from: previousIndex, to: currentIndex };\n }\n if (scrub !== null) {\n const scrubbed = resolveScrubReorder({\n ...scrub,\n from: windowIndices[previousIndex] ?? previousIndex,\n });\n if (scrubbed !== null) {\n return scrubbed;\n }\n }\n return translateWindowReorder(windowIndices, previousIndex, currentIndex);\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport { DestroyRef, effect, inject, PLATFORM_ID, type Signal, signal } from '@angular/core';\n\nexport interface ElementBox {\n /** Padding-box width (`clientWidth`) in CSS pixels — content plus padding, excluding borders and any scrollbar. */\n readonly width: number;\n /** Padding-box height (`clientHeight`) in CSS pixels — content plus padding, excluding borders and any scrollbar. */\n readonly height: number;\n /**\n * `scrollWidth` in CSS pixels, as of the last measurement. Re-read only when\n * the element's own box resizes or the observed element changes, so content\n * growing inside an unchanged box leaves it stale.\n */\n readonly scrollWidth: number;\n /**\n * `scrollHeight` in CSS pixels, as of the last measurement. Re-read only when\n * the element's own box resizes or the observed element changes, so content\n * growing inside an unchanged box leaves it stale.\n */\n readonly scrollHeight: number;\n}\n\n/**\n * Observes a target element's size with `ResizeObserver` and exposes the\n * result as a signal. A measurement emits only when one of the four\n * `ElementBox` fields actually changed.\n *\n * Returns `null` until the first measurement is taken (or while `target()`\n * is `null`). The first measurement runs when the observing `effect` first\n * sees a non-null target, then on every `ResizeObserver` callback. The\n * observer reports box-size changes only, so `scrollWidth` / `scrollHeight`\n * follow content that overflows a fixed-size box only on the next resize of\n * the box itself; a caller that needs live scroll extents observes the\n * content element too, as `[forScrollAreaContent]` does.\n *\n * Implementation notes:\n * - Browser-only: `ResizeObserver` is a DOM API, so off-browser (SSR) the\n * helper returns a frozen `signal(null)` and never constructs an observer.\n * - One `ResizeObserver` per call. The browser batches all observers, so\n * creating several is cheap.\n * - The last emitted box is held in a plain `prev` variable, not read back\n * from the `out` signal, so the effect never reads-and-writes the same\n * signal (the activation `sync(el)` would otherwise be a self-cycle).\n * - A single synchronous `sync(el)` runs when the effect attaches the\n * observer, so the target is measured exactly once on first activation.\n * - Cleaned up via `DestroyRef`.\n */\nexport function injectElementSize(target: Signal<HTMLElement | null>): Signal<ElementBox | null> {\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n return signal<ElementBox | null>(null).asReadonly();\n }\n\n const out = signal<ElementBox | null>(null);\n let observed: HTMLElement | null = null;\n let observer: ResizeObserver | null = null;\n let prev: ElementBox | null = null;\n\n const measure = (el: HTMLElement): ElementBox => ({\n width: el.clientWidth,\n height: el.clientHeight,\n scrollWidth: el.scrollWidth,\n scrollHeight: el.scrollHeight,\n });\n\n const sync = (el: HTMLElement): void => {\n const next = measure(el);\n if (\n !prev ||\n prev.width !== next.width ||\n prev.height !== next.height ||\n prev.scrollWidth !== next.scrollWidth ||\n prev.scrollHeight !== next.scrollHeight\n ) {\n prev = next;\n out.set(next);\n }\n };\n\n // React to target changes, and to box resizes through the observer.\n // @sanctioned-effect(external-source): `out` mirrors a ResizeObserver, and the\n // last emitted box is held in `prev` rather than read back from `out`, so no\n // read in this effect can depend on the signal it writes.\n effect(() => {\n const el = target();\n if (el === observed) return;\n if (observer) {\n observer.disconnect();\n observer = null;\n }\n observed = el;\n if (!el) {\n prev = null;\n out.set(null);\n return;\n }\n observer = new ResizeObserver(() => sync(el));\n observer.observe(el);\n sync(el);\n });\n\n inject(DestroyRef).onDestroy(() => {\n observer?.disconnect();\n observer = null;\n observed = null;\n });\n\n return out.asReadonly();\n}\n","import { fortyError } from './errors';\n\nconst TEMPLATE_CAUSE =\n \"Angular resolves a directive's dependencies at the template's declaration site rather than \" +\n 'where it is stamped, so a piece declared in an ng-template outside the root resolves nothing ' +\n 'even when it renders inside it.';\n\n/** Identity of a piece that resolved no coordination context, and of the root it needs. */\nexport interface OrphanContextSpec {\n /** Stable `FORCDK-<AREA>-<NNN>` identifier for this orphan case. */\n readonly code: string;\n /** The piece the error names, e.g. `'ForDialogTitle'` or `'[forSelectOption]'`. */\n readonly piece: string;\n /** Selector(s) of the root it must sit inside, e.g. `'[forDialog]'`. */\n readonly root: string;\n /** Token that resolved nothing, e.g. `'FOR_DIALOG_CONTEXT'`. */\n readonly token: string;\n /** Overrides the entry point derived from `code` — for a shared core resolver. */\n readonly scope?: string;\n}\n\n/**\n * The error a piece throws when it resolved no coordination context — by far\n * the library's most common developer mistake, and the one whose prose had\n * drifted furthest: the same failure was reported with, and without, the\n * ng-template caveat that is its real cause about a fifth of the time.\n *\n * The caveat now ships once, in this module, so every orphan report carries it\n * at no per-entry-point cost.\n */\nexport function orphanContextError(spec: OrphanContextSpec): Error {\n return fortyError({\n code: spec.code,\n scope: spec.scope,\n message: `${spec.piece} must be used inside a ${spec.root} element.`,\n cause: `No ${spec.token} provider is visible from ${spec.piece}. ${TEMPLATE_CAUSE}`,\n fix: `Move ${spec.piece} inside a ${spec.root} element, declaring any ng-template it lives in there too.`,\n });\n}\n\n/** Identity of an overlay trigger that resolved its root through neither channel. */\nexport interface UnresolvedRootSpec {\n /** Stable `FORCDK-<AREA>-<NNN>` identifier for this trigger's unresolved-root case. */\n readonly code: string;\n /** The trigger's selector, e.g. `'[forPopoverTrigger]'`. */\n readonly trigger: string;\n /** Selector of the root, e.g. `'[forPopover]'`. */\n readonly root: string;\n /** Token that resolved nothing, e.g. `'FOR_POPOVER_CONTEXT'`. */\n readonly token: string;\n /** The root's `exportAs` name, for the template-reference fix, e.g. `'forPopover'`. */\n readonly exportAs: string;\n}\n\n/**\n * The error an overlay trigger throws when neither of its two channels resolved\n * a root: no visible `token` provider, and no explicit root passed through its\n * own input. Distinct from {@link orphanContextError} because the second\n * channel makes the remedy different — a trigger stamped from an ng-template\n * can stay where it is and take the root by reference.\n */\nexport function unresolvedRootError(spec: UnresolvedRootSpec): Error {\n return fortyError({\n code: spec.code,\n message: `${spec.trigger} could not resolve its ${spec.root} root.`,\n cause: `No ${spec.token} provider is visible and no explicit root was passed. ${TEMPLATE_CAUSE}`,\n fix:\n `Move ${spec.trigger} inside the ${spec.root} element, or pass the root explicitly: ` +\n `${spec.trigger}=\"root\" with #root=\"${spec.exportAs}\".`,\n });\n}\n","import { inject, InjectionToken, type Signal, signal } from '@angular/core';\n\n/**\n * The positioning-anchor slot a `[forField]` offers the overlay controls inside\n * it. `[forFieldAnchor]` fills it; `[forSelect]`, `[forCombobox]`,\n * `[forDatePicker]` and `[forTimePicker]` position their panel against it when\n * they have no anchor of their own.\n */\nexport interface ForFieldAnchorContext {\n /** The element registered by `[forFieldAnchor]`, or `null`. */\n readonly anchor: Signal<HTMLElement | null>;\n /**\n * Register the field's positioning anchor. A field takes one anchor; a second\n * one still registered once the change-detection pass settles warns in dev\n * mode, and the most recently registered one is used.\n */\n registerAnchor(el: HTMLElement): void;\n /** Remove a previously registered anchor. A no-op for an element that never registered. */\n unregisterAnchor(el: HTMLElement): void;\n}\n\n/**\n * Injection token for the surrounding field's anchor slot. `[forField]`\n * provides it and `[forFieldBoundary]` leaves it in place, so an auxiliary\n * picker opted out of the field's control registration still aligns to the\n * field box. Resolves to `null` inside an overlay surface, whose controls are\n * positioned relative to that surface rather than to the field around it.\n */\nexport const FOR_FIELD_ANCHOR_CONTEXT = new InjectionToken<ForFieldAnchorContext | null>(\n 'FOR_FIELD_ANCHOR_CONTEXT',\n);\n\n/**\n * The surrounding field's anchor element, or a signal that stays `null` when no\n * field is reachable. An overlay root reads it as the fallback between its own\n * anchor and its trigger or input.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\nexport function injectFieldAnchor(): Signal<HTMLElement | null> {\n return (\n inject(FOR_FIELD_ANCHOR_CONTEXT, { optional: true })?.anchor ??\n signal<HTMLElement | null>(null).asReadonly()\n );\n}\n","import { untracked } from '@angular/core';\n\nexport interface DescribedByContribution {\n readonly consumer: string | null;\n write(): void;\n release(): void;\n}\n\ninterface DescribedByOwner {\n readonly consumer: string | null;\n readonly sources: Set<() => string | null>;\n}\n\nconst owners = new WeakMap<Element, DescribedByOwner>();\n\nexport function contributeDescribedBy(\n element: Element,\n ids: () => string | null,\n): DescribedByContribution {\n let owner = owners.get(element);\n if (!owner) {\n owner = { consumer: element.getAttribute('aria-describedby') || null, sources: new Set() };\n owners.set(element, owner);\n }\n const current = owner;\n const source = (): string | null => ids();\n current.sources.add(source);\n return {\n consumer: current.consumer,\n write: () => writeDescribedBy(element, current),\n release: () => {\n if (!current.sources.delete(source)) {\n return;\n }\n if (current.sources.size === 0 && owners.get(element) === current) {\n owners.delete(element);\n }\n untracked(() => writeDescribedBy(element, current));\n },\n };\n}\n\nfunction writeDescribedBy(element: Element, owner: DescribedByOwner): void {\n let value = owner.consumer;\n for (const source of owner.sources) {\n value = composeIds(value, source());\n }\n if (value === null) {\n element.removeAttribute('aria-describedby');\n } else if (element.getAttribute('aria-describedby') !== value) {\n element.setAttribute('aria-describedby', value);\n }\n}\n\n/**\n * Composes a consumer's own id-reference list with the library's own ids: the\n * consumer's ids first, then any library id not already present. Returns `null`\n * when both sides are empty so the caller removes the attribute rather than\n * setting it to `\"\"`.\n *\n * @param consumer The consumer-authored value, captured before the library\n * touched the element.\n * @param libraryIds The library-owned ids to append.\n */\nexport function composeIds(consumer: string | null, libraryIds: string | null): string | null {\n if (!consumer) {\n return libraryIds;\n }\n if (!libraryIds) {\n return consumer;\n }\n const seen = new Set(consumer.split(/\\s+/).filter(Boolean));\n const extra = libraryIds.split(/\\s+/).filter((id) => id && !seen.has(id));\n return extra.length > 0 ? `${consumer} ${extra.join(' ')}` : consumer;\n}\n","import { untracked } from '@angular/core';\n\nimport { fortyWarn } from '../errors/errors';\n\n/** An id-reference attribute whose value one owner replaces rather than composes. */\nexport type ReplacedAttribute = 'aria-labelledby' | 'aria-errormessage';\n\n/** One library piece's claim on a {@link ReplacedAttribute} of an element. */\nexport interface ReplacedAttributeClaim {\n /** The element's static value, captured before any claim wrote the attribute. */\n readonly consumer: string | null;\n /** Writes the element's resolved value. */\n write(): void;\n /** Drops this claim and rewrites the element from the claims that remain. */\n release(): void;\n}\n\ninterface ReplacedAttributeOwner {\n readonly consumer: string | null;\n readonly claims: Set<() => string | null>;\n warned: boolean;\n}\n\nconst owners: Record<ReplacedAttribute, WeakMap<Element, ReplacedAttributeOwner>> = {\n 'aria-labelledby': new WeakMap(),\n 'aria-errormessage': new WeakMap(),\n};\n\n/**\n * Registers a library piece's value for one of an element's replaced id-reference\n * attributes. Every claim on the element resolves the same value: the consumer's\n * static value, captured once by the first claim, else the earliest claim still\n * registered that resolves one. In dev mode a second claim that is still\n * registered once the pass settles, on an element with no consumer value, warns.\n *\n * @param element The element carrying the attribute.\n * @param name The attribute.\n * @param value The ids this piece supplies, or `null` while it supplies none.\n */\nexport function claimReplacedAttribute(\n element: Element,\n name: ReplacedAttribute,\n value: () => string | null,\n): ReplacedAttributeClaim {\n const registry = owners[name];\n let owner = registry.get(element);\n if (!owner) {\n owner = { consumer: element.getAttribute(name) || null, claims: new Set(), warned: false };\n registry.set(element, owner);\n }\n const current = owner;\n const claim = (): string | null => value() || null;\n current.claims.add(claim);\n if ((typeof ngDevMode === 'undefined' || ngDevMode) && current.claims.size > 1) {\n queueMicrotask(() => warnIfContested(element, name, current));\n }\n return {\n consumer: current.consumer,\n write: () => writeReplaced(element, name, current),\n release: () => {\n if (!current.claims.delete(claim)) {\n return;\n }\n if (current.claims.size <= 1) {\n current.warned = false;\n }\n if (current.claims.size === 0 && registry.get(element) === current) {\n registry.delete(element);\n }\n untracked(() => writeReplaced(element, name, current));\n },\n };\n}\n\nfunction writeReplaced(\n element: Element,\n name: ReplacedAttribute,\n owner: ReplacedAttributeOwner,\n): void {\n let value = owner.consumer;\n for (const claim of owner.claims) {\n if (value !== null) {\n break;\n }\n value = claim();\n }\n if (value === null) {\n element.removeAttribute(name);\n } else if (element.getAttribute(name) !== value) {\n element.setAttribute(name, value);\n }\n}\n\nfunction warnIfContested(\n element: Element,\n name: ReplacedAttribute,\n owner: ReplacedAttributeOwner,\n): void {\n if (owner.consumer !== null || owner.claims.size <= 1 || owner.warned) {\n return;\n }\n owner.warned = true;\n fortyWarn({\n code: 'FORCDK-CORE-013',\n message: `${owner.claims.size} library pieces supply \\`${name}\\` for the same <${element.localName}> element.`,\n cause:\n 'The attribute holds one value, so the earliest piece that resolves one is written and ' +\n 'the others are never announced.',\n fix: `Move one of the pieces to another element, or write a static \\`${name}\\` on it, which replaces every library value.`,\n });\n}\n","import { DestroyRef, effect, ElementRef, inject, InjectionToken, type Signal } from '@angular/core';\n\nimport { composedParentElement } from '../composed-tree/composed-tree';\nimport {\n contributeDescribedBy,\n type DescribedByContribution,\n} from '../host-attributes/described-by-owner';\nimport {\n claimReplacedAttribute,\n type ReplacedAttributeClaim,\n} from '../host-attributes/replaced-attribute-owner';\n\n/**\n * A validation error a form control reports to its surrounding `[forField]`.\n * Signal Forms' `ValidationError` is assignable to it.\n */\nexport interface FieldValidationError {\n /** Identifies the kind of error, such as `'required'`. */\n readonly kind: string;\n /** Human-readable message, when the validator supplied one. */\n readonly message?: string;\n}\n\n/**\n * A form control's contribution to its surrounding `[forField]`. The control\n * exposes the signals the field needs to reflect state (`data-invalid` etc.)\n * and to gate the error region; `host` is the wiring target for `id` and the\n * `aria-*` association attributes.\n */\nexport interface FieldControlHandle {\n /**\n * The control's host element. Default target of `id` / `aria-*` wiring and\n * of the label click, unless {@link labelledElement} nominates a distinct\n * element.\n */\n readonly host: HTMLElement;\n /**\n * The element that should carry the field's `aria-*` association, when it\n * differs from {@link host}. For primitives whose host is a non-interactive\n * wrapper (`<div forSelect>`, `<div forCombobox>`) this nominates the\n * focusable control inside it (the trigger button / `role=\"combobox\"` input),\n * which registers after the field wiring runs — hence a signal. When omitted\n * or resolving to `null` the field falls back to {@link host} (the\n * host-is-the-control case, e.g. `ForListbox` or a native\n * `<input forFieldControl>`).\n *\n * This nominates the **association** target only. Where focus should land on\n * a label click is {@link focus}'s job, because the two diverge on a\n * composite: a segmented date / time field names its whole `role=\"group\"` on\n * this channel and focuses one spinbutton inside it.\n */\n readonly labelledElement?: Signal<HTMLElement | null>;\n /**\n * The element a label press clicks and focuses, when it differs from the\n * association target. A picker-anatomy `[forCombobox]` nominates its trigger\n * here: while its panel is open the association moves onto the search input\n * inside it, but the label keeps toggling the panel through the trigger.\n * When omitted or resolving to `null` the label activates the association\n * target.\n */\n readonly activationTarget?: Signal<HTMLElement | null>;\n /**\n * Moves focus into the control, when it exposes an entry point of its own\n * (`FormValueControl.focus`). The field prefers this over focusing the\n * association target on a label click, because a composite root is not\n * focusable: `[forDateField]` & friends host a `role=\"group\"` whose real\n * entry point is the first editable segment. Omitted by controls whose\n * association target is itself focusable, where the field focuses that\n * element directly.\n */\n readonly focus?: (options?: FocusOptions) => void;\n /**\n * The id already host-bound on {@link labelledElement} (the Select trigger's\n * `triggerId`, the Combobox input's `inputId`). The field adopts it as its\n * `controlId` so the label's `for` points at the focusable control and the\n * primitive's own `aria-labelledby` (e.g. on the listbox content) stays in\n * sync. Only meaningful alongside `labelledElement`.\n */\n readonly labelledElementId?: Signal<string | undefined>;\n /** Reflected by the field as `data-invalid` and gates the error region. */\n readonly invalid?: Signal<boolean>;\n /** Reflected by the field as `data-required`. */\n readonly required?: Signal<boolean>;\n /** Reflected by the field as `data-disabled`. */\n readonly disabled?: Signal<boolean>;\n /** Reflected by the field as `data-touched`. */\n readonly touched?: Signal<boolean>;\n /** Validation errors surfaced by Signal Forms; read by `ForFieldError`. */\n readonly errors?: Signal<readonly FieldValidationError[]>;\n /**\n * Whether a composite control around this one currently stands in for it —\n * a field-anatomy `[forDatePicker]` adopting its `[forDateField]`. While\n * `true` the field neither resolves this handle as its control nor wires its\n * association attributes onto it; the adopting composite registers its own\n * handle and nominates this control's host as its labelled element.\n */\n readonly adopted?: Signal<boolean>;\n}\n\n/**\n * Coordination contract owned by the `ForField` root. The label, description,\n * and error pieces register with it and read the generated ids; the control\n * (via `injectFieldWiring`) registers its handle and consumes the resolved\n * `aria-*` ids.\n */\nexport interface ForFieldContext {\n /** Id assigned to the control (a label's `for` points here). */\n readonly controlId: Signal<string>;\n /** Id of the label element. */\n readonly labelId: Signal<string>;\n /** Id of the description element. */\n readonly descriptionId: Signal<string>;\n /** Id of the error element. */\n readonly errorId: Signal<string>;\n /** Resolved `aria-labelledby` for the control (label id, or null). */\n readonly labelledBy: Signal<string | null>;\n /** Resolved `aria-describedby` (description id, plus error id when invalid). */\n readonly describedBy: Signal<string | null>;\n /** Resolved `aria-errormessage` (error id when present and invalid, else null). */\n readonly errorMessageId: Signal<string | null>;\n /** Whether the registered control is currently invalid. */\n readonly invalid: Signal<boolean>;\n /** Whether the registered control is required. */\n readonly required: Signal<boolean>;\n /** Whether the registered control is disabled. */\n readonly disabled: Signal<boolean>;\n /** Whether the registered control has been touched. */\n readonly touched: Signal<boolean>;\n /** The currently registered control handle, or null. */\n readonly control: Signal<FieldControlHandle | null>;\n /**\n * The element a label press activates: the control's\n * {@link FieldControlHandle.activationTarget} when it nominates one, else\n * the element carrying the association. `null` while no control is\n * registered.\n */\n readonly activationTarget: Signal<HTMLElement | null>;\n /** The host elements of the registered `[forLabel]`s, in registration order. */\n readonly labelElements: Signal<readonly HTMLElement[]>;\n /**\n * Register the control whose state the field reflects. A field exposes a\n * single `controlId` (not an id list), so one control per `[forField]` is the\n * supported shape — group several under a `[forFieldset]`. Registrations are\n * tracked so unmounting one of several accidental duplicates falls back to the\n * previous still-mounted control; a duplicate is flagged with a dev-mode\n * warning.\n */\n registerControl(handle: FieldControlHandle): void;\n /** Remove a previously registered control. */\n unregisterControl(handle: FieldControlHandle): void;\n /**\n * Register a label's host element; returns an unregister callback. A static\n * `id` on the host is adopted as the `labelId`. The field\n * exposes a single `labelId` (not an id list), so one `[forLabel]` per field\n * is the supported shape. Registrations are **counted** (not a boolean) so\n * unmounting one of several accidental duplicates never drops the association\n * while another is still mounted; a duplicate is flagged with a dev-mode\n * warning.\n */\n registerLabel(element: HTMLElement): () => void;\n /** Register a description's host element; returns an unregister callback. A static `id` on the host is adopted as the `descriptionId`. Counted, single `[forFieldDescription]` per field — see {@link registerLabel}. */\n registerDescription(element: HTMLElement): () => void;\n /** Register an error region's host element; returns an unregister callback. A static `id` on the host is adopted as the `errorId`. Counted, single `[forFieldError]` per field — see {@link registerLabel}. */\n registerError(element: HTMLElement): () => void;\n /**\n * Forward a click to the registered control, then move focus into it — the\n * same outcome a native `<label for>` produces through the browser's\n * click-forwarding (toggling a checkbox / switch, activating a button). Used\n * by a `[forLabel]` the browser will not forward for: a non-`<label>` host,\n * which has no native `for` forwarding at all, and a native `<label>` whose\n * `for` resolves to an element other than the {@link activationTarget} (the\n * `role=\"group\"` of a segmented date / time field, the search input of an\n * open picker-anatomy combobox), so label-click activation stays consistent\n * across host shapes and control anatomies.\n */\n clickControl(): void;\n}\n\n/**\n * Injection token for the surrounding `ForField` coordination contract.\n * Resolves to `null` under a field boundary (`[forFieldBoundary]` and every\n * overlay surface that can host a control), so inject it with\n * `{ optional: true }` and treat `null` as \"no field\".\n */\nexport const FOR_FIELD_CONTEXT = new InjectionToken<ForFieldContext | null>('FOR_FIELD_CONTEXT');\n\nconst INTERACTIVE_CONTENT = 'a[href], button, input, select, textarea, summary, [tabindex]';\n\n/**\n * Wires the calling directive's host element to a surrounding `[forField]`,\n * if one exists. When there is no ancestor field this is a near-zero-cost\n * no-op (a single optional DI lookup), so every `FormUiControlBase` subclass\n * can call it unconditionally and gain field support for free.\n *\n * When a field is present it:\n * - registers the control handle so the field can reflect `data-*` state,\n * gate its error region, and focus the control on label click;\n * - reflects `id` (only if the target has none — the field owns the id a\n * label's `for` points at), `aria-labelledby`, and `aria-errormessage` on\n * the target, kept in sync via a single `effect`. A **static**\n * `aria-labelledby` / `aria-errormessage` the consumer wrote on the target\n * **replaces** the field's value (a name has one owner) and is restored\n * verbatim on teardown, so the field never erases or overrides it. When\n * another library piece also names the target, the one registered first\n * keeps the attribute, and dev mode warns;\n * - **composes** `aria-describedby`: any value the consumer set statically on\n * the target is captured on first wiring and preserved, with the field's own\n * description / error ids appended after it — so a `aria-describedby=\"hint\"`\n * is never clobbered, and it is restored verbatim when the control (or the\n * target) is torn down. Ids another library piece contributes to the same\n * element (a tooltip trigger on the control) are kept beside the field's.\n *\n * The wiring target is the host by default, or the handle's\n * {@link FieldControlHandle.labelledElement} when it nominates a distinct\n * focusable control (Select trigger / Combobox input) inside a non-interactive\n * wrapper host. That element registers after this runs, so the effect tracks it\n * reactively and migrates the attributes (clearing the previously-targeted\n * element) once it appears.\n *\n * Imperative DOM writes (mirroring `FormUiControlBase`'s `data-*` reflection)\n * so the caller's declarative `host: { ... }` block stays free of these\n * attributes.\n *\n * @param handle The control's state signals (all optional). `host` is filled\n * in from the calling directive's `ElementRef`. Pass `labelledElement` to\n * target a child control instead of the host.\n */\nexport function injectFieldWiring(handle: Omit<FieldControlHandle, 'host'> = {}): void {\n const field = inject(FOR_FIELD_CONTEXT, { optional: true });\n if (!field) {\n return;\n }\n\n const el = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const fullHandle: FieldControlHandle = { host: el, ...handle };\n field.registerControl(fullHandle);\n inject(DestroyRef).onDestroy(() => field.unregisterControl(fullHandle));\n\n const labelledElement = handle.labelledElement;\n const adopted = handle.adopted;\n let previousTarget: HTMLElement | null = null;\n let ownsId = false;\n let association: FieldAssociation | null = null;\n\n effect(() => {\n // Resolve the wiring target: the nominated focusable element when a\n // `labelledElement` is declared, else the host. A declared-but-unresolved\n // labelled element (its directive registers after this runs) yields `null`\n // here, and we wire nothing — never the wrapper host — until it appears.\n const target = adopted?.() ? null : labelledElement ? labelledElement() : el;\n\n if (previousTarget !== target) {\n if (previousTarget) {\n releaseTarget(previousTarget, ownsId, field.controlId());\n ownsId = false;\n }\n association?.release();\n association = target ? associate(target, field) : null;\n previousTarget = target;\n }\n\n if (!target) {\n return;\n }\n\n if (!target.getAttribute('id')) {\n target.setAttribute('id', field.controlId());\n ownsId = true;\n }\n association?.write();\n });\n\n inject(DestroyRef).onDestroy(() => {\n if (previousTarget) {\n releaseTarget(previousTarget, ownsId, field.controlId());\n }\n association?.release();\n });\n}\n\ninterface FieldAssociation {\n write(): void;\n release(): void;\n}\n\n/**\n * Claims the target's `aria-labelledby` and `aria-errormessage` and contributes\n * to its `aria-describedby`, each through the attribute's per-element owner, so\n * a consumer's static value and any other library piece's are kept.\n */\nfunction associate(target: HTMLElement, field: ForFieldContext): FieldAssociation {\n const parts: ReadonlyArray<ReplacedAttributeClaim | DescribedByContribution> = [\n claimReplacedAttribute(target, 'aria-labelledby', () => field.labelledBy()),\n contributeDescribedBy(target, () => field.describedBy()),\n claimReplacedAttribute(target, 'aria-errormessage', () => field.errorMessageId()),\n ];\n return {\n write: () => parts.forEach((part) => part.write()),\n release: () => parts.forEach((part) => part.release()),\n };\n}\n\n/**\n * Drops the field-owned `id` from a previously-targeted element when this\n * helper set it, so an arbitrary foreign `labelledElement` is left clean once\n * the control is destroyed or the target migrates.\n */\nfunction releaseTarget(target: HTMLElement, ownsId: boolean, controlId: string): void {\n if (ownsId && target.getAttribute('id') === controlId) {\n target.removeAttribute('id');\n }\n}\n\nexport function crossesInteractiveContent(target: Node | null, boundary: Element): boolean {\n for (let node = target; node !== null && node !== boundary; node = composedParentElement(node)) {\n if (node.nodeType === node.ELEMENT_NODE && (node as Element).matches(INTERACTIVE_CONTENT)) {\n return true;\n }\n }\n return false;\n}\n\nexport function injectFieldLabelExemption(\n exempt: () => readonly Element[],\n): (target: Node) => readonly Element[] {\n const field = inject(FOR_FIELD_CONTEXT, { optional: true, skipSelf: true });\n if (!field) {\n return exempt;\n }\n return (target) => {\n const elements = exempt();\n const control = field.activationTarget();\n if (control === null || !elements.includes(control)) {\n return elements;\n }\n const labels = field\n .labelElements()\n .filter((label) => !crossesInteractiveContent(target, label));\n return [...elements, ...labels];\n };\n}\n","import { InjectionToken, type Signal } from '@angular/core';\n\n/**\n * Coordination contract owned by the `ForFieldset` root. A `[forFieldsetLegend]`\n * reads `legendId`, hands its host over for static-`id` adoption, and registers\n * its presence so the fieldset can resolve its `aria-labelledby`; a descendant\n * form control optionally reads `effectiveDisabled` and ORs it into its own\n * disabled state.\n *\n * The token lives in its own file (no directive import) so a consumer of another\n * primitive — a form control reading `effectiveDisabled` here — pulls in only the\n * token, never the `ForFieldset` directive, keeping the library tree-shakable.\n */\nexport interface ForFieldsetContext {\n /** Id of the legend element; the group's `aria-labelledby` points here. */\n readonly legendId: Signal<string>;\n /**\n * Adopt a consumer-set **static** `id` on the legend host into `legendId`, so\n * the legend's `[id]` host binding re-emits it instead of clobbering it with\n * the generated fallback. Called by `[forFieldsetLegend]` from its\n * constructor, before the first host-binding pass.\n */\n adoptLegendId(el: HTMLElement): void;\n /**\n * Whether the fieldset (and therefore its descendants) is effectively\n * disabled — its own `disabled` input OR'd with an enclosing disabled\n * `[forFieldset]`, so nested groups compose like native `<fieldset disabled>`.\n * Descendant controls OR this into their own disabled state.\n */\n readonly disabled: Signal<boolean>;\n /** Mark a legend present; returns an unregister callback. */\n registerLegend(): () => void;\n}\n\n/** Injection token for the surrounding `ForFieldset` coordination contract. */\nexport const FOR_FIELDSET_CONTEXT = new InjectionToken<ForFieldsetContext>('FOR_FIELDSET_CONTEXT');\n","import {\n composedContains,\n composedParentElement,\n composedPrecedes,\n} from '../composed-tree/composed-tree';\n\n/**\n * The ten local names {@link FOCUSABLE_SELECTOR} anchors a clause on, each\n * mapped to the qualifier that clause carries — `[href]` for the two link\n * elements, `[controls]` for the two media ones, `:not([disabled])` for the\n * form controls, and nothing for the two that are focusable on their own.\n * Keys are lowercase and compared against `localName` rather than `tagName`,\n * so the two agree on a non-HTML-namespaced element: an SVG `<a href>` is\n * matched by the selector's `a[href]` clause and reports `tagName` `'a'`,\n * which an uppercase set would drop.\n */\nconst FOCUSABLE_LOCAL_NAME_QUALIFIERS: Readonly<Record<string, string>> = {\n a: '[href]',\n area: '[href]',\n button: ':not([disabled])',\n input: ':not([disabled]):not([type=\"hidden\"])',\n select: ':not([disabled])',\n textarea: ':not([disabled])',\n audio: '[controls]',\n video: '[controls]',\n iframe: '',\n summary: '',\n};\n\n/**\n * The two clauses {@link FOCUSABLE_SELECTOR} anchors on an attribute rather\n * than on a local name, so any element can match them.\n */\nconst FOCUSABLE_ATTRIBUTE_CLAUSES = ['[tabindex]:not([tabindex=\"-1\"])', '[contenteditable=\"true\"]'];\n\nconst HIDDEN_ATTRIBUTE = 'hidden';\nconst INERT_ATTRIBUTE = 'inert';\nconst OPEN_ATTRIBUTE = 'open';\n\n/**\n * Shared CSS selector for focusable elements. Single source of truth for the\n * library — primitives that need their own focus-finding logic (e.g. the\n * dialog directive's non-modal initial focus, the programmatic dialog\n * manager's bootstrap, future menu / popover initial-focus paths) import\n * this rather than maintaining a private copy that drifts.\n *\n * This matches elements that can *receive* focus — the superset used for\n * initial-focus targets. A natively-focusable element carrying\n * `tabindex=\"-1\"` (e.g. a `<button tabindex=\"-1\">` roving-tabindex\n * collection item) still matches via its tag selector, but is excluded from\n * the sequential Tab cycle at runtime by `isTabbableCandidate`. `iframe` and\n * `summary` are included because both are natively focusable and can\n * legitimately be an initial-focus target inside a trapped surface.\n *\n * Derived from {@link FOCUSABLE_LOCAL_NAME_QUALIFIERS} plus\n * {@link FOCUSABLE_ATTRIBUTE_CLAUSES} so the pre-filter below cannot fall out\n * of step with it — the correspondence the two used to keep by hand is now\n * structural. `focusable-candidate.spec.ts` pins the derived clause set\n * against the literal it replaced.\n */\nexport const FOCUSABLE_SELECTOR = /* @__PURE__ */ [\n ...Object.entries(FOCUSABLE_LOCAL_NAME_QUALIFIERS).map(([name, qualifier]) => name + qualifier),\n ...FOCUSABLE_ATTRIBUTE_CLAUSES,\n].join(',');\n\nfunction focusabilityAttributes(selector: string): string[] {\n return [\n ...new Set([\n ...[...selector.matchAll(/\\[([\\w-]+)/g)].map((match) => match[1]!),\n HIDDEN_ATTRIBUTE,\n INERT_ATTRIBUTE,\n OPEN_ATTRIBUTE,\n ]),\n ];\n}\n\nexport const FOCUSABILITY_ATTRIBUTES: readonly string[] =\n /* @__PURE__ */ focusabilityAttributes(FOCUSABLE_SELECTOR);\n\n/**\n * Every element under `container` matching {@link FOCUSABLE_SELECTOR}, in\n * composed-tree order, descending into open shadow roots.\n *\n * The walk enumerates elements and filters in JS rather than handing the selector to the engine,\n * because `querySelectorAll` stops at a shadow boundary and a shadow host is not expressible in\n * CSS. `container`'s own shadow root is traversed before its light children, matching what\n * `composedContains` already counts as inside it. Closed shadow roots stay invisible.\n *\n * **Order** follows the light tree with each host's shadow contents inlined at the host — the\n * flattened order for a host that renders no `<slot>`. Once content is slotted the two diverge:\n * assigned nodes are visited with the light tree, after the whole shadow tree, whereas the browser\n * sequences them at the `<slot>`'s position. A host with focusables after its `<slot>` therefore\n * yields a first / last pair the real Tab cycle disagrees with.\n */\nexport function queryFocusableCandidates(container: HTMLElement): HTMLElement[] {\n const found: HTMLElement[] = [];\n if (container.shadowRoot) {\n collectFocusableCandidates(container.shadowRoot, found);\n }\n collectFocusableCandidates(container, found);\n return found;\n}\n\n/**\n * Reports whether `el` can currently receive focus. An element is excluded when it:\n *\n * - carries the `[hidden]` attribute;\n * - is `:disabled`, by its own `disabled` attribute or by an ancestor `<fieldset disabled>`\n * (a control inside that fieldset's first `<legend>` stays enabled);\n * - carries `[inert]` itself, or is nested under an `[inert]` ancestor below `root`;\n * - is not rendered: `display: none` on the element or any ancestor below `root`,\n * `visibility: hidden` / `collapse` on the element itself, `content-visibility: hidden` on an\n * ancestor below `root`, or content of a closed `<details>` below `root` outside its first\n * `<summary>`.\n *\n * `root` bounds the ancestor walk, so the container's own state is never consulted. Both walks\n * climb the composed tree, so an `[inert]` or `display: none` shadow host disqualifies the controls\n * inside its shadow root.\n *\n * This is the *focusable* set, not the Tab cycle: a candidate carrying `tabindex=\"-1\"` qualifies.\n *\n * Reads `getComputedStyle`, so callers must gate it behind `isPlatformBrowser`.\n */\nexport function isFocusableCandidate(el: HTMLElement, root: HTMLElement): boolean {\n return (\n !el.hasAttribute(HIDDEN_ATTRIBUTE) &&\n !isDisabledControl(el) &&\n !hasInertAncestor(el, root) &&\n !isUnrendered(el, root)\n );\n}\n\n/**\n * Whether `el` is a form control the browser refuses to focus because it is `:disabled`: its own\n * `disabled` attribute, or an ancestor `<fieldset disabled>` it does not sit in the first\n * `<legend>` of. An element that has no disabled state, such as a `tabindex` host inside a disabled\n * fieldset, reports `false`.\n */\nexport function isDisabledControl(el: Element): boolean {\n return el.matches(':disabled');\n}\n\n/**\n * Reports whether `el` is a *tabbable* candidate — a focusable candidate\n * (`isFocusableCandidate`) that also participates in the sequential Tab cycle\n * (`tabIndex >= 0`). A natively-focusable element carrying `tabindex=\"-1\"` is\n * a valid focus target but is excluded here.\n *\n * A native radio in a named group is a tab stop only when it is the group's checked member, or\n * when no member is checked: the browser stops on one radio per group. The group is every radio\n * sharing its name and form owner in the same document or shadow root, inside `root` or not.\n */\nexport function isTabbableCandidate(el: HTMLElement, root: HTMLElement): boolean {\n return isTabStop(el, root, new Map());\n}\n\n/**\n * Reports whether `el` can take an explicit initial-focus move into `root`: it lives inside `root`\n * in the composed tree, is focusable natively or through a `tabindex` attribute (`tabindex=\"-1\"`\n * included, so a static heading qualifies), and is a focusable candidate under\n * {@link isFocusableCandidate}.\n *\n * Reads `getComputedStyle`, so callers must gate it behind `isPlatformBrowser`.\n */\nexport function isInitialFocusTarget(el: HTMLElement, root: HTMLElement): boolean {\n return (\n composedContains(root, el) &&\n (el.matches(FOCUSABLE_SELECTOR) || el.hasAttribute('tabindex')) &&\n isFocusableCandidate(el, root)\n );\n}\n\n/** The two ends of a container's Tab cycle, as resolved by {@link findTabbableEdges}. */\nexport interface TabbableEdges {\n /** First tabbable descendant in candidate order, or `null` when the container has none. */\n first: HTMLElement | null;\n /** Last tabbable descendant; the same element as `first` when only one qualifies. */\n last: HTMLElement | null;\n}\n\n/**\n * The first and last tabbable descendants of `container`, resolved from a single\n * {@link queryFocusableCandidates} enumeration.\n *\n * Only the two ends are ever needed to cycle Tab, so the filter runs from each end and stops on the\n * first candidate that qualifies instead of resolving the whole set. That is what keeps the cost of\n * a keystroke off the size of the surface: `isFocusableCandidate` climbs the composed ancestor chain\n * calling `getComputedStyle` at every level, so filtering N candidates to read two of them costs\n * O(N × depth) forced style recalculations where O(depth) will do. The cheap `tabIndex` half of the\n * test is what makes the scan short on a roving collection too — every item carrying\n * `tabindex=\"-1\"` is rejected without a style read.\n *\n * Both ends are `null` only when the container has no tabbable descendant at all, which is the one\n * case that still walks every candidate.\n */\nexport function findTabbableEdges(container: HTMLElement): TabbableEdges {\n const candidates = queryFocusableCandidates(container);\n const groups = new Map<HTMLInputElement, boolean>();\n const firstIndex = candidates.findIndex((el) => isTabStop(el, container, groups));\n if (firstIndex === -1) {\n return { first: null, last: null };\n }\n const first = candidates[firstIndex]!;\n for (let i = candidates.length - 1; i > firstIndex; i--) {\n const candidate = candidates[i]!;\n if (isTabStop(candidate, container, groups)) {\n return { first, last: candidate };\n }\n }\n return { first, last: first };\n}\n\n/**\n * Whether a Tab press from `active` leaves the Tab cycle whose ends are `edges`: going backward\n * from the first tabbable or anything before it, going forward from the last tabbable or anything\n * after it. An edge that is a native radio stands for its whole group, since Tab from any member\n * moves past all of them. A container with no tabbable descendant, or a `null` `active`, always\n * leaves.\n */\nexport function leavesTabSequence(\n { first, last }: TabbableEdges,\n active: Element | null,\n backward: boolean,\n): boolean {\n if (first === null || last === null || active === null) {\n return true;\n }\n return backward\n ? active === first || inSameRadioGroup(active, first) || composedPrecedes(active, first)\n : active === last || inSameRadioGroup(active, last) || composedPrecedes(last, active);\n}\n\n/**\n * Where a Tab press from `active` lands when the tabbable descendants of `moved` are read as\n * sitting right after `anchor` in the document's Tab sequence, or `null` when the press can be\n * left to the browser.\n *\n * A press starting at `anchor` or inside `moved` always resolves to a stop, so the relocated\n * stretch is walked the same way in a browser that skips some of its elements by default, as\n * Safari does links. Any other press is left to the browser when document order lands on the same\n * stop. `null` is also returned for an `active` or `anchor` outside the candidate set, an `anchor`\n * inside `moved`, and a move that would run off either end of the sequence.\n *\n * Both sequences are read from {@link queryFocusableCandidates} over the document body, so the\n * order limits stated there apply, and a positive `tabindex` is read in document order.\n *\n * Reads `getComputedStyle`, so callers must gate it behind `isPlatformBrowser`.\n */\nexport function findRelocatedTabStop(\n active: Element,\n anchor: HTMLElement,\n moved: HTMLElement,\n backward: boolean,\n): HTMLElement | null {\n const doc = anchor.ownerDocument;\n if (!doc.body || composedContains(moved, anchor)) {\n return null;\n }\n const candidates = queryFocusableCandidates(doc.body);\n const outside: HTMLElement[] = [];\n const inside: HTMLElement[] = [];\n for (const candidate of candidates) {\n (composedContains(moved, candidate) ? inside : outside).push(candidate);\n }\n const anchorIndex = outside.indexOf(anchor);\n if (anchorIndex === -1) {\n return null;\n }\n const relocated = [\n ...outside.slice(0, anchorIndex + 1),\n ...inside,\n ...outside.slice(anchorIndex + 1),\n ];\n const root = doc.documentElement;\n const groups = new Map<HTMLInputElement, boolean>();\n const step = backward ? -1 : 1;\n const target = nextTabStop(relocated, active, step, root, groups);\n if (target === null || active === anchor || composedContains(moved, active)) {\n return target;\n }\n const native = nextTabStop(candidates, active, step, root, groups);\n return target === native ? null : target;\n}\n\nfunction nextTabStop(\n sequence: readonly HTMLElement[],\n active: Element,\n step: 1 | -1,\n root: HTMLElement,\n groups: Map<HTMLInputElement, boolean>,\n): HTMLElement | null {\n const from = sequence.findIndex((el) => el === active);\n if (from === -1) {\n return null;\n }\n for (let i = from + step; i >= 0 && i < sequence.length; i += step) {\n const candidate = sequence[i]!;\n if (isTabStop(candidate, root, groups)) {\n return candidate;\n }\n }\n return null;\n}\n\n/**\n * The focusable descendant of `container` one step from `from` in candidate order — the next\n * one for `'forward'`, the previous for `'backward'` — wrapping around at either end, so a\n * caller cycling a bounded set never runs out. `null` only when `container` has no focusable\n * descendant at all.\n *\n * `from` is matched against the candidate set through composed containment, resolving to the\n * *innermost* candidate that contains it: an event target nested inside a candidate (a `<span>`\n * within a `<button>`) steps from that candidate, and a candidate nested inside another (a\n * `<button>` inside a `<summary>`) steps from the inner one rather than from its wrapper. A `from`\n * that is `null`, outside `container`, or no longer a candidate yields the first candidate going\n * forward and the last going backward — the step stays inside `container` either way.\n *\n * This is the *focusable* set, not the Tab cycle: a candidate carrying `tabindex=\"-1\"` takes part,\n * so the cycle reaches exactly what {@link findFirstFocusable} would enter.\n *\n * Like {@link findTabbableEdges} it filters lazily, walking outwards from `from` and stopping on\n * the first candidate that qualifies, so a keystroke costs the O(depth) style reads of a single\n * `isFocusableCandidate` call rather than the O(N × depth) of filtering the whole set up front.\n * Only a container whose every candidate is hidden walks all of them, which is the case that\n * returns `null`.\n *\n * Reads `getComputedStyle`, so callers must gate it behind `isPlatformBrowser`.\n */\nexport function stepFocusableCycle(\n container: HTMLElement,\n from: Element | null,\n direction: 'forward' | 'backward',\n): HTMLElement | null {\n const candidates = queryFocusableCandidates(container);\n if (candidates.length === 0) {\n return null;\n }\n const step = direction === 'forward' ? 1 : -1;\n const current = from === null ? -1 : indexOfInnermostContaining(candidates, from);\n const start = current === -1 ? (step === 1 ? 0 : candidates.length - 1) : current + step;\n for (let i = 0; i < candidates.length; i++) {\n const offset = (start + i * step) % candidates.length;\n const candidate = candidates[(offset + candidates.length) % candidates.length]!;\n if (isFocusableCandidate(candidate, container)) {\n return candidate;\n }\n }\n return null;\n}\n\n/**\n * The index of the innermost candidate containing `from`, or `-1` when none does. The candidates\n * that contain `from` are its ancestors-or-self, so document order lists them outermost first and\n * the last match is the innermost — the one that actually holds the focus, rather than a wrapper\n * whose next step would land back on it.\n */\nfunction indexOfInnermostContaining(candidates: readonly HTMLElement[], from: Element): number {\n for (let i = candidates.length - 1; i >= 0; i--) {\n if (composedContains(candidates[i]!, from)) {\n return i;\n }\n }\n return -1;\n}\n\nconst FOCUSABLE_LOCAL_NAMES = /* @__PURE__ */ new Set(\n /* @__PURE__ */ Object.keys(FOCUSABLE_LOCAL_NAME_QUALIFIERS),\n);\n\n/**\n * Whether `el` could possibly match {@link FOCUSABLE_SELECTOR} — a deliberate superset, so `false`\n * is a safe skip and `true` still has to clear the selector itself.\n *\n * Every clause of that selector is anchored on one of {@link FOCUSABLE_LOCAL_NAMES}, on\n * `[tabindex]:not([tabindex=\"-1\"])`, or on `[contenteditable=\"true\"]`, which lets a structural\n * element answer without entering the selector engine. The name-anchored half is the same\n * declaration the selector is built from, so a name can no longer be added to one and not the\n * other; the two attribute clauses are matched here in their relaxed form (any\n * `contenteditable` value, not only `\"true\"`), which is what keeps this a superset.\n */\nfunction mayMatchFocusableSelector(el: Element): boolean {\n if (FOCUSABLE_LOCAL_NAMES.has(el.localName)) {\n return true;\n }\n const tabindex = el.getAttribute('tabindex');\n return (tabindex !== null && tabindex !== '-1') || el.hasAttribute('contenteditable');\n}\n\nfunction inSameRadioGroup(a: Element, b: Element): boolean {\n return (\n a !== b &&\n isGroupedRadio(a) &&\n isGroupedRadio(b) &&\n a.name === b.name &&\n a.form === b.form &&\n a.getRootNode() === b.getRootNode()\n );\n}\n\nfunction isTabStop(\n el: HTMLElement,\n root: HTMLElement,\n groups: Map<HTMLInputElement, boolean>,\n): boolean {\n return (\n el.tabIndex >= 0 &&\n (!isGroupedRadio(el) || el.checked || !radioGroupHasChecked(el, groups)) &&\n isFocusableCandidate(el, root)\n );\n}\n\nfunction isGroupedRadio(el: Element): el is HTMLInputElement {\n return (\n el.localName === 'input' &&\n (el as HTMLInputElement).type === 'radio' &&\n (el as HTMLInputElement).name !== ''\n );\n}\n\nfunction radioGroupHasChecked(\n radio: HTMLInputElement,\n groups: Map<HTMLInputElement, boolean>,\n): boolean {\n const known = groups.get(radio);\n if (known !== undefined) {\n return known;\n }\n const scope = radio.getRootNode() as ParentNode;\n const members = [...scope.querySelectorAll<HTMLInputElement>('input[type=\"radio\"]')].filter(\n (other) => other.name === radio.name && other.form === radio.form,\n );\n const hasChecked = members.some((member) => member.checked);\n for (const member of members) {\n groups.set(member, hasChecked);\n }\n groups.set(radio, hasChecked);\n return hasChecked;\n}\n\nfunction collectFocusableCandidates(root: ParentNode, found: HTMLElement[]): void {\n for (const el of root.querySelectorAll<HTMLElement>('*')) {\n if (mayMatchFocusableSelector(el) && el.matches(FOCUSABLE_SELECTOR)) {\n found.push(el);\n }\n const shadow = el.shadowRoot;\n if (shadow) {\n collectFocusableCandidates(shadow, found);\n }\n }\n}\n\nfunction hasInertAncestor(el: HTMLElement, root: HTMLElement): boolean {\n let cur: HTMLElement | null = el;\n while (cur && cur !== root) {\n if (cur.hasAttribute(INERT_ATTRIBUTE)) {\n return true;\n }\n cur = composedParentElement(cur);\n }\n return false;\n}\n\nfunction isUnrendered(el: HTMLElement, root: HTMLElement): boolean {\n const win = el.ownerDocument.defaultView;\n const canReadStyle = !!win && typeof win.getComputedStyle === 'function';\n let cur: HTMLElement | null = el;\n while (cur && cur !== root) {\n if (canReadStyle) {\n const style = win.getComputedStyle(cur);\n if (style.display === 'none') {\n return true;\n }\n if (cur === el) {\n if (style.visibility === 'hidden' || style.visibility === 'collapse') {\n return true;\n }\n } else if (style.contentVisibility === 'hidden') {\n return true;\n }\n }\n const parent = composedParentElement(cur);\n if (parent !== null && parent !== root && isClosedDetailsContent(parent, cur)) {\n return true;\n }\n cur = parent;\n }\n return false;\n}\n\nfunction isClosedDetailsContent(parent: HTMLElement, child: HTMLElement): boolean {\n return (\n parent.localName === 'details' &&\n !parent.hasAttribute(OPEN_ATTRIBUTE) &&\n child !== parent.querySelector(':scope > summary')\n );\n}\n","/**\n * Attribute that exempts a root-level child from the modal inert pass.\n * Carried by dialog / drawer backdrops (portaled alongside the modal), which\n * host-bind the literal, and written by `InertSiblingsStack` onto a registered\n * overlay host while that overlay belongs to the topmost modal, so the initial\n * sweep and the late-sibling observer skip it instead of inerting it like a\n * background sibling.\n *\n * Lives in `forty-cdk/core` rather than beside `InertSiblingsStack` in\n * `forty-cdk/core-overlay` because `LiveAnnouncer` stamps the exempt attribute\n * on its own regions, and the announcer is reached by primitives that compose\n * no overlay at all.\n */\nexport const MODAL_PEER_ATTRIBUTE = 'data-for-modal-peer';\n\n/**\n * Marks a root-level child as an independent overlay surface that must stay usable while a modal is\n * open.\n *\n * Stronger than {@link MODAL_PEER_ATTRIBUTE}: like a peer it is skipped by the inert pass, and in\n * addition every active modal's dismissible layer treats interactions inside it as inside, so a\n * pointer-down or focus within it never dismisses the modal. A peer such as a backdrop\n * stays part of the dismiss-outside surface; an exempt overlay does not.\n *\n * Carried by `ForToastViewport` and by every `LiveAnnouncer` region. The viewport host-binds the\n * literal; imperative callers use this constant.\n */\nexport const MODAL_EXEMPT_ATTRIBUTE = 'data-for-modal-exempt';\n","import { isPlatformBrowser } from '@angular/common';\nimport { DestroyRef, DOCUMENT, ElementRef, Injectable, inject, PLATFORM_ID } from '@angular/core';\n\nimport {\n composedClosest,\n composedContains,\n resolveActiveElement,\n} from '../composed-tree/composed-tree';\nimport {\n findTabbableEdges,\n isFocusableCandidate,\n leavesTabSequence,\n queryFocusableCandidates,\n} from './focusable-candidate';\nimport { fortyWarn } from '../errors/errors';\nimport { MODAL_EXEMPT_ATTRIBUTE, MODAL_PEER_ATTRIBUTE } from '../host-attributes/modal-attributes';\n\nconst INDEPENDENT_SURFACE_SELECTOR = `[${MODAL_EXEMPT_ATTRIBUTE}], [${MODAL_PEER_ATTRIBUTE}]`;\n\n/**\n * Returns the first focusable descendant of `container`, or `null` if none exists.\n *\n * Excludes `[hidden]`, disabled controls, `[inert]` subtrees and content that is not rendered,\n * the closed part of a `<details>` included. A candidate carrying `tabindex=\"-1\"` still\n * qualifies — this is the focusable set, not the Tab cycle. Descends into open shadow roots.\n */\nexport function findFirstFocusable(container: HTMLElement): HTMLElement | null {\n const candidates = queryFocusableCandidates(container);\n for (const el of candidates) {\n if (isFocusableCandidate(el, container)) {\n return el;\n }\n }\n return null;\n}\n\nexport interface FocusTrapActivateOptions {\n /**\n * Where to send focus on activation.\n * - `'first'` (default): the first focusable descendant. Falls back to the container.\n * - `'container'`: the trap container itself (gains `tabindex=\"-1\"` if needed).\n * - explicit element: focuses that element directly.\n */\n initialFocus?: 'first' | 'container' | HTMLElement;\n /**\n * Sets up Tab cycling and captures the return-focus target, but skips the imperative `.focus()`\n * call so focus stays wherever the consumer put it. Default `false`.\n */\n preventInitialFocus?: boolean;\n /**\n * Element to restore focus to on `deactivate({ returnFocus: true })`. Defaults to\n * `document.activeElement` at activation time.\n *\n * Pass it explicitly when the return target must be locked in before a side effect that moves\n * focus itself, such as applying `inert` to sibling elements.\n */\n returnFocus?: HTMLElement | null;\n}\n\nexport interface FocusTrapDeactivateOptions {\n /** Whether to restore focus to whatever held it at activation time. Default `true`. */\n returnFocus?: boolean;\n}\n\n/**\n * Application-scoped LIFO registry of active {@link FocusTrap} instances.\n *\n * Only the topmost trap handles Tab; shallower traps stay registered with inert keydown handlers,\n * so nested overlays cycle focus inside the innermost surface.\n */\n@Injectable({ providedIn: 'root' })\nexport class FocusTrapStack {\n readonly #stack: FocusTrap[] = [];\n\n /** Pushes a newly-activated trap onto the top of the stack. */\n push(trap: FocusTrap): void {\n this.#stack.push(trap);\n }\n\n /** Removes a deactivated trap from the stack (last occurrence). */\n remove(trap: FocusTrap): void {\n const idx = this.#stack.lastIndexOf(trap);\n if (idx >= 0) {\n this.#stack.splice(idx, 1);\n }\n }\n\n /** Returns `true` when `trap` is the topmost (most recently pushed) trap. */\n isTopmost(trap: FocusTrap): boolean {\n return this.#stack[this.#stack.length - 1] === trap;\n }\n}\n\n/**\n * Cycles Tab / Shift+Tab focus inside a container element.\n *\n * When several traps are active, only the topmost one handles Tab; the rest stay registered with\n * inert handlers until it deactivates.\n *\n * Both the tabbable set and the containment check are resolved against the composed tree, so\n * controls inside an open shadow root take part in the cycle. A closed shadow root stays opaque.\n *\n * Tab wraps whenever the browser's own move would leave the container: from the last tabbable, or\n * from any focused element after it, Tab goes to the first; from the first tabbable, or from the\n * container or any focused element before it, Shift+Tab goes to the last.\n *\n * A surface outside the container carrying `data-for-modal-exempt` or `data-for-modal-peer` (a\n * toast viewport, a popover opened from inside the modal) keeps its own Tab sequence: Tab moves\n * natively between its tabbables, and a move past either end of it is left to the surface's own\n * keydown handlers first. When one of them moves focus back into the container (a tab-out to the\n * trigger), the in-container rule applies from there and the browser advances natively; when\n * focus is still on the surface, it returns to the container — Tab to the first tabbable,\n * Shift+Tab to the last. Focus anywhere else outside the container is pulled back to the first\n * tabbable.\n *\n * Marking the rest of the page `inert` is out of scope — pointer isolation is the consumer's job.\n */\nexport class FocusTrap {\n readonly #container: HTMLElement;\n readonly #stack: FocusTrapStack;\n readonly #document: Document;\n readonly #isBrowser: boolean;\n #returnTo: HTMLElement | null = null;\n #active = false;\n #containerHadTabindex = false;\n #keyboardChannel: AbortController | null = null;\n #deferredTab: KeyboardEvent | null = null;\n\n readonly #onKeyDown = (event: KeyboardEvent): void => this.#handleKeyDown(event);\n readonly #onKeyDownSettled = (event: KeyboardEvent): void => this.#settleDeferredTab(event);\n\n constructor(container: HTMLElement, stack: FocusTrapStack, doc?: Document, isBrowser = true) {\n this.#container = container;\n this.#stack = stack;\n this.#document = doc ?? container.ownerDocument;\n this.#isBrowser = isBrowser;\n }\n\n get container(): HTMLElement {\n return this.#container;\n }\n\n /**\n * Whether the trap has been activated and not yet deactivated.\n *\n * Only `deactivate()` clears it — {@link releaseKeyboardChannel} leaves it set. It is therefore\n * not a reading of the keyboard channel, and it is still `true` during a `DestroyRef.onDestroy`\n * hook that runs before the owner's own `deactivate()`.\n */\n get isActive(): boolean {\n return this.#active;\n }\n\n activate(options: FocusTrapActivateOptions = {}): void {\n if (this.#active || !this.#isBrowser) {\n return;\n }\n this.#active = true;\n this.#containerHadTabindex = this.#container.hasAttribute('tabindex');\n this.#returnTo =\n options.returnFocus !== undefined\n ? options.returnFocus\n : (resolveActiveElement(this.#document) as HTMLElement | null);\n this.#keyboardChannel = new AbortController();\n this.#document.addEventListener('keydown', this.#onKeyDown, {\n capture: true,\n signal: this.#keyboardChannel.signal,\n });\n this.#document.addEventListener('keydown', this.#onKeyDownSettled, {\n signal: this.#keyboardChannel.signal,\n });\n this.#stack.push(this);\n\n if (options.preventInitialFocus) {\n // Tab cycling and return-focus are still set up; the imperative\n // focus move is the only thing skipped. Focus stays wherever the\n // consumer wants until they choose to enter the trap.\n return;\n }\n\n const initial = options.initialFocus ?? 'first';\n if (initial === 'first') {\n const first = findFirstFocusable(this.#container);\n if (first) {\n first.focus();\n } else {\n this.#focusContainer();\n }\n } else if (initial === 'container') {\n this.#focusContainer();\n } else {\n initial.focus();\n }\n }\n\n /**\n * Removes the keydown listener, unregisters from the stack and — unless `returnFocus: false` —\n * restores focus to the element captured on activation.\n *\n * Return focus is skipped when that element is no longer connected to the document, leaving the\n * browser's own default in place rather than dropping focus to `<body>`.\n */\n deactivate(options: FocusTrapDeactivateOptions = {}): void {\n if (!this.#active) {\n return;\n }\n this.releaseKeyboardChannel();\n this.#active = false;\n\n if (this.#containerHadTabindex === false && this.#container.getAttribute('tabindex') === '-1') {\n // We added it on activation; remove it so we don't leak.\n this.#container.removeAttribute('tabindex');\n }\n this.#containerHadTabindex = false;\n\n const returnFocus = options.returnFocus !== false;\n if (returnFocus && this.#returnTo?.isConnected) {\n this.#returnTo.focus();\n }\n this.#returnTo = null;\n }\n\n /**\n * Removes the `document` keydown listener and the {@link FocusTrapStack} entry, leaving focus,\n * {@link isActive} and the temporary container `tabindex` untouched. A no-op on an inactive trap.\n *\n * Idempotent, and safe to call before or after `deactivate()` — a later\n * `deactivate({ returnFocus: true })` still performs its focus move.\n *\n * Not a substitute for `deactivate()`: calling it on a trap still in use leaves one that reports\n * `isActive` yet cycles nothing, and whose `activate()` is a silent no-op.\n */\n releaseKeyboardChannel(): void {\n if (!this.#active) {\n return;\n }\n this.#keyboardChannel?.abort();\n this.#keyboardChannel = null;\n this.#deferredTab = null;\n this.#stack.remove(this);\n }\n\n #focusContainer(): void {\n if (!this.#containerHadTabindex && !this.#container.hasAttribute('tabindex')) {\n this.#container.setAttribute('tabindex', '-1');\n }\n this.#container.focus();\n }\n\n #handleKeyDown(event: KeyboardEvent): void {\n if (event.key !== 'Tab') {\n return;\n }\n // Only the topmost active trap handles Tab. Earlier (shadowed) traps\n // bail so a parent drawer's \"focus jumped outside\" guard does not\n // pull focus out of a nested child drawer's surface.\n if (!this.#stack.isTopmost(this)) {\n return;\n }\n const active = resolveActiveElement(this.#document);\n if (composedContains(this.#container, active)) {\n this.#cycleInside(event, active);\n return;\n }\n\n const surface = this.#independentSurfaceOf(active);\n if (surface === null) {\n this.#pullBack(event, false);\n } else if (leavesTabSequence(findTabbableEdges(surface), active, event.shiftKey)) {\n this.#deferredTab = event;\n }\n }\n\n #settleDeferredTab(event: KeyboardEvent): void {\n if (event !== this.#deferredTab) {\n return;\n }\n this.#deferredTab = null;\n const active = resolveActiveElement(this.#document);\n if (composedContains(this.#container, active)) {\n if (!event.defaultPrevented) {\n this.#cycleInside(event, active);\n }\n return;\n }\n if (event.defaultPrevented && this.#independentSurfaceOf(active) !== null) {\n return;\n }\n this.#pullBack(event, true);\n }\n\n #cycleInside(event: KeyboardEvent, active: Element | null): void {\n const backward = event.shiftKey;\n const edges = findTabbableEdges(this.#container);\n if (leavesTabSequence(edges, active, backward)) {\n event.preventDefault();\n (backward ? edges.last : edges.first)?.focus();\n }\n }\n\n #pullBack(event: KeyboardEvent, fromSurface: boolean): void {\n event.preventDefault();\n const { first, last } = findTabbableEdges(this.#container);\n const target = fromSurface && event.shiftKey ? last : first;\n if (target) {\n target.focus();\n } else {\n this.#focusContainer();\n }\n }\n\n #independentSurfaceOf(active: Element | null): HTMLElement | null {\n if (active === null) {\n return null;\n }\n const surface = composedClosest(active, INDEPENDENT_SURFACE_SELECTOR);\n return surface !== null && !composedContains(surface, this.#container) ? surface : null;\n }\n}\n\n/**\n * Reports an owner that activated a trap and was destroyed without calling `deactivate()`.\n *\n * Must be scheduled as a microtask rather than run inside the destroy hook: `onDestroy` callbacks\n * fire in registration order, so {@link FocusTrap.isActive} is only settled once the whole chain\n * has run.\n */\nfunction warnIfNeverDeactivated(trap: FocusTrap): void {\n if (!trap.isActive) {\n return;\n }\n fortyWarn({\n code: 'FORCDK-CORE-004',\n message:\n 'A focus trap was still active when its owner was destroyed, so focus was not returned.',\n cause:\n 'The owner never called `deactivate()`. The teardown safety net released the keyboard ' +\n 'channel (the `document` keydown listener and the stack entry), but only the owner can ' +\n 'decide where focus goes.',\n fix: \"Call `trap.deactivate({ returnFocus })` from the owner's own `DestroyRef.onDestroy`.\",\n });\n}\n\n/**\n * Creates a {@link FocusTrap} for the current directive's host element.\n *\n * Activation and teardown are the caller's responsibility: call `trap.activate()` when the surface\n * opens and `trap.deactivate({ returnFocus })` from a `DestroyRef.onDestroy` when it closes.\n *\n * On injector destroy the helper releases the keyboard channel unconditionally, so a trap whose\n * owner skipped `deactivate()` cannot keep intercepting Tab. It never moves focus — only the owner\n * can decide where focus goes — and warns in dev mode when it finds that repair necessary.\n *\n * SSR-safe: off-browser the trap registers no listener and `activate()` is a no-op.\n */\nexport function injectFocusTrap(): FocusTrap {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const trap = new FocusTrap(\n host.nativeElement,\n inject(FocusTrapStack),\n inject(DOCUMENT),\n isPlatformBrowser(inject(PLATFORM_ID)),\n );\n inject(DestroyRef).onDestroy(() => {\n const wasActive = trap.isActive;\n trap.releaseKeyboardChannel();\n if ((typeof ngDevMode === 'undefined' || ngDevMode) && wasActive) {\n queueMicrotask(() => warnIfNeverDeactivated(trap));\n }\n });\n return trap;\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n DestroyRef,\n ElementRef,\n PLATFORM_ID,\n afterNextRender,\n inject,\n signal,\n type Signal,\n} from '@angular/core';\n\nimport {\n FOCUSABILITY_ATTRIBUTES,\n isFocusableCandidate,\n queryFocusableCandidates,\n} from './focusable-candidate';\n\n/**\n * Reports whether the host element currently has at least one focusable\n * descendant, reactive to subtree mutations.\n *\n * Backs the WAI-ARIA Tabs rule that a `tabpanel` is itself a tab stop only when it has no focusable\n * content of its own.\n *\n * Candidates are filtered through the same predicate `FocusTrap` uses, so `[hidden]`, disabled,\n * `[inert]` and unrendered elements (CSS-hidden, or inside a closed `<details>`) do not count, and\n * content inside an open shadow root does.\n *\n * A `MutationObserver` on the host's subtree re-measures on childList and attribute changes. Two\n * boundaries follow from it: the observer cannot see into a shadow root, and its `attributeFilter`\n * excludes `class` and `style`, so a visibility flip driven purely by a stylesheet keeps the\n * previously measured answer.\n *\n * SSR-safe: off-browser no observer is created and the signal stays `false`.\n *\n * Must be called from an injection context.\n */\nexport function injectHasFocusableContent(): Signal<boolean> {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n const destroyRef = inject(DestroyRef);\n\n const has = signal(false);\n\n if (!isBrowser) {\n return has.asReadonly();\n }\n\n const measure = (): void => has.set(hasFocusableDescendant(host));\n\n const win = host.ownerDocument.defaultView;\n if (win && typeof win.MutationObserver === 'function') {\n const observer = new win.MutationObserver(() => measure());\n observer.observe(host, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: [...FOCUSABILITY_ATTRIBUTES],\n });\n destroyRef.onDestroy(() => observer.disconnect());\n }\n\n afterNextRender(measure);\n\n return has.asReadonly();\n}\n\nfunction hasFocusableDescendant(host: HTMLElement): boolean {\n const candidates = queryFocusableCandidates(host);\n for (const el of candidates) {\n if (isFocusableCandidate(el, host)) {\n return true;\n }\n }\n return false;\n}\n","import { Injectable } from '@angular/core';\n\nimport { composedParentElement } from '../composed-tree/composed-tree';\n\n@Injectable({ providedIn: 'root' })\nexport class ReturnFocusResolver {\n readonly #fallbacks = new WeakMap<Element, () => HTMLElement | null>();\n\n recordRemoval(removed: Element, fallback: () => HTMLElement | null): void {\n this.#fallbacks.set(removed, fallback);\n }\n\n resolve(...candidates: readonly (HTMLElement | null)[]): HTMLElement | null {\n const present = candidates.filter((candidate): candidate is HTMLElement => candidate !== null);\n const connected = present.find((candidate) => candidate.isConnected);\n if (connected !== undefined) {\n return connected;\n }\n for (const candidate of present) {\n const fallback = this.#fallbackFor(candidate);\n if (fallback?.isConnected) {\n return fallback;\n }\n }\n return null;\n }\n\n #fallbackFor(target: HTMLElement): HTMLElement | null {\n for (let node: Element | null = target; node !== null; node = composedParentElement(node)) {\n const fallback = this.#fallbacks.get(node);\n if (fallback !== undefined) {\n return fallback();\n }\n }\n return null;\n }\n}\n","import {\n booleanAttribute,\n computed,\n Directive,\n effect,\n ElementRef,\n inject,\n input,\n model,\n output,\n} from '@angular/core';\n\nimport { FOR_FIELDSET_CONTEXT } from '../field/fieldset-context';\nimport { type FieldValidationError, injectFieldWiring } from '../field/field-wiring';\n\n/**\n * Abstract base for primitives that implement `FormValueControl<T>` or\n * `FormCheckboxControl` from `@angular/forms/signals`. Owns the universal\n * `disabled` / `readonly` / `required` / `invalid` / `pending` / `dirty` /\n * `name` / `errors` inputs plus the `touched` model and `touch` output so each\n * form-control primitive doesn't redeclare them.\n *\n * Subclasses keep ownership of their value signal — `value: model<T>()` for\n * `FormValueControl<T>` or `checked: model<boolean>()` for\n * `FormCheckboxControl` — and any control-shape-specific members\n * (`min` / `max` / `pattern`, `multiple`, `orientation`, etc.).\n *\n * The base constructor reflects the four form-state booleans (`touched` /\n * `dirty` / `pending` / `invalid`) as boolean `data-*` attributes on each\n * subclass's host element automatically — subclasses don't need to opt in.\n * Imperative `toggleAttribute` writes (present with empty string when truthy,\n * absent otherwise) keep the subclass's declarative `host: { ... }` block free\n * of these attributes; no conflict because they aren't bound elsewhere.\n *\n * Implemented as an `@Directive()`-decorated abstract class because Angular\n * recognises signal inputs only when `input()` / `model()` calls appear\n * directly in a class-field initializer; a factory function returning the\n * bundle would not be detected by the compiler. Inheritance is the\n * supported mechanism for sharing initializer-API declarations across\n * directives.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\n@Directive()\nexport abstract class FormUiControlBase {\n /**\n * Consumer/Signal-Forms `disabled` input. Subclasses gate behavior and reflect\n * ARIA/`data-*` off {@link effectiveDisabled}, not this raw input, so a\n * surrounding disabled `[forFieldset]` also disables the control. Bind to this\n * via `[disabled]` or `[formField]`; read {@link effectiveDisabled} for state.\n */\n readonly disabled = input(false, { transform: booleanAttribute });\n\n /**\n * When true, interaction is ignored but the control stays focusable. Reflected\n * as `data-readonly`, plus `aria-readonly=\"true\"` where the control's role\n * supports it; a `role=\"group\"` or `role=\"button\"` host carries `data-readonly`\n * alone.\n */\n readonly readonly = input(false, { transform: booleanAttribute });\n\n /**\n * Marks the control required. A control hosted on a native `<input>` or\n * `<textarea>` reflects it as the native `required` attribute, a custom-role\n * control as `aria-required=\"true\"` where its role supports it, and a\n * `role=\"group\"` or `role=\"button\"` host as `data-required`.\n */\n readonly required = input(false, { transform: booleanAttribute });\n\n /** Reflected as `aria-invalid=\"true\"` and `data-invalid` when truthy. */\n readonly invalid = input(false, { transform: booleanAttribute });\n\n /** Reflected as `aria-busy=\"true\"` and `data-pending` when truthy. */\n readonly pending = input(false, { transform: booleanAttribute });\n\n /** Reflected as `data-dirty` when truthy. */\n readonly dirty = input(false, { transform: booleanAttribute });\n\n /** When non-empty, hidden inputs are mounted under that name for native form submission. */\n readonly name = input<string>('');\n\n /** Validation errors surfaced by Signal Forms. */\n readonly errors = input<readonly FieldValidationError[]>([]);\n\n /**\n * Set to true on the first touch-producing interaction (see {@link touch}).\n * Two-way bindable for standalone consumers; under `[formField]` the directive pushes the field's\n * touched state down through this input, so the form stays the source of\n * truth (e.g. a form reset clears it).\n */\n readonly touched = model<boolean>(false);\n\n /**\n * Emitted on every touch-producing interaction — including repeats once the\n * control is already touched. Those are: focus leaving the control (a move\n * between its own parts, such as a picker's field and trigger, is not a\n * leave), an activation or selection commit, and a dismissal by an outside\n * press or outside focus. Escape is not one: it leaves focus in the control.\n * The {@link touched} model itself only changes on the first, and Signal\n * Forms' `markAsTouched()` is idempotent, so re-emission is safe. No control\n * once-guards this. `[formField]` listens to this output to mark the field\n * touched — since Signal Forms v22 the `touched` input is write-only from the\n * form's perspective and never read back.\n */\n readonly touch = output<void>();\n\n /**\n * Moves focus into the control, mirroring the optional `FormUiControl.focus`\n * from `@angular/forms/signals`. Declared here without an implementation —\n * the base has no idea where a subclass's focus entry point is — so that a\n * surrounding `[forField]` can be handed the subclass's own `focus()` for\n * label-click activation whenever one exists. A subclass whose host is\n * itself focusable declares nothing and the field focuses that host.\n *\n * A subclass must declare this as a **method**, not an arrow-valued field:\n * the base reads it during `super()`, before subclass fields initialize.\n */\n focus?(options?: FocusOptions): void;\n\n /**\n * Returns the control to its pristine state, mirroring the optional\n * `FormUiControl.reset` that Signal Forms calls on a form reset. Declared\n * without an implementation: only a control that can hold a draft its value\n * cannot represent, such as a partly typed date, has anything to discard.\n */\n reset?(): void;\n\n /**\n * Whether a composite around this control currently stands in for it with a\n * surrounding `[forField]` — a field-anatomy picker adopting its segmented\n * field. While it returns `true` the field neither resolves nor wires this\n * control. Declared without an implementation so only a control that can be\n * adopted pays for the extra reactive read.\n *\n * A subclass must declare this as a **method**, for the same reason as\n * {@link focus}. It is read lazily, so it may reference the subclass's own\n * fields.\n */\n protected fieldAdopted?(): boolean;\n\n /**\n * Whether a composite this control is projected into, and defers to, is\n * disabled — a date picker around the time source it composes. Folded into\n * {@link effectiveDisabled}. Declared without an implementation so only a\n * control that can be projected that way pays for the extra reactive read.\n *\n * A subclass must declare this as a **method**, for the same reason as\n * {@link focus}. It is read lazily, so it may reference the subclass's own\n * fields.\n */\n protected inheritedDisabled?(): boolean;\n\n readonly #fieldset = inject(FOR_FIELDSET_CONTEXT, { optional: true });\n\n /**\n * The control's own {@link disabled} OR'd with a surrounding disabled\n * `[forFieldset]` and with a disabled composite it defers to. This is the\n * value that gates interaction and drives `aria-disabled` / `data-disabled` —\n * a native `<fieldset disabled>` does not reach custom-role controls\n * (`forSwitch`, `forCheckbox`, …), so the group's disabled state must compose\n * in here. Subclasses read this, never the raw {@link disabled} input.\n */\n readonly effectiveDisabled = computed(\n () =>\n this.disabled() ||\n (this.#fieldset?.disabled() ?? false) ||\n (this.inheritedDisabled?.() ?? false),\n );\n\n readonly #hostEl = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n\n /**\n * The focusable element a surrounding `[forField]` should target for\n * `aria-*` association and focus. Defaults to the directive host — correct\n * when the host IS the control (Listbox, native `<input>`). Override when the\n * host is a non-interactive wrapper and the real control is a child (the\n * Select trigger button / the Combobox `role=\"combobox\"` input), returning\n * that element — or `null` while it hasn't registered yet, in which case the\n * field defers wiring rather than targeting the wrapper.\n *\n * Read lazily inside the field-wiring effect, so a subclass override may\n * reference its own signals (initialized after this base `super()` runs).\n */\n protected fieldLabelledElement(): HTMLElement | null {\n return this.#hostEl;\n }\n\n /**\n * The id already host-bound on {@link fieldLabelledElement} when a subclass\n * nominates a child control (e.g. the Select trigger's `triggerId`). The\n * field adopts it as its `controlId` so the label's `for` and the primitive's\n * internal `aria-labelledby` point at the same element. `null` (the default,\n * and the host-is-the-control case) falls back to the field's owned id.\n */\n protected fieldLabelledElementId(): string | null {\n return null;\n }\n\n protected fieldActivationTarget(): HTMLElement | null {\n return null;\n }\n\n /**\n * Marks the control touched: flips the {@link touched} model (standalone\n * reflection) and emits {@link touch} (Signal Forms integration). Subclasses\n * call this from every touch-producing interaction instead of writing\n * `touched` directly, so both channels always fire together.\n * Never once-guard this in a subclass: the emission cadence is part of the\n * uniform form-control contract.\n */\n protected markTouched(): void {\n this.touched.set(true);\n this.touch.emit();\n }\n\n /**\n * The element the four form-state `data-*` booleans (`data-touched` /\n * `data-dirty` / `data-pending` / `data-invalid`) are reflected onto. Defaults\n * to the directive host — correct when the host carries the control's styling\n * surface. Override (returning `null` until it exists) when the reflected\n * element is a child the directive injects, e.g. `ForOtpInput`'s real\n * `<input>` rather than its `role=\"group\"` host. Read reactively inside the\n * reflection effect, so a returned signal re-targets once the element appears.\n */\n protected fieldStateReflectionTarget(): HTMLElement | null {\n return this.#hostEl;\n }\n\n /**\n * The control's effective invalidity — reflected as `data-invalid` and fed to\n * a surrounding `[forField]` (which gates its error region and folds the error\n * id into `aria-describedby`). Defaults to the raw {@link invalid} input.\n * Override to fold in invalidity the form itself can't express (e.g.\n * `ForDateRangeField` / `ForTimeRangeField` treating an out-of-order range as\n * invalid) so `aria-invalid`, `data-invalid`, and the field wiring stay\n * consistent. Read reactively inside the reflection and field-wiring effects,\n * so an override may reference its own signals (initialized after this base\n * `super()` runs).\n */\n protected effectiveInvalid(): boolean {\n return this.invalid();\n }\n\n constructor() {\n effect(() => {\n const target = this.fieldStateReflectionTarget();\n if (!target) {\n return;\n }\n target.toggleAttribute('data-touched', this.touched());\n target.toggleAttribute('data-dirty', this.dirty());\n target.toggleAttribute('data-pending', this.pending());\n target.toggleAttribute('data-invalid', this.effectiveInvalid());\n });\n const fieldAdopted = this.fieldAdopted?.bind(this);\n injectFieldWiring({\n adopted: fieldAdopted ? computed(fieldAdopted) : undefined,\n invalid: computed(() => this.effectiveInvalid()),\n required: this.required,\n disabled: this.effectiveDisabled,\n touched: this.touched,\n errors: this.errors,\n labelledElement: computed(() => this.fieldLabelledElement()),\n labelledElementId: computed(() => this.fieldLabelledElementId() ?? undefined),\n activationTarget: computed(() => this.fieldActivationTarget()),\n focus: this.focus?.bind(this),\n });\n }\n}\n","import {\n Directive,\n ElementRef,\n booleanAttribute,\n computed,\n inject,\n input,\n signal,\n} from '@angular/core';\n\n/**\n * The \"visually hidden\" clip rectangle: an inline style declaration that\n * removes an element from the visual layout while keeping it in the\n * accessibility tree (unlike `display:none` / `visibility:hidden`, which both\n * also drop it from the a11y tree). Shared by {@link ForVisuallyHidden} and the\n * `LiveAnnouncer` so the clip CSS is defined in exactly one place.\n *\n * Internal tier, and not exported from the core\n * barrel: the published surface for this capability is {@link ForVisuallyHidden}\n * (blessed, shipped from `forty-cdk/visually-hidden`), which applies the clip\n * for the consumer. A raw style string covers no use case the directive does\n * not.\n */\nexport const VISUALLY_HIDDEN_STYLE =\n 'position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border:0;';\n\n/**\n * Visually hides its host while leaving it in the accessibility tree, applying\n * the clip rectangle inline (no global stylesheet). Use it for hidden labels,\n * descriptions, and live-region content that screen readers must reach but\n * sighted users should not see.\n *\n * With `focusable`, the host is revealed whenever it — or any descendant —\n * holds focus, then clips itself again on blur. This is the skip-link pattern:\n * a control that is invisible until a keyboard user tabs to it. Focus is\n * tracked through `focusin` / `focusout` rather than a `:focus-within` CSS\n * rule, because the clip is applied inline and an inline style cannot express a\n * pseudo-class.\n *\n * Part of the blessed core tier: consumers import it from the\n * `forty-cdk/visually-hidden` entry point, which carries the library's semver\n * guarantee.\n */\n@Directive({\n selector: '[forVisuallyHidden]',\n exportAs: 'forVisuallyHidden',\n host: {\n '[style]': 'styles()',\n '(focusin)': 'onFocusIn()',\n '(focusout)': 'onFocusOut($event)',\n },\n})\nexport class ForVisuallyHidden {\n readonly #host = inject<ElementRef<HTMLElement>>(ElementRef);\n\n /**\n * When `true`, the host un-clips while it (or a descendant) holds focus and\n * re-clips on blur — the skip-link \"visible on focus\" behavior. Defaults to\n * `false`, which keeps the host hidden at all times.\n */\n readonly focusable = input(false, { transform: booleanAttribute });\n\n readonly #focused = signal(false);\n\n private readonly styles = computed(() =>\n this.focusable() && this.#focused() ? null : VISUALLY_HIDDEN_STYLE,\n );\n\n private onFocusIn(): void {\n this.#focused.set(true);\n }\n\n private onFocusOut(event: FocusEvent): void {\n const next = event.relatedTarget as Node | null;\n if (next && this.#host.nativeElement.contains(next)) {\n return;\n }\n this.#focused.set(false);\n }\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n DOCUMENT,\n DestroyRef,\n effect,\n ElementRef,\n inject,\n PLATFORM_ID,\n type Signal,\n} from '@angular/core';\n\nimport { VISUALLY_HIDDEN_STYLE } from '../visually-hidden/visually-hidden';\n\n/**\n * The visually hidden clip with `position:fixed`, so the validation input never\n * extends the scrollable overflow of the document or of an unpositioned\n * scroller it sits in.\n */\nconst VALIDATION_INPUT_STYLE = `${VISUALLY_HIDDEN_STYLE}position:fixed;`;\n\nexport interface HiddenInputConfig<T = string> {\n /**\n * Form name. While empty, no hidden inputs are mounted — set a non-empty\n * `name` (typically via `[name]` on the host primitive) to opt in.\n */\n name: Signal<string>;\n\n /**\n * Reactive list of values to mirror. Each entry becomes a separate\n * `<input type=\"hidden\" name=\"…\" value=\"…\">`. Use:\n * - `['on']` (checked) / `[]` (unchecked) for boolean controls.\n * - `[value]` (selected) / `[]` (none) for single-value controls.\n * - the array as-is for multi-value controls.\n */\n values: Signal<readonly T[]>;\n\n /**\n * How to serialize each entry to a string for the hidden input's `value`\n * attribute. Defaults to `String(item)`, which is identity for strings.\n * Object-valued primitives (e.g. generic `[forCombobox]`) pass a custom\n * function — typically a consumer-provided `itemToFormValue` — so the\n * wire format is explicit (per-item id, per-item JSON, …).\n */\n serialize?: (item: T) => string;\n\n /**\n * Optional disabled mirror. Disabled hidden inputs are skipped by native\n * form serialization, matching the behavior of disabled visible controls.\n */\n disabled?: Signal<boolean>;\n\n /**\n * Optional required state. While it is `true` and `values` is empty, the\n * surrounding `<form>` fails native constraint validation: submission is\n * blocked and `form:invalid` matches, as for a native `<select required>`.\n * Independent of `name`. A disabled control never blocks.\n */\n required?: Signal<boolean>;\n\n /**\n * Moves focus into the control when the browser reports it invalid.\n * Defaults to focusing the host element.\n */\n focus?: () => void;\n}\n\n/**\n * Mirrors a headless form control's value into native\n * `<input type=\"hidden\">` siblings so the surrounding `<form>` picks it up\n * during native submission. Multiple values produce multiple inputs (used\n * by multi-select primitives like the listbox).\n *\n * Inputs are inserted right after the directive's host element so they\n * live inside whatever `<form>` the host lives in. Lifecycle is wired to\n * `DestroyRef`: the inputs are removed when the directive is destroyed.\n *\n * Browser-only: on the server this is a no-op — no `<input>` is created or\n * serialized. The hidden inputs are **client-only** siblings: they are net-new\n * nodes the server never rendered, so they are not part of the hydrated tree\n * and a full (non-incremental) hydration sees the same server markup (the host\n * primitive alone) with no mismatch and no duplicated / double-submitted field.\n *\n * Caveat: the initial mount runs inside the directive's first `effect()` pass,\n * which can fire before hydration finishes settling under incremental\n * hydration. That is harmless today because the inputs are always net-new\n * (never claimed from the server DOM), but it means the \"after hydration\"\n * guarantee is \"not part of the hydrated tree\", not \"strictly sequenced after\n * the hydration pass\". If incremental hydration ever needs the stricter\n * ordering, move the initial mount into `afterNextRender`.\n *\n * A hidden input is barred from constraint validation, so a `required` control\n * also gets one validation input: a visually hidden, fixed-positioned, unnamed\n * `<input required tabindex=\"-1\" aria-hidden=\"true\">` mounted after the host,\n * filled while `values` is non-empty. Being fixed, it never makes the document\n * or a scroll container taller, whatever the host's ancestors are. It submits nothing, and focusing it, which\n * the browser does when it reports the form, moves focus into the control.\n *\n * Returns a function that writes the current values into the hidden inputs\n * immediately. A control whose value changes in the same event that submits\n * the form calls it, so the submission carries the new value rather than the\n * one the next render would have written. It is a no-op on the server.\n */\nexport function injectHiddenInput<T = string>(config: HiddenInputConfig<T>): () => void {\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n return () => undefined;\n }\n\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const doc = inject(DOCUMENT);\n const inputs: HTMLInputElement[] = [];\n let validation: HTMLInputElement | null = null;\n let destroyed = false;\n\n const focusControl = (): void => {\n if (config.focus) {\n config.focus();\n } else {\n host.nativeElement.focus();\n }\n };\n\n const syncValidation = (disabled: boolean): void => {\n if (!(config.required?.() ?? false)) {\n validation?.remove();\n validation = null;\n return;\n }\n if (validation === null) {\n validation = doc.createElement('input');\n validation.required = true;\n validation.tabIndex = -1;\n validation.autocomplete = 'off';\n validation.setAttribute('aria-hidden', 'true');\n validation.setAttribute('style', VALIDATION_INPUT_STYLE);\n validation.addEventListener('focus', focusControl);\n host.nativeElement.insertAdjacentElement('afterend', validation);\n }\n const filled = config.values().length > 0 ? 'on' : '';\n if (validation.defaultValue !== filled) {\n validation.defaultValue = filled;\n }\n if (validation.value !== filled) {\n validation.value = filled;\n }\n validation.toggleAttribute('disabled', disabled);\n };\n\n const sync = (): void => {\n if (destroyed) {\n return;\n }\n const name = config.name();\n const values = name ? config.values() : ([] as readonly T[]);\n const disabled = config.disabled?.() ?? false;\n const serialize = config.serialize;\n syncValidation(disabled);\n\n while (inputs.length > values.length) {\n inputs.pop()?.remove();\n }\n while (inputs.length < values.length) {\n const input = doc.createElement('input');\n input.type = 'hidden';\n const anchor = inputs.length === 0 ? host.nativeElement : inputs[inputs.length - 1]!;\n anchor.insertAdjacentElement('afterend', input);\n inputs.push(input);\n }\n\n for (let i = 0; i < values.length; i++) {\n const input = inputs[i]!;\n if (input.name !== name) {\n input.name = name;\n }\n const item = values[i] as T;\n let next: string;\n if (serialize) {\n next = serialize(item);\n } else if (item == null) {\n next = '';\n } else {\n next = String(item);\n }\n if (input.value !== next) {\n input.value = next;\n }\n input.toggleAttribute('disabled', disabled);\n }\n };\n\n effect(sync);\n\n inject(DestroyRef).onDestroy(() => {\n destroyed = true;\n for (const input of inputs) {\n input.remove();\n }\n inputs.length = 0;\n validation?.remove();\n validation = null;\n });\n\n return sync;\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n afterNextRender,\n DestroyRef,\n effect,\n ElementRef,\n inject,\n Injector,\n PLATFORM_ID,\n untracked,\n type WritableSignal,\n} from '@angular/core';\n\ntype ValueElement = HTMLInputElement | HTMLTextAreaElement;\n\nfunction listenForFormReset(\n element: Element,\n form: () => HTMLFormElement | null,\n onReset: () => void,\n): () => void {\n const root = element.getRootNode();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const listener = (event: Event): void => {\n const owner = form();\n if (owner === null || event.target !== owner) {\n return;\n }\n clearTimeout(timer);\n timer = setTimeout(() => {\n timer = undefined;\n if (!event.defaultPrevented) {\n onReset();\n }\n }, 0);\n };\n root.addEventListener('reset', listener);\n return () => {\n root.removeEventListener('reset', listener);\n clearTimeout(timer);\n };\n}\n\nexport function injectNativeFormReset(\n el: () => ValueElement | null,\n onReset?: (text: string) => void,\n): void {\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n return;\n }\n const injector = inject(Injector);\n effect((onCleanup) => {\n const element = el();\n if (!element) {\n return;\n }\n let baseline: string | null = null;\n const ref = untracked(() =>\n afterNextRender(\n () => {\n baseline = element.value;\n },\n { injector },\n ),\n );\n const stop = listenForFormReset(\n element,\n () => element.form,\n () => {\n const text = baseline ?? element.value;\n if (element.value !== text) {\n element.value = text;\n }\n onReset?.(text);\n },\n );\n onCleanup(() => {\n ref.destroy();\n stop();\n });\n });\n}\n\nexport function injectNativeFormResetToInitial<T>(\n model: WritableSignal<T>,\n onReset?: () => void,\n): void {\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n return;\n }\n const host = inject<ElementRef<Element>>(ElementRef).nativeElement;\n let stop: (() => void) | undefined;\n afterNextRender(() => {\n const initial = model();\n stop = listenForFormReset(\n host,\n () => host.closest('form'),\n () => {\n model.set(initial);\n onReset?.();\n },\n );\n });\n inject(DestroyRef).onDestroy(() => stop?.());\n}\n","import { effect, ElementRef, inject, type Signal } from '@angular/core';\n\n/**\n * Non-destructively reflects a `disabled` signal onto the host element's native\n * `disabled` attribute.\n *\n * The naive host binding `'[attr.disabled]': 'disabled() ? \"\" : null'` is\n * destructive: its `null` branch removes the attribute on the first change\n * detection whenever the expression is falsy, clobbering a `disabled` attribute\n * the consumer set themselves (a static `disabled` in the template, or an\n * imperative `setAttribute('disabled', '')`) even though the primitive never\n * owned it. For a host whose disabled expression has no same-element `disabled`\n * input to seed, that markup silently disappears.\n *\n * This helper tracks ownership instead: it sets the attribute only when absent, and on the falsy\n * edge removes it only when it was the one that set it. A consumer-set `disabled` therefore\n * survives an enabled state, while a primitive-set one is cleaned up on re-enable.\n *\n * Must be called from an injection context.\n *\n * **Not the right tool for every clobber-capable host.** Two kinds of control reflect\n * `aria-disabled` + `data-disabled` with an in-handler activation guard instead: one carrying a\n * custom ARIA role, because the native attribute would drop it from the focus order where the APG\n * requires a disabled control to stay focusable; and one whose disabled state the primitive\n * auto-computes from its own position and can flip while the button holds focus, because the\n * attribute would eject focus to `<body>` at the moment the user reaches the bound. Native\n * `disabled` is correct only on genuine form elements and on single-purpose `<button>` triggers\n * whose disabled state the consumer drives through an input.\n *\n * **The two channels are mutually exclusive**: a host calling this helper must not also host-bind\n * `[attr.aria-disabled]` for the same state, since the native attribute already exposes it through\n * HTML-AAM and a second channel leaves consumers two selectors for one condition. `data-disabled`\n * stays as the styling hook. The exclusion is per state rather than per attribute — a host whose\n * `aria-disabled` encodes a *different* condition may keep it, provided it can never be `\"true\"`\n * while this helper owns the native attribute. `forty-cdk/no-doubled-disabled-reflection` enforces\n * the declarative form.\n *\n * @param disabled Signal whose truthiness drives the native `disabled`\n * attribute on the host element.\n */\nexport function reflectDisabled(disabled: Signal<boolean>): void {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n let owned = false;\n effect(() => {\n if (disabled()) {\n if (!host.hasAttribute('disabled')) {\n host.setAttribute('disabled', '');\n owned = true;\n }\n } else if (owned) {\n host.removeAttribute('disabled');\n owned = false;\n }\n });\n}\n","import { effect, ElementRef, inject, type Signal } from '@angular/core';\n\nexport function reflectRequired(\n required: Signal<boolean>,\n target?: () => HTMLElement | null,\n): void {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const resolve = target ?? (() => host);\n let owner: HTMLElement | null = null;\n effect(() => {\n const el = resolve();\n if (owner !== null && owner !== el) {\n owner.removeAttribute('required');\n owner = null;\n }\n if (!el) {\n return;\n }\n if (required()) {\n if (!el.hasAttribute('required')) {\n el.setAttribute('required', '');\n owner = el;\n }\n } else if (owner === el) {\n el.removeAttribute('required');\n owner = null;\n }\n });\n}\n","import { DOCUMENT, effect, inject } from '@angular/core';\n\nimport { resolveActiveElement } from '../composed-tree/composed-tree';\n\ntype ValueElement = HTMLInputElement | HTMLTextAreaElement;\n\n/**\n * Mirrors a value string onto a native `<input>` / `<textarea>`'s `.value`\n * whenever the two differ, focused or not, except while an IME composition is\n * in progress. It is for controls whose displayed text is the text being typed\n * (`ForInput`, `ForTextarea`, `ForOtpInput`'s clamped code): typing already\n * lands in the model, so the only writes this ever makes come from elsewhere —\n * a consumer clearing the field on submit, a `[formField]` reset, a reformat in\n * `(valueChange)` — and each one must reach the element before the next\n * keystroke reads the old text back.\n *\n * The `el` accessor returns `null` until the element exists (`ForOtpInput`\n * injects its real `<input>` after hydration); a `null` target is skipped and\n * the effect re-runs once the element appears, since it is read reactively.\n *\n * Must be called from an injection context. Internal core tier — exported from\n * `forty-cdk/core` for the library's own entry points, with no semver guarantee.\n *\n * @param el Accessor for the target element, or `null` until it exists.\n * @param value Accessor for the desired displayed text.\n * @param composing Whether an IME composition is in progress on the element.\n */\nexport function mirrorValue(\n el: () => ValueElement | null,\n value: () => string,\n composing: () => boolean,\n): void {\n effect(() => {\n const element = el();\n if (!element) {\n return;\n }\n const next = value();\n if (element.value !== next && !composing()) {\n element.value = next;\n }\n });\n}\n\nexport function mirrorExternalValue<T>(\n el: () => ValueElement,\n value: () => T,\n text: () => string,\n): (own: T) => void {\n const document = inject(DOCUMENT);\n let claimed: { readonly value: T } | null = null;\n effect(() => {\n const element = el();\n const current = value();\n const next = text();\n if (\n claimed !== null &&\n Object.is(claimed.value, current) &&\n resolveActiveElement(document) === element\n ) {\n return;\n }\n claimed = null;\n if (element.value !== next) {\n element.value = next;\n }\n });\n return (own) => {\n claimed = { value: own };\n };\n}\n","import { Directive, ElementRef, inject, model } from '@angular/core';\n\nimport { reflectDisabled } from '../host-attributes/disabled-reflection';\nimport { reflectRequired } from '../host-attributes/required-reflection';\nimport { FormUiControlBase } from './form-ui-control-base';\nimport { injectNativeFormReset } from './native-form-reset';\nimport { mirrorValue } from './value-mirror';\n\n/**\n * Shared base for the text-valued form controls `ForInput` and `ForTextarea`.\n * Owns the `value` model and the bridge between the native element's editing\n * (the `input` event) and that signal, layered on the universal form-control\n * inputs inherited from `FormUiControlBase`.\n *\n * The native `<input>` / `<textarea>` is itself the submittable element: each\n * concrete directive reflects `[attr.name]` on its host, so the browser\n * serializes the field natively. No hidden input is injected — one would\n * double-submit alongside the real control. This mirrors the OTP-input design\n * and diverges from `ForNumberInput`, whose displayed (formatted)\n * text differs from its submitted value.\n *\n * Implemented as an `@Directive()`-decorated abstract class so Angular detects\n * the inherited `value` model — the same mechanism `FormUiControlBase` relies\n * on. Internal core tier — no semver guarantee.\n */\n@Directive()\nexport abstract class TextValueControlBase extends FormUiControlBase {\n /**\n * Two-way bindable text value. Required by `FormValueControl<string>`.\n * Defaults to `''` — a text field is naturally empty, not absent, which\n * keeps the type non-nullable. Reflected as `data-empty` while `''`.\n */\n readonly value = model<string>('');\n\n readonly #host = inject<ElementRef<HTMLInputElement | HTMLTextAreaElement>>(ElementRef);\n\n #composing = false;\n\n constructor() {\n super();\n\n // Reflect the native `disabled` attribute non-destructively so a\n // consumer-set `disabled` on the same element survives an enabled state.\n reflectDisabled(this.effectiveDisabled);\n reflectRequired(this.required);\n\n mirrorValue(\n () => this.#host.nativeElement,\n this.value,\n () => this.#composing,\n );\n\n injectNativeFormReset(\n () => this.#host.nativeElement,\n (text) => this.value.set(text),\n );\n }\n\n /** Bridges the native `input` event into the `value` model. */\n protected onInput(event: Event): void {\n if (this.effectiveDisabled() || this.readonly()) {\n return;\n }\n // Suppress the intermediate text an IME emits between `compositionstart`\n // and `compositionend`; the final composed string is flushed once on\n // `compositionend`. Mirrors the OTP / Combobox guard so all three text\n // controls behave identically.\n if (this.#composing) {\n return;\n }\n this.value.set((event.target as HTMLInputElement | HTMLTextAreaElement).value);\n }\n\n /** Starts an IME composition; suppresses intermediate `input` propagation. */\n private onCompositionStart(): void {\n this.#composing = true;\n }\n\n /** Ends an IME composition and flushes the final composed value once. */\n private onCompositionEnd(): void {\n this.#composing = false;\n if (this.effectiveDisabled() || this.readonly()) {\n return;\n }\n this.value.set(this.#host.nativeElement.value);\n }\n\n /**\n * Marks the control touched and re-syncs the native element to `value()`,\n * discarding any text written to the element without an `input` event.\n */\n private onBlur(): void {\n this.markTouched();\n const el = this.#host.nativeElement;\n if (el.value !== this.value()) {\n el.value = this.value();\n }\n }\n}\n","/**\n * A user-driven dismissal of a form control's open surface, named by the\n * channel that requested it.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\nexport type TouchDismissal = 'escape' | 'pointerDownOutside' | 'focusOutside';\n\n/**\n * Whether a `focusout` leaves the control. Returns `false` when the element\n * receiving focus sits inside any of `boundaries`, the elements that together\n * make up the control (its host, an open surface, a composite root around a\n * trigger and a field), and `true` otherwise, including when focus leaves the\n * document.\n *\n * Every form control that marks itself touched from a `focusout` decides it\n * here, so a focus move between the parts of one control never touches it.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\nexport function leavesControl(\n event: FocusEvent,\n boundaries: readonly (Node | null | undefined)[],\n): boolean {\n const next = event.relatedTarget as Node | null;\n if (!next) {\n return true;\n }\n return !boundaries.some((boundary) => boundary?.contains(next) ?? false);\n}\n\n/**\n * Whether a dismissal marks the control touched. An outside interaction is the\n * control's blur and touches it; Escape leaves focus in the control and blurs\n * nothing, so it does not.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\nexport function dismissMarksTouched(dismissal: TouchDismissal): boolean {\n return dismissal !== 'escape';\n}\n","/**\n * Collapse a config's `class` / `classList` into a single space-separated\n * string suitable for an Angular `[class]` binding or an `el.className`\n * assignment. De-duplicates tokens and drops empty entries so the rendered\n * `class` attribute stays clean. Returns `null` when neither field carries a\n * class.\n *\n * Shared by every imperative overlay manager (`ForToastManager`,\n * `ForDialogManager`, `ForDrawerManager`, and any future one) so the\n * `class` / `classList` config resolves identically across primitives:\n * applied to the overlay root, merged with — never clobbering — the\n * directive's own host attributes (`data-state`, `data-side`, …).\n *\n * Internal composition surface shared across forty-cdk's entry points — no\n * semver guarantees.\n */\nexport function resolveConfigClass(config: {\n class?: string;\n classList?: string | readonly string[];\n}): string | null {\n const tokens: string[] = [];\n const push = (value: string | readonly string[] | undefined): void => {\n if (typeof value === 'string') {\n tokens.push(...value.split(/\\s+/));\n } else if (Array.isArray(value)) {\n for (const entry of value) {\n tokens.push(...entry.split(/\\s+/));\n }\n }\n };\n push(config.class);\n push(config.classList);\n const unique = [...new Set(tokens.filter(Boolean))];\n return unique.length > 0 ? unique.join(' ') : null;\n}\n","import { computed, DestroyRef, effect, ElementRef, inject, type Signal } from '@angular/core';\n\nimport { composeIds, contributeDescribedBy } from './described-by-owner';\nimport { claimReplacedAttribute } from './replaced-attribute-owner';\n\n/**\n * Writes the `aria-labelledby` a piece exposes onto its host and returns it: the host element's\n * pre-existing **static** `aria-labelledby` when present, else the library's own generated\n * fallback (a trigger / heading / label id). The host must not also bind the attribute.\n *\n * A name has one owner, so a value the consumer wrote in the template always wins over the\n * fallback. A surface with no consumer value keeps its fallback verbatim.\n *\n * Only **static** values are adopted: a `[attr.aria-labelledby]=\"expr\"` binding evaluates after\n * directive construction, so it is invisible here and still fights the library's write. This\n * mirrors the static-only boundary of `resolveHostId` / `adoptHostId`.\n *\n * Must be invoked in an injection context.\n *\n * @param fallback The library-generated value, evaluated only when the host\n * carries no static `aria-labelledby`.\n */\nexport function hostLabelledBy(fallback: () => string | null): Signal<string | null> {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const claim = claimReplacedAttribute(host, 'aria-labelledby', fallback);\n effect(() => claim.write());\n inject(DestroyRef).onDestroy(() => claim.release());\n return computed(() => claim.consumer ?? fallback());\n}\n\n/**\n * Resolves the `aria-label` a piece should expose: the host element's\n * pre-existing **static** `aria-label` when present, else the library's own\n * value (an `ariaLabel` input, a scope default, or a computed name).\n *\n * Reuses {@link hostLabelledBy}'s replace semantics. Adoption matters more here: most of these host\n * bindings resolve to `null` when the library has no name of its own, and a `null` binding calls\n * `removeAttribute`, so without it a consumer's `aria-label` is deleted and the widget is left with\n * no accessible name at all.\n *\n * A piece emitting both channels must gate its {@link hostLabelledBy} fallback on this signal\n * rather than on the raw input, since `aria-labelledby` outranks `aria-label` in ARIA and a\n * generated fallback would otherwise beat the consumer's adopted name.\n *\n * Only **static** values are adopted; see {@link hostLabelledBy} for the boundary.\n *\n * Must be invoked in an injection context.\n *\n * @param fallback The library's own accessible name, evaluated only when the\n * host carries no static `aria-label`.\n */\nexport function hostAriaLabel(fallback: () => string | null): Signal<string | null> {\n const consumer = staticHostAttribute('aria-label');\n return computed(() => consumer ?? fallback());\n}\n\n/**\n * Writes the library's own description ids into the host's `aria-describedby`,\n * **composed** after the host's pre-existing **static** value, consumer ids\n * first, and returns that composition. The host must not also bind the\n * attribute.\n *\n * Descriptions are additive — assistive tech reads every referenced element — so unlike\n * {@link hostLabelledBy} this composes instead of replacing, and a consumer's\n * `aria-describedby=\"hint\"` keeps announcing alongside a registered description piece.\n * Ids another library piece contributes to the same element (the surrounding\n * `[forField]` of a control that is also a tooltip trigger) are kept beside these.\n *\n * Only **static** values are adopted; see {@link hostLabelledBy} for the boundary.\n *\n * Must be invoked in an injection context.\n *\n * @param fallback The library-owned description ids, composed after the\n * consumer's own.\n */\nexport function hostDescribedBy(fallback: () => string | null): Signal<string | null> {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const contribution = contributeDescribedBy(host, fallback);\n effect(() => contribution.write());\n inject(DestroyRef).onDestroy(() => contribution.release());\n return computed(() => composeIds(contribution.consumer, fallback()));\n}\n\nfunction staticHostAttribute(name: string): string | null {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n return host.getAttribute(name) || null;\n}\n","import { computed, ElementRef, inject, type Signal } from '@angular/core';\n\nexport function hostStaticAttribute(\n name: string,\n fallback: () => string | null,\n): Signal<string | null> {\n const consumer = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement.getAttribute(name);\n return computed(() => fallback() ?? (consumer || null));\n}\n","import { ElementRef, inject, signal, type Signal } from '@angular/core';\n\n/**\n * Resolves the `type` attribute a piece must emit to force `type=\"button\"`:\n * `'button'` on a native `<button>` host, `null` on any other element.\n *\n * Pieces that want submit protection host-bind it as\n * `'[attr.type]': 'buttonType()'`. A host binding always beats a consumer's\n * static template attribute, so `<button forCheckbox type=\"submit\">` still emits\n * `type=\"button\"`.\n *\n * The consumer's own `type` is therefore **not** adopted — the inverse of the\n * `hostId` / `hostAriaLabel` / `hostLabelledBy` seams. A piece that forces\n * `type=\"button\"` treats a consumer `type=\"submit\"` as an authoring error rather\n * than an override, so activating the control never submits a form.\n * `[forButton]` is the one piece that preserves the consumer's `type` (a\n * `[forButton]` on a real submit button is valid usage): it binds no `type` at\n * all and only writes `type=\"button\"` at construction on a native button that\n * has none, so a consumer binding always wins.\n *\n * The host's tag name cannot change after construction, so the returned signal is\n * constant. Must be invoked in an injection context.\n */\nexport function hostButtonType(): Signal<string | null> {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n return signal(host.tagName === 'BUTTON' ? 'button' : null).asReadonly();\n}\n","import { Injectable } from '@angular/core';\n\n/**\n * Answers whether an `Escape` pressed inside a node belongs to an overlay layered above it.\n *\n * A widget that consumes `Escape` itself (a grid cell leaving interaction mode) asks first, so a\n * dismissible layer stacked over it (a tooltip on the cell's widget) is dismissed instead. The\n * dismissible-layer stack registers the query when it is created; with no stack there is no layer,\n * and the answer is `false`. Living in `forty-cdk/core` lets an entry point ask without importing\n * the overlay machinery.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own entry points, with\n * no semver guarantee.\n */\n@Injectable({ providedIn: 'root' })\nexport class EscapeArbiter {\n #query: ((node: Node) => boolean) | null = null;\n\n /**\n * Installs the query {@link hasEscapeLayerAbove} delegates to, replacing any earlier one.\n * Returns a function that removes it again.\n */\n register(query: (node: Node) => boolean): () => void {\n this.#query = query;\n return () => {\n if (this.#query === query) {\n this.#query = null;\n }\n };\n }\n\n /**\n * Whether an active layer sits above every layer containing `node`, so the stack would hand it\n * an `Escape` pressed inside `node`.\n */\n hasEscapeLayerAbove(node: Node): boolean {\n return this.#query?.(node) ?? false;\n }\n}\n","import { Injectable, inject } from '@angular/core';\n\nimport { composedContains } from '../composed-tree/composed-tree';\nimport { IdGenerator } from '../id-generator/id-generator';\n\ninterface AppliedOwnership {\n readonly owner: HTMLElement;\n readonly added: readonly string[];\n}\n\n/**\n * Keeps the regions that must stay readable over a modal inside the accessibility subtree of the\n * topmost `aria-modal` surface.\n *\n * A region lives outside every modal and still has to reach assistive technology while one is\n * open: each `LiveAnnouncer` region, and a toast viewport exempt from the modal. A screen reader\n * that hides everything outside an `aria-modal=\"true\"` element would drop whatever is written into\n * one, so the topmost claiming surface lists every registered region in its `aria-owns`.\n *\n * Only the topmost claim owns the regions, because an element can have one owner: a stacked modal\n * takes them over and hands them back when it releases, whatever the release order. The ids the\n * registry adds are merged with the surface's own `aria-owns`, and they are the only ones it\n * removes. A region with no `id` is given one the first time it is owned, and a region inside the\n * owning surface is left out.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own entry points, with\n * no semver guarantee.\n */\n@Injectable({ providedIn: 'root' })\nexport class ModalOwnedRegions {\n readonly #ids = inject(IdGenerator);\n readonly #regions: HTMLElement[] = [];\n readonly #claims: HTMLElement[] = [];\n #applied: AppliedOwnership | null = null;\n\n /** Adds `region` to what the topmost claiming surface owns. Returns the matching removal. */\n register(region: HTMLElement): () => void {\n return this.#track(this.#regions, region);\n }\n\n /** Makes `surface` the topmost owner of every registered region. Returns the matching release. */\n claim(surface: HTMLElement): () => void {\n return this.#track(this.#claims, surface);\n }\n\n #track(list: HTMLElement[], el: HTMLElement): () => void {\n list.push(el);\n this.#sync();\n let active = true;\n return () => {\n if (!active) {\n return;\n }\n active = false;\n list.splice(list.indexOf(el), 1);\n this.#sync();\n };\n }\n\n #sync(): void {\n if (this.#applied !== null) {\n removeOwnedIds(this.#applied.owner, this.#applied.added);\n this.#applied = null;\n }\n const owner = this.#claims.at(-1);\n if (owner === undefined) {\n return;\n }\n const ids = this.#regions\n .filter((region) => !composedContains(owner, region))\n .map((region) => this.#idOf(region));\n const added = addOwnedIds(owner, ids);\n if (added.length > 0) {\n this.#applied = { owner, added };\n }\n }\n\n #idOf(region: HTMLElement): string {\n if (region.id === '') {\n region.id = this.#ids.next('for-modal-owned');\n }\n return region.id;\n }\n}\n\nfunction ownedIds(el: HTMLElement): string[] {\n return (el.getAttribute('aria-owns') ?? '').split(/\\s+/).filter((id) => id !== '');\n}\n\nfunction addOwnedIds(el: HTMLElement, ids: readonly string[]): string[] {\n const current = ownedIds(el);\n const added = [...new Set(ids)].filter((id) => !current.includes(id));\n if (added.length > 0) {\n el.setAttribute('aria-owns', [...current, ...added].join(' '));\n }\n return added;\n}\n\nfunction removeOwnedIds(el: HTMLElement, ids: readonly string[]): void {\n const remaining = ownedIds(el).filter((id) => !ids.includes(id));\n if (remaining.length > 0) {\n el.setAttribute('aria-owns', remaining.join(' '));\n } else {\n el.removeAttribute('aria-owns');\n }\n}\n","import { DOCUMENT, DestroyRef, Injectable, PLATFORM_ID, inject } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\nimport { MODAL_EXEMPT_ATTRIBUTE } from '../host-attributes/modal-attributes';\nimport { ModalOwnedRegions } from '../modal-owned-regions/modal-owned-regions';\nimport { VISUALLY_HIDDEN_STYLE } from '../visually-hidden/visually-hidden';\n\ntype Politeness = 'polite' | 'assertive';\n\ninterface LiveRegion {\n readonly element: HTMLElement;\n readonly unregister: () => void;\n generation: number;\n timer: ReturnType<typeof setTimeout> | null;\n}\n\n/**\n * Tiny ARIA live-region helper. Injects two persistent off-screen regions\n * (`polite` and `assertive`) into `document.body` at construction, then\n * writes / clears messages on demand.\n *\n * Each region declares one channel — `aria-live` plus `aria-atomic`, never a `role`. A live role\n * buys nothing here: its advantage is being read when a node is *inserted* with its text already\n * present, and these regions are inserted empty and only ever rewritten.\n *\n * They are created up front rather than on first use, because a live region must already be in the\n * accessibility tree before its text changes for the change to be announced; creating one inside\n * the first `announce()` risks dropping the first message of a session.\n *\n * Every message is flushed through a deferred write so the region is briefly emptied first, since\n * screen readers ignore repeated text that has not changed. The delay is a macrotask on purpose —\n * with both writes in one microtask drain the empty state never reaches the accessibility tree, and\n * NVDA and VoiceOver miss the repeat.\n *\n * The two politeness regions own independent timers, so a `polite` announce cannot cancel a pending\n * `assertive` one. Within a single region a superseding `announce()` coalesces and the latest\n * message wins, so text that evolves across a change-detection pass is read out once, in full.\n *\n * Each region carries the `MODAL_EXEMPT_ATTRIBUTE`, so an open modal does not inert it and swallow\n * every announcement made over it. The marker is stamped before the region is appended, so a region\n * created while a modal is already open is skipped too. The topmost open `aria-modal` surface of\n * the library also lists each region in its `aria-owns`, so a screen reader that hides everything\n * outside that surface still reads it.\n *\n * The regions are detached and every pending write cancelled when the injector is destroyed. DOM\n * access is gated on `isPlatformBrowser`, so `announce()` and `clear()` are no-ops on the server.\n *\n * @example\n * ```ts\n * private readonly announcer = inject(LiveAnnouncer);\n *\n * onUploadComplete(): void {\n * this.announcer.announce('Upload complete', 'polite');\n * }\n * ```\n */\n@Injectable({ providedIn: 'root' })\nexport class LiveAnnouncer {\n readonly #document = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n readonly #regions = new Map<Politeness, LiveRegion>();\n readonly #modalOwned = inject(ModalOwnedRegions);\n\n constructor() {\n if (this.#isBrowser) {\n for (const politeness of ['polite', 'assertive'] as const) {\n this.#createRegion(politeness);\n }\n }\n inject(DestroyRef).onDestroy(() => {\n for (const region of this.#regions.values()) {\n this.#cancel(region);\n region.unregister();\n region.element.remove();\n }\n this.#regions.clear();\n });\n }\n\n /**\n * Announce a message in the requested politeness region. Defaults to\n * `polite`, which lets the screen reader finish what it is currently\n * reading; `assertive` interrupts immediately.\n *\n * A superseding announce to the same region coalesces (the latest message\n * wins); the two regions are independent, so a `polite` announce never\n * cancels a pending `assertive` one. Pass an empty string (or call `clear()`)\n * to silence a pending announcement. No-op on a non-browser platform.\n */\n announce(message: string, politeness: Politeness = 'polite'): void {\n if (!this.#isBrowser) {\n return;\n }\n const region = this.#regions.get(politeness)!;\n region.element.textContent = '';\n this.#cancel(region);\n const generation = region.generation;\n region.timer = setTimeout(() => {\n region.timer = null;\n if (generation !== region.generation) {\n return;\n }\n region.element.textContent = message;\n }, 0);\n }\n\n /** Empty all live regions and cancel any pending announce so it never paints. */\n clear(): void {\n if (!this.#isBrowser) {\n return;\n }\n for (const region of this.#regions.values()) {\n this.#cancel(region);\n region.element.textContent = '';\n }\n }\n\n #cancel(region: LiveRegion): void {\n region.generation++;\n if (region.timer !== null) {\n clearTimeout(region.timer);\n region.timer = null;\n }\n }\n\n #createRegion(politeness: Politeness): void {\n const region = this.#document.createElement('div');\n region.setAttribute('aria-live', politeness);\n region.setAttribute('aria-atomic', 'true');\n region.setAttribute(MODAL_EXEMPT_ATTRIBUTE, '');\n // Visually hidden but kept in the accessibility tree.\n region.style.cssText = VISUALLY_HIDDEN_STYLE;\n this.#document.body.appendChild(region);\n this.#regions.set(politeness, {\n element: region,\n unregister: this.#modalOwned.register(region),\n generation: 0,\n timer: null,\n });\n }\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n DOCUMENT,\n DestroyRef,\n Injectable,\n PLATFORM_ID,\n inject,\n signal,\n type Signal,\n} from '@angular/core';\n\n/**\n * Application-scoped `matchMedia` observer: one `MediaQueryList` and one\n * `change` listener per distinct query string, shared by every caller and\n * removed when the application is destroyed.\n *\n * SSR-safe: off the browser, where `matchMedia` is unavailable, or once the\n * application is destroyed, an unobserved query reads a frozen `false` and\n * `matchMedia` is never touched.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\n@Injectable({ providedIn: 'root' })\nexport class MediaQueryRegistry {\n readonly #win = inject(DOCUMENT).defaultView;\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n readonly #entries = new Map<string, Signal<boolean>>();\n readonly #teardowns: Array<() => void> = [];\n readonly #unmatched = signal(false).asReadonly();\n #destroyed = false;\n\n constructor() {\n inject(DestroyRef).onDestroy(() => {\n this.#destroyed = true;\n for (const teardown of this.#teardowns) {\n teardown();\n }\n this.#teardowns.length = 0;\n });\n }\n\n /**\n * Reflects `MediaQueryList.matches` for `query` as a signal. Repeated calls\n * with the same query return the same signal.\n */\n observe(query: string): Signal<boolean> {\n const cached = this.#entries.get(query);\n if (cached !== undefined) {\n return cached;\n }\n const win = this.#win;\n if (this.#destroyed || !this.#isBrowser || !win || typeof win.matchMedia !== 'function') {\n return this.#unmatched;\n }\n\n const mql = win.matchMedia(query);\n const matches = signal(mql.matches);\n const listener = (event: MediaQueryListEvent): void => {\n matches.set(event.matches);\n };\n mql.addEventListener('change', listener);\n this.#teardowns.push(() => mql.removeEventListener('change', listener));\n\n const result = matches.asReadonly();\n this.#entries.set(query, result);\n return result;\n }\n}\n\n/**\n * Reflects the result of `MediaQueryList.matches` for `query` as a signal,\n * staying in sync via `addEventListener('change')`. Every call reading the\n * same query shares one `MediaQueryList` and one listener, which live as long\n * as the application rather than the calling injection context.\n *\n * Must be called from an injection context. SSR-safe: when `PLATFORM_ID`\n * is not the browser the helper returns a frozen `signal(false)` and never\n * touches `matchMedia`. Browsers without `matchMedia` (extreme legacy) fall\n * into the same SSR path.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\nexport function injectMediaQuery(query: string): Signal<boolean> {\n return inject(MediaQueryRegistry).observe(query);\n}\n\n/**\n * Reflects the `prefers-reduced-motion: reduce` media query as a signal — the\n * standard hook for users who have asked their OS to suppress animations. The\n * signal flips reactively if the preference changes mid-session.\n *\n * Because forty-cdk ships no styles, every animation is the consumer's, and so\n * is honouring this preference. Treat a `true` result as a hard signal to skip\n * the animated path entirely, not just to shorten the duration. The primitives\n * whose own default behaviour involves motion (drag gestures, large transforms,\n * parallax) read the same signal.\n *\n * Must be called from an injection context. SSR-safe: on the server the\n * returned signal is a frozen `false`, so the server render takes the animated\n * path's markup and the preference is applied once the client observes it.\n *\n * @example\n * ```ts\n * private readonly reducedMotion = injectPrefersReducedMotion();\n *\n * protected readonly transition = computed(() =>\n * this.reducedMotion() ? 'none' : 'transform 200ms ease-out',\n * );\n * ```\n *\n * @returns A `Signal<boolean>` that is `true` while the user asks for reduced\n * motion.\n */\nexport function injectPrefersReducedMotion(): Signal<boolean> {\n return injectMediaQuery('(prefers-reduced-motion: reduce)');\n}\n","/** Clamps `value` into the inclusive `[min, max]` range. */\nexport function clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\n/**\n * The number of decimal places `n` carries, handling both plain (`0.1` → 1) and\n * exponential (`1e-7` → 7, `1.5e-7` → 8) notation — `String(n)` switches to\n * exponential form below ~`1e-7`, which a naive `indexOf('.')` would read as\n * zero decimals. Non-finite values report 0.\n */\nexport function decimalPlaces(n: number): number {\n if (!Number.isFinite(n)) {\n return 0;\n }\n const text = String(n);\n const exponentIndex = text.indexOf('e');\n if (exponentIndex < 0) {\n const dot = text.indexOf('.');\n return dot < 0 ? 0 : text.length - dot - 1;\n }\n const exponent = Number(text.slice(exponentIndex + 1));\n const mantissa = text.slice(0, exponentIndex);\n const mantissaDot = mantissa.indexOf('.');\n const mantissaDecimals = mantissaDot < 0 ? 0 : mantissa.length - mantissaDot - 1;\n return Math.max(0, mantissaDecimals - exponent);\n}\n\n/**\n * Rounds `value` to `decimals` decimal places. A non-positive `decimals` (an\n * integer-precision request) returns `value` unchanged.\n */\nexport function roundToDecimals(value: number, decimals: number): number {\n if (decimals <= 0) {\n return value;\n }\n const factor = 10 ** decimals;\n return Math.round(value * factor) / factor;\n}\n\n/**\n * Rounds `value` to the decimal precision a `step` carries, so repeated\n * `value ± step` arithmetic with a fractional step (e.g. `0.1`) cannot accumulate\n * float noise (`0.1 * 3 === 0.30000000000000004`) that defeats a `next === value`\n * change guard or leaks into `aria-valuenow`. Precision is derived via\n * {@link decimalPlaces}, so exponential steps (`1e-7`) round correctly; integer\n * steps return `value` unchanged.\n */\nexport function roundToStepPrecision(value: number, step: number): number {\n return roundToDecimals(value, decimalPlaces(step));\n}\n\n/**\n * Snaps `raw` onto the `[min, min + step, min + 2·step, …]` grid, then rounds the\n * result to the greater of the step's and `min`'s decimal precision so a\n * fractional step can't accumulate float noise and a `min` finer than `step`\n * still lands exactly on the grid (e.g. `min=0.05, step=0.1` keeps `0.15`\n * instead of rounding to the step's single decimal and drifting to `0.2`). A\n * non-positive `step` disables snapping and returns `raw` unchanged. Clamping to\n * an outer range is the caller's responsibility — pass the snapped result to\n * {@link clamp}.\n */\nexport function snapToStep(raw: number, step: number, min: number): number {\n if (step <= 0) {\n return raw;\n }\n return roundToDecimals(\n Math.round((raw - min) / step) * step + min,\n Math.max(decimalPlaces(step), decimalPlaces(min)),\n );\n}\n\n/** Configuration for a single {@link stepOnGrid} move. */\nexport interface StepOnGridOptions {\n /**\n * Grid spacing. The grid is `origin ± k · step`. A non-positive or\n * non-finite `step` disables snapping (see {@link stepOnGrid}).\n */\n readonly step: number;\n /** Direction of travel: `1` toward `+∞`, `-1` toward `-∞`. */\n readonly direction: 1 | -1;\n /**\n * Grid origin — the value the grid is measured from, normally the control's\n * `min`. Defaults to `0`.\n */\n readonly origin?: number;\n /**\n * Distance travelled from a value that is already on the grid (a page step,\n * or a caller-supplied amount finer than `step`). Defaults to `step`. It is\n * ignored when the value is off the grid.\n */\n readonly by?: number;\n}\n\n/**\n * Moves `value` one grid position in `direction` along the\n * `origin ± k · step` grid, matching the platform `stepUp()` / `stepDown()`\n * rule so a spinbutton and a slider answer the same key the same way:\n *\n * - **Off the grid** → the nearest grid point strictly in `direction`\n * (`0.55` with `step: 1` gives `1` up / `0` down, `0.36` with `step: 0.1`\n * gives `0.4` up / `0.3` down), so an arbitrary consumer value is corrected\n * onto the grid instead of carrying its offset forever.\n * `by` is ignored here — a page-sized jump from an off-grid\n * value still only lands on the adjacent grid point, exactly as\n * `HTMLInputElement.stepUp(n)` behaves.\n * - **On the grid** → `value ± by` (`1` with `step: 1` gives `2`, never `1`),\n * so a `by` finer than `step` keeps its own precision.\n *\n * The result is rounded to the greatest decimal precision of `step`, `by` and\n * `origin`, so repeated fractional stepping cannot accumulate float noise\n * (`0.1 + 0.2` stepped up by `0.1` yields `0.4`, not `0.4000000000000001`). A\n * value is on the grid when it sits within float noise of a grid point, so one\n * carrying that noise is still recognised as on-grid while one with more\n * decimals than the step is not. A `by` of `0` returns `value` unchanged; a\n * non-positive or non-finite `step` (and a non-finite `value` / `origin`)\n * disables snapping and falls back to plain `value + direction · by` at the\n * same precision. Clamping to an outer range\n * is the caller's responsibility — pass the result to {@link clamp}. Use\n * {@link snapToStep} instead when the input is a continuous measurement with\n * no direction of travel (a pointer drag), which snaps to the *nearest* grid\n * point rather than the next one.\n */\nexport function stepOnGrid(value: number, options: StepOnGridOptions): number {\n const { step, direction, origin = 0, by = step } = options;\n const precision = Math.max(decimalPlaces(step), decimalPlaces(by), decimalPlaces(origin));\n if (by === 0) {\n return value;\n }\n if (\n !(step > 0) ||\n !Number.isFinite(step) ||\n !Number.isFinite(value) ||\n !Number.isFinite(origin)\n ) {\n return roundToDecimals(value + direction * by, precision);\n }\n const index = (value - origin) / step;\n if (!Number.isFinite(index)) {\n return roundToDecimals(value + direction * by, precision);\n }\n const floatNoise = ((Math.abs(value) + Math.abs(origin)) / step) * Number.EPSILON * 1024;\n if (Math.abs(index - Math.round(index)) <= floatNoise) {\n return roundToDecimals(value + direction * by, precision);\n }\n const gridIndex = direction > 0 ? Math.ceil(index) : Math.floor(index);\n return roundToDecimals(gridIndex * step + origin, precision);\n}\n","import { DOCUMENT, DestroyRef, Injectable, PLATFORM_ID, inject } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\n/**\n * Refcounted `document.visibilitychange` subscription. Multiple toasts\n * (or any other primitive that wants to pause work while the page is in\n * the background) call `subscribe` independently — only the first\n * subscribe attaches the listener, only the last unsubscribe removes it.\n *\n * Each subscriber receives `true` while `document.visibilityState !== 'visible'`\n * (the page is hidden / backgrounded) and `false` when it becomes visible\n * again. Subscribers are not invoked synchronously on subscribe — they\n * only fire on transitions, so register them in a context where the\n * primitive's \"visible\" state is the implicit starting point.\n *\n * SSR: `providedIn: 'root'` so the listener set is scoped to one Angular\n * bootstrap. Server-side calls return a no-op unsubscribe.\n */\ntype VisibilityListener = (hidden: boolean) => void;\n\n@Injectable({ providedIn: 'root' })\nexport class VisibilityPause {\n readonly #document = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n readonly #listeners = new Set<VisibilityListener>();\n #domListener: (() => void) | null = null;\n\n constructor() {\n if (!this.#isBrowser) {\n return;\n }\n inject(DestroyRef).onDestroy(() => {\n this.#detachDomListener();\n this.#listeners.clear();\n });\n }\n\n /**\n * Whether the page is currently hidden / backgrounded\n * (`document.visibilityState !== 'visible'`). Returns `false` on the\n * server. Use this to seed initial pause state, since `subscribe` only\n * fires on transitions and never synchronously on subscribe.\n */\n currentlyHidden(): boolean {\n return this.#isBrowser ? this.#document.visibilityState !== 'visible' : false;\n }\n\n subscribe(listener: VisibilityListener): () => void {\n if (!this.#isBrowser) {\n return () => {};\n }\n if (this.#listeners.size === 0) {\n this.#attachDomListener();\n }\n this.#listeners.add(listener);\n\n return (): void => {\n if (!this.#listeners.delete(listener)) {\n return;\n }\n if (this.#listeners.size === 0) {\n this.#detachDomListener();\n }\n };\n }\n\n #attachDomListener(): void {\n this.#domListener = (): void => {\n const hidden = this.#document.visibilityState !== 'visible';\n for (const fn of this.#listeners) {\n fn(hidden);\n }\n };\n this.#document.addEventListener('visibilitychange', this.#domListener);\n }\n\n #detachDomListener(): void {\n if (this.#domListener) {\n this.#document.removeEventListener('visibilitychange', this.#domListener);\n this.#domListener = null;\n }\n }\n}\n\n/**\n * Convenience wrapper that resolves the application-scoped\n * `VisibilityPause` and subscribes. Must be called from an injection\n * context.\n */\nexport function subscribeVisibilityPause(listener: VisibilityListener): () => void {\n return inject(VisibilityPause).subscribe(listener);\n}\n\n/**\n * Convenience wrapper that resolves the application-scoped\n * `VisibilityPause` and reports whether the page is currently hidden.\n * Must be called from an injection context. Returns `false` on the server.\n */\nexport function isPageHidden(): boolean {\n return inject(VisibilityPause).currentlyHidden();\n}\n","import { DestroyRef, inject, type Signal, signal } from '@angular/core';\n\nimport { isPageHidden, subscribeVisibilityPause } from './visibility-pause';\n\n/**\n * Options for {@link injectPauseController}.\n */\nexport interface PauseControllerOptions {\n /**\n * When `true` (default), the controller auto-subscribes the shared\n * `visibility-pause` source: it applies the `'visibility'` reason while the\n * page is backgrounded (seeding from the current state on construction) and\n * releases it when the page becomes visible again. The reason key is always\n * the literal `'visibility'`, so the reason union `R` must include it — a\n * caller that leaves page-visibility tracking enabled (i.e. does not pass\n * `trackPageVisibility: false`) fails to compile unless `'visibility'` is\n * assignable to `R`. Pass `trackPageVisibility: false` to opt out, which also\n * exempts the caller from that constraint.\n */\n trackPageVisibility?: boolean;\n /**\n * Invoked synchronously on every `paused` transition (and only on a genuine\n * change), after the `paused` signal has been updated. Lets a consumer layer\n * imperative side effects on the edge — e.g. Toast captures the remaining\n * auto-dismiss time on pause and reschedules on resume — without putting its\n * timer on the reactive graph.\n */\n onChange?: (paused: boolean) => void;\n}\n\n/**\n * Multi-reason pause controller shared by Toast and Carousel.\n *\n * Holds the set of active pause reasons and a derived `paused` signal (`true`\n * while any reason is held). Several independent sources — pointer hover,\n * focus, page visibility — can each pause and resume independently; the work\n * stays paused until every reason is released. Toast and Carousel previously\n * hand-rolled byte-identical copies of the reason set plus `apply` / `release`\n * / `update` helpers, and the copies had already drifted (only Toast wired the\n * page-visibility source through it). Centralizing both restores parity.\n *\n * Must be called from an injection context (subscribes `visibility-pause` via\n * the injector-scoped source). Internal core tier — no semver guarantee.\n */\nexport interface PauseController<R extends string> {\n /** `true` while at least one pause reason is held. */\n readonly paused: Signal<boolean>;\n /** Hold `reason`. Idempotent — holding an already-held reason is a no-op. */\n apply(reason: R): void;\n /** Release `reason`. Idempotent — releasing a not-held reason is a no-op. */\n release(reason: R): void;\n}\n\n/**\n * Builds a {@link PauseController}. When `trackPageVisibility` is enabled the\n * `'visibility'` reason is wired to the shared `visibility-pause` source and\n * its subscription is torn down with the surrounding injector.\n *\n * The caller contract is compiler-checked: because page-visibility tracking\n * defaults on and always holds the literal `'visibility'` reason, a caller that\n * leaves it enabled must have `'visibility'` assignable to `R`. When it isn't,\n * the `options` argument becomes required and must be `{ trackPageVisibility:\n * false }`, so enabling the source without a matching reason union fails to\n * compile. Callers that pass `trackPageVisibility: false` are exempt (any `R`).\n */\nexport function injectPauseController<R extends string>(\n ...args: 'visibility' extends R\n ? [options?: PauseControllerOptions]\n : [options: PauseControllerOptions & { trackPageVisibility: false }]\n): PauseController<R> {\n const options: PauseControllerOptions = args[0] ?? {};\n const reasons = new Set<R>();\n const paused = signal(false);\n\n function update(): void {\n const next = reasons.size > 0;\n if (next === paused()) {\n return;\n }\n paused.set(next);\n options.onChange?.(next);\n }\n\n function apply(reason: R): void {\n reasons.add(reason);\n update();\n }\n\n function release(reason: R): void {\n reasons.delete(reason);\n update();\n }\n\n if (options.trackPageVisibility ?? true) {\n const visibilityReason = 'visibility' as R;\n const unsubscribe = subscribeVisibilityPause((hidden) => {\n if (hidden) {\n apply(visibilityReason);\n } else {\n release(visibilityReason);\n }\n });\n inject(DestroyRef).onDestroy(unsubscribe);\n if (isPageHidden()) {\n apply(visibilityReason);\n }\n }\n\n return {\n paused: paused.asReadonly(),\n apply,\n release,\n };\n}\n","/**\n * Whether a pointer event comes from a device that hovers.\n *\n * Hover-driven menu behaviour — sub-trigger hover-open / hover-close,\n * hover-follows-pointer highlighting, the submenu safe triangle, the menubar's\n * hover keepalive — is a mouse affordance: touch and pen are both reported as\n * non-hovering here, so on those pointer types the same primitives are driven\n * by tap (the native click) instead. The empty `pointerType` counts as\n * hover-capable: a synthetic `PointerEvent` leaves it `''` (browsers only\n * populate it for real input), and a synthetic hover must behave like a mouse\n * hover rather than being dropped.\n *\n * This is the stricter of the library's two hover vocabularies — see\n * {@link isNonTouchPointer} for the pen-inclusive twin used by the tooltip /\n * hover-card family. The two are kept apart: a pen genuinely\n * hovers a tooltip, and genuinely should not hover-open a submenu.\n *\n * @param event The pointer event to classify — only `pointerType` is read.\n * @returns `true` for `'mouse'` and for the empty synthetic `pointerType`,\n * `false` for `'touch'` / `'pen'` / any other value.\n */\nexport function isHoverCapablePointer(event: Pick<PointerEvent, 'pointerType'>): boolean {\n return event.pointerType === '' || event.pointerType === 'mouse';\n}\n\n/**\n * Whether a pointer event comes from a device whose hover is meaningful for\n * descriptive, supplementary content.\n *\n * Tooltip / hover-card triggers and the `injectHovered` hover state treat a pen\n * as a hovering device — a stylus reports `pointerover` / `pointerenter` while\n * it is detected above the digitizer, so a pen user gets the same preview a\n * mouse user does. Only `'touch'` is rejected: a tap emits an emulated\n * `pointerenter` that would otherwise leave the element stuck in a hovered\n * state after the finger lifts, and the APG flags hover-revealed content as\n * problematic on touch (no hover, no obvious dismiss). The empty synthetic\n * `pointerType` passes, matching {@link isHoverCapablePointer}.\n *\n * This is the pen-inclusive twin of {@link isHoverCapablePointer}, which is\n * mouse-only because the menu family drives submenu hover-open by tap on both\n * touch and pen. Pick the predicate that matches the family you are writing\n * for; do not fold one onto the other.\n *\n * Neither predicate covers the non-hover `pointerType` checks in the library —\n * the twelve primary-button guards (`pointerType === 'mouse' && button !== 0`\n * in `pressed`, the drag-session handle guard, swipe-dismiss, listbox reorder,\n * virtual reorder, table row reorder, tree node drag, the pane resizer, the\n * table column resizer, the slider, the scroll-area thumb and the scroll-area\n * track press) and the context-menu long-press gate\n * (`pointerType !== 'touch'`). Those classify a press, not a hover, so they\n * stay inline by design.\n *\n * @param event The pointer event to classify — only `pointerType` is read.\n * @returns `false` for `'touch'`, `true` for every other `pointerType`\n * (`'mouse'`, `'pen'`, the empty synthetic value, or a future device type).\n */\nexport function isNonTouchPointer(event: Pick<PointerEvent, 'pointerType'>): boolean {\n return event.pointerType !== 'touch';\n}\n","import { DestroyRef, ElementRef, inject } from '@angular/core';\n\nimport { composedParentElement, resolveEventTarget } from '../composed-tree/composed-tree';\nimport { FOCUSABLE_SELECTOR, isDisabledControl } from '../focus-trap/focusable-candidate';\n\nexport function preventPointerFocus(when: (event: MouseEvent) => boolean = () => true): void {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const onMouseDown = (event: MouseEvent): void => {\n if (when(event)) {\n event.preventDefault();\n }\n };\n host.addEventListener('mousedown', onMouseDown);\n inject(DestroyRef).onDestroy(() => host.removeEventListener('mousedown', onMouseDown));\n}\n\nexport function pressFocusesDescendant(event: Event, host: Element): boolean {\n return mouseFocusTarget(resolveEventTarget(event), host) !== null;\n}\n\nexport function mouseFocusTarget(\n node: Node | null,\n boundary: Element | null = null,\n): HTMLElement | null {\n for (let current = node; current !== null && current !== boundary;) {\n if (current.nodeType === current.ELEMENT_NODE && isMouseFocusable(current as Element)) {\n return current as HTMLElement;\n }\n current = composedParentElement(current);\n }\n return null;\n}\n\nfunction isMouseFocusable(el: Element): boolean {\n return (el.hasAttribute('tabindex') || el.matches(FOCUSABLE_SELECTOR)) && !isDisabledControl(el);\n}\n\nexport function focusAfterPress(host: HTMLElement): void {\n host.focus({ preventScroll: true });\n}\n\n/** How long (ms) after a press, or its release, a focus still counts as caused by it. */\nexport const DEFAULT_PRESS_FOCUS_WINDOW_MS = 500;\n\n/**\n * Tells a focus a pointer press caused from a keyboard focus, for a trigger that\n * opens on keyboard focus only.\n *\n * A press counts for a bounded window only, so a press that never focuses its\n * target (a `<button>` or `<a>` in macOS Safari and Firefox, a `mousedown` whose\n * default is prevented) cannot make a later keyboard focus read as\n * pointer-induced.\n */\nexport interface PressFocus {\n /** Records a press on the element. Call it from `pointerdown`. */\n press(): void;\n /**\n * Restarts the window when a recorded press ends, since a touch tap focuses\n * its target only after the release. Call it from `pointerup`; a no-op when\n * no press is recorded.\n */\n release(): void;\n /** Whether a focus arriving now was caused by the recorded press. Forgets the press. */\n consume(): boolean;\n /** Forgets the recorded press. Call it from `blur`. */\n reset(): void;\n}\n\n/**\n * Creates a {@link PressFocus} backed by a timestamp window.\n *\n * @param windowMs How long a press stays able to explain a focus. Defaults to\n * {@link DEFAULT_PRESS_FOCUS_WINDOW_MS}.\n */\nexport function createPressFocus(windowMs: number = DEFAULT_PRESS_FOCUS_WINDOW_MS): PressFocus {\n let pressed = false;\n let stampedAt = 0;\n return {\n press(): void {\n pressed = true;\n stampedAt = Date.now();\n },\n release(): void {\n if (pressed) {\n stampedAt = Date.now();\n }\n },\n consume(): boolean {\n const induced = pressed && Date.now() - stampedAt < windowMs;\n pressed = false;\n return induced;\n },\n reset(): void {\n pressed = false;\n },\n };\n}\n","/**\n * Pointer-suppression window.\n *\n * When keyboard navigation moves the active option of an\n * `aria-activedescendant` listbox and scrolls it into view, the scroll can\n * slide a *different* option under a stationary cursor. The browser then fires\n * a synthetic `pointermove` / `pointerover` for that option even though the\n * pointer never physically moved, and a naive hover handler would hijack the\n * active descendant onto the option the user merely scrolled past — fighting\n * the keyboard intent.\n *\n * The fix every native-feeling listbox uses is a brief window, opened the\n * moment the directive scrolls programmatically, during which hover-driven\n * activation is ignored. A genuine pointer move that lands after the window\n * elapses takes over again, so mouse and keyboard intent stay in sync without\n * the scroll stealing the active option.\n *\n * Pure and Angular-free: no DI, no timers, no globals touched at module load.\n * State is a single \"suppressed until\" timestamp compared against `Date.now()`\n * inside the (browser-only) event handlers that call it, so it is SSR-safe and\n * needs no teardown. Unit-tested in `pointer-suppression.spec.ts`.\n */\n\n/** Default suppression window, in milliseconds. */\nexport const DEFAULT_POINTER_SUPPRESSION_MS = 200;\n\n/**\n * Tracks a short window during which hover-driven activation should be ignored.\n * Created once per primitive instance; consulted synchronously inside pointer\n * event handlers.\n */\nexport interface PointerSuppression {\n /**\n * Open (or extend) the suppression window from the current instant. Call it\n * immediately before a programmatic scroll that could move options under a\n * stationary cursor.\n */\n suppress(): void;\n /**\n * Whether the suppression window is currently open. Hover handlers bail out\n * (leaving the active descendant unchanged) while this returns `true`.\n */\n isSuppressed(): boolean;\n}\n\n/**\n * Create a {@link PointerSuppression} backed by a timestamp window.\n *\n * @param windowMs How long the window stays open after each {@link\n * PointerSuppression.suppress} call. Defaults to\n * {@link DEFAULT_POINTER_SUPPRESSION_MS}.\n */\nexport function createPointerSuppression(\n windowMs: number = DEFAULT_POINTER_SUPPRESSION_MS,\n): PointerSuppression {\n let suppressedUntil = 0;\n return {\n suppress(): void {\n suppressedUntil = Date.now() + windowMs;\n },\n isSuppressed(): boolean {\n return Date.now() < suppressedUntil;\n },\n };\n}\n","import { DOCUMENT, inject, Injectable } from '@angular/core';\n\n@Injectable({ providedIn: 'root' })\nexport class StationaryPointerMoves {\n readonly #document = inject(DOCUMENT);\n readonly #verdicts = new WeakMap<Event, boolean>();\n #controller: AbortController | null = null;\n #users = 0;\n #pointerId = -1;\n #x = Number.NaN;\n #y = Number.NaN;\n #scrolled = false;\n\n acquire(): () => void {\n if (this.#users === 0) {\n this.#listen();\n }\n this.#users += 1;\n let released = false;\n return () => {\n if (released) {\n return;\n }\n released = true;\n this.#users -= 1;\n if (this.#users === 0) {\n this.#controller?.abort();\n this.#controller = null;\n }\n };\n }\n\n isStationary(event: PointerEvent): boolean {\n const known = this.#verdicts.get(event);\n if (known !== undefined) {\n return known;\n }\n const stationary =\n this.#scrolled &&\n event.pointerId === this.#pointerId &&\n event.clientX === this.#x &&\n event.clientY === this.#y;\n this.#verdicts.set(event, stationary);\n this.#scrolled = false;\n this.#pointerId = event.pointerId;\n this.#x = event.clientX;\n this.#y = event.clientY;\n return stationary;\n }\n\n #listen(): void {\n this.#controller = new AbortController();\n this.#pointerId = -1;\n this.#x = Number.NaN;\n this.#y = Number.NaN;\n this.#scrolled = false;\n this.#document.addEventListener(\n 'scroll',\n () => {\n this.#scrolled = true;\n },\n { capture: true, passive: true, signal: this.#controller.signal },\n );\n }\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n computed,\n DestroyRef,\n ElementRef,\n inject,\n PLATFORM_ID,\n signal,\n type Signal,\n untracked,\n} from '@angular/core';\n\nimport { KeyedFlag } from '../keyed-flag/keyed-flag';\nimport { createPointerSuppression } from './pointer-suppression';\nimport { StationaryPointerMoves } from './stationary-pointer-moves';\n\nexport function injectPointerMove(handler: (event: PointerEvent) => void): void {\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n return;\n }\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const moves = inject(StationaryPointerMoves);\n const release = moves.acquire();\n const controller = new AbortController();\n host.addEventListener(\n 'pointermove',\n (event) => {\n if (!moves.isStationary(event)) {\n handler(event);\n }\n },\n { signal: controller.signal },\n );\n inject(DestroyRef).onDestroy(() => {\n controller.abort();\n release();\n });\n}\n\nexport interface PointerHighlightItem {\n readonly host: HTMLElement;\n readonly disabled: Signal<boolean>;\n}\n\nexport interface PointerHighlightActiveDescendant {\n readonly active: () => boolean;\n readonly claim: (id: string) => void;\n}\n\nexport interface PointerHighlightConfig {\n readonly items: () => readonly PointerHighlightItem[];\n readonly activeDescendant?: PointerHighlightActiveDescendant;\n}\n\nexport interface PointerHighlight {\n readonly pointed: Signal<HTMLElement | null>;\n /**\n * Whether an enabled item is under the pointer. Notifies its readers only\n * when that answer changes, not when the pointer moves between enabled items.\n */\n hasPointed(): boolean;\n /** Whether `host` is the enabled item under the pointer. Reactive per host. */\n isPointed(host: HTMLElement): boolean;\n claim(host: HTMLElement, id?: string): void;\n release(): void;\n suppress(): void;\n isSuppressed(): boolean;\n}\n\nexport function createPointerHighlight(config: PointerHighlightConfig): PointerHighlight {\n const suppression = createPointerSuppression();\n const host = signal<HTMLElement | null>(null);\n const pointed = computed<HTMLElement | null>(() => {\n const current = host();\n if (current === null) {\n return null;\n }\n const item = config.items().find((candidate) => candidate.host === current);\n return item && !item.disabled() ? current : null;\n });\n const flag = new KeyedFlag<HTMLElement>();\n const epoch = signal(0);\n let tracksItems = false;\n const hasPointed = computed(() => {\n epoch();\n if (tracksItems) {\n for (const item of config.items()) {\n item.disabled();\n }\n }\n return untracked(pointed) !== null;\n });\n const point = (next: HTMLElement | null): void => {\n untracked(() => {\n if (host() === next) {\n return;\n }\n const before = hasPointed();\n flag.move(next);\n host.set(next);\n const subscribes = next !== null && !tracksItems;\n if (subscribes) {\n tracksItems = true;\n }\n if (subscribes || (pointed() !== null) !== before) {\n epoch.update((value) => value + 1);\n }\n });\n };\n return {\n pointed,\n hasPointed,\n isPointed(target: HTMLElement): boolean {\n return flag.has(target) && hasPointed();\n },\n claim(target: HTMLElement, id: string = target.id): void {\n if (suppression.isSuppressed()) {\n return;\n }\n const activeDescendant = config.activeDescendant;\n if (activeDescendant?.active()) {\n activeDescendant.claim(id);\n return;\n }\n point(target);\n },\n release(): void {\n point(null);\n },\n suppress(): void {\n suppression.suppress();\n },\n isSuppressed(): boolean {\n return suppression.isSuppressed();\n },\n };\n}\n","import {\n DOCUMENT,\n PLATFORM_ID,\n DestroyRef,\n ElementRef,\n effect,\n inject,\n signal,\n} from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\nimport { afterNextRenderCancellable } from '../after-next-render-cancellable/after-next-render-cancellable';\nimport { composedParentElement } from '../composed-tree/composed-tree';\nimport { injectDeclaredDirection, stampAmbientDirection } from '../text-direction/text-direction';\n\nexport interface PortalConfig {\n /**\n * Where to portal the host element. Defaults to `document.body`. Pass a\n * specific container for cases like fullscreen API stacking, scoped\n * testing harnesses, or shadow DOM hosts.\n *\n * A function form is also accepted; it is resolved lazily inside the\n * existing `afterNextRender` callback so a value that is not yet available\n * at construction time — for example a directive input — can be used.\n * Returns `null` or `undefined` to fall back to `document.body`.\n */\n readonly target?: HTMLElement | (() => HTMLElement | null | undefined);\n\n /**\n * Sibling the host is inserted immediately before, resolved in the same `afterNextRender`\n * callback as `target`. Honoured only while that element is a child of the target; otherwise,\n * or when it returns `null` / `undefined`, the host is appended.\n */\n readonly before?: () => Element | null | undefined;\n}\n\n/**\n * Moves the directive's host element to `target` (default `document.body`)\n * after the first render and removes it on destroy. Designed for primitives\n * that need to escape clipping / `transform` / `overflow: hidden` ancestors:\n * tooltips, popovers, dialogs, toasts.\n *\n * Must be called from an injection context. The directive's `ElementRef` is\n * the host that gets portaled. Angular destroy hooks still fire normally —\n * the view tree is unaffected, only the DOM position changes.\n *\n * The portaled host keeps the writing direction of the position it left: unless it already\n * carries a `dir` attribute when it moves, it is given the `dir` declared above its original\n * parent (the nearest `[dir]` ancestor, across open shadow roots, then `<html dir>`), and follows\n * runtime `dir` changes there. So content opened inside a `dir=\"rtl\"` subtree stays RTL, and a\n * floating `align` of `start` / `end` resolves against that direction rather than against\n * `<body>`'s. When no element declares a `dir`, the host is left without one and inherits its\n * direction where it lands, CSS `direction` included.\n *\n * Note: any styles scoped to the original parent (CSS modules, encapsulated\n * `:host` rules, descendant selectors) won't reach the portaled element.\n * Style it via global CSS or with classes on the host directive itself.\n *\n * SSR: the portal is a no-op on the server. Overlay primitives use\n * `afterNextRender` to wire side effects, which doesn't run server-side\n * either; static markup (role, aria-*, ids, data-state) renders normally\n * and the portaled position is established once the client takes over.\n *\n * Implementation note — destroy ordering. The deferred `appendChild` is\n * registered via `afterNextRenderCancellable`; the destroy hook runs\n * `el.remove()`. If the directive is torn down between construction and the\n * next render (rare, but happens in synchronous open/close test paths or fast\n * SPA navigations), the destroy hook sees a not-yet-portaled element and\n * `el.remove()` is effectively a no-op against the original parent. Without\n * defending against it, the queued `afterNextRender` would still fire after\n * destroy and re-attach the element to `target` with no remaining destroy\n * hook to clean it up — a leak. The shared `afterNextRenderCancellable`\n * helper cancels the queued callback on destroy (it captures the\n * `AfterRenderRef`, calls `.destroy()` from its own destroy hook, and guards\n * the callback with a `destroyed` flag), so the `appendChild` never runs once\n * the directive is gone.\n */\nexport function injectPortal(config: PortalConfig = {}): void {\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n return;\n }\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const destroyRef = inject(DestroyRef);\n const doc = inject(DOCUMENT);\n const el = host.nativeElement;\n const resolveTarget = (): HTMLElement => {\n const t = typeof config.target === 'function' ? config.target() : config.target;\n return t ?? doc.body;\n };\n\n const origin = signal<Element | null>(null);\n const declaredDir = injectDeclaredDirection(origin);\n\n afterNextRenderCancellable(() => {\n const target = resolveTarget();\n const sibling = config.before?.() ?? null;\n const anchor =\n sibling !== null && sibling !== el && sibling.parentNode === target ? sibling : null;\n if (el.parentNode === target && (anchor === null || el.nextSibling === anchor)) {\n return;\n }\n if (el.parentNode !== target && !el.hasAttribute('dir')) {\n const parent = composedParentElement(el);\n origin.set(parent);\n stampAmbientDirection(el, parent);\n }\n target.insertBefore(el, anchor);\n });\n\n effect(() => {\n const dir = declaredDir();\n if (origin() === null) {\n return;\n }\n if (dir === null) {\n el.removeAttribute('dir');\n } else if (el.getAttribute('dir') !== dir) {\n el.setAttribute('dir', dir);\n }\n });\n\n destroyRef.onDestroy(() => {\n if (typeof requestAnimationFrame === 'undefined' || typeof el.getAnimations !== 'function') {\n el.remove();\n return;\n }\n requestAnimationFrame(() => {\n const finite = el.getAnimations({ subtree: true }).filter(isFiniteAnimation);\n if (finite.length === 0) {\n el.remove();\n return;\n }\n Promise.all(finite.map((animation) => animation.finished.catch(() => undefined))).then(() =>\n el.remove(),\n );\n });\n });\n}\n\n/**\n * True when `animation` will actually finish — i.e. it does not run forever.\n * An infinite animation (a shimmer / pulse with `animation-iteration-count:\n * infinite`) reports `Infinity` iterations, and its `finished` promise never\n * resolves; awaiting it would strand deferred teardown and leak the node.\n * Filtering these out before awaiting `finished` lets teardown proceed once the\n * finite animations settle (or immediately, when none remain). Guards for a\n * possibly-null effect and for environments lacking `getComputedTiming`.\n */\nfunction isFiniteAnimation(animation: Animation): boolean {\n const effect = animation.effect;\n if (!effect || typeof effect.getComputedTiming !== 'function') {\n return true;\n }\n return effect.getComputedTiming().iterations !== Infinity;\n}\n","import { fortyError } from '../errors/errors';\n\n/**\n * Identity of the piece asserting its root context, plus the probe that tells\n * the root apart from any other value the token's public type admits.\n */\nexport interface RootContextAssertion {\n /** Entry-point name for the `[forty-cdk/<entryPoint>]` error prefix, e.g. `'accordion'`. */\n readonly entryPoint: string;\n /** Name of the token the piece resolved, e.g. `'FOR_ACCORDION_CONTEXT'`. */\n readonly token: string;\n /** Selector of the root the token must be aliased to, e.g. `'[forAccordion]'`. */\n readonly root: string;\n /** The piece the error names, e.g. `'ForAccordionTrigger'`. */\n readonly piece: string;\n /**\n * Reads one member the resolved context only has when it is the root: a\n * `register*` method the internal interface adds, or — where the internal\n * interface adds no method of its own and only widens a member, as in Select\n * — a nested member the public facade narrows away.\n *\n * The probe passes when it resolves to a function. A probe that *throws*\n * counts as a miss, so a value missing the whole nesting level fails with the\n * error below instead of with the raw `TypeError` the read produced.\n */\n readonly probe: () => unknown;\n}\n\n/** The probed member, or `undefined` when reading it threw. */\nfunction readProbe(probe: () => unknown): unknown {\n try {\n return probe();\n } catch {\n return undefined;\n }\n}\n\n/**\n * Dev-mode guard that the value behind a split root's context token really is\n * the root. Call it from the primitive's `inject<Primitive>Context` resolver,\n * immediately after the orphan branch.\n *\n * A split root provides **one** token, publicly typed as\n * the consumer read surface, which the resolver reads at the unexported\n * internal interface's type so the pieces reach the registration protocol.\n * Nothing checks that cast: a consumer who provides the token with any other\n * value satisfying the public type typechecks and resolves, then fails inside\n * the first piece to reach the protocol — with no `[forty-cdk/<entry>]` prefix\n * and a stack pointing at a library file for a mistake made in consumer\n * providers.\n *\n * There is no compile-time channel for this, which is why the check is a\n * runtime one: the roots declare `implements For<Primitive>Context` only, and a\n * `satisfies <Primitive>Context` cannot be added because the protocol members\n * are TS-`private` — keeping them out of the emitted `.d.ts` and coupling the\n * class to the internal interface are mutually exclusive.\n *\n * The gate lives inside the helper, so it travels with the check and no call\n * site can forget it. The resolver runs from a piece's constructor, so the\n * throw aborts the render and a consumer's `try` sees it — unlike an assertion\n * routed through an `effect()`.\n */\nexport function assertRootContext(assertion: RootContextAssertion): void {\n if (typeof ngDevMode !== 'undefined' && !ngDevMode) {\n return;\n }\n if (typeof readProbe(assertion.probe) === 'function') {\n return;\n }\n throw fortyError({\n code: 'FORCDK-CORE-007',\n scope: assertion.entryPoint,\n message: `${assertion.piece} resolved a ${assertion.token} provider that is not the ${assertion.root} root.`,\n cause:\n 'The token is publicly typed as the consumer read surface, but the pieces read it at the ' +\n \"root's internal registration protocol, which only the root implements.\",\n fix:\n `Alias the token to the root itself: { provide: ${assertion.token}, useExisting: MyRoot }, ` +\n `where MyRoot is ${assertion.root} or a subclass of it.`,\n });\n}\n","import { InjectionToken, type Signal } from '@angular/core';\n\nimport type { CollectionHandle } from '../collection/collection';\nimport type {\n ListNavigationAction,\n WritingDirection,\n} from '../keyboard-navigation/keyboard-navigation';\nimport type { RovingTabindex } from './roving-tabindex';\n\n/**\n * The handle an embedded item registers with a host-roving container: its\n * host element and a `disabled` signal the container reads to skip it during\n * arrow-key navigation. Container-specific extras, such as a toggle item's\n * `value`, live on the container's own handle.\n */\nexport interface HostRovingItemHandle extends CollectionHandle {\n /**\n * Narrowed from {@link CollectionHandle}'s `Node`: the host owns focus moves\n * and the roving tab stop, both of which are element operations.\n */\n readonly host: HTMLElement;\n readonly disabled: Signal<boolean>;\n}\n\n/**\n * Coordination contract of a container that owns the roving tab stop and\n * arrow-key navigation for the items it composes, including items that\n * belong to a nested primitive and delegate focus management upward.\n *\n * Embedded items inject the token with `{ optional: true, skipSelf: true }`:\n * `optional` because an item used outside any such container has none, and\n * `skipSelf` so a container implementing the contract never resolves its\n * own provider.\n */\nexport interface HostRovingContext {\n /** Layout direction the host wants its items to navigate along. */\n readonly orientation: Signal<'horizontal' | 'vertical'>;\n /** Reading direction. RTL swaps ArrowLeft / ArrowRight semantics. */\n readonly dir: Signal<WritingDirection>;\n /** When true, every embedded item is disabled regardless of its own state. */\n readonly disabled: Signal<boolean>;\n\n /**\n * Roving-tabindex tracker owned by the host. Embedded items call\n * `setActive` on `(focus)` and prefer `active()` in their tabindex\n * computed so the host's single tab stop follows the last focused item\n * (APG re-entry), exactly like Tabs / Tree. Before any focus `active()`\n * is `null` and the item falls back to {@link isFirstFocusableItem}.\n */\n readonly roving: RovingTabindex;\n\n /**\n * Predicate for the per-item `tabindex` host binding. Returns `true`\n * for the single item that should currently carry `tabindex=0`\n * (the host's \"entry point\"); every other registered item is `-1`.\n * Only consulted before the roving tracker has an active item.\n */\n isFirstFocusableItem(el: HTMLElement): boolean;\n\n /**\n * Move focus from `currentItem` to the next item in registration order\n * matching `action`, respecting the host's `loop` policy and skipping\n * disabled handles.\n */\n navigate(currentItem: HTMLElement, action: ListNavigationAction): void;\n\n registerItem(handle: HostRovingItemHandle): void;\n unregisterItem(handle: HostRovingItemHandle): void;\n}\n\n/**\n * Injection token for `HostRovingContext`. Internal to the library — must\n * NOT be re-exported from `public-api.ts`. Containers that implement the\n * contract provide it via `useExisting` alongside their own primitive\n * context token.\n */\nexport const FOR_HOST_ROVING_CONTEXT = new InjectionToken<HostRovingContext>(\n 'FOR_HOST_ROVING_CONTEXT',\n);\n","import { afterEveryRender, DestroyRef, DOCUMENT, ElementRef, inject } from '@angular/core';\n\nimport { resolveActiveElement } from '../composed-tree/composed-tree';\n\n/**\n * The owner of a roving group's tab stop, read by {@link injectRovingFocusRestore}:\n * a `RovingTabindex` built with `fallback: 'nearest'`, or the selection-driven\n * owner of a group that builds no tracker.\n */\nexport interface RovingFocusTarget {\n /** The element that owns the group's tab stop, or `null` when none does. */\n readonly active: () => HTMLElement | null;\n /** Receives the element holding DOM focus inside the group, or `null` once focus left it. */\n readonly noteFocus?: (el: Element | null) => void;\n}\n\n/** Options for {@link injectRovingFocusRestore}. */\nexport interface RovingFocusRestoreOptions {\n /** Whether the departure of `departed`, which held focus, moves no focus. */\n readonly skip?: (departed: Element) => boolean;\n}\n\n/**\n * Keeps DOM focus inside a roving group whose focused element leaves it. When a\n * render detaches the element that held DOM focus inside the group's host while\n * focus has fallen to `<body>`, focus moves to the host the tracker re-seeded to.\n * An element that did not hold focus when it left moves nothing, whatever the\n * tracker's pointer says, and focus anywhere else is left alone, so a consumer\n * control that removed or collapsed the item keeps it, and so does a targeted\n * focus move another render hook makes in the same render (a keyboard drop\n * focusing the moved node). It also reports the element holding focus inside\n * the group to the target's `noteFocus`, which a tracker reads to yield the tab\n * stop while a disabled item holds focus.\n *\n * Pair it with a tracker built with `fallback: 'nearest'`, so the new owner is\n * the item beside the one that left rather than the first in the group, or, for\n * a group whose tab stop follows its selection and builds no tracker, with the\n * owner that selection resolves. Call it in the injection context of the\n * group's host directive; it moves no focus during a server render.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\nexport function injectRovingFocusRestore(\n roving: RovingFocusTarget,\n options: RovingFocusRestoreOptions = {},\n): void {\n const document = inject(DOCUMENT);\n const root = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n let held: Element | null = null;\n\n const onFocusIn = (event: FocusEvent): void => {\n held = event.target instanceof Element ? event.target : null;\n roving.noteFocus?.(held);\n };\n const onFocusOut = (event: FocusEvent): void => {\n roving.noteFocus?.(null);\n const target = event.target;\n queueMicrotask(() => {\n if (held !== null && held === target && held.isConnected) {\n held = null;\n }\n });\n };\n const controller = new AbortController();\n root.addEventListener('focusin', onFocusIn, { signal: controller.signal });\n root.addEventListener('focusout', onFocusOut, { signal: controller.signal });\n inject(DestroyRef).onDestroy(() => controller.abort());\n\n afterEveryRender(() => {\n const departed = held;\n if (departed === null || departed.isConnected) {\n return;\n }\n held = null;\n if (options.skip?.(departed) === true) {\n return;\n }\n const active = roving.active();\n if (active === null) {\n return;\n }\n queueMicrotask(() => {\n const focused = resolveActiveElement(document);\n const lost =\n focused === null || focused === document.body || focused === document.documentElement;\n if (lost && active.isConnected && roving.active() === active) {\n active.focus();\n }\n });\n });\n}\n","import type { CollectionHandle } from '../collection/collection';\nimport {\n type ListNavigationAction,\n type ListNavigationOptions,\n moveIndex,\n resolveListNavigation,\n} from '../keyboard-navigation/keyboard-navigation';\nimport type { RovingTabindex } from './roving-tabindex';\n\n/** Options for {@link rovingListTarget}. */\nexport interface RovingListTargetOptions {\n /** Wrap around at the ends. Default `false`. */\n loop?: boolean;\n}\n\n/**\n * Resolves the handle a 1D list-navigation action lands on **without skipping\n * disabled items** — the disabled-inclusive twin of `nextEnabledHandle`. Used\n * by roving primitives that keep disabled items keyboard-reachable per the\n * WAI-ARIA APG (a disabled control stays focusable so assistive tech announces\n * it; activation is guarded separately by the caller).\n *\n * `current` may be the currently focused host element or an explicit index.\n * When a host is passed it is located via its `host` property; a host not\n * present in `items` is treated as index `0`. When an index is passed it is\n * used verbatim (no clamp).\n *\n * Returns the resolved handle, or `null` when the list is empty or no target\n * exists in the requested direction (e.g. `loop=false` past the end).\n */\nexport function rovingListTarget<H extends CollectionHandle>(\n items: readonly H[],\n current: HTMLElement | number,\n action: ListNavigationAction,\n options: RovingListTargetOptions = {},\n): H | null {\n if (items.length === 0) {\n return null;\n }\n let currentIndex: number;\n if (typeof current === 'number') {\n currentIndex = current;\n } else {\n const found = items.findIndex((item) => item.host === current);\n currentIndex = found < 0 ? 0 : found;\n }\n const next = moveIndex(currentIndex, items.length, action, { loop: options.loop ?? false });\n return next === null ? null : (items[next] ?? null);\n}\n\n/** Options for {@link selectionTabStop}. */\nexport interface SelectionTabStopOptions {\n /**\n * Whether this item is disabled. A disabled item never owns the Tab stop,\n * so it always resolves to `-1` (while staying arrow-reachable via\n * {@link rovingListTarget}).\n */\n disabled: boolean;\n /** Whether this item is the selected / current one. */\n selected: boolean;\n /** Whether some enabled item in the group is selected / current. */\n hasSelected: boolean;\n /** Whether this item is the first enabled entry-point fallback. */\n isFirstEnabled: boolean;\n /**\n * Whether every item of the group yields the Tab stop because a disabled item\n * holds DOM focus, so `Tab` leaves the group from it. Default `false`.\n */\n yields?: boolean;\n}\n\n/** Options for {@link rovingTabStop}. */\nexport interface RovingTabStopOptions extends SelectionTabStopOptions {\n /** The group's roving tracker. */\n roving: RovingTabindex;\n /** This item's host element (queried against the roving tracker). */\n host: HTMLElement;\n}\n\n/**\n * Computes the **selection-driven** half of the tab-stop ladder — the rungs a\n * group owns when its single Tab entry point is defined by its selection rather\n * than by which item the user last focused. Returns `0` (Tab entry point) or\n * `-1` (arrow-reachable only):\n *\n * - disabled, or the group yields to a focused disabled item → `-1`.\n * - selected / current → `0`.\n * - another item owns the current selection → `-1`.\n * - otherwise the first enabled item → `0`, else `-1`.\n *\n * The third rung is what keeps a selection pointing at a disabled or absent item from taking the\n * whole group out of the tab order.\n *\n * `[forRadio]` is the one caller that uses this alone. Selection follows focus\n * in the WAI-ARIA Radio Group pattern, so a radio group has no user-driven\n * roving pointer to consult — see {@link rovingTabStop} for the groups that do.\n */\nexport function selectionTabStop(options: SelectionTabStopOptions): 0 | -1 {\n const { disabled, selected, hasSelected, isFirstEnabled, yields } = options;\n if (disabled || yields === true) {\n return -1;\n }\n if (selected) {\n return 0;\n }\n if (hasSelected) {\n return -1;\n }\n return isFirstEnabled ? 0 : -1;\n}\n\n/**\n * Computes the roving-tabindex ladder shared by every roving list primitive:\n * {@link selectionTabStop}'s rungs with the user-driven roving pointer taking\n * precedence over them once any item has been focused.\n *\n * - disabled → `-1` (never the Tab entry point, but still arrow-reachable).\n * - the roving tracker owns the tab stop → `roving.tabindexFor(host)`.\n * - otherwise the selection rungs of {@link selectionTabStop}.\n */\nexport function rovingTabStop(options: RovingTabStopOptions): 0 | -1 {\n const { roving, host, ...selection } = options;\n if (selection.disabled) {\n return -1;\n }\n if (roving.hasActive()) {\n return roving.tabindexFor(host);\n }\n return selectionTabStop(selection);\n}\n\n/** Options for {@link navigateFromRovingItem}. */\nexport interface RovingItemNavigationOptions extends ListNavigationOptions {\n /**\n * Whether the whole group is disabled, which leaves every navigation key\n * unconsumed. The item's own disabled state is deliberately not an option.\n */\n groupDisabled: boolean;\n /** Moves focus from the item for the resolved action. */\n navigate: (action: ListNavigationAction) => void;\n}\n\n/**\n * Handles the list-navigation keys (arrows, `Home` / `End`, and `PageUp` /\n * `PageDown` when `pageKeys` is set) on a roving item: consumes the key and\n * hands the action to `navigate`. Returns whether the key was handled.\n *\n * Gated on the group only. A disabled item keeps focus, so an item that becomes\n * disabled while it holds focus must still let the keyboard user leave it;\n * every caller guards its own activation keys separately.\n */\nexport function navigateFromRovingItem(\n event: KeyboardEvent,\n options: RovingItemNavigationOptions,\n): boolean {\n if (options.groupDisabled) {\n return false;\n }\n const action = resolveListNavigation(event, options);\n if (action === null) {\n return false;\n }\n event.preventDefault();\n options.navigate(action);\n return true;\n}\n\n/** Options for {@link handleDisabledRovingItemKey}. */\nexport interface DisabledRovingItemKeyOptions extends RovingItemNavigationOptions {\n /**\n * Moves focus for a key no navigation action claimed, by typeahead or by an\n * item-specific move. Returns whether the key was handled.\n */\n typeahead: (event: KeyboardEvent) => boolean;\n}\n\n/**\n * Handles a key on an item that is disabled while it holds focus: the\n * list-navigation keys of {@link navigateFromRovingItem}, then `typeahead`.\n * Activation and commit keys are left unconsumed, so the caller handles\n * nothing else from a disabled item. Gated on the group only. Returns whether\n * the key was handled.\n */\nexport function handleDisabledRovingItemKey(\n event: KeyboardEvent,\n options: DisabledRovingItemKeyOptions,\n): boolean {\n if (navigateFromRovingItem(event, options)) {\n return true;\n }\n if (options.groupDisabled) {\n return false;\n }\n return options.typeahead(event);\n}\n","import { signal, type Signal } from '@angular/core';\n\nimport { nextEnabledHandle } from '../collection/enabled-handle-navigation';\nimport { appendMissing, isInArray, membership, toggleInArray } from './selection';\nimport { isUnset, type Unset } from '../unset-input/unset-input';\n\n/**\n * Minimal option-handle shape the range-selection algorithm needs: a host\n * element to focus, the option's `value` signal, and a `disabled` signal to\n * skip. Both `ForListboxOptionHandle` and `ForSelectOptionHandle` widen this\n * with their own per-option fields (id, label, posInSet, …).\n *\n * @typeParam T Option value type.\n */\nexport interface RangeSelectionOptionHandle<T> {\n readonly host: HTMLElement;\n readonly value: Signal<T | Unset>;\n readonly disabled: Signal<boolean>;\n}\n\n/**\n * Construction-time wiring for {@link RangeSelectionEngine}. Plain signals and\n * a value setter only — the engine never imports a primitive's context token,\n * mirroring the `ListboxOverlayController` precedent, so it stays orthogonal to\n * each root's surface.\n *\n * @typeParam T Option value type.\n * @typeParam H Primitive option-handle type.\n */\nexport interface RangeSelectionEngineDeps<T, H extends RangeSelectionOptionHandle<T>> {\n /** All registered options, in DOM (rendered) order. */\n readonly options: Signal<readonly H[]>;\n /** The control's current selection. */\n readonly value: Signal<readonly T[]>;\n /** Commit a new selection array. */\n readonly setValue: (value: readonly T[]) => void;\n /** Compare two items for equality (`===` for primitives, custom for objects). */\n readonly compareWith: Signal<(a: T, b: T) => boolean>;\n /** Whether multiple options can be selected. Range actions are no-ops in single mode. */\n readonly multiple: Signal<boolean>;\n /** The control's effective disabled — gates every action. */\n readonly effectiveDisabled: Signal<boolean>;\n /** Whether the control is read-only — focus still moves, selection mutation is blocked. */\n readonly readonly: Signal<boolean>;\n readonly reveal: (host: HTMLElement) => void;\n}\n\n/**\n * The APG multi-select range-selection state machine shared by `ForListbox` and\n * `ForSelect`. Owns the range anchor and implements the range keyboard actions\n * (Shift+Arrow, Shift+Space, Ctrl/Cmd+A, Ctrl+Shift+Home/End) plus the\n * single-mode idempotent select guard — the blocks both roots used to duplicate\n * verbatim. The option source and value model differ between the two roots, so\n * they are threaded in through {@link RangeSelectionEngineDeps}.\n *\n * Every action skips an option seeded with the `unsetInput` sentinel: its\n * `[value]` binding has not been written yet, so there is no value to select and\n * handing the sentinel to `compareWith` would leak it to the consumer.\n *\n * Internal — lives in `forty-cdk/core`, consumed only by the primitives that\n * compose it; carries no semver guarantees.\n *\n * @typeParam T Option value type.\n * @typeParam H Primitive option-handle type.\n */\nexport class RangeSelectionEngine<T, H extends RangeSelectionOptionHandle<T>> {\n readonly #deps: RangeSelectionEngineDeps<T, H>;\n\n /**\n * Anchor value for APG range-selection actions (Shift+Space). Stored as the\n * option's *value* (resolved to its current index at range time via\n * `compareWith`) rather than a DOM index, so reordering or removing\n * options before the anchor can't silently shift the range to the wrong span.\n */\n readonly #anchorValue = signal<T | null>(null);\n\n constructor(deps: RangeSelectionEngineDeps<T, H>) {\n this.#deps = deps;\n }\n\n /**\n * Set the range anchor. Both roots call this on every unmodified activation\n * (click / Space / Enter); it is not touched by Shift+Arrow, which APG defines\n * as a per-option toggle.\n */\n setAnchor(value: T): void {\n this.#anchorValue.set(value);\n }\n\n /**\n * Single-mode idempotent select: replace the selection with `[value]`, but\n * skip the redundant set (and its `valueChange` emission) when the same sole\n * value is already selected. No disabled / readonly guard — the caller applies\n * it before delegating.\n */\n selectSingle(value: T | Unset): void {\n if (isUnset(value)) {\n return;\n }\n const current = this.#deps.value();\n if (current.length === 1 && isInArray(current, value, this.#deps.compareWith())) {\n return;\n }\n this.#deps.setValue([value]);\n }\n\n /**\n * APG \"Shift+ArrowDown / Shift+ArrowUp\": move focus to the next / previous\n * enabled option and toggle its selected state, without moving the range\n * anchor. Non-wrapping. No-op in single mode or when disabled. Focus still\n * moves under `readonly`; only the selection mutation is blocked. Focus also\n * still moves onto an option whose `[value]` binding has not landed yet; only\n * its selection is skipped, since the value is not knowable.\n */\n extendByArrow(currentOption: HTMLElement, action: 'next' | 'prev'): void {\n if (this.#deps.effectiveDisabled() || !this.#deps.multiple()) {\n return;\n }\n const target = nextEnabledHandle(this.#deps.options(), currentOption, action, { loop: false });\n if (target === null) {\n return;\n }\n this.#deps.reveal(target.host);\n if (this.#deps.readonly()) {\n return;\n }\n const targetValue = target.value();\n if (isUnset(targetValue)) {\n return;\n }\n this.#deps.setValue(toggleInArray(this.#deps.value(), targetValue, this.#deps.compareWith()));\n }\n\n /**\n * APG \"Shift+Space\": select every enabled option from the anchor (set on the\n * most recent unmodified activation) up to and including `currentOption`,\n * preserving any selection outside the span. Falls back to selecting just the\n * focused option when no anchor exists. No-op in single mode, disabled, or\n * readonly.\n */\n selectRangeToFocused(currentOption: HTMLElement): void {\n if (this.#deps.effectiveDisabled() || this.#deps.readonly() || !this.#deps.multiple()) {\n return;\n }\n const options = this.#deps.options();\n const currentIndex = options.findIndex((o) => o.host === currentOption);\n if (currentIndex < 0) {\n return;\n }\n const anchorValue = this.#anchorValue();\n const equals = this.#deps.compareWith();\n const anchorIndex =\n anchorValue === null\n ? -1\n : options.findIndex((o) => {\n const v = o.value();\n return !isUnset(v) && equals(v, anchorValue);\n });\n const start = anchorIndex < 0 ? currentIndex : anchorIndex;\n const [lo, hi] = start <= currentIndex ? [start, currentIndex] : [currentIndex, start];\n\n const span: T[] = [];\n for (let i = lo; i <= hi; i++) {\n const opt = options[i];\n if (!opt || opt.disabled()) {\n continue;\n }\n const v = opt.value();\n if (!isUnset(v)) {\n span.push(v);\n }\n }\n this.#deps.setValue(appendMissing(this.#deps.value(), span, equals));\n }\n\n /**\n * APG \"Ctrl/Cmd+A\": add every enabled option to the selection, or remove them\n * when they are all already selected (toggle). Selected values that are not an\n * enabled rendered option (a disabled option, one hidden by a filter) are kept\n * either way. An option whose `[value]` binding has not landed yet is left\n * out. No-op in single mode, disabled, or readonly.\n */\n selectAll(): void {\n if (this.#deps.effectiveDisabled() || this.#deps.readonly() || !this.#deps.multiple()) {\n return;\n }\n const enabled: T[] = [];\n for (const opt of this.#deps.options()) {\n if (opt.disabled()) {\n continue;\n }\n const v = opt.value();\n if (isUnset(v)) {\n continue;\n }\n enabled.push(v);\n }\n if (enabled.length === 0) {\n return;\n }\n const equals = this.#deps.compareWith();\n const current = this.#deps.value();\n if (enabled.every(membership(current, equals))) {\n const isEnabled = membership(enabled, equals);\n this.#deps.setValue(current.filter((x) => !isEnabled(x)));\n return;\n }\n this.#deps.setValue(appendMissing(current, enabled, equals));\n }\n\n /**\n * APG \"Ctrl+Shift+Home / Ctrl+Shift+End\": select every enabled option from\n * `currentOption` (inclusive) to the first / last enabled option, and move\n * focus to that edge, preserving any selection outside the span. No-op in\n * single mode or when disabled. Focus still moves under `readonly`; only the\n * selection mutation is blocked.\n */\n selectFromCurrentToEdge(currentOption: HTMLElement, edge: 'first' | 'last'): void {\n if (this.#deps.effectiveDisabled() || !this.#deps.multiple()) {\n return;\n }\n const options = this.#deps.options();\n const currentIndex = options.findIndex((o) => o.host === currentOption);\n if (currentIndex < 0) {\n return;\n }\n const [lo, hi] = edge === 'first' ? [0, currentIndex] : [currentIndex, options.length - 1];\n\n const span: T[] = [];\n let firstEnabled: HTMLElement | null = null;\n let lastEnabled: HTMLElement | null = null;\n for (let i = lo; i <= hi; i++) {\n const opt = options[i];\n if (!opt || opt.disabled()) {\n continue;\n }\n const v = opt.value();\n if (!isUnset(v)) {\n span.push(v);\n }\n if (firstEnabled === null) {\n firstEnabled = opt.host;\n }\n lastEnabled = opt.host;\n }\n const edgeFocusTarget = edge === 'first' ? firstEnabled : lastEnabled;\n if (edgeFocusTarget !== null) {\n this.#deps.reveal(edgeFocusTarget);\n }\n if (this.#deps.readonly()) {\n return;\n }\n this.#deps.setValue(appendMissing(this.#deps.value(), span, this.#deps.compareWith()));\n }\n}\n","/**\n * Pointer-based swipe-to-dismiss helper.\n *\n * Used by `ForToast`, `ForDrawer` (via its drag engine), and `ForCarousel`\n * (via its drag directive): a horizontal / vertical drag that, released past\n * the configured threshold, triggers a dismissal.\n *\n * The helper keeps no Angular DI surface — it's a plain function that attaches\n * listeners to an `HTMLElement` and returns a cleanup function. Callers wire it\n * through the directive's `DestroyRef`.\n *\n * It is a thin **domain layer over `createPointerDragSession`**: the session\n * owns the transport (the host `pointerdown` capture, the document-level\n * `pointermove` / `pointerup` / `pointercancel` capture listeners, the\n * `pointerId` filter, pointer capture, and the post-drag click suppression),\n * while this helper owns the swipe semantics on top of it — dominant-axis\n * direction detection, the constrained delta, the release-threshold split, and\n * the reactive mid-gesture directions abort.\n *\n * Behavior summary:\n * - The start position is recorded on `pointerdown` but no swipe is announced\n * yet, so a plain tap fires nothing. A press with no allowed direction, and a\n * non-primary mouse button, are rejected before tracking begins.\n * - Once the drag travels past an internal arm distance the dominant axis picks\n * the candidate direction; if it is not in the allowed set the press keeps\n * watching — it stays tracked and unarmed, re-checking the dominant axis on\n * every further move — instead of arming. A mouse move seen with no button held\n * is a press released off-element (no `pointerup` reached it) and does not arm a\n * phantom swipe.\n * - On arming, `onSwipeStart` fires (with the constrained delta) and\n * `onSwipeMove` fires for every move including the arming one. `getDirections()`\n * is re-read on every armed move: if the active direction is toggled out of the\n * allowed set mid-gesture the swipe aborts (`onSwipeCancel` fires).\n * - On `pointerup`, if the projection along the active direction reaches\n * `getThreshold()`, `onSwipeEnd` fires; otherwise `onSwipeCancel` fires.\n * - On `pointercancel`, `onSwipeCancel` fires when the gesture had armed.\n *\n * Movement perpendicular to the active direction is clamped to `0`, and movement\n * opposite to the direction is clamped to `0` as well — the consumer's CSS only\n * ever sees a non-negative push along the dismissal axis, so animations stay\n * simple.\n */\n\nimport { resolveEventTarget } from '../composed-tree/composed-tree';\nimport { createPointerDragSession, type PointerDragSession } from '../drag-session/pointer-session';\nimport {\n type DragAxes,\n dragSurfaceTouchAction,\n type DragTouchAction,\n} from '../drag-session/drag-touch-action';\n\n/** A single swipe direction, named after the pointer-travel direction. */\nexport type SwipeDirection = 'left' | 'right' | 'up' | 'down';\n\nexport interface SwipeEventDetail {\n /** The active direction picked by the dominant-axis check. */\n readonly direction: SwipeDirection;\n /**\n * Movement vector relative to the swipe start, in CSS pixels.\n * Constrained: the perpendicular axis is always `0`, and the\n * primary axis is clamped to the half-line that points along\n * `direction` (e.g. `right` → `x >= 0`, `up` → `y <= 0`).\n */\n readonly delta: { readonly x: number; readonly y: number };\n /**\n * The element the press landed on, resolved through open shadow roots.\n * Answer \"where did this gesture start?\" with it rather than with\n * `originalEvent.target`, which belongs to the current move and may have\n * been retargeted to a shadow host.\n */\n readonly target: Element | null;\n /** The originating pointer event. */\n readonly originalEvent: PointerEvent;\n}\n\nexport interface SwipeDismissOptions {\n /** Element listening for pointer events. */\n readonly element: HTMLElement;\n /**\n * Reactive getter for the allowed swipe directions. Returning an\n * empty array disables swipe entirely (a dynamically-toggled\n * direction is the canonical \"off switch\").\n */\n readonly getDirections: () => readonly SwipeDirection[];\n /** Reactive getter for the dismiss threshold in CSS pixels. */\n readonly getThreshold: () => number;\n /**\n * Pre-arm predicate consulted once per gesture, after the dominant-axis\n * direction has been picked but before the session arms or captures the\n * pointer. Return `false` to decline this gesture: the underlying pointer\n * session is aborted, so the pointer is never captured and no post-release\n * click trap is installed, leaving native text selection / inner scrolling\n * intact for the rest of the press. Omit it to always begin.\n */\n readonly canBegin?: (detail: SwipeEventDetail) => boolean;\n readonly onSwipeStart?: (detail: SwipeEventDetail) => void;\n readonly onSwipeMove?: (detail: SwipeEventDetail) => void;\n /** Pointer-up while projection along direction `>= threshold`. */\n readonly onSwipeEnd?: (detail: SwipeEventDetail) => void;\n /** Pointer-up before threshold, or pointer-cancel. */\n readonly onSwipeCancel?: (detail: SwipeEventDetail) => void;\n}\n\nconst ARM_DISTANCE_PX = 4;\n\nfunction detectDirection(\n dx: number,\n dy: number,\n allowed: readonly SwipeDirection[],\n): SwipeDirection | null {\n const ax = Math.abs(dx);\n const ay = Math.abs(dy);\n if (ax < ARM_DISTANCE_PX && ay < ARM_DISTANCE_PX) {\n return null;\n }\n const candidate: SwipeDirection =\n ax >= ay ? (dx >= 0 ? 'right' : 'left') : dy >= 0 ? 'down' : 'up';\n return allowed.includes(candidate) ? candidate : null;\n}\n\nfunction projection(dx: number, dy: number, dir: SwipeDirection): number {\n switch (dir) {\n case 'right':\n return dx;\n case 'left':\n return -dx;\n case 'down':\n return dy;\n case 'up':\n return -dy;\n }\n}\n\nfunction constrainedDelta(dx: number, dy: number, dir: SwipeDirection): { x: number; y: number } {\n switch (dir) {\n case 'right':\n return { x: Math.max(0, dx), y: 0 };\n case 'left':\n return { x: Math.min(0, dx), y: 0 };\n case 'down':\n return { x: 0, y: Math.max(0, dy) };\n case 'up':\n return { x: 0, y: Math.min(0, dy) };\n }\n}\n\nfunction elementOf(node: Node | null): Element | null {\n return node === null || node instanceof Element ? node : node.parentElement;\n}\n\n/**\n * Cutoff (ms) past which a flick's last velocity sample is considered stale.\n * A release whose last `pointermove` sample is older than this — a fast final\n * move followed by a hold-still before lifting — must not carry the stale\n * sample into the release decision. Consumed by {@link flickVelocity}.\n */\nexport const FLICK_STALE_VELOCITY_MS = 100;\n\n/**\n * Release speed (CSS px/ms) past which a gesture counts as a deliberate flick\n * rather than a slow position drag. A release at or above it resolves toward\n * the flick direction from where the gesture was let go, instead of to the\n * nearest target.\n *\n * Shared by every swipe-driven resolution in the library — `ForCarousel`'s\n * drag directive (`resolveDragIndex`), `ForDrawer`'s no-snap-points dismiss\n * check, and `resolveSnapTarget`'s velocity bias — so the \"intentional flick\"\n * semantics stay identical across the library.\n */\nexport const FLICK_VELOCITY_PX_PER_MS = 0.4;\n\n/**\n * Zeroes the flick velocity when the release is stale — its last `pointermove`\n * sample is older than {@link FLICK_STALE_VELOCITY_MS} — so a fast final move\n * followed by a hold-still before lifting can't carry the stale sample into the\n * release decision. Returns the effective velocity the caller feeds into its\n * snap / dismiss resolution.\n *\n * Shared by the swipe-driven primitives (`ForDrawer`'s drag engine and\n * `ForCarousel`'s drag directive) so the staleness rule stays identical across\n * the library.\n */\nexport function flickVelocity(rawVelocity: number, stale: boolean): number {\n return stale ? 0 : rawVelocity;\n}\n\n/**\n * The `touch-action` a surface swiping in `directions` needs: the browser keeps\n * the axis no direction uses (`pan-y` for `left` / `right`, `pan-x` for `up` /\n * `down`, `none` once both axes swipe), so a finger moving along a swipe axis\n * reaches the pointer handlers instead of being claimed as a pan, which would\n * end the gesture with `pointercancel`. An axis the surface itself scrolls on\n * (`hostScrolls`, as `injectHostScrollAxes` measures it) stays with the browser\n * too, so a scrollable surface keeps its own touch scrolling. `null` when\n * there is no direction, so an idle surface leaves the browser's default in\n * place.\n */\nexport function swipeTouchAction(\n directions: readonly SwipeDirection[],\n hostScrolls: DragAxes,\n): DragTouchAction {\n return dragSurfaceTouchAction({\n armable: directions.length > 0,\n handles: false,\n axes: {\n x: directions.some((d) => d === 'left' || d === 'right'),\n y: directions.some((d) => d === 'up' || d === 'down'),\n },\n hostScrolls,\n });\n}\n\n/**\n * Attach swipe-dismiss listeners to `opts.element`. Returns a cleanup\n * function that tears down the underlying pointer-drag session (every\n * listener and any pending click trap).\n */\nexport function attachSwipeDismiss(opts: SwipeDismissOptions): () => void {\n const el = opts.element;\n let startX = 0;\n let startY = 0;\n let pressTarget: Element | null = null;\n let direction: SwipeDirection | null = null;\n\n const detailFor = (event: PointerEvent, dir: SwipeDirection): SwipeEventDetail => ({\n direction: dir,\n delta: constrainedDelta(event.clientX - startX, event.clientY - startY, dir),\n target: pressTarget,\n originalEvent: event,\n });\n\n const session: PointerDragSession = createPointerDragSession({\n host: el,\n document: el.ownerDocument,\n armThreshold: ARM_DISTANCE_PX,\n capturePointer: true,\n canStart: (event) => {\n if (event.pointerType === 'mouse' && event.button !== 0) {\n return false;\n }\n if (opts.getDirections().length === 0) {\n return false;\n }\n startX = event.clientX;\n startY = event.clientY;\n pressTarget = elementOf(resolveEventTarget(event));\n direction = null;\n return true;\n },\n onLift: (event) => {\n if (event.pointerType === 'mouse' && event.buttons === 0) {\n return false;\n }\n const dir = detectDirection(\n event.clientX - startX,\n event.clientY - startY,\n opts.getDirections(),\n );\n if (!dir) {\n return 'skip';\n }\n const detail = detailFor(event, dir);\n if (opts.canBegin && !opts.canBegin(detail)) {\n return false;\n }\n direction = dir;\n opts.onSwipeStart?.(detail);\n return true;\n },\n onMove: (event) => {\n if (!direction) {\n return;\n }\n if (!opts.getDirections().includes(direction)) {\n session.cancel(event);\n return;\n }\n opts.onSwipeMove?.(detailFor(event, direction));\n },\n onCommit: (event) => {\n if (!direction) {\n return;\n }\n const dir = direction;\n direction = null;\n const proj = projection(event.clientX - startX, event.clientY - startY, dir);\n if (proj >= opts.getThreshold()) {\n opts.onSwipeEnd?.(detailFor(event, dir));\n } else {\n opts.onSwipeCancel?.(detailFor(event, dir));\n }\n },\n onCancel: (event) => {\n if (direction && event) {\n opts.onSwipeCancel?.(detailFor(event, direction));\n }\n direction = null;\n },\n });\n\n return () => session.destroy();\n}\n","import { computed, type Signal } from '@angular/core';\n\nimport { injectPrefersReducedMotion } from '../media-query/media-query';\n\n/**\n * The reduced-motion policy shared by every surface built on\n * `attachSwipeDismiss`. Under `prefers-reduced-motion: reduce` the gesture\n * stays armed, commits on release (snap, dismiss, advance) and fires its swipe\n * outputs, but the surface publishes no movement that follows the finger: every\n * value routed through {@link SwipeMotion.follow} reads `0`.\n */\nexport interface SwipeMotion {\n /** `false` while the user asks for reduced motion. */\n readonly enabled: Signal<boolean>;\n /**\n * The value a surface publishes for a live, finger-following quantity (a\n * displacement in px, a progress fraction): `value` while motion is enabled,\n * `0` under reduced motion. Reads {@link enabled}, so a `computed` or host\n * binding calling it follows a runtime change of the preference.\n */\n readonly follow: (value: number) => number;\n}\n\n/**\n * Resolve the {@link SwipeMotion} policy for a swipe surface. Must be called\n * from an injection context. SSR-safe: the server reads motion as enabled.\n */\nexport function injectSwipeMotion(): SwipeMotion {\n const reducedMotion = injectPrefersReducedMotion();\n const enabled = computed(() => !reducedMotion());\n return { enabled, follow: (value) => (enabled() ? value : 0) };\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport { DestroyRef, ElementRef, PLATFORM_ID, inject, type Signal } from '@angular/core';\n\n/** Configuration for {@link injectDisabledClickGuard}. */\nexport interface DisabledClickGuardConfig {\n /** While truthy, a click on the host or on any of its descendants is cancelled. */\n disabled: Signal<boolean>;\n\n /**\n * Also cancel a middle-button `auxclick` while disabled, so a disabled link\n * cannot be opened in a new tab. Other buttons' `auxclick` pass through.\n */\n middleClick?: boolean;\n}\n\n/**\n * Cancels every click on a disabled host that stays focusable, which is why it\n * carries `aria-disabled` rather than the native `disabled` attribute.\n *\n * While `disabled()` is true, a capture-phase listener on the host calls\n * `preventDefault()` and `stopImmediatePropagation()` on each `click` (and, with\n * `middleClick`, each middle-button `auxclick`). Capture on the host runs before\n * every bubble-phase listener on the host and its descendants, so no `(click)`\n * binding on the element runs, whether a directive's host listener or the\n * consumer's template, and neither does any listener on an ancestor.\n *\n * Inert on the server. Must be called from an injection context.\n */\nexport function injectDisabledClickGuard(config: DisabledClickGuardConfig): void {\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n return;\n }\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const controller = new AbortController();\n const options = { capture: true, signal: controller.signal };\n\n const cancel = (event: MouseEvent): void => {\n if (!config.disabled()) {\n return;\n }\n event.preventDefault();\n event.stopImmediatePropagation();\n };\n\n host.addEventListener('click', cancel, options);\n if (config.middleClick) {\n host.addEventListener(\n 'auxclick',\n (event: MouseEvent) => {\n if (event.button === 1) {\n cancel(event);\n }\n },\n options,\n );\n }\n\n inject(DestroyRef).onDestroy(() => controller.abort());\n}\n","import { ElementRef, inject, signal, type Signal } from '@angular/core';\n\n/** Configuration for {@link injectSyntheticActivation}. */\nexport interface SyntheticActivationConfig {\n /**\n * Reactive disabled state gating the synthesized activation. While truthy the\n * handlers never click the host, but `Space` keydown still calls\n * `preventDefault()` so a disabled control does not scroll the page — the\n * behavior a native `<button>` with `aria-disabled` has.\n */\n disabled?: Signal<boolean>;\n}\n\n/** Surface returned by {@link injectSyntheticActivation}. */\nexport interface SyntheticActivation {\n /**\n * Whether the host is a native `<button>`. The platform then owns activation\n * and tab order, so the synthesis is inert and the caller emits no `role` /\n * `tabindex` of its own.\n */\n readonly nativeButton: boolean;\n\n /**\n * `'0'` on a non-native host, so it is reachable with `Tab`; `null` on a\n * native `<button>`, whose tab stop the platform already owns. Host-bind it\n * as `'[attr.tabindex]': 'tabindex()'`. Disabled hosts keep their tab stop:\n * custom-role controls stay focusable per the APG.\n */\n readonly tabindex: Signal<string | null>;\n\n /** Wire to the host's `(keydown)`. */\n keydown(event: KeyboardEvent): void;\n\n /** Wire to the host's `(keyup)`. */\n keyup(event: KeyboardEvent): void;\n\n /**\n * Wire to the host's `(blur)` / `(focusout)`. Drops a half-finished `Space`\n * press so a `keyup` arriving after focus left cannot activate the control.\n */\n reset(): void;\n}\n\n/**\n * Gives a host that may not be a `<button>` the activation semantics of one:\n * a tab stop plus `Enter` / `Space` synthesis. The keyboard path funnels\n * through `host.click()`, so the caller keeps a single activation handler (its\n * `(click)` listener) regardless of which host element the consumer picked.\n *\n * `Enter` activates on `keydown`, `Space` on `keyup` — matching native button\n * and APG behavior. `Space` keydown always calls `preventDefault()` (even while\n * disabled) to stop the page scrolling, and a `Space` press is only honored\n * when its `keydown` reached the same host.\n *\n * On a native `<button>` every handler returns immediately and `tabindex` is\n * `null`: the platform already synthesizes click from `Enter` / `Space`, so\n * doing it again would double-activate.\n *\n * Callers own their `role`: `[forButton]` emits `role=\"button\"` on a non-native\n * host, while the form primitives (`[forCheckbox]`, `[forSwitch]`) already\n * carry a static `role=\"checkbox\"` / `\"switch\"` on every host.\n *\n * @example\n * ```ts\n * @Directive({\n * selector: '[myControl]',\n * host: {\n * '[attr.tabindex]': 'tabindex()',\n * '(click)': 'onClick()',\n * '(keydown)': 'onKeydown($event)',\n * '(keyup)': 'onKeyup($event)',\n * '(blur)': 'onBlur()',\n * },\n * })\n * export class MyControl {\n * readonly #activation = injectSyntheticActivation({ disabled: this.disabled });\n * protected readonly tabindex = this.#activation.tabindex;\n * }\n * ```\n */\nexport function injectSyntheticActivation(\n config: SyntheticActivationConfig = {},\n): SyntheticActivation {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const nativeButton = host.tagName === 'BUTTON';\n const isDisabled = (): boolean => config.disabled?.() ?? false;\n let spaceHeld = false;\n\n return {\n nativeButton,\n tabindex: signal(nativeButton ? null : '0').asReadonly(),\n keydown(event: KeyboardEvent): void {\n if (nativeButton) {\n return;\n }\n if (event.key === 'Enter') {\n if (isDisabled()) {\n return;\n }\n event.preventDefault();\n host.click();\n return;\n }\n if (event.key === ' ') {\n event.preventDefault();\n if (isDisabled()) {\n return;\n }\n spaceHeld = true;\n }\n },\n keyup(event: KeyboardEvent): void {\n if (nativeButton || event.key !== ' ' || !spaceHeld) {\n return;\n }\n spaceHeld = false;\n if (isDisabled()) {\n return;\n }\n event.preventDefault();\n host.click();\n },\n reset(): void {\n spaceHeld = false;\n },\n };\n}\n","import { InjectionToken, type Signal } from '@angular/core';\n\n/**\n * Handle a `ForTableCell` registers with its parent `ForTableRow`, so the row can\n * order its cells (for `aria-colindex`) and the root can flatten them into the\n * roving-navigation grid (skipping disabled cells).\n */\nexport interface ForTableCellHandle {\n /** The cell's host element (`role=\"cell\"` / `\"gridcell\"`). */\n readonly host: HTMLElement;\n /** Whether this cell is disabled — skipped during arrow-key navigation. */\n readonly disabled: Signal<boolean>;\n}\n\n/**\n * Handle a `ForTableRow` registers with the root `ForTable`, so the root can order\n * rows (for `aria-rowindex`) and build the row-major flat cell grid for navigation.\n */\nexport interface ForTableRowHandle {\n /** The row's host element (`role=\"row\"`). */\n readonly host: HTMLElement;\n /** This row's data cells, in DOM order. */\n readonly cells: Signal<readonly ForTableCellHandle[]>;\n /** This row's selection identity, from its `[value]` input; `undefined` when unset (not selectable). */\n readonly value: Signal<unknown>;\n /** 1-based tree depth of this row (`aria-level`); always `1` outside treegrid mode. */\n readonly level: Signal<number>;\n /** Whether this row is an expandable parent (drives `aria-expanded` / `data-state`). */\n readonly expandable: Signal<boolean>;\n /** Absolute 0-based index of this row in the full (virtualized) dataset, or `null` when not virtualized. */\n readonly virtualIndex: Signal<number | null>;\n}\n\n/**\n * A single row in a {@link TableVirtualWindow}: its absolute dataset index and\n * pixel offset from the start of the scroll range.\n */\nexport interface TableVirtualRow {\n /** Absolute 0-based index of this row in the full dataset. */\n readonly index: number;\n /** Pixel offset of this row from the start of the scroll range. */\n readonly start: number;\n}\n\n/**\n * A rendered virtual window published by `[forTableVirtualized]` for the\n * declarative `<for-table-body>` to render. It lets the body render only the\n * windowed rows — each absolutely positioned inside a full-height sizer —\n * instead of iterating the whole `rows` input, without `forty-cdk/table`\n * importing the virtualization core. Mirrors {@link TableVirtualRowNavigation}:\n * the virtualization companion owns the windowing math and publishes the result\n * through the shared registration surface.\n */\nexport interface TableVirtualWindow {\n /**\n * The rows to render this frame — the visible window plus overscan and the\n * retained focused / reordering rows, each carrying its absolute dataset\n * `index` and pixel `start`. `<for-table-body>` indexes its `rows` input by\n * `index` and positions each row at `translateY(start)`.\n */\n readonly rows: Signal<readonly TableVirtualRow[]>;\n /**\n * Total scroll height of the full dataset in px. Applied to the body's\n * rowgroup so the scrollbar spans the whole set while only the window mounts.\n */\n readonly totalSize: Signal<number>;\n /**\n * Record a stamped row element's real measured height, so the virtualizer\n * replaces the `estimateRowSize` estimate with it and re-aligns the offsets of\n * the rows below. Implemented by `[forTableVirtualized]`; `<for-table-body>`\n * calls it once per stamped row (browser-only, after render) when its\n * `measureRows` input is set, so a window mixing row shapes (denser variant\n * rows, group separators) stays contiguous after scroll. The element must\n * carry the `data-index` attribute a `[forTableRow]` reflects from its\n * `virtualIndex`.\n *\n * `<for-table-body>` also calls it with `null` after measuring the rendered\n * rows to sweep detached rows recycled out of the window, evicting them from\n * the virtualizer's measurement cache so they are not retained/observed until\n * the directive is destroyed.\n */\n measureRow(element: HTMLElement | null): void;\n}\n\n/**\n * Cross-window row-navigation delegate registered by `[forTableVirtualized]`.\n * `ForTable` consults it when a grid keyboard action resolves a row outside the\n * rendered window, keeping the virtualization bridge out of `ForTable` itself.\n */\nexport interface TableVirtualRowNavigation {\n /**\n * Move roving focus to the data cell at the absolute `(rowIndex, 0-based\n * column)`, scrolling that row into the window first when it is not mounted.\n * `direction` (`+1` down / `-1` up) is the travel sense of the originating\n * grid action, so the bridge can step over full-span variant rows — which\n * register no cells — onto the adjacent data row.\n */\n navigateTo(rowIndex: number, column: number, direction: 1 | -1): void;\n /**\n * Scroll the virtualizer so the row at the absolute `index` is in the window.\n * Used by `[forTableRowReorder]` to follow a keyboard reorder target across\n * the rendered window without taking a direct dependency on `ForTableVirtualized`.\n */\n scrollToRow(index: number): void;\n /**\n * Stop a {@link scrollToRow} that is still running. `[forTableRowReorder]` calls it when a\n * pointer drag lifts a row, so the scroll no longer moves the rows under the pointer.\n */\n cancelScroll(): void;\n /**\n * Whether the virtualizer's own window covers the row at the absolute `index`. A row kept\n * mounted only because it is focused or being reordered does not count, so\n * `[forTableRowReorder]` can wait for a scroll it requested to land before it releases a pin.\n */\n isRowInWindow(index: number): boolean;\n /**\n * The bounding rect of the scroll container along the visible viewport, or\n * `null` before it is available. `[forTableRowReorder]` reads it to map a\n * modifier-held pointer drag onto an absolute dataset index (windowed-scrub\n * drop to a far row), without depending on `ForTableVirtualized` directly.\n */\n scrollViewportRect(): DOMRect | null;\n /**\n * The count of rows the virtualizer can place — `[virtualRowCount]`, else the\n * table's resolved row count, else `0`. `ForTable` bounds row-crossing grid\n * actions by it, and `[forTableRowReorder]` its keyboard reorder and drag\n * announcements, rather than by the `aria-rowcount` total, which stays unknown\n * for a windowed grid whose server reports no total.\n */\n placeableRowCount(): number;\n /**\n * Drop any stashed cross-window target. `ForTable` calls this on the next\n * keyboard interaction that reaches the grid, so a pending move set by an\n * earlier Ctrl+End / Page / Arrow is superseded rather than teleporting focus\n * when a far page later mounts.\n */\n clearPending(): void;\n}\n\n/**\n * The table's piece-registration protocol: how header rows, header cells, data\n * rows, the declarative body's row count, the virtualization seams and the\n * resized column widths wire themselves into the `[forTable]` root.\n *\n * **Not** part of `ForTableContext`, and never re-exported from a\n * stable entry point. It lives in the core internal tier — exported from\n * `forty-cdk/core` with no semver guarantee — because\n * `forty-cdk/table-virtualization`'s `[forTableVirtualized]` registers through it from\n * a second entry point, and a consumer must not be able to name — let alone\n * call — the wiring protocol the library refactors freely.\n */\nexport interface TableRegistrationContext {\n /** Registers the header row's host so the root can measure its height for the sticky-header CSS var. */\n registerHeaderRow(el: HTMLElement): void;\n /** Unregisters the header row's host. Reference-based; safe to call if never registered. */\n unregisterHeaderRow(el: HTMLElement): void;\n /**\n * Registers a header cell so it can join the roving-navigation grid as the grid's\n * first row, giving the table a single composite tab stop shared with the data\n * cells. Draggable header cells (`[forTableColumnReorder]`) register the same way so\n * a column-reorderable grid stays a single tab stop. Inert in `mode=\"table\"`, where\n * header cells stay static structure and the row does not join any grid.\n */\n registerHeaderCell(handle: ForTableCellHandle): void;\n /** Unregisters a header cell. Reference-based. */\n unregisterHeaderCell(handle: ForTableCellHandle): void;\n /**\n * Moves roving focus onto the header cell in the 0-based `column`, answering `true`\n * when the header row took the move and `false` when it does not join the composite\n * roving grid (`mode=\"table\"`, no header row, or an incomplete one).\n *\n * It is the header crossing `ForTable` resolves through its own flat cell grid when no\n * virtualizer is involved: `[forTableVirtualized]` calls it when an upward cross-window\n * walk steps over the last full-span variant row above the dataset, since the row above\n * absolute index `0` is the grid's header row.\n */\n focusHeaderCell(column: number): boolean;\n /** Registers a data row so it joins the row index space and the navigation grid. */\n registerRow(handle: ForTableRowHandle): void;\n /** Unregisters a data row. Reference-based. */\n unregisterRow(handle: ForTableRowHandle): void;\n /**\n * Live registered data rows in DOM order. `[forTableVirtualized]` reads this to\n * resolve a pending cross-window navigation once the target row mounts, and\n * `[forTableRowReorder]` to map a pointer target back onto a row handle.\n */\n readonly rows: Signal<readonly ForTableRowHandle[]>;\n /**\n * Registers (or clears, with `null`) the declarative `<for-table-body>`'s dataset\n * length as the body-derived total row count. `ForTableBody` registers\n * `computed(() => rows().length)` at construction and clears it on destroy, so a\n * declarative table needs no `[rowCount]` binding; an explicit `[rowCount]` input\n * still wins over it (for a server-known total larger than the loaded rows).\n */\n registerBodyRowCount(count: Signal<number> | null): void;\n /**\n * Registers (or clears, with `null`) the cross-window row-navigation delegate.\n * `[forTableVirtualized]` registers itself so row-crossing grid keyboard actions\n * targeting an unmounted row are handled by the virtualization bridge.\n */\n registerVirtualNavigation(navigation: TableVirtualRowNavigation | null): void;\n /**\n * The currently registered cross-window row-navigation delegate, or `null`\n * when the table is not virtualized. `[forTableRowReorder]` reads this to gate\n * keyboard reordering to virtualized tables and to scroll the reorder target\n * into view, without taking a direct dependency on `ForTableVirtualized`.\n */\n readonly virtualRowNavigation: Signal<TableVirtualRowNavigation | null>;\n /**\n * Registers (or clears, with `null`) the rendered virtual window.\n * `[forTableVirtualized]` registers itself so the declarative\n * `<for-table-body>` renders only the windowed rows without importing the\n * virtualization core. No-op for tables built from the raw `[forTableRow]`\n * primitives, which render their own window.\n */\n registerVirtualWindow(window: TableVirtualWindow | null): void;\n /**\n * The currently registered virtual window, or `null` when the table is not\n * virtualized (or is built from the raw `[forTableRow]` primitives directly).\n * `<for-table-body>` reads this to switch between rendering the full `rows`\n * input and rendering only the window inside a full-height sizer.\n */\n readonly virtualWindow: Signal<TableVirtualWindow | null>;\n /**\n * Sets (or clears, with `null`) the absolute index of the row being\n * pointer-reordered. Called by `[forTableRowReorder]`; read by\n * `[forTableVirtualized]` to retain the lifted row in the rendered window.\n */\n setReorderingRow(index: number | null): void;\n /**\n * Absolute index of the row currently being pointer-reordered (set by\n * `[forTableRowReorder]` on lift, cleared on release), or `null` when no row is\n * being reordered. `[forTableVirtualized]` keeps this row mounted for the\n * duration of the drag so auto-scroll cannot unmount the lifted row and desync\n * the emitted drop indices. `null` and unused outside a virtualized table.\n */\n readonly reorderingRowIndex: Signal<number | null>;\n /**\n * Publishes a column's resolved width as the CSS custom property\n * `--for-table-col-<column>-width` on the table root, so the consumer's layout\n * can apply it. Called by `[forTableColumnResizer]`.\n */\n setColumnWidth(column: string, width: number): void;\n /**\n * Removes a column's published `--for-table-col-<column>-width` custom property\n * from the table root. Called by `[forTableColumnResizer]` when its width resets\n * to `undefined` or the handle is destroyed, so a stale track var cannot survive\n * a width reset or resurrect when the column is re-added.\n */\n removeColumnWidth(column: string): void;\n}\n\n/**\n * A row's cell-registration protocol: how `[forTableCell]` joins its\n * `[forTableRow]` so the row can order its cells for `aria-colindex` and the\n * root can flatten them into the roving grid.\n *\n * Lives here beside {@link TableRegistrationContext} rather than in\n * `forty-cdk/table`, so `ForTableCellHandle` never has to surface in the table\n * entry point's emitted types — the row's public read surface stays free of it.\n */\nexport interface TableRowRegistrationContext {\n /** Registers a data cell with this row. */\n registerCell(handle: ForTableCellHandle): void;\n /** Unregisters a data cell. Reference-based. */\n unregisterCell(handle: ForTableCellHandle): void;\n}\n\n/** DI token carrying a row's {@link TableRowRegistrationContext}. Provided by `[forTableRow]`. */\nexport const TABLE_ROW_REGISTRATION_CONTEXT = new InjectionToken<TableRowRegistrationContext>(\n 'TABLE_ROW_REGISTRATION_CONTEXT',\n);\n\n/** DI token carrying the table's {@link TableRegistrationContext}. Provided by `[forTable]`. */\nexport const TABLE_REGISTRATION_CONTEXT = new InjectionToken<TableRegistrationContext>(\n 'TABLE_REGISTRATION_CONTEXT',\n);\n","/** State of the typeahead buffer at the moment a match is resolved. */\nexport interface TypeaheadMatchQuery {\n /** The accumulated typeahead buffer. Matched case- and diacritics-insensitively. */\n readonly buffer: string;\n /**\n * Whether the buffer is a single character pressed repeatedly (`\"c\"`,\n * `\"cc\"`, …), per `Typeahead.isRepeatedChar()`. When `true` the match cycles\n * to the next same-initial option after `anchorIndex`; when `false` it\n * prefix-matches from `anchorIndex` inclusive (or the top when unanchored).\n */\n readonly repeated: boolean;\n /**\n * Index of the currently-anchored option (the focused / active one), or `-1`\n * when nothing is anchored. The cycle starts just after it; the prefix scan\n * starts at it (clamped to `0`).\n */\n readonly anchorIndex: number;\n}\n\n/**\n * Folds text to a case- and diacritics-insensitive form for typeahead\n * matching: decomposes accented characters (`NFD`), strips the combining\n * diacritical marks, and lowercases, so `\"e\"` matches `\"Évora\"`. Shared by\n * `findTypeaheadMatch` and Combobox's inline autocomplete, the one call site\n * that runs its own prefix matching, so every collection typeahead and\n * Combobox behave alike for accented text.\n *\n * @param text Raw text to fold (an option label or the typed buffer).\n */\nexport function foldTypeaheadText(text: string): string {\n return text\n .normalize('NFD')\n .replace(/\\p{Diacritic}/gu, '')\n .toLowerCase();\n}\n\n/**\n * The option-level typeahead match shared by Select and Listbox (DOM-focus and\n * virtualized paths). Scans `options` from the anchor, skipping disabled\n * options, and returns the first whose text starts with the query — matching\n * the WAI-ARIA APG typeahead behaviour:\n *\n * - A single character pressed repeatedly (`repeated`) cycles to the next\n * same-initial option after the anchor and wraps around.\n * - A distinct multi-character prefix re-anchors on the current option\n * (inclusive) so a growing prefix keeps it when it still matches.\n * - Both fall back to the top when nothing is anchored (`anchorIndex < 0`).\n *\n * Text and query are compared trimmed, case-insensitively, and\n * diacritics-insensitively (accents are folded via `foldTypeaheadText`).\n * Returns the matching option, or `null` when none matches (or the buffer is\n * empty).\n *\n * @typeParam H Option handle type.\n * @param options Live options to scan, in document order.\n * @param query Buffer state at the moment of the match.\n * @param getText Resolves an option's match text (e.g. its `textContent`), or\n * several candidate texts, any of which may match.\n * @param isDisabled Whether an option is skipped.\n */\nexport function findTypeaheadMatch<H>(\n options: readonly H[],\n query: TypeaheadMatchQuery,\n getText: (option: H) => string | readonly string[],\n isDisabled: (option: H) => boolean,\n): H | null {\n const buffer = foldTypeaheadText(query.buffer);\n if (!buffer || options.length === 0) {\n return null;\n }\n const needle = query.repeated ? buffer[0]! : buffer;\n const start = query.repeated ? query.anchorIndex + 1 : Math.max(query.anchorIndex, 0);\n for (let offset = 0; offset < options.length; offset++) {\n const option = options[(start + offset) % options.length]!;\n if (isDisabled(option)) {\n continue;\n }\n const text = getText(option);\n const candidates = typeof text === 'string' ? [text] : text;\n if (candidates.some((c) => foldTypeaheadText(c.trim()).startsWith(needle))) {\n return option;\n }\n }\n return null;\n}\n","import { fortyError } from '../errors/errors';\nimport {\n type ListOrientation,\n resolveListNavigation,\n type WritingDirection,\n} from '../keyboard-navigation/keyboard-navigation';\nimport { findTypeaheadMatch } from './match-options';\nimport type { Typeahead } from './typeahead';\n\n/** Orientation / direction context {@link isRangeSelectShortcut} reads to resolve arrow intent. */\nexport interface RangeSelectShortcutContext {\n /** The list's navigation orientation. */\n readonly orientation: ListOrientation;\n /** The list's resolved writing direction. */\n readonly dir: WritingDirection;\n}\n\n/**\n * Whether a keydown is one of the APG multi-select range-selection shortcuts:\n * Ctrl/Cmd+A (select all), Ctrl+Shift+Home / End (range to edge), Shift+Space\n * (range to focused), or Shift+Arrow along the list axis (extend by one).\n * `Alt` disqualifies every combination. Shared by the virtualized keydown\n * handlers of Listbox and Select to detect an unsupported range action before\n * throwing.\n */\nexport function isRangeSelectShortcut(\n event: KeyboardEvent,\n context: RangeSelectShortcutContext,\n): boolean {\n if (event.altKey) {\n return false;\n }\n const mod = event.ctrlKey || event.metaKey;\n if (mod && !event.shiftKey) {\n return event.key === 'a' || event.key === 'A';\n }\n if (mod && event.shiftKey) {\n return event.key === 'Home' || event.key === 'End';\n }\n if (event.shiftKey) {\n if (event.key === ' ' || event.key === 'Spacebar') {\n return true;\n }\n const action = resolveListNavigation(event, {\n orientation: context.orientation,\n dir: context.dir,\n });\n return action === 'next' || action === 'prev';\n }\n return false;\n}\n\n/** Identity of the primitive throwing {@link throwUnsupportedVirtualizedRangeSelect}. */\nexport interface UnsupportedVirtualizedRangeSelectContext {\n /** Primitive name for the `[forty-cdk/<primitive>]` error prefix (e.g. `'listbox'`). */\n readonly primitive: string;\n /** Non-virtualized focus model named in the remediation hint (e.g. `'roving-tabindex'`). */\n readonly focusModel: string;\n /** Collection the hint names after the focus model (e.g. `'listbox'`, `'tree'`). */\n readonly collection: string;\n /**\n * The range shortcuts this primitive actually detects, as the message spells\n * them — `'Shift+Arrow, Shift+Space, Ctrl/Cmd+A, Ctrl+Shift+Home/End'` for the\n * listbox family, which routes through {@link isRangeSelectShortcut}. It is a\n * fragment rather than a shared literal because Tree's own predicate detects\n * the first three only: naming a fourth there would report a combination the\n * tree supports in neither the virtualized nor the non-virtualized path, so\n * the error would be describing a restriction that does not exist.\n */\n readonly shortcuts: string;\n /**\n * The primitive's own way of multi-selecting under virtualization, opening\n * the remediation hint — e.g. `'Toggle options individually with Enter,\n * Space, or click'` for the listbox family, `'Use selectionMode=\"checkbox\"'`\n * for a tree. The shared \"or drop `totalCount`\" clause follows it.\n */\n readonly alternative: string;\n}\n\n/**\n * Throws (in dev mode only) the standard error explaining that APG range\n * keyboard is unsupported together with virtualization, because range selection\n * needs the full set of enabled items across the range while the collection is\n * only partially mounted. Shared by Listbox, Select and Tree; the primitive\n * name, the shortcut list it detects, the two hint fragments and the\n * primitive's own multi-select\n * {@link UnsupportedVirtualizedRangeSelectContext.alternative} are the only\n * per-primitive differences — add a fourth collection by calling this, not by\n * copying it.\n */\nexport function throwUnsupportedVirtualizedRangeSelect(\n context: UnsupportedVirtualizedRangeSelectContext,\n): void {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n throw fortyError({\n code: 'FORCDK-CORE-008',\n scope: context.primitive,\n message:\n `Multi-select range keyboard (${context.shortcuts}) is not supported together with ` +\n 'virtualization (`totalCount` set).',\n cause:\n 'Range selection needs the full set of enabled items across the range, which is ' +\n 'unavailable while the collection is only partially mounted.',\n fix:\n `${context.alternative}, or drop \\`totalCount\\` to use the non-virtualized ` +\n `${context.focusModel} ${context.collection}.`,\n });\n }\n}\n\n/**\n * Identity of the primitive asserting\n * {@link assertVirtualizedSelectionFollowsFocusSupported}.\n */\nexport interface UnsupportedVirtualizedSelectionFollowsFocusContext {\n /** Primitive name for the `[forty-cdk/<primitive>]` error prefix (e.g. `'listbox'`). */\n readonly primitive: string;\n /** Non-virtualized focus model named in the remediation hint (e.g. `'roving-tabindex'`). */\n readonly focusModel: string;\n /** Collection the hint names after the focus model (e.g. `'listbox'`, `'tree'`). */\n readonly collection: string;\n}\n\n/** The root state {@link assertVirtualizedSelectionFollowsFocusSupported} decides from. */\nexport interface VirtualizedSelectionFollowsFocusState {\n /**\n * The `selectionFollowsFocus` value the element bound itself, `undefined` when\n * it inherits the scope default. A virtualized root ignores the scope default,\n * so only a binding on the element is a misconfiguration.\n */\n readonly bound: boolean | undefined;\n /** Whether more than one item can be selected, where the option is inert. */\n readonly multiple: boolean;\n}\n\n/**\n * Throws (in dev mode only) the standard error explaining that\n * `selectionFollowsFocus` is unsupported together with virtualization, because\n * the activedescendant path resolves off-window navigation targets\n * asynchronously and so cannot carry selection with focus.\n *\n * It decides when the guard applies, so no root restates it: only when the\n * element bound `selectionFollowsFocus` to `true` itself, and only in single\n * mode. A scope default never reaches a virtualized root, and a multi-select\n * root ignores the option, so neither degrades a move.\n *\n * Call it from **every keyboard move of the virtualized activedescendant**\n * rather than from a config-watching `effect`: the combination degrades a\n * keyboard move, so the move is the point at which a throw carries a stack the\n * consumer can act on. \"Every\" is load-bearing — arrow navigation is only one\n * of the moves, and a guard on that branch alone leaves a consumer who\n * navigates by typeahead (or, in a tree, by entering a child) with the same\n * silent degradation and no report. Each root routes its moves through one\n * private `#assertSelectionFollowsFocusSupported()` for that reason. Seeding\n * the activedescendant on focus / open is not a move and is\n * uncovered.\n *\n * Shared by Listbox, Select and Tree; the primitive name and the two hint\n * fragments are the only per-primitive differences.\n */\nexport function assertVirtualizedSelectionFollowsFocusSupported(\n state: VirtualizedSelectionFollowsFocusState,\n context: UnsupportedVirtualizedSelectionFollowsFocusContext,\n): void {\n if (typeof ngDevMode !== 'undefined' && !ngDevMode) {\n return;\n }\n if (state.bound !== true || state.multiple) {\n return;\n }\n throw fortyError({\n code: 'FORCDK-CORE-009',\n scope: context.primitive,\n message:\n '`selectionFollowsFocus` is not supported together with virtualization (`totalCount` set).',\n cause:\n 'The virtualized activedescendant path resolves off-window navigation targets ' +\n 'asynchronously, so selection cannot follow focus there.',\n fix:\n 'Remove one of the two: use `selectionFollowsFocus` only with the non-virtualized ' +\n `${context.focusModel} ${context.collection}.`,\n });\n}\n\n/** Per-call inputs {@link resolveListTypeahead} needs to run a match. */\nexport interface ListTypeaheadConfig<H> {\n /** Live options to scan, in document order. */\n readonly items: readonly H[];\n /** Index of the currently-anchored option, or `-1` when nothing is anchored. */\n readonly anchorIndex: number;\n /** Resolve an option's match text (e.g. its accessible `textContent`), or several candidates. */\n readonly getText: (item: H) => string | readonly string[];\n /** Whether an option is skipped. */\n readonly isDisabled: (item: H) => boolean;\n}\n\n/** Outcome of a {@link resolveListTypeahead} call. */\nexport interface ListTypeaheadResult<H> {\n /** Whether the key was a printable character the typeahead buffer consumed. */\n readonly handled: boolean;\n /** The matched option when the buffer resolved one, else `null`. */\n readonly match: H | null;\n}\n\n/**\n * The shared list-typeahead policy for the open (DOM-focus) and virtualized\n * (activedescendant) paths of Listbox and Select: feed the key to the\n * `Typeahead` buffer, and — when consumed — run `findTypeaheadMatch` always\n * threading `repeated: isRepeatedChar()` and the caller-resolved `anchorIndex`.\n * Callers decide what to do with the match (focus it, or move\n * `aria-activedescendant`). A consumed Space is already `preventDefault()`-ed\n * by the buffer, so a caller whose own Space branch activates offers the key\n * here first and activates only when `handled` is `false`.\n */\nexport function resolveListTypeahead<H>(\n typeahead: Typeahead,\n event: KeyboardEvent,\n config: ListTypeaheadConfig<H>,\n): ListTypeaheadResult<H> {\n if (!typeahead.handle(event)) {\n return { handled: false, match: null };\n }\n const match = findTypeaheadMatch(\n config.items,\n {\n buffer: typeahead.buffer(),\n repeated: typeahead.isRepeatedChar(),\n anchorIndex: config.anchorIndex,\n },\n config.getText,\n config.isDisabled,\n );\n return { handled: true, match };\n}\n","import { DestroyRef, inject, signal } from '@angular/core';\n\nimport { isImeComposing } from '../keyboard-navigation/ime-composition';\nimport { isShortcutChord } from '../keyboard-navigation/modifier-chord';\n\nexport interface TypeaheadOptions {\n /** Milliseconds before the buffer is reset. Default 500. */\n debounceMs?: number;\n}\n\n/**\n * Stateful typeahead helper. Accumulates printable single-character keypresses\n * into a debounced buffer. The consumer reads `buffer()` after each handled\n * key and uses it to find a matching item (case-insensitive prefix match,\n * usually).\n *\n * The instance owns a debounce timer — call `destroy()` to clear it, or use\n * `injectTypeahead()` to register cleanup automatically with `DestroyRef`.\n */\nexport class Typeahead {\n readonly #buffer = signal('');\n readonly buffer = this.#buffer.asReadonly();\n readonly #debounceMs: number;\n #timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n constructor(options: TypeaheadOptions = {}) {\n this.#debounceMs = options.debounceMs ?? 500;\n }\n\n /**\n * Handles a key event. Returns `true` and appends to the buffer if the key\n * is a printable single character; returns `false` otherwise so the caller\n * can let the event keep flowing.\n *\n * A shortcut chord is not typing and is rejected: anything with Meta held,\n * Ctrl without AltGr, or Alt without AltGr on an ASCII key (an accelerator\n * or `accesskey` on Windows and Linux). A character composed through AltGr\n * (`ł` on a Polish layout) or through the macOS Option key (`ø`) is typing\n * and is accepted.\n *\n * Space is accepted **only while the buffer already holds at least one\n * character**, so multi-word labels (\"New York\") can accumulate past the\n * first word. The first Space with an empty buffer is rejected so widgets\n * that use Space for activation keep that behavior when the user is not\n * mid-typing. A Space this method accepts is `preventDefault()`-ed, so a\n * native `<button>` host never turns it into a click on `keyup`. A caller\n * whose own Space branch activates must offer the key here first and\n * activate only when this returns `false`.\n */\n handle(event: KeyboardEvent): boolean {\n if (isImeComposing(event) || isShortcutChord(event)) {\n return false;\n }\n const ch = event.key;\n if (typeof ch !== 'string' || ch.length !== 1) {\n return false;\n }\n if (ch === ' ') {\n if (this.#buffer() === '') {\n return false;\n }\n event.preventDefault();\n }\n\n this.#buffer.update((current) => current + ch);\n this.#scheduleReset();\n return true;\n }\n\n /**\n * Whether the buffer is a single printable character, optionally pressed\n * repeatedly (every character identical — `\"c\"`, `\"cc\"`, `\"ccc\"`). Callers\n * use this to switch from prefix matching to cycling among same-initial\n * items, matching the WAI-ARIA APG menu typeahead behavior: pressing one key\n * (and re-pressing it) steps through every item that starts with it, instead\n * of looking for a literal `\"ccc\"` prefix that never exists.\n */\n isRepeatedChar(): boolean {\n const buffer = this.#buffer();\n return buffer.length >= 1 && [...buffer].every((ch) => ch === buffer[0]);\n }\n\n reset(): void {\n if (this.#timeoutId !== null) {\n clearTimeout(this.#timeoutId);\n this.#timeoutId = null;\n }\n this.#buffer.set('');\n }\n\n destroy(): void {\n if (this.#timeoutId !== null) {\n clearTimeout(this.#timeoutId);\n this.#timeoutId = null;\n }\n }\n\n #scheduleReset(): void {\n if (this.#timeoutId !== null) {\n clearTimeout(this.#timeoutId);\n }\n this.#timeoutId = setTimeout(() => {\n this.#buffer.set('');\n this.#timeoutId = null;\n }, this.#debounceMs);\n }\n}\n\n/**\n * Creates a `Typeahead` and registers `destroy()` with the current `DestroyRef`.\n * Must be called within an Angular injection context (constructor / field\n * initializer of a directive/component, or `runInInjectionContext`).\n */\nexport function injectTypeahead(options?: TypeaheadOptions): Typeahead {\n const typeahead = new Typeahead(options);\n inject(DestroyRef).onDestroy(() => typeahead.destroy());\n return typeahead;\n}\n","import { DestroyRef, inject, type OutputEmitterRef } from '@angular/core';\n\n/**\n * An event a consumer can veto by calling `preventDefault()`. The directive\n * inspects `defaultPrevented` after emitting and skips its default action\n * (close, focus move, etc.) when set.\n *\n * Replaces the prior pattern of passing a real DOM `CustomEvent`, which\n * was a poor fit: Angular `output()` is a synchronous in-process\n * emitter — events don't bubble, don't propagate, and have no `target` /\n * `currentTarget`. `CustomEvent` cost an allocation per emit and gave\n * consumers a misleading \"looks like a DOM event\" surface.\n */\nexport interface VetoableEvent {\n /** Mark this event as vetoed; the directive will skip its default action. */\n preventDefault(): void;\n /** True after `preventDefault()` has been called. */\n readonly defaultPrevented: boolean;\n}\n\n/**\n * Vetoable event that also carries the original DOM event that triggered\n * it. Used for outputs whose semantic action is anchored to a real\n * keyboard / pointer / focus event: `(escapeKeyDown)` (`KeyboardEvent`),\n * `(pointerDownOutside)` (`PointerEvent`), `(focusOutside)` (`FocusEvent`),\n * `(interactOutside)` (`PointerEvent | FocusEvent`).\n */\nexport interface VetoableNativeEvent<E extends Event> extends VetoableEvent {\n /** Original DOM event the directive received. */\n readonly event: E;\n}\n\n/**\n * Builds a `VetoableEvent` (no native payload). The returned object's\n * `defaultPrevented` flips to `true` once any handler calls `preventDefault()`.\n */\nexport function createVetoableEvent(): VetoableEvent {\n let prevented = false;\n return {\n preventDefault() {\n prevented = true;\n },\n get defaultPrevented() {\n return prevented;\n },\n };\n}\n\n/**\n * Builds a `VetoableNativeEvent` wrapping `event`. Useful when the same\n * physical interaction must be observable through more than one output —\n * e.g. a pointer-down-outside emits the same wrapper through\n * `(pointerDownOutside)` and `(interactOutside)` so a `preventDefault()`\n * in either handler vetoes the close.\n */\nexport function createVetoableNativeEvent<E extends Event>(event: E): VetoableNativeEvent<E> {\n let prevented = false;\n return {\n event,\n preventDefault() {\n prevented = true;\n },\n get defaultPrevented() {\n return prevented;\n },\n };\n}\n\n/**\n * Builds a fresh `VetoableEvent`, emits it through `emitter`, and returns\n * whether the consumer vetoed. Use for one-shot outputs whose veto state\n * doesn't need to be observed by sibling outputs (e.g. `(autoFocusOnOpen)`,\n * a menu item's `(activate)`).\n */\nexport function emitVetoableEvent(emitter: OutputEmitterRef<VetoableEvent>): boolean {\n const veto = createVetoableEvent();\n emitter.emit(veto);\n return veto.defaultPrevented;\n}\n\n/**\n * Builds a `VetoableNativeEvent` wrapping `event`, emits it through\n * `emitter`, and returns whether the consumer vetoed. Use for outputs\n * whose veto is scoped to a single emit (e.g. `(escapeKeyDown)`).\n */\nexport function emitVetoableNativeEvent<E extends Event>(\n emitter: OutputEmitterRef<VetoableNativeEvent<E>>,\n event: E,\n): boolean {\n const veto = createVetoableNativeEvent(event);\n emitter.emit(veto);\n return veto.defaultPrevented;\n}\n\n/**\n * Builds a veto resolver over `emitter` that answers `true` — vetoed — once the\n * directive declaring it is destroyed, instead of emitting.\n *\n * Use it for a vetoable hook the primitive also fires from a teardown path: the\n * consumer's handler is unreachable there, and a dropped emit would otherwise\n * read as \"not vetoed\" and run the default action.\n *\n * Call it from the injection context of the directive that declares `emitter`.\n */\nexport function injectVetoableEmitter(emitter: OutputEmitterRef<VetoableEvent>): () => boolean {\n const destroyRef = inject(DestroyRef);\n return () => (destroyRef.destroyed ? true : emitVetoableEvent(emitter));\n}\n","import { lookupByValue } from '../selection/selection';\nimport type { VirtualizedResumeEntry } from './virtualized-resume';\n\n/** What {@link resolveCommittedPosition} reads to place the committed selection. */\nexport interface CommittedPositionQuery<T> {\n /** The committed values, in selection order. */\n readonly values: readonly T[];\n /** The navigator's position snapshot. */\n readonly snapshotByPos: ReadonlyMap<number, VirtualizedResumeEntry<T>>;\n /** Item identity, used to match a committed value against a snapshot entry. */\n readonly compareWith: (a: T, b: T) => boolean;\n /** The consumer's absolute index hint for a selection that was never rendered. */\n readonly selectedIndex: number | undefined;\n /** Full source length; a hint at or past it is ignored. */\n readonly totalCount: number | undefined;\n}\n\n/**\n * The absolute position a virtualized activedescendant collection seeds when it\n * lands on its committed selection: the first committed value whose enabled\n * entry is in the position snapshot, else the consumer's `selectedIndex` hint\n * when it is in range, else `null`. An empty selection resolves to `null`, so a\n * stale hint never seeds a collection with nothing selected.\n *\n * The caller seeds the result through the navigator's `seedActive`, which emits\n * `(scrollToIndex)` when the position is outside the rendered window.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\nexport function resolveCommittedPosition<T>(query: CommittedPositionQuery<T>): number | null {\n if (query.values.length === 0) {\n return null;\n }\n const byValue = lookupByValue(\n [...query.snapshotByPos].filter(([, entry]) => !entry.disabled),\n ([, entry]) => entry.value,\n query.compareWith,\n );\n for (const value of query.values) {\n const hit = byValue(value);\n if (hit) {\n return hit[0];\n }\n }\n const { selectedIndex, totalCount } = query;\n if (\n selectedIndex === undefined ||\n totalCount === undefined ||\n selectedIndex < 0 ||\n selectedIndex >= totalCount\n ) {\n return null;\n }\n return selectedIndex;\n}\n","import { computed, linkedSignal, signal, type Signal } from '@angular/core';\n\nimport { type ListNavigationAction, moveIndex } from '../keyboard-navigation/keyboard-navigation';\nimport { resolveListTypeahead } from '../typeahead/list-typeahead';\nimport type { Typeahead } from '../typeahead/typeahead';\n\n/**\n * Minimal shape every position-snapshot entry must expose so the engine can\n * resolve the current absolute position from `aria-activedescendant` and skip\n * disabled positions outside the rendered window. Primitive adapters widen this\n * with their own per-entry fields (value, label, level, …).\n */\nexport interface VirtualizedNavigatorEntry {\n /** Stable host id — the activedescendant target. */\n readonly id: string;\n /** Whether the position is disabled, so `moveIndex` skips over it. */\n readonly disabled: boolean;\n}\n\n/**\n * Handle-shape adapters. Each primitive's option / node handle exposes its\n * absolute position, id, and host element under different accessor names; these\n * bridge the engine to whichever shape the primitive uses, so the navigation\n * algorithm itself stays handle-agnostic.\n */\nexport interface VirtualizedNavigatorAccessors<H, E extends VirtualizedNavigatorEntry> {\n /** Absolute position of a live handle, or `null` before it is assigned. */\n readonly posOf: (item: H) => number | null;\n /** Stable id of a live handle. */\n readonly idOf: (item: H) => string;\n /** Host element of a live handle, scrolled into view when it becomes active. */\n readonly hostOf: (item: H) => HTMLElement;\n /**\n * Whether a live handle is disabled, read without going through the position\n * snapshot. {@link VirtualizedNavigator.seedFirstRenderedEnabled} needs the\n * flag for handles the fold may have skipped, so the snapshot cannot answer\n * it: {@link readEntry} returns `null` for an option whose `[value]` binding\n * is not written yet, and such an option is still a legitimate seed target.\n */\n readonly isDisabled: (item: H) => boolean;\n /**\n * Build the position-snapshot entry for a live handle, or `null` to skip it\n * this fold. The unwritten-binding guard is injected here: a\n * statically-rendered option that registers before its `[value]` binding is\n * written reads the `unsetInput` sentinel, returns `null`, and is folded in\n * on the binding's re-run.\n */\n readonly readEntry: (item: H) => E | null;\n /**\n * Scroll the active host into view. Defaults to\n * `host.scrollIntoView?.({ block: 'nearest' })`; the combobox overrides it to\n * open its pointer-suppression window first.\n */\n readonly scrollIntoView?: (host: HTMLElement) => void;\n}\n\n/** Tunables for the position-snapshot fold. */\nexport interface VirtualizedNavigatorOptions {\n /**\n * Behaviour on a `totalCount` transition. `false` (default) restarts from an\n * empty map **and folds the current window in the same compute** (Select /\n * Listbox / Tree). `true` returns the empty map **without folding**, deferring\n * to the next run once `items` catches up — the stale-window invariant the\n * Combobox needs, because a `totalCount` flip (a query / source rebuild) can\n * fire while `items()` still holds the previous window.\n */\n readonly deferFoldOnTotalTransition?: boolean;\n}\n\n/**\n * Signal-graph wiring. The root directive owns the activedescendant and the\n * virtualizer bridge, so the engine reads / writes them through callbacks\n * instead of holding its own copies.\n */\nexport interface VirtualizedNavigatorDeps<H> {\n /** Live registered handles — the rendered window when virtualizing. */\n readonly items: Signal<readonly H[]>;\n /** Total handle count for the virtualized path. */\n readonly totalCount: Signal<number | undefined>;\n /** Inclusive-exclusive range of currently rendered handles when virtualizing. */\n readonly visibleRange: Signal<readonly [number, number] | undefined>;\n /** Whether keyboard navigation wraps at the ends. */\n readonly loop: () => boolean;\n /** Read the root's current activedescendant id. */\n readonly getActiveId: () => string | null;\n /** Write the root's activedescendant id. */\n readonly setActiveId: (id: string | null) => void;\n /** Forward a `(scrollToIndex)` request to the consumer's virtualizer. */\n readonly emitScrollToIndex: (idx: number) => void;\n /**\n * Optional resume position, consulted only when there is no active id. Lets a\n * primitive that clears its dangling `aria-activedescendant` on unmount (a\n * removed element is an invalid target) still resume navigation from the last\n * active absolute position instead of restarting at the edge. Returns `null`\n * when there is nothing to resume from.\n */\n readonly getResumePos?: () => number | null;\n /**\n * Optional monotonic \"the dataset changed\" signal. When provided and its\n * value changes between folds, the position snapshot rebuilds from empty —\n * exactly as a `totalCount` transition does — discarding carried-over\n * off-window entries. This is the consumer-facing counterpart to\n * {@link VirtualizedNavigator.invalidateSnapshot}: wire a signal that bumps on\n * a same-length dataset refresh (a re-sort / reload that keeps `totalCount`\n * unchanged) so navigation never resolves against a stale off-window entry.\n */\n readonly dataVersion?: Signal<unknown>;\n}\n\n/** Outcome of a {@link VirtualizedNavigator.resolveTypeahead} call. */\nexport interface VirtualizedTypeaheadResult {\n /** Whether the key was a printable character the typeahead buffer consumed. */\n readonly handled: boolean;\n /** Absolute position of the matched entry, or `null` when nothing matched. */\n readonly pos: number | null;\n}\n\n/**\n * Tracked source of the position-snapshot fold: the live window, its total, and\n * the merged data version (the consumer's `dataVersion` plus the imperative\n * {@link VirtualizedNavigator.invalidateSnapshot} counter). A change to the\n * version rebuilds from empty and folds the current window; a change to `total`\n * rebuilds from empty and folds or defers per `deferFoldOnTotalTransition`.\n */\ninterface SnapshotSource<H> {\n readonly total: number | undefined;\n readonly items: readonly H[];\n readonly version: unknown;\n}\n\n/**\n * The single activedescendant-over-absolute-index navigation engine shared by\n * every virtualized collection primitive (Select, Listbox, Combobox, Tree).\n * Constructed lazily by each primitive's root through its own accessor factory —\n * only once the consumer sets `totalCount()` — so a non-virtualized collection\n * never pulls this position-map machinery into its hot path. Encapsulates two\n * pieces of state that make keyboard navigation work across a virtualized window\n * where the active item may be unmounted at any time:\n *\n * - **Snapshot by position** — entry data keyed by absolute position. Drives\n * navigation past the rendered window so `moveIndex` knows about disabled\n * boundaries it cannot see, and lets adapters resolve off-window entries\n * (committed-index resolution, level-aware tree moves, label fallbacks). The\n * map is updated in place with each rendered window, so a fold costs\n * O(window), and restarts empty on a `totalCount` transition. A same-length\n * dataset refresh (invisible to the `totalCount` diff) can force the same\n * reset through {@link invalidateSnapshot} or the optional\n * `deps.dataVersion` signal.\n * - **Pending active position** — when navigation lands outside the visible\n * window, the engine emits `(scrollToIndex)` and remembers the target. The\n * root's bridge effect calls `tryResolvePending` once the freshly-mounted item\n * carries that position.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n *\n * @typeParam H Primitive handle type (option / node).\n * @typeParam E Position-snapshot entry; widens {@link VirtualizedNavigatorEntry}.\n */\nexport class VirtualizedNavigator<H, E extends VirtualizedNavigatorEntry> {\n readonly #deps: VirtualizedNavigatorDeps<H>;\n\n readonly #accessors: VirtualizedNavigatorAccessors<H, E>;\n\n readonly #snapshotByPos: Signal<Map<number, E>>;\n\n /**\n * Monotonic counter bumped by {@link invalidateSnapshot}. The snapshot fold\n * tracks it as a `dataVersion` alongside the consumer's own optional\n * `deps.dataVersion`, so an imperative call forces a from-empty rebuild on the\n * next fold even when `totalCount` is unchanged.\n */\n readonly #invalidationVersion = signal(0);\n\n /**\n * The pending navigation slot. Carries the requested absolute position, the\n * action that produced it, and whether a resolve landing on a disabled entry\n * should continue the walk. Directional navigation (`navigate` / `#moveFrom`)\n * sets `continueOnDisabled`, so it never settles activedescendant on a\n * disabled id; a directionless `seedActive` (committed-index / enter-child /\n * parent move — all targeting enabled positions in practice) settles on the\n * resolved item as before.\n */\n #pendingActivePos: {\n pos: number;\n action: ListNavigationAction;\n continueOnDisabled: boolean;\n } | null = null;\n\n constructor(\n deps: VirtualizedNavigatorDeps<H>,\n accessors: VirtualizedNavigatorAccessors<H, E>,\n options: VirtualizedNavigatorOptions = {},\n ) {\n this.#deps = deps;\n this.#accessors = accessors;\n\n const consumerVersion = deps.dataVersion;\n const version = computed(\n () => ({\n invalidation: this.#invalidationVersion(),\n consumer: consumerVersion ? consumerVersion() : undefined,\n }),\n { equal: (a, b) => a.invalidation === b.invalidation && a.consumer === b.consumer },\n );\n\n const defer = options.deferFoldOnTotalTransition === true;\n const fold = (snapshot: Map<number, E>, window: readonly H[]): Map<number, E> => {\n for (const item of window) {\n const pos = accessors.posOf(item);\n if (pos === null) continue;\n const entry = accessors.readEntry(item);\n if (entry === null) continue;\n snapshot.set(pos, entry);\n }\n return snapshot;\n };\n\n this.#snapshotByPos = linkedSignal<SnapshotSource<H>, Map<number, E>>({\n source: () => ({ total: deps.totalCount(), items: deps.items(), version: version() }),\n computation: ({ total, items: window, version: currentVersion }, prev) => {\n if (prev !== undefined && prev.source.version !== currentVersion) {\n return fold(new Map<number, E>(), window);\n }\n if (prev !== undefined && prev.source.total !== total) {\n return defer ? new Map<number, E>() : fold(new Map<number, E>(), window);\n }\n return fold(prev?.value ?? new Map<number, E>(), window);\n },\n equal: () => false,\n });\n }\n\n /**\n * Pull the position-map so its `linkedSignal` `prev` slot gets seeded while\n * the items are tracked. Called from the root's bridge effect.\n */\n prime(): void {\n this.#snapshotByPos();\n }\n\n /**\n * Read-only position snapshot, keyed by absolute position. Persists across\n * close → reopen while `totalCount` is unchanged. Adapters read it for\n * committed-index resolution, level-aware moves, and off-window label\n * fallbacks. Later folds update the returned map in place, so read it again\n * rather than holding it across a window change.\n */\n snapshotByPos(): ReadonlyMap<number, E> {\n return this.#snapshotByPos();\n }\n\n /**\n * Force the position snapshot to rebuild from empty on the next fold,\n * discarding every carried-over off-window entry. Call this after a\n * same-length dataset refresh — a re-sort / reload that keeps `totalCount`\n * unchanged — so navigation never resolves against a stale `id` / `disabled` /\n * `value` for a position outside the current `items()` window. Positions not\n * in the current window are gone after the rebuild; the current window folds\n * in as usual on the next `prime()`. The `deps.dataVersion` signal is the\n * reactive counterpart when the consumer already models \"the dataset changed\".\n */\n invalidateSnapshot(): void {\n this.#invalidationVersion.update((v) => v + 1);\n }\n\n /**\n * Try to resolve a pending virtualized navigation. Once an item carrying the\n * requested position mounts, seeds activedescendant to its id and scrolls it\n * into view. If the freshly-mounted entry turns out to be disabled, the walk\n * continues from that position in the pending direction rather than settling\n * activedescendant on a disabled id. Returns `true` if a pending request was\n * resolved (or continued), `false` otherwise.\n *\n * Called from the root's bridge effect, whose documented reactive trigger\n * is `items()`. The pending slot is a plain field, not a signal: this method\n * writes it back to `null` on a successful resolve, and a tracked slot would\n * make that write re-invalidate the calling effect — a self-invalidation that\n * double-runs the prime / fold pass in every consuming primitive.\n */\n tryResolvePending(): boolean {\n const pending = this.#pendingActivePos;\n if (pending === null) {\n return false;\n }\n const match = this.#deps.items().find((it) => this.#accessors.posOf(it) === pending.pos);\n if (!match) {\n return false;\n }\n if (pending.continueOnDisabled && this.#accessors.readEntry(match)?.disabled === true) {\n this.#pendingActivePos = null;\n this.#moveFrom(pending.pos, this.#continuationDirection(pending.action));\n return true;\n }\n this.#deps.setActiveId(this.#accessors.idOf(match));\n this.#pendingActivePos = null;\n this.#scrollIntoView(this.#accessors.hostOf(match));\n return true;\n }\n\n /**\n * Virtualized arrow / Home / End navigation. Resolves the current absolute\n * position from the active id (live item, else the snapshot) or the resume\n * position, then delegates the `moveIndex` walk to {@link #moveFrom}.\n *\n * An active item still in the rendered window resolves in O(window) via\n * `items`; one scrolled off it is matched against every snapshot entry, so\n * that branch costs O(total) once per keypress.\n */\n navigate(direction: ListNavigationAction): void {\n const total = this.#deps.totalCount();\n if (total === undefined || total <= 0) {\n return;\n }\n const indexed = this.#snapshotByPos();\n const items = this.#deps.items();\n\n const currentId = this.#deps.getActiveId();\n let currentPos = -1;\n if (currentId !== null) {\n const live = items.find((o) => this.#accessors.idOf(o) === currentId);\n const livePos = live ? this.#accessors.posOf(live) : null;\n if (livePos !== null) {\n currentPos = livePos;\n } else {\n for (const [pos, entry] of indexed) {\n if (entry.id === currentId) {\n currentPos = pos;\n break;\n }\n }\n }\n } else {\n const resume = this.#deps.getResumePos?.();\n if (resume !== undefined && resume !== null && resume >= 0 && resume < total) {\n currentPos = resume;\n }\n }\n\n let action = direction;\n if (currentPos < 0 && direction === 'next') {\n action = 'first';\n } else if (currentPos < 0 && direction === 'prev') {\n action = 'last';\n }\n\n this.#moveFrom(currentPos, action);\n }\n\n /**\n * Run a typeahead keystroke against the **position snapshot** rather than the\n * rendered window, so a match the consumer's virtualizer has unmounted is\n * still reachable. Entries are scanned in absolute-position order and the\n * anchor is the current activedescendant's entry, or the resume position\n * when there is no active id, so the repeated-character cycle and the\n * anchored prefix scan of `findTypeaheadMatch` mean the same thing they mean\n * in a fully-mounted collection.\n *\n * Returns the matched **absolute position** rather than moving to it: the\n * caller runs its own per-primitive guards first, then hands the position to\n * {@link seedActive}, which emits `(scrollToIndex)` when the match is outside\n * the rendered window.\n *\n * The reachable set is bounded by the snapshot, which only holds positions\n * that have been rendered at least once — a position the consumer's window has\n * never reached is invisible to the search, and each collection's README\n * states that limit for consumers.\n *\n * @param typeahead The root's buffer; the key is fed to it before matching.\n * @param event The keydown to match on.\n * @param getText Resolves an entry's match text.\n */\n resolveTypeahead(\n typeahead: Typeahead,\n event: KeyboardEvent,\n getText: (entry: E) => string,\n ): VirtualizedTypeaheadResult {\n const entries = [...this.#snapshotByPos().entries()].sort(([a], [b]) => a - b);\n const { handled, match } = resolveListTypeahead(typeahead, event, {\n items: entries,\n anchorIndex: this.#typeaheadAnchorIndex(entries),\n getText: ([, entry]) => getText(entry),\n isDisabled: ([, entry]) => entry.disabled,\n });\n return { handled, pos: match === null ? null : match[0] };\n }\n\n /**\n * Land the activedescendant on a specific absolute index (the committed item\n * on open, an enter-child / parent move, or a first / last fallback). If the\n * index is inside the rendered window and live, seeds activedescendant\n * directly; otherwise stashes it as pending and emits `(scrollToIndex)` so the\n * consumer's virtualizer mounts it. A seed has no inherent direction, so its\n * pending resolve settles on the resolved item even if disabled (callers\n * target enabled positions) rather than continuing a directional walk.\n */\n seedActive(index: number): void {\n if (this.#seedIfRendered(index)) {\n return;\n }\n this.#pendingActivePos = { pos: index, action: 'next', continueOnDisabled: false };\n this.#deps.emitScrollToIndex(index);\n }\n\n /**\n * Seed activedescendant on the first or last enabled handle that is\n * **currently rendered**, ordered by absolute position. No-op when\n * `totalCount` is unset / zero, when nothing is rendered, or when every\n * rendered handle is disabled.\n *\n * *Passive*: it only ever moves activedescendant, never the\n * consumer's scroll position, so it emits no `(scrollToIndex)`. The Combobox\n * auto-highlight bridge — its one caller — re-seeds every time the\n * activedescendant is cleared, and scrolling the active option out of the\n * rendered window clears it. A seed that targeted the absolute first position\n * would therefore snap the listbox back to the top on every wheel tick that\n * unmounted the active row. Off-window targets are reached only through\n * {@link navigate} / {@link seedActive}, which own scroll-into-view.\n */\n seedFirstRenderedEnabled(direction: 'first' | 'last'): void {\n const total = this.#deps.totalCount();\n if (total === undefined || total <= 0) {\n return;\n }\n const items = this.#deps.items();\n if (items.length === 0) {\n return;\n }\n const ordered = [...items].sort((a, b) => {\n const pa = this.#accessors.posOf(a) ?? 0;\n const pb = this.#accessors.posOf(b) ?? 0;\n return direction === 'last' ? pb - pa : pa - pb;\n });\n for (const item of ordered) {\n if (!this.#accessors.isDisabled(item)) {\n this.#deps.setActiveId(this.#accessors.idOf(item));\n return;\n }\n }\n }\n\n /** Clear any pending navigation (called by the root on close). */\n resetPending(): void {\n this.#pendingActivePos = null;\n }\n\n /**\n * Walk `moveIndex` from `fromPos` in `action`, using the indexed snapshot to\n * skip disabled items outside the rendered window. Seeds activedescendant when\n * the target is rendered; otherwise stashes it (with the action, so a\n * resolve-on-disabled can continue the walk) and emits `(scrollToIndex)`.\n */\n #moveFrom(fromPos: number, action: ListNavigationAction): void {\n const total = this.#deps.totalCount();\n if (total === undefined || total <= 0) {\n return;\n }\n const indexed = this.#snapshotByPos();\n const next = moveIndex(fromPos, total, action, {\n loop: this.#deps.loop(),\n isDisabled: (i) => indexed.get(i)?.disabled === true,\n });\n if (next === null) {\n return;\n }\n if (this.#seedIfRendered(next)) {\n return;\n }\n this.#pendingActivePos = { pos: next, action, continueOnDisabled: true };\n this.#deps.emitScrollToIndex(next);\n }\n\n #typeaheadAnchorIndex(entries: readonly (readonly [number, E])[]): number {\n const activeId = this.#deps.getActiveId();\n if (activeId !== null) {\n return entries.findIndex(([, entry]) => entry.id === activeId);\n }\n const resume = this.#deps.getResumePos?.() ?? null;\n return resume === null ? -1 : entries.findIndex(([pos]) => pos === resume);\n }\n\n #continuationDirection(action: ListNavigationAction): ListNavigationAction {\n return action === 'prev' || action === 'last' ? 'prev' : 'next';\n }\n\n #seedIfRendered(index: number): boolean {\n const range = this.#deps.visibleRange();\n const inRange = !range || (index >= range[0] && index < range[1]);\n if (inRange) {\n const live = this.#deps.items().find((it) => this.#accessors.posOf(it) === index);\n if (live) {\n this.#pendingActivePos = null;\n this.#deps.setActiveId(this.#accessors.idOf(live));\n this.#scrollIntoView(this.#accessors.hostOf(live));\n return true;\n }\n }\n return false;\n }\n\n #scrollIntoView(host: HTMLElement): void {\n if (this.#accessors.scrollIntoView) {\n this.#accessors.scrollIntoView(host);\n return;\n }\n host.scrollIntoView?.({ block: 'nearest' });\n }\n}\n","/**\n * The two members a bridge effect needs from the navigation engine: the\n * position-map pull and the pending-navigation resolve. Structural on purpose —\n * Select, Listbox and Combobox hold a {@link VirtualizedNavigator} directly,\n * while Tree reaches the same pair through its activedescendant focus model,\n * which wraps one.\n */\nexport interface VirtualizedNavigatorBridgeTarget {\n /** @see VirtualizedNavigator.prime */\n prime(): void;\n /** @see VirtualizedNavigator.tryResolvePending */\n tryResolvePending(): boolean;\n}\n\n/** Signal-graph wiring for {@link runVirtualizedNavigatorBridge}. */\nexport interface VirtualizedNavigatorBridgeDeps<N extends VirtualizedNavigatorBridgeTarget> {\n /**\n * The live handle window. Read for its dependency alone — the bridge never\n * looks at the value — so the effect re-runs whenever the consumer's\n * virtualizer mounts or unmounts a row.\n */\n readonly items: () => unknown;\n /** Whether the consumer set `totalCount` (the virtualized path). */\n readonly virtualized: () => boolean;\n /**\n * Resolve the navigation engine, constructing it on first use. Called only on\n * the virtualized branch so a plain collection never builds the position-map\n * machinery.\n */\n readonly requireNavigator: () => N;\n}\n\n/**\n * The position-map bridge every virtualized collection primitive runs from a\n * single `effect()`: it pulls the navigator's position snapshot while the\n * rendered window is tracked, then resolves any pending off-window navigation\n * the freshly-mounted window can now satisfy. Returns `true` when a pending\n * request was resolved (or continued), so a caller with further work — the\n * Combobox auto-highlight bridge — can stand down.\n *\n * The pull is the load-bearing half and is **not** redundant with the resolve\n * next to it: `tryResolvePending` reads `items()` and the matched handle, never\n * the snapshot, and returns early when nothing is pending. Without the pull the\n * snapshot is a lazy derivation over a transient source, so the positions of\n * every window the user scrolls past never enter the map and off-window\n * navigation stops resolving. The effect that runs this therefore carries the\n * sanctioned-pull marker naming `navigator-position-map` (spelled out only at\n * the marker itself, so the library's grep ledger stays exact), and any write\n * sharing that effect must already track `items` / `totalCount` / the data\n * version — the pull drags those in. The resolve's own activedescendant write\n * is such a write: the lint bans the pair outright rather than judging that\n * overlap, and this one passes only because it sits one file away, so every\n * bridge effect relies on the overlap argument the conventions spell out.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\nexport function runVirtualizedNavigatorBridge<N extends VirtualizedNavigatorBridgeTarget>(\n deps: VirtualizedNavigatorBridgeDeps<N>,\n): boolean {\n deps.items();\n if (!deps.virtualized()) {\n return false;\n }\n const navigator = deps.requireNavigator();\n navigator.prime();\n return navigator.tryResolvePending();\n}\n","import { signal, type Signal } from '@angular/core';\n\nimport { isUnset, type Unset } from '../unset-input/unset-input';\nimport type { VirtualizedNavigatorEntry } from './virtualized-navigator';\n\n/**\n * Position-snapshot entry a {@link VirtualizedResume} can validate: the\n * engine's minimal shape plus the value of the item at that position.\n */\nexport interface VirtualizedResumeEntry<T> extends VirtualizedNavigatorEntry {\n /** The item's value, matched against the retained one. */\n readonly value: T;\n}\n\n/** Wiring for {@link VirtualizedResume}. */\nexport interface VirtualizedResumeDeps<T, E extends VirtualizedResumeEntry<T>> {\n /** Total item count; a retained position at or past it resolves to nothing. */\n readonly totalCount: Signal<number | undefined>;\n /** The navigator's position snapshot. Read lazily, so the navigator may be built later. */\n readonly snapshotByPos: () => ReadonlyMap<number, E>;\n /** Item identity, used to match the retained value against the snapshot entry. */\n readonly compareWith: Signal<(a: T, b: T) => boolean>;\n}\n\n/** A retained position resolved against the current position snapshot. */\nexport interface VirtualizedResumeMatch<E> {\n /** Absolute position of the retained item. */\n readonly pos: number;\n /** The snapshot entry at that position. */\n readonly entry: E;\n}\n\n/**\n * The position a virtualized activedescendant collection resumes from once its\n * active item unmounts. A removed element is an invalid `aria-activedescendant`\n * target, so the root clears its active id when the active handle unregisters\n * and retains that handle's absolute position and value here. Wiring\n * {@link pos} as the navigator's `getResumePos` makes arrow navigation continue\n * from it, and {@link resolve} lets activation and Tab-commit act on the item\n * the user was on, re-seeding it through `seedActive`.\n *\n * The retained value is what makes the position answer for its own identity. A\n * snapshot rebuild (a `totalCount` transition, a data-version change or\n * `invalidateSnapshot()`) drops the off-window entry, and a refresh that put a\n * different item at the position fails the comparison, so both resolve to\n * nothing instead of resuming on whatever now occupies the slot.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n *\n * @typeParam T Item value type.\n * @typeParam E Position-snapshot entry; widens {@link VirtualizedResumeEntry}.\n */\nexport class VirtualizedResume<T, E extends VirtualizedResumeEntry<T>> {\n readonly #deps: VirtualizedResumeDeps<T, E>;\n\n readonly #target = signal<{ readonly pos: number; readonly value: T } | null>(null);\n\n constructor(deps: VirtualizedResumeDeps<T, E>) {\n this.#deps = deps;\n }\n\n /**\n * Retain the position and value of the active item that is unmounting.\n * Retains nothing when the position is unknown or the value binding is not\n * written yet.\n */\n retain(pos: number | null, value: T | Unset): void {\n this.#target.set(pos === null || isUnset(value) ? null : { pos, value });\n }\n\n /** Forget the retained position. The root calls it whenever a new item becomes active. */\n clear(): void {\n this.#target.set(null);\n }\n\n /**\n * The retained position and its snapshot entry, or `null` when nothing is\n * retained or the position no longer holds the retained item.\n */\n resolve(): VirtualizedResumeMatch<E> | null {\n const target = this.#target();\n if (target === null || target.pos < 0) {\n return null;\n }\n const total = this.#deps.totalCount();\n if (total === undefined || target.pos >= total) {\n return null;\n }\n const entry = this.#deps.snapshotByPos().get(target.pos);\n if (!entry || !this.#deps.compareWith()(entry.value, target.value)) {\n return null;\n }\n return { pos: target.pos, entry };\n }\n\n retained(): { readonly pos: number; readonly value: T } | null {\n return this.#target();\n }\n\n /** The resolved position alone, in the shape the navigator's `getResumePos` takes. */\n pos(): number | null {\n return this.resolve()?.pos ?? null;\n }\n}\n"],"mappings":";;;;;AAoBA,SAAgB,sBAAsB,MAAU;CAC9C,IAAI,OAAO;CACX,KAAK,WAAW,SAAS,UAAS;EAChC,IAAI,MAAM,aAAa,MAAM,WAAW;GACtC,QAAQ,MAAM,aAAa;GAC3B;EACF;EACA,IAAI,MAAM,aAAa,MAAM,cAAc;GACzC,IAAK,MAAkB,aAAa,aAAa,MAAM,QACrD;GAEF,QAAQ,sBAAsB,KAAK;EACrC;CACF,CAAC;CACD,OAAO;AACT;ACCA,SAAgB,2BAA2B,IAAc;CACvD,MAAM,aAAa,OAAO,UAAU;CAEpC,IAAI,YAAY;CAEhB,MAAM,MAAM,sBAAqB;EAC/B,IAAI,WAAW;EACf,GAAE;CACJ,CAAC;CAED,WAAW,gBAAe;EACxB,YAAY;EACZ,IAAI,QAAO;CACb,CAAC;AACH;AC1BA,SAAS,aAAgB,GAAiB,GAAe;CACvD,IAAI,MAAM,GACR,OAAO;CAET,IAAI,EAAE,WAAW,EAAE,QACjB,OAAO;CAET,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAC5B,IAAI,EAAE,OAAO,EAAE,IACb,OAAO;CAGX,OAAO;AACT;AA0BA,IAAa,aAAb,MAAuB;CACZ,8BAAc,IAAI,IAAG;CACrB,gBAAgB,OAAO,GAAE,GAAA,YAAA,CAAA,EAAA,WAAA,gBAAA,CAAA,+BAAA,CAAA,CAAA;CACzB,YAAY,OAAO,GAAE,GAAA,YAAA,CAAA,EAAA,WAAA,YAAA,CAAA,+BAAA,CAAA,CAAA;CAE9B,YAAqC;CAC5B,iCAAiB,IAAI,IAAG;CACjC,aAAa;CACb,iBAAiB;CAEjB,cAAA;EACE,OAAO,UAAU,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AAI,QAAQ,QAAQ,QAAQ,KAAK,IAAI,OAAO;GAAE;GAAK;EAAK,CAAE;CACzE;CAGA,QAAK;EACH,KAAK,QAAQ,IAAI,IAAI;CACvB;CAMA,UAAO;EACL,MAAM,SAAS,KAAK,QAAO;EAC3B,IAAI,WAAW,QAAQ,OAAO,MAAM,GAClC,OAAO;EAET,MAAM,QAAQ,KAAK,MAAM,WAAU;EACnC,IAAI,UAAU,UAAa,OAAO,OAAO,OACvC,OAAO;EAET,MAAM,QAAQ,KAAK,MAAM,cAAa,CAAE,CAAC,IAAI,OAAO,GAAG;EACvD,IAAI,CAAC,SAAS,CAAC,KAAK,MAAM,YAAW,CAAE,CAAC,MAAM,OAAO,OAAO,KAAK,GAC/D,OAAO;EAET,OAAO;GAAE,KAAK,OAAO;GAAK;EAAK;CACjC;CAEA,WAAQ;EACN,OAAO,KAAK,QAAO;CACrB;CAGA,MAAG;EACD,OAAO,KAAK,QAAO,CAAE,EAAE,OAAO;CAChC;AACD"}
|
|
1
|
+
{"version":3,"file":"forty-cdk-core.mjs","names":["DIGITS","owners"],"sources":["../../../projects/forty-cdk/core/src/accessible-text/accessible-text.ts","../../../projects/forty-cdk/core/src/after-next-render-cancellable/after-next-render-cancellable.ts","../../../projects/forty-cdk/core/src/collection/collection.ts","../../../projects/forty-cdk/core/src/keyboard-navigation/modifier-chord.ts","../../../projects/forty-cdk/core/src/keyboard-navigation/keyboard-navigation.ts","../../../projects/forty-cdk/core/src/collection/enabled-handle-navigation.ts","../../../projects/forty-cdk/core/src/selection/selection.ts","../../../projects/forty-cdk/core/src/errors/errors.ts","../../../projects/forty-cdk/core/src/unset-input/unset-input.ts","../../../projects/forty-cdk/core/src/collection/label-cache.ts","../../../projects/forty-cdk/core/src/id-generator/id-generator.ts","../../../projects/forty-cdk/core/src/host-attributes/host-id.ts","../../../projects/forty-cdk/core/src/collection/register-handle.ts","../../../projects/forty-cdk/core/src/collection/single-slot.ts","../../../projects/forty-cdk/core/src/collection/rooted-registry.ts","../../../projects/forty-cdk/core/src/composed-tree/composed-tree.ts","../../../projects/forty-cdk/core/src/datetime/date-adapter.ts","../../../projects/forty-cdk/core/src/datetime/hour-cycle.ts","../../../projects/forty-cdk/core/src/datetime/locale-digits.ts","../../../projects/forty-cdk/core/src/datetime/segment-editor.ts","../../../projects/forty-cdk/core/src/datetime/field-engine-base.ts","../../../projects/forty-cdk/core/src/datetime/date-segments.ts","../../../projects/forty-cdk/core/src/datetime/serialize.ts","../../../projects/forty-cdk/core/src/datetime/date-field-engine.ts","../../../projects/forty-cdk/core/src/datetime/literal-directive.ts","../../../projects/forty-cdk/core/src/datetime/picker-source-host.ts","../../../projects/forty-cdk/core/src/keyed-flag/keyed-flag.ts","../../../projects/forty-cdk/core/src/roving-tabindex/roving-focus-yield.ts","../../../projects/forty-cdk/core/src/roving-tabindex/roving-tabindex.ts","../../../projects/forty-cdk/core/src/datetime/range-field-composer.ts","../../../projects/forty-cdk/core/src/keyboard-navigation/ime-composition.ts","../../../projects/forty-cdk/core/src/datetime/editable-content.ts","../../../projects/forty-cdk/core/src/datetime/unicode-digit.ts","../../../projects/forty-cdk/core/src/datetime/segment-directive.ts","../../../projects/forty-cdk/core/src/datetime/segmented-field-host.ts","../../../projects/forty-cdk/core/src/datetime/time-segments.ts","../../../projects/forty-cdk/core/src/datetime/time-field-engine.ts","../../../projects/forty-cdk/core/src/datetime/time-value-source.ts","../../../projects/forty-cdk/core/src/defaults/localizable-text.ts","../../../projects/forty-cdk/core/src/drag-session/clamp-preview.ts","../../../projects/forty-cdk/core/src/drag-session/drag-geometry.ts","../../../projects/forty-cdk/core/src/drag-session/drag-announcement-label.ts","../../../projects/forty-cdk/core/src/drag-session/drag-announcer.ts","../../../projects/forty-cdk/core/src/swipe-dismiss/scroll-boundary.ts","../../../projects/forty-cdk/core/src/drag-session/drag-touch-action.ts","../../../projects/forty-cdk/core/src/drag-session/drag-item-hosts.ts","../../../projects/forty-cdk/core/src/text-direction/text-direction.ts","../../../projects/forty-cdk/core/src/drag-session/transform-transition.ts","../../../projects/forty-cdk/core/src/drag-session/drag-preview.ts","../../../projects/forty-cdk/core/src/drag-session/focus-when-mounted.ts","../../../projects/forty-cdk/core/src/drag-session/keyboard-drag-keys.ts","../../../projects/forty-cdk/core/src/drag-session/keyboard-drag-mediator.ts","../../../projects/forty-cdk/core/src/drag-session/lift-arbitration.ts","../../../projects/forty-cdk/core/src/drag-session/pointer-session.ts","../../../projects/forty-cdk/core/src/drag-session/placeholder-slot.ts","../../../projects/forty-cdk/core/src/drag-session/pressed-drag-item.ts","../../../projects/forty-cdk/core/src/drag-session/preview-controller.ts","../../../projects/forty-cdk/core/src/drag-session/window-index-map.ts","../../../projects/forty-cdk/core/src/element-size/element-size.ts","../../../projects/forty-cdk/core/src/errors/orphan-context.ts","../../../projects/forty-cdk/core/src/field/field-anchor.ts","../../../projects/forty-cdk/core/src/host-attributes/described-by-owner.ts","../../../projects/forty-cdk/core/src/host-attributes/replaced-attribute-owner.ts","../../../projects/forty-cdk/core/src/field/field-wiring.ts","../../../projects/forty-cdk/core/src/field/fieldset-context.ts","../../../projects/forty-cdk/core/src/focus-trap/focusable-candidate.ts","../../../projects/forty-cdk/core/src/host-attributes/modal-attributes.ts","../../../projects/forty-cdk/core/src/focus-trap/focus-trap.ts","../../../projects/forty-cdk/core/src/focus-trap/focusable-content.ts","../../../projects/forty-cdk/core/src/focus-trap/return-focus.ts","../../../projects/forty-cdk/core/src/form-ui-control/form-ui-control-base.ts","../../../projects/forty-cdk/core/src/visually-hidden/visually-hidden.ts","../../../projects/forty-cdk/core/src/form-ui-control/hidden-input.ts","../../../projects/forty-cdk/core/src/form-ui-control/native-form-reset.ts","../../../projects/forty-cdk/core/src/host-attributes/disabled-reflection.ts","../../../projects/forty-cdk/core/src/host-attributes/required-reflection.ts","../../../projects/forty-cdk/core/src/form-ui-control/value-mirror.ts","../../../projects/forty-cdk/core/src/form-ui-control/text-value-control-base.ts","../../../projects/forty-cdk/core/src/form-ui-control/touch-timing.ts","../../../projects/forty-cdk/core/src/host-attributes/config-class.ts","../../../projects/forty-cdk/core/src/host-attributes/host-aria.ts","../../../projects/forty-cdk/core/src/host-attributes/host-static-attribute.ts","../../../projects/forty-cdk/core/src/host-attributes/hidden-until-found.ts","../../../projects/forty-cdk/core/src/host-attributes/host-type.ts","../../../projects/forty-cdk/core/src/escape-arbiter/escape-arbiter.ts","../../../projects/forty-cdk/core/src/modal-owned-regions/modal-owned-regions.ts","../../../projects/forty-cdk/core/src/live-announcer/live-announcer.ts","../../../projects/forty-cdk/core/src/media-query/media-query.ts","../../../projects/forty-cdk/core/src/numeric-step/numeric-step.ts","../../../projects/forty-cdk/core/src/pausable/visibility-pause.ts","../../../projects/forty-cdk/core/src/pausable/pause-controller.ts","../../../projects/forty-cdk/core/src/pointer/pointer-capability.ts","../../../projects/forty-cdk/core/src/pointer/pointer-focus.ts","../../../projects/forty-cdk/core/src/pointer/pointer-suppression.ts","../../../projects/forty-cdk/core/src/pointer/stationary-pointer-moves.ts","../../../projects/forty-cdk/core/src/pointer/pointer-highlight.ts","../../../projects/forty-cdk/core/src/portal/portal.ts","../../../projects/forty-cdk/core/src/root-context/root-context.ts","../../../projects/forty-cdk/core/src/roving-tabindex/host-roving-context.ts","../../../projects/forty-cdk/core/src/roving-tabindex/roving-focus-restore.ts","../../../projects/forty-cdk/core/src/roving-tabindex/roving-list-navigation.ts","../../../projects/forty-cdk/core/src/selection/range-selection-engine.ts","../../../projects/forty-cdk/core/src/swipe-dismiss/swipe-dismiss.ts","../../../projects/forty-cdk/core/src/swipe-dismiss/swipe-motion.ts","../../../projects/forty-cdk/core/src/synthetic-activation/disabled-click-guard.ts","../../../projects/forty-cdk/core/src/synthetic-activation/synthetic-activation.ts","../../../projects/forty-cdk/core/src/table-registration/table-registration.ts","../../../projects/forty-cdk/core/src/typeahead/match-options.ts","../../../projects/forty-cdk/core/src/typeahead/list-typeahead.ts","../../../projects/forty-cdk/core/src/typeahead/typeahead.ts","../../../projects/forty-cdk/core/src/vetoable-event/vetoable-event.ts","../../../projects/forty-cdk/core/src/virtualized-navigator/virtualized-committed-position.ts","../../../projects/forty-cdk/core/src/virtualized-navigator/virtualized-navigator.ts","../../../projects/forty-cdk/core/src/virtualized-navigator/virtualized-navigator-bridge.ts","../../../projects/forty-cdk/core/src/virtualized-navigator/virtualized-resume.ts"],"sourcesContent":["/**\n * Concatenate the accessible text of a DOM node, excluding any subtree marked\n * `aria-hidden=\"true\"`. Mirrors how assistive technology derives an accessible\n * name from text content: an `aria-hidden` element (a decorative indicator\n * glyph, badge, icon, …) contributes nothing, while visually-hidden but\n * announced content (`hidden` / `display:none` are NOT skipped here) is kept.\n *\n * This is the definition the library itself reasons about: the label a\n * `[forSelectOption]` / `[forComboboxOption]` reports, the text its typeahead\n * matches on, and the name a reorder announcement uses. Read it through this\n * function rather than through `textContent` so a decorative glyph inside an\n * option cannot make the two disagree.\n *\n * The result is returned untrimmed, so apply your own `.trim()` when comparing.\n * SSR-safe: it touches no `document` / `window` and branches on the node's own\n * `nodeType` constants.\n *\n * @param node The DOM node whose accessible text to read (typically an option host).\n * @returns The concatenated text of all non-`aria-hidden` descendant text nodes.\n */\nexport function accessibleTextContent(node: Node): string {\n let text = '';\n node.childNodes.forEach((child) => {\n if (child.nodeType === child.TEXT_NODE) {\n text += child.nodeValue ?? '';\n return;\n }\n if (child.nodeType === child.ELEMENT_NODE) {\n if ((child as Element).getAttribute('aria-hidden') === 'true') {\n return;\n }\n text += accessibleTextContent(child);\n }\n });\n return text;\n}\n","import { afterNextRender, DestroyRef, inject } from '@angular/core';\n\n/**\n * `afterNextRender` whose queued callback is cancelled on destroy. Solves the\n * destroy-before-first-render hazard that both overlay shells\n * (`forty-cdk/core-overlay`'s modal shell, `forty-cdk/core-anchored`'s\n * overlay shell) share: a directive torn down between construction\n * and the next render (synchronous open/close test paths, fast SPA\n * mount+unmount), where the queued render callback\n * would otherwise still activate a global side effect with no hook left to\n * undo it (body inert + scroll lock + a document keydown listener for the\n * modal shell, a permanent topmost dismissible-layer entry for the overlay\n * shell).\n *\n * The helper:\n *\n * 1. Captures the `AfterRenderRef` returned by `afterNextRender` and calls\n * `.destroy()` from the `DestroyRef.onDestroy` hook, so a callback still\n * genuinely pending at teardown (true async path — the render flush comes\n * after destroy) is cancelled and never runs.\n * 2. Sets a `destroyed` flag the wrapper re-checks before invoking `fn`, in\n * case the callback interleaves before `.destroy()` takes effect.\n *\n * Teardown before the render flush therefore never runs `fn`. When the render\n * flushes first, `fn` has run, and undoing its side effect is the adopter's own\n * `DestroyRef.onDestroy` (portal removes the element, the modal shell\n * deactivates inert / scroll lock / focus trap, the overlay shell deactivates\n * its dismissible layer). Either way no global side effect survives teardown.\n *\n * Must be called from an injection context (typically a directive constructor\n * or an `inject`-based helper). SSR-safe: `afterNextRender` never runs on the\n * server, so the callback simply never fires.\n *\n * @param fn The render callback. Runs once after the first render unless the\n * injection context is destroyed before the queued render flushes.\n */\nexport function afterNextRenderCancellable(fn: () => void): void {\n const destroyRef = inject(DestroyRef);\n\n let destroyed = false;\n\n const ref = afterNextRender(() => {\n if (destroyed) return;\n fn();\n });\n\n destroyRef.onDestroy(() => {\n destroyed = true;\n ref.destroy();\n });\n}\n","import { computed, DestroyRef, inject, signal, type Signal } from '@angular/core';\n\n/**\n * Minimal contract every `Collection` entry must satisfy: it carries the DOM\n * node that positions the handle, so the collection can order handles by\n * document position and consumers can correlate a handle with a node\n * (`findByHost`, `indexOfHost`).\n *\n * The node is typed `Node`, not `HTMLElement`, because that is everything the\n * collection reads on it — `isConnected`, `compareDocumentPosition`,\n * `parentNode`, and identity. A handle anchored on a comment node therefore\n * satisfies the contract honestly: a piece declared on an `<ng-container>` or\n * an `<ng-template>` has a comment node for its `ElementRef.nativeElement`, and\n * `forty-cdk/table`'s def registry orders exactly those.\n *\n * A handle whose host is focused, scrolled or measured declares\n * `readonly host: HTMLElement` on its own interface rather than inheriting the\n * assumption from here — `DisableableHandle` and `HostRovingItemHandle` are the\n * shared ones.\n */\nexport interface CollectionHandle {\n readonly host: Node;\n}\n\nfunction sameSequence<T>(a: readonly T[], b: readonly T[]): boolean {\n if (a === b) {\n return true;\n }\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Generic, signal-backed registry of handles for a primitive's children\n * (e.g. tab triggers, radios, listbox options, dialog titles). Items are\n * exposed in **DOM document order**, resolved from each handle's `host` node\n * regardless of the order children registered in.\n *\n * Document order rather than registration order is what keeps `items()` and `indexOfHost` correct\n * under a template that reorders its list at runtime: `@for (…; track id)` moves existing DOM nodes\n * without re-running child constructors, so registration order would freeze and corrupt\n * `aria-posinset` / `aria-setsize` and the keyboard navigation order. An internal\n * `MutationObserver` re-orders the exposed array when nodes move.\n *\n * The observer watches `childList` on every node from each host's direct parent up to the deepest\n * common ancestor of all registered hosts, so a reorder applied at an intermediate wrapper — moving\n * `<li>` elements inside a `<ul>` without touching any host's own parent — is still seen, while a\n * mutation confined to a sibling subtree does not invalidate the collection.\n *\n * Must be constructed in an injection context: it registers `destroy()` with the ambient\n * `DestroyRef`, so the observer is disconnected with the owner even if children never unregister.\n * Call `register` / `unregister` from each child's constructor and `DestroyRef.onDestroy`.\n *\n * Reads are memoized — `items()` returns the same array reference until membership or DOM order\n * changes, and `findByHost` / `indexOfHost` resolve through a companion index instead of scanning.\n */\nexport class Collection<H extends CollectionHandle> {\n readonly #membersSet = new Set<H>();\n readonly #membersEpoch = signal(0);\n readonly #domEpoch = signal(0);\n\n #observer: MutationObserver | null = null;\n readonly #observedNodes = new Set<Node>();\n #destroyed = false;\n #syncScheduled = false;\n\n constructor() {\n inject(DestroyRef).onDestroy(() => this.destroy());\n }\n\n /**\n * All registered handles, in DOM document order.\n *\n * Order is resolved from each handle's `host` via `compareDocumentPosition`\n * and refreshed reactively when membership changes or a node on the hosts'\n * common-ancestor chain reorders its children, so it stays correct under\n * runtime reordering (`@for` sort / drag-reorder), not just under static\n * `@for` / `@if`.\n * Handles whose host is detached (or shares an exact position with another)\n * keep a stable relative order at the end.\n *\n * The contract is type-level: the `readonly H[]` return type is what stops a\n * caller sorting or splicing in place. It is enforced at compile time rather\n * than by freezing the array, because the returned reference is the memoized\n * cache backing this `computed` and freezing it would cost a pass over every\n * recomputation for a guarantee the type already gives. Copy before sorting.\n */\n readonly items: Signal<readonly H[]> = computed(\n () => {\n this.#membersEpoch();\n this.#domEpoch();\n return this.#sortByDomOrder([...this.#membersSet]);\n },\n { equal: sameSequence },\n );\n\n register(handle: H): void {\n if (this.#destroyed || this.#membersSet.has(handle)) {\n return;\n }\n this.#membersSet.add(handle);\n this.#membersEpoch.update((e) => e + 1);\n this.#scheduleSync();\n }\n\n unregister(handle: H): void {\n if (!this.#membersSet.has(handle)) {\n return;\n }\n this.#membersSet.delete(handle);\n this.#membersEpoch.update((e) => e + 1);\n this.#scheduleSync();\n }\n\n /**\n * Position of each registered host in {@link items}, keyed by node.\n *\n * Derived from `items` rather than from the member set so it inherits the\n * `sameSequence` equality — a DOM-epoch bump that resolves to the same order\n * does not rebuild it. It is lazy like any `computed`, so a collection whose\n * consumers never look a host up never pays for the map.\n *\n * Two handles may share a host (a piece composed onto the same element\n * twice); the first in document order wins, matching the `find` /\n * `findIndex` scan this replaced.\n */\n readonly #indexByHost = computed(() => {\n const index = new Map<Node, number>();\n const ordered = this.items();\n for (let i = 0; i < ordered.length; i++) {\n const host = ordered[i]!.host;\n if (!index.has(host)) {\n index.set(host, i);\n }\n }\n return index;\n });\n\n /** Lookup by host node. Returns `undefined` if no handle has that host. */\n findByHost(node: Node): H | undefined {\n const index = this.#indexByHost().get(node);\n return index === undefined ? undefined : this.items()[index];\n }\n\n /** Index in DOM document order, or -1 if not registered. */\n indexOfHost(node: Node): number {\n return this.#indexByHost().get(node) ?? -1;\n }\n\n /**\n * Disconnects the `MutationObserver` and clears membership. Idempotent and\n * safe to call from a `DestroyRef.onDestroy` hook — which the constructor\n * wires automatically. After `destroy()`, further `register` calls are\n * ignored.\n */\n destroy(): void {\n this.#destroyed = true;\n this.#syncScheduled = false;\n this.#observer?.disconnect();\n this.#observer = null;\n this.#observedNodes.clear();\n if (this.#membersSet.size > 0) {\n this.#membersSet.clear();\n this.#membersEpoch.update((e) => e + 1);\n }\n }\n\n #sortByDomOrder(handles: H[]): readonly H[] {\n if (handles.length < 2) {\n return handles;\n }\n const position = new Map<H, number>(handles.map((h, i) => [h, i]));\n const indexOrder = (a: H, b: H): number => position.get(a)! - position.get(b)!;\n return handles.sort((a, b) => {\n if (a.host === b.host) {\n return indexOrder(a, b);\n }\n const aConnected = a.host.isConnected;\n const bConnected = b.host.isConnected;\n if (aConnected !== bConnected) {\n return aConnected ? -1 : 1;\n }\n if (!aConnected) {\n return indexOrder(a, b);\n }\n const rel = a.host.compareDocumentPosition(b.host);\n if ((rel & Node.DOCUMENT_POSITION_FOLLOWING) !== 0) {\n return -1;\n }\n if ((rel & Node.DOCUMENT_POSITION_PRECEDING) !== 0) {\n return 1;\n }\n return indexOrder(a, b);\n });\n }\n\n #scheduleSync(): void {\n if (this.#syncScheduled || this.#destroyed) {\n return;\n }\n this.#syncScheduled = true;\n queueMicrotask(() => {\n this.#syncScheduled = false;\n if (this.#destroyed) {\n return;\n }\n this.#syncObserver();\n });\n }\n\n #syncObserver(): void {\n if (typeof MutationObserver === 'undefined' || this.#destroyed) {\n return;\n }\n const nodes = this.#resolveObservedNodes();\n if (this.#sameNodes(nodes)) {\n return;\n }\n this.#observer ??= new MutationObserver(() => {\n this.#domEpoch.update((e) => e + 1);\n this.#scheduleSync();\n });\n this.#observer.disconnect();\n this.#observedNodes.clear();\n for (const node of nodes) {\n this.#observer.observe(node, { childList: true });\n this.#observedNodes.add(node);\n }\n }\n\n #resolveObservedNodes(): Set<Node> {\n const hosts: Node[] = [];\n for (const member of this.#membersSet) {\n if (member.host.isConnected) {\n hosts.push(member.host);\n }\n }\n const nodes = new Set<Node>();\n if (hosts.length === 0) {\n return nodes;\n }\n if (hosts.length === 1) {\n const parent = hosts[0]!.parentNode;\n if (parent) {\n nodes.add(parent);\n }\n return nodes;\n }\n const commonAncestor = this.#commonAncestor(hosts);\n for (const host of hosts) {\n for (let node: Node | null = host.parentNode; node; node = node.parentNode) {\n nodes.add(node);\n if (node === commonAncestor) {\n break;\n }\n }\n }\n return nodes;\n }\n\n #commonAncestor(hosts: Node[]): Node | null {\n const chain: Node[] = [];\n const chainIndex = new Map<Node, number>();\n for (let node: Node | null = hosts[0]!; node; node = node.parentNode) {\n chainIndex.set(node, chain.length);\n chain.push(node);\n }\n let ancestorIndex = 0;\n for (let i = 1; i < hosts.length; i++) {\n let node: Node | null = hosts[i]!;\n while (node && !chainIndex.has(node)) {\n node = node.parentNode;\n }\n if (!node) {\n return null;\n }\n const index = chainIndex.get(node)!;\n if (index > ancestorIndex) {\n ancestorIndex = index;\n }\n }\n return chain[ancestorIndex]!;\n }\n\n #sameNodes(nodes: Set<Node>): boolean {\n if (nodes.size !== this.#observedNodes.size) {\n return false;\n }\n for (const node of nodes) {\n if (!this.#observedNodes.has(node)) {\n return false;\n }\n }\n return true;\n }\n}\n","export function isHistoryChord(event: KeyboardEvent): boolean {\n return event.altKey || event.metaKey;\n}\n\nexport function isShortcutChord(event: KeyboardEvent): boolean {\n if (event.metaKey) {\n return true;\n }\n if (event.getModifierState?.('AltGraph')) {\n return false;\n }\n if (event.ctrlKey) {\n return true;\n }\n return event.altKey && event.key.length === 1 && event.key.charCodeAt(0) < 0x80;\n}\n","/**\n * Pure helpers that translate keyboard events into navigation intents and\n * compute the resulting index for 1D lists and 2D grids. No DOM access, no\n * DI, no state — primitives compose them inside their own keydown handlers.\n *\n * Pair with `RovingTabindex` to actually move focus.\n */\n\nimport { isHistoryChord } from './modifier-chord';\n\nexport type ListOrientation = 'horizontal' | 'vertical' | 'both' | 'mixed';\nexport type WritingDirection = 'ltr' | 'rtl';\n\nexport type ListNavigationAction = 'next' | 'prev' | 'first' | 'last';\n\nexport interface ListNavigationOptions {\n orientation: ListOrientation;\n /** Reading direction. RTL swaps ArrowLeft/ArrowRight. Default `'ltr'`. */\n dir?: WritingDirection;\n /**\n * When true, PageUp / PageDown map to `first` / `last`. Default `false` —\n * controls that handle paging themselves should keep this off.\n */\n pageKeys?: boolean;\n}\n\n/**\n * Maps a keyboard event to a 1D navigation action, or `null` if the key is\n * not handled by the configured orientation or is held with Alt or Meta, which\n * leaves the browser its history shortcuts. `'both'` and `'mixed'` accept\n * every arrow direction and map each to a linear `next` / `previous` step —\n * `'mixed'` models a visually-wrapped grid as a 1D DOM sequence, so there is no\n * separate row/column keyboard step.\n */\nexport function resolveListNavigation(\n event: KeyboardEvent,\n options: ListNavigationOptions,\n): ListNavigationAction | null {\n if (isHistoryChord(event)) {\n return null;\n }\n const { orientation, dir = 'ltr', pageKeys = false } = options;\n const acceptsBothAxes = orientation === 'both' || orientation === 'mixed';\n const acceptsVertical = orientation === 'vertical' || acceptsBothAxes;\n const acceptsHorizontal = orientation === 'horizontal' || acceptsBothAxes;\n\n switch (event.key) {\n case 'Home':\n return 'first';\n case 'End':\n return 'last';\n case 'PageUp':\n return pageKeys ? 'first' : null;\n case 'PageDown':\n return pageKeys ? 'last' : null;\n case 'ArrowUp':\n return acceptsVertical ? 'prev' : null;\n case 'ArrowDown':\n return acceptsVertical ? 'next' : null;\n case 'ArrowLeft':\n return acceptsHorizontal ? (dir === 'rtl' ? 'next' : 'prev') : null;\n case 'ArrowRight':\n return acceptsHorizontal ? (dir === 'rtl' ? 'prev' : 'next') : null;\n default:\n return null;\n }\n}\n\nexport type GridNavigationAction =\n | 'next'\n | 'prev'\n | 'next-row'\n | 'prev-row'\n | 'first'\n | 'last'\n | 'first-in-row'\n | 'last-in-row'\n | 'page-up'\n | 'page-down';\n\nexport interface GridNavigationOptions {\n /** Number of columns in the grid. Required. */\n cols: number;\n /** Reading direction. RTL swaps ArrowLeft/ArrowRight. Default `'ltr'`. */\n dir?: WritingDirection;\n /**\n * PageUp / PageDown map to `page-up` / `page-down` when true. Default `false`.\n * APG grid semantics move focus by one page of rows while keeping the current\n * column, unlike a 1D list where paging jumps to the ends.\n */\n pageKeys?: boolean;\n}\n\n/**\n * Maps a keyboard event to a 2D grid navigation action.\n *\n * APG: `Ctrl+Home` / `Ctrl+End` jump to the first / last cell of the entire\n * grid, with `Cmd` accepted as the macOS alias for `Ctrl`. Plain `Home` / `End`\n * go to the first / last cell of the current row.\n * `PageUp` / `PageDown` (when `pageKeys` is enabled) page up / down by whole\n * rows while preserving the current column — they do not jump to the grid ends.\n * Any key held with Alt, and an arrow held with Meta, resolve to `null` so the\n * browser keeps its history shortcuts.\n */\nexport function resolveGridNavigation(\n event: KeyboardEvent,\n options: GridNavigationOptions,\n): GridNavigationAction | null {\n if (event.altKey || (isHistoryChord(event) && event.key.startsWith('Arrow'))) {\n return null;\n }\n const { dir = 'ltr', pageKeys = false } = options;\n\n switch (event.key) {\n case 'ArrowUp':\n return 'prev-row';\n case 'ArrowDown':\n return 'next-row';\n case 'ArrowLeft':\n return dir === 'rtl' ? 'next' : 'prev';\n case 'ArrowRight':\n return dir === 'rtl' ? 'prev' : 'next';\n case 'Home':\n return event.ctrlKey || event.metaKey ? 'first' : 'first-in-row';\n case 'End':\n return event.ctrlKey || event.metaKey ? 'last' : 'last-in-row';\n case 'PageUp':\n return pageKeys ? 'page-up' : null;\n case 'PageDown':\n return pageKeys ? 'page-down' : null;\n default:\n return null;\n }\n}\n\nexport interface MoveIndexOptions {\n /** Wrap around at the ends. Default `false`. */\n loop?: boolean;\n /** Predicate to skip indices (e.g. disabled items). */\n isDisabled?: (index: number) => boolean;\n}\n\n/**\n * Computes the resulting index for a 1D navigation action, respecting `loop`\n * and skipping disabled items. Returns `null` when no enabled target exists\n * in the requested direction.\n */\nexport function moveIndex(\n current: number,\n count: number,\n action: ListNavigationAction,\n options: MoveIndexOptions = {},\n): number | null {\n if (count <= 0) {\n return null;\n }\n const { loop = false, isDisabled } = options;\n\n if (action === 'first') {\n return scanFirstEnabled(0, count, 1, isDisabled);\n }\n if (action === 'last') {\n return scanFirstEnabled(count - 1, count, -1, isDisabled);\n }\n\n const step = action === 'next' ? 1 : -1;\n return scanNextEnabled(current, count, step, loop, isDisabled);\n}\n\nexport interface MoveGridIndexOptions extends MoveIndexOptions {\n cols: number;\n /**\n * Number of rows a `page-up` / `page-down` action moves. Required for those\n * actions; ignored otherwise. Values below `1` are treated as `1`.\n */\n pageSize?: number;\n}\n\n/**\n * Computes the resulting index for a 2D grid navigation action.\n *\n * - `next` / `prev`: steps forward / backward by one cell within the current\n * row, skipping disabled cells. The move stops at the row edge and never\n * crosses into an adjacent row; when `loop=true` it wraps to the other end of\n * the same row instead.\n * - `next-row` / `prev-row`: moves to the cell in the same column one row down /\n * up. If that cell is disabled, keeps moving in the same direction one row at\n * a time until an enabled cell is found, so navigation never lands on a\n * disabled cell. The last row may be incomplete; if the column doesn't exist\n * there, falls back to the last filled cell of that row. When `loop=true` the\n * row index wraps top-to-bottom; otherwise the search stops at the grid edge.\n * - `page-up` / `page-down`: moves up / down by `pageSize` rows in the same\n * column, clamped to the first / last row (no loop). If the landing cell is\n * disabled, keeps stepping toward the grid edge one row at a time until an\n * enabled cell is found.\n * - `first` / `last`: first / last enabled cell overall.\n * - `first-in-row` / `last-in-row`: row extremes.\n *\n * Returns `null` when no enabled target exists for the requested action.\n */\nexport function moveGridIndex(\n current: number,\n count: number,\n action: GridNavigationAction,\n options: MoveGridIndexOptions,\n): number | null {\n if (count <= 0 || options.cols <= 0) {\n return null;\n }\n const { cols, loop = false, isDisabled } = options;\n const rowOf = (i: number) => Math.floor(i / cols);\n const colOf = (i: number) => i % cols;\n const totalRows = Math.ceil(count / cols);\n\n switch (action) {\n case 'first':\n return scanFirstEnabled(0, count, 1, isDisabled);\n case 'last':\n return scanFirstEnabled(count - 1, count, -1, isDisabled);\n case 'page-up':\n case 'page-down': {\n const direction = action === 'page-down' ? 1 : -1;\n const pageSize = Math.max(1, Math.floor(options.pageSize ?? 1));\n const col = colOf(current);\n const currentRow = rowOf(current);\n const edgeRow = direction === 1 ? totalRows - 1 : 0;\n let row = currentRow + direction * pageSize;\n row = Math.min(totalRows - 1, Math.max(0, row));\n for (;;) {\n const rowStart = row * cols;\n const rowEnd = Math.min(rowStart + cols, count);\n const target = rowStart + col < rowEnd ? rowStart + col : rowEnd - 1;\n if (target === current) {\n return null;\n }\n if (!isDisabled || !isDisabled(target)) {\n return target;\n }\n if (row === edgeRow) {\n return null;\n }\n row += direction;\n }\n }\n case 'first-in-row': {\n const row = rowOf(current);\n const start = row * cols;\n const end = Math.min(start + cols, count);\n return scanFirstEnabledInRange(start, end, 1, isDisabled);\n }\n case 'last-in-row': {\n const row = rowOf(current);\n const start = row * cols;\n const end = Math.min(start + cols, count);\n return scanFirstEnabledInRange(end - 1, start - 1, -1, isDisabled);\n }\n case 'next':\n case 'prev': {\n const start = rowOf(current) * cols;\n const end = Math.min(start + cols, count);\n const target = scanNextEnabled(\n current - start,\n end - start,\n action === 'next' ? 1 : -1,\n loop,\n isDisabled && ((i) => isDisabled(start + i)),\n );\n return target === null ? null : start + target;\n }\n case 'next-row':\n case 'prev-row': {\n const direction = action === 'next-row' ? 1 : -1;\n const col = colOf(current);\n let row = rowOf(current) + direction;\n for (let visited = 0; visited < totalRows; visited++) {\n if (row < 0 || row >= totalRows) {\n if (!loop) {\n return null;\n }\n row = ((row % totalRows) + totalRows) % totalRows;\n }\n const candidateRowStart = row * cols;\n const candidateRowEnd = Math.min(candidateRowStart + cols, count);\n // Try the same column; if missing in last partial row, fall back to row's last cell.\n const target =\n candidateRowStart + col < candidateRowEnd ? candidateRowStart + col : candidateRowEnd - 1;\n if (target === current) {\n return null;\n }\n if (!isDisabled || !isDisabled(target)) {\n return target;\n }\n row += direction;\n }\n return null;\n }\n default:\n return null;\n }\n}\n\n/** A horizontal-arrow intent to expand or collapse a treegrid parent row. */\nexport type ExpandCollapseAction = 'expand' | 'collapse';\n\n/**\n * Maps a horizontal arrow keydown to an expand/collapse intent for a treegrid,\n * RTL-mirrored: ArrowRight expands (collapses in `rtl`), ArrowLeft collapses\n * (expands in `rtl`). Returns `null` for any other key, and for an arrow held\n * with Alt or Meta. The caller decides whether the intent actually applies (row\n * is an expandable parent in the right open/closed state) and otherwise falls\n * through to grid navigation.\n */\nexport function resolveTreegridExpandCollapse(\n event: KeyboardEvent,\n dir: WritingDirection = 'ltr',\n): ExpandCollapseAction | null {\n if (isHistoryChord(event)) {\n return null;\n }\n if (event.key === 'ArrowRight') {\n return dir === 'rtl' ? 'collapse' : 'expand';\n }\n if (event.key === 'ArrowLeft') {\n return dir === 'rtl' ? 'expand' : 'collapse';\n }\n return null;\n}\n\nexport interface TreeExpandCollapseOptions {\n /** Navigation axis of the tree. */\n orientation: ListOrientation;\n /** Reading direction. RTL swaps ArrowLeft/ArrowRight. Default `'ltr'`. */\n dir?: WritingDirection;\n}\n\n/**\n * Maps an arrow keydown to an expand/collapse intent for a `tree` (APG Tree\n * View), spanning both orientations. In a vertical tree the horizontal arrows\n * drive expansion (RTL-mirrored via {@link resolveTreegridExpandCollapse}); in\n * a horizontal tree ArrowDown expands and ArrowUp collapses. Returns `null` for\n * any other key, and for an arrow held with Alt or Meta. The caller decides\n * whether the intent actually applies (the focused node is an expandable parent\n * in the right open/closed state) and otherwise falls through to list\n * navigation.\n */\nexport function resolveTreeExpandCollapse(\n event: KeyboardEvent,\n options: TreeExpandCollapseOptions,\n): ExpandCollapseAction | null {\n if (isHistoryChord(event)) {\n return null;\n }\n const { orientation, dir = 'ltr' } = options;\n if (orientation === 'vertical') {\n return resolveTreegridExpandCollapse(event, dir);\n }\n if (event.key === 'ArrowDown') {\n return 'expand';\n }\n if (event.key === 'ArrowUp') {\n return 'collapse';\n }\n return null;\n}\n\nfunction scanFirstEnabled(\n start: number,\n count: number,\n step: number,\n isDisabled: ((i: number) => boolean) | undefined,\n): number | null {\n for (let i = start; i >= 0 && i < count; i += step) {\n if (!isDisabled || !isDisabled(i)) {\n return i;\n }\n }\n return null;\n}\n\nfunction scanFirstEnabledInRange(\n start: number,\n end: number,\n step: number,\n isDisabled: ((i: number) => boolean) | undefined,\n): number | null {\n for (let i = start; step > 0 ? i < end : i > end; i += step) {\n if (!isDisabled || !isDisabled(i)) {\n return i;\n }\n }\n return null;\n}\n\nfunction scanNextEnabled(\n current: number,\n count: number,\n step: number,\n loop: boolean,\n isDisabled: ((i: number) => boolean) | undefined,\n): number | null {\n if (loop && current < 0 && step < 0) {\n current = count;\n }\n for (let visited = 1; visited <= count; visited++) {\n let candidate = current + step * visited;\n if (candidate < 0 || candidate >= count) {\n if (!loop) {\n return null;\n }\n candidate = ((candidate % count) + count) % count;\n }\n if (candidate === current) {\n return null;\n }\n if (!isDisabled || !isDisabled(candidate)) {\n return candidate;\n }\n }\n return null;\n}\n","import type { Signal } from '@angular/core';\n\nimport { type ListNavigationAction, moveIndex } from '../keyboard-navigation/keyboard-navigation';\nimport type { CollectionHandle } from './collection';\n\n/**\n * Collection handle that also exposes a `disabled` signal. Required input\n * shape for {@link firstEnabledHandle}, {@link lastEnabledHandle} and\n * {@link nextEnabledHandle}.\n */\nexport interface DisableableHandle extends CollectionHandle {\n /**\n * Narrowed from {@link CollectionHandle}'s `Node`: the navigators here hand\n * the host back to callers that focus it and compare it against\n * `document.activeElement`, so a disableable handle owes an element.\n */\n readonly host: HTMLElement;\n readonly disabled: Signal<boolean>;\n}\n\n/**\n * Returns the first non-disabled handle in `items`, or `null` if every handle\n * is disabled (or the list is empty). Iteration follows the order of the input\n * array — pass `Collection.items()` to get DOM document order.\n *\n * Callers that only need the element take {@link firstEnabledHost}; this one is\n * for the callers that act on the handle itself (the menu item list arms the\n * item's one-shot highlight suppression before focusing it).\n */\nexport function firstEnabledHandle<H extends DisableableHandle>(items: readonly H[]): H | null {\n for (const item of items) {\n if (!item.disabled()) {\n return item;\n }\n }\n return null;\n}\n\n/**\n * Returns the last non-disabled handle in `items`, or `null` if every handle is\n * disabled (or the list is empty). The reverse twin of\n * {@link firstEnabledHandle}, scanning from the end of the input array.\n */\nexport function lastEnabledHandle<H extends DisableableHandle>(items: readonly H[]): H | null {\n for (let i = items.length - 1; i >= 0; i--) {\n const item = items[i];\n if (item && !item.disabled()) {\n return item;\n }\n }\n return null;\n}\n\n/**\n * Returns the host element of the first non-disabled handle in `items`, or\n * `null` if every handle is disabled (or the list is empty). Iteration\n * follows the order of the input array — pass `Collection.items()` to get\n * DOM document order.\n *\n * Used by primitives that pick a roving-tabindex entry point: when there's\n * no selection, the first enabled child becomes the tab stop.\n */\nexport function firstEnabledHost<H extends DisableableHandle>(\n items: readonly H[],\n): HTMLElement | null {\n return firstEnabledHandle(items)?.host ?? null;\n}\n\n/**\n * Returns the host element of the last non-disabled handle in `items`, or\n * `null` if every handle is disabled (or the list is empty). The reverse twin\n * of {@link firstEnabledHost}, for the overlays whose End / `'last'` initial\n * focus lands on the bottom of the collection.\n */\nexport function lastEnabledHost<H extends DisableableHandle>(\n items: readonly H[],\n): HTMLElement | null {\n return lastEnabledHandle(items)?.host ?? null;\n}\n\n/** Options for {@link nextEnabledHandle}. */\nexport interface NextEnabledHandleOptions {\n /** Wrap around at the ends. Default `false`. */\n loop?: boolean;\n}\n\n/**\n * Resolves the handle a 1D list-navigation action lands on, skipping disabled\n * items. Generalizes the \"find the current index → `moveIndex` → bail →\n * resolve the handle\" walk that every roving / activedescendant list navigator\n * repeats verbatim, so each caller keeps only its own focus-vs-activedescendant\n * tail.\n *\n * `current` may be the currently focused/active host element or an explicit\n * index. When a host is passed it is located via its `host` property; a host\n * not present in `items` is treated as index `0` (navigation starts from the\n * top), matching the `currentIndex < 0 ? 0 : currentIndex` clamp the call\n * sites used. When an index is passed it is used verbatim (no clamp), so\n * callers that compute the index themselves — e.g. an activedescendant lookup\n * by id, or a value-based lookup — keep full control, including a deliberate\n * `-1` for \"nothing active yet\".\n *\n * Returns the resolved handle, or `null` when the list is empty or no enabled\n * target exists in the requested direction.\n */\nexport function nextEnabledHandle<H extends DisableableHandle>(\n items: readonly H[],\n current: HTMLElement | number,\n action: ListNavigationAction,\n options: NextEnabledHandleOptions = {},\n): H | null {\n if (items.length === 0) {\n return null;\n }\n let currentIndex: number;\n if (typeof current === 'number') {\n currentIndex = current;\n } else {\n const found = items.findIndex((item) => item.host === current);\n currentIndex = found < 0 ? 0 : found;\n }\n const next = moveIndex(currentIndex, items.length, action, {\n loop: options.loop ?? false,\n isDisabled: (i) => items[i]!.disabled(),\n });\n return next === null ? null : (items[next] ?? null);\n}\n","import { computed, type Signal } from '@angular/core';\n\n/**\n * Pure helpers backing the array-modeled selection contract of `Select`,\n * `Listbox`, and `Combobox` — the form-value selection primitives whose value\n * is a generic `readonly T[]` with equality-aware membership. They encode the\n * shape those three share: equality-aware membership, an immutable\n * multi-toggle, the default form-value serializer, and the single-mode derived\n * view. No DOM access, no DI, no state — those primitives compose them inside\n * their own selection logic, and the shared definition keeps a fix from\n * drifting across the three copies.\n *\n * Scope note: these helpers are NOT a universal selection contract. `ForTree`\n * composes the two membership helpers but keeps its own select / expand /\n * extend-by-arrow logic. `Accordion` and `ToggleGroup` manage their arrays\n * directly, because their value semantics (string keys, no equality comparator,\n * no single-mode `T | null` view) differ.\n */\n\nexport const defaultCompareWith = <T>(a: T, b: T): boolean => a === b;\n\nexport function membership<T>(\n values: readonly T[],\n equals: (a: T, b: T) => boolean,\n): (value: T) => boolean {\n if (equals === defaultCompareWith) {\n const hashed = new Set(values);\n return (value) => hashed.has(value);\n }\n return (value) => values.some((candidate) => equals(candidate, value));\n}\n\nexport function selectionMembership<T>(\n value: Signal<readonly T[]>,\n compareWith: Signal<(a: T, b: T) => boolean>,\n): Signal<(value: T) => boolean> {\n return computed(() => membership(value(), compareWith()));\n}\n\nexport function lookupByValue<E, T>(\n entries: readonly E[],\n valueOf: (entry: E) => T,\n equals: (a: T, b: T) => boolean,\n): (value: T) => E | undefined {\n if (equals === defaultCompareWith) {\n const byValue = new Map<T, E>();\n for (const entry of entries) {\n const value = valueOf(entry);\n if (!byValue.has(value)) {\n byValue.set(value, entry);\n }\n }\n return (value) => byValue.get(value);\n }\n return (value) => entries.find((entry) => equals(valueOf(entry), value));\n}\n\nexport function appendMissing<T>(\n current: readonly T[],\n added: readonly T[],\n equals: (a: T, b: T) => boolean,\n): T[] {\n const next = [...current];\n if (equals === defaultCompareWith) {\n const seen = new Set(current);\n for (const value of added) {\n if (!seen.has(value)) {\n seen.add(value);\n next.push(value);\n }\n }\n return next;\n }\n for (const value of added) {\n if (!next.some((candidate) => equals(candidate, value))) {\n next.push(value);\n }\n }\n return next;\n}\n\nexport function dedupeValues<T>(values: readonly T[], equals: (a: T, b: T) => boolean): T[] {\n return appendMissing([], values, equals);\n}\n\n/**\n * Returns `true` when `current` contains an element equal to `v` under the\n * supplied `equals` comparator. Backs each primitive's `isSelected(v)`.\n */\nexport function isInArray<T>(\n current: readonly T[],\n v: T,\n equals: (a: T, b: T) => boolean,\n): boolean {\n return current.some((x) => equals(x, v));\n}\n\n/**\n * Immutable multi-select toggle: returns a new array with `v` removed when an\n * equal element is already present, otherwise appended. Never mutates\n * `current`, so the result is safe to `set()` straight into a\n * `model<readonly T[]>`. Backs the multi-mode branch of each primitive's\n * `activate()`.\n */\nexport function toggleInArray<T>(\n current: readonly T[],\n v: T,\n equals: (a: T, b: T) => boolean,\n): T[] {\n return current.some((x) => equals(x, v)) ? current.filter((x) => !equals(x, v)) : [...current, v];\n}\n\n/**\n * Default `itemToFormValue` serializer for the hidden input that participates\n * in native form submission: identity for strings, `JSON.stringify` for any\n * other item so the primitive round-trips objects out of the box. Consumers\n * override per primitive when the backend expects a specific wire format.\n */\nexport function defaultItemToFormValue<T>(item: T): string {\n return typeof item === 'string' ? item : JSON.stringify(item);\n}\n\n/**\n * Builds the read-only single-select convenience view derived from an\n * array-backed value signal. Returns the sole element when exactly one is\n * selected (regardless of `multiple`), otherwise `null` (zero, or 2+\n * selected). A pure `computed()` — the array model stays the source of truth.\n * Backs `ForSelect.selected` / `ForListbox.selected` and\n * `ForCombobox.selectedItem`.\n */\nexport function singleSelected<T>(value: Signal<readonly T[]>): Signal<T | null> {\n return computed<T | null>(() => {\n const values = value();\n return values.length === 1 ? values[0]! : null;\n });\n}\n","const CODE_PREFIX = 'FORCDK-';\n\n/**\n * The four pieces every developer-facing message in the library is built from.\n *\n * `code` is the stable identity; `scope` only ever differs from the area the\n * code carries when a shared helper reports on behalf of a primitive it\n * resolves at runtime.\n */\nexport interface FortyMessageSpec {\n /**\n * Stable `FORCDK-<AREA>-<NNN>` identifier. Never reused for a second meaning:\n * a code names one concrete failure for as long as that failure exists.\n */\n readonly code: string;\n /** What is wrong, in one sentence, in the consumer's vocabulary. */\n readonly message: string;\n /** Why it happens — omitted when the message already says it. */\n readonly cause?: string;\n /** The concrete action that resolves it — omitted when there is no single action. */\n readonly fix?: string;\n /**\n * Entry-point name for the `[forty-cdk/<scope>]` prefix. Derived from\n * `code`'s area when omitted, which is what every call site outside\n * `forty-cdk/core` wants.\n */\n readonly scope?: string;\n}\n\n/** The entry-point name a code's area spells, e.g. `FORCDK-DATE-PICKER-001` → `date-picker`. */\nfunction scopeOf(code: string): string {\n const end = code.lastIndexOf('-');\n if (!code.startsWith(CODE_PREFIX) || end <= CODE_PREFIX.length) {\n return 'core';\n }\n return code.slice(CODE_PREFIX.length, end).toLowerCase();\n}\n\n/**\n * Renders a {@link FortyMessageSpec} into the library's one message layout:\n *\n * ```text\n * [forty-cdk/dialog] FORCDK-DIALOG-001: ForDialogTitle must be used inside a [forDialog] element.\n *\n * Cause: No FOR_DIALOG_CONTEXT provider is visible from ForDialogTitle.\n *\n * Fix: Move ForDialogTitle inside a [forDialog] element.\n * ```\n *\n * The first line is self-sufficient — prefix, code and what went wrong — so a\n * consumer skimming a stack trace, and a search for the code, both land on it.\n * `Cause` and `Fix` are appended only when supplied.\n *\n * The layout {@link fortyError}, {@link fortyWarn} and the shape helpers in\n * `orphan-context.ts` all build on. Module-local to `forty-cdk/core`: no\n * caller outside this entry point formats a message itself.\n */\nexport function formatFortyMessage(spec: FortyMessageSpec): string {\n const scope = spec.scope ?? scopeOf(spec.code);\n let out = `[forty-cdk/${scope}] ${spec.code}: ${spec.message}`;\n if (spec.cause) {\n out += `\\n\\nCause: ${spec.cause}`;\n }\n if (spec.fix) {\n out += `\\n\\nFix: ${spec.fix}`;\n }\n return out;\n}\n\n/**\n * Builds the `Error` a primitive throws for a developer mistake. Call sites\n * keep the `throw` so the control flow stays visible to a reader and to\n * TypeScript's reachability analysis:\n *\n * ```ts\n * throw fortyError({ code: 'FORCDK-DRAWER-004', message: '…', fix: '…' });\n * ```\n *\n * This helper does **not** gate on dev mode. Whether a given check is\n * dev-only is a property of the check, not of the formatting — an orphan\n * context would fail with a bare `TypeError` one line later in production, so\n * those throw unconditionally, while a pure assertion gates inside its own\n * `assert*` / `throw*` helper as `.claude/rules/conventions.md` requires.\n */\nexport function fortyError(spec: FortyMessageSpec): Error {\n return new Error(formatFortyMessage(spec));\n}\n\n/**\n * Reports a developer mistake the library can recover from, in the same layout\n * as {@link fortyError}. Dev mode only — a warning's whole audience is the\n * developer, so the gate travels with the report and no call site can forget it.\n */\nexport function fortyWarn(spec: FortyMessageSpec): void {\n if (typeof ngDevMode !== 'undefined' && !ngDevMode) {\n return;\n }\n console.warn(formatFortyMessage(spec));\n}\n","import { effect, type Signal } from '@angular/core';\nimport { fortyError } from '../errors/errors';\n\nconst UNSET: unique symbol = Symbol('forty-cdk:unset-input');\n\n/**\n * The type of the {@link unsetInput} sentinel. A signal typed `T | Unset`\n * belongs to a piece whose binding may not be written yet; narrow it with\n * {@link isUnset} before the value is used as a `T`.\n */\nexport type Unset = typeof UNSET;\n\n/**\n * The sentinel a piece seeds an otherwise-required input with, typed\n * `T | Unset` so every read site has to narrow with {@link isUnset} before it\n * uses the value.\n *\n * A piece registers with its parent during the content view's *creation* pass\n * and has its binding written in that view's *update* pass, so any parent\n * lookup running in between reads a value the consumer has not supplied yet.\n * `input.required` answers that read by throwing, which forced every such\n * lookup through a `try` / `catch` keyed on an Angular error code; seeding a\n * plain `input()` with this sentinel answers it with a value instead, and the\n * lookup becomes an identity comparison ({@link isUnset}).\n *\n * The sentinel is a module-private `symbol`, so it can never collide with a\n * consumer value — which `undefined` can, on the roots generic over an\n * unconstrained `T`. Never let the sentinel reach a consumer callback\n * (`compareWith`, `itemToLabel`, …): guard with {@link isUnset} before the\n * value leaves the read site.\n *\n * The read is still tracked — Angular's input signal registers itself as a\n * producer before it resolves a value — so the binding's write marks the\n * reader dirty and the piece folds in on the run that follows.\n *\n * @example\n * ```ts\n * readonly value: InputSignal<T | Unset> = input(unsetInput<T>());\n * ```\n */\nexport function unsetInput<T>(): T | Unset {\n return UNSET;\n}\n\n/**\n * Whether `value` is the {@link unsetInput} sentinel — i.e. the piece's binding\n * has not been written yet. Compare before the value leaves the read site; a\n * `false` result means the value is a genuine `T`, including `null`,\n * `undefined`, or any other value a consumer's domain may contain.\n */\nexport function isUnset(value: unknown): value is Unset {\n return value === UNSET;\n}\n\n/** A handle paired with the value read from it, known not to be {@link Unset}. */\nexport interface BoundEntry<H, T> {\n readonly handle: H;\n readonly value: T;\n}\n\n/**\n * The handles whose binding is written, each paired with the value that was\n * read to decide it. A fold downstream of the filter reads `entry.value` as a\n * `T` instead of calling the signal again, which the compiler cannot narrow.\n */\nexport function boundEntries<H, T>(\n handles: readonly H[],\n valueOf: (handle: H) => T | Unset,\n): BoundEntry<H, T>[] {\n const entries: BoundEntry<H, T>[] = [];\n for (const handle of handles) {\n const value = valueOf(handle);\n if (!isUnset(value)) {\n entries.push({ handle, value });\n }\n }\n return entries;\n}\n\n/**\n * Dev-mode guard that a piece seeded with {@link unsetInput} actually had its\n * binding written. Call it from the piece's constructor.\n *\n * Seeding the sentinel makes the input optional to Angular's template type\n * checker, so a consumer who omits the binding no longer gets a compile-time\n * error — and, because every parent lookup now skips an unset piece instead of\n * throwing, the piece would otherwise stay silently invisible to its parent.\n * This restores the loud failure, in the library's own vocabulary and naming\n * both the piece and the input.\n *\n * The check runs in an `effect`, which is the first point at which the update\n * pass has written the binding, and only in dev mode — a production build\n * creates no reactive node per piece.\n *\n * @param value The piece's input signal.\n * @param primitive Entry-point name for the error prefix, e.g. `'listbox'`.\n * @param piece Selector of the piece the error names, e.g. `'[forListboxOption]'`.\n * @param inputName Name of the unbound input, e.g. `'value'`.\n */\nexport function assertInputBound<T>(\n value: Signal<T>,\n primitive: string,\n piece: string,\n inputName: string,\n): void {\n if (typeof ngDevMode !== 'undefined' && !ngDevMode) {\n return;\n }\n effect(() => {\n if (isUnset(value())) {\n throw fortyError({\n code: 'FORCDK-CORE-010',\n scope: primitive,\n message: `${piece} has no [${inputName}] binding.`,\n cause:\n 'The input is declared optional so the parent can skip a piece whose binding is not ' +\n 'written yet, which means a permanently unbound piece never joins its parent instead ' +\n 'of failing to compile.',\n fix: `Bind [${inputName}] on every ${piece}.`,\n });\n }\n });\n}\n","import { computed, linkedSignal, type Signal } from '@angular/core';\n\nimport { lookupByValue } from '../selection/selection';\nimport { isUnset, type Unset } from '../unset-input/unset-input';\n\n/**\n * Minimal option-handle shape a {@link LabelCache} reads. Every member is a\n * `Signal` so the cache never peeks at `textContent` — a handle carrying extra\n * members (`posInSet`, `host`, …) satisfies it structurally.\n */\nexport interface LabelCacheHandle<T> {\n /** Stable host `id` — the activedescendant target in the virtualized path. */\n readonly id: Signal<string>;\n /** The option's underlying value, or {@link Unset} before its binding is written. */\n readonly value: Signal<T | Unset>;\n /** The option's resolved display label. */\n readonly label: Signal<string>;\n /** The option's typeahead override, `''` when unset. Absent on a handle that never carries one. */\n readonly textValue?: Signal<string>;\n /** Whether the option is disabled. */\n readonly disabled: Signal<boolean>;\n}\n\n/**\n * One cached option tuple. The superset both consumers need: the stable id\n * (activedescendant / off-window resolution), the underlying value, the resolved\n * label string, and the `disabled` flag so inline autocomplete can skip disabled\n * options that are no longer rendered.\n */\nexport interface LabelCacheEntry<T> {\n readonly id: string;\n readonly value: T;\n readonly label: string;\n /** The handle's typeahead override when it carries one, so a closed-state matcher can prefer it. */\n readonly textValue?: string;\n readonly disabled: boolean;\n}\n\n/** Tracked source of the window store: the live handles and the key fn. */\ninterface WindowSource<T> {\n readonly items: readonly LabelCacheHandle<T>[];\n readonly toFormValue: (item: T) => string;\n}\n\n/** Tracked source of the selection store: the window store, the selection, and the comparator. */\ninterface SelectionSource<T> {\n readonly window: readonly LabelCacheEntry<T>[];\n readonly value: readonly T[];\n readonly compareWith: (a: T, b: T) => boolean;\n}\n\n/**\n * Dependencies of a {@link LabelCache}. Plain signals — the cache never injects\n * a primitive's context token, so both roots construct it from their own\n * registries.\n */\nexport interface LabelCacheDeps<T> {\n /** Live registered option handles. The same signal the root exposes. */\n readonly items: Signal<readonly LabelCacheHandle<T>[]>;\n /** The root's selection model, so selected labels survive an unmount. */\n readonly value: Signal<readonly T[]>;\n /** Serializes an item to the key the window store is de-duplicated by. */\n readonly itemToFormValue: Signal<(item: T) => string>;\n /** The root's equality comparator, which matches a selected value to its cached entry. */\n readonly compareWith: Signal<(a: T, b: T) => boolean>;\n}\n\nconst EMPTY_WINDOW = new Map<string, LabelCacheEntry<never>>();\n\n/**\n * Bounded option-label cache shared by `[forSelect]` and `[forCombobox]`. Both roots must resolve\n * labels for options that are not mounted, since the live registry is empty whenever the consumer's\n * `@if` unmounts the listbox, and neither may retain every option it has ever seen.\n *\n * Two projections, each bounded by a different quantity:\n *\n * - {@link selectedEntries} carries the currently selected values, so the select value, the\n * combobox chips and the combobox input label keep resolving after the options unmount. A value\n * that leaves the selection leaves the cache with it.\n * - {@link windowEntries} carries the most recent non-empty option window, replaced rather than\n * merged, and backs the closed-state typeahead and inline completion matchers. Because it is\n * replaced, an option removed while the listbox was open is gone from the next window.\n *\n * They are separate `linkedSignal`s so a commit of `value` rebuilds the selection map alone instead\n * of re-reading every handle in the window.\n *\n * Replacing rather than merging bounds the window to the rendered slice, so a virtualized\n * closed-state match only sees the last window. Neither projection consults a virtualized position\n * map: a value entering the selection while its option sits outside the current window resolves\n * only if an earlier window cached it, and the caller owns that fallback.\n *\n * Constructed once per root. Never surfaced on a primitive's public context.\n */\nexport class LabelCache<T> {\n readonly #windowByKey: Signal<ReadonlyMap<string, LabelCacheEntry<T>>>;\n\n readonly #selectedEntries: Signal<readonly LabelCacheEntry<T>[]>;\n\n readonly #windowEntries: Signal<readonly LabelCacheEntry<T>[]>;\n\n constructor(deps: LabelCacheDeps<T>) {\n this.#windowByKey = linkedSignal<WindowSource<T>, ReadonlyMap<string, LabelCacheEntry<T>>>({\n source: () => ({ items: deps.items(), toFormValue: deps.itemToFormValue() }),\n computation: ({ items, toFormValue }, prev) =>\n items.length === 0 ? (prev?.value ?? EMPTY_WINDOW) : readWindow(items, toFormValue),\n });\n this.#windowEntries = computed(() => [...this.#windowByKey().values()]);\n this.#selectedEntries = linkedSignal<SelectionSource<T>, readonly LabelCacheEntry<T>[]>({\n source: () => ({\n window: this.#windowEntries(),\n value: deps.value(),\n compareWith: deps.compareWith(),\n }),\n computation: ({ window, value, compareWith }, prev) => {\n const inWindow = lookupByValue(window, (entry) => entry.value, compareWith);\n const carried = lookupByValue(prev?.value ?? [], (entry) => entry.value, compareWith);\n const selected: LabelCacheEntry<T>[] = [];\n for (const item of value) {\n const entry = inWindow(item) ?? carried(item);\n if (entry !== undefined) {\n selected.push(entry);\n }\n }\n return selected;\n },\n });\n }\n\n /**\n * Pull both stores so they observe the mounted options. Called from a\n * dedicated read-only effect on the root, never from one that also writes:\n * pulling the cache tracks the selection, and an effect that writes\n * activedescendant must not re-run on every commit of `value`.\n *\n * This read is the one thing the cache cannot derive for itself: the option\n * window is transient, and a lazy computation only ever sees the source as it\n * stands when something reads it. `selectedEntries` is pulled naturally — by\n * whatever renders the selected label — but the window store has no such\n * reader during the open cycle, so a consumer who renders no selected label\n * (or none yet) would leave it empty and the closed-state matchers with\n * nothing to match against. The selection store is pulled here too so its\n * carried-over entries are captured while the option that owns each selected\n * value is still in the window. A read, not a write: forcing a lazy derivation\n * to run is a side effect, not state propagation.\n */\n prime(): void {\n this.#windowByKey();\n this.#selectedEntries();\n }\n\n /**\n * Cached entries for the currently selected values, in selection order. A\n * selected value with no cached entry is absent rather than represented — the\n * caller owns the fallback (a consumer `itemToLabel`, else the serialized\n * value).\n */\n selectedEntries(): readonly LabelCacheEntry<T>[] {\n return this.#selectedEntries();\n }\n\n /**\n * The most recent non-empty option window, in DOM order and de-duplicated by\n * serialized form value. Drives the closed-state matchers; empty until the\n * first window is observed.\n */\n windowEntries(): readonly LabelCacheEntry<T>[] {\n return this.#windowEntries();\n }\n}\n\nfunction readWindow<T>(\n items: readonly LabelCacheHandle<T>[],\n toFormValue: (item: T) => string,\n): ReadonlyMap<string, LabelCacheEntry<T>> {\n const byKey = new Map<string, LabelCacheEntry<T>>();\n for (const item of items) {\n const id = item.id();\n const value = item.value();\n if (isUnset(value)) {\n continue;\n }\n byKey.set(toFormValue(value), {\n id,\n value,\n label: item.label(),\n textValue: item.textValue?.(),\n disabled: item.disabled(),\n });\n }\n return byKey;\n}\n","import { Injectable, inject } from '@angular/core';\n\nimport { FOR_ID_SALT } from 'forty-cdk/id-salt';\n\nimport { fortyError } from '../errors/errors';\n\n/**\n * Generates unique string IDs scoped to the application instance.\n *\n * Backs the `aria-controls` / `aria-labelledby` wiring between a primitive's pieces. Ids are stable\n * for the lifetime of the instance that minted them.\n *\n * Scoped to the application injector, so each bootstrap — and each SSR request — starts a fresh\n * counter. Ids are salted with {@link FOR_ID_SALT}, defaulting to `APP_ID`, so a server and client\n * render of the same order produce identical strings.\n *\n * Because the counter is monotonic, that agreement is a property of the render order rather than of\n * any single id. Ordinary hydration replays the server's order; incremental hydration does not, so\n * an id minted by a deferred root for a piece that is still dehydrated can keep a drifted value.\n * Keeping a primitive's pieces in one hydration unit avoids it, and is documented for consumers\n * under \"Incremental hydration\" in the `forty-cdk/shared` README.\n *\n * Mounting several apps on one page requires a distinct salt per app via `provideForIdSalt`,\n * or they emit colliding ids.\n */\n@Injectable({ providedIn: 'root' })\nexport class IdGenerator {\n readonly #salt = inject(FOR_ID_SALT);\n #counter = 0;\n\n /**\n * Returns a fresh, unique ID with the given prefix. In dev mode, throws when the salt contains\n * whitespace.\n *\n * @param prefix Optional prefix for the generated ID. Defaults to `for`.\n */\n next(prefix = 'for'): string {\n assertIdSalt(this.#salt);\n return `${prefix}-${this.#salt}-${++this.#counter}`;\n }\n}\n\nfunction assertIdSalt(salt: string): void {\n if ((typeof ngDevMode === 'undefined' || ngDevMode) && /\\s/.test(salt)) {\n throw fortyError({\n code: 'FORCDK-CORE-012',\n message: `The id salt \"${salt}\" contains whitespace.`,\n cause:\n 'Generated ids are referenced from aria-labelledby, aria-controls and aria-describedby, ' +\n 'which are space-separated id lists, so an id with a space in it resolves to two ids ' +\n 'that do not exist.',\n fix: 'Pass provideForIdSalt() (or FOR_ID_SALT) a salt without whitespace, e.g. \"admin-panel\".',\n });\n }\n}\n","import { ElementRef, inject, signal, type Signal, type WritableSignal } from '@angular/core';\n\nimport { IdGenerator } from '../id-generator/id-generator';\n\n/**\n * Resolves the id a piece should expose: the host element's pre-existing\n * **static** `id` when present, else a freshly generated `<prefix>-*` id.\n *\n * The generated id is always produced (advancing the {@link IdGenerator}\n * counter) even when a host id is adopted, so the per-app id sequence stays\n * deterministic across renders regardless of which hosts carry a consumer id —\n * a server and client render of the same template adopt identically, so\n * hydration still agrees.\n *\n * Only **static** ids (written in the template, present on the element at\n * directive construction) are visible here. A consumer `[id]=\"expr\"` property\n * binding evaluates after construction, so it is not adopted — and still\n * fights the `[id]` host binding.\n *\n * Must be invoked in an injection context.\n *\n * @param host The directive's host element, or `null` to always generate (e.g.\n * when the owning helper resolved `ElementRef` optionally and found none).\n * @param prefix Prefix for the generated fallback id.\n */\nexport function resolveHostId(host: HTMLElement | null, prefix: string): string {\n const generated = inject(IdGenerator).next(prefix);\n return host?.getAttribute('id') || generated;\n}\n\n/**\n * Adopt a host element's pre-existing **static** `id` into `idSignal`. A no-op\n * when the host has no `id`, leaving the signal's generated fallback in place.\n *\n * The canonical shape for the \"context-owned id\" pieces (overlay\n * trigger / content, form-field control): the owning root seeds `idSignal`\n * with a generated id at construction, then calls this from its\n * `register…(el)` method so a consumer-set `id` on the registered host is\n * preserved and re-emitted by the `[id]` host binding — external references\n * (anchors, `aria-labelledby`, label `for`, test hooks) keep resolving.\n *\n * Only **static** ids are adopted; see {@link resolveHostId} for the\n * static-only boundary.\n *\n * @param host The element whose static `id` should be adopted.\n * @param idSignal The writable id signal to adopt into.\n */\nexport function adoptHostId(host: HTMLElement, idSignal: WritableSignal<string>): void {\n const existing = host.getAttribute('id');\n if (existing) {\n idSignal.set(existing);\n }\n}\n\nexport function staticHostId(host: HTMLElement): string | null {\n return host.getAttribute('id') || null;\n}\n\n/**\n * Convenience for the \"piece owns its own id\" pieces: seeds a read-only id\n * signal from the host element's pre-existing static `id`, falling back to a\n * freshly generated `<prefix>-*` id.\n *\n * The piece's `[id]` host binding therefore re-emits a consumer-set static id\n * instead of clobbering it. Must be invoked in an injection context.\n *\n * @param prefix Prefix for the generated fallback id.\n */\nexport function hostId(prefix: string): Signal<string> {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n return signal(resolveHostId(host, prefix)).asReadonly();\n}\n","import { afterNextRender, DestroyRef, ElementRef, inject } from '@angular/core';\n\nimport { resolveHostId } from '../host-attributes/host-id';\n\n/**\n * Scheduling for the `register` call.\n *\n * - `'sync'` (default) — register inside the directive's constructor, at\n * directive-construction time. Matches what most callsites do today.\n * - `'afterNextRender'` — defer the `register` call to `afterNextRender`, so the parent's lookups\n * can read the handle's mandatory signals without hitting an unbound `input.required`.\n *\n * The hook never fires in a server render, so a deferred registration is invisible to SSR. Prefer\n * `'sync'` with `unsetInput` seeding and an `isUnset`-guarded lookup whenever the registration\n * drives markup the pre-hydration DOM needs; `'afterNextRender'` is only safe for a piece that\n * emits no registration-derived markup.\n *\n * `unregister` always runs eagerly via `DestroyRef.onDestroy`, so destroy-before-register is a safe\n * no-op as long as it is reference-based.\n */\nexport type RegistrationScheduling = 'sync' | 'afterNextRender';\n\n/**\n * Registers `target` with an owning parent on construction and unregisters it on destroy.\n *\n * Works for any target shape — object handles, raw elements, id strings — since it only hands the\n * value back to the supplied callbacks.\n *\n * Must be invoked in an injection context.\n *\n * @param target The value to register. Passed verbatim to both callbacks.\n * @param register Registers the target with the owning parent.\n * @param unregister Called from `DestroyRef.onDestroy`. Must be reference-based and tolerant of\n * running before `register` ever did, which happens when a deferred registration is destroyed\n * before its render fires.\n * @param scheduling When the `register` callback runs. Defaults to `'sync'`.\n */\nexport function registerHandle<T>(\n target: T,\n register: (target: T) => void,\n unregister: (target: T) => void,\n scheduling: RegistrationScheduling = 'sync',\n): void {\n if (scheduling === 'afterNextRender') {\n afterNextRender(() => register(target));\n } else {\n register(target);\n }\n inject(DestroyRef).onDestroy(() => unregister(target));\n}\n\n/**\n * Owner contract for {@link registerA11yName}. The owner is typically the\n * primitive's context object (e.g. `injectDialogContext('ForDialogTitle')`)\n * or the parent directive instance — duck-typed so cross-primitive code\n * reuse doesn't force a shared base type.\n */\nexport interface A11yLabelOwner {\n registerLabel(id: string): void;\n unregisterLabel(id: string): void;\n}\n\n/**\n * Owner contract for {@link registerA11yDescription}. See\n * {@link A11yLabelOwner} for the rationale.\n */\nexport interface A11yDescriptionOwner {\n registerDescription(id: string): void;\n unregisterDescription(id: string): void;\n}\n\n/**\n * Resolves a stable `id` for the host element and registers it with the owner's `aria-labelledby`\n * collection. Returns a plain `string` — the id never changes — for host-binding as `'[id]': 'id'`.\n *\n * A consumer-set static `id` is adopted rather than clobbered; see {@link resolveHostId} for the\n * static-only boundary. The host element is read optionally, so the helper falls back to a\n * generated id when invoked outside a directive host context.\n *\n * Must be invoked in an injection context.\n */\nexport function registerA11yName(owner: A11yLabelOwner, prefix: string): string {\n const host =\n inject<ElementRef<HTMLElement>>(ElementRef, { optional: true })?.nativeElement ?? null;\n const id = resolveHostId(host, prefix);\n registerHandle(\n id,\n (myId) => owner.registerLabel(myId),\n (myId) => owner.unregisterLabel(myId),\n );\n return id;\n}\n\n/**\n * Counterpart to {@link registerA11yName} for `aria-describedby`. See that\n * function for the rationale and usage — including the consumer-set static\n * `id` adoption.\n */\nexport function registerA11yDescription(owner: A11yDescriptionOwner, prefix: string): string {\n const host =\n inject<ElementRef<HTMLElement>>(ElementRef, { optional: true })?.nativeElement ?? null;\n const id = resolveHostId(host, prefix);\n registerHandle(\n id,\n (myId) => owner.registerDescription(myId),\n (myId) => owner.unregisterDescription(myId),\n );\n return id;\n}\n","import { computed, effect, type Signal, signal } from '@angular/core';\nimport { fortyWarn } from '../errors/errors';\n\n/**\n * Identifies a {@link SingleSlot} in its dev-mode duplicate-registration\n * warning. All three fields are literals from the adopting primitive, never\n * runtime values.\n */\nexport interface SingleSlotConfig {\n /** Entry-point name used in the `[forty-cdk/<primitive>]` warning prefix (e.g. `'search'`). */\n readonly primitive: string;\n /** Selector of the directive that owns the slot (e.g. `'[forSearchGroup]'`). */\n readonly owner: string;\n /** Selector of the directive that registers into the slot (e.g. `'[forSearch]'`). */\n readonly claimant: string;\n}\n\n/**\n * A registry for a coordination seam that supports exactly one occupant: a\n * root or group directive that must reach a single sibling piece which cannot\n * be its DOM descendant (a void `<input>` next to its buttons, the native file\n * input next to its drop zone).\n *\n * Registrations are **stacked** rather than overwritten, mirroring\n * `ForField`'s counted label / description / error slots: the newest\n * registration is the coordinated one, a duplicate emits a dev-mode warning,\n * and unregistering the newest restores the previous survivor instead of\n * emptying the slot while a piece is still mounted.\n *\n * The warning reads the occupant count once the change-detection pass has\n * settled, so a structural swap that mounts the replacement before destroying\n * the outgoing piece (two sibling `@if` blocks under one owner) is not\n * reported. It fires once each time the slot becomes duplicated, not on every\n * further registration.\n *\n * The helper owns no teardown of its own — pair `register` / `unregister` with\n * the core `registerHandle` helper at the claimant's construction so the\n * claimant's own `DestroyRef` drives unregistration.\n *\n * @typeParam T The occupant type — a context interface, a handle, or a raw\n * element.\n */\nexport interface SingleSlot<T> {\n /**\n * The coordinated occupant: the most recently registered one, or `null`\n * while the slot is empty.\n */\n readonly value: Signal<T | null>;\n /**\n * Register an occupant, making it the coordinated one. A second occupant\n * still registered once the pass settles means the owner's single\n * coordination surface is ambiguous, and warns in dev mode.\n */\n register(occupant: T): void;\n /**\n * Remove a previously registered occupant. A no-op when it never registered,\n * and — because registrations are stacked — a late teardown of a stale\n * occupant never clears a newer one.\n */\n unregister(occupant: T): void;\n}\n\nexport function warnOnDuplicateRegistration(count: () => number, config: SingleSlotConfig): void {\n if (typeof ngDevMode !== 'undefined' && !ngDevMode) {\n return;\n }\n let warned = false;\n effect(() => {\n const registered = count();\n if (registered <= 1) {\n warned = false;\n } else if (!warned) {\n warned = true;\n fortyWarn({\n code: 'FORCDK-CORE-005',\n scope: config.primitive,\n message: `A ${config.owner} coordinates a single ${config.claimant}, but ${registered} are registered.`,\n cause: 'Only the most recently registered one is coordinated; the rest are inert.',\n fix: `Keep one ${config.claimant} per ${config.owner}.`,\n });\n }\n });\n}\n\n/**\n * Creates a {@link SingleSlot}. Must be called in an injection context, which a\n * directive field initializer is, because the dev-mode duplicate warning runs\n * on an `effect`. Safe under SSR.\n */\nexport function createSingleSlot<T>(config: SingleSlotConfig): SingleSlot<T> {\n const occupants = signal<readonly T[]>([]);\n const value = computed<T | null>(() => occupants().at(-1) ?? null);\n\n warnOnDuplicateRegistration(() => occupants().length, config);\n\n return {\n value,\n register(occupant: T): void {\n occupants.set([...occupants(), occupant]);\n },\n unregister(occupant: T): void {\n const current = occupants();\n const index = current.lastIndexOf(occupant);\n if (index < 0) {\n return;\n }\n occupants.set([...current.slice(0, index), ...current.slice(index + 1)]);\n },\n };\n}\n","import { computed, type Signal, signal } from '@angular/core';\n\nexport interface RootedHandle<R> {\n readonly root: Signal<R | null>;\n}\n\nconst NONE: readonly never[] = [];\n\nexport class RootedRegistry<R extends object, H extends RootedHandle<R>> {\n /** Every registered handle, in registration order. Mutated in place; `#version` tracks it. */\n readonly #handles = new Set<H>();\n\n readonly #version = signal(0);\n\n readonly #byRoot = computed(() => {\n this.#version();\n const index = new WeakMap<R, H[]>();\n for (const handle of this.#handles) {\n const root = handle.root();\n if (typeof root !== 'object' || root === null) {\n continue;\n }\n const bucket = index.get(root);\n if (bucket) {\n bucket.push(handle);\n } else {\n index.set(root, [handle]);\n }\n }\n return index;\n });\n\n add(handle: H): void {\n if (!this.#handles.has(handle)) {\n this.#handles.add(handle);\n this.#version.update((version) => version + 1);\n }\n }\n\n remove(handle: H): void {\n if (this.#handles.delete(handle)) {\n this.#version.update((version) => version + 1);\n }\n }\n\n of(root: R): Signal<readonly H[]> {\n return computed(() => this.#byRoot().get(root) ?? NONE, { equal: sameHandles });\n }\n}\n\nfunction sameHandles<H>(a: readonly H[], b: readonly H[]): boolean {\n return a.length === b.length && a.every((handle, index) => handle === b[index]);\n}\n","/**\n * Resolves the element that actually holds focus, descending through open\n * shadow roots.\n *\n * `document.activeElement` reports the shadow **host** while focus sits inside\n * a shadow tree, so any check that compares it against a specific descendant —\n * the focus trap's first / last tabbable, an \"is focus still mine?\" guard —\n * answers about the host instead of about the focused control.\n *\n * A closed shadow root exposes no `activeElement`, so the walk stops at its\n * host: the library resolves through open shadow roots only.\n */\nexport function resolveActiveElement(root: DocumentOrShadowRoot): Element | null {\n let active = root.activeElement;\n while (active?.shadowRoot?.activeElement) {\n active = active.shadowRoot.activeElement;\n }\n return active;\n}\n\n/**\n * Resolves the effective target of an interaction event for containment\n * checks. Prefers `composedPath()[0]` so a pointer-down / focus inside a shadow\n * tree reports the real originating node rather than the shadow host the event\n * was retargeted to. Falls back to `event.target` in environments without\n * `composedPath`.\n */\nexport function resolveEventTarget(event: Event): Node | null {\n const path = event.composedPath?.();\n const first = path && path.length > 0 ? path[0] : null;\n return (first ?? event.target) as Node | null;\n}\n\n/**\n * Whether `node` sits inside `container` in the composed tree: native\n * `contains`, plus a walk up through every open shadow boundary between the\n * two.\n *\n * `Node.contains` answers within a single node tree, so it reports `false` for\n * a node inside a shadow root nested in `container` — which is what makes\n * {@link resolveEventTarget} unsafe on its own: the deep target it resolves is\n * exactly the one plain containment then disowns, turning a press on a web\n * component inside an overlay into an outside-dismissal.\n */\nexport function composedContains(container: Node, node: Node | null): boolean {\n let current = node;\n while (current) {\n if (container.contains(current)) {\n return true;\n }\n current = shadowHostOf(current);\n }\n return false;\n}\n\n/**\n * The element `node` hangs from in the composed tree: its `parentElement`, or\n * the host of the shadow root it is a top-level child of. Bounded ancestor\n * walks use this so a shadow boundary continues the walk instead of silently\n * ending it one element short of the root they were bounded by.\n */\nexport function composedParentElement(node: Node): HTMLElement | null {\n const parent = node.parentNode;\n if (parent !== null && isShadowRoot(parent)) {\n return parent.host as HTMLElement;\n }\n return node.parentElement;\n}\n\n/**\n * The nearest inclusive ancestor of `node` matching `selector`, searching\n * across every open shadow boundary above it.\n *\n * The composed-tree counterpart of `Element.closest`, which — like\n * `querySelectorAll` and `Node.contains` — answers within a single node tree\n * and returns `null` for a match that lives above a shadow host. It pairs with\n * {@link resolveActiveElement}: resolving the deep active element and then\n * asking plain `closest` about it is the same half-applied posture\n * {@link composedContains} exists to prevent — the resolution hands over a node\n * from inside the shadow tree, which is exactly the one the un-composed walk\n * cannot climb out of.\n *\n * Each level delegates to the native `closest`, so the fast path inside a tree\n * stays the engine's; only the hop to the next host is done here.\n */\nexport function composedClosest(node: Element, selector: string): HTMLElement | null {\n let current: Element | null = node;\n while (current) {\n const match = current.closest<HTMLElement>(selector);\n if (match) {\n return match;\n }\n current = shadowHostOf(current);\n }\n return null;\n}\n\n/**\n * Whether `a` comes before `b` in composed-tree order, where an ancestor precedes its descendants\n * and a shadow host's shadow contents precede its light children — the order\n * `queryFocusableCandidates` enumerates in.\n *\n * `Node.compareDocumentPosition` reports two nodes on opposite sides of a shadow boundary as\n * disconnected, with an arbitrary order bit; this lifts each to its host in the lowest tree scope\n * the two share before comparing. Reports `false` for the same node, and for nodes with no shared\n * tree scope.\n */\nexport function composedPrecedes(a: Node, b: Node): boolean {\n const chainB = hostChainOf(b);\n for (const x of hostChainOf(a)) {\n const scope = x.getRootNode();\n const y = chainB.find((node) => node.getRootNode() === scope);\n if (y === undefined) {\n continue;\n }\n if (x === y) {\n return x === a && y !== b;\n }\n return (x.compareDocumentPosition(y) & x.DOCUMENT_POSITION_FOLLOWING) !== 0;\n }\n return false;\n}\n\nfunction hostChainOf(node: Node): Node[] {\n const chain: Node[] = [node];\n let host = shadowHostOf(node);\n while (host) {\n chain.push(host);\n host = shadowHostOf(host);\n }\n return chain;\n}\n\nfunction shadowHostOf(node: Node): Element | null {\n if (typeof node.getRootNode !== 'function') {\n return null;\n }\n const root = node.getRootNode();\n return root !== node && isShadowRoot(root) ? root.host : null;\n}\n\n/**\n * Narrows to an open shadow root. The `nodeType` half is load-bearing: `host`\n * alone is also a property of `<a>` / `<area>` / `<link>` (the URL's host), so\n * a duck-type on the name alone reads an anchor ancestor as a shadow boundary\n * and returns a string where an element belongs. Reading the constant off the\n * instance keeps the check free of the `Node` global, so it costs nothing on a\n * server.\n */\nfunction isShadowRoot(node: Node): node is ShadowRoot {\n return node.nodeType === node.DOCUMENT_FRAGMENT_NODE && 'host' in node;\n}\n","import { inject } from '@angular/core';\n\nimport {\n type DateAdapter,\n FOR_DATE_ADAPTER,\n type TimeCapableDateAdapter,\n} from 'forty-cdk/date-adapter';\nimport { fortyError } from '../errors/errors';\n\n/**\n * Day-only comparison for `adapter`, honouring its optional\n * {@link DateAdapter.compareDate} when implemented and otherwise deriving the\n * ordering from the `getYear` / `getMonth` / `getDate` getters. Returns a\n * negative number when `a`'s calendar day is before `b`'s, `0` when they fall\n * on the same day, and a positive number when `a`'s day is after `b`'s.\n *\n * Use this for day-granular availability and bounds (e.g. the calendar grid),\n * where the boundary day of a date-time `min`/`max` must stay selectable on\n * every adapter. For full-instant ordering — including any time component —\n * call {@link DateAdapter.compare} directly.\n *\n * @typeParam D The adapter's immutable date representation.\n * @param adapter The active date adapter.\n * @param a The first date.\n * @param b The second date.\n */\nexport function compareDateOf<D>(adapter: DateAdapter<D>, a: D, b: D): number {\n if (adapter.compareDate) {\n return adapter.compareDate(a, b);\n }\n const ay = adapter.getYear(a);\n const by = adapter.getYear(b);\n if (ay !== by) {\n return ay - by;\n }\n const am = adapter.getMonth(a);\n const bm = adapter.getMonth(b);\n if (am !== bm) {\n return am - bm;\n }\n return adapter.getDate(a) - adapter.getDate(b);\n}\n\n/**\n * Injects the active {@link DateAdapter}, throwing a descriptive,\n * primitive-prefixed error when no adapter has been provided.\n *\n * @param piece Name of the calling directive, used in the error message.\n * @param options `scope` is the entry point the error reports under, e.g.\n * `'date-field'`. Omit it from shared machinery that does not know one — the\n * check then reports under `[forty-cdk/core]` and `piece` carries the\n * attribution alone. The type stays inline on purpose: a named interface here\n * would be a core symbol reached from a blessed public signature, so it would\n * have to be published from `forty-cdk/shared` and carry that guarantee\n * forever, for one optional string.\n */\nexport function injectDateAdapter<D>(\n piece: string,\n options?: { readonly scope?: string },\n): DateAdapter<D> {\n const adapter = inject(FOR_DATE_ADAPTER, { optional: true });\n if (!adapter) {\n throw fortyError({\n code: 'FORCDK-CORE-002',\n scope: options?.scope,\n message: `${piece} requires a DateAdapter, and none is provided.`,\n fix:\n 'Add provideNativeDateAdapter() or provideInternationalizedDateAdapter() to your ' +\n 'application or component providers.',\n });\n }\n return adapter as DateAdapter<D>;\n}\n\n/**\n * Asserts that `adapter` implements the optional time accessors, returning it\n * narrowed to {@link TimeCapableDateAdapter}. Throws a descriptive,\n * primitive-prefixed error when the active adapter is day-only — the\n * zero-dependency `provideNativeDateAdapter()` is time-capable, as is\n * `provideInternationalizedDateTimeAdapter()`, but the day-pure\n * `provideInternationalizedDateAdapter()` (`CalendarDate`) is not.\n *\n * @param adapter The active adapter, typically from {@link injectDateAdapter}.\n * @param piece Name of the calling directive, used in the error message.\n * @param options `scope` is the entry point the error reports under — same\n * contract, and same inline-type reasoning, as {@link injectDateAdapter}.\n */\nexport function assertTimeCapable<D>(\n adapter: DateAdapter<D>,\n piece: string,\n options?: { readonly scope?: string },\n): TimeCapableDateAdapter<D> {\n if (\n typeof adapter.getHours !== 'function' ||\n typeof adapter.getMinutes !== 'function' ||\n typeof adapter.getSeconds !== 'function' ||\n typeof adapter.setTime !== 'function'\n ) {\n throw fortyError({\n code: 'FORCDK-CORE-003',\n scope: options?.scope,\n message: `${piece} requires a time-capable DateAdapter, and the active one is day-only.`,\n cause:\n 'provideInternationalizedDateAdapter() supplies CalendarDate values, which carry no time ' +\n 'of day, so the adapter implements none of the time accessors.',\n fix:\n 'Switch to provideNativeDateAdapter() or provideInternationalizedDateTimeAdapter() in the ' +\n 'providers that reach this piece.',\n });\n }\n return adapter as TimeCapableDateAdapter<D>;\n}\n","/**\n * Resolves the effective hour cycle. An explicit `12` / `24` always wins;\n * otherwise the runtime locale's preference is read from\n * `Intl.DateTimeFormat(...).resolvedOptions().hourCycle` (`h11` / `h12` → 12,\n * `h23` / `h24` → 24).\n *\n * @param locale BCP 47 locale, or `undefined` for the runtime default.\n * @param override The `hourCycle` input, or `null` to derive from the locale.\n */\nexport function resolveHourCycle(locale: string | undefined, override: 12 | 24 | null): 12 | 24 {\n if (override !== null) {\n return override;\n }\n const cycle = new Intl.DateTimeFormat(locale, {\n calendar: 'gregory',\n hour: 'numeric',\n }).resolvedOptions().hourCycle;\n return cycle === 'h11' || cycle === 'h12' ? 12 : 24;\n}\n\n/**\n * Maps a 0-23 hour to its 12-hour display value and AM/PM period.\n *\n * @param hour The 0-23 hour.\n * @param min The lowest display hour: `1` counts 1-12 (`h12`), `0` counts 0-11 (`h11`).\n */\nexport function to12(hour: number, min: 0 | 1 = 1): { h12: number; pm: boolean } {\n const h12 = hour % 12;\n return { h12: h12 < min ? h12 + 12 : h12, pm: hour >= 12 };\n}\n\n/**\n * The lowest hour a 12-hour clock displays in `locale`: `0` where the locale\n * counts 0-11 (`h11`, e.g. `ja-JP`, where 12:30 reads 午後0:30), `1` where it\n * counts 1-12 (`h12`). Pure.\n *\n * @param locale BCP 47 locale, or `undefined` for the runtime default.\n */\nexport function twelveHourMin(locale: string | undefined): 0 | 1 {\n const cycle = new Intl.DateTimeFormat(locale, {\n calendar: 'gregory',\n hour: 'numeric',\n hour12: true,\n }).resolvedOptions().hourCycle;\n return cycle === 'h11' ? 0 : 1;\n}\n\n/** Combines a 0-12 display hour and an AM/PM period back into a 0-23 hour. */\nexport function from12(h12: number, pm: boolean): number {\n const base = h12 % 12;\n return pm ? base + 12 : base;\n}\n\n/**\n * Reads the localized AM / PM strings for a locale (e.g. `AM` / `PM`,\n * `a.m.` / `p.m.`, `午前` / `午後`). Pure.\n *\n * @param locale BCP 47 locale, or `undefined` for the runtime default.\n */\nexport function dayPeriodNames(locale: string | undefined): { am: string; pm: string } {\n const fmt = new Intl.DateTimeFormat(locale, {\n calendar: 'gregory',\n hour: 'numeric',\n hour12: true,\n });\n const read = (date: Date): string =>\n fmt.formatToParts(date).find((part) => part.type === 'dayPeriod')?.value ?? '';\n return {\n am: read(new Date(2000, 0, 1, 1)) || 'AM',\n pm: read(new Date(2000, 0, 1, 13)) || 'PM',\n };\n}\n\nfunction firstDifferingIndex(a: string, b: string): number {\n const length = Math.min(a.length, b.length);\n for (let i = 0; i < length; i++) {\n if (a[i] !== b[i]) {\n return i;\n }\n }\n return -1;\n}\n\n/**\n * Resolves a single typed character to an AM / PM period for the `dayPeriod`\n * segment, so localized fields accept the locale's own day-period key (e.g.\n * `前` / `後` for `午前` / `午後`, `ص` / `م`) rather than only Latin `a` / `p`.\n *\n * The key is matched against the first character at which the two localized\n * names (`names.am` / `names.pm`) differ — this disambiguates locales whose\n * names share a leading character (`午前` / `午後`, `오전` / `오후`) while\n * coinciding with the first character for English. A Latin `a` / `p` fallback\n * always applies, since AM/PM is universal and many users lack an IME for the\n * native character. Returns `null` for a multi-character key or an unrecognized\n * character. Pure.\n *\n * @param key The typed character (`event.key`).\n * @param names The localized AM / PM strings, as read by {@link dayPeriodNames}.\n */\nexport function matchDayPeriod(key: string, names: { am: string; pm: string }): 'am' | 'pm' | null {\n if (key.length !== 1) {\n return null;\n }\n const lowerKey = key.toLowerCase();\n const am = names.am.toLowerCase();\n const pm = names.pm.toLowerCase();\n const index = firstDifferingIndex(am, pm);\n if (index !== -1) {\n if (lowerKey === am[index]) {\n return 'am';\n }\n if (lowerKey === pm[index]) {\n return 'pm';\n }\n }\n if (lowerKey === 'a') {\n return 'am';\n }\n if (lowerKey === 'p') {\n return 'pm';\n }\n return null;\n}\n","const formatters = new Map<string, Intl.NumberFormat>();\n\n/**\n * Renders a non-negative date or time part (a day, a month, a year, an hour)\n * as the text a piece displays, in the numbering system `locale` formats its\n * dates with: Arabic-Indic digits for `ar-EG`, Persian digits for `fa-IR`,\n * Devanagari for `hi-IN-u-nu-deva`, Latin digits for `en-US`. Never grouped,\n * and zero-padded to `minimumIntegerDigits`.\n *\n * The numbering system is read off a Gregorian `Intl.DateTimeFormat` for the\n * same locale, so the digits match what the date adapters' `format` renders\n * beside them. Formatters are cached per `(locale, minimumIntegerDigits)`.\n *\n * @param value The part's number.\n * @param minimumIntegerDigits The width to zero-pad to (`1` for no padding).\n * @param locale BCP 47 locale, or `undefined` for the runtime default.\n */\nexport function formatLocaleDigits(\n value: number,\n minimumIntegerDigits: number,\n locale: string | undefined,\n): string {\n const key = `${locale ?? ''}|${minimumIntegerDigits}`;\n let formatter = formatters.get(key);\n if (formatter === undefined) {\n const { numberingSystem } = new Intl.DateTimeFormat(locale, {\n calendar: 'gregory',\n }).resolvedOptions();\n formatter = new Intl.NumberFormat(locale, {\n numberingSystem,\n useGrouping: false,\n minimumIntegerDigits,\n });\n formatters.set(key, formatter);\n }\n return formatter.format(value);\n}\n","import { computed, signal, type Signal } from '@angular/core';\n\nimport type { RovingTabindex } from '../roving-tabindex/roving-tabindex';\nimport { from12, matchDayPeriod, to12 } from './hour-cycle';\nimport { formatLocaleDigits } from './locale-digits';\nimport type { TimeSegmentType } from './segment-types';\n\n/** Which calendar part an editable date segment edits. */\nexport type DateSegmentType = 'day' | 'month' | 'year';\n\n/**\n * Every editable part a date(-time) or time field can render — the date parts\n * plus the time parts (`hour` / `minute` / `second` / the AM·PM `dayPeriod`).\n */\nexport type SegmentType = DateSegmentType | TimeSegmentType;\n\n/** Spec for a single editable spinbutton segment. */\nexport interface EditableSpec {\n readonly kind: 'editable';\n /** The date or time part this segment edits. */\n readonly type: SegmentType;\n /** Maximum number of digits the segment accepts before it is full (`0` for the AM/PM toggle). */\n readonly digits: number;\n}\n\n/** Spec for a non-editable separator rendered between segments. */\nexport interface LiteralSpec {\n readonly kind: 'literal';\n /** The separator characters (`/`, `.`, `-`, `:`, a space, …) for the runtime locale. */\n readonly literal: string;\n}\n\n/** A single entry in the locale-ordered segment list. */\nexport type FieldSpec = EditableSpec | LiteralSpec;\n\n/** Per-part entered state: the entered value for each editable segment, hour as 0-23. */\nexport type SegmentParts = Partial<Record<SegmentType, number | null>>;\n\n/**\n * A rendered segment descriptor for the consumer's `@for`. Covers both editable\n * spinbutton segments and the decorative literal separators between them.\n *\n * @typeParam T The segment-type union the owning field renders (the date field\n * carries the full {@link SegmentType}; the time field narrows to its\n * `TimeSegmentType`).\n */\nexport interface FieldSegment<T extends SegmentType = SegmentType> {\n /** Stable key for `@for` tracking. */\n readonly id: string;\n /** `true` for a separator; `false` for an editable segment. */\n readonly isLiteral: boolean;\n /** The part an editable segment edits; `null` for a literal. */\n readonly type: T | null;\n /**\n * Text to render: the formatted value when the segment is filled, the\n * placeholder while empty, or the literal separator.\n */\n readonly text: string;\n}\n\n/** Handle a segment directive registers with the editor for focus moves. */\nexport interface SegmentHandle<T extends SegmentType = SegmentType> {\n /** The segment's host element. */\n readonly host: HTMLElement;\n /** The part the segment edits. */\n readonly type: Signal<T>;\n}\n\n/**\n * The per-segment accessor and behavior surface a date / time field engine\n * exposes to its segment children. It is the non-signal half of a\n * {@link import('./segment-directive').SegmentEditorContext}: segments read the\n * reactive accessors for their ARIA / display bindings and call the behavior\n * methods to type, step, clear, and move focus. `DateFieldEngine` and\n * `TimeFieldEngine` both satisfy it, so one segment directive drives either\n * flavour of field and one composer coordinates either flavour of endpoint.\n */\nexport interface SegmentEditorDelegate {\n /** Current display value of `type`, or `null` while empty. */\n segmentValue(type: SegmentType): number | null;\n /** Lowest accepted display value for `type`. */\n segmentMin(type: SegmentType): number;\n /** Highest accepted display value for `type`. */\n segmentMax(type: SegmentType): number;\n /** Field-specific `aria-valuetext` for `type`, or `null` for the numeric reading. */\n segmentValueText(type: SegmentType): string | null;\n /** Text to render for `type`: the formatted value, the placeholder, or the typing buffer. */\n segmentDisplayText(type: SegmentType): string;\n /** Whether `type` currently holds no entered value. */\n isSegmentEmpty(type: SegmentType): boolean;\n /** Whether `type` is the first editable segment in locale order. */\n isFirstSegmentType(type: SegmentType): boolean;\n\n /** Registers a segment handle for focus moves. */\n registerSegment(handle: SegmentHandle): void;\n /** Removes a previously registered segment handle. */\n unregisterSegment(handle: SegmentHandle): void;\n\n /** Moves the roving tab stop to `type` and clears the typing buffer. */\n focusSegment(type: SegmentType): void;\n /** Types a digit into `type` (fill + auto-advance). */\n typeDigit(type: SegmentType, digit: number): void;\n /** Steps `type` by `delta` (arrow keys), wrapping / clamping per part. */\n step(type: SegmentType, delta: number): void;\n /** Jumps `type` to its minimum or maximum (Home / End). */\n goToBound(type: SegmentType, bound: 'min' | 'max'): void;\n /** Sets the AM / PM period. */\n setDayPeriod(period: 'am' | 'pm'): void;\n /** Sets AM/PM from a typed character; returns whether the key was recognized. */\n setDayPeriodFromKey(key: string): boolean;\n /** Clears `type` back to empty (Delete). */\n clear(type: SegmentType): void;\n /** Removes the last entered digit of `type` (whole clear when the last digit goes). */\n backspace(type: SegmentType): void;\n /** Moves focus to the sibling segment in the given direction. */\n focusSibling(type: SegmentType, step: -1 | 1): void;\n /**\n * Flushes any mid-typing transient and clears the typing buffer (blur). When\n * `next`, the element receiving focus, is not one of the field's segments, the\n * field settles: its segments re-read the committed value, clamp included.\n */\n endTyping(next?: EventTarget | null): void;\n}\n\n/**\n * The field-specific surface a date / time root supplies to its\n * {@link SegmentEditor}. The editor owns the spin-button state machine (typing\n * buffer, step / clear / Home-End, digit auto-advance, RTL focus moves, the\n * segment registry); the host supplies only what differs between a date field\n * and a time field: the reactive specs / cycle / locale data, the per-segment\n * bounds, the empty-segment seed, the placeholder, the extra `aria-valuetext`,\n * and how a committed parts record is composed into the value.\n *\n * @typeParam P The host's parts shape (a subtype of {@link SegmentParts}).\n */\nexport interface SegmentEditorHost<P extends SegmentParts> {\n /** Whether the field is disabled. */\n readonly disabled: Signal<boolean>;\n /** Whether the field is read-only. */\n readonly readonly: Signal<boolean>;\n /** Shared roving-tabindex tracker: one segment owns `tabindex=0` at a time. */\n readonly roving: RovingTabindex;\n /** Resolved hour cycle (`12` shows AM/PM, `24` does not). */\n readonly cycle: Signal<12 | 24>;\n /** The ordered, locale-derived spec list (editable + literals). */\n readonly specs: Signal<readonly FieldSpec[]>;\n /** The editable parts in their locale order — the navigation / auto-advance order. */\n readonly editableOrder: Signal<readonly SegmentType[]>;\n /** Localized AM / PM strings for the `dayPeriod` segment. */\n readonly periodNames: Signal<{ am: string; pm: string }>;\n /** The resolved locale the segment digits render in, `undefined` for the runtime default. */\n readonly locale: Signal<string | undefined>;\n\n /** Current entered parts. */\n parts(): P;\n /** Lowest accepted display value for `type`. */\n segmentMin(type: SegmentType): number;\n /** Highest accepted display value for `type`. */\n segmentMax(type: SegmentType): number;\n /** Base value for stepping an empty `type` on first step. */\n seed(type: SegmentType): number;\n /** Placeholder shown while `type` is empty. */\n placeholderFor(type: SegmentType): string;\n /**\n * Field-specific `aria-valuetext` for a filled `type` (e.g. the month name),\n * or `null` to fall back to the default numeric reading.\n */\n valueText(type: SegmentType): string | null;\n /**\n * Records the next parts for the field.\n *\n * `transient` is `true` for a mid-typing digit whose segment buffer has not\n * yet settled (a non-final keystroke): the host updates its live segment\n * display only and does **not** emit the composed value, so an intermediate\n * keystroke composition is never observable through the field value. A\n * settled commit (`false`: a completed digit / auto-advance, a step, a\n * Home/End jump, a day-period toggle, a clear, or a blur flush) clamps to the\n * bounds and emits the composed value.\n */\n commit(next: P, transient: boolean): void;\n /** Re-reads the entered parts from the committed value once focus leaves the segments. */\n settle(): void;\n /**\n * Whether `parts` name a wall-clock time the day skips (a DST gap), so a step\n * of `type` passes over it.\n */\n nonexistent(type: SegmentType, parts: P): boolean;\n}\n\n/**\n * The shared spin-button editor backing `ForDateField` and `ForTimeField`.\n *\n * It owns everything that was duplicated ~95% between the two roots: the\n * ephemeral digit-typing buffer, `typeDigit` (digit fill + auto-advance), `step`\n * (with the 12/24-hour-aware hour stepping), `goToBound`, `setDayPeriod`,\n * `clear`, the RTL-mirrored `focusSibling` / `focusSegment`, the\n * `registerSegment` / `unregisterSegment` `Map`, and the reactive per-part\n * accessors (`segmentValue` / `segmentDisplayText` / `segmentValueText` /\n * `isSegmentEmpty` / `isFirstSegmentType`) plus the rendered `segments` list.\n *\n * Constructed directly (`new SegmentEditor(host)`); it holds no injection\n * context. The host (a date or time root) supplies the field-specific bits\n * through {@link SegmentEditorHost}.\n *\n * @typeParam P The host's parts shape.\n * @typeParam T The segment-type union the owning field renders.\n */\nexport class SegmentEditor<P extends SegmentParts, T extends SegmentType = SegmentType> {\n readonly #host: SegmentEditorHost<P>;\n readonly #segments = new Map<SegmentType, SegmentHandle>();\n\n /** Ephemeral type-to-fill buffer for the segment currently being typed into. */\n readonly #typing = signal<{ type: SegmentType; buffer: string } | null>(null);\n\n #pendingSettle = false;\n\n /**\n * The ordered, locale-derived segments (editable + literals) to render. Each\n * entry carries the text to display: the formatted value when filled, the\n * placeholder while empty, or the literal separator.\n */\n readonly segments: Signal<readonly FieldSegment<T>[]>;\n\n /** `true` while every editable segment is empty — the field shows no entered digits. */\n readonly empty: Signal<boolean>;\n\n constructor(host: SegmentEditorHost<P>) {\n this.#host = host;\n this.segments = computed<readonly FieldSegment<T>[]>(() => {\n let literalIndex = 0;\n return this.#host.specs().map((spec): FieldSegment<T> => {\n if (spec.kind === 'literal') {\n return {\n id: `literal-${literalIndex++}`,\n isLiteral: true,\n type: null,\n text: spec.literal,\n };\n }\n return {\n id: spec.type,\n isLiteral: false,\n type: spec.type as T,\n text: this.segmentDisplayText(spec.type),\n };\n });\n });\n this.empty = computed(() =>\n this.#host.editableOrder().every((type) => this.isSegmentEmpty(type)),\n );\n }\n\n segmentValue(type: SegmentType): number | null {\n const parts = this.#host.parts();\n if (type === 'dayPeriod') {\n return parts.dayPeriod ?? null;\n }\n if (type === 'hour') {\n const hour = parts.hour;\n if (hour == null) {\n return null;\n }\n return this.#host.cycle() === 12 ? to12(hour, this.#twelveHourMin()).h12 : hour;\n }\n return parts[type] ?? null;\n }\n\n segmentValueText(type: SegmentType): string | null {\n if (type === 'dayPeriod') {\n const dayPeriod = this.#host.parts().dayPeriod;\n if (dayPeriod == null) {\n return this.#host.valueText(type);\n }\n const names = this.#host.periodNames();\n return dayPeriod === 1 ? names.pm : names.am;\n }\n return this.#host.valueText(type);\n }\n\n segmentDisplayText(type: SegmentType): string {\n const typing = this.#typing();\n if (typing && typing.type === type) {\n return formatLocaleDigits(Number(typing.buffer), typing.buffer.length, this.#host.locale());\n }\n if (type === 'dayPeriod') {\n const dayPeriod = this.#host.parts().dayPeriod;\n if (dayPeriod == null) {\n return this.#host.placeholderFor(type);\n }\n const names = this.#host.periodNames();\n return dayPeriod === 1 ? names.pm : names.am;\n }\n const value = this.segmentValue(type);\n if (value === null) {\n return this.#host.placeholderFor(type);\n }\n return formatLocaleDigits(value, type === 'year' ? 4 : 2, this.#host.locale());\n }\n\n isSegmentEmpty(type: SegmentType): boolean {\n return this.#host.parts()[type] == null;\n }\n\n isFirstSegmentType(type: SegmentType): boolean {\n return this.#host.editableOrder()[0] === type;\n }\n\n registerSegment(handle: SegmentHandle): void {\n this.#segments.set(handle.type(), handle);\n }\n\n unregisterSegment(handle: SegmentHandle): void {\n if (this.#segments.get(handle.type()) === handle) {\n this.#segments.delete(handle.type());\n }\n this.#host.roving.unregister(handle.host);\n }\n\n focusSegment(type: SegmentType): void {\n const handle = this.#segments.get(type);\n if (handle) {\n this.#host.roving.setActive(handle.host);\n }\n this.#typing.set(null);\n }\n\n /**\n * Clears the ephemeral type-to-fill buffer so a partially typed, uncommitted\n * digit is not left painted once the segment loses focus. The segment repaints\n * from its committed value (zero-padded, or the placeholder when empty).\n *\n * A blur is a settle event: when a mid-typing transient is still pending, it\n * is flushed as a settled commit of the current parts before the buffer is\n * cleared, so leaving a partially typed segment settles (and clamps) its value.\n * When focus moves anywhere but another of this field's segments, the host\n * settles too.\n */\n endTyping(next?: EventTarget | null): void {\n if (this.#pendingSettle) {\n this.#commit(this.#host.parts(), false);\n }\n this.#typing.set(null);\n if (!this.#ownsSegment(next)) {\n this.#host.settle();\n }\n }\n\n /** Drops the typing buffer and any pending transient without committing it. */\n resetTyping(): void {\n this.#pendingSettle = false;\n this.#typing.set(null);\n }\n\n #ownsSegment(target: EventTarget | null | undefined): boolean {\n if (!target) {\n return false;\n }\n for (const handle of this.#segments.values()) {\n if (handle.host === target) {\n return true;\n }\n }\n return false;\n }\n\n #commit(next: P, transient: boolean): void {\n this.#pendingSettle = transient;\n this.#host.commit(next, transient);\n }\n\n typeDigit(type: SegmentType, digit: number): void {\n if (this.#host.disabled() || this.#host.readonly() || type === 'dayPeriod') {\n return;\n }\n const spec = this.#editableSpec(type);\n const min = this.#host.segmentMin(type);\n const max = this.#host.segmentMax(type);\n const previous = this.#typing();\n let buffer = (previous?.type === type ? previous.buffer : '') + String(digit);\n if (Number(buffer) > max || buffer.length > spec.digits) {\n buffer = String(digit);\n }\n const num = Number(buffer);\n const valid = num >= min && num <= max;\n const full = valid && (buffer.length >= spec.digits || num * 10 > max);\n this.#typing.set({ type, buffer });\n this.#commit(this.#withPart(type, valid ? this.#toInternal(type, num) : null), !full);\n if (full) {\n this.#typing.set(null);\n this.focusSibling(type, 1);\n }\n }\n\n step(type: SegmentType, delta: number): void {\n if (this.#host.disabled() || this.#host.readonly()) {\n return;\n }\n this.#typing.set(null);\n if (type === 'dayPeriod') {\n const period = this.#host.parts().dayPeriod;\n this.setDayPeriod(period == null ? (delta > 0 ? 'pm' : 'am') : period === 1 ? 'am' : 'pm');\n return;\n }\n const parts = this.#host.parts();\n const current = parts[type];\n if (current == null) {\n this.#commit(this.#withPart(type, this.#host.seed(type)), false);\n return;\n }\n let next = this.#stepValue(type, current, delta);\n let skips = this.#host.segmentMax(type) - this.#host.segmentMin(type);\n while (skips-- > 0 && this.#host.nonexistent(type, this.#withPart(type, next))) {\n next = this.#stepValue(type, next, delta);\n }\n this.#commit(this.#withPart(type, next), false);\n }\n\n #stepValue(type: SegmentType, current: number, delta: number): number {\n if (type === 'hour') {\n return this.#stepHour(current, delta);\n }\n if (type === 'minute' || type === 'second') {\n return (((current + delta) % 60) + 60) % 60;\n }\n if (type === 'year') {\n return Math.min(\n this.#host.segmentMax(type),\n Math.max(this.#host.segmentMin(type), current + delta),\n );\n }\n const min = this.#host.segmentMin(type);\n const range = this.#host.segmentMax(type) - min + 1;\n return min + ((((current - min + delta) % range) + range) % range);\n }\n\n goToBound(type: SegmentType, bound: 'min' | 'max'): void {\n if (this.#host.disabled() || this.#host.readonly()) {\n return;\n }\n this.#typing.set(null);\n if (type === 'dayPeriod') {\n this.setDayPeriod(bound === 'min' ? 'am' : 'pm');\n return;\n }\n const display = bound === 'min' ? this.#host.segmentMin(type) : this.#host.segmentMax(type);\n this.#commit(this.#withPart(type, this.#toInternal(type, display)), false);\n }\n\n setDayPeriod(period: 'am' | 'pm'): void {\n if (this.#host.disabled() || this.#host.readonly()) {\n return;\n }\n this.#typing.set(null);\n const parts = this.#host.parts();\n const pm = period === 'pm';\n const hour = parts.hour ?? null;\n const nextHour = hour === null ? null : from12(to12(hour).h12, pm);\n this.#commit({ ...parts, dayPeriod: pm ? 1 : 0, hour: nextHour } as P, false);\n }\n\n /**\n * Sets the AM / PM period from a single typed character on the `dayPeriod`\n * segment, matched against the localized day-period names (with a Latin\n * `a` / `p` fallback) via {@link matchDayPeriod}. Returns `true` when `key`\n * is a recognized period character — regardless of disabled / read-only, so\n * the caller can `preventDefault` on a known key even when no commit\n * occurs — and `false` when it is not.\n */\n setDayPeriodFromKey(key: string): boolean {\n const period = matchDayPeriod(key, this.#host.periodNames());\n if (period === null) {\n return false;\n }\n this.setDayPeriod(period);\n return true;\n }\n\n clear(type: SegmentType): void {\n if (this.#host.disabled() || this.#host.readonly() || type === 'dayPeriod') {\n return;\n }\n this.#typing.set(null);\n this.#commit(this.#withPart(type, null), false);\n }\n\n /**\n * Removes the last entered digit of a numeric segment (the mirror of\n * {@link typeDigit}). It pops one display digit off the active typing buffer,\n * or off the committed display value when nothing is being typed, then\n * re-commits the shortened buffer as a mid-typing transient — so a partial\n * value is not clamped or rehydrated. When the last digit is removed the\n * segment settles to empty (a settled `null` commit, identical to\n * {@link clear}). No-op on the `dayPeriod` toggle and while disabled /\n * read-only.\n */\n backspace(type: SegmentType): void {\n if (this.#host.disabled() || this.#host.readonly() || type === 'dayPeriod') {\n return;\n }\n const previous = this.#typing();\n const source = previous?.type === type ? previous.buffer : this.#currentDigits(type);\n const buffer = source.slice(0, -1);\n if (buffer === '') {\n this.#typing.set(null);\n this.#commit(this.#withPart(type, null), false);\n return;\n }\n const num = Number(buffer);\n const valid = num >= this.#host.segmentMin(type) && num <= this.#host.segmentMax(type);\n this.#typing.set({ type, buffer });\n this.#commit(this.#withPart(type, valid ? this.#toInternal(type, num) : null), true);\n }\n\n focusSibling(type: SegmentType, step: -1 | 1): void {\n const order = this.#host.editableOrder();\n const targetType = order[order.indexOf(type) + step];\n if (targetType === undefined) {\n return;\n }\n const handle = this.#segments.get(targetType);\n if (!handle) {\n return;\n }\n this.#host.roving.setActive(handle.host);\n handle.host.focus();\n }\n\n /**\n * Move focus to the first editable segment in locale order — the entry point\n * a field's `FormValueControl.focus` targets so Signal Forms' focus-on-error\n * lands on a real spinbutton rather than the non-focusable `role=\"group\"`\n * host. No-op when no segment has registered yet.\n */\n focusFirstSegment(options?: FocusOptions): void {\n const first = this.#host.editableOrder()[0];\n if (first === undefined) {\n return;\n }\n const handle = this.#segments.get(first);\n if (!handle) {\n return;\n }\n this.#host.roving.setActive(handle.host);\n handle.host.focus(options);\n }\n\n #currentDigits(type: SegmentType): string {\n const value = this.segmentValue(type);\n return value === null ? '' : String(value);\n }\n\n /** Converts a displayed segment value to its internal representation (hour: 12h→24h). */\n #toInternal(type: SegmentType, display: number): number {\n if (type !== 'hour' || this.#host.cycle() === 24) {\n return display;\n }\n const parts = this.#host.parts();\n const pm =\n parts.dayPeriod != null ? parts.dayPeriod === 1 : parts.hour != null && parts.hour >= 12;\n return from12(display, pm);\n }\n\n #stepHour(current: number, delta: number): number {\n if (this.#host.cycle() === 24) {\n return (((current + delta) % 24) + 24) % 24;\n }\n const min = this.#twelveHourMin();\n const { h12, pm } = to12(current, min);\n return from12(min + ((((h12 - min + delta) % 12) + 12) % 12), pm);\n }\n\n #twelveHourMin(): 0 | 1 {\n return this.#host.segmentMin('hour') === 0 ? 0 : 1;\n }\n\n #editableSpec(type: SegmentType): EditableSpec {\n return this.#host\n .specs()\n .find((spec): spec is EditableSpec => spec.kind === 'editable' && spec.type === type)!;\n }\n\n /**\n * Returns the current parts with `type` set to `value`. `type` is always a key\n * the host's parts record carries, so the computed-key spread is a genuine `P`\n * at runtime; the assertion narrows the object-literal index type back to `P`.\n */\n #withPart(type: SegmentType, value: number | null): P {\n return { ...this.#host.parts(), [type]: value } as P;\n }\n}\n","import { computed, linkedSignal, type Signal, untracked, type WritableSignal } from '@angular/core';\n\nimport type { RovingTabindex } from '../roving-tabindex/roving-tabindex';\nimport type { DateAdapter } from 'forty-cdk/date-adapter';\nimport { dayPeriodNames, resolveHourCycle, twelveHourMin } from './hour-cycle';\nimport {\n type FieldSegment,\n type FieldSpec,\n SegmentEditor,\n type SegmentHandle,\n type SegmentParts,\n type SegmentType,\n} from './segment-editor';\n\n/**\n * The reactive configuration shared by every segmented date / time field engine:\n * the disabled / read-only flags, the roving tracker, the hour-cycle / locale\n * inputs that drive the resolved cycle, the empty-segment text, the\n * authoritative `source` value, and the `onCommit` sink. Each concrete engine's\n * config extends this with its adapter, granularity, placeholder, and bounds.\n *\n * @typeParam D The adapter's immutable date (or date-time) type.\n */\nexport interface BaseFieldEngineConfig<D> {\n /** The active date adapter; its `locale()` backs an unset {@link locale}. */\n readonly adapter: DateAdapter<D>;\n /** Whether editing is disabled (the field's effective disabled). */\n readonly disabled: Signal<boolean>;\n /** Whether editing is read-only. */\n readonly readonly: Signal<boolean>;\n /** Shared roving-tabindex tracker for this field's segments. */\n readonly roving: RovingTabindex;\n /** 12- / 24-hour override, or `null` to derive from the locale. */\n readonly hourCycle: Signal<12 | 24 | null>;\n /**\n * BCP 47 locale driving segment order, separators, and AM/PM names, or `null`\n * for the adapter's `locale()`, then the runtime default.\n */\n readonly locale: Signal<string | null>;\n /** Accessible `aria-valuetext` announced for an empty editable segment. */\n readonly emptySegmentText: Signal<string>;\n /** Authoritative current value the entered parts rehydrate from. */\n readonly source: Signal<D | null>;\n /** Sink called with the composed value (or `null` while incomplete) on every edit. */\n readonly onCommit: (value: D | null) => void;\n}\n\n/**\n * The shared base backing `DateFieldEngine` and `TimeFieldEngine`. It owns\n * everything the two engines duplicated on top of the generic\n * {@link SegmentEditor}: the resolved hour cycle, the editable-order / period-name\n * derivations, the rendered `segments` / `empty` / `composed` signals, the editor\n * wiring, the segment-behavior forwarding, and the settle-vs-transient commit\n * skeleton. Each concrete engine supplies only what differs between a date field\n * and a time field: the locale-ordered `specs`, the entered `parts`, the\n * per-segment bounds / seed / placeholder / `aria-valuetext`, and how a parts\n * record composes into the value.\n *\n * Constructed by the concrete subclass, which must assign {@link specs} and\n * {@link parts} and then call {@link initEditor} at the end of its constructor:\n * the editor captures `specs` / `parts`, so building it in a base field\n * initializer (which runs before the subclass assigns them) would capture\n * `undefined`.\n *\n * @typeParam D The adapter's immutable date (or date-time) type.\n * @typeParam P The engine's parts shape (a subtype of {@link SegmentParts}).\n * @typeParam T The segment-type union the owning field renders.\n */\nexport abstract class DateTimeFieldEngineBase<\n D,\n P extends SegmentParts,\n T extends SegmentType = SegmentType,\n> {\n private readonly config: BaseFieldEngineConfig<D>;\n\n /** The effective locale: the field's own, then the adapter's, then the runtime default. */\n protected readonly locale = computed<string | undefined>(\n () => this.config.locale() ?? this.config.adapter.locale?.() ?? undefined,\n );\n\n protected readonly cycle = computed(() =>\n resolveHourCycle(this.locale(), this.config.hourCycle()),\n );\n\n /** The lowest display hour: `0` in 24-hour and in an `h11` 12-hour locale, `1` otherwise. */\n protected readonly hourMin = computed<0 | 1>(() =>\n this.cycle() === 12 ? twelveHourMin(this.locale()) : 0,\n );\n\n /** The ordered, locale-derived spec list (editable + literals). */\n protected abstract readonly specs: Signal<readonly FieldSpec[]>;\n\n /** The entered parts, rehydrated from `source` and updated on every commit. */\n protected abstract readonly parts: WritableSignal<P>;\n\n private readonly editableOrder = computed<readonly SegmentType[]>(() =>\n this.specs()\n .filter((spec): spec is Extract<FieldSpec, { kind: 'editable' }> => spec.kind === 'editable')\n .map((spec) => spec.type),\n );\n\n private readonly periodNames = computed(() => dayPeriodNames(this.locale()));\n\n private editor!: SegmentEditor<P, T>;\n\n #ownCommit: { readonly source: D | null; readonly rehydrate: boolean } | null = null;\n\n readonly #retainedAnchor = linkedSignal<D | null, D | null>({\n source: () => this.config.source(),\n computation: () => null,\n });\n\n protected readonly anchor = computed<D | null>(\n () => this.config.source() ?? this.#retainedAnchor(),\n );\n\n #committing = false;\n\n #adopted: { readonly source: D } | null = null;\n\n /**\n * The ordered, locale-derived segments (editable + literals) to render. Each\n * entry carries the text to display: the formatted value when filled, the\n * placeholder while empty, or the literal separator.\n */\n readonly segments: Signal<readonly FieldSegment<T>[]> = computed(() => this.editor.segments());\n\n /** `true` while every editable segment is empty — no digits are entered. */\n readonly empty: Signal<boolean> = computed(() => this.editor.empty());\n\n /** The composed value of the entered parts, or `null` while any segment is empty. */\n readonly composed = computed<D | null>(() => this.composeFrom(this.parts()));\n\n constructor(config: BaseFieldEngineConfig<D>) {\n this.config = config;\n }\n\n /**\n * Builds the shared {@link SegmentEditor} and wires it to this engine's specs,\n * parts, bounds, and commit. The concrete subclass calls this at the very end\n * of its constructor, after it has assigned {@link specs} and {@link parts}.\n */\n protected initEditor(): void {\n this.editor = new SegmentEditor<P, T>({\n disabled: this.config.disabled,\n readonly: this.config.readonly,\n roving: this.config.roving,\n cycle: this.cycle,\n specs: this.specs,\n editableOrder: this.editableOrder,\n periodNames: this.periodNames,\n locale: this.locale,\n parts: () => this.parts(),\n segmentMin: (type) => this.segmentMin(type),\n segmentMax: (type) => this.segmentMax(type),\n seed: (type) => this.seed(type),\n placeholderFor: (type) => this.placeholderFor(type),\n valueText: (type) => this.valueText(type),\n commit: (next, transient) => this.commitParts(next, transient),\n settle: () => this.settle(),\n nonexistent: (type, parts) =>\n (type === 'hour' || type === 'minute') && this.wallClockShifts(parts),\n });\n }\n\n segmentValue(type: SegmentType): number | null {\n return this.editor.segmentValue(type);\n }\n\n segmentValueText(type: SegmentType): string | null {\n return this.editor.segmentValueText(type);\n }\n\n segmentDisplayText(type: SegmentType): string {\n return this.editor.segmentDisplayText(type);\n }\n\n isSegmentEmpty(type: SegmentType): boolean {\n return this.editor.isSegmentEmpty(type);\n }\n\n isFirstSegmentType(type: SegmentType): boolean {\n return this.editor.isFirstSegmentType(type);\n }\n\n registerSegment(handle: SegmentHandle): void {\n this.editor.registerSegment(handle);\n }\n\n unregisterSegment(handle: SegmentHandle): void {\n this.editor.unregisterSegment(handle);\n }\n\n focusSegment(type: SegmentType): void {\n this.editor.focusSegment(type);\n }\n\n /** Move focus to the first editable segment — the field's focus-on-error target. */\n focusFirstSegment(options?: FocusOptions): void {\n this.editor.focusFirstSegment(options);\n }\n\n typeDigit(type: SegmentType, digit: number): void {\n this.editor.typeDigit(type, digit);\n }\n\n step(type: SegmentType, delta: number): void {\n this.editor.step(type, delta);\n }\n\n goToBound(type: SegmentType, bound: 'min' | 'max'): void {\n this.editor.goToBound(type, bound);\n }\n\n setDayPeriod(period: 'am' | 'pm'): void {\n this.editor.setDayPeriod(period);\n }\n\n setDayPeriodFromKey(key: string): boolean {\n return this.editor.setDayPeriodFromKey(key);\n }\n\n clear(type: SegmentType): void {\n this.editor.clear(type);\n }\n\n backspace(type: SegmentType): void {\n this.editor.backspace(type);\n }\n\n focusSibling(type: SegmentType, step: -1 | 1): void {\n this.editor.focusSibling(type, step);\n }\n\n endTyping(next?: EventTarget | null): void {\n this.editor.endTyping(next);\n }\n\n /**\n * Discards whatever the segments hold that the value cannot represent — a\n * partly typed entry, an in-progress typing buffer, or parts held back from\n * a commit — and rehydrates them from the current `source`: its parts when\n * it holds a value, every segment empty when it is `null`.\n */\n reset(): void {\n this.#ownCommit = null;\n this.#retainedAnchor.set(null);\n this.editor.resetTyping();\n const source = untracked(this.config.source);\n this.parts.set(source === null ? this.emptyParts() : this.partsFrom(source));\n }\n\n /** Lowest accepted display value for `type`. */\n abstract segmentMin(type: SegmentType): number;\n\n /** Highest accepted display value for `type`. */\n abstract segmentMax(type: SegmentType): number;\n\n /** Base value for stepping an empty `type` on first step. */\n protected abstract seed(type: SegmentType): number;\n\n /** Placeholder shown while `type` is empty. */\n protected abstract placeholderFor(type: SegmentType): string;\n\n /** Field-specific `aria-valuetext` for `type`, or `null` for the numeric reading. */\n protected abstract valueText(type: SegmentType): string | null;\n\n /** Composes a parts record into the value, clamped to the bounds, or `null` while incomplete. */\n protected abstract composeFrom(parts: P): D | null;\n\n protected abstract partsFrom(value: D): P;\n\n /** A parts record with every segment empty. */\n protected abstract emptyParts(): P;\n\n protected abstract wallClockShifts(parts: P): boolean;\n\n protected someEditableEmpty(parts: P): boolean {\n return this.editableOrder().some((type) => parts[type] == null);\n }\n\n protected heldParts(current: D | null, previous: { readonly value: P } | undefined): P | null {\n if (previous && this.#ownCommit !== null && current === this.#ownCommit.source) {\n return previous.value;\n }\n this.#ownCommit = null;\n return null;\n }\n\n private settle(): void {\n const commit = this.#ownCommit;\n this.#ownCommit = null;\n if (commit?.rehydrate) {\n this.parts.set(this.partsFrom(commit.source!));\n }\n }\n\n /**\n * Finalizes the parts recorded by a commit before they are stored. The default\n * is the identity; the date engine overrides it to re-clamp the day on a\n * settled commit.\n */\n protected finalizeCommitParts(next: P, _transient: boolean): P {\n return next;\n }\n\n private commitParts(rawNext: P, transient: boolean): void {\n const next = this.finalizeCommitParts(rawNext, transient);\n this.parts.set(next);\n if (transient) {\n return;\n }\n const composed = this.composeFrom(next);\n const anchor = untracked(this.anchor);\n this.#adopted = null;\n this.#committing = true;\n try {\n this.config.onCommit(composed);\n } finally {\n this.#committing = false;\n }\n const source = untracked(this.config.source);\n if (source === null && anchor !== null) {\n this.#retainedAnchor.set(anchor);\n }\n const adopted = this.#takeAdopted();\n this.#ownCommit = adopted\n ? { source: adopted.source, rehydrate: true }\n : {\n source,\n rehydrate:\n source !== null &&\n composed !== null &&\n this.config.adapter.compare(source, composed) === 0,\n };\n }\n\n #takeAdopted(): { readonly source: D } | null {\n const adopted = this.#adopted;\n this.#adopted = null;\n return adopted;\n }\n\n /**\n * Records `value` as what the commit in progress resolved to, for a host that\n * normalises the commit (grafts it onto its own day, clamps it to its own\n * bounds) and hands the result back through `source`. The segments then keep\n * what was typed until the field settles, as they do when the engine clamps a\n * commit itself. Ignored outside `onCommit`.\n */\n adoptCommit(value: D): void {\n if (this.#committing) {\n this.#adopted = { source: value };\n }\n }\n}\n","import { type FieldSpec, type SegmentType } from './segment-editor';\n\n/** Date-time precision of a date field; `'day'` keeps it date-only. */\nexport type FieldGranularity = 'day' | 'hour' | 'minute' | 'second';\n\nconst DIGITS: Record<SegmentType, number> = {\n day: 2,\n month: 2,\n year: 4,\n hour: 2,\n minute: 2,\n second: 2,\n dayPeriod: 0,\n};\n\n/**\n * 1 Feb 2000: distinct day and month, so a locale that reuses a digit cannot\n * mask the part order. Only the `type` of each formatted part is read.\n */\nfunction referenceDate(): Date {\n return new Date(2000, 1, 1);\n}\n\n/**\n * 1 Feb 2000, 1:23:45 PM: distinct day / month and hour / minute / second, in\n * the afternoon so the `dayPeriod` part is present to read back.\n */\nfunction referenceDateTime(): Date {\n return new Date(2000, 1, 1, 13, 23, 45);\n}\n\n/**\n * Derives the ordered segment list for a day-granularity date field from the\n * runtime locale, using `Intl.DateTimeFormat(...).formatToParts`. The visible\n * order of day / month / year (and the separator characters between them)\n * follows the locale — `MM/DD/YYYY` for `en-US`, `DD.MM.YYYY` for `de-DE`,\n * `YYYY/MM/DD` for `ja-JP` — so the field never has to parse ambiguous\n * free text.\n *\n * Pure: the same `locale` always yields the same list, and it touches no\n * signals or DOM. A fixed reference date with distinct day / month values is\n * formatted purely to read back the part order; its actual value never\n * surfaces.\n *\n * @param locale BCP 47 locale, or `undefined` for the runtime default.\n */\nexport function buildSegments(locale: string | undefined): readonly FieldSpec[] {\n const parts = new Intl.DateTimeFormat(locale, {\n calendar: 'gregory',\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n }).formatToParts(referenceDate());\n\n const segments: FieldSpec[] = [];\n for (const part of parts) {\n switch (part.type) {\n case 'day':\n case 'month':\n case 'year':\n segments.push({ kind: 'editable', type: part.type, digits: DIGITS[part.type] });\n break;\n case 'literal':\n segments.push({ kind: 'literal', literal: part.value });\n break;\n default:\n break;\n }\n }\n return segments;\n}\n\n/**\n * Derives the ordered segment list for a date(-time) field. At\n * `granularity === 'day'` this is exactly {@link buildSegments} (date-only,\n * byte-for-byte). At a finer granularity it appends the locale-ordered time\n * segments (and the date↔time separator) by formatting a reference date-time\n * with both date and time options in a single `Intl.DateTimeFormat` pass, so\n * the order of every part — and whether an AM/PM `dayPeriod` is present —\n * follows the locale and the resolved hour cycle.\n *\n * Pure: the same arguments always yield the same list.\n *\n * @param locale BCP 47 locale, or `undefined` for the runtime default.\n * @param granularity Smallest editable unit; `'day'` stays date-only.\n * @param hourCycle Resolved hour cycle (`12` shows AM/PM, `24` does not).\n */\nexport function buildDateTimeSegments(\n locale: string | undefined,\n granularity: FieldGranularity,\n hourCycle: 12 | 24,\n): readonly FieldSpec[] {\n if (granularity === 'day') {\n return buildSegments(locale);\n }\n const options: Intl.DateTimeFormatOptions = {\n calendar: 'gregory',\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n hour12: hourCycle === 12,\n };\n if (granularity !== 'hour') {\n options.minute = '2-digit';\n }\n if (granularity === 'second') {\n options.second = '2-digit';\n }\n\n const parts = new Intl.DateTimeFormat(locale, options).formatToParts(referenceDateTime());\n const segments: FieldSpec[] = [];\n for (const part of parts) {\n switch (part.type) {\n case 'day':\n case 'month':\n case 'year':\n case 'hour':\n case 'minute':\n case 'second':\n case 'dayPeriod':\n segments.push({ kind: 'editable', type: part.type, digits: DIGITS[part.type] });\n break;\n case 'literal':\n segments.push({ kind: 'literal', literal: part.value });\n break;\n default:\n break;\n }\n }\n return segments;\n}\n","import type { DateAdapter, TimeCapableDateAdapter } from 'forty-cdk/date-adapter';\nimport { assertTimeCapable, compareDateOf } from './date-adapter';\n\n/**\n * The granularity at which a date control serializes its value: a bare calendar\n * day, or a day plus a wall-clock time down to the hour, minute, or second.\n */\nexport type DateSerializeGranularity = 'day' | 'hour' | 'minute' | 'second';\n\n/**\n * The granularity at which a time control serializes its value: a bare hour, or\n * an hour plus minutes, or down to the second.\n */\nexport type TimeSerializeGranularity = 'hour' | 'minute' | 'second';\n\n/**\n * Clamps `date` into the inclusive `[min, max]` range, returning the nearer\n * bound when `date` falls outside and `date` itself when it is within (or both\n * bounds are `null`). Comparison defaults to {@link DateAdapter.compare} (the\n * full instant); pass `compare` to clamp on a different ordering — the calendar\n * grid clamps day-granularly via `compareDateOf`, the form controls clamp on the\n * full instant via `adapter.compare`.\n *\n * @typeParam D The adapter's immutable date representation.\n * @param adapter The active date adapter (supplies the default comparator).\n * @param date The date to clamp.\n * @param min The lower bound (inclusive), or `null` for unbounded.\n * @param max The upper bound (inclusive), or `null` for unbounded.\n * @param compare Comparator returning `< 0` / `0` / `> 0`; defaults to\n * `adapter.compare`.\n */\nexport function clampToBounds<D>(\n adapter: DateAdapter<D>,\n date: D,\n min: D | null,\n max: D | null,\n compare: (a: D, b: D) => number = (a, b) => adapter.compare(a, b),\n): D {\n if (min !== null && compare(date, min) < 0) {\n return min;\n }\n if (max !== null && compare(date, max) > 0) {\n return max;\n }\n return date;\n}\n\n/**\n * The day a date-time picker grafts a committed time onto: its current `value`,\n * or, before any day is picked, today clamped day-granularly into `[min, max]` —\n * the day the projected calendar focuses when the value is empty. The caller\n * still clamps the composed instant, so a time outside the bounds on the\n * boundary day is clamped to the bound.\n *\n * @typeParam D The adapter's immutable date representation.\n * @param adapter The active date adapter.\n * @param value The picker's current value, or `null` when no day is picked.\n * @param min The lower bound (inclusive), or `null` for unbounded.\n * @param max The upper bound (inclusive), or `null` for unbounded.\n */\nexport function timeGraftBaseDay<D>(\n adapter: DateAdapter<D>,\n value: D | null,\n min: D | null,\n max: D | null,\n): D {\n return (\n value ??\n clampToBounds(adapter, adapter.today(), min, max, (a, b) => compareDateOf(adapter, a, b))\n );\n}\n\n/**\n * Serializes `date` to the ISO 8601 string the date controls write into their\n * native hidden input: `YYYY-MM-DD` at day granularity, `YYYY-MM-DDTHH:mm` at\n * hour / minute granularity, and `YYYY-MM-DDTHH:mm:ss` at second granularity.\n * At any non-day granularity the adapter must be time-capable; a day-only\n * adapter throws via {@link assertTimeCapable} with `piece` in the message,\n * reported under `scope`.\n *\n * @typeParam D The adapter's immutable date representation.\n * @param adapter The active date adapter.\n * @param date The value to serialize.\n * @param granularity The serialization granularity.\n * @param piece Name of the calling directive, used in the time-capability error.\n * @param options `scope` is the caller's entry point, which the time-capability\n * error reports under. It is required because this branch can be the first\n * report a consumer reads: a picker in the trigger anatomy has no projected\n * field to reject the adapter earlier.\n */\nexport function serializeISODate<D>(\n adapter: DateAdapter<D>,\n date: D,\n granularity: DateSerializeGranularity,\n piece: string,\n options: { readonly scope: string },\n): string {\n const year = String(adapter.getYear(date)).padStart(4, '0');\n const month = String(adapter.getMonth(date)).padStart(2, '0');\n const day = String(adapter.getDate(date)).padStart(2, '0');\n const isoDate = `${year}-${month}-${day}`;\n if (granularity === 'day') {\n return isoDate;\n }\n const time = assertTimeCapable(adapter, piece, options);\n const hour = String(time.getHours(date)).padStart(2, '0');\n const minute = String(time.getMinutes(date)).padStart(2, '0');\n if (granularity === 'second') {\n const second = String(time.getSeconds(date)).padStart(2, '0');\n return `${isoDate}T${hour}:${minute}:${second}`;\n }\n return `${isoDate}T${hour}:${minute}`;\n}\n\n/**\n * Serializes the wall-clock time of `date` to the ISO 8601 partial-time string\n * the time controls write into their native hidden input: `HH` at hour\n * granularity, `HH:mm` at minute granularity, and `HH:mm:ss` at second\n * granularity.\n *\n * @typeParam D The adapter's immutable date-time representation.\n * @param adapter The active time-capable date adapter.\n * @param date The value whose time-of-day is serialized.\n * @param granularity The serialization granularity.\n */\nexport function serializeISOTime<D>(\n adapter: TimeCapableDateAdapter<D>,\n date: D,\n granularity: TimeSerializeGranularity,\n): string {\n const hour = String(adapter.getHours(date)).padStart(2, '0');\n if (granularity === 'hour') {\n return hour;\n }\n const minute = String(adapter.getMinutes(date)).padStart(2, '0');\n if (granularity === 'minute') {\n return `${hour}:${minute}`;\n }\n const second = String(adapter.getSeconds(date)).padStart(2, '0');\n return `${hour}:${minute}:${second}`;\n}\n\n/**\n * Grafts the wall-clock time of `source` onto the calendar day of `day`,\n * returning a fresh date that keeps `day`'s date and carries `source`'s\n * hour / minute / second. Used when composing a date selection with a separately\n * edited time-of-day.\n *\n * @typeParam D The adapter's immutable date-time representation.\n * @param adapter The active time-capable date adapter.\n * @param day The date contributing the calendar day.\n * @param source The date contributing the wall-clock time.\n */\nexport function composeWithTime<D>(adapter: TimeCapableDateAdapter<D>, day: D, source: D): D {\n return adapter.setTime(\n day,\n adapter.getHours(source),\n adapter.getMinutes(source),\n adapter.getSeconds(source),\n );\n}\n\n/**\n * Whether `hours:minutes` on `day` is a wall-clock time the day skips, such as\n * the hour a spring-forward DST transition removes: the adapter normalizes it to\n * a different time.\n *\n * @typeParam D The adapter's immutable date-time representation.\n * @param adapter The active time-capable date adapter.\n * @param day The calendar day the time falls on.\n * @param hours The wall-clock hour (0-23).\n * @param minutes The wall-clock minute.\n */\nexport function shiftsWallClock<D>(\n adapter: TimeCapableDateAdapter<D>,\n day: D,\n hours: number,\n minutes: number,\n): boolean {\n const probe = adapter.setTime(day, hours, minutes, 0);\n return adapter.getHours(probe) !== hours || adapter.getMinutes(probe) !== minutes;\n}\n\n/**\n * The fixed, DST-stable sentinel date (`2000-01-01`) a time control anchors a\n * wall-clock time to when it has no committed date of its own, so a time always\n * round-trips through the adapter without an ambiguous-hour DST shift.\n *\n * @typeParam D The adapter's immutable date representation.\n * @param adapter The active date adapter.\n */\nexport function timeSentinel<D>(adapter: DateAdapter<D>): D {\n return adapter.createDate(2000, 1, 1);\n}\n\n/**\n * Reduces the wall-clock time of `date` to seconds-of-day (`hours * 3600 +\n * minutes * 60 + seconds`), ignoring the calendar day. Used to compare or clamp\n * two dates by their time-of-day alone.\n *\n * @typeParam D The adapter's immutable date-time representation.\n * @param adapter The active time-capable date adapter.\n * @param date The value whose time-of-day is reduced.\n */\nexport function secondsOfDay<D>(adapter: TimeCapableDateAdapter<D>, date: D): number {\n return adapter.getHours(date) * 3600 + adapter.getMinutes(date) * 60 + adapter.getSeconds(date);\n}\n","import { computed, linkedSignal, type Signal } from '@angular/core';\n\nimport type { DateAdapter, TimeCapableDateAdapter } from 'forty-cdk/date-adapter';\nimport { assertTimeCapable } from './date-adapter';\nimport { type BaseFieldEngineConfig, DateTimeFieldEngineBase } from './field-engine-base';\nimport { buildDateTimeSegments, type FieldGranularity } from './date-segments';\nimport { type FieldSpec, type SegmentType } from './segment-editor';\nimport { clampToBounds, composeWithTime, shiftsWallClock } from './serialize';\n\n/** Internal per-part state: the entered value for each editable segment, hour as 0-23. */\nexport interface DateTimeParts {\n day: number | null;\n month: number | null;\n year: number | null;\n hour: number | null;\n minute: number | null;\n second: number | null;\n dayPeriod: number | null;\n}\n\n/**\n * The reactive configuration a segmented date(-time) field supplies to its\n * {@link DateFieldEngine}. The shared `signal`-driven inputs (granularity,\n * hour cycle, locale, placeholder, bounds, disabled / read-only) plus the\n * authoritative `source` value and the `onCommit` sink let the engine derive\n * the locale-ordered segments, the entered parts, and the composed value\n * without owning any directive of its own.\n *\n * @typeParam D The adapter's immutable date (or date-time) type.\n */\nexport interface DateFieldEngineConfig<D> extends BaseFieldEngineConfig<D> {\n /** The active date adapter (shared with `ForCalendar`). */\n readonly adapter: DateAdapter<D>;\n /** Date-time precision; `'day'` keeps the field date-only. */\n readonly granularity: Signal<FieldGranularity>;\n /** Per-segment placeholder overrides shown while empty. */\n readonly placeholder: Signal<Partial<Record<SegmentType, string>>>;\n /** Minimum selectable date (inclusive), or `null` for unbounded. */\n readonly minDate: Signal<D | null>;\n /** Maximum selectable date (inclusive), or `null` for unbounded. */\n readonly maxDate: Signal<D | null>;\n /** Name of the owning directive, used in the time-capability error message. */\n readonly piece: string;\n /**\n * Entry point that error reports under, e.g. `'date-field'`. The engine is\n * shared, but the consumer who combined a time `granularity` with a day-only\n * adapter wrote a field, so the prefix must name theirs.\n */\n readonly scope: string;\n}\n\n/**\n * Year used to resolve day ranges (Feb length) while the year segment is empty.\n * A leap year so an empty-year February admits day 29: the day\n * segment reports `aria-valuemax=\"29\"`, and February 29 can be typed in the\n * natural year-last locale order (`M/d/y`, `d.M.y`) before the year settles. The\n * clamp down to 28 happens only once an actually-non-leap year is committed.\n */\nconst RESOLVER_YEAR = 2000;\n\n/**\n * The shared date(-time) field engine backing `ForDateField` and each endpoint\n * of `ForDateRangeField`. It owns everything a segmented date field needs on\n * top of the generic {@link SegmentEditor}: the locale-ordered spec list, the\n * resolved hour cycle, the entered {@link DateTimeParts} (rehydrated from the\n * configured `source`), the date-specific segment bounds / today-seed / month\n * `aria-valuetext` / day re-clamp, and the create-and-clamp compose. The owning\n * directive supplies the reactive {@link DateFieldEngineConfig} and decides what\n * to do with each composed value through `onCommit` (a single field writes its\n * own `value`; the range field reports the endpoint up to the root).\n *\n * Constructed directly (`new DateFieldEngine(config)`); it holds no injection\n * context, mirroring how {@link SegmentEditor} and `CalendarRangeSelection` are\n * lifted out of their roots.\n *\n * @typeParam D The adapter's immutable date (or date-time) type.\n */\nexport class DateFieldEngine<D> extends DateTimeFieldEngineBase<D, DateTimeParts> {\n readonly #config: DateFieldEngineConfig<D>;\n\n /**\n * The locale-ordered segment specs. A granularity finer than a day builds\n * hour / minute / second segments, so a day-only adapter throws here — at the\n * derivation that asked for a time segment, not from a scheduler callback.\n */\n protected readonly specs = computed<readonly FieldSpec[]>(() => {\n const granularity = this.#config.granularity();\n if (granularity !== 'day') {\n assertTimeCapable(this.#config.adapter, this.#config.piece, { scope: this.#config.scope });\n }\n return buildDateTimeSegments(this.locale(), granularity, this.cycle());\n });\n\n /**\n * The entered parts. A `linkedSignal` keyed on `source`: a non-null write\n * (consumer, `[formField]`, or a settled field) rehydrates the segments from\n * the date, while the value the field itself just committed keeps the parts\n * as entered until focus leaves its segments, so a clamped intermediate never\n * rewrites the segments still being edited. A `null` transition is\n * disambiguated by the prior parts: an *internal* edit clearing one segment\n * always leaves the others, so `previous` still carries a filled part and is\n * preserved (clearing the day never wipes the month / year); an *external*\n * reset of a complete value leaves `previous` fully filled, so the field\n * clears.\n */\n protected readonly parts = linkedSignal<D | null, DateTimeParts>({\n source: () => this.#config.source(),\n computation: (current, previous) => {\n const held = this.heldParts(current, previous);\n if (held !== null) {\n return held;\n }\n if (current !== null) {\n return this.partsFrom(current);\n }\n const prior = previous?.value;\n if (prior && this.someEditableEmpty(prior)) {\n return prior;\n }\n return this.emptyParts();\n },\n });\n\n constructor(config: DateFieldEngineConfig<D>) {\n super(config);\n this.#config = config;\n this.initEditor();\n }\n\n segmentMin(type: SegmentType): number {\n if (type === 'hour') {\n return this.hourMin();\n }\n if (type === 'minute' || type === 'second' || type === 'dayPeriod') {\n return 0;\n }\n return 1;\n }\n\n segmentMax(type: SegmentType): number {\n switch (type) {\n case 'month':\n return 12;\n case 'year':\n return 9999;\n case 'hour':\n return this.cycle() === 12 ? this.hourMin() + 11 : 23;\n case 'minute':\n case 'second':\n return 59;\n case 'dayPeriod':\n return 1;\n default: {\n const parts = this.parts();\n const probe = this.#config.adapter.createDate(\n parts.year ?? RESOLVER_YEAR,\n parts.month ?? 1,\n 1,\n );\n return this.#config.adapter.getDaysInMonth(probe);\n }\n }\n }\n\n /** The active adapter, narrowed to a time-capable one; throws when it is day-only. */\n #time(): TimeCapableDateAdapter<D> {\n return assertTimeCapable(this.#config.adapter, this.#config.piece, {\n scope: this.#config.scope,\n });\n }\n\n #preserveSourceTime(day: D): D {\n const anchor = this.anchor();\n if (anchor === null || this.#config.adapter.supportsTime?.() !== true) {\n return day;\n }\n return composeWithTime(\n assertTimeCapable(this.#config.adapter, this.#config.piece, { scope: this.#config.scope }),\n day,\n anchor,\n );\n }\n\n /** Field-specific `aria-valuetext`: the empty marker or the localized month name. */\n protected valueText(type: SegmentType): string | null {\n if (this.isSegmentEmpty(type)) {\n return this.#config.emptySegmentText();\n }\n if (type !== 'month') {\n return null;\n }\n const month = this.parts().month;\n if (month === null) {\n return null;\n }\n // Route the month name through the adapter's `format` so it tracks the\n // adapter's calendar system rather than assuming Gregorian month numbering.\n // A probe date built with `createDate` maps the 1-12 number to a localized\n // long name without involving the entered value.\n return this.#config.adapter.format(\n this.#config.adapter.createDate(RESOLVER_YEAR, month, 1),\n { month: 'long' },\n this.locale(),\n );\n }\n\n /** Base value for stepping an empty segment: date parts from today, time parts from their minimum. */\n protected seed(type: SegmentType): number {\n if (type === 'hour') {\n return this.#toInternalHour(this.segmentMin('hour'));\n }\n if (type === 'minute' || type === 'second' || type === 'dayPeriod') {\n return 0;\n }\n const adapter = this.#config.adapter;\n const today = adapter.today();\n const base =\n type === 'day'\n ? adapter.getDate(today)\n : type === 'month'\n ? adapter.getMonth(today)\n : adapter.getYear(today);\n return Math.min(this.segmentMax(type), Math.max(this.segmentMin(type), base));\n }\n\n /** Converts a 12-hour display hour to a 0-23 hour, preserving the entered AM/PM. */\n #toInternalHour(display: number): number {\n if (this.cycle() === 24) {\n return display;\n }\n const parts = this.parts();\n const pm =\n parts.dayPeriod !== null ? parts.dayPeriod === 1 : parts.hour !== null && parts.hour >= 12;\n const base = display % 12;\n return pm ? base + 12 : base;\n }\n\n protected placeholderFor(type: SegmentType): string {\n const override = this.#config.placeholder()[type];\n if (override) {\n return override;\n }\n switch (type) {\n case 'day':\n return 'dd';\n case 'month':\n return 'mm';\n case 'year':\n return 'yyyy';\n case 'hour':\n return 'hh';\n case 'minute':\n return 'mm';\n case 'second':\n return 'ss';\n default:\n return '--';\n }\n }\n\n protected partsFrom(value: D): DateTimeParts {\n const adapter = this.#config.adapter;\n const parts: DateTimeParts = {\n day: adapter.getDate(value),\n month: adapter.getMonth(value),\n year: adapter.getYear(value),\n hour: null,\n minute: null,\n second: null,\n dayPeriod: null,\n };\n if (this.#config.granularity() !== 'day') {\n const time = this.#time();\n parts.hour = time.getHours(value);\n parts.minute = time.getMinutes(value);\n parts.second = time.getSeconds(value);\n parts.dayPeriod = time.getHours(value) >= 12 ? 1 : 0;\n }\n return parts;\n }\n\n protected emptyParts(): DateTimeParts {\n return {\n day: null,\n month: null,\n year: null,\n hour: null,\n minute: null,\n second: null,\n dayPeriod: null,\n };\n }\n\n protected wallClockShifts(parts: DateTimeParts): boolean {\n if (parts.hour === null || parts.day === null || parts.month === null || parts.year === null) {\n return false;\n }\n const day = this.#config.adapter.createDate(parts.year, parts.month, parts.day);\n return shiftsWallClock(this.#time(), day, parts.hour, parts.minute ?? 0);\n }\n\n /**\n * Re-clamps `day` to the resolved month/year length so the day segment's\n * `aria-valuenow` never exceeds its `aria-valuemax` after stepping the month\n * or year (e.g. day 31 + step to February → 28/29). Only ever shrinks the\n * day; an empty day is left untouched.\n */\n #clampDay(parts: DateTimeParts): DateTimeParts {\n if (parts.day === null) {\n return parts;\n }\n const adapter = this.#config.adapter;\n const probe = adapter.createDate(parts.year ?? RESOLVER_YEAR, parts.month ?? 1, 1);\n const maxDay = adapter.getDaysInMonth(probe);\n if (parts.day <= maxDay) {\n return parts;\n }\n return { ...parts, day: maxDay };\n }\n\n /**\n * Composes a parts record into the value, clamped to the bounds, or `null`\n * while any visible segment, the AM/PM one included, is empty.\n */\n protected composeFrom(parts: DateTimeParts): D | null {\n if (this.someEditableEmpty(parts)) {\n return null;\n }\n const granularity = this.#config.granularity();\n const needHour = granularity !== 'day';\n const needMinute = granularity === 'minute' || granularity === 'second';\n const needSecond = granularity === 'second';\n let created = this.#config.adapter.createDate(parts.year!, parts.month!, parts.day!);\n if (needHour) {\n created = this.#time().setTime(\n created,\n parts.hour!,\n needMinute ? parts.minute! : 0,\n needSecond ? parts.second! : 0,\n );\n } else {\n created = this.#preserveSourceTime(created);\n }\n return clampToBounds(\n this.#config.adapter,\n created,\n this.#config.minDate(),\n this.#config.maxDate(),\n );\n }\n\n protected override finalizeCommitParts(next: DateTimeParts, transient: boolean): DateTimeParts {\n return transient ? next : this.#clampDay(next);\n }\n}\n","import { Directive } from '@angular/core';\n\n/**\n * Shared base for the decorative separator directives `[forDateFieldLiteral]`\n * and `[forTimeFieldLiteral]`. It marks the host `aria-hidden` and keeps it out\n * of the tab order, so assistive tech reads only the spinbutton segments. The\n * separator characters come from the root's locale-ordered `segments()` list.\n *\n * `@Directive` without a `selector` so the public subclasses declare the\n * concrete `[forXxxFieldLiteral]` selector and `exportAs`; the `aria-hidden`\n * host binding is inherited.\n */\n@Directive({\n host: {\n 'aria-hidden': 'true',\n },\n})\nexport abstract class ForDateTimeLiteralBase {}\n","import { InjectionToken, type Signal } from '@angular/core';\n\n/**\n * The picker every source projected into it defers to: a `[forCalendar]`, a\n * `[forTimeField]` or a `[forTimePicker]` is read-only or disabled whenever its\n * picker is, on top of its own inputs.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\nexport interface PickerSourceHost {\n /** The picker's effective disabled state. */\n readonly effectiveDisabled: Signal<boolean>;\n /** The picker's read-only state. */\n readonly readonly: Signal<boolean>;\n}\n\n/**\n * Token `[forDatePicker]` and `[forDateRangePicker]` provide so the calendar and\n * the time source projected into them can find them.\n */\nexport const FOR_PICKER_SOURCE_HOST = new InjectionToken<PickerSourceHost>(\n 'FOR_PICKER_SOURCE_HOST',\n);\n","import { signal, type WritableSignal } from '@angular/core';\n\n/**\n * Marks at most one key at a time, read per key: {@link has} is reactive, and\n * {@link move} notifies only the reads of the key losing the mark and of the\n * key gaining it, so a group of N items that each read their own key pays O(1)\n * per move instead of O(N).\n *\n * Internal core tier — used by the roving and pointer trackers, with no semver\n * guarantee.\n */\nexport class KeyedFlag<K extends object> {\n readonly #slots = new WeakMap<K, WritableSignal<boolean>>();\n\n #current: K | null = null;\n\n /** The marked key, or `null`. Not reactive. */\n get current(): K | null {\n return this.#current;\n }\n\n /** Whether `key` holds the mark. Reactive per key. */\n has(key: K): boolean {\n return this.#slot(key)();\n }\n\n /** Hand the mark to `next`, or clear it with `null`. */\n move(next: K | null): void {\n const previous = this.#current;\n if (previous === next) {\n return;\n }\n this.#current = next;\n if (previous !== null) {\n this.#slot(previous).set(false);\n }\n if (next !== null) {\n this.#slot(next).set(true);\n }\n }\n\n #slot(key: K): WritableSignal<boolean> {\n let slot = this.#slots.get(key);\n if (slot === undefined) {\n slot = signal(this.#current === key);\n this.#slots.set(key, slot);\n }\n return slot;\n }\n}\n","import { computed, type Signal, signal, untracked } from '@angular/core';\n\nimport type { HostRovingItemHandle } from './host-roving-context';\n\n/**\n * Whether a disabled item of a roving group holds DOM focus, the state in which\n * every item of the group yields its tab stop so `Tab` and `Shift+Tab` leave\n * the group from that item. Fed through {@link noteFocus}.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\nexport class RovingFocusYield {\n /** The element last reported to {@link noteFocus}; a plain field so a focus move notifies nothing. */\n #focused: Element | null = null;\n\n /**\n * Set by the first {@link noteFocus} naming an element. Until then\n * {@link yields} does not track the items, so a group focus never entered\n * never reads its item list.\n */\n #tracksItems = false;\n\n /** Bumped by a {@link noteFocus} that changes {@link yields}, the only way a focus move reaches it. */\n readonly #epoch = signal(0);\n\n readonly #items: () => readonly HostRovingItemHandle[];\n\n /**\n * `true` while the element last reported to {@link noteFocus} is a disabled\n * item. Notifies its readers only when that answer changes, not on every\n * focus move inside the group.\n */\n readonly yields: Signal<boolean>;\n\n constructor(items: () => readonly HostRovingItemHandle[]) {\n this.#items = items;\n this.yields = computed(() => {\n this.#epoch();\n if (this.#tracksItems) {\n for (const item of items()) {\n item.disabled();\n }\n }\n return untracked(() => this.#holdsDisabled());\n });\n }\n\n /** Report the element holding DOM focus inside the group, or `null` once focus left it. */\n noteFocus(el: Element | null): void {\n untracked(() => {\n if (this.#focused === el) {\n return;\n }\n const before = this.yields();\n this.#focused = el;\n const subscribes = el !== null && !this.#tracksItems;\n if (subscribes) {\n this.#tracksItems = true;\n }\n if (subscribes || this.#holdsDisabled() !== before) {\n this.#epoch.update((epoch) => epoch + 1);\n }\n });\n }\n\n #holdsDisabled(): boolean {\n const focused = this.#focused;\n return (\n focused !== null && this.#items().some((item) => item.host === focused && item.disabled())\n );\n }\n}\n","import { computed, linkedSignal, type Signal, signal, untracked } from '@angular/core';\n\nimport { KeyedFlag } from '../keyed-flag/keyed-flag';\nimport type { HostRovingItemHandle } from './host-roving-context';\nimport { RovingFocusYield } from './roving-focus-yield';\n\n/**\n * Tracks the single \"active\" element of a roving-tabindex group: the one\n * with `tabindex=0`, while every other registered item gets `tabindex=-1`.\n * The active item is the entry point for `Tab` into the group; arrow-key\n * navigation moves it (the consumer wires this with `KeyboardNavigation`).\n *\n * The utility does not handle key events. Its job is to expose\n * a reactive `tabindexFor(el)` for host bindings on each item, plus\n * `setActive` / `focusActive` for the consumer.\n *\n * The active pointer is **self-healing** on read: a stale active element —\n * one that has detached from the document, or carries `disabled` /\n * `aria-disabled` (every primitive reflects its disabled state to one of\n * those attributes) — is discounted by every call to `hasActive` /\n * `tabindexFor`, so the consumer's first-enabled fallback re-engages and the\n * group keeps exactly one tab stop even before reconciliation settles. A\n * reactive read (a `computed`, a host binding) re-runs only when a signal it\n * read changes, and detaching an element changes none, so a container calls\n * {@link unregister} when an item leaves the group.\n *\n * When constructed with an `items` producer, the active pointer is also\n * **reconciled reactively**: whenever the active host leaves the group's\n * usable set (unregisters, becomes disabled, or detaches), `active()` is\n * re-seeded. The `fallback` option chooses how: `'none'` (default) nulls it\n * so each item's first-enabled fallback re-engages (pull-based, for a\n * container whose item tabindex derives from {@link hasActive}), while\n * `'nearest'` promotes the closest usable handle before the departed one in\n * the previous item order, else the closest after it, else the first enabled\n * (push-based, for a container whose item tabindex reads {@link active} and\n * needs a concrete owner rather than a null pointer, e.g. Tree). Under\n * `'nearest'` the departed pointer is kept, so a host that is re-enabled\n * reclaims the tab stop. Omitting `items` yields a pass-through of the raw\n * pointer for consumers that own no roving collection (date-field /\n * time-field).\n *\n * While a disabled item of the `items` producer holds DOM focus, as reported\n * through {@link noteFocus}, every item **yields**: {@link tabindexFor} is `-1`\n * for all of them and {@link hasActive} reports that the tracker owns the tab\n * stop, so the group holds none and `Tab` / `Shift+Tab` leave it.\n *\n * The per-item reads, {@link isActive}, {@link tabindexFor} and {@link hasActive},\n * cost O(1) per move: moving the active element between two usable items\n * notifies only the reads for those two items, so a group of N items does not\n * re-evaluate N item bindings per arrow key. {@link active} stays a group-wide\n * read for the container's own handlers.\n *\n * Construct directly with `new RovingTabindex()` — there is no internal\n * state requiring an injection context or `DestroyRef` cleanup.\n */\nexport class RovingTabindex {\n readonly #rawActive = signal<HTMLElement | null>(null);\n\n /** Marks the element {@link setActive} last named, read per item by {@link isActive}. */\n readonly #raw = new KeyedFlag<HTMLElement>();\n\n /**\n * Bumped by a write that changes {@link #settled}'s answer, the only way a\n * change of the raw pointer reaches it, so a move that leaves the answer as\n * it was notifies none of its readers.\n */\n readonly #epoch = signal(0);\n\n /**\n * Set by the first write naming an element. Until then {@link #settled} does\n * not track the items, so a group nothing has been focused in never reads\n * its item list.\n */\n #tracksItems = false;\n\n /**\n * The group-wide facts every item reads: whether the tracker owns the tab\n * stop, and the element promoted in place of an unusable raw pointer. Tracks\n * the items and their `disabled` state, which can move the reconciled\n * pointer without a write, and reads the raw pointer untracked.\n */\n readonly #settled: Signal<Settled>;\n\n readonly #keepsDeparted: boolean;\n\n readonly #focusYield: RovingFocusYield | null;\n\n readonly #active: Signal<HTMLElement | null>;\n\n /**\n * The active element, or `null`. Follows the last {@link setActive} call,\n * reconciled away from a host that has left the usable set when an `items`\n * producer is supplied (otherwise verbatim). Use it for \"is this the\n * focused candidate\" styling (`data-highlighted`). For the tab-stop gate,\n * prefer {@link hasActive}, which additionally discounts a stale active on\n * read.\n */\n readonly active: Signal<HTMLElement | null>;\n\n constructor(\n items?: () => readonly HostRovingItemHandle[],\n options: { fallback?: 'none' | 'nearest' } = {},\n ) {\n const fallback = options.fallback ?? 'none';\n this.#keepsDeparted = fallback === 'nearest';\n this.#active = linkedSignal<ActiveSource, HTMLElement | null>({\n source: () => {\n const raw = this.#rawActive();\n return { items: items && raw !== null ? items() : null, raw };\n },\n computation: ({ items: list, raw }, previous) => {\n if (list === null || raw === null) {\n return raw;\n }\n const handle = list.find((item) => item.host === raw);\n if (handle && !handle.disabled() && raw.isConnected) {\n return raw;\n }\n if (fallback === 'none') {\n return null;\n }\n const anchor = previous?.source.raw === raw ? (previous.value ?? raw) : raw;\n return nearestUsable(list, previous?.source.items ?? null, anchor);\n },\n });\n this.active = this.#active;\n this.#focusYield = items ? new RovingFocusYield(items) : null;\n this.#settled = computed(\n () => {\n this.#epoch();\n if (items && this.#tracksItems) {\n for (const item of items()) {\n item.disabled();\n }\n }\n return untracked(() => this.#settle());\n },\n { equal: sameSettled },\n );\n }\n\n /**\n * Whether `el` is the active element, as {@link active} reports it. Reactive\n * per element: a move notifies only the reads for the element losing the\n * pointer and the element gaining it.\n */\n isActive(el: HTMLElement): boolean {\n if (this.#raw.has(el)) {\n return this.#active() === el;\n }\n return this.#settled().promoted === el;\n }\n\n /**\n * Whether the tracker currently owns the tab stop: a usable active element\n * does, and so does a group whose items yield while a disabled item holds\n * focus. `false` when nothing is active **or** the active element is stale\n * (detached / disabled) at the time of the call, signalling the consumer to\n * fall back to its first-enabled entry point. Reactive — wire the per-item\n * `tabindex` gate to this rather than `active() !== null`.\n */\n hasActive(): boolean {\n if (this.#focusYield?.yields() === true) {\n return true;\n }\n if (!this.#settled().owns) {\n return false;\n }\n const el = untracked(this.#active);\n return el !== null && !isStale(el);\n }\n\n /**\n * Whether {@link active} is non-null, without {@link hasActive}'s discount of\n * a stale element. Notifies its readers only when that answer changes.\n */\n holdsActive(): boolean {\n return this.#settled().present;\n }\n\n /**\n * Returns the tabindex value for `el`: `0` if it is the active element,\n * `-1` otherwise. Reactive — wire into a host binding.\n *\n * If no element is active yet (or the active element is stale), or the items\n * yield to a focused disabled item, returns `-1` for everything. The container directive is responsible for promoting\n * one item (typically the first enabled one) to active on init.\n */\n tabindexFor(el: HTMLElement): 0 | -1 {\n if (this.#focusYield?.yields() === true) {\n return -1;\n }\n return this.isActive(el) && !isStale(el) ? 0 : -1;\n }\n\n /**\n * Report the element holding DOM focus inside the group, or `null` once focus\n * has left it. Call it from the group host's `focusin` and `focusout`; while\n * it names a disabled item, every item yields the tab stop.\n */\n noteFocus(el: Element | null): void {\n this.#focusYield?.noteFocus(el);\n }\n\n setActive(el: HTMLElement | null): void {\n this.#write(el);\n }\n\n /**\n * Drop `el` as the active element if it currently is, resetting the tracker\n * to \"no active\" so the first-enabled fallback reclaims the tab stop.\n * No-op when `el` is not the active element. Containers call this when an\n * item unregisters (`DestroyRef.onDestroy`) so a removed host never lingers\n * as the entry point. No-op under `fallback: 'nearest'`, which re-seeds from\n * the position the removed host held instead.\n */\n unregister(el: HTMLElement): void {\n if (!this.#keepsDeparted && this.#active() === el) {\n this.#write(null);\n }\n }\n\n /**\n * Move active to `el` and immediately focus it. Convenience for arrow-key\n * handlers.\n */\n focusActive(el?: HTMLElement | null): void {\n const target = el ?? this.#active();\n if (!target) {\n return;\n }\n if (target !== this.#active()) {\n this.#write(target);\n }\n target.focus();\n }\n\n #write(next: HTMLElement | null): void {\n untracked(() => {\n if (this.#rawActive() === next) {\n return;\n }\n const before = this.#settled();\n this.#raw.move(next);\n this.#rawActive.set(next);\n const after = this.#settle();\n const subscribes = next !== null && !this.#tracksItems;\n if (subscribes) {\n this.#tracksItems = true;\n }\n if (subscribes || !sameSettled(before, after)) {\n this.#epoch.update((epoch) => epoch + 1);\n }\n });\n }\n\n #settle(): Settled {\n const raw = this.#rawActive();\n const active = this.#active();\n return {\n present: active !== null,\n owns: active !== null && !isStale(active),\n promoted: active === raw ? null : active,\n };\n }\n}\n\ninterface Settled {\n readonly present: boolean;\n readonly owns: boolean;\n readonly promoted: HTMLElement | null;\n}\n\nfunction sameSettled(a: Settled, b: Settled): boolean {\n return a.present === b.present && a.owns === b.owns && a.promoted === b.promoted;\n}\n\ninterface ActiveSource {\n readonly items: readonly HostRovingItemHandle[] | null;\n readonly raw: HTMLElement | null;\n}\n\nfunction nearestUsable(\n list: readonly HostRovingItemHandle[],\n order: readonly HostRovingItemHandle[] | null,\n anchor: HTMLElement,\n): HTMLElement | null {\n const usable = new Set(\n list.filter((item) => !item.disabled() && item.host.isConnected).map((item) => item.host),\n );\n if (usable.has(anchor)) {\n return anchor;\n }\n const at = order?.findIndex((item) => item.host === anchor) ?? -1;\n if (order !== null && at >= 0) {\n for (let i = at - 1; i >= 0; i--) {\n if (usable.has(order[i]!.host)) {\n return order[i]!.host;\n }\n }\n for (let i = at + 1; i < order.length; i++) {\n if (usable.has(order[i]!.host)) {\n return order[i]!.host;\n }\n }\n }\n return list.find((item) => usable.has(item.host))?.host ?? null;\n}\n\nfunction isStale(el: HTMLElement): boolean {\n return (\n !el.isConnected || el.hasAttribute('disabled') || el.getAttribute('aria-disabled') === 'true'\n );\n}\n","import {\n computed,\n linkedSignal,\n type Signal,\n signal,\n untracked,\n type WritableSignal,\n} from '@angular/core';\n\nimport { type DateRange } from './date-range';\nimport type { WritingDirection } from '../keyboard-navigation/keyboard-navigation';\nimport { RovingTabindex } from '../roving-tabindex/roving-tabindex';\nimport { type SegmentEditorDelegate } from './segment-editor';\nimport { type SegmentEditorContext } from './segment-directive';\n\n/** Which endpoint of a range field — the composer keys its two sources on this. */\nexport type RangeFieldEndpoint = 'start' | 'end';\n\n/**\n * The date / time field engine surface the composer provides as an endpoint's\n * {@link SegmentEditorContext} delegate: the per-segment accessors and behavior\n * methods. Both `DateFieldEngine` and `TimeFieldEngine` satisfy it structurally,\n * so one composer coordinates either flavour of endpoint. Alias of\n * {@link SegmentEditorDelegate}.\n */\nexport type RangeFieldEndpointEngine = SegmentEditorDelegate;\n\n/**\n * The engine surface {@link RangeFieldComposer.commitEndpoint} hands a held\n * endpoint's composed value back through. Both `DateFieldEngine` and\n * `TimeFieldEngine` satisfy it structurally.\n */\nexport interface RangeFieldCommitTarget<D> {\n adoptCommit(value: D): void;\n}\n\n/** The committed range paired with the generation of its last internal write. */\ninterface CommittedRange<D> {\n range: DateRange<D> | null;\n generation: number;\n}\n\n/**\n * The reactive configuration a range field root supplies to its\n * {@link RangeFieldComposer}. The shared `value` model plus the field-level\n * `effectiveDisabled` / `readonly` / `dir` signals wire the endpoint contexts;\n * the `composedStart` / `composedEnd` thunks read each engine's composed value\n * (lazy, so the engines can be built *after* the composer); and the `compose` /\n * `disordered` / `normalizeEndpointSource` policies are the only behaviour that\n * differs between a date range and a time range.\n *\n * @typeParam D The adapter's immutable date (or date-time) type.\n */\nexport interface RangeFieldComposerConfig<D> {\n /** The field's committed range model — the composer's sole write target. */\n readonly value: WritableSignal<DateRange<D> | null>;\n /** The field's effective disabled (own input OR a surrounding disabled `[forFieldset]`). */\n readonly effectiveDisabled: Signal<boolean>;\n /** Whether the field is read-only. */\n readonly readonly: Signal<boolean>;\n /** Resolved writing direction, mirrored onto each endpoint context. */\n readonly dir: Signal<WritingDirection>;\n /** Reads the start endpoint's composed value (or `null` while incomplete). */\n readonly composedStart: () => D | null;\n /** Reads the end endpoint's composed value (or `null` while incomplete). */\n readonly composedEnd: () => D | null;\n /**\n * Builds the committed range from two complete, non-null endpoints, or returns\n * `null` when they cannot form a valid range. A date range commits `{ start,\n * end }` only when ordered; a time range additionally maps a `start > end`\n * entry to a midnight-crossing range under `allowOvernight`.\n */\n readonly compose: (start: D, end: D) => DateRange<D> | null;\n /**\n * Whether two complete, non-null endpoints are an unorderable, error range\n * (reflected as `aria-invalid`). Distinct from {@link compose} because a time\n * range in overnight mode composes a `start > end` entry into a valid range\n * yet is never flagged.\n */\n readonly disordered: (start: D, end: D) => boolean;\n /**\n * Normalizes an endpoint pulled from a committed range before it seeds the\n * engine's source. Omitted (identity) for a date range; a time range in\n * overnight mode re-anchors each endpoint on the DST-stable sentinel so the\n * engine composes purely on time-of-day.\n */\n readonly normalizeEndpointSource?: (value: D) => D;\n}\n\n/**\n * The shared range-composition core backing `ForDateRangeField` and\n * `ForTimeRangeField`. It owns everything the two roots duplicated line for\n * line: the per-endpoint roving trackers, the generation-tagged committed value,\n * the two rehydration sources (with the internal-vs-external `null`\n * disambiguation), the `disordered` signal, the `recompose` commit, and the\n * per-endpoint {@link SegmentEditorContext} construction. The field-specific\n * ordering / overnight / sentinel policies enter through\n * {@link RangeFieldComposerConfig}.\n *\n * Constructed directly (`new RangeFieldComposer(config)`); it holds no injection\n * context, mirroring how `DateFieldEngine` / `TimeFieldEngine` and\n * `SegmentEditor` are lifted out of their roots. The `composedStart` /\n * `composedEnd` config thunks are read lazily, so a root can build its engines\n * from {@link startSource} / {@link endSource} *after* constructing the composer.\n *\n * @typeParam D The adapter's immutable date (or date-time) type.\n */\nexport class RangeFieldComposer<D> {\n readonly #config: RangeFieldComposerConfig<D>;\n\n /** Shared roving-tabindex tracker for the start endpoint's segments. */\n readonly startRoving = new RovingTabindex();\n /** Shared roving-tabindex tracker for the end endpoint's segments. */\n readonly endRoving = new RovingTabindex();\n\n /**\n * Monotonic generation bumped by {@link recompose} on every value it writes.\n * It tags each *internal* commit so an endpoint source can tell a `null` the\n * field itself produced (one endpoint mid-edit or the two out of order) from a\n * `null` an external reset wrote — the two are indistinguishable by the\n * `value` alone, since `null === null`.\n */\n readonly #commitGeneration = signal(0);\n\n readonly #committedValue = computed<CommittedRange<D>>(() => ({\n range: this.#config.value(),\n generation: this.#commitGeneration(),\n }));\n\n /**\n * The start endpoint's rehydration source. A `linkedSignal` keyed on the\n * committed range tagged with the commit generation: a non-null `value`\n * (external write or our own commit) drives the endpoint from `range.start`; a\n * `null` `value` is disambiguated by the generation — an **internal** null\n * (the generation advanced since the last computation, because *either*\n * endpoint is mid-edit or the two are out of order) **preserves** the prior\n * endpoint value so a complete endpoint isn't wiped while its sibling is\n * incomplete; an **external** null over a non-null range (a Signal Forms\n * reset or a consumer `[(value)]=\"null\"`, where the generation is unchanged)\n * **clears** the endpoint. An external null over an internal one changes no\n * signal, so it reaches the endpoint only through {@link reset}. Each\n * endpoint reads its own `previous`, so there is no cross-endpoint race.\n */\n readonly startSource = linkedSignal<CommittedRange<D>, D | null>({\n source: this.#committedValue,\n computation: (committed, previous) => this.#rehydrate(committed, previous, 'start'),\n });\n /** The end endpoint's rehydration source; mirror of {@link startSource} for `range.end`. */\n readonly endSource = linkedSignal<CommittedRange<D>, D | null>({\n source: this.#committedValue,\n computation: (committed, previous) => this.#rehydrate(committed, previous, 'end'),\n });\n\n /**\n * Both endpoints complete but they cannot form a valid range — reflected as\n * `aria-invalid` by the root. `false` whenever either endpoint is still\n * incomplete, then delegated to the config's {@link RangeFieldComposerConfig.disordered}\n * policy.\n */\n readonly disordered = computed(() => {\n const start = this.#config.composedStart();\n const end = this.#config.composedEnd();\n if (start === null || end === null) {\n return false;\n }\n return this.#config.disordered(start, end);\n });\n\n constructor(config: RangeFieldComposerConfig<D>) {\n this.#config = config;\n }\n\n /**\n * Re-assembles the committed range from both endpoints' composed values and\n * writes it to `value`. Emits the config's composed range when both endpoints\n * are complete, otherwise clears to `null` while preserving each endpoint's\n * typed segments (their parts survive an internal `null` value). Every write\n * bumps the commit generation so the endpoint sources mark the resulting\n * `null` as internal.\n */\n recompose(): void {\n const start = this.#config.composedStart();\n const end = this.#config.composedEnd();\n this.#commitGeneration.update((generation) => generation + 1);\n if (start === null || end === null) {\n this.#config.value.set(null);\n return;\n }\n this.#config.value.set(this.#config.compose(start, end));\n }\n\n /**\n * The `onCommit` sink of an endpoint engine: {@link recompose}s the range and,\n * while the range is held at an internal `null` (the other endpoint incomplete,\n * or the two out of order), hands the endpoint's composed value back to its\n * engine through `adoptCommit`. The engine then shows that value once focus\n * leaves the endpoint, so an entry clamped to the bounds displays clamped\n * without waiting for the other endpoint, as it does in a complete range.\n *\n * @param engine The engine whose commit is in progress.\n * @param composed The value it composed, clamped to its bounds, or `null` while incomplete.\n */\n commitEndpoint(engine: RangeFieldCommitTarget<D>, composed: D | null): void {\n this.recompose();\n if (composed !== null && untracked(this.#config.value) === null) {\n engine.adoptCommit(composed);\n }\n }\n\n /**\n * Re-seeds both endpoint sources from the current `value`, dropping an\n * endpoint preserved across an internal `null`. The root resets each\n * endpoint's engine right after, so their segments follow.\n */\n reset(): void {\n const range = untracked(this.#config.value);\n this.startSource.set(range === null ? null : this.#endpointOf(range, 'start'));\n this.endSource.set(range === null ? null : this.#endpointOf(range, 'end'));\n }\n\n /**\n * Builds the {@link SegmentEditorContext} an endpoint group provides to its\n * segment / literal children: the field-level `effectiveDisabled` / `readonly`\n * / `dir` plus that endpoint's roving tracker, with `engine` as the\n * per-segment accessor / behavior delegate.\n *\n * @param engine The endpoint's date / time field engine.\n * @param which Which endpoint, selecting its roving tracker.\n */\n makeEndpointContext(\n engine: RangeFieldEndpointEngine,\n which: RangeFieldEndpoint,\n ): SegmentEditorContext {\n return {\n effectiveDisabled: this.#config.effectiveDisabled,\n readonly: this.#config.readonly,\n dir: this.#config.dir,\n roving: which === 'start' ? this.startRoving : this.endRoving,\n delegate: engine,\n };\n }\n\n #rehydrate(\n committed: CommittedRange<D>,\n previous: { source: CommittedRange<D>; value: D | null } | undefined,\n which: RangeFieldEndpoint,\n ): D | null {\n if (committed.range !== null) {\n return this.#endpointOf(committed.range, which);\n }\n if (previous && committed.generation !== previous.source.generation) {\n return previous.value;\n }\n return null;\n }\n\n #endpointOf(range: DateRange<D>, which: RangeFieldEndpoint): D {\n const endpoint = range[which];\n return this.#config.normalizeEndpointSource\n ? this.#config.normalizeEndpointSource(endpoint)\n : endpoint;\n }\n}\n","/**\n * Whether `event` belongs to an IME composition rather than to the page.\n *\n * True while a composition is in progress (`isComposing`), and for the keydown an engine reports\n * with `keyCode` 229 — WebKit's keydown for the key that commits or cancels a composition arrives\n * after `compositionend` with `isComposing` already `false`. An Escape that cancels a CJK\n * conversion is one of these, so a handler that closes or clears on Escape returns early on it and\n * leaves the key to the IME.\n */\nexport function isImeComposing(event: KeyboardEvent): boolean {\n return event.isComposing || event.keyCode === 229;\n}\n","export function captureContent(host: HTMLElement): () => void {\n const parents: (readonly [Node, readonly ChildNode[]])[] = [];\n const texts: (readonly [ChildNode, string | null])[] = [];\n const visit = (node: Node): void => {\n const children = Array.from(node.childNodes);\n parents.push([node, children]);\n for (const child of children) {\n if (child.nodeType === child.TEXT_NODE) {\n texts.push([child, child.nodeValue]);\n } else {\n visit(child);\n }\n }\n };\n visit(host);\n return () => {\n for (const [parent, children] of parents) {\n const current = parent.childNodes;\n if (current.length !== children.length || children.some((child, i) => current[i] !== child)) {\n (parent as ParentNode).replaceChildren(...children);\n }\n }\n for (const [text, value] of texts) {\n if (text.nodeValue !== value) {\n text.nodeValue = value;\n }\n }\n };\n}\n","const DECIMAL_DIGIT = /^\\p{Nd}$/u;\n\n/**\n * Maps a single Unicode decimal digit character (General_Category `Nd`) to its\n * numeric value `0`–`9`, regardless of numbering system — ASCII `'0'`–`'9'`,\n * Arabic-Indic, Devanagari, Bengali, Thai, fullwidth, and so on. Returns `null`\n * for anything that is not exactly one decimal digit, including multi-character\n * keys (`'Enter'`, `'ArrowUp'`), the empty string, and non-digit characters.\n */\nexport function unicodeDigitValue(char: string): number | null {\n if (!DECIMAL_DIGIT.test(char)) {\n return null;\n }\n const code = char.codePointAt(0)!;\n if (code >= 0x30 && code <= 0x39) {\n return code - 0x30;\n }\n let start = code;\n while (DECIMAL_DIGIT.test(String.fromCodePoint(start - 1))) {\n start--;\n }\n return (code - start) % 10;\n}\n","import { computed, Directive, ElementRef, inject, type Signal } from '@angular/core';\n\nimport { registerHandle } from '../collection/register-handle';\nimport { isImeComposing } from '../keyboard-navigation/ime-composition';\nimport { isHistoryChord, isShortcutChord } from '../keyboard-navigation/modifier-chord';\nimport type { WritingDirection } from '../keyboard-navigation/keyboard-navigation';\nimport type { RovingTabindex } from '../roving-tabindex/roving-tabindex';\nimport { captureContent } from './editable-content';\nimport type { SegmentEditorDelegate, SegmentType } from './segment-editor';\nimport { unicodeDigitValue } from './unicode-digit';\n\n/**\n * The coordination surface a date / time root exposes to its segment children,\n * as consumed by the shared {@link ForDateTimeSegmentBase}. The field-level\n * `effectiveDisabled` / `readonly` / `dir` / `roving` signals come off the root\n * directly; every per-part accessor and behavior method lives on the\n * {@link SegmentEditorDelegate} (the field engine itself), reached through\n * `delegate`.\n */\nexport interface SegmentEditorContext {\n /**\n * The field's effective disabled — its own `disabled` input OR'd with a\n * surrounding disabled `[forFieldset]`. Segments read this so a disabled field\n * (or fieldset) is inert and exposes `aria-disabled`.\n */\n readonly effectiveDisabled: Signal<boolean>;\n /** Whether the field is read-only. */\n readonly readonly: Signal<boolean>;\n /** Resolved writing direction (mirrors ArrowLeft / ArrowRight navigation). */\n readonly dir: Signal<WritingDirection>;\n /** Shared roving-tabindex tracker: one segment owns `tabindex=0` at a time. */\n readonly roving: RovingTabindex;\n /** The field engine backing the per-segment accessors and behavior methods. */\n readonly delegate: SegmentEditorDelegate;\n}\n\n/**\n * The shared spinbutton segment directive backing `[forDateFieldSegment]` and\n * `[forTimeFieldSegment]`. It owns `role=\"spinbutton\"`, the `aria-value*`\n * reflection, the roving tabindex, the digit / arrow / Home-End / Backspace\n * (pop last digit) / Delete (clear whole segment) keyboard map (RTL-mirrored\n * ArrowLeft / ArrowRight), and the segment\n * registration. While the field is neither disabled nor read-only the host is a\n * `contenteditable=\"plaintext-only\"` editing host, so a touch device opens its\n * on-screen keyboard; text the browser would insert goes through the same digit /\n * AM·PM handling as a key press and never reaches the DOM. All state lives on the\n * root via {@link SegmentEditorContext}; the segment only reads it and forwards\n * intents.\n *\n * `@Directive` without a `selector` so the public subclasses\n * (`ForDateFieldSegment` / `ForTimeFieldSegment`) declare the concrete\n * `[forXxxFieldSegment]` selector, `exportAs`, and the `segment` /\n * `ariaLabel` inputs. The host block and behavior are inherited.\n */\n@Directive({\n host: {\n role: 'spinbutton',\n '[attr.tabindex]': 'tabindex()',\n '[attr.contenteditable]': 'editable() ? \"plaintext-only\" : null',\n '[attr.inputmode]': 'inputmode()',\n '[attr.autocorrect]': 'editable() ? \"off\" : null',\n '[attr.spellcheck]': 'editable() ? \"false\" : null',\n '[attr.aria-valuemin]': 'ctx.delegate.segmentMin(segment())',\n '[attr.aria-valuemax]': 'ctx.delegate.segmentMax(segment())',\n '[attr.aria-valuenow]': 'valueNow()',\n '[attr.aria-valuetext]': 'ctx.delegate.segmentValueText(segment())',\n '[attr.aria-label]': 'resolvedAriaLabel()',\n '[attr.aria-disabled]': 'ctx.effectiveDisabled() ? \"true\" : null',\n '[attr.aria-readonly]': 'ctx.readonly() ? \"true\" : null',\n '[attr.data-highlighted]': 'highlighted() ? \"\" : null',\n '[attr.data-placeholder]': 'ctx.delegate.isSegmentEmpty(segment()) ? \"\" : null',\n '[attr.data-disabled]': 'ctx.effectiveDisabled() ? \"\" : null',\n '[attr.data-readonly]': 'ctx.readonly() ? \"\" : null',\n '(keydown)': 'onKeyDown($event)',\n '(beforeinput)': 'onBeforeInput($event)',\n '(input)': 'onInput($event)',\n '(compositionend)': 'onCompositionEnd($event)',\n '(focus)': 'onFocus()',\n '(blur)': 'onBlur($event)',\n },\n})\nexport abstract class ForDateTimeSegmentBase {\n /** The coordination surface of the surrounding date / time root. */\n protected abstract readonly ctx: SegmentEditorContext;\n\n /** Which date or time part this segment edits. */\n abstract readonly segment: Signal<SegmentType>;\n\n /** Accessible name for this segment. Falls back to the segment type when unset. */\n abstract readonly ariaLabel: Signal<string | null>;\n\n private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);\n\n /**\n * The accessible name bound to `aria-label`. Defaults to the explicit\n * `ariaLabel` input, falling back to the raw segment type; the concrete\n * subclasses override this to source localized, injector-scoped defaults.\n */\n protected readonly resolvedAriaLabel: Signal<string> = computed(\n () => this.ariaLabel() ?? this.segment(),\n );\n\n private readonly valueNow = computed(() => this.ctx.delegate.segmentValue(this.segment()));\n\n private readonly editable = computed(() => !this.ctx.effectiveDisabled() && !this.ctx.readonly());\n\n private readonly inputmode = computed<'numeric' | null>(() =>\n this.editable() && this.segment() !== 'dayPeriod' ? 'numeric' : null,\n );\n\n #restoreContent: (() => void) | null = null;\n\n private readonly highlighted = computed(() => this.ctx.roving.isActive(this.host.nativeElement));\n\n /**\n * APG tabindex: the user-focused segment owns `tabindex=0` (tracked by the\n * shared `RovingTabindex`). Before any interaction the first segment in the\n * locale order is the field's single tab entry; disabled fields are skipped.\n */\n private readonly tabindex = computed<-1 | 0>(() => {\n if (this.ctx.effectiveDisabled()) {\n return -1;\n }\n if (this.ctx.roving.hasActive()) {\n return this.ctx.roving.tabindexFor(this.host.nativeElement);\n }\n return this.ctx.delegate.isFirstSegmentType(this.segment()) ? 0 : -1;\n });\n\n protected registerSegment(): void {\n const handle = { host: this.host.nativeElement, type: this.segment };\n registerHandle(\n handle,\n (h) => this.ctx.delegate.registerSegment(h),\n (h) => this.ctx.delegate.unregisterSegment(h),\n 'afterNextRender',\n );\n }\n\n private onFocus(): void {\n this.ctx.delegate.focusSegment(this.segment());\n if (this.editable()) {\n const host = this.host.nativeElement;\n host.ownerDocument.getSelection()?.collapse(host, 0);\n }\n }\n\n private onBlur(event: FocusEvent): void {\n this.ctx.delegate.endTyping(event.relatedTarget);\n }\n\n private onBeforeInput(event: InputEvent): void {\n if (!event.cancelable) {\n this.#restoreContent ??= captureContent(this.host.nativeElement);\n return;\n }\n event.preventDefault();\n if (!this.editable()) {\n return;\n }\n const type = this.segment();\n switch (event.inputType) {\n case 'deleteContentBackward':\n this.ctx.delegate.backspace(type);\n return;\n case 'deleteContentForward':\n this.ctx.delegate.clear(type);\n return;\n case 'insertCompositionText':\n case 'insertFromComposition':\n case 'deleteCompositionText':\n return;\n default:\n if (event.data !== null) {\n this.#typeText(type, event.data);\n }\n }\n }\n\n private onInput(event: InputEvent): void {\n const restore = this.#restoreContent;\n this.#restoreContent = null;\n restore?.();\n const type = this.segment();\n if (\n event.inputType === 'insertCompositionText' &&\n event.data &&\n type === 'dayPeriod' &&\n this.editable()\n ) {\n this.ctx.delegate.setDayPeriodFromKey(event.data.charAt(0));\n }\n }\n\n private onCompositionEnd(event: CompositionEvent): void {\n if (event.data && this.editable()) {\n this.#typeText(this.segment(), event.data);\n }\n }\n\n #typeText(type: SegmentType, text: string): void {\n const host = this.host.nativeElement;\n const chars = Array.from(text);\n for (let i = 0; i < chars.length; i++) {\n this.#typeCharacter(type, chars[i]!);\n const next = this.ctx.roving.active();\n if (next !== null && next !== host && i < chars.length - 1) {\n next.dispatchEvent(\n new InputEvent('beforeinput', {\n inputType: 'insertText',\n data: chars.slice(i + 1).join(''),\n cancelable: true,\n }),\n );\n return;\n }\n }\n }\n\n #typeCharacter(type: SegmentType, char: string): boolean {\n const digit = unicodeDigitValue(char);\n if (digit !== null) {\n this.ctx.delegate.typeDigit(type, digit);\n return true;\n }\n return type === 'dayPeriod' && this.ctx.delegate.setDayPeriodFromKey(char);\n }\n\n private onKeyDown(event: KeyboardEvent): void {\n if (this.ctx.effectiveDisabled() || isImeComposing(event)) {\n return;\n }\n const type = this.segment();\n const key = event.key;\n if (!isShortcutChord(event) && this.#typeCharacter(type, key)) {\n event.preventDefault();\n return;\n }\n if (isHistoryChord(event) && isSegmentNavigationKey(key)) {\n return;\n }\n const rtl = this.ctx.dir() === 'rtl';\n switch (key) {\n case 'ArrowUp':\n event.preventDefault();\n this.ctx.delegate.step(type, 1);\n return;\n case 'ArrowDown':\n event.preventDefault();\n this.ctx.delegate.step(type, -1);\n return;\n case 'ArrowRight':\n event.preventDefault();\n this.ctx.delegate.focusSibling(type, rtl ? -1 : 1);\n return;\n case 'ArrowLeft':\n event.preventDefault();\n this.ctx.delegate.focusSibling(type, rtl ? 1 : -1);\n return;\n case 'Home':\n event.preventDefault();\n this.ctx.delegate.goToBound(type, 'min');\n return;\n case 'End':\n event.preventDefault();\n this.ctx.delegate.goToBound(type, 'max');\n return;\n case 'Backspace':\n event.preventDefault();\n this.ctx.delegate.backspace(type);\n return;\n case 'Delete':\n event.preventDefault();\n this.ctx.delegate.clear(type);\n return;\n default:\n return;\n }\n }\n}\n\nfunction isSegmentNavigationKey(key: string): boolean {\n return key.startsWith('Arrow') || key === 'Home' || key === 'End';\n}\n","import { computed, InjectionToken, type Signal } from '@angular/core';\n\nimport type { DateAdapter } from 'forty-cdk/date-adapter';\nimport type { FieldGranularity } from './date-segments';\nimport type { PickerSourceHost } from './picker-source-host';\nimport type { SegmentEditorContext } from './segment-directive';\nimport type { TimeGranularity } from './time-segments';\n\n/**\n * What a segmented field registers with the picker that adopts it: the element\n * the picker names through a surrounding `[forField]`, and the focus and reset\n * entry points the picker's own `focus()` / `reset()` delegate to.\n */\nexport interface AdoptedField {\n /** The field's `role=\"group\"` host. */\n readonly element: HTMLElement;\n /** Moves focus to the field's first editable segment. */\n focus(options?: FocusOptions): void;\n /** Discards a partly typed entry and redisplays the picker's value. */\n reset(): void;\n /**\n * Records `value` as what the field's commit in progress resolved to once a\n * picker downstream normalised it, so the typed segments survive it.\n */\n adoptCommit(value: unknown): void;\n}\n\n/**\n * The picker a segmented field defers to while the picker's `anatomy` is\n * `'field'`. The picker is the form control: the field reads its value and\n * state from here and writes its commits back through {@link commitFieldValue}.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n *\n * @typeParam D The adapter's immutable date (or date-time) type.\n */\nexport interface SegmentedFieldHost<D> {\n /** The picker's date adapter; the field must resolve the same one. */\n readonly adapter: DateAdapter<D>;\n /** Whether the picker currently adopts its projected field. */\n readonly adoptsField: Signal<boolean>;\n /** The picker's value, which the adopted field displays and edits. */\n readonly value: Signal<D | null>;\n /** The picker's effective disabled state. */\n readonly effectiveDisabled: Signal<boolean>;\n /** The picker's read-only state. */\n readonly readonly: Signal<boolean>;\n /** The picker's required state. */\n readonly required: Signal<boolean>;\n /** The picker's invalid state. */\n readonly invalid: Signal<boolean>;\n /** The picker's pending state, which the adopted field reflects as `aria-busy`. */\n readonly pending: Signal<boolean>;\n /** The picker's hour cycle after its scope defaults, or `null` to let the field resolve its own. */\n readonly resolvedHourCycle: Signal<12 | 24 | null>;\n /** The picker's locale, or `null` to let the field resolve its own. */\n readonly locale: Signal<string | null>;\n /** Registers the projected field. */\n registerField(field: AdoptedField): void;\n /** Removes a previously registered field. */\n unregisterField(field: AdoptedField): void;\n /** Writes a value the adopted field composed into the picker. */\n commitFieldValue(value: D | null): void;\n /** Marks the picker touched. */\n markTouched(): void;\n /**\n * The elements that make up the picker as one control: its root and its open\n * surface. A focus move between them does not mark the picker touched.\n */\n touchBoundaries(): readonly (Node | null)[];\n}\n\n/**\n * {@link SegmentedFieldHost} provided by `[forDatePicker]` for a projected\n * `[forDateField]`.\n *\n * @typeParam D The adapter's immutable date (or date-time) type.\n */\nexport interface DateFieldHost<D> extends SegmentedFieldHost<D> {\n /** The picker's minimum date. */\n readonly minDate: Signal<D | null>;\n /** The picker's maximum date. */\n readonly maxDate: Signal<D | null>;\n /** The picker's date-time precision. */\n readonly granularity: Signal<FieldGranularity>;\n}\n\n/**\n * {@link SegmentedFieldHost} provided by `[forTimePicker]` for a projected\n * `[forTimeField]`.\n *\n * @typeParam D The adapter's immutable date-time type.\n */\nexport interface TimeFieldHost<D> extends SegmentedFieldHost<D> {\n /** The picker's earliest time of day. */\n readonly minTime: Signal<D | null>;\n /** The picker's latest time of day. */\n readonly maxTime: Signal<D | null>;\n /** The picker's smallest time unit. */\n readonly granularity: Signal<TimeGranularity>;\n}\n\n/** Token `[forDatePicker]` provides so a projected `[forDateField]` can find it. */\nexport const FOR_DATE_FIELD_HOST = new InjectionToken<DateFieldHost<unknown>>(\n 'FOR_DATE_FIELD_HOST',\n);\n\n/** Token `[forTimePicker]` provides so a projected `[forTimeField]` can find it. */\nexport const FOR_TIME_FIELD_HOST = new InjectionToken<TimeFieldHost<unknown>>(\n 'FOR_TIME_FIELD_HOST',\n);\n\n/**\n * The segment-facing view of a field's context with the disabled and read-only\n * states folded in of an adopting picker and of a picker the field is projected\n * into as a time source, so a segment's `aria-disabled` / `aria-readonly` match\n * what the field's engine enforces. Returns `ctx` itself when neither is\n * reachable.\n *\n * @param ctx The field's own coordination context.\n * @param host The picker that may adopt the field, or `null`.\n * @param source The picker the field is projected into as a source, or `null`.\n */\nexport function adoptedSegmentContext(\n ctx: SegmentEditorContext,\n host: SegmentedFieldHost<unknown> | null,\n source: PickerSourceHost | null = null,\n): SegmentEditorContext {\n if (host === null && source === null) {\n return ctx;\n }\n return {\n effectiveDisabled: computed(\n () =>\n ctx.effectiveDisabled() ||\n (host?.adoptsField() === true && host.effectiveDisabled()) ||\n (source?.effectiveDisabled() ?? false),\n ),\n readonly: computed(\n () =>\n ctx.readonly() ||\n (host?.adoptsField() === true && host.readonly()) ||\n (source?.readonly() ?? false),\n ),\n dir: ctx.dir,\n roving: ctx.roving,\n delegate: ctx.delegate,\n };\n}\n","import { type FieldSpec } from './segment-editor';\nimport { type TimeSegmentType } from './segment-types';\n\n/** Smallest editable time unit; controls which segments are rendered. */\nexport type TimeGranularity = 'hour' | 'minute' | 'second';\n\nconst DIGITS: Record<TimeSegmentType, number> = {\n hour: 2,\n minute: 2,\n second: 2,\n dayPeriod: 0,\n};\n\n/**\n * 1:23:45 PM: distinct hour / minute / second values, in the afternoon so the\n * `dayPeriod` part is present to read back. Only each part's `type` and the\n * separators are read.\n */\nfunction referenceTime(): Date {\n return new Date(2000, 0, 1, 13, 23, 45);\n}\n\n/**\n * Derives the ordered segment list for a time field from the runtime locale,\n * the resolved hour cycle, and the granularity, using\n * `Intl.DateTimeFormat(...).formatToParts`. The visible order of the segments\n * (and the separators between them), and whether an AM/PM `dayPeriod` segment\n * is present, follow the locale and the 12-/24-hour cycle.\n *\n * Pure: the same arguments always yield the same list, touching no signals or\n * DOM.\n *\n * @param locale BCP 47 locale, or `undefined` for the runtime default.\n * @param hourCycle Resolved hour cycle (`12` shows AM/PM, `24` does not).\n * @param granularity Smallest editable unit; trims minute / second segments.\n */\nexport function buildTimeSegments(\n locale: string | undefined,\n hourCycle: 12 | 24,\n granularity: TimeGranularity,\n): readonly FieldSpec[] {\n const options: Intl.DateTimeFormatOptions = {\n calendar: 'gregory',\n hour: '2-digit',\n hour12: hourCycle === 12,\n };\n if (granularity !== 'hour') {\n options.minute = '2-digit';\n }\n if (granularity === 'second') {\n options.second = '2-digit';\n }\n\n const parts = new Intl.DateTimeFormat(locale, options).formatToParts(referenceTime());\n const segments: FieldSpec[] = [];\n for (const part of parts) {\n switch (part.type) {\n case 'hour':\n case 'minute':\n case 'second':\n case 'dayPeriod':\n segments.push({ kind: 'editable', type: part.type, digits: DIGITS[part.type] });\n break;\n case 'literal':\n segments.push({ kind: 'literal', literal: part.value });\n break;\n default:\n break;\n }\n }\n return segments;\n}\n","import { computed, linkedSignal, type Signal } from '@angular/core';\n\nimport type { TimeCapableDateAdapter } from 'forty-cdk/date-adapter';\nimport { type BaseFieldEngineConfig, DateTimeFieldEngineBase } from './field-engine-base';\nimport { type FieldSpec, type SegmentType } from './segment-editor';\nimport { type TimeSegmentType } from './segment-types';\nimport { composeWithTime, secondsOfDay, shiftsWallClock, timeSentinel } from './serialize';\nimport { buildTimeSegments, type TimeGranularity } from './time-segments';\n\n/** Internal per-part state: the entered value for each editable time segment, hour as 0-23. */\nexport interface TimeParts {\n hour: number | null;\n minute: number | null;\n second: number | null;\n dayPeriod: number | null;\n}\n\n/**\n * The reactive configuration a segmented time-of-day field supplies to its\n * {@link TimeFieldEngine}. The shared `signal`-driven inputs (granularity, hour\n * cycle, locale, placeholder, bounds, disabled / read-only) plus the\n * authoritative `source` value and the `onCommit` sink let the engine derive the\n * locale-ordered segments, the entered parts, and the composed value without\n * owning any directive of its own.\n *\n * @typeParam D The adapter's immutable, time-capable date-time type.\n */\nexport interface TimeFieldEngineConfig<D> extends BaseFieldEngineConfig<D> {\n /** The active, time-capable date adapter (shared with `ForCalendar`). */\n readonly adapter: TimeCapableDateAdapter<D>;\n /** Smallest editable unit (`'hour'` / `'minute'` / `'second'`). */\n readonly granularity: Signal<TimeGranularity>;\n /** Per-segment placeholder overrides shown while empty. */\n readonly placeholder: Signal<Partial<Record<TimeSegmentType, string>>>;\n /** Earliest selectable time-of-day (inclusive), or `null` for unbounded. */\n readonly minTime: Signal<D | null>;\n /** Latest selectable time-of-day (inclusive), or `null` for unbounded. */\n readonly maxTime: Signal<D | null>;\n}\n\n/**\n * The shared time-of-day field engine backing `ForTimeField` and each endpoint\n * of `ForTimeRangeField`. It owns everything a segmented time field needs on top\n * of the generic {@link SegmentEditor}: the locale-ordered spec list, the\n * resolved hour cycle, the entered {@link TimeParts} (rehydrated from the\n * configured `source`), the time-specific segment bounds / min-hour seed / empty\n * `aria-valuetext`, and the sentinel-anchored setTime/clamp compose. The owning\n * directive supplies the reactive {@link TimeFieldEngineConfig} and decides what\n * to do with each composed value through `onCommit` (a single field writes its\n * own `value`; the range field reports the endpoint up to the root).\n *\n * Constructed directly (`new TimeFieldEngine(config)`); it holds no injection\n * context, mirroring how {@link SegmentEditor} and `DateFieldEngine` are lifted\n * out of their roots.\n *\n * @typeParam D The adapter's immutable, time-capable date-time type.\n */\nexport class TimeFieldEngine<D> extends DateTimeFieldEngineBase<D, TimeParts, TimeSegmentType> {\n readonly #config: TimeFieldEngineConfig<D>;\n\n protected readonly specs = computed<readonly FieldSpec[]>(() =>\n buildTimeSegments(this.locale(), this.cycle(), this.#config.granularity()),\n );\n\n /**\n * The entered parts. A `linkedSignal` keyed on `source`: a non-null write\n * (consumer, `[formField]`, or a settled field) rehydrates the segments from\n * the date-time, while the value the field itself just committed keeps the\n * parts as entered until focus leaves its segments, so a clamped intermediate\n * never rewrites the segments still being edited. A `null` transition is\n * disambiguated by the prior parts: an *internal* edit clearing one segment\n * leaves the others, so `previous` still carries a filled part and is\n * preserved; an *external* reset of a complete value leaves `previous` fully\n * filled, so the field clears.\n */\n protected readonly parts = linkedSignal<D | null, TimeParts>({\n source: () => this.#config.source(),\n computation: (current, previous) => {\n const held = this.heldParts(current, previous);\n if (held !== null) {\n return held;\n }\n if (current !== null) {\n return this.partsFrom(current);\n }\n const prior = previous?.value;\n if (prior && this.someEditableEmpty(prior)) {\n return prior;\n }\n return this.emptyParts();\n },\n });\n\n constructor(config: TimeFieldEngineConfig<D>) {\n super(config);\n this.#config = config;\n this.initEditor();\n }\n\n segmentMin(type: SegmentType): number {\n if (type === 'hour') {\n return this.hourMin();\n }\n return 0;\n }\n\n segmentMax(type: SegmentType): number {\n if (type === 'hour') {\n return this.cycle() === 12 ? this.hourMin() + 11 : 23;\n }\n if (type === 'dayPeriod') {\n return 1;\n }\n return 59;\n }\n\n /** Field-specific `aria-valuetext`: only the empty marker; numeric otherwise. */\n protected valueText(type: SegmentType): string | null {\n return this.isSegmentEmpty(type) ? this.#config.emptySegmentText() : null;\n }\n\n /** Base value for stepping an empty segment: the hour from its minimum (midnight in 24-hour and `h11`, 1 AM in `h12`), minute and second 0. */\n protected seed(type: SegmentType): number {\n if (type !== 'hour') {\n return 0;\n }\n const display = this.segmentMin('hour');\n if (this.cycle() === 24) {\n return display;\n }\n const parts = this.parts();\n const pm =\n parts.dayPeriod !== null ? parts.dayPeriod === 1 : parts.hour !== null && parts.hour >= 12;\n const base = display % 12;\n return pm ? base + 12 : base;\n }\n\n protected placeholderFor(type: SegmentType): string {\n if (type === 'hour' || type === 'minute' || type === 'second' || type === 'dayPeriod') {\n const override = this.#config.placeholder()[type];\n if (override) {\n return override;\n }\n }\n switch (type) {\n case 'hour':\n return 'hh';\n case 'minute':\n return 'mm';\n case 'second':\n return 'ss';\n default:\n return '--';\n }\n }\n\n /**\n * Composes a parts record into the value, clamped to the bounds, or `null`\n * while any visible segment, the AM/PM one included, is empty.\n */\n protected composeFrom(parts: TimeParts): D | null {\n if (this.someEditableEmpty(parts)) {\n return null;\n }\n const granularity = this.#config.granularity();\n const needMinute = granularity !== 'hour';\n const needSecond = granularity === 'second';\n const base = this.#base();\n const composed = this.#config.adapter.setTime(\n base,\n parts.hour!,\n needMinute ? parts.minute! : 0,\n needSecond ? parts.second! : 0,\n );\n return this.#clampToBounds(composed);\n }\n\n protected partsFrom(value: D): TimeParts {\n const adapter = this.#config.adapter;\n return {\n hour: adapter.getHours(value),\n minute: adapter.getMinutes(value),\n second: adapter.getSeconds(value),\n dayPeriod: adapter.getHours(value) >= 12 ? 1 : 0,\n };\n }\n\n protected emptyParts(): TimeParts {\n return { hour: null, minute: null, second: null, dayPeriod: null };\n }\n\n protected wallClockShifts(parts: TimeParts): boolean {\n if (parts.hour === null) {\n return false;\n }\n return shiftsWallClock(this.#config.adapter, this.#base(), parts.hour, parts.minute ?? 0);\n }\n\n #base(): D {\n return this.anchor() ?? timeSentinel(this.#config.adapter);\n }\n\n #clampToBounds(date: D): D {\n const adapter = this.#config.adapter;\n const min = this.#config.minTime();\n if (min !== null && secondsOfDay(adapter, date) < secondsOfDay(adapter, min)) {\n return composeWithTime(adapter, date, min);\n }\n const max = this.#config.maxTime();\n if (max !== null && secondsOfDay(adapter, date) > secondsOfDay(adapter, max)) {\n return composeWithTime(adapter, date, max);\n }\n return date;\n }\n}\n","import { InjectionToken, type ModelSignal } from '@angular/core';\nimport type { DateAdapter } from 'forty-cdk/date-adapter';\n\n/**\n * Shared contract implemented by both `ForTimeField` and `ForTimePicker`. The\n * `ForDatePicker` time bridge queries this token via `contentChild` so it can\n * observe whichever time-editing primitive the consumer projects — without a\n * hard import of either, keeping date-picker tree-shaking intact.\n *\n * @typeParam D The adapter's date-time type.\n */\nexport interface TimeValueSource<D> {\n readonly value: ModelSignal<D | null>;\n readonly adapter: DateAdapter<D>;\n /**\n * Records `value` as what the source's commit in progress resolved to in the\n * picker, which grafts it onto its day and clamps it to its bounds before\n * handing it back through the one-way `[value]` binding. Called synchronously\n * from the picker's `valueChange` subscription; a source with no typed\n * segments ignores it.\n */\n adoptCommit(value: D): void;\n /**\n * Discards a partly typed time the source holds and redisplays its value.\n * The picker forwards its own `FormUiControl.reset` here, so a Signal Forms\n * reset reaches a draft the picker's value cannot represent.\n */\n reset(): void;\n}\n\n/**\n * Token provided by `ForTimeField` and `ForTimePicker`. `ForDatePicker`\n * queries descendants for this token to locate the projected time source.\n */\nexport const FOR_TIME_VALUE_SOURCE = new InjectionToken<TimeValueSource<unknown>>(\n 'FOR_TIME_VALUE_SOURCE',\n);\n","/**\n * Text a defaults key holds: a plain string, or a function returning the\n * current string. The library calls the function each time it reads the\n * text, from inside the reactive context that renders or announces it, so a\n * function that reads a signal (the active language, say) keeps the text\n * current as that signal changes.\n *\n * @example\n * ```ts\n * provideForComboboxDefaults(() => {\n * const i18n = inject(AppI18n);\n * return { clearAriaLabel: () => i18n.t('combobox.clear') };\n * });\n * ```\n */\nexport type LocalizableText = string | (() => string);\n\nexport function resolveText(text: LocalizableText): string {\n return typeof text === 'function' ? text() : text;\n}\n\nexport function resolveTextInput(\n own: string | null | undefined,\n fallback: LocalizableText,\n): string | null {\n return own === undefined ? resolveText(fallback) : own;\n}\n\nexport function resolveTextRecord<K extends string>(\n scope: Partial<Record<K, LocalizableText>>,\n own: Partial<Record<K, string>>,\n): Partial<Record<K, string>> {\n const result: Partial<Record<K, string>> = {};\n for (const key of Object.keys(scope) as K[]) {\n const text = scope[key];\n if (text !== undefined) {\n result[key] = resolveText(text);\n }\n }\n for (const key of Object.keys(own) as K[]) {\n const text = own[key];\n if (text !== undefined) {\n result[key] = text;\n }\n }\n return result;\n}\n","import { type DragRect } from './drag-geometry';\n\n/** A point in viewport coordinates (the preview's top-left). */\nexport interface PreviewPoint {\n readonly x: number;\n readonly y: number;\n}\n\n/** The preview box's measured size. */\nexport interface PreviewSize {\n readonly width: number;\n readonly height: number;\n}\n\n/**\n * Constrains a drag preview's desired top-left position.\n *\n * Applies, in order:\n * - **axis lock** — when `lockAxis` is `'x'` the preview moves along the x axis only, so its\n * `y` is held at `origin.y`; when `'y'` it moves along the y axis only, so its `x` is held at\n * `origin.x`; `null` leaves both free.\n * - **boundary clamp** — when `boundary` is non-null, the resulting top-left is clamped so the\n * preview box (`size`) stays fully inside the boundary rect. When the boundary is smaller than\n * the preview on an axis, the preview is pinned to the boundary's start edge on that axis.\n *\n * Pure: takes already-measured rects/sizes, performs no DOM reads. `origin` is the preview's\n * desired top-left at lift time (the axis-lock anchor).\n */\nexport function clampPreviewPosition(\n desired: PreviewPoint,\n size: PreviewSize,\n boundary: DragRect | null,\n lockAxis: 'x' | 'y' | null,\n origin: PreviewPoint,\n): PreviewPoint {\n let x = lockAxis === 'y' ? origin.x : desired.x;\n let y = lockAxis === 'x' ? origin.y : desired.y;\n if (boundary) {\n x = Math.max(boundary.left, Math.min(x, boundary.right - size.width));\n y = Math.max(boundary.top, Math.min(y, boundary.bottom - size.height));\n }\n return { x, y };\n}\n\n/**\n * Resolves a drag `boundary` input into the element that confines the movement.\n *\n * `null` is unbounded and yields `null`; an `HTMLElement` is returned as-is; a string is treated as\n * a selector resolved with `host.closest(...)`, so it matches the host itself or the nearest\n * matching ancestor and yields `null` when nothing matches.\n *\n * Unlike {@link clampPreviewPosition} this reads the DOM, so the caller decides *when* the lookup\n * happens: `[forDropList]` resolves once at lift time and hands the element to\n * `PreviewController`; `[forFreeDrag]` re-resolves on every move.\n */\nexport function resolveBoundaryElement(\n host: HTMLElement,\n boundary: HTMLElement | string | null,\n): HTMLElement | null {\n if (boundary === null) {\n return null;\n }\n return typeof boundary === 'string' ? host.closest<HTMLElement>(boundary) : boundary;\n}\n","/** Minimal rectangle shape (structurally satisfied by `DOMRect`). */\nexport interface DragRect {\n readonly left: number;\n readonly top: number;\n readonly right: number;\n readonly bottom: number;\n}\n\n/** A drop container's live geometry: its own rect plus the rects of its non-lifted items. */\nexport interface DropContainerGeometry {\n readonly rect: DragRect;\n /** Item rects in DOM order, EXCLUDING the lifted item. */\n readonly itemRects: readonly DragRect[];\n /**\n * This container's own layout axis — the insertion index is resolved against it. `'mixed'` is\n * 2D resolution for wrapping grids of uniformly-sized items, considering both axes; it reduces\n * to the single-axis result when the items form a single row or a single column.\n */\n readonly orientation: 'horizontal' | 'vertical' | 'mixed';\n /** This container's own resolved writing direction. */\n readonly dir: 'ltr' | 'rtl';\n readonly clip?: DragRect;\n}\n\n/** A resolved pointer drop target: a container plus the insertion index within it. */\nexport interface DropTarget {\n /** Index into the `[source, ...connected]` container array (0 = source). */\n readonly containerIndex: number;\n /** Insertion index within that container. */\n readonly index: number;\n}\n\nfunction rectContains(rect: DragRect, x: number, y: number): boolean {\n return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;\n}\n\nfunction visibleRect(container: DropContainerGeometry): DragRect {\n const { rect, clip } = container;\n if (!clip) {\n return rect;\n }\n return {\n left: Math.max(rect.left, clip.left),\n top: Math.max(rect.top, clip.top),\n right: Math.min(rect.right, clip.right),\n bottom: Math.min(rect.bottom, clip.bottom),\n };\n}\n\nfunction isEmptyRect(rect: DragRect): boolean {\n return rect.left > rect.right || rect.top > rect.bottom;\n}\n\nfunction nearestContainer(rects: readonly DragRect[], x: number, y: number): number {\n let nearest = -1;\n let minDist = Infinity;\n for (let i = 0; i < rects.length; i++) {\n const rect = rects[i]!;\n if (isEmptyRect(rect)) {\n continue;\n }\n const d = clampedDistance(rect, x, y);\n if (d < minDist) {\n minDist = d;\n nearest = i;\n }\n }\n return nearest;\n}\n\nfunction clampedDistance(rect: DragRect, x: number, y: number): number {\n const cx = Math.max(rect.left, Math.min(rect.right, x));\n const cy = Math.max(rect.top, Math.min(rect.bottom, y));\n return Math.hypot(x - cx, y - cy);\n}\n\nfunction insertionIndex(\n itemRects: readonly DragRect[],\n x: number,\n y: number,\n orientation: 'horizontal' | 'vertical' | 'mixed',\n dir: 'ltr' | 'rtl',\n): number {\n if (orientation === 'mixed') {\n return mixedInsertionIndex(itemRects, x, y, dir);\n }\n for (let i = 0; i < itemRects.length; i++) {\n const r = itemRects[i]!;\n const past =\n orientation === 'vertical'\n ? y < (r.top + r.bottom) / 2\n : dir === 'rtl'\n ? x > (r.left + r.right) / 2\n : x < (r.left + r.right) / 2;\n if (past) {\n return i;\n }\n }\n return itemRects.length;\n}\n\nfunction mixedInsertionIndex(\n itemRects: readonly DragRect[],\n x: number,\n y: number,\n dir: 'ltr' | 'rtl',\n): number {\n if (isSingleRow(itemRects)) {\n return insertionIndex(itemRects, x, y, 'horizontal', dir);\n }\n if (isSingleColumn(itemRects)) {\n return insertionIndex(itemRects, x, y, 'vertical', dir);\n }\n for (let i = 0; i < itemRects.length; i++) {\n const r = itemRects[i]!;\n const beforeRow = y < r.top;\n const withinRow = y <= r.bottom;\n const pastColumn = dir === 'rtl' ? x > (r.left + r.right) / 2 : x < (r.left + r.right) / 2;\n if (beforeRow || (withinRow && pastColumn)) {\n return i;\n }\n }\n return itemRects.length;\n}\n\nfunction isSingleRow(itemRects: readonly DragRect[]): boolean {\n let maxTop = -Infinity;\n let minBottom = Infinity;\n for (const r of itemRects) {\n maxTop = Math.max(maxTop, r.top);\n minBottom = Math.min(minBottom, r.bottom);\n }\n return maxTop < minBottom;\n}\n\nfunction isSingleColumn(itemRects: readonly DragRect[]): boolean {\n let maxLeft = -Infinity;\n let minRight = Infinity;\n for (const r of itemRects) {\n maxLeft = Math.max(maxLeft, r.left);\n minRight = Math.min(minRight, r.right);\n }\n return maxLeft < minRight;\n}\n\n/**\n * Resolves the drop target container and insertion index from a pointer position.\n *\n * Each container carries its own `orientation` / `dir`, and the insertion index is resolved\n * against the axis of the container that won the selection — so a transfer into a connected\n * container whose orientation or writing direction differs from the source's resolves the index\n * on the TARGET's axis.\n *\n * @param point Viewport pointer coordinates.\n * @param containers Ordered `[source, ...connected]` container geometries.\n * @returns The resolved `DropTarget`, or `null` when `containers` is empty.\n */\nexport function resolveDropTarget(\n point: { readonly x: number; readonly y: number },\n containers: readonly DropContainerGeometry[],\n): DropTarget | null {\n if (containers.length === 0) {\n return null;\n }\n\n const visible = containers.map(visibleRect);\n let containerIndex = visible.findIndex((rect) => rectContains(rect, point.x, point.y));\n\n if (containerIndex < 0) {\n containerIndex = nearestContainer(visible, point.x, point.y);\n }\n if (containerIndex < 0) {\n containerIndex = nearestContainer(\n containers.map((c) => c.rect),\n point.x,\n point.y,\n );\n }\n\n const container = containers[containerIndex]!;\n const index = insertionIndex(\n container.itemRects,\n point.x,\n point.y,\n container.orientation,\n container.dir,\n );\n\n return { containerIndex, index };\n}\n","/**\n * The name every drag and reorder announcement calls an item by, resolved like an accessible\n * name: a non-empty `override` (a `[textValue]`), else the text of the elements the node's\n * `aria-labelledby` references, else its `aria-label`, else its descendant text. Descendant text\n * skips any `aria-hidden` subtree such as a decorative `[forDragHandle]` glyph, keeps\n * visually-hidden but announced content, reads a descendant's own `aria-label` in place of its\n * content, and puts a space between element children so adjacent elements are not run together.\n * Whitespace is collapsed and trimmed. SSR-safe: it reads no global `document`.\n */\nexport function dragAnnouncementLabel(node: Element, override?: string | null): string {\n const explicit = override?.trim();\n if (explicit) {\n return explicit;\n }\n return dragElementName(node) || collapse(spacedText(node));\n}\n\n/**\n * The name `node` is given by `aria-labelledby` (the referenced elements' text, joined with\n * spaces) or, failing that, by `aria-label`; `''` when it declares neither. It never falls back\n * to descendant text, so a drop list is not named after the items it holds.\n */\nexport function dragElementName(node: Element): string {\n const ids = node.getAttribute('aria-labelledby')?.split(/\\s+/).filter(Boolean) ?? [];\n const referenced = collapse(\n ids\n .map((id) => referencedElement(node, id))\n .map((el) => (el === null ? '' : (explicitLabel(el) ?? spacedText(el))))\n .join(' '),\n );\n return referenced || (explicitLabel(node) ?? '');\n}\n\nfunction referencedElement(node: Element, id: string): Element | null {\n const root = node.getRootNode();\n const scope = 'getElementById' in root ? (root as Document | DocumentFragment) : null;\n return (scope ?? node.ownerDocument).getElementById(id);\n}\n\nfunction explicitLabel(el: Element): string | null {\n const label = el.getAttribute('aria-label')?.trim();\n return label ? label : null;\n}\n\nfunction spacedText(node: Node): string {\n let text = '';\n node.childNodes.forEach((child) => {\n if (child.nodeType === child.TEXT_NODE) {\n text += child.nodeValue ?? '';\n return;\n }\n if (child.nodeType !== child.ELEMENT_NODE) {\n return;\n }\n const el = child as Element;\n if (el.getAttribute('aria-hidden') === 'true') {\n return;\n }\n text += ` ${explicitLabel(el) ?? spacedText(el)} `;\n });\n return text;\n}\n\nfunction collapse(text: string): string {\n return text.replace(/\\s+/g, ' ').trim();\n}\n","import type { LiveAnnouncer } from '../live-announcer/live-announcer';\n\nimport { dragAnnouncementLabel, dragElementName } from './drag-announcement-label';\n\n/** What a positional announcement says about the list its position belongs to. */\nexport interface DragAnnouncementContext {\n /** The list's accessible name from `aria-labelledby` / `aria-label`, or `''`. */\n readonly list: string;\n /** Whether that list is not the one the item was lifted from. */\n readonly transfer: boolean;\n}\n\n/** A positional announcement builder: 1-based `index` of `total` valid positions. */\nexport type PositionalDragAnnouncement = (\n label: string,\n index: number,\n total: number,\n context: DragAnnouncementContext,\n) => string;\n\n/** The four builders a reorder coordinator announces a drag with. */\nexport interface DragAnnouncementText {\n readonly lift: PositionalDragAnnouncement;\n readonly move: PositionalDragAnnouncement;\n readonly drop: PositionalDragAnnouncement;\n readonly cancel: (label: string) => string;\n}\n\n/**\n * The dragged item: its host, plus the `[textValue]` override naming it when it has one. A\n * `null` host, read after the session it belonged to ended, names the item `''`.\n */\nexport interface DragAnnouncedItem {\n readonly host: Element | null;\n readonly textValue?: string | null;\n}\n\n/** A position an announcement describes. */\nexport interface DragAnnouncedPosition {\n /** 0-based position within `list`. */\n readonly index: number;\n /** Number of valid drop positions in `list`. */\n readonly total: number;\n /** Host of the list the position belongs to. */\n readonly list: Element;\n /** Host of the list the item was lifted from. */\n readonly source: Element;\n}\n\n/**\n * The one place a reorder coordinator turns a drag into live-region text. It names the item\n * through {@link dragAnnouncementLabel}, names the list a position belongs to and whether that\n * list is a transfer target, and hands both to the coordinator's builders. Lift, drop and cancel\n * are announced assertively and a move politely unless the caller asks otherwise.\n */\nexport class DragAnnouncer {\n readonly #announcer: LiveAnnouncer;\n readonly #text: () => DragAnnouncementText;\n\n constructor(announcer: LiveAnnouncer, text: () => DragAnnouncementText) {\n this.#announcer = announcer;\n this.#text = text;\n }\n\n lift(item: DragAnnouncedItem, at: DragAnnouncedPosition): void {\n this.#positional(this.#text().lift, item, at, 'assertive');\n }\n\n move(\n item: DragAnnouncedItem,\n at: DragAnnouncedPosition,\n politeness: 'polite' | 'assertive' = 'polite',\n ): void {\n this.#positional(this.#text().move, item, at, politeness);\n }\n\n drop(item: DragAnnouncedItem, at: DragAnnouncedPosition): void {\n this.#positional(this.#text().drop, item, at, 'assertive');\n }\n\n cancel(item: DragAnnouncedItem): void {\n this.#announcer.announce(this.#text().cancel(itemName(item)), 'assertive');\n }\n\n #positional(\n build: PositionalDragAnnouncement,\n item: DragAnnouncedItem,\n at: DragAnnouncedPosition,\n politeness: 'polite' | 'assertive',\n ): void {\n const context = { list: dragElementName(at.list), transfer: at.list !== at.source };\n this.#announcer.announce(build(itemName(item), at.index + 1, at.total, context), politeness);\n }\n}\n\nfunction itemName(item: DragAnnouncedItem): string {\n return item.host === null ? '' : dragAnnouncementLabel(item.host, item.textValue);\n}\n\n/** `index` clamped to the positions `[0, count - 1]`; `0` when there are none. */\nexport function clampDragIndex(index: number, count: number): number {\n return Math.max(0, Math.min(count - 1, index));\n}\n\n/**\n * The position a keyboard step from `current` towards `requested` lands on, clamped to\n * `[0, count - 1]`, or `null` when it lands on `current`. A coordinator applies a step only when\n * this is non-null, so a key pressed at a boundary neither announces nor scrolls.\n */\nexport function stepDragTarget(current: number, requested: number, count: number): number | null {\n const next = clampDragIndex(requested, count);\n return next === current ? null : next;\n}\n","import { composedParentElement } from '../composed-tree/composed-tree';\nimport type { SwipeDirection } from './swipe-dismiss';\n\nconst EDGE_TOLERANCE_PX = 1;\n\n/** Whether a computed `overflow-x` / `overflow-y` value makes its element a scroll container. */\nexport function overflowScrolls(overflow: string): boolean {\n return overflow === 'auto' || overflow === 'scroll' || overflow === 'overlay';\n}\n\n/**\n * Returns true when `target` is inside a scrollable ancestor that has not\n * yet reached its edge along the gesture direction — meaning the gesture\n * should be left to scroll the inner content rather than starting a swipe\n * on the outer drawer. Stops walking at `boundary` (typically the drawer\n * root) so unrelated ancestors above it don't affect the decision; the walk\n * crosses open shadow boundaries. With `includeBoundary` set, the boundary\n * itself is checked too, for a surface that is its own scroll container.\n *\n * Direction semantics match {@link SwipeDirection}: `'down'` means a\n * pointer-travel-down gesture (which on a scrollable scrolls the content\n * up; we therefore care whether there is room above). Mirrored for the\n * other three, and the horizontal room is read in the scroller's own\n * writing direction.\n *\n * Conservative: an element with `overflow: hidden` is treated as\n * non-scrollable; an element within 1px of its edge along the gesture\n * direction returns `false` (i.e. the gesture is fair game for the swipe).\n */\nexport function isScrollableAtEdge(\n target: Element | null,\n direction: SwipeDirection,\n boundary?: Element | null,\n includeBoundary = false,\n): boolean {\n let cur: Element | null = target;\n while (cur) {\n const atBoundary = cur === boundary;\n if (atBoundary && !includeBoundary) {\n return false;\n }\n if (cur instanceof HTMLElement && hasRoomAgainst(cur, direction)) {\n return true;\n }\n if (atBoundary) {\n return false;\n }\n cur = composedParentElement(cur);\n }\n return false;\n}\n\nfunction hasRoomAgainst(el: HTMLElement, direction: SwipeDirection): boolean {\n const style = el.ownerDocument.defaultView?.getComputedStyle(el);\n if (direction === 'up' || direction === 'down') {\n if (!overflowScrolls(style?.overflowY ?? '') || el.scrollHeight <= el.clientHeight) {\n return false;\n }\n const room =\n direction === 'down' ? el.scrollTop : el.scrollHeight - el.clientHeight - el.scrollTop;\n return room > EDGE_TOLERANCE_PX;\n }\n if (!overflowScrolls(style?.overflowX ?? '') || el.scrollWidth <= el.clientWidth) {\n return false;\n }\n const max = el.scrollWidth - el.clientWidth;\n const rtl = style?.direction === 'rtl';\n const roomLeft = rtl ? max + el.scrollLeft : el.scrollLeft;\n const roomRight = rtl ? -el.scrollLeft : max - el.scrollLeft;\n return (direction === 'right' ? roomLeft : roomRight) > EDGE_TOLERANCE_PX;\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n afterNextRender,\n DestroyRef,\n inject,\n PLATFORM_ID,\n type Signal,\n signal,\n} from '@angular/core';\n\nimport { overflowScrolls } from '../swipe-dismiss/scroll-boundary';\n\n/** A `touch-action` value a drag surface or handle binds; `null` leaves the browser default. */\nexport type DragTouchAction = 'none' | 'pan-x' | 'pan-y' | null;\n\n/** One flag per axis. */\nexport interface DragAxes {\n /** The horizontal axis. */\n readonly x: boolean;\n /** The vertical axis. */\n readonly y: boolean;\n}\n\n/** Both axes set: a free drag, or a reorder whose list may lie either way. */\nexport const BOTH_DRAG_AXES: DragAxes = { x: true, y: true };\n\n/** Neither axis set: a host that scrolls on no axis. */\nexport const NO_DRAG_AXES: DragAxes = { x: false, y: false };\n\n/** The inputs every drag surface's `touch-action` is computed from. */\nexport interface DragSurfaceTouchActionInput {\n /** Whether a press on the surface can currently arm the drag. */\n readonly armable: boolean;\n /** Whether handles are registered, so the drag arms only from a handle and never from the surface. */\n readonly handles: boolean;\n /** The axes the gesture moves along, on which the browser must not pan. */\n readonly axes: DragAxes;\n /** The axes on which the host itself is a scroll container that currently overflows. */\n readonly hostScrolls: DragAxes;\n}\n\n/**\n * The `touch-action` a drag surface binds. The browser keeps panning on every axis the gesture does\n * not move along, and on every axis the host scrolls on by itself, so a scroll container that is\n * also a drag surface still scrolls by touch. `null` while the surface cannot arm, or while handles\n * are registered, since each handle then carries {@link dragHandleTouchAction}.\n */\nexport function dragSurfaceTouchAction(input: DragSurfaceTouchActionInput): DragTouchAction {\n if (!input.armable || input.handles) {\n return null;\n }\n const x = input.axes.x && !input.hostScrolls.x;\n const y = input.axes.y && !input.hostScrolls.y;\n if (x && y) {\n return 'none';\n }\n if (x) {\n return 'pan-y';\n }\n return y ? 'pan-x' : null;\n}\n\n/**\n * The `touch-action` a drag handle binds: `'none'` while the drag can arm, so a touch drag on the\n * handle is not taken by the page's scrolling, else `null`.\n */\nexport function dragHandleTouchAction(armable: boolean): 'none' | null {\n return armable ? 'none' : null;\n}\n\nfunction measureScrollAxes(host: HTMLElement): DragAxes {\n const style = host.ownerDocument.defaultView?.getComputedStyle(host);\n return {\n x: overflowScrolls(style?.overflowX ?? '') && host.scrollWidth > host.clientWidth,\n y: overflowScrolls(style?.overflowY ?? '') && host.scrollHeight > host.clientHeight,\n };\n}\n\n/**\n * The axes on which `host` is a scroll container whose content overflows it, kept current while\n * the host or one of its children resizes and while children are added or removed. The browser\n * fixes a touch's `touch-action` when the touch starts, so a surface reads this ahead of the press\n * rather than measuring at `pointerdown`. A change to the host's `overflow` style with no resize is\n * seen on the next resize. {@link NO_DRAG_AXES} on the server and until the first render.\n *\n * Call from an injection context.\n */\nexport function injectHostScrollAxes(host: HTMLElement): Signal<DragAxes> {\n const out = signal<DragAxes>(NO_DRAG_AXES);\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n return out.asReadonly();\n }\n\n let prev = NO_DRAG_AXES;\n const sync = (): void => {\n const next = measureScrollAxes(host);\n if (next.x !== prev.x || next.y !== prev.y) {\n prev = next;\n out.set(next);\n }\n };\n\n let resize: ResizeObserver | null = null;\n let mutation: MutationObserver | null = null;\n const observeChildren = (): void => {\n if (!resize) {\n return;\n }\n resize.disconnect();\n resize.observe(host);\n for (const child of Array.from(host.children)) {\n resize.observe(child);\n }\n };\n\n afterNextRender(() => {\n sync();\n if (typeof ResizeObserver !== 'undefined') {\n resize = new ResizeObserver(sync);\n observeChildren();\n }\n if (typeof MutationObserver !== 'undefined') {\n mutation = new MutationObserver(() => {\n observeChildren();\n sync();\n });\n mutation.observe(host, { childList: true });\n }\n });\n\n inject(DestroyRef).onDestroy(() => {\n resize?.disconnect();\n mutation?.disconnect();\n });\n\n return out.asReadonly();\n}\n","import {\n computed,\n DestroyRef,\n inject,\n Injectable,\n type Signal,\n signal,\n type WritableSignal,\n} from '@angular/core';\n\n/**\n * The elements a drag item (`[forDraggable]`, `[forFreeDrag]`) is mounted on, so a piece sharing\n * one of them can tell it is co-located with a draggable without importing `forty-cdk/drag-drop`.\n * The draggable marks its host from its constructor, which a subclass inherits and a\n * `hostDirectives` wrapper runs, so every wrapping shape is seen; a selector attribute is rendered\n * for neither.\n */\n@Injectable({ providedIn: 'root' })\nexport class DragItemHosts {\n /** Per host, how many drag items are mounted on it. Created by whichever side asks first. */\n readonly #counts = new WeakMap<HTMLElement, WritableSignal<number>>();\n\n /** Records a drag item on `host`; the returned function removes it again. */\n mark(host: HTMLElement): () => void {\n const count = this.#count(host);\n count.update((n) => n + 1);\n return () => count.update((n) => n - 1);\n }\n\n /** Whether a drag item is mounted on `host`, tracking a draggable constructed after the reader. */\n carries(host: HTMLElement): Signal<boolean> {\n const count = this.#count(host);\n return computed(() => count() > 0);\n }\n\n #count(host: HTMLElement): WritableSignal<number> {\n let count = this.#counts.get(host);\n if (count === undefined) {\n count = signal(0);\n this.#counts.set(host, count);\n }\n return count;\n }\n}\n\n/**\n * Marks `host` as carrying a drag item until the calling directive is destroyed. Call from the\n * drag item's constructor.\n */\nexport function markDragItemHost(host: HTMLElement): void {\n const unmark = inject(DragItemHosts).mark(host);\n inject(DestroyRef).onDestroy(unmark);\n}\n\n/**\n * Whether a drag item shares `host` with the calling piece. Call from an injection context; the\n * signal turns `true` once the draggable on `host` is constructed, whichever is constructed first.\n */\nexport function injectHostCarriesDragItem(host: HTMLElement): Signal<boolean> {\n return inject(DragItemHosts).carries(host);\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n computed,\n DOCUMENT,\n DestroyRef,\n ElementRef,\n Injectable,\n inject,\n PLATFORM_ID,\n signal,\n type Signal,\n} from '@angular/core';\n\nimport { composedClosest, composedParentElement } from '../composed-tree/composed-tree';\nimport type { WritingDirection } from '../keyboard-navigation/keyboard-navigation';\n\n/**\n * Normalise an arbitrary `dir` attribute value to a concrete writing\n * direction. Only `'rtl'` (case-insensitive) maps to RTL; everything else —\n * including `'auto'`, the empty string, and unknown tokens — resolves to\n * `'ltr'`, matching the spec's behaviour that a non-`rtl` enumerated value is\n * treated as the default direction.\n */\nfunction normalizeDir(value: string | null | undefined): WritingDirection {\n return value?.toLowerCase() === 'rtl' ? 'rtl' : 'ltr';\n}\n\n/**\n * Owns the single application-wide `MutationObserver` watching `dir` attribute changes across the\n * document, exposed as a monotonically increasing `revision` tick.\n *\n * One observer covers every primitive: each host derives its ambient direction from a `computed`\n * keyed on `revision`, so N primitives mounting at once collapse into one batched callback rather\n * than N per-instance observers.\n *\n * `revision` bumps only for a `dir` write that changes the direction some element declares to its\n * descendants: its own normalised `dir` when it carries one, otherwise what its parent declares. A\n * write repeating what the element already inherits — a root reflecting its ambient direction, a\n * portal stamp under `<html dir>` — leaves every resolution as it was and is ignored. A flip that\n * does change a declared direction invalidates every dir-aware primitive, each re-walking its own\n * ancestor chain through open shadow roots. The observer does not reach into shadow roots, so a\n * `dir` changed inside one is picked up on the next document-level change that bumps `revision`.\n *\n * SSR-safe: off-browser no observer is created and `revision` stays `0`.\n */\n@Injectable({ providedIn: 'root' })\nclass AmbientDirection {\n readonly #doc = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n readonly #destroyRef = inject(DestroyRef);\n\n readonly #revision = signal(0);\n\n /**\n * Bumps whenever a `dir` attribute change alters the direction an element declares to its\n * descendants. Stays `0` on the server.\n */\n readonly revision = this.#revision.asReadonly();\n\n constructor() {\n if (!this.#isBrowser) {\n return;\n }\n\n const win = this.#doc.defaultView;\n if (win && typeof win.MutationObserver === 'function') {\n const observer = new win.MutationObserver((records) => {\n if (records.some((record) => changesDeclaredDirection(record, this.#doc))) {\n this.#revision.update((v) => v + 1);\n }\n });\n observer.observe(this.#doc.documentElement, {\n attributes: true,\n attributeFilter: ['dir'],\n attributeOldValue: true,\n subtree: true,\n });\n this.#destroyRef.onDestroy(() => observer.disconnect());\n }\n }\n}\n\n/**\n * Whether a `dir` mutation changed what its target declares to its descendants. Before the write\n * that is the record's old `dir`, or the parent's declared direction when there was none; after it,\n * the current `dir`, or the parent's declared direction once it is gone. Equal values mean no\n * descendant's resolution changed.\n */\nfunction changesDeclaredDirection(record: MutationRecord, doc: Document): boolean {\n const target = record.target as Element;\n const inherited = (): WritingDirection | null =>\n target === doc.documentElement\n ? null\n : resolveAttributeDirection(composedParentElement(target), doc);\n const before = record.oldValue === null ? inherited() : normalizeDir(record.oldValue);\n const after = target.hasAttribute('dir') ? normalizeDir(target.getAttribute('dir')) : inherited();\n return before !== after;\n}\n\n/**\n * Resolves the effective writing direction for the host element, reactive to\n * runtime changes.\n *\n * An explicit `[dir]` always wins. When it is `null` the value falls back to the nearest ancestor\n * carrying a `dir` attribute — the host itself is skipped, since it carries\n * {@link injectReflectedDirection} — then to `<html dir>`, defaulting to `'ltr'`. The ancestor walk crosses open shadow roots,\n * so a primitive rendered inside a `ViewEncapsulation.ShadowDom` component follows a `dir` set\n * above its host.\n *\n * Direction is read from the semantic `dir` attribute, never from CSS `direction`, so consumers set\n * `dir` on an ancestor rather than styling it.\n *\n * A runtime `dir` change on an ancestor recomputes the signal. SSR-safe: the ancestor walk runs\n * server-side too, so a server-rendered RTL app resolves `'rtl'` and hydration matches.\n *\n * Limitation: only `dir` attribute mutations in the document are observed, not `childList`, and not\n * mutations inside a shadow root. Moving the host into a different-`dir` subtree, or changing a\n * `dir` inside a shadow root, does not recompute the ambient until a `dir` change elsewhere in the\n * document alters a declared direction; set an explicit `[dir]` on the element if that happens.\n *\n * Must be called from an injection context.\n */\nexport function injectTextDirection(\n explicitDir: Signal<WritingDirection | null>,\n): Signal<WritingDirection> {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const ambient = injectAmbientDirection(() => composedParentElement(host));\n\n return computed(() => explicitDir() ?? ambient());\n}\n\n/**\n * The `dir` value a direction-aware root reflects onto its own host: the explicit `[dir]` when set,\n * otherwise the direction declared above the host (the nearest ancestor carrying a `dir`\n * attribute, across open shadow roots, then `<html dir>`), otherwise `null`.\n *\n * Bind it as `'[attr.dir]'` in place of the resolved {@link injectTextDirection} value. A root with\n * no direction declared anywhere then carries no `dir` attribute, so its subtree keeps inheriting\n * CSS `direction` and a surface portaled out of it is not stamped with a default nobody declared.\n * Omit `explicitDir` on a piece that only mirrors the direction declared above it.\n *\n * Must be called from an injection context.\n */\nexport function injectReflectedDirection(\n explicitDir?: Signal<WritingDirection | null>,\n): Signal<WritingDirection | null> {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const declared = injectDeclaredDirection(() => composedParentElement(host));\n\n return explicitDir ? computed(() => explicitDir() ?? declared()) : declared;\n}\n\n/**\n * Resolves the writing direction in effect at `origin`: the nearest element carrying a `dir`\n * attribute, `origin` itself included and open shadow roots crossed, then `<html dir>`, defaulting\n * to `'ltr'`. Recomputes on any runtime `dir` attribute change in the document, and on `origin`\n * when it reads a signal.\n *\n * Must be called from an injection context.\n */\nexport function injectAmbientDirection(\n origin: () => Element | null | undefined,\n): Signal<WritingDirection> {\n const declared = injectDeclaredDirection(origin);\n return computed(() => declared() ?? 'ltr');\n}\n\nexport function injectDeclaredDirection(\n origin: () => Element | null | undefined,\n): Signal<WritingDirection | null> {\n const doc = inject(DOCUMENT);\n const direction = inject(AmbientDirection);\n\n return computed(() => {\n direction.revision();\n return resolveAttributeDirection(origin() ?? null, doc);\n });\n}\n\nfunction resolveAttributeDirection(origin: Element | null, doc: Document): WritingDirection | null {\n const declared = (origin ? composedClosest(origin, '[dir]') : null) ?? htmlWithDir(doc);\n return declared ? normalizeDir(declared.getAttribute('dir')) : null;\n}\n\nexport function stampAmbientDirection(el: Element, origin: Element | null): void {\n if (el.hasAttribute('dir')) {\n return;\n }\n const dir = resolveAttributeDirection(origin, el.ownerDocument);\n if (dir !== null) {\n el.setAttribute('dir', dir);\n }\n}\n\nfunction htmlWithDir(doc: Document): Element | null {\n const html = doc.documentElement as Element | null;\n return html?.hasAttribute('dir') ? html : null;\n}\n","const TRANSITION_END_SAFETY_MS = 50;\n\nfunction parseTimeMs(segment: string): number {\n const value = parseFloat(segment);\n if (!Number.isFinite(value)) {\n return 0;\n }\n return segment.endsWith('ms') ? value : value * 1000;\n}\n\nfunction splitList(value: string | undefined): string[] {\n return value ? value.split(',').map((segment) => segment.trim()) : [];\n}\n\n/**\n * The delay plus duration (ms) of the computed transition on `transform` (or `all`), or of the\n * longest configured transition when none animates `transform`; `0` when none is configured.\n */\nfunction transformTransitionEndMs(style: CSSStyleDeclaration): number {\n const durations = splitList(style.transitionDuration);\n if (durations.length === 0) {\n return 0;\n }\n const delays = splitList(style.transitionDelay);\n const properties = splitList(style.transitionProperty);\n let transformEnd = 0;\n let longestEnd = 0;\n (properties.length > 0 ? properties : ['all']).forEach((property, i) => {\n if (property === 'none') {\n return;\n }\n const duration = parseTimeMs(durations[i % durations.length] ?? '');\n const delay = delays.length > 0 ? parseTimeMs(delays[i % delays.length] ?? '') : 0;\n const end = duration > 0 ? Math.max(0, duration + delay) : 0;\n longestEnd = Math.max(longestEnd, end);\n if (property === 'transform' || property === 'all') {\n transformEnd = end;\n }\n });\n return transformEnd || longestEnd;\n}\n\n/**\n * Calls `onDone` exactly once, when the `transform` transition of `el` itself ends: on a\n * `transitionend` whose target is `el` and whose property is `transform`, or, if none arrives, once\n * the delay plus duration of the computed transition on `transform` (or `all`, or of the longest\n * configured transition when none animates `transform`) and a small safety margin have elapsed.\n * A `transitionend` of another property, or one bubbling up from a descendant, is ignored. Calls\n * `onDone` synchronously when `el` has no transition configured.\n *\n * Reads the computed style of `el` once, so call it after the styling hook that configures the\n * transition is in place.\n */\nexport function awaitTransformTransition(el: HTMLElement, win: Window, onDone: () => void): void {\n const endMs = transformTransitionEndMs(win.getComputedStyle(el));\n if (endMs === 0) {\n onDone();\n return;\n }\n let done = false;\n const controller = new AbortController();\n const finish = (): void => {\n if (done) {\n return;\n }\n done = true;\n controller.abort();\n onDone();\n };\n el.addEventListener(\n 'transitionend',\n (event: TransitionEvent): void => {\n if (event.target !== el || (event.propertyName && event.propertyName !== 'transform')) {\n return;\n }\n finish();\n },\n { signal: controller.signal },\n );\n win.setTimeout(finish, endMs + TRANSITION_END_SAFETY_MS);\n}\n","import { stampAmbientDirection } from '../text-direction/text-direction';\nimport { awaitTransformTransition } from './transform-transition';\n\n/** A floating clone of the dragged element that follows the pointer. */\nexport interface DragPreview {\n /**\n * The element that floats under the pointer. When present, a boundary clamp keeps this\n * element's box inside the boundary; when absent, it keeps the dragged item's box inside.\n */\n readonly element?: HTMLElement;\n /** Position the preview's top-left at `(x, y)` in viewport coordinates. */\n moveTo(x: number, y: number): void;\n /**\n * Transition the preview's top-left to `(x, y)`, then `destroy()` it once its own `transform`\n * transition ends; a transition of another property, or of a descendant, does not end it.\n * Marks the element `data-settling` so a consumer CSS rule keyed on it governs duration /\n * easing. A fallback timeout covers a `transitionend` that never arrives:\n * it waits for the delay plus duration of the computed transition on `transform` (or `all`),\n * or of the longest configured transition when none animates `transform`, plus a small safety\n * margin. If no transition is configured, destroys immediately. Caller must pass the browser\n * `Window`.\n */\n settle(x: number, y: number, win: Window): void;\n /** Remove the preview from the DOM. Idempotent. */\n destroy(): void;\n}\n\nfunction attachSettle(target: HTMLElement, destroyFn: () => void): DragPreview['settle'] {\n return (x: number, y: number, win: Window): void => {\n target.setAttribute('data-settling', '');\n void target.offsetWidth;\n awaitTransformTransition(target, win, destroyFn);\n target.style.transform = `translate(${x}px, ${y}px)`;\n };\n}\n\n/**\n * Wraps a minimal preview (with only `moveTo` and `destroy`) into a full `DragPreview`.\n * The `settle` implementation falls back to an immediate `destroy` call since the wrapped\n * object carries no DOM element to animate. Used when a caller-supplied preview does not yet\n * implement `settle`.\n */\nexport function wrapPreview(preview: {\n moveTo(x: number, y: number): void;\n destroy(): void;\n}): DragPreview {\n return {\n moveTo: (x, y) => preview.moveTo(x, y),\n settle: (_x, _y, _win) => {\n preview.destroy();\n },\n destroy: () => preview.destroy(),\n };\n}\n\nconst IDENTITY_HOOKS = ['id', 'data-testid'];\n\nconst LIVE_ATTRIBUTES = ['name', 'form', 'autofocus', 'autoplay'];\n\nconst EMBEDDED_CONTENT = 'iframe, object, embed';\n\nfunction selfAndDescendants(root: HTMLElement, selector: string): HTMLElement[] {\n const descendants = Array.from(root.querySelectorAll<HTMLElement>(selector));\n return root.matches(selector) ? [root, ...descendants] : descendants;\n}\n\nfunction stripAttributes(root: HTMLElement, names: readonly string[]): void {\n for (const el of selfAndDescendants(root, names.map((name) => `[${name}]`).join(', '))) {\n for (const name of names) {\n el.removeAttribute(name);\n }\n }\n}\n\nfunction replaceEmbeddedContent(clone: HTMLElement, source: HTMLElement, doc: Document): void {\n const originals = source.querySelectorAll(EMBEDDED_CONTENT);\n clone.querySelectorAll(EMBEDDED_CONTENT).forEach((embedded, i) => {\n const rect = originals[i]?.getBoundingClientRect();\n const box = doc.createElement('div');\n box.style.display = 'inline-block';\n box.style.width = `${rect?.width ?? 0}px`;\n box.style.height = `${rect?.height ?? 0}px`;\n embedded.replaceWith(box);\n });\n}\n\n/**\n * Creates a default drag preview: a fixed-position clone of `source` appended to `doc.body`, sized to the\n * source's current bounding box, non-interactive, and hidden from assistive tech. The clone carries the\n * writing direction declared at `source`, so it keeps the alignment and bidi ordering of the item it\n * floats away from. Caller must gate on a browser platform.\n *\n * `id` and `data-testid` are stripped from the clone root and from every descendant carrying one, so the\n * preview is never reachable through a hook that identifies a single element: duplicating an `id` while the\n * preview lives makes the document invalid (and `getElementById` ambiguous) regardless of `aria-hidden`.\n * The clone still answers the source's own attribute selectors — a directive selector such as\n * `[forDraggable]`, plus `data-index` where the source carries one — so code enumerating items by selector\n * during a drag must exclude `[data-for-drag-preview]`.\n *\n * The clone's live content is made inert before it joins the document: `name` and `form` are stripped so a\n * cloned control never joins the source's radio group or form (a checked radio would otherwise uncheck the\n * source's), `autofocus` and `autoplay` are stripped, and every `iframe`, `object` and `embed` is replaced by\n * an empty box the size of the source's, so nothing reloads or plays.\n */\nexport function createDragPreview(source: HTMLElement, doc: Document): DragPreview {\n const rect = source.getBoundingClientRect();\n const clone = source.cloneNode(true) as HTMLElement;\n\n clone.style.position = 'fixed';\n clone.style.top = '0';\n clone.style.left = '0';\n clone.style.width = `${rect.width}px`;\n clone.style.height = `${rect.height}px`;\n clone.style.margin = '0';\n clone.style.pointerEvents = 'none';\n clone.style.boxSizing = 'border-box';\n clone.style.zIndex = '2147483647';\n\n clone.setAttribute('data-for-drag-preview', '');\n clone.setAttribute('aria-hidden', 'true');\n stripAttributes(clone, IDENTITY_HOOKS);\n stripAttributes(clone, LIVE_ATTRIBUTES);\n replaceEmbeddedContent(clone, source, doc);\n\n stampAmbientDirection(clone, source);\n doc.body.appendChild(clone);\n\n const destroy = (): void => {\n clone.remove();\n };\n\n return {\n element: clone,\n moveTo(x: number, y: number): void {\n clone.style.transform = `translate(${x}px, ${y}px)`;\n },\n settle: attachSettle(clone, destroy),\n destroy,\n };\n}\n\n/**\n * Creates a drag preview from caller-supplied root nodes (e.g. an Angular embedded view's\n * `rootNodes`): wraps them in a fixed-position, non-interactive, assistive-tech-hidden container\n * appended to `doc.body`. `onDestroy` runs on teardown (before the wrapper is removed) so the\n * caller can dispose the backing view. The wrapper carries the writing direction declared at\n * `source`, the dragged item's host. Caller must gate on a browser platform.\n */\nexport function createTemplatePreview(\n nodes: readonly Node[],\n source: Element,\n doc: Document,\n onDestroy: () => void,\n): DragPreview {\n const wrapper = doc.createElement('div');\n wrapper.style.position = 'fixed';\n wrapper.style.top = '0';\n wrapper.style.left = '0';\n wrapper.style.margin = '0';\n wrapper.style.pointerEvents = 'none';\n wrapper.style.zIndex = '2147483647';\n wrapper.setAttribute('data-for-drag-preview', '');\n wrapper.setAttribute('aria-hidden', 'true');\n\n for (const node of nodes) {\n wrapper.appendChild(node);\n }\n stampAmbientDirection(wrapper, source);\n doc.body.appendChild(wrapper);\n\n const destroy = (): void => {\n onDestroy();\n wrapper.remove();\n };\n\n return {\n element: wrapper,\n moveTo(x: number, y: number): void {\n wrapper.style.transform = `translate(${x}px, ${y}px)`;\n },\n settle: attachSettle(wrapper, destroy),\n destroy,\n };\n}\n","import { afterEveryRender, type Injector } from '@angular/core';\n\nimport { composedContains, resolveActiveElement } from '../composed-tree/composed-tree';\n\nconst MAX_RENDERS = 10;\n\n/** A focus target: anything `focus()` can be called on. */\nexport type FocusWhenMountedTarget = HTMLElement | SVGElement;\n\n/** Wiring for {@link focusWhenMounted}. */\nexport interface FocusWhenMountedOptions {\n /** Injector the render hook registers against; the hook is torn down with it. */\n readonly injector: Injector;\n /** The document focus is read from. */\n readonly document: Document;\n /**\n * The element focus must be on or inside when the step starts — the lifted item, or the\n * focused row. The step does nothing when focus is anywhere else.\n */\n readonly from: Element;\n /**\n * Resolves the element to focus among what is rendered, or `null` while it is not mounted\n * yet. Receives the element that held focus when the step started.\n */\n readonly target: (origin: FocusWhenMountedTarget) => FocusWhenMountedTarget | null;\n /** Brings the target into the rendered set. Runs once, synchronously, before any render. */\n readonly reveal?: () => void;\n /**\n * Runs once when the step ends, whether it moved focus, yielded to a focus move made\n * elsewhere, or gave up on a target that never mounted. Not called by `cancel()`.\n */\n readonly release?: () => void;\n}\n\n/** Handle on a pending {@link focusWhenMounted} step. */\nexport interface FocusWhenMountedRef {\n /** Abandon the step without moving focus and without calling `release`. */\n cancel(): void;\n}\n\nconst NOOP_REF: FocusWhenMountedRef = { cancel: () => undefined };\n\n/**\n * Moves focus to an element that may not be rendered yet, once a render has mounted it: the\n * step a keyboard drop or a dataset-wide jump owes the keyboard user when the element they\n * were on is moved, recycled or destroyed by the re-render that follows.\n *\n * It starts only when focus is on or inside `from`, and remembers that element as the origin.\n * `reveal` then runs synchronously (scroll the target into the window, pin it), and after each\n * render the step resolves `target`. Focus moves when it resolves and focus is still on the\n * origin or was lost to `<body>`; a focus move made elsewhere in the meantime wins, and so does\n * a target that is still unmounted after a bounded number of renders. Every one of those ends\n * calls `release` once.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own entry points, with\n * no semver guarantee.\n */\nexport function focusWhenMounted(options: FocusWhenMountedOptions): FocusWhenMountedRef {\n const { document } = options;\n const active = resolveActiveElement(document);\n if (\n active === null ||\n !composedContains(options.from, active) ||\n !(active instanceof HTMLElement || active instanceof SVGElement)\n ) {\n return NOOP_REF;\n }\n const origin = active;\n let renders = 0;\n let done = false;\n\n options.reveal?.();\n\n const hook = afterEveryRender(\n () => {\n if (done) {\n return;\n }\n renders++;\n const current = resolveActiveElement(document);\n const lost =\n current === null || current === document.body || current === document.documentElement;\n if (!lost && current !== origin) {\n end();\n return;\n }\n const target = options.target(origin);\n if (target !== null) {\n if (current !== target) {\n target.focus();\n }\n end();\n return;\n }\n if (renders >= MAX_RENDERS) {\n end();\n }\n },\n { injector: options.injector },\n );\n\n function stop(): void {\n done = true;\n hook.destroy();\n }\n\n function end(): void {\n stop();\n options.release?.();\n }\n\n return {\n cancel: () => {\n if (!done) {\n stop();\n }\n },\n };\n}\n","import { isImeComposing } from '../keyboard-navigation/ime-composition';\n\n/**\n * Shared keyboard resolvers for container-level drag-reorder coordinators\n * (`ForTreeNodeDrag`, `ForListboxReorder`, `ForTableRowReorder`). Framework-free\n * and unit-testable in isolation. Not part of the public API.\n *\n * A coordinator that lives next to a roving / selectable collection cannot reuse\n * the plain Space / Enter lift the drag-drop primitive uses on a `[forDraggable]`\n * item — those keys already activate / select the focused item. The convention\n * across these coordinators is therefore a dedicated **lift binding**, read from\n * `ForDragDropDefaults.liftKey` so a consumer can rebind it per scope, plus a\n * shared commit / cancel vocabulary while a node is lifted.\n */\n\n/**\n * Whether a key press lifts the focused item into a keyboard drag: the scope's\n * `liftKey` binding accepts it and it does not belong to an IME composition.\n *\n * @param event The keydown fired while no item is lifted.\n * @param liftKey The resolved `ForDragDropDefaults.liftKey` of the coordinator's scope.\n */\nexport function isDragLiftKey(\n event: KeyboardEvent,\n liftKey: (event: KeyboardEvent) => boolean,\n): boolean {\n return !isImeComposing(event) && liftKey(event);\n}\n\n/**\n * Resolves the commit / cancel control common to every lifted keyboard drag:\n * `Escape` / `Tab` cancel, `Space` / `Enter` commit. Returns `null` for keys\n * with no control meaning, leaving the caller to resolve its own movement keys\n * (sibling steps, depth changes, etc.).\n *\n * @param event The keydown event fired while an item is lifted.\n */\nexport function resolveLiftedDragControl(event: KeyboardEvent): 'cancel' | 'commit' | null {\n if ((event.key === 'Escape' && !isImeComposing(event)) || event.key === 'Tab') {\n return 'cancel';\n }\n if (event.key === ' ' || event.key === 'Enter') {\n return 'commit';\n }\n return null;\n}\n","import type { DestroyRef } from '@angular/core';\n\nimport { composedContains, resolveActiveElement } from '../composed-tree/composed-tree';\n\n/**\n * Configuration for {@link createKeyboardDragMediator}.\n *\n * The mediator owns the listener *lifecycle* plus the one DOM fact it is positioned to answer\n * (\"did focus leave the host?\"); the caller owns every *domain* decision. `isLifted` is read on\n * each keydown to route the event and again before a deferred focus leave is reported, the two\n * keydown callbacks carry the caller's key semantics, and `onFocusLeave` carries the consequence\n * of a leave.\n */\nexport interface KeyboardDragMediatorConfig {\n /** Element the capture-phase `keydown` / `focusout` listeners attach to (the coordinator host). */\n readonly host: HTMLElement;\n /**\n * The host's document. Its active element, resolved through open shadow roots, decides a\n * `focusout` that reports no destination.\n */\n readonly document: Document;\n /** Whether code runs in a browser. The mediator no-ops entirely on the server. */\n readonly isBrowser: boolean;\n /** The owner's `DestroyRef`; the mediator removes its listeners on destroy. */\n readonly destroyRef: DestroyRef;\n /** `true` while a keyboard drag is in progress. Read on every keydown to route the event. */\n isLifted(): boolean;\n /**\n * A keydown fired while no keyboard drag is in progress. The caller decides whether it starts\n * a lift (and whether to `preventDefault` / `stopPropagation`). Keys with no lift meaning must\n * be left untouched so they fall through to the underlying collection's own handlers.\n */\n onIdleKeydown(event: KeyboardEvent): void;\n /**\n * A keydown fired while a keyboard drag is in progress. The caller resolves it to a move /\n * commit / cancel and consumes the event (`preventDefault` + `stopPropagation`) so the\n * underlying collection never sees the navigation / activation key. A key it maps to no action\n * goes through `consumeUnmappedLiftedKey`, so no key reaches the collection while lifted.\n */\n onLiftedKeydown(event: KeyboardEvent): void;\n /**\n * Focus has genuinely left the host while a keyboard drag was in progress — the mediator has\n * already resolved containment, so there is nothing left to re-check here. The caller decides\n * the *consequence*, which in every coordinator today is cancelling the in-flight drag.\n *\n * It fires at most once per `focusout`, never while `isLifted()` reports `false`, and never\n * after the owner is destroyed.\n */\n onFocusLeave(): void;\n}\n\n/**\n * Wires the capture-phase keyboard mediation shared by container-level drag-reorder\n * coordinators (`ForTreeNodeDrag`, `ForTableRowReorder`, `ForListboxReorder`,\n * `ForVirtualReorder`).\n *\n * Each of those coordinators lives on a container whose children own their own roving\n * tabindex / selection, so the coordinator must intercept keys in the **capture phase** —\n * before they reach the focused child — and `stopPropagation` the ones it consumes, leaving\n * untouched keys to fall through. This function owns the error-prone half of that contract:\n * the SSR gate, the `{ capture: true }` `keydown` listener and its paired `focusout` listener,\n * the lifted-vs-idle routing decision, and teardown via `DestroyRef`. Both listeners share one\n * `AbortController`, so a single `abort()` drops them and a `capture` flag can no longer be\n * mismatched between an add and its removal. Domain behavior — what lifts, what each key does,\n * what a focus leave costs — stays with the caller through the callbacks.\n *\n * **Resolving a focus leave is the mediator's job, not the caller's.** A `focusout` whose\n * `relatedTarget` is a node reports where focus landed, so containment against the host answers it\n * outright. A\n * `focusout` reporting `relatedTarget: null` says nothing about *where* focus went — focus may\n * have left the document, landed on a non-focusable area, or simply been dropped by a re-render\n * detaching the focused element — so the decision is deferred one microtask and taken against\n * the active element, resolved through open shadow roots, once the focus update has settled, the same resolution\n * `[forNavigationMenu]` applies to its own leave channel. Only then does `onFocusLeave` fire.\n * Before this was folded in, the four callers answered it three different ways and a consumer\n * re-render mid-gesture announced a cancel the user never asked for.\n *\n * The caller keeps ownership of its pointer session and of cancelling an in-flight drag on\n * destroy (those differ per coordinator); this mediator removes only the keyboard / focus\n * listeners it installed.\n */\nexport function createKeyboardDragMediator(config: KeyboardDragMediatorConfig): void {\n if (!config.isBrowser) {\n return;\n }\n const { host } = config;\n let destroyed = false;\n const onKeydown = (event: KeyboardEvent): void => {\n if (config.isLifted()) {\n config.onLiftedKeydown(event);\n } else {\n config.onIdleKeydown(event);\n }\n };\n const reportLeaveIfFocusIsOutside = (): void => {\n if (destroyed || !config.isLifted()) {\n return;\n }\n const active = resolveActiveElement(config.document);\n if (active !== null && composedContains(host, active)) {\n return;\n }\n config.onFocusLeave();\n };\n const onFocusOut = (event: FocusEvent): void => {\n if (!config.isLifted()) {\n return;\n }\n const related = event.relatedTarget;\n if (related instanceof Node) {\n if (!host.contains(related)) {\n config.onFocusLeave();\n }\n return;\n }\n queueMicrotask(reportLeaveIfFocusIsOutside);\n };\n\n const controller = new AbortController();\n host.addEventListener('keydown', onKeydown, { capture: true, signal: controller.signal });\n host.addEventListener('focusout', onFocusOut, { signal: controller.signal });\n\n config.destroyRef.onDestroy(() => {\n destroyed = true;\n controller.abort();\n });\n}\n","import { isImeComposing } from '../keyboard-navigation/ime-composition';\n\n/** A pointer press arriving at a reorder coordinator, read against its keyboard lift. */\nexport interface LiftPress {\n /** Whether a keyboard lift is live. */\n readonly keyboardLifted: boolean;\n /** The item the keyboard lift holds, `null` when none is held. */\n readonly liftedHost: HTMLElement | null;\n /** The item the press landed on, `null` when it landed on no item. */\n readonly pressedHost: HTMLElement | null;\n /** Ends the live keyboard lift through the owner's announced cancel path. */\n cancelKeyboardLift(): void;\n}\n\n/**\n * Arbitrates a pointer press against a live keyboard lift, so the two never run at once. Every\n * keyboard-drop owner calls it from its pointer `canStart`, before writing any pointer state.\n *\n * With no keyboard lift live the press is free. A press on another item cancels the lift first,\n * so the pointer gesture that may follow starts from a clean session. A press on the lifted item,\n * or on no item, is refused and the lift continues.\n *\n * @returns Whether the press may go on to start a pointer gesture.\n */\nexport function arbitrateLiftPress(press: LiftPress): boolean {\n if (!press.keyboardLifted) {\n return true;\n }\n if (press.pressedHost === null || press.pressedHost === press.liftedHost) {\n return false;\n }\n press.cancelKeyboardLift();\n return true;\n}\n\n/**\n * Whether a key keeps its browser default while an item is lifted: a Ctrl / Cmd / Alt chord, a\n * function key, or a key belonging to an IME composition.\n *\n * @param event The keydown event fired while an item is lifted.\n */\nexport function isLiftedPassthroughKey(event: KeyboardEvent): boolean {\n return (\n isImeComposing(event) ||\n event.ctrlKey ||\n event.metaKey ||\n event.altKey ||\n /^F\\d{1,2}$/.test(event.key)\n );\n}\n\n/**\n * Consumes a keydown the lifted drag maps to no action. The event never reaches the collection\n * under the coordinator, and its browser default is cancelled unless\n * {@link isLiftedPassthroughKey} keeps it.\n *\n * @param event The keydown event fired while an item is lifted.\n */\nexport function consumeUnmappedLiftedKey(event: KeyboardEvent): void {\n event.stopPropagation();\n if (!isLiftedPassthroughKey(event)) {\n event.preventDefault();\n }\n}\n","import { isImeComposing } from '../keyboard-navigation/ime-composition';\n\n/**\n * Framework-free pointer-drag session transport.\n *\n * Owns the parts of a pointer drag that have nothing to do with any one primitive's\n * domain model: the host `pointerdown` capture listener, the document-level\n * `pointermove` / `pointerup` / `pointercancel` capture listeners, the arm threshold\n * (a drag is not \"lifted\" until the pointer travels past `armThreshold` from the start\n * point), the post-drag click suppression that stops the release from triggering a\n * stray `click` on whatever sat under the pointer, and — when `capturePointer` is set —\n * pointer capture on the host (which also suppresses the browser's native drag behaviours,\n * e.g. text-selection auto-scroll near a scroll-container edge).\n *\n * The session keeps no Angular DI surface — it's a plain function that returns a cleanup\n * handle. Callers wire it through the directive's `DestroyRef`. Domain decisions stay with\n * the caller through callbacks:\n *\n * - `canStart(event)` runs on `pointerdown`. Return `true` to begin tracking (the start\n * point is recorded), `false` to ignore the press. All primitive-specific guards\n * (disabled state, hit-testing the grabbed element, handle constraints, mouse button)\n * live here.\n * - `onLift(event, start)` fires on the first move that crosses `armThreshold`, before the\n * session arms or captures the pointer, with `start` the recorded press point. Return `false`\n * to abort the session in flight (e.g. the grabbed element has since vanished): the document\n * listeners are torn down and no further callback fires. Return `'skip'` to decline arming for now while keeping the press tracked\n * and unarmed — `onLift` is re-consulted on every subsequent move still past `armThreshold`,\n * with the delta and dominant axis recomputed from the fixed start point each time. Returning\n * `true` or `void` arms the session, captures the pointer when `capturePointer` is set, and\n * lets the move flow through to `onMove`.\n * - `onMove(event)` fires on every armed move after the lift.\n * - `onCommit(event)` fires on `pointerup` while armed.\n * - `onCancel(event?)` fires on `pointercancel`, on `Escape` when `cancelOnEscape` is set, and on an\n * imperative `session.cancel(event?)`. It receives the triggering `PointerEvent` when one exists\n * (`pointercancel` or the event handed to `cancel`), `undefined` for an `Escape` abort.\n *\n * The returned handle also exposes `cancel(event?)`: an imperative abort that tears the in-flight\n * drag down and fires `onCancel(event)` while keeping the host listener alive for the next press.\n * A caller layering its own reactive guards on top of the transport (e.g. `attachSwipeDismiss`\n * re-reading its allowed directions mid-gesture) uses it to cancel from inside `onMove`.\n *\n * **Escape.** With `cancelOnEscape`, a document `keydown` listener alive only while a press is\n * tracked aborts an armed drag, tearing the session down and firing `onCancel` like a\n * `pointercancel`. It is opt-in, so callers owning their own keyboard-drag mode stay unaffected.\n * While armed it consumes the event in the capture phase, so cancelling a drag inside an overlay\n * does not also dismiss the surrounding dialog or popover. A non-armed press stays transparent.\n *\n * **Click suppression.** A `pointerup` ending an armed drag records the release point and installs\n * a capture-phase `click` listener. Only a click landing at those coordinates — the synthetic click\n * the release itself generates — is swallowed; a click elsewhere reaches its target untouched. The\n * listener removes itself after the first click, with a `suppressClickTimeoutMs` fallback if none\n * follows.\n *\n * **Native drag.** While a press accepted through `canStart` is tracked, a capture-phase `dragstart`\n * listener on the host cancels the browser's own HTML5 drag. An image, a link or selected text\n * starts one at about 4px, before most arm thresholds, and the `pointercancel` that follows it\n * would abort the session. A press a nested control opted out of (below) is left alone.\n *\n * **Nested-control opt-out.** When the originating `pointerdown` was `defaultPrevented` by a\n * descendant owning the same gesture, the session stands down on the first move instead of arming.\n * The check is deferred to `pointermove` because the descendant's `preventDefault()` runs in the\n * bubble phase, after this capture-phase listener.\n *\n * **Self-prevention.** A `canStart` calling `preventDefault()` is signalling *ancestor* sessions to\n * stand down, not itself, so the session snapshots `defaultPrevented` around the call and skips its\n * own stand-down check when `canStart` flipped it. A nested handle therefore still arms while its\n * ancestors stand down.\n */\n\n/** A live pointer-drag session. Call `destroy()` to remove every listener. */\nexport interface PointerDragSession {\n /**\n * Remove the host listener, any active document listeners, and any pending click trap.\n * With `cancelOnDestroy` set, an in-flight (tracked) drag is first aborted through the\n * cancel path (`onCancel` fires) before teardown; otherwise `destroy()` fires no callback.\n */\n destroy(): void;\n /**\n * Abort an in-flight drag imperatively, as if a `pointercancel` had arrived: release capture,\n * tear down the active document listeners, and fire `onCancel(event)`. The host `pointerdown`\n * listener stays attached, so a fresh press can still start a new session. A no-op when no\n * press is currently tracked. `event`, when supplied, is forwarded to `onCancel` so the caller\n * can build an event-accurate payload (e.g. the `pointermove` that triggered the abort).\n */\n cancel(event?: PointerEvent): void;\n}\n\n/**\n * The {@link PointerDragSessionOptions.armThreshold} a pointer-driven **resize**\n * gesture uses: the travel a press must cover before it starts mutating the\n * value it resizes.\n *\n * Shared by `[forPaneResizer]` and `[forTableColumnResizer]` so both arm at the same distance. The\n * drag-drop family arms on its own `POINTER_ARM_THRESHOLD_PX`, and Slider arms at `0` because a\n * press on its track commits immediately.\n */\nexport const DRAG_DEAD_ZONE_PX = 3;\n\n/** Configuration for {@link createPointerDragSession}. */\nexport interface PointerDragSessionOptions {\n /** Element whose `pointerdown` (capture) starts a potential session. */\n readonly host: HTMLElement;\n /** The document owning the move/up/cancel/click listeners (injected for SSR/testing). */\n readonly document: Document;\n /** Distance in CSS pixels the pointer must travel before the drag arms (lifts). */\n readonly armThreshold: number;\n /**\n * Runs on `pointerdown`. Return `true` to begin tracking the press as a potential drag,\n * `false` to ignore it. Houses all primitive-specific start guards.\n */\n readonly canStart: (event: PointerEvent) => boolean;\n /**\n * Fires on the first move past `armThreshold`, before the session arms or captures the\n * pointer. `start` is the `pointerdown` point: a drag measures its travel from it, so the\n * distance covered before arming is not lost. Return `false` to abort the session in flight\n * (the grabbed element vanished, etc.); the session tears its listeners down and fires no\n * further callback. Return `'skip'` to\n * decline arming for now while keeping the press tracked and unarmed: `onLift` is re-consulted\n * on every subsequent move still past `armThreshold`, with the delta and dominant axis\n * recomputed from the fixed start point each time. Returning `true` or `void` arms the session\n * and lets the move flow through to `onMove`.\n */\n readonly onLift: (\n event: PointerEvent,\n start: { readonly x: number; readonly y: number },\n ) => boolean | 'skip' | void;\n /** Fires on every armed move after the lift. */\n readonly onMove: (event: PointerEvent) => void;\n /** Fires on `pointerup` while armed. */\n readonly onCommit: (event: PointerEvent) => void;\n /**\n * Fires on `pointercancel`, on `Escape` while armed when {@link cancelOnEscape} is set, and on\n * an imperative {@link PointerDragSession.cancel}. Receives the triggering `PointerEvent` when\n * one exists (`pointercancel`, or the event passed to `cancel`); `undefined` for an `Escape`\n * abort, which has no pointer event.\n */\n readonly onCancel: (event?: PointerEvent) => void;\n /**\n * When `true`, an `Escape` keydown aborts an armed drag (tears the session down and fires\n * `onCancel`). Defaults to `false` so callers owning their own `Escape` handling are unaffected.\n */\n readonly cancelOnEscape?: boolean;\n /**\n * When `true`, `destroy()` aborts an in-flight (tracked) drag through the same path as\n * `cancel()` / `pointercancel` — `resetTracking()` then `onCancel(undefined)` — before removing\n * listeners. Defaults to `false`, so `destroy()` is a pure teardown that fires no callback. Opt in\n * when the owning directive must revert transient drag state on unmount (e.g. a column resizer\n * restoring its pre-drag width).\n */\n readonly cancelOnDestroy?: boolean;\n /**\n * When `true`, the host captures the pointer once the drag arms and releases it on\n * commit / cancel / teardown. Capture also suppresses the browser's native drag behaviours\n * (notably text-selection auto-scroll when the pointer reaches a scroll-container edge).\n * Defaults to `false`; capture is no-op'd in environments without `PointerCapture` (jsdom).\n */\n readonly capturePointer?: boolean;\n /** Fallback timeout (ms) that drops the click trap if no click follows the release. */\n readonly suppressClickTimeoutMs?: number;\n}\n\nconst DEFAULT_SUPPRESS_CLICK_TIMEOUT_MS = 500;\nconst CLICK_SUPPRESS_TOLERANCE_PX = 2;\n\n/**\n * Attach a pointer-drag session to `opts.host`. Returns a {@link PointerDragSession} whose\n * `destroy()` removes every listener and any pending click trap.\n */\nexport function createPointerDragSession(opts: PointerDragSessionOptions): PointerDragSession {\n const { host, document } = opts;\n const suppressTimeout = opts.suppressClickTimeoutMs ?? DEFAULT_SUPPRESS_CLICK_TIMEOUT_MS;\n\n let start: { x: number; y: number } | null = null;\n let armed = false;\n let selfPrevented = false;\n let pointerId: number | null = null;\n let downEvent: PointerEvent | null = null;\n\n let pressListeners: AbortController | null = null;\n let clickTrap: AbortController | null = null;\n\n const removeDocumentListeners = (): void => {\n pressListeners?.abort();\n pressListeners = null;\n };\n\n const removeClickTrap = (): void => {\n clickTrap?.abort();\n clickTrap = null;\n };\n\n const releaseCapture = (): void => {\n if (pointerId === null) {\n return;\n }\n try {\n if (host.hasPointerCapture?.(pointerId)) {\n host.releasePointerCapture?.(pointerId);\n }\n } catch {\n // Some environments (jsdom) reject release on detached nodes.\n }\n };\n\n const resetTracking = (): void => {\n releaseCapture();\n start = null;\n armed = false;\n selfPrevented = false;\n pointerId = null;\n downEvent = null;\n removeDocumentListeners();\n };\n\n const move = (event: PointerEvent): void => {\n if (!start || event.pointerId !== pointerId) {\n return;\n }\n if (!armed) {\n const dx = event.clientX - start.x;\n const dy = event.clientY - start.y;\n if (Math.hypot(dx, dy) < opts.armThreshold) {\n return;\n }\n if (downEvent?.defaultPrevented && !selfPrevented) {\n resetTracking();\n return;\n }\n const lift = opts.onLift(event, start);\n if (lift === false) {\n resetTracking();\n return;\n }\n if (lift === 'skip') {\n return;\n }\n armed = true;\n if (opts.capturePointer && pointerId !== null) {\n try {\n host.setPointerCapture?.(pointerId);\n } catch {\n // Some environments (jsdom) reject capture on detached nodes.\n }\n }\n }\n opts.onMove(event);\n };\n\n const installClickTrap = (release: { x: number; y: number }): void => {\n removeClickTrap();\n const controller = new AbortController();\n const trap = (event: MouseEvent): void => {\n if (\n Math.abs(event.clientX - release.x) <= CLICK_SUPPRESS_TOLERANCE_PX &&\n Math.abs(event.clientY - release.y) <= CLICK_SUPPRESS_TOLERANCE_PX\n ) {\n event.stopPropagation();\n event.preventDefault();\n }\n controller.abort();\n if (clickTrap === controller) {\n clickTrap = null;\n }\n };\n clickTrap = controller;\n document.addEventListener('click', trap, { capture: true, signal: controller.signal });\n setTimeout(() => {\n if (clickTrap === controller) {\n removeClickTrap();\n }\n }, suppressTimeout);\n };\n\n const up = (event: PointerEvent): void => {\n if (event.pointerId !== pointerId) {\n return;\n }\n const wasArmed = armed;\n if (wasArmed) {\n installClickTrap({ x: event.clientX, y: event.clientY });\n }\n resetTracking();\n if (wasArmed) {\n opts.onCommit(event);\n }\n };\n\n const abort = (event?: PointerEvent): void => {\n resetTracking();\n opts.onCancel(event);\n };\n\n const cancel = (event: PointerEvent): void => {\n if (event.pointerId !== pointerId) {\n return;\n }\n abort(event);\n };\n\n const down = (event: PointerEvent): void => {\n if (start !== null) {\n return;\n }\n const preventedBefore = event.defaultPrevented;\n if (!opts.canStart(event)) {\n return;\n }\n selfPrevented = !preventedBefore && event.defaultPrevented;\n start = { x: event.clientX, y: event.clientY };\n armed = false;\n pointerId = event.pointerId;\n downEvent = event;\n\n pressListeners = new AbortController();\n const options = { capture: true, signal: pressListeners.signal };\n document.addEventListener('pointermove', move, options);\n document.addEventListener('pointerup', up, options);\n document.addEventListener('pointercancel', cancel, options);\n\n if (opts.cancelOnEscape) {\n const escape = (event: KeyboardEvent): void => {\n if (armed && event.key === 'Escape' && !isImeComposing(event)) {\n event.preventDefault();\n event.stopPropagation();\n abort();\n }\n };\n document.addEventListener('keydown', escape, options);\n }\n };\n\n const nativeDrag = (event: Event): void => {\n if (start !== null && !(downEvent?.defaultPrevented && !selfPrevented)) {\n event.preventDefault();\n }\n };\n\n const hostListener = new AbortController();\n host.addEventListener('pointerdown', down, { capture: true, signal: hostListener.signal });\n host.addEventListener('dragstart', nativeDrag, { capture: true, signal: hostListener.signal });\n\n return {\n destroy(): void {\n if (opts.cancelOnDestroy && start !== null) {\n abort();\n }\n hostListener.abort();\n releaseCapture();\n removeDocumentListeners();\n removeClickTrap();\n },\n cancel(event?: PointerEvent): void {\n if (start === null) {\n return;\n }\n abort(event);\n },\n };\n}\n","const SLOT_LAYOUT_PROPERTIES = [\n 'position',\n 'top',\n 'right',\n 'bottom',\n 'left',\n 'inset-block-start',\n 'inset-block-end',\n 'inset-inline-start',\n 'inset-inline-end',\n 'width',\n 'height',\n 'transform',\n 'translate',\n] as const;\n\n/**\n * Places the `[forDragPlaceholder]` root nodes in the slot of the out-of-flow `lifted` item by\n * copying each inline position, inset, size and transform declaration the item carries. A\n * declaration the item leaves unset keeps the placeholder's own value, so a template that sizes\n * itself keeps its height. Non-element nodes are skipped.\n */\nexport function layoutPlaceholderInSlot(nodes: readonly Node[], lifted: HTMLElement): void {\n for (const node of nodes) {\n if (!(node instanceof HTMLElement)) {\n continue;\n }\n for (const property of SLOT_LAYOUT_PROPERTIES) {\n const value = lifted.style.getPropertyValue(property);\n if (value !== '') {\n node.style.setProperty(property, value);\n }\n }\n }\n}\n","/** A registered element a press can land in: a drag item, a table row. */\nexport interface PressTarget {\n readonly host: HTMLElement;\n}\n\n/** The part of a registered drag item {@link resolvePressedDragItem} reads. */\nexport interface PressableDragItem extends PressTarget {\n /** Whether the item cannot be lifted. */\n disabled(): boolean;\n /**\n * Whether a pointer press on `target` may start a drag of this item: `false` for a press inside\n * a draggable nested in it, or outside its drag handles when it has any. Has no side effects.\n */\n acceptsPointerStart(target: EventTarget | null): boolean;\n}\n\n/**\n * The entry of `items` whose `host` is `target` or contains it, else `null`. When several do, the\n * innermost wins. Resolves through the registered hosts rather than a selector attribute, so a\n * host that received its directive through `hostDirectives` or a subclass is found like any other.\n */\nexport function findPressedDragItem<T extends PressTarget>(\n items: readonly T[],\n target: EventTarget | null,\n): T | null {\n if (!(target instanceof Node)) {\n return null;\n }\n let pressed: T | null = null;\n for (const item of items) {\n if (item.host.contains(target) && (pressed === null || pressed.host.contains(item.host))) {\n pressed = item;\n }\n }\n return pressed;\n}\n\n/**\n * The drag item a pointer press on `target` would start a drag of: the entry of `items` that\n * {@link findPressedDragItem} resolves, provided it is enabled and accepts a pointer start from\n * `target` (see {@link PressableDragItem.acceptsPointerStart}). `null` otherwise, so a coordinator\n * arms nothing for a press its item's own guard refuses.\n */\nexport function resolvePressedDragItem<T extends PressableDragItem>(\n items: readonly T[],\n target: EventTarget | null,\n): T | null {\n const pressed = findPressedDragItem(items, target);\n if (pressed === null || pressed.disabled() || !pressed.acceptsPointerStart(target)) {\n return null;\n }\n return pressed;\n}\n","import { clampPreviewPosition, type PreviewPoint } from './clamp-preview';\nimport { createDragPreview, wrapPreview, type DragPreview } from './drag-preview';\n\n/** Options handed to {@link PreviewController} at lift time. */\nexport interface PreviewControllerOptions {\n /** The lifted item's host element (the clone source for the default preview). */\n readonly source: HTMLElement;\n /** The lift-time pointer position, used to seed the grab offset and lock origin. */\n readonly point: PreviewPoint;\n /**\n * The floating preview supplied by the draggable (a consumer `[forDragPreview]` template),\n * the minimal `{ moveTo, destroy }` legacy shape, or `null`/`undefined` to let the controller\n * clone the source into the default preview.\n */\n readonly preview?: DragPreview | { moveTo(x: number, y: number): void; destroy(): void } | null;\n /** The owning document (the clone is appended to its body). */\n readonly doc: Document;\n /** The resolved boundary element confining the preview, or `null` for unbounded movement. */\n readonly boundary: HTMLElement | null;\n /** Reactive axis lock read live on every move (`'x'` / `'y'` / `null`). */\n readonly lockAxis: () => 'x' | 'y' | null;\n}\n\n/**\n * Owns a single pointer drag's floating preview and the geometry it carries: the grab offset,\n * the preview size measured at lift (the supplied preview's `element` box, else the source's),\n * the resolved boundary, the axis-lock origin, and the boundary/axis-lock clamp applied on every\n * move.\n *\n * Created once per pointer drag at lift time and disposed via {@link destroy} / {@link settle} at\n * teardown. Shared by both `ForDropList` (drag-drop) and `ForTreeNodeDrag` (tree). The supplied\n * preview may be either a full `DragPreview` or the minimal `{ moveTo, destroy }` shape.\n * Callers with no boundary or axis lock pass `boundary: null` and\n * `lockAxis: () => null` (tree's case), leaving the preview to follow the pointer at the grab\n * offset.\n *\n * Constructed directly (`new PreviewController(options)`); it holds no injection context. The\n * caller gates construction on a browser platform.\n */\nexport class PreviewController {\n readonly #preview: DragPreview;\n readonly #grabOffsetX: number;\n readonly #grabOffsetY: number;\n readonly #previewSize: { width: number; height: number };\n readonly #lockOrigin: { x: number; y: number };\n readonly #boundaryEl: HTMLElement | null;\n readonly #lockAxis: () => 'x' | 'y' | null;\n\n constructor(options: PreviewControllerOptions) {\n const { source, point, preview, doc, boundary, lockAxis } = options;\n const rect = source.getBoundingClientRect();\n this.#grabOffsetX = point.x - rect.left;\n this.#grabOffsetY = point.y - rect.top;\n this.#lockOrigin = { x: point.x - this.#grabOffsetX, y: point.y - this.#grabOffsetY };\n this.#boundaryEl = boundary;\n this.#lockAxis = lockAxis;\n const supplied = preview ? ('settle' in preview ? preview : wrapPreview(preview)) : null;\n this.#preview = supplied ?? createDragPreview(source, doc);\n const box = supplied?.element?.getBoundingClientRect() ?? rect;\n this.#previewSize = { width: box.width, height: box.height };\n const topLeft = this.#clampedTopLeft(point);\n this.#preview.moveTo(topLeft.x, topLeft.y);\n }\n\n /** Position the preview at the clamped top-left for `point`. */\n moveTo(point: PreviewPoint): void {\n const topLeft = this.#clampedTopLeft(point);\n this.#preview.moveTo(topLeft.x, topLeft.y);\n }\n\n /** The boundary/axis-lock-clamped top-left the preview would occupy for `point`. */\n #clampedTopLeft(point: PreviewPoint): PreviewPoint {\n const desired = { x: point.x - this.#grabOffsetX, y: point.y - this.#grabOffsetY };\n const boundaryRect = this.#boundaryEl?.getBoundingClientRect() ?? null;\n return clampPreviewPosition(\n desired,\n this.#previewSize,\n boundaryRect,\n this.#lockAxis(),\n this.#lockOrigin,\n );\n }\n\n /** The underlying preview, for drop-settle animation handoff. */\n get preview(): DragPreview {\n return this.#preview;\n }\n\n /** Remove the preview from the DOM. */\n destroy(): void {\n this.#preview.destroy();\n }\n}\n","/** Previous and new absolute (dataset) index of a reordered windowed row. */\nexport interface WindowReorderResult {\n /** Previous absolute (dataset) index of the lifted row (0-based). */\n readonly from: number;\n /** New absolute (dataset) index the lifted row moves to (0-based). */\n readonly to: number;\n}\n\n/**\n * Absolute index of `value` once the lifted row at `from` has been removed from\n * the dataset: every index above `from` shifts down by one to close the gap the\n * removal opened. The single post-removal shift both insertion branches of\n * {@link translateWindowReorder} share, so the `> from ? 1 : 0` surgery lives in one place rather\n * than being re-derived per branch.\n */\nfunction indexAfterRemoval(value: number, from: number): number {\n return value - (value > from ? 1 : 0);\n}\n\n/**\n * Translates a windowed list's window-relative `previousIndex` / `currentIndex`\n * into absolute dataset indices, so a virtualized list's consumer can apply\n * `moveItemInArray` over the **full** array. `windowIndices` holds the absolute\n * index of every rendered draggable row, in DOM (ascending) order — its length\n * is the rendered window size; `previousIndex` is the lifted row's position in\n * that window and `currentIndex` the resolved insertion index (post-removal\n * space, `0..windowIndices.length - 1`). Reduces to the identity when the window\n * spans the whole dataset, so a non-virtualized list is unaffected.\n */\nexport function translateWindowReorder(\n windowIndices: readonly number[],\n previousIndex: number,\n currentIndex: number,\n): WindowReorderResult {\n const from = windowIndices[previousIndex] ?? previousIndex;\n const rest = windowIndices.filter((_, i) => i !== previousIndex);\n if (currentIndex >= rest.length) {\n const last = rest[rest.length - 1];\n if (last === undefined) {\n return { from, to: from };\n }\n return { from, to: indexAfterRemoval(last + 1, from) };\n }\n const target = rest[currentIndex]!;\n return { from, to: indexAfterRemoval(target, from) };\n}\n\n/** Geometry and state for {@link resolveScrubReorder}. */\nexport interface ScrubReorderParams {\n /**\n * Whether the windowed-scrub affordance is engaged for this gesture (e.g. a\n * modifier key held during a pointer drag). When `false`, scrubbing is off and\n * the resolver returns `null` so the caller falls back to mounted-rect drop\n * resolution.\n */\n readonly engaged: boolean;\n /** Pointer position along the scroll axis, in client pixels. */\n readonly pointer: number;\n /** Scroll viewport's start edge along the scroll axis, in client pixels (top when vertical). */\n readonly viewportStart: number;\n /** Scroll viewport's end edge along the scroll axis, in client pixels (bottom when vertical). */\n readonly viewportEnd: number;\n /** Absolute (dataset) index of the lifted row. */\n readonly from: number;\n /** Total number of items in the full (non-windowed) dataset. */\n readonly count: number;\n}\n\n/**\n * Resolves a **windowed-scrub** drop: maps the pointer's position over the scroll\n * viewport to an absolute dataset index, so a single gesture can drop a lifted row\n * at an arbitrary far target without auto-scroll having to mount it first. The\n * viewport's main-axis extent maps linearly onto the final positions of the whole\n * dataset — the start edge lands the row at index `0`, the end edge at the last\n * index — independent of which rows are currently rendered, so a concurrent\n * auto-scroll never desyncs the result.\n *\n * Returns `null` when scrubbing is not engaged or the geometry is degenerate\n * (zero-height viewport, empty dataset); the caller then uses its normal\n * mounted-rect resolution, leaving the in-window path unchanged. Otherwise returns\n * the `from` / `to` pair with `to` as the row's final index (matching\n * {@link translateWindowReorder}), so `moveItemInArray` over the full array moves\n * the right row to the right place.\n */\nexport function resolveScrubReorder(params: ScrubReorderParams): WindowReorderResult | null {\n if (!params.engaged || params.count <= 0) {\n return null;\n }\n const span = params.viewportEnd - params.viewportStart;\n if (span <= 0) {\n return null;\n }\n const fraction = Math.min(1, Math.max(0, (params.pointer - params.viewportStart) / span));\n return { from: params.from, to: Math.round(fraction * (params.count - 1)) };\n}\n\n/** Inputs for {@link resolveWindowedReorder}. */\nexport interface WindowedReorderParams {\n /**\n * Absolute index of every rendered row in DOM order, or `null` when a rendered row carries\n * none — the list is then not windowed and the window-relative pair is reported unchanged.\n */\n readonly windowIndices: readonly number[] | null;\n /** The lifted row's position in the rendered window. */\n readonly previousIndex: number;\n /** The resolved insertion index in the rendered window (post-removal space). */\n readonly currentIndex: number;\n /**\n * Windowed-scrub geometry for {@link resolveScrubReorder}, without the `from` this resolver\n * derives itself, or `null` when the list offers no scrub.\n */\n readonly scrub: Omit<ScrubReorderParams, 'from'> | null;\n}\n\n/**\n * The dataset-absolute `from` / `to` pair a windowed reorder coordinator reports for one\n * window-relative reorder: the windowed-scrub target when scrub is engaged, else the\n * {@link translateWindowReorder} translation of the window pair. Every announcement and every\n * emitted descriptor of the gesture resolves through it, so what a screen reader hears is\n * where the item lands.\n */\nexport function resolveWindowedReorder(params: WindowedReorderParams): WindowReorderResult {\n const { windowIndices, previousIndex, currentIndex, scrub } = params;\n if (windowIndices === null) {\n return { from: previousIndex, to: currentIndex };\n }\n if (scrub !== null) {\n const scrubbed = resolveScrubReorder({\n ...scrub,\n from: windowIndices[previousIndex] ?? previousIndex,\n });\n if (scrubbed !== null) {\n return scrubbed;\n }\n }\n return translateWindowReorder(windowIndices, previousIndex, currentIndex);\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport { DestroyRef, effect, inject, PLATFORM_ID, type Signal, signal } from '@angular/core';\n\nexport interface ElementBox {\n /** Padding-box width (`clientWidth`) in CSS pixels — content plus padding, excluding borders and any scrollbar. */\n readonly width: number;\n /** Padding-box height (`clientHeight`) in CSS pixels — content plus padding, excluding borders and any scrollbar. */\n readonly height: number;\n /**\n * `scrollWidth` in CSS pixels, as of the last measurement. Re-read only when\n * the element's own box resizes or the observed element changes, so content\n * growing inside an unchanged box leaves it stale.\n */\n readonly scrollWidth: number;\n /**\n * `scrollHeight` in CSS pixels, as of the last measurement. Re-read only when\n * the element's own box resizes or the observed element changes, so content\n * growing inside an unchanged box leaves it stale.\n */\n readonly scrollHeight: number;\n}\n\n/**\n * Observes a target element's size with `ResizeObserver` and exposes the\n * result as a signal. A measurement emits only when one of the four\n * `ElementBox` fields actually changed.\n *\n * Returns `null` until the first measurement is taken (or while `target()`\n * is `null`). The first measurement runs when the observing `effect` first\n * sees a non-null target, then on every `ResizeObserver` callback. The\n * observer reports box-size changes only, so `scrollWidth` / `scrollHeight`\n * follow content that overflows a fixed-size box only on the next resize of\n * the box itself; a caller that needs live scroll extents observes the\n * content element too, as `[forScrollAreaContent]` does.\n *\n * Implementation notes:\n * - Browser-only: `ResizeObserver` is a DOM API, so off-browser (SSR) the\n * helper returns a frozen `signal(null)` and never constructs an observer.\n * - One `ResizeObserver` per call. The browser batches all observers, so\n * creating several is cheap.\n * - The last emitted box is held in a plain `prev` variable, not read back\n * from the `out` signal, so the effect never reads-and-writes the same\n * signal (the activation `sync(el)` would otherwise be a self-cycle).\n * - A single synchronous `sync(el)` runs when the effect attaches the\n * observer, so the target is measured exactly once on first activation.\n * - Cleaned up via `DestroyRef`.\n */\nexport function injectElementSize(target: Signal<HTMLElement | null>): Signal<ElementBox | null> {\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n return signal<ElementBox | null>(null).asReadonly();\n }\n\n const out = signal<ElementBox | null>(null);\n let observed: HTMLElement | null = null;\n let observer: ResizeObserver | null = null;\n let prev: ElementBox | null = null;\n\n const measure = (el: HTMLElement): ElementBox => ({\n width: el.clientWidth,\n height: el.clientHeight,\n scrollWidth: el.scrollWidth,\n scrollHeight: el.scrollHeight,\n });\n\n const sync = (el: HTMLElement): void => {\n const next = measure(el);\n if (\n !prev ||\n prev.width !== next.width ||\n prev.height !== next.height ||\n prev.scrollWidth !== next.scrollWidth ||\n prev.scrollHeight !== next.scrollHeight\n ) {\n prev = next;\n out.set(next);\n }\n };\n\n // React to target changes, and to box resizes through the observer.\n // @sanctioned-effect(external-source): `out` mirrors a ResizeObserver, and the\n // last emitted box is held in `prev` rather than read back from `out`, so no\n // read in this effect can depend on the signal it writes.\n effect(() => {\n const el = target();\n if (el === observed) return;\n if (observer) {\n observer.disconnect();\n observer = null;\n }\n observed = el;\n if (!el) {\n prev = null;\n out.set(null);\n return;\n }\n observer = new ResizeObserver(() => sync(el));\n observer.observe(el);\n sync(el);\n });\n\n inject(DestroyRef).onDestroy(() => {\n observer?.disconnect();\n observer = null;\n observed = null;\n });\n\n return out.asReadonly();\n}\n","import { fortyError } from './errors';\n\nconst TEMPLATE_CAUSE =\n \"Angular resolves a directive's dependencies at the template's declaration site rather than \" +\n 'where it is stamped, so a piece declared in an ng-template outside the root resolves nothing ' +\n 'even when it renders inside it.';\n\n/** Identity of a piece that resolved no coordination context, and of the root it needs. */\nexport interface OrphanContextSpec {\n /** Stable `FORCDK-<AREA>-<NNN>` identifier for this orphan case. */\n readonly code: string;\n /** The piece the error names, e.g. `'ForDialogTitle'` or `'[forSelectOption]'`. */\n readonly piece: string;\n /** Selector(s) of the root it must sit inside, e.g. `'[forDialog]'`. */\n readonly root: string;\n /** Token that resolved nothing, e.g. `'FOR_DIALOG_CONTEXT'`. */\n readonly token: string;\n /** Overrides the entry point derived from `code` — for a shared core resolver. */\n readonly scope?: string;\n}\n\n/**\n * The error a piece throws when it resolved no coordination context — by far\n * the library's most common developer mistake, and the one whose prose had\n * drifted furthest: the same failure was reported with, and without, the\n * ng-template caveat that is its real cause about a fifth of the time.\n *\n * The caveat now ships once, in this module, so every orphan report carries it\n * at no per-entry-point cost.\n */\nexport function orphanContextError(spec: OrphanContextSpec): Error {\n return fortyError({\n code: spec.code,\n scope: spec.scope,\n message: `${spec.piece} must be used inside a ${spec.root} element.`,\n cause: `No ${spec.token} provider is visible from ${spec.piece}. ${TEMPLATE_CAUSE}`,\n fix: `Move ${spec.piece} inside a ${spec.root} element, declaring any ng-template it lives in there too.`,\n });\n}\n\n/** Identity of an overlay trigger that resolved its root through neither channel. */\nexport interface UnresolvedRootSpec {\n /** Stable `FORCDK-<AREA>-<NNN>` identifier for this trigger's unresolved-root case. */\n readonly code: string;\n /** The trigger's selector, e.g. `'[forPopoverTrigger]'`. */\n readonly trigger: string;\n /** Selector of the root, e.g. `'[forPopover]'`. */\n readonly root: string;\n /** Token that resolved nothing, e.g. `'FOR_POPOVER_CONTEXT'`. */\n readonly token: string;\n /** The root's `exportAs` name, for the template-reference fix, e.g. `'forPopover'`. */\n readonly exportAs: string;\n}\n\n/**\n * The error an overlay trigger throws when neither of its two channels resolved\n * a root: no visible `token` provider, and no explicit root passed through its\n * own input. Distinct from {@link orphanContextError} because the second\n * channel makes the remedy different — a trigger stamped from an ng-template\n * can stay where it is and take the root by reference.\n */\nexport function unresolvedRootError(spec: UnresolvedRootSpec): Error {\n return fortyError({\n code: spec.code,\n message: `${spec.trigger} could not resolve its ${spec.root} root.`,\n cause: `No ${spec.token} provider is visible and no explicit root was passed. ${TEMPLATE_CAUSE}`,\n fix:\n `Move ${spec.trigger} inside the ${spec.root} element, or pass the root explicitly: ` +\n `${spec.trigger}=\"root\" with #root=\"${spec.exportAs}\".`,\n });\n}\n","import { inject, InjectionToken, type Signal, signal } from '@angular/core';\n\n/**\n * The positioning-anchor slot a `[forField]` offers the overlay controls inside\n * it. `[forFieldAnchor]` fills it; `[forSelect]`, `[forCombobox]`,\n * `[forDatePicker]` and `[forTimePicker]` position their panel against it when\n * they have no anchor of their own.\n */\nexport interface ForFieldAnchorContext {\n /** The element registered by `[forFieldAnchor]`, or `null`. */\n readonly anchor: Signal<HTMLElement | null>;\n /**\n * Register the field's positioning anchor. A field takes one anchor; a second\n * one still registered once the change-detection pass settles warns in dev\n * mode, and the most recently registered one is used.\n */\n registerAnchor(el: HTMLElement): void;\n /** Remove a previously registered anchor. A no-op for an element that never registered. */\n unregisterAnchor(el: HTMLElement): void;\n}\n\n/**\n * Injection token for the surrounding field's anchor slot. `[forField]`\n * provides it and `[forFieldBoundary]` leaves it in place, so an auxiliary\n * picker opted out of the field's control registration still aligns to the\n * field box. Resolves to `null` inside an overlay surface, whose controls are\n * positioned relative to that surface rather than to the field around it.\n */\nexport const FOR_FIELD_ANCHOR_CONTEXT = new InjectionToken<ForFieldAnchorContext | null>(\n 'FOR_FIELD_ANCHOR_CONTEXT',\n);\n\n/**\n * The surrounding field's anchor element, or a signal that stays `null` when no\n * field is reachable. An overlay root reads it as the fallback between its own\n * anchor and its trigger or input.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\nexport function injectFieldAnchor(): Signal<HTMLElement | null> {\n return (\n inject(FOR_FIELD_ANCHOR_CONTEXT, { optional: true })?.anchor ??\n signal<HTMLElement | null>(null).asReadonly()\n );\n}\n","import { untracked } from '@angular/core';\n\nexport interface DescribedByContribution {\n readonly consumer: string | null;\n write(): void;\n release(): void;\n}\n\ninterface DescribedByOwner {\n readonly consumer: string | null;\n readonly sources: Set<() => string | null>;\n}\n\nconst owners = new WeakMap<Element, DescribedByOwner>();\n\nexport function contributeDescribedBy(\n element: Element,\n ids: () => string | null,\n): DescribedByContribution {\n let owner = owners.get(element);\n if (!owner) {\n owner = { consumer: element.getAttribute('aria-describedby') || null, sources: new Set() };\n owners.set(element, owner);\n }\n const current = owner;\n const source = (): string | null => ids();\n current.sources.add(source);\n return {\n consumer: current.consumer,\n write: () => writeDescribedBy(element, current),\n release: () => {\n if (!current.sources.delete(source)) {\n return;\n }\n if (current.sources.size === 0 && owners.get(element) === current) {\n owners.delete(element);\n }\n untracked(() => writeDescribedBy(element, current));\n },\n };\n}\n\nfunction writeDescribedBy(element: Element, owner: DescribedByOwner): void {\n let value = owner.consumer;\n for (const source of owner.sources) {\n value = composeIds(value, source());\n }\n if (value === null) {\n element.removeAttribute('aria-describedby');\n } else if (element.getAttribute('aria-describedby') !== value) {\n element.setAttribute('aria-describedby', value);\n }\n}\n\n/**\n * Composes a consumer's own id-reference list with the library's own ids: the\n * consumer's ids first, then any library id not already present. Returns `null`\n * when both sides are empty so the caller removes the attribute rather than\n * setting it to `\"\"`.\n *\n * @param consumer The consumer-authored value, captured before the library\n * touched the element.\n * @param libraryIds The library-owned ids to append.\n */\nexport function composeIds(consumer: string | null, libraryIds: string | null): string | null {\n if (!consumer) {\n return libraryIds;\n }\n if (!libraryIds) {\n return consumer;\n }\n const seen = new Set(consumer.split(/\\s+/).filter(Boolean));\n const extra = libraryIds.split(/\\s+/).filter((id) => id && !seen.has(id));\n return extra.length > 0 ? `${consumer} ${extra.join(' ')}` : consumer;\n}\n","import { untracked } from '@angular/core';\n\nimport { fortyWarn } from '../errors/errors';\n\n/** An id-reference attribute whose value one owner replaces rather than composes. */\nexport type ReplacedAttribute = 'aria-labelledby' | 'aria-errormessage';\n\n/** One library piece's claim on a {@link ReplacedAttribute} of an element. */\nexport interface ReplacedAttributeClaim {\n /** The element's static value, captured before any claim wrote the attribute. */\n readonly consumer: string | null;\n /** Writes the element's resolved value. */\n write(): void;\n /** Drops this claim and rewrites the element from the claims that remain. */\n release(): void;\n}\n\ninterface ReplacedAttributeOwner {\n readonly consumer: string | null;\n readonly claims: Set<() => string | null>;\n warned: boolean;\n}\n\nconst owners: Record<ReplacedAttribute, WeakMap<Element, ReplacedAttributeOwner>> = {\n 'aria-labelledby': new WeakMap(),\n 'aria-errormessage': new WeakMap(),\n};\n\n/**\n * Registers a library piece's value for one of an element's replaced id-reference\n * attributes. Every claim on the element resolves the same value: the consumer's\n * static value, captured once by the first claim, else the earliest claim still\n * registered that resolves one. In dev mode a second claim that is still\n * registered once the pass settles, on an element with no consumer value, warns.\n *\n * @param element The element carrying the attribute.\n * @param name The attribute.\n * @param value The ids this piece supplies, or `null` while it supplies none.\n */\nexport function claimReplacedAttribute(\n element: Element,\n name: ReplacedAttribute,\n value: () => string | null,\n): ReplacedAttributeClaim {\n const registry = owners[name];\n let owner = registry.get(element);\n if (!owner) {\n owner = { consumer: element.getAttribute(name) || null, claims: new Set(), warned: false };\n registry.set(element, owner);\n }\n const current = owner;\n const claim = (): string | null => value() || null;\n current.claims.add(claim);\n if ((typeof ngDevMode === 'undefined' || ngDevMode) && current.claims.size > 1) {\n queueMicrotask(() => warnIfContested(element, name, current));\n }\n return {\n consumer: current.consumer,\n write: () => writeReplaced(element, name, current),\n release: () => {\n if (!current.claims.delete(claim)) {\n return;\n }\n if (current.claims.size <= 1) {\n current.warned = false;\n }\n if (current.claims.size === 0 && registry.get(element) === current) {\n registry.delete(element);\n }\n untracked(() => writeReplaced(element, name, current));\n },\n };\n}\n\nfunction writeReplaced(\n element: Element,\n name: ReplacedAttribute,\n owner: ReplacedAttributeOwner,\n): void {\n let value = owner.consumer;\n for (const claim of owner.claims) {\n if (value !== null) {\n break;\n }\n value = claim();\n }\n if (value === null) {\n element.removeAttribute(name);\n } else if (element.getAttribute(name) !== value) {\n element.setAttribute(name, value);\n }\n}\n\nfunction warnIfContested(\n element: Element,\n name: ReplacedAttribute,\n owner: ReplacedAttributeOwner,\n): void {\n if (owner.consumer !== null || owner.claims.size <= 1 || owner.warned) {\n return;\n }\n owner.warned = true;\n fortyWarn({\n code: 'FORCDK-CORE-013',\n message: `${owner.claims.size} library pieces supply \\`${name}\\` for the same <${element.localName}> element.`,\n cause:\n 'The attribute holds one value, so the earliest piece that resolves one is written and ' +\n 'the others are never announced.',\n fix: `Move one of the pieces to another element, or write a static \\`${name}\\` on it, which replaces every library value.`,\n });\n}\n","import { DestroyRef, effect, ElementRef, inject, InjectionToken, type Signal } from '@angular/core';\n\nimport { composedParentElement } from '../composed-tree/composed-tree';\nimport {\n contributeDescribedBy,\n type DescribedByContribution,\n} from '../host-attributes/described-by-owner';\nimport {\n claimReplacedAttribute,\n type ReplacedAttributeClaim,\n} from '../host-attributes/replaced-attribute-owner';\n\n/**\n * A validation error a form control reports to its surrounding `[forField]`.\n * Signal Forms' `ValidationError` is assignable to it.\n */\nexport interface FieldValidationError {\n /** Identifies the kind of error, such as `'required'`. */\n readonly kind: string;\n /** Human-readable message, when the validator supplied one. */\n readonly message?: string;\n}\n\n/**\n * A form control's contribution to its surrounding `[forField]`. The control\n * exposes the signals the field needs to reflect state (`data-invalid` etc.)\n * and to gate the error region; `host` is the wiring target for `id` and the\n * `aria-*` association attributes.\n */\nexport interface FieldControlHandle {\n /**\n * The control's host element. Default target of `id` / `aria-*` wiring and\n * of the label click, unless {@link labelledElement} nominates a distinct\n * element.\n */\n readonly host: HTMLElement;\n /**\n * The element that should carry the field's `aria-*` association, when it\n * differs from {@link host}. For primitives whose host is a non-interactive\n * wrapper (`<div forSelect>`, `<div forCombobox>`) this nominates the\n * focusable control inside it (the trigger button / `role=\"combobox\"` input),\n * which registers after the field wiring runs — hence a signal. When omitted\n * or resolving to `null` the field falls back to {@link host} (the\n * host-is-the-control case, e.g. `ForListbox` or a native\n * `<input forFieldControl>`).\n *\n * This nominates the **association** target only. Where focus should land on\n * a label click is {@link focus}'s job, because the two diverge on a\n * composite: a segmented date / time field names its whole `role=\"group\"` on\n * this channel and focuses one spinbutton inside it.\n */\n readonly labelledElement?: Signal<HTMLElement | null>;\n /**\n * The element a label press clicks and focuses, when it differs from the\n * association target. A picker-anatomy `[forCombobox]` nominates its trigger\n * here: while its panel is open the association moves onto the search input\n * inside it, but the label keeps toggling the panel through the trigger.\n * When omitted or resolving to `null` the label activates the association\n * target.\n */\n readonly activationTarget?: Signal<HTMLElement | null>;\n /**\n * Moves focus into the control, when it exposes an entry point of its own\n * (`FormValueControl.focus`). The field prefers this over focusing the\n * association target on a label click, because a composite root is not\n * focusable: `[forDateField]` & friends host a `role=\"group\"` whose real\n * entry point is the first editable segment. Omitted by controls whose\n * association target is itself focusable, where the field focuses that\n * element directly.\n */\n readonly focus?: (options?: FocusOptions) => void;\n /**\n * The id already host-bound on {@link labelledElement} (the Select trigger's\n * `triggerId`, the Combobox input's `inputId`). The field adopts it as its\n * `controlId` so the label's `for` points at the focusable control and the\n * primitive's own `aria-labelledby` (e.g. on the listbox content) stays in\n * sync. Only meaningful alongside `labelledElement`.\n */\n readonly labelledElementId?: Signal<string | undefined>;\n /** Reflected by the field as `data-invalid` and gates the error region. */\n readonly invalid?: Signal<boolean>;\n /** Reflected by the field as `data-required`. */\n readonly required?: Signal<boolean>;\n /** Reflected by the field as `data-disabled`. */\n readonly disabled?: Signal<boolean>;\n /** Reflected by the field as `data-touched`. */\n readonly touched?: Signal<boolean>;\n /** Validation errors surfaced by Signal Forms; read by `ForFieldError`. */\n readonly errors?: Signal<readonly FieldValidationError[]>;\n /**\n * Whether a composite control around this one currently stands in for it —\n * a field-anatomy `[forDatePicker]` adopting its `[forDateField]`. While\n * `true` the field neither resolves this handle as its control nor wires its\n * association attributes onto it; the adopting composite registers its own\n * handle and nominates this control's host as its labelled element.\n */\n readonly adopted?: Signal<boolean>;\n}\n\n/**\n * Coordination contract owned by the `ForField` root. The label, description,\n * and error pieces register with it and read the generated ids; the control\n * (via `injectFieldWiring`) registers its handle and consumes the resolved\n * `aria-*` ids.\n */\nexport interface ForFieldContext {\n /** Id assigned to the control (a label's `for` points here). */\n readonly controlId: Signal<string>;\n /** Id of the label element. */\n readonly labelId: Signal<string>;\n /** Id of the description element. */\n readonly descriptionId: Signal<string>;\n /** Id of the error element. */\n readonly errorId: Signal<string>;\n /** Resolved `aria-labelledby` for the control (label id, or null). */\n readonly labelledBy: Signal<string | null>;\n /** Resolved `aria-describedby` (description id, plus error id when invalid). */\n readonly describedBy: Signal<string | null>;\n /** Resolved `aria-errormessage` (error id when present and invalid, else null). */\n readonly errorMessageId: Signal<string | null>;\n /** Whether the registered control is currently invalid. */\n readonly invalid: Signal<boolean>;\n /** Whether the registered control is required. */\n readonly required: Signal<boolean>;\n /** Whether the registered control is disabled. */\n readonly disabled: Signal<boolean>;\n /** Whether the registered control has been touched. */\n readonly touched: Signal<boolean>;\n /** The currently registered control handle, or null. */\n readonly control: Signal<FieldControlHandle | null>;\n /**\n * The element a label press activates: the control's\n * {@link FieldControlHandle.activationTarget} when it nominates one, else\n * the element carrying the association. `null` while no control is\n * registered.\n */\n readonly activationTarget: Signal<HTMLElement | null>;\n /** The host elements of the registered `[forLabel]`s, in registration order. */\n readonly labelElements: Signal<readonly HTMLElement[]>;\n /**\n * Register the control whose state the field reflects. A field exposes a\n * single `controlId` (not an id list), so one control per `[forField]` is the\n * supported shape — group several under a `[forFieldset]`. Registrations are\n * tracked so unmounting one of several accidental duplicates falls back to the\n * previous still-mounted control; a duplicate is flagged with a dev-mode\n * warning.\n */\n registerControl(handle: FieldControlHandle): void;\n /** Remove a previously registered control. */\n unregisterControl(handle: FieldControlHandle): void;\n /**\n * Register a label's host element; returns an unregister callback. A static\n * `id` on the host is adopted as the `labelId`. The field\n * exposes a single `labelId` (not an id list), so one `[forLabel]` per field\n * is the supported shape. Registrations are **counted** (not a boolean) so\n * unmounting one of several accidental duplicates never drops the association\n * while another is still mounted; a duplicate is flagged with a dev-mode\n * warning.\n */\n registerLabel(element: HTMLElement): () => void;\n /** Register a description's host element; returns an unregister callback. A static `id` on the host is adopted as the `descriptionId`. Counted, single `[forFieldDescription]` per field — see {@link registerLabel}. */\n registerDescription(element: HTMLElement): () => void;\n /** Register an error region's host element; returns an unregister callback. A static `id` on the host is adopted as the `errorId`. Counted, single `[forFieldError]` per field — see {@link registerLabel}. */\n registerError(element: HTMLElement): () => void;\n /**\n * Forward a click to the registered control, then move focus into it — the\n * same outcome a native `<label for>` produces through the browser's\n * click-forwarding (toggling a checkbox / switch, activating a button). Used\n * by a `[forLabel]` the browser will not forward for: a non-`<label>` host,\n * which has no native `for` forwarding at all, and a native `<label>` whose\n * `for` resolves to an element other than the {@link activationTarget} (the\n * `role=\"group\"` of a segmented date / time field, the search input of an\n * open picker-anatomy combobox), so label-click activation stays consistent\n * across host shapes and control anatomies.\n */\n clickControl(): void;\n}\n\n/**\n * Injection token for the surrounding `ForField` coordination contract.\n * Resolves to `null` under a field boundary (`[forFieldBoundary]` and every\n * overlay surface that can host a control), so inject it with\n * `{ optional: true }` and treat `null` as \"no field\".\n */\nexport const FOR_FIELD_CONTEXT = new InjectionToken<ForFieldContext | null>('FOR_FIELD_CONTEXT');\n\nconst INTERACTIVE_CONTENT = 'a[href], button, input, select, textarea, summary, [tabindex]';\n\n/**\n * Wires the calling directive's host element to a surrounding `[forField]`,\n * if one exists. When there is no ancestor field this is a near-zero-cost\n * no-op (a single optional DI lookup), so every `FormUiControlBase` subclass\n * can call it unconditionally and gain field support for free.\n *\n * When a field is present it:\n * - registers the control handle so the field can reflect `data-*` state,\n * gate its error region, and focus the control on label click;\n * - reflects `id` (only if the target has none — the field owns the id a\n * label's `for` points at), `aria-labelledby`, and `aria-errormessage` on\n * the target, kept in sync via a single `effect`. A **static**\n * `aria-labelledby` / `aria-errormessage` the consumer wrote on the target\n * **replaces** the field's value (a name has one owner) and is restored\n * verbatim on teardown, so the field never erases or overrides it. When\n * another library piece also names the target, the one registered first\n * keeps the attribute, and dev mode warns;\n * - **composes** `aria-describedby`: any value the consumer set statically on\n * the target is captured on first wiring and preserved, with the field's own\n * description / error ids appended after it — so a `aria-describedby=\"hint\"`\n * is never clobbered, and it is restored verbatim when the control (or the\n * target) is torn down. Ids another library piece contributes to the same\n * element (a tooltip trigger on the control) are kept beside the field's.\n *\n * The wiring target is the host by default, or the handle's\n * {@link FieldControlHandle.labelledElement} when it nominates a distinct\n * focusable control (Select trigger / Combobox input) inside a non-interactive\n * wrapper host. That element registers after this runs, so the effect tracks it\n * reactively and migrates the attributes (clearing the previously-targeted\n * element) once it appears.\n *\n * Imperative DOM writes (mirroring `FormUiControlBase`'s `data-*` reflection)\n * so the caller's declarative `host: { ... }` block stays free of these\n * attributes.\n *\n * @param handle The control's state signals (all optional). `host` is filled\n * in from the calling directive's `ElementRef`. Pass `labelledElement` to\n * target a child control instead of the host.\n */\nexport function injectFieldWiring(handle: Omit<FieldControlHandle, 'host'> = {}): void {\n const field = inject(FOR_FIELD_CONTEXT, { optional: true });\n if (!field) {\n return;\n }\n\n const el = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const fullHandle: FieldControlHandle = { host: el, ...handle };\n field.registerControl(fullHandle);\n inject(DestroyRef).onDestroy(() => field.unregisterControl(fullHandle));\n\n const labelledElement = handle.labelledElement;\n const adopted = handle.adopted;\n let previousTarget: HTMLElement | null = null;\n let ownsId = false;\n let association: FieldAssociation | null = null;\n\n effect(() => {\n // Resolve the wiring target: the nominated focusable element when a\n // `labelledElement` is declared, else the host. A declared-but-unresolved\n // labelled element (its directive registers after this runs) yields `null`\n // here, and we wire nothing — never the wrapper host — until it appears.\n const target = adopted?.() ? null : labelledElement ? labelledElement() : el;\n\n if (previousTarget !== target) {\n if (previousTarget) {\n releaseTarget(previousTarget, ownsId, field.controlId());\n ownsId = false;\n }\n association?.release();\n association = target ? associate(target, field) : null;\n previousTarget = target;\n }\n\n if (!target) {\n return;\n }\n\n if (!target.getAttribute('id')) {\n target.setAttribute('id', field.controlId());\n ownsId = true;\n }\n association?.write();\n });\n\n inject(DestroyRef).onDestroy(() => {\n if (previousTarget) {\n releaseTarget(previousTarget, ownsId, field.controlId());\n }\n association?.release();\n });\n}\n\ninterface FieldAssociation {\n write(): void;\n release(): void;\n}\n\n/**\n * Claims the target's `aria-labelledby` and `aria-errormessage` and contributes\n * to its `aria-describedby`, each through the attribute's per-element owner, so\n * a consumer's static value and any other library piece's are kept.\n */\nfunction associate(target: HTMLElement, field: ForFieldContext): FieldAssociation {\n const parts: ReadonlyArray<ReplacedAttributeClaim | DescribedByContribution> = [\n claimReplacedAttribute(target, 'aria-labelledby', () => field.labelledBy()),\n contributeDescribedBy(target, () => field.describedBy()),\n claimReplacedAttribute(target, 'aria-errormessage', () => field.errorMessageId()),\n ];\n return {\n write: () => parts.forEach((part) => part.write()),\n release: () => parts.forEach((part) => part.release()),\n };\n}\n\n/**\n * Drops the field-owned `id` from a previously-targeted element when this\n * helper set it, so an arbitrary foreign `labelledElement` is left clean once\n * the control is destroyed or the target migrates.\n */\nfunction releaseTarget(target: HTMLElement, ownsId: boolean, controlId: string): void {\n if (ownsId && target.getAttribute('id') === controlId) {\n target.removeAttribute('id');\n }\n}\n\nexport function crossesInteractiveContent(target: Node | null, boundary: Element): boolean {\n for (let node = target; node !== null && node !== boundary; node = composedParentElement(node)) {\n if (node.nodeType === node.ELEMENT_NODE && (node as Element).matches(INTERACTIVE_CONTENT)) {\n return true;\n }\n }\n return false;\n}\n\nexport function injectFieldLabelExemption(\n exempt: () => readonly Element[],\n): (target: Node) => readonly Element[] {\n const field = inject(FOR_FIELD_CONTEXT, { optional: true, skipSelf: true });\n if (!field) {\n return exempt;\n }\n return (target) => {\n const elements = exempt();\n const control = field.activationTarget();\n if (control === null || !elements.includes(control)) {\n return elements;\n }\n const labels = field\n .labelElements()\n .filter((label) => !crossesInteractiveContent(target, label));\n return [...elements, ...labels];\n };\n}\n","import { InjectionToken, type Signal } from '@angular/core';\n\n/**\n * Coordination contract owned by the `ForFieldset` root. A `[forFieldsetLegend]`\n * reads `legendId`, hands its host over for static-`id` adoption, and registers\n * its presence so the fieldset can resolve its `aria-labelledby`; a descendant\n * form control optionally reads `effectiveDisabled` and ORs it into its own\n * disabled state.\n *\n * The token lives in its own file (no directive import) so a consumer of another\n * primitive — a form control reading `effectiveDisabled` here — pulls in only the\n * token, never the `ForFieldset` directive, keeping the library tree-shakable.\n */\nexport interface ForFieldsetContext {\n /** Id of the legend element; the group's `aria-labelledby` points here. */\n readonly legendId: Signal<string>;\n /**\n * Adopt a consumer-set **static** `id` on the legend host into `legendId`, so\n * the legend's `[id]` host binding re-emits it instead of clobbering it with\n * the generated fallback. Called by `[forFieldsetLegend]` from its\n * constructor, before the first host-binding pass.\n */\n adoptLegendId(el: HTMLElement): void;\n /**\n * Whether the fieldset (and therefore its descendants) is effectively\n * disabled — its own `disabled` input OR'd with an enclosing disabled\n * `[forFieldset]`, so nested groups compose like native `<fieldset disabled>`.\n * Descendant controls OR this into their own disabled state.\n */\n readonly disabled: Signal<boolean>;\n /** Mark a legend present; returns an unregister callback. */\n registerLegend(): () => void;\n}\n\n/** Injection token for the surrounding `ForFieldset` coordination contract. */\nexport const FOR_FIELDSET_CONTEXT = new InjectionToken<ForFieldsetContext>('FOR_FIELDSET_CONTEXT');\n","import {\n composedContains,\n composedParentElement,\n composedPrecedes,\n} from '../composed-tree/composed-tree';\n\n/**\n * The ten local names {@link FOCUSABLE_SELECTOR} anchors a clause on, each\n * mapped to the qualifier that clause carries — `[href]` for the two link\n * elements, `[controls]` for the two media ones, `:not([disabled])` for the\n * form controls, and nothing for the two that are focusable on their own.\n * Keys are lowercase and compared against `localName` rather than `tagName`,\n * so the two agree on a non-HTML-namespaced element: an SVG `<a href>` is\n * matched by the selector's `a[href]` clause and reports `tagName` `'a'`,\n * which an uppercase set would drop.\n */\nconst FOCUSABLE_LOCAL_NAME_QUALIFIERS: Readonly<Record<string, string>> = {\n a: '[href]',\n area: '[href]',\n button: ':not([disabled])',\n input: ':not([disabled]):not([type=\"hidden\"])',\n select: ':not([disabled])',\n textarea: ':not([disabled])',\n audio: '[controls]',\n video: '[controls]',\n iframe: '',\n summary: '',\n};\n\n/**\n * The two clauses {@link FOCUSABLE_SELECTOR} anchors on an attribute rather\n * than on a local name, so any element can match them.\n */\nconst FOCUSABLE_ATTRIBUTE_CLAUSES = ['[tabindex]:not([tabindex=\"-1\"])', '[contenteditable=\"true\"]'];\n\nconst HIDDEN_ATTRIBUTE = 'hidden';\nconst INERT_ATTRIBUTE = 'inert';\nconst OPEN_ATTRIBUTE = 'open';\n\n/**\n * Shared CSS selector for focusable elements. Single source of truth for the\n * library — primitives that need their own focus-finding logic (e.g. the\n * dialog directive's non-modal initial focus, the programmatic dialog\n * manager's bootstrap, future menu / popover initial-focus paths) import\n * this rather than maintaining a private copy that drifts.\n *\n * This matches elements that can *receive* focus — the superset used for\n * initial-focus targets. A natively-focusable element carrying\n * `tabindex=\"-1\"` (e.g. a `<button tabindex=\"-1\">` roving-tabindex\n * collection item) still matches via its tag selector, but is excluded from\n * the sequential Tab cycle at runtime by `isTabbableCandidate`. `iframe` and\n * `summary` are included because both are natively focusable and can\n * legitimately be an initial-focus target inside a trapped surface.\n *\n * Derived from {@link FOCUSABLE_LOCAL_NAME_QUALIFIERS} plus\n * {@link FOCUSABLE_ATTRIBUTE_CLAUSES} so the pre-filter below cannot fall out\n * of step with it — the correspondence the two used to keep by hand is now\n * structural. `focusable-candidate.spec.ts` pins the derived clause set\n * against the literal it replaced.\n */\nexport const FOCUSABLE_SELECTOR = /* @__PURE__ */ [\n ...Object.entries(FOCUSABLE_LOCAL_NAME_QUALIFIERS).map(([name, qualifier]) => name + qualifier),\n ...FOCUSABLE_ATTRIBUTE_CLAUSES,\n].join(',');\n\nfunction focusabilityAttributes(selector: string): string[] {\n return [\n ...new Set([\n ...[...selector.matchAll(/\\[([\\w-]+)/g)].map((match) => match[1]!),\n HIDDEN_ATTRIBUTE,\n INERT_ATTRIBUTE,\n OPEN_ATTRIBUTE,\n ]),\n ];\n}\n\nexport const FOCUSABILITY_ATTRIBUTES: readonly string[] =\n /* @__PURE__ */ focusabilityAttributes(FOCUSABLE_SELECTOR);\n\n/**\n * Every element under `container` matching {@link FOCUSABLE_SELECTOR}, in\n * composed-tree order, descending into open shadow roots.\n *\n * The walk enumerates elements and filters in JS rather than handing the selector to the engine,\n * because `querySelectorAll` stops at a shadow boundary and a shadow host is not expressible in\n * CSS. `container`'s own shadow root is traversed before its light children, matching what\n * `composedContains` already counts as inside it. Closed shadow roots stay invisible.\n *\n * **Order** follows the light tree with each host's shadow contents inlined at the host — the\n * flattened order for a host that renders no `<slot>`. Once content is slotted the two diverge:\n * assigned nodes are visited with the light tree, after the whole shadow tree, whereas the browser\n * sequences them at the `<slot>`'s position. A host with focusables after its `<slot>` therefore\n * yields a first / last pair the real Tab cycle disagrees with.\n */\nexport function queryFocusableCandidates(container: HTMLElement): HTMLElement[] {\n const found: HTMLElement[] = [];\n if (container.shadowRoot) {\n collectFocusableCandidates(container.shadowRoot, found);\n }\n collectFocusableCandidates(container, found);\n return found;\n}\n\n/**\n * Reports whether `el` can currently receive focus. An element is excluded when it:\n *\n * - carries the `[hidden]` attribute;\n * - is `:disabled`, by its own `disabled` attribute or by an ancestor `<fieldset disabled>`\n * (a control inside that fieldset's first `<legend>` stays enabled);\n * - carries `[inert]` itself, or is nested under an `[inert]` ancestor below `root`;\n * - is not rendered: `display: none` on the element or any ancestor below `root`,\n * `visibility: hidden` / `collapse` on the element itself, `content-visibility: hidden` on an\n * ancestor below `root`, or content of a closed `<details>` below `root` outside its first\n * `<summary>`.\n *\n * `root` bounds the ancestor walk, so the container's own state is never consulted. Both walks\n * climb the composed tree, so an `[inert]` or `display: none` shadow host disqualifies the controls\n * inside its shadow root.\n *\n * This is the *focusable* set, not the Tab cycle: a candidate carrying `tabindex=\"-1\"` qualifies.\n *\n * Reads `getComputedStyle`, so callers must gate it behind `isPlatformBrowser`.\n */\nexport function isFocusableCandidate(el: HTMLElement, root: HTMLElement): boolean {\n return (\n !el.hasAttribute(HIDDEN_ATTRIBUTE) &&\n !isDisabledControl(el) &&\n !hasInertAncestor(el, root) &&\n !isUnrendered(el, root)\n );\n}\n\n/**\n * Whether `el` is a form control the browser refuses to focus because it is `:disabled`: its own\n * `disabled` attribute, or an ancestor `<fieldset disabled>` it does not sit in the first\n * `<legend>` of. An element that has no disabled state, such as a `tabindex` host inside a disabled\n * fieldset, reports `false`.\n */\nexport function isDisabledControl(el: Element): boolean {\n return el.matches(':disabled');\n}\n\n/**\n * Reports whether `el` is a *tabbable* candidate — a focusable candidate\n * (`isFocusableCandidate`) that also participates in the sequential Tab cycle\n * (`tabIndex >= 0`). A natively-focusable element carrying `tabindex=\"-1\"` is\n * a valid focus target but is excluded here.\n *\n * A native radio in a named group is a tab stop only when it is the group's checked member, or\n * when no member is checked: the browser stops on one radio per group. The group is every radio\n * sharing its name and form owner in the same document or shadow root, inside `root` or not.\n */\nexport function isTabbableCandidate(el: HTMLElement, root: HTMLElement): boolean {\n return isTabStop(el, root, new Map());\n}\n\n/**\n * Reports whether `el` can take an explicit initial-focus move into `root`: it lives inside `root`\n * in the composed tree, is focusable natively or through a `tabindex` attribute (`tabindex=\"-1\"`\n * included, so a static heading qualifies), and is a focusable candidate under\n * {@link isFocusableCandidate}.\n *\n * Reads `getComputedStyle`, so callers must gate it behind `isPlatformBrowser`.\n */\nexport function isInitialFocusTarget(el: HTMLElement, root: HTMLElement): boolean {\n return (\n composedContains(root, el) &&\n (el.matches(FOCUSABLE_SELECTOR) || el.hasAttribute('tabindex')) &&\n isFocusableCandidate(el, root)\n );\n}\n\n/** The two ends of a container's Tab cycle, as resolved by {@link findTabbableEdges}. */\nexport interface TabbableEdges {\n /** First tabbable descendant in candidate order, or `null` when the container has none. */\n first: HTMLElement | null;\n /** Last tabbable descendant; the same element as `first` when only one qualifies. */\n last: HTMLElement | null;\n}\n\n/**\n * The first and last tabbable descendants of `container`, resolved from a single\n * {@link queryFocusableCandidates} enumeration.\n *\n * Only the two ends are ever needed to cycle Tab, so the filter runs from each end and stops on the\n * first candidate that qualifies instead of resolving the whole set. That is what keeps the cost of\n * a keystroke off the size of the surface: `isFocusableCandidate` climbs the composed ancestor chain\n * calling `getComputedStyle` at every level, so filtering N candidates to read two of them costs\n * O(N × depth) forced style recalculations where O(depth) will do. The cheap `tabIndex` half of the\n * test is what makes the scan short on a roving collection too — every item carrying\n * `tabindex=\"-1\"` is rejected without a style read.\n *\n * Both ends are `null` only when the container has no tabbable descendant at all, which is the one\n * case that still walks every candidate.\n */\nexport function findTabbableEdges(container: HTMLElement): TabbableEdges {\n const candidates = queryFocusableCandidates(container);\n const groups = new Map<HTMLInputElement, boolean>();\n const firstIndex = candidates.findIndex((el) => isTabStop(el, container, groups));\n if (firstIndex === -1) {\n return { first: null, last: null };\n }\n const first = candidates[firstIndex]!;\n for (let i = candidates.length - 1; i > firstIndex; i--) {\n const candidate = candidates[i]!;\n if (isTabStop(candidate, container, groups)) {\n return { first, last: candidate };\n }\n }\n return { first, last: first };\n}\n\n/**\n * Whether a Tab press from `active` leaves the Tab cycle whose ends are `edges`: going backward\n * from the first tabbable or anything before it, going forward from the last tabbable or anything\n * after it. An edge that is a native radio stands for its whole group, since Tab from any member\n * moves past all of them. A container with no tabbable descendant, or a `null` `active`, always\n * leaves.\n */\nexport function leavesTabSequence(\n { first, last }: TabbableEdges,\n active: Element | null,\n backward: boolean,\n): boolean {\n if (first === null || last === null || active === null) {\n return true;\n }\n return backward\n ? active === first || inSameRadioGroup(active, first) || composedPrecedes(active, first)\n : active === last || inSameRadioGroup(active, last) || composedPrecedes(last, active);\n}\n\n/**\n * Where a Tab press from `active` lands when the tabbable descendants of `moved` are read as\n * sitting right after `anchor` in the document's Tab sequence, or `null` when the press can be\n * left to the browser.\n *\n * A press starting at `anchor` or inside `moved` always resolves to a stop, so the relocated\n * stretch is walked the same way in a browser that skips some of its elements by default, as\n * Safari does links. Any other press is left to the browser when document order lands on the same\n * stop. `null` is also returned for an `active` or `anchor` outside the candidate set, an `anchor`\n * inside `moved`, and a move that would run off either end of the sequence.\n *\n * Both sequences are read from {@link queryFocusableCandidates} over the document body, so the\n * order limits stated there apply, and a positive `tabindex` is read in document order.\n *\n * Reads `getComputedStyle`, so callers must gate it behind `isPlatformBrowser`.\n */\nexport function findRelocatedTabStop(\n active: Element,\n anchor: HTMLElement,\n moved: HTMLElement,\n backward: boolean,\n): HTMLElement | null {\n const doc = anchor.ownerDocument;\n if (!doc.body || composedContains(moved, anchor)) {\n return null;\n }\n const candidates = queryFocusableCandidates(doc.body);\n const outside: HTMLElement[] = [];\n const inside: HTMLElement[] = [];\n for (const candidate of candidates) {\n (composedContains(moved, candidate) ? inside : outside).push(candidate);\n }\n const anchorIndex = outside.indexOf(anchor);\n if (anchorIndex === -1) {\n return null;\n }\n const relocated = [\n ...outside.slice(0, anchorIndex + 1),\n ...inside,\n ...outside.slice(anchorIndex + 1),\n ];\n const root = doc.documentElement;\n const groups = new Map<HTMLInputElement, boolean>();\n const step = backward ? -1 : 1;\n const target = nextTabStop(relocated, active, step, root, groups);\n if (target === null || active === anchor || composedContains(moved, active)) {\n return target;\n }\n const native = nextTabStop(candidates, active, step, root, groups);\n return target === native ? null : target;\n}\n\nfunction nextTabStop(\n sequence: readonly HTMLElement[],\n active: Element,\n step: 1 | -1,\n root: HTMLElement,\n groups: Map<HTMLInputElement, boolean>,\n): HTMLElement | null {\n const from = sequence.findIndex((el) => el === active);\n if (from === -1) {\n return null;\n }\n for (let i = from + step; i >= 0 && i < sequence.length; i += step) {\n const candidate = sequence[i]!;\n if (isTabStop(candidate, root, groups)) {\n return candidate;\n }\n }\n return null;\n}\n\n/**\n * The focusable descendant of `container` one step from `from` in candidate order — the next\n * one for `'forward'`, the previous for `'backward'` — wrapping around at either end, so a\n * caller cycling a bounded set never runs out. `null` only when `container` has no focusable\n * descendant at all.\n *\n * `from` is matched against the candidate set through composed containment, resolving to the\n * *innermost* candidate that contains it: an event target nested inside a candidate (a `<span>`\n * within a `<button>`) steps from that candidate, and a candidate nested inside another (a\n * `<button>` inside a `<summary>`) steps from the inner one rather than from its wrapper. A `from`\n * that is `null`, outside `container`, or no longer a candidate yields the first candidate going\n * forward and the last going backward — the step stays inside `container` either way.\n *\n * This is the *focusable* set, not the Tab cycle: a candidate carrying `tabindex=\"-1\"` takes part,\n * so the cycle reaches exactly what {@link findFirstFocusable} would enter.\n *\n * Like {@link findTabbableEdges} it filters lazily, walking outwards from `from` and stopping on\n * the first candidate that qualifies, so a keystroke costs the O(depth) style reads of a single\n * `isFocusableCandidate` call rather than the O(N × depth) of filtering the whole set up front.\n * Only a container whose every candidate is hidden walks all of them, which is the case that\n * returns `null`.\n *\n * Reads `getComputedStyle`, so callers must gate it behind `isPlatformBrowser`.\n */\nexport function stepFocusableCycle(\n container: HTMLElement,\n from: Element | null,\n direction: 'forward' | 'backward',\n): HTMLElement | null {\n const candidates = queryFocusableCandidates(container);\n if (candidates.length === 0) {\n return null;\n }\n const step = direction === 'forward' ? 1 : -1;\n const current = from === null ? -1 : indexOfInnermostContaining(candidates, from);\n const start = current === -1 ? (step === 1 ? 0 : candidates.length - 1) : current + step;\n for (let i = 0; i < candidates.length; i++) {\n const offset = (start + i * step) % candidates.length;\n const candidate = candidates[(offset + candidates.length) % candidates.length]!;\n if (isFocusableCandidate(candidate, container)) {\n return candidate;\n }\n }\n return null;\n}\n\n/**\n * The index of the innermost candidate containing `from`, or `-1` when none does. The candidates\n * that contain `from` are its ancestors-or-self, so document order lists them outermost first and\n * the last match is the innermost — the one that actually holds the focus, rather than a wrapper\n * whose next step would land back on it.\n */\nfunction indexOfInnermostContaining(candidates: readonly HTMLElement[], from: Element): number {\n for (let i = candidates.length - 1; i >= 0; i--) {\n if (composedContains(candidates[i]!, from)) {\n return i;\n }\n }\n return -1;\n}\n\nconst FOCUSABLE_LOCAL_NAMES = /* @__PURE__ */ new Set(\n /* @__PURE__ */ Object.keys(FOCUSABLE_LOCAL_NAME_QUALIFIERS),\n);\n\n/**\n * Whether `el` could possibly match {@link FOCUSABLE_SELECTOR} — a deliberate superset, so `false`\n * is a safe skip and `true` still has to clear the selector itself.\n *\n * Every clause of that selector is anchored on one of {@link FOCUSABLE_LOCAL_NAMES}, on\n * `[tabindex]:not([tabindex=\"-1\"])`, or on `[contenteditable=\"true\"]`, which lets a structural\n * element answer without entering the selector engine. The name-anchored half is the same\n * declaration the selector is built from, so a name can no longer be added to one and not the\n * other; the two attribute clauses are matched here in their relaxed form (any\n * `contenteditable` value, not only `\"true\"`), which is what keeps this a superset.\n */\nfunction mayMatchFocusableSelector(el: Element): boolean {\n if (FOCUSABLE_LOCAL_NAMES.has(el.localName)) {\n return true;\n }\n const tabindex = el.getAttribute('tabindex');\n return (tabindex !== null && tabindex !== '-1') || el.hasAttribute('contenteditable');\n}\n\nfunction inSameRadioGroup(a: Element, b: Element): boolean {\n return (\n a !== b &&\n isGroupedRadio(a) &&\n isGroupedRadio(b) &&\n a.name === b.name &&\n a.form === b.form &&\n a.getRootNode() === b.getRootNode()\n );\n}\n\nfunction isTabStop(\n el: HTMLElement,\n root: HTMLElement,\n groups: Map<HTMLInputElement, boolean>,\n): boolean {\n return (\n el.tabIndex >= 0 &&\n (!isGroupedRadio(el) || el.checked || !radioGroupHasChecked(el, groups)) &&\n isFocusableCandidate(el, root)\n );\n}\n\nfunction isGroupedRadio(el: Element): el is HTMLInputElement {\n return (\n el.localName === 'input' &&\n (el as HTMLInputElement).type === 'radio' &&\n (el as HTMLInputElement).name !== ''\n );\n}\n\nfunction radioGroupHasChecked(\n radio: HTMLInputElement,\n groups: Map<HTMLInputElement, boolean>,\n): boolean {\n const known = groups.get(radio);\n if (known !== undefined) {\n return known;\n }\n const scope = radio.getRootNode() as ParentNode;\n const members = [...scope.querySelectorAll<HTMLInputElement>('input[type=\"radio\"]')].filter(\n (other) => other.name === radio.name && other.form === radio.form,\n );\n const hasChecked = members.some((member) => member.checked);\n for (const member of members) {\n groups.set(member, hasChecked);\n }\n groups.set(radio, hasChecked);\n return hasChecked;\n}\n\nfunction collectFocusableCandidates(root: ParentNode, found: HTMLElement[]): void {\n for (const el of root.querySelectorAll<HTMLElement>('*')) {\n if (mayMatchFocusableSelector(el) && el.matches(FOCUSABLE_SELECTOR)) {\n found.push(el);\n }\n const shadow = el.shadowRoot;\n if (shadow) {\n collectFocusableCandidates(shadow, found);\n }\n }\n}\n\nfunction hasInertAncestor(el: HTMLElement, root: HTMLElement): boolean {\n let cur: HTMLElement | null = el;\n while (cur && cur !== root) {\n if (cur.hasAttribute(INERT_ATTRIBUTE)) {\n return true;\n }\n cur = composedParentElement(cur);\n }\n return false;\n}\n\nfunction isUnrendered(el: HTMLElement, root: HTMLElement): boolean {\n const win = el.ownerDocument.defaultView;\n const canReadStyle = !!win && typeof win.getComputedStyle === 'function';\n let cur: HTMLElement | null = el;\n while (cur && cur !== root) {\n if (canReadStyle) {\n const style = win.getComputedStyle(cur);\n if (style.display === 'none') {\n return true;\n }\n if (cur === el) {\n if (style.visibility === 'hidden' || style.visibility === 'collapse') {\n return true;\n }\n } else if (style.contentVisibility === 'hidden') {\n return true;\n }\n }\n const parent = composedParentElement(cur);\n if (parent !== null && parent !== root && isClosedDetailsContent(parent, cur)) {\n return true;\n }\n cur = parent;\n }\n return false;\n}\n\nfunction isClosedDetailsContent(parent: HTMLElement, child: HTMLElement): boolean {\n return (\n parent.localName === 'details' &&\n !parent.hasAttribute(OPEN_ATTRIBUTE) &&\n child !== parent.querySelector(':scope > summary')\n );\n}\n","/**\n * Attribute that exempts a root-level child from the modal inert pass.\n * Carried by dialog / drawer backdrops (portaled alongside the modal), which\n * host-bind the literal, and written by `InertSiblingsStack` onto a registered\n * overlay host while that overlay belongs to the topmost modal, so the initial\n * sweep and the late-sibling observer skip it instead of inerting it like a\n * background sibling.\n *\n * Lives in `forty-cdk/core` rather than beside `InertSiblingsStack` in\n * `forty-cdk/core-overlay` because `LiveAnnouncer` stamps the exempt attribute\n * on its own regions, and the announcer is reached by primitives that compose\n * no overlay at all.\n */\nexport const MODAL_PEER_ATTRIBUTE = 'data-for-modal-peer';\n\n/**\n * Marks a root-level child as an independent overlay surface that must stay usable while a modal is\n * open.\n *\n * Stronger than {@link MODAL_PEER_ATTRIBUTE}: like a peer it is skipped by the inert pass, and in\n * addition every active modal's dismissible layer treats interactions inside it as inside, so a\n * pointer-down or focus within it never dismisses the modal. A peer such as a backdrop\n * stays part of the dismiss-outside surface; an exempt overlay does not.\n *\n * Carried by `ForToastViewport` and by every `LiveAnnouncer` region. The viewport host-binds the\n * literal; imperative callers use this constant.\n */\nexport const MODAL_EXEMPT_ATTRIBUTE = 'data-for-modal-exempt';\n","import { isPlatformBrowser } from '@angular/common';\nimport { DestroyRef, DOCUMENT, ElementRef, Injectable, inject, PLATFORM_ID } from '@angular/core';\n\nimport {\n composedClosest,\n composedContains,\n resolveActiveElement,\n} from '../composed-tree/composed-tree';\nimport {\n findTabbableEdges,\n isFocusableCandidate,\n leavesTabSequence,\n queryFocusableCandidates,\n} from './focusable-candidate';\nimport { fortyWarn } from '../errors/errors';\nimport { MODAL_EXEMPT_ATTRIBUTE, MODAL_PEER_ATTRIBUTE } from '../host-attributes/modal-attributes';\n\nconst INDEPENDENT_SURFACE_SELECTOR = `[${MODAL_EXEMPT_ATTRIBUTE}], [${MODAL_PEER_ATTRIBUTE}]`;\n\n/**\n * Returns the first focusable descendant of `container`, or `null` if none exists.\n *\n * Excludes `[hidden]`, disabled controls, `[inert]` subtrees and content that is not rendered,\n * the closed part of a `<details>` included. A candidate carrying `tabindex=\"-1\"` still\n * qualifies — this is the focusable set, not the Tab cycle. Descends into open shadow roots.\n */\nexport function findFirstFocusable(container: HTMLElement): HTMLElement | null {\n const candidates = queryFocusableCandidates(container);\n for (const el of candidates) {\n if (isFocusableCandidate(el, container)) {\n return el;\n }\n }\n return null;\n}\n\nexport interface FocusTrapActivateOptions {\n /**\n * Where to send focus on activation.\n * - `'first'` (default): the first focusable descendant. Falls back to the container.\n * - `'container'`: the trap container itself (gains `tabindex=\"-1\"` if needed).\n * - explicit element: focuses that element directly.\n */\n initialFocus?: 'first' | 'container' | HTMLElement;\n /**\n * Sets up Tab cycling and captures the return-focus target, but skips the imperative `.focus()`\n * call so focus stays wherever the consumer put it. Default `false`.\n */\n preventInitialFocus?: boolean;\n /**\n * Element to restore focus to on `deactivate({ returnFocus: true })`. Defaults to\n * `document.activeElement` at activation time.\n *\n * Pass it explicitly when the return target must be locked in before a side effect that moves\n * focus itself, such as applying `inert` to sibling elements.\n */\n returnFocus?: HTMLElement | null;\n}\n\nexport interface FocusTrapDeactivateOptions {\n /** Whether to restore focus to whatever held it at activation time. Default `true`. */\n returnFocus?: boolean;\n}\n\n/**\n * Application-scoped LIFO registry of active {@link FocusTrap} instances.\n *\n * Only the topmost trap handles Tab; shallower traps stay registered with inert keydown handlers,\n * so nested overlays cycle focus inside the innermost surface.\n */\n@Injectable({ providedIn: 'root' })\nexport class FocusTrapStack {\n readonly #stack: FocusTrap[] = [];\n\n /** Pushes a newly-activated trap onto the top of the stack. */\n push(trap: FocusTrap): void {\n this.#stack.push(trap);\n }\n\n /** Removes a deactivated trap from the stack (last occurrence). */\n remove(trap: FocusTrap): void {\n const idx = this.#stack.lastIndexOf(trap);\n if (idx >= 0) {\n this.#stack.splice(idx, 1);\n }\n }\n\n /** Returns `true` when `trap` is the topmost (most recently pushed) trap. */\n isTopmost(trap: FocusTrap): boolean {\n return this.#stack[this.#stack.length - 1] === trap;\n }\n}\n\n/**\n * Cycles Tab / Shift+Tab focus inside a container element.\n *\n * When several traps are active, only the topmost one handles Tab; the rest stay registered with\n * inert handlers until it deactivates.\n *\n * Both the tabbable set and the containment check are resolved against the composed tree, so\n * controls inside an open shadow root take part in the cycle. A closed shadow root stays opaque.\n *\n * Tab wraps whenever the browser's own move would leave the container: from the last tabbable, or\n * from any focused element after it, Tab goes to the first; from the first tabbable, or from the\n * container or any focused element before it, Shift+Tab goes to the last.\n *\n * A surface outside the container carrying `data-for-modal-exempt` or `data-for-modal-peer` (a\n * toast viewport, a popover opened from inside the modal) keeps its own Tab sequence: Tab moves\n * natively between its tabbables, and a move past either end of it is left to the surface's own\n * keydown handlers first. When one of them moves focus back into the container (a tab-out to the\n * trigger), the in-container rule applies from there and the browser advances natively; when\n * focus is still on the surface, it returns to the container — Tab to the first tabbable,\n * Shift+Tab to the last. Focus anywhere else outside the container is pulled back to the first\n * tabbable.\n *\n * Marking the rest of the page `inert` is out of scope — pointer isolation is the consumer's job.\n */\nexport class FocusTrap {\n readonly #container: HTMLElement;\n readonly #stack: FocusTrapStack;\n readonly #document: Document;\n readonly #isBrowser: boolean;\n #returnTo: HTMLElement | null = null;\n #active = false;\n #containerHadTabindex = false;\n #keyboardChannel: AbortController | null = null;\n #deferredTab: KeyboardEvent | null = null;\n\n readonly #onKeyDown = (event: KeyboardEvent): void => this.#handleKeyDown(event);\n readonly #onKeyDownSettled = (event: KeyboardEvent): void => this.#settleDeferredTab(event);\n\n constructor(container: HTMLElement, stack: FocusTrapStack, doc?: Document, isBrowser = true) {\n this.#container = container;\n this.#stack = stack;\n this.#document = doc ?? container.ownerDocument;\n this.#isBrowser = isBrowser;\n }\n\n get container(): HTMLElement {\n return this.#container;\n }\n\n /**\n * Whether the trap has been activated and not yet deactivated.\n *\n * Only `deactivate()` clears it — {@link releaseKeyboardChannel} leaves it set. It is therefore\n * not a reading of the keyboard channel, and it is still `true` during a `DestroyRef.onDestroy`\n * hook that runs before the owner's own `deactivate()`.\n */\n get isActive(): boolean {\n return this.#active;\n }\n\n activate(options: FocusTrapActivateOptions = {}): void {\n if (this.#active || !this.#isBrowser) {\n return;\n }\n this.#active = true;\n this.#containerHadTabindex = this.#container.hasAttribute('tabindex');\n this.#returnTo =\n options.returnFocus !== undefined\n ? options.returnFocus\n : (resolveActiveElement(this.#document) as HTMLElement | null);\n this.#keyboardChannel = new AbortController();\n this.#document.addEventListener('keydown', this.#onKeyDown, {\n capture: true,\n signal: this.#keyboardChannel.signal,\n });\n this.#document.addEventListener('keydown', this.#onKeyDownSettled, {\n signal: this.#keyboardChannel.signal,\n });\n this.#stack.push(this);\n\n if (options.preventInitialFocus) {\n // Tab cycling and return-focus are still set up; the imperative\n // focus move is the only thing skipped. Focus stays wherever the\n // consumer wants until they choose to enter the trap.\n return;\n }\n\n const initial = options.initialFocus ?? 'first';\n if (initial === 'first') {\n const first = findFirstFocusable(this.#container);\n if (first) {\n first.focus();\n } else {\n this.#focusContainer();\n }\n } else if (initial === 'container') {\n this.#focusContainer();\n } else {\n initial.focus();\n }\n }\n\n /**\n * Removes the keydown listener, unregisters from the stack and — unless `returnFocus: false` —\n * restores focus to the element captured on activation.\n *\n * Return focus is skipped when that element is no longer connected to the document, leaving the\n * browser's own default in place rather than dropping focus to `<body>`.\n */\n deactivate(options: FocusTrapDeactivateOptions = {}): void {\n if (!this.#active) {\n return;\n }\n this.releaseKeyboardChannel();\n this.#active = false;\n\n if (this.#containerHadTabindex === false && this.#container.getAttribute('tabindex') === '-1') {\n // We added it on activation; remove it so we don't leak.\n this.#container.removeAttribute('tabindex');\n }\n this.#containerHadTabindex = false;\n\n const returnFocus = options.returnFocus !== false;\n if (returnFocus && this.#returnTo?.isConnected) {\n this.#returnTo.focus();\n }\n this.#returnTo = null;\n }\n\n /**\n * Removes the `document` keydown listener and the {@link FocusTrapStack} entry, leaving focus,\n * {@link isActive} and the temporary container `tabindex` untouched. A no-op on an inactive trap.\n *\n * Idempotent, and safe to call before or after `deactivate()` — a later\n * `deactivate({ returnFocus: true })` still performs its focus move.\n *\n * Not a substitute for `deactivate()`: calling it on a trap still in use leaves one that reports\n * `isActive` yet cycles nothing, and whose `activate()` is a silent no-op.\n */\n releaseKeyboardChannel(): void {\n if (!this.#active) {\n return;\n }\n this.#keyboardChannel?.abort();\n this.#keyboardChannel = null;\n this.#deferredTab = null;\n this.#stack.remove(this);\n }\n\n #focusContainer(): void {\n if (!this.#containerHadTabindex && !this.#container.hasAttribute('tabindex')) {\n this.#container.setAttribute('tabindex', '-1');\n }\n this.#container.focus();\n }\n\n #handleKeyDown(event: KeyboardEvent): void {\n if (event.key !== 'Tab') {\n return;\n }\n // Only the topmost active trap handles Tab. Earlier (shadowed) traps\n // bail so a parent drawer's \"focus jumped outside\" guard does not\n // pull focus out of a nested child drawer's surface.\n if (!this.#stack.isTopmost(this)) {\n return;\n }\n const active = resolveActiveElement(this.#document);\n if (composedContains(this.#container, active)) {\n this.#cycleInside(event, active);\n return;\n }\n\n const surface = this.#independentSurfaceOf(active);\n if (surface === null) {\n this.#pullBack(event, false);\n } else if (leavesTabSequence(findTabbableEdges(surface), active, event.shiftKey)) {\n this.#deferredTab = event;\n }\n }\n\n #settleDeferredTab(event: KeyboardEvent): void {\n if (event !== this.#deferredTab) {\n return;\n }\n this.#deferredTab = null;\n const active = resolveActiveElement(this.#document);\n if (composedContains(this.#container, active)) {\n if (!event.defaultPrevented) {\n this.#cycleInside(event, active);\n }\n return;\n }\n if (event.defaultPrevented && this.#independentSurfaceOf(active) !== null) {\n return;\n }\n this.#pullBack(event, true);\n }\n\n #cycleInside(event: KeyboardEvent, active: Element | null): void {\n const backward = event.shiftKey;\n const edges = findTabbableEdges(this.#container);\n if (leavesTabSequence(edges, active, backward)) {\n event.preventDefault();\n (backward ? edges.last : edges.first)?.focus();\n }\n }\n\n #pullBack(event: KeyboardEvent, fromSurface: boolean): void {\n event.preventDefault();\n const { first, last } = findTabbableEdges(this.#container);\n const target = fromSurface && event.shiftKey ? last : first;\n if (target) {\n target.focus();\n } else {\n this.#focusContainer();\n }\n }\n\n #independentSurfaceOf(active: Element | null): HTMLElement | null {\n if (active === null) {\n return null;\n }\n const surface = composedClosest(active, INDEPENDENT_SURFACE_SELECTOR);\n return surface !== null && !composedContains(surface, this.#container) ? surface : null;\n }\n}\n\n/**\n * Reports an owner that activated a trap and was destroyed without calling `deactivate()`.\n *\n * Must be scheduled as a microtask rather than run inside the destroy hook: `onDestroy` callbacks\n * fire in registration order, so {@link FocusTrap.isActive} is only settled once the whole chain\n * has run.\n */\nfunction warnIfNeverDeactivated(trap: FocusTrap): void {\n if (!trap.isActive) {\n return;\n }\n fortyWarn({\n code: 'FORCDK-CORE-004',\n message:\n 'A focus trap was still active when its owner was destroyed, so focus was not returned.',\n cause:\n 'The owner never called `deactivate()`. The teardown safety net released the keyboard ' +\n 'channel (the `document` keydown listener and the stack entry), but only the owner can ' +\n 'decide where focus goes.',\n fix: \"Call `trap.deactivate({ returnFocus })` from the owner's own `DestroyRef.onDestroy`.\",\n });\n}\n\n/**\n * Creates a {@link FocusTrap} for the current directive's host element.\n *\n * Activation and teardown are the caller's responsibility: call `trap.activate()` when the surface\n * opens and `trap.deactivate({ returnFocus })` from a `DestroyRef.onDestroy` when it closes.\n *\n * On injector destroy the helper releases the keyboard channel unconditionally, so a trap whose\n * owner skipped `deactivate()` cannot keep intercepting Tab. It never moves focus — only the owner\n * can decide where focus goes — and warns in dev mode when it finds that repair necessary.\n *\n * SSR-safe: off-browser the trap registers no listener and `activate()` is a no-op.\n */\nexport function injectFocusTrap(): FocusTrap {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const trap = new FocusTrap(\n host.nativeElement,\n inject(FocusTrapStack),\n inject(DOCUMENT),\n isPlatformBrowser(inject(PLATFORM_ID)),\n );\n inject(DestroyRef).onDestroy(() => {\n const wasActive = trap.isActive;\n trap.releaseKeyboardChannel();\n if ((typeof ngDevMode === 'undefined' || ngDevMode) && wasActive) {\n queueMicrotask(() => warnIfNeverDeactivated(trap));\n }\n });\n return trap;\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n DestroyRef,\n ElementRef,\n PLATFORM_ID,\n afterNextRender,\n inject,\n signal,\n type Signal,\n} from '@angular/core';\n\nimport {\n FOCUSABILITY_ATTRIBUTES,\n isFocusableCandidate,\n queryFocusableCandidates,\n} from './focusable-candidate';\n\n/**\n * Reports whether the host element currently has at least one focusable\n * descendant, reactive to subtree mutations.\n *\n * Backs the WAI-ARIA Tabs rule that a `tabpanel` is itself a tab stop only when it has no focusable\n * content of its own.\n *\n * Candidates are filtered through the same predicate `FocusTrap` uses, so `[hidden]`, disabled,\n * `[inert]` and unrendered elements (CSS-hidden, or inside a closed `<details>`) do not count, and\n * content inside an open shadow root does.\n *\n * A `MutationObserver` on the host's subtree re-measures on childList and attribute changes. Two\n * boundaries follow from it: the observer cannot see into a shadow root, and its `attributeFilter`\n * excludes `class` and `style`, so a visibility flip driven purely by a stylesheet keeps the\n * previously measured answer.\n *\n * SSR-safe: off-browser no observer is created and the signal stays `false`.\n *\n * Must be called from an injection context.\n */\nexport function injectHasFocusableContent(): Signal<boolean> {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n const destroyRef = inject(DestroyRef);\n\n const has = signal(false);\n\n if (!isBrowser) {\n return has.asReadonly();\n }\n\n const measure = (): void => has.set(hasFocusableDescendant(host));\n\n const win = host.ownerDocument.defaultView;\n if (win && typeof win.MutationObserver === 'function') {\n const observer = new win.MutationObserver(() => measure());\n observer.observe(host, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: [...FOCUSABILITY_ATTRIBUTES],\n });\n destroyRef.onDestroy(() => observer.disconnect());\n }\n\n afterNextRender(measure);\n\n return has.asReadonly();\n}\n\nfunction hasFocusableDescendant(host: HTMLElement): boolean {\n const candidates = queryFocusableCandidates(host);\n for (const el of candidates) {\n if (isFocusableCandidate(el, host)) {\n return true;\n }\n }\n return false;\n}\n","import { Injectable } from '@angular/core';\n\nimport { composedParentElement } from '../composed-tree/composed-tree';\n\n@Injectable({ providedIn: 'root' })\nexport class ReturnFocusResolver {\n readonly #fallbacks = new WeakMap<Element, () => HTMLElement | null>();\n\n recordRemoval(removed: Element, fallback: () => HTMLElement | null): void {\n this.#fallbacks.set(removed, fallback);\n }\n\n resolve(...candidates: readonly (HTMLElement | null)[]): HTMLElement | null {\n const present = candidates.filter((candidate): candidate is HTMLElement => candidate !== null);\n const connected = present.find((candidate) => candidate.isConnected);\n if (connected !== undefined) {\n return connected;\n }\n for (const candidate of present) {\n const fallback = this.#fallbackFor(candidate);\n if (fallback?.isConnected) {\n return fallback;\n }\n }\n return null;\n }\n\n #fallbackFor(target: HTMLElement): HTMLElement | null {\n for (let node: Element | null = target; node !== null; node = composedParentElement(node)) {\n const fallback = this.#fallbacks.get(node);\n if (fallback !== undefined) {\n return fallback();\n }\n }\n return null;\n }\n}\n","import {\n booleanAttribute,\n computed,\n Directive,\n effect,\n ElementRef,\n inject,\n input,\n model,\n output,\n} from '@angular/core';\n\nimport { FOR_FIELDSET_CONTEXT } from '../field/fieldset-context';\nimport { type FieldValidationError, injectFieldWiring } from '../field/field-wiring';\n\n/**\n * Abstract base for primitives that implement `FormValueControl<T>` or\n * `FormCheckboxControl` from `@angular/forms/signals`. Owns the universal\n * `disabled` / `readonly` / `required` / `invalid` / `pending` / `dirty` /\n * `name` / `errors` inputs plus the `touched` model and `touch` output so each\n * form-control primitive doesn't redeclare them.\n *\n * Subclasses keep ownership of their value signal — `value: model<T>()` for\n * `FormValueControl<T>` or `checked: model<boolean>()` for\n * `FormCheckboxControl` — and any control-shape-specific members\n * (`min` / `max` / `pattern`, `multiple`, `orientation`, etc.).\n *\n * The base constructor reflects the four form-state booleans (`touched` /\n * `dirty` / `pending` / `invalid`) as boolean `data-*` attributes on each\n * subclass's host element automatically — subclasses don't need to opt in.\n * Imperative `toggleAttribute` writes (present with empty string when truthy,\n * absent otherwise) keep the subclass's declarative `host: { ... }` block free\n * of these attributes; no conflict because they aren't bound elsewhere.\n *\n * Implemented as an `@Directive()`-decorated abstract class because Angular\n * recognises signal inputs only when `input()` / `model()` calls appear\n * directly in a class-field initializer; a factory function returning the\n * bundle would not be detected by the compiler. Inheritance is the\n * supported mechanism for sharing initializer-API declarations across\n * directives.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\n@Directive()\nexport abstract class FormUiControlBase {\n /**\n * Consumer/Signal-Forms `disabled` input. Subclasses gate behavior and reflect\n * ARIA/`data-*` off {@link effectiveDisabled}, not this raw input, so a\n * surrounding disabled `[forFieldset]` also disables the control. Bind to this\n * via `[disabled]` or `[formField]`; read {@link effectiveDisabled} for state.\n */\n readonly disabled = input(false, { transform: booleanAttribute });\n\n /**\n * When true, interaction is ignored but the control stays focusable. Reflected\n * as `data-readonly`, plus `aria-readonly=\"true\"` where the control's role\n * supports it; a `role=\"group\"` or `role=\"button\"` host carries `data-readonly`\n * alone.\n */\n readonly readonly = input(false, { transform: booleanAttribute });\n\n /**\n * Marks the control required. A control hosted on a native `<input>` or\n * `<textarea>` reflects it as the native `required` attribute, a custom-role\n * control as `aria-required=\"true\"` where its role supports it, and a\n * `role=\"group\"` or `role=\"button\"` host as `data-required`.\n */\n readonly required = input(false, { transform: booleanAttribute });\n\n /** Reflected as `aria-invalid=\"true\"` and `data-invalid` when truthy. */\n readonly invalid = input(false, { transform: booleanAttribute });\n\n /** Reflected as `aria-busy=\"true\"` and `data-pending` when truthy. */\n readonly pending = input(false, { transform: booleanAttribute });\n\n /** Reflected as `data-dirty` when truthy. */\n readonly dirty = input(false, { transform: booleanAttribute });\n\n /** When non-empty, hidden inputs are mounted under that name for native form submission. */\n readonly name = input<string>('');\n\n /** Validation errors surfaced by Signal Forms. */\n readonly errors = input<readonly FieldValidationError[]>([]);\n\n /**\n * Set to true on the first touch-producing interaction (see {@link touch}).\n * Two-way bindable for standalone consumers; under `[formField]` the directive pushes the field's\n * touched state down through this input, so the form stays the source of\n * truth (e.g. a form reset clears it).\n */\n readonly touched = model<boolean>(false);\n\n /**\n * Emitted on every touch-producing interaction — including repeats once the\n * control is already touched. Those are: focus leaving the control (a move\n * between its own parts, such as a picker's field and trigger, is not a\n * leave), an activation or selection commit, and a dismissal by an outside\n * press or outside focus. Escape is not one: it leaves focus in the control.\n * The {@link touched} model itself only changes on the first, and Signal\n * Forms' `markAsTouched()` is idempotent, so re-emission is safe. No control\n * once-guards this. `[formField]` listens to this output to mark the field\n * touched — since Signal Forms v22 the `touched` input is write-only from the\n * form's perspective and never read back.\n */\n readonly touch = output<void>();\n\n /**\n * Moves focus into the control, mirroring the optional `FormUiControl.focus`\n * from `@angular/forms/signals`. Declared here without an implementation —\n * the base has no idea where a subclass's focus entry point is — so that a\n * surrounding `[forField]` can be handed the subclass's own `focus()` for\n * label-click activation whenever one exists. A subclass whose host is\n * itself focusable declares nothing and the field focuses that host.\n *\n * A subclass must declare this as a **method**, not an arrow-valued field:\n * the base reads it during `super()`, before subclass fields initialize.\n */\n focus?(options?: FocusOptions): void;\n\n /**\n * Returns the control to its pristine state, mirroring the optional\n * `FormUiControl.reset` that Signal Forms calls on a form reset. Declared\n * without an implementation: only a control that can hold a draft its value\n * cannot represent, such as a partly typed date, has anything to discard.\n */\n reset?(): void;\n\n /**\n * Whether a composite around this control currently stands in for it with a\n * surrounding `[forField]` — a field-anatomy picker adopting its segmented\n * field. While it returns `true` the field neither resolves nor wires this\n * control. Declared without an implementation so only a control that can be\n * adopted pays for the extra reactive read.\n *\n * A subclass must declare this as a **method**, for the same reason as\n * {@link focus}. It is read lazily, so it may reference the subclass's own\n * fields.\n */\n protected fieldAdopted?(): boolean;\n\n /**\n * Whether a composite this control is projected into, and defers to, is\n * disabled — a date picker around the time source it composes. Folded into\n * {@link effectiveDisabled}. Declared without an implementation so only a\n * control that can be projected that way pays for the extra reactive read.\n *\n * A subclass must declare this as a **method**, for the same reason as\n * {@link focus}. It is read lazily, so it may reference the subclass's own\n * fields.\n */\n protected inheritedDisabled?(): boolean;\n\n readonly #fieldset = inject(FOR_FIELDSET_CONTEXT, { optional: true });\n\n /**\n * The control's own {@link disabled} OR'd with a surrounding disabled\n * `[forFieldset]` and with a disabled composite it defers to. This is the\n * value that gates interaction and drives `aria-disabled` / `data-disabled` —\n * a native `<fieldset disabled>` does not reach custom-role controls\n * (`forSwitch`, `forCheckbox`, …), so the group's disabled state must compose\n * in here. Subclasses read this, never the raw {@link disabled} input.\n */\n readonly effectiveDisabled = computed(\n () =>\n this.disabled() ||\n (this.#fieldset?.disabled() ?? false) ||\n (this.inheritedDisabled?.() ?? false),\n );\n\n readonly #hostEl = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n\n /**\n * The focusable element a surrounding `[forField]` should target for\n * `aria-*` association and focus. Defaults to the directive host — correct\n * when the host IS the control (Listbox, native `<input>`). Override when the\n * host is a non-interactive wrapper and the real control is a child (the\n * Select trigger button / the Combobox `role=\"combobox\"` input), returning\n * that element — or `null` while it hasn't registered yet, in which case the\n * field defers wiring rather than targeting the wrapper.\n *\n * Read lazily inside the field-wiring effect, so a subclass override may\n * reference its own signals (initialized after this base `super()` runs).\n */\n protected fieldLabelledElement(): HTMLElement | null {\n return this.#hostEl;\n }\n\n /**\n * The id already host-bound on {@link fieldLabelledElement} when a subclass\n * nominates a child control (e.g. the Select trigger's `triggerId`). The\n * field adopts it as its `controlId` so the label's `for` and the primitive's\n * internal `aria-labelledby` point at the same element. `null` (the default,\n * and the host-is-the-control case) falls back to the field's owned id.\n */\n protected fieldLabelledElementId(): string | null {\n return null;\n }\n\n protected fieldActivationTarget(): HTMLElement | null {\n return null;\n }\n\n /**\n * Marks the control touched: flips the {@link touched} model (standalone\n * reflection) and emits {@link touch} (Signal Forms integration). Subclasses\n * call this from every touch-producing interaction instead of writing\n * `touched` directly, so both channels always fire together.\n * Never once-guard this in a subclass: the emission cadence is part of the\n * uniform form-control contract.\n */\n protected markTouched(): void {\n this.touched.set(true);\n this.touch.emit();\n }\n\n /**\n * The element the four form-state `data-*` booleans (`data-touched` /\n * `data-dirty` / `data-pending` / `data-invalid`) are reflected onto. Defaults\n * to the directive host — correct when the host carries the control's styling\n * surface. Override (returning `null` until it exists) when the reflected\n * element is a child the directive injects, e.g. `ForOtpInput`'s real\n * `<input>` rather than its `role=\"group\"` host. Read reactively inside the\n * reflection effect, so a returned signal re-targets once the element appears.\n */\n protected fieldStateReflectionTarget(): HTMLElement | null {\n return this.#hostEl;\n }\n\n /**\n * The control's effective invalidity — reflected as `data-invalid` and fed to\n * a surrounding `[forField]` (which gates its error region and folds the error\n * id into `aria-describedby`). Defaults to the raw {@link invalid} input.\n * Override to fold in invalidity the form itself can't express (e.g.\n * `ForDateRangeField` / `ForTimeRangeField` treating an out-of-order range as\n * invalid) so `aria-invalid`, `data-invalid`, and the field wiring stay\n * consistent. Read reactively inside the reflection and field-wiring effects,\n * so an override may reference its own signals (initialized after this base\n * `super()` runs).\n */\n protected effectiveInvalid(): boolean {\n return this.invalid();\n }\n\n constructor() {\n effect(() => {\n const target = this.fieldStateReflectionTarget();\n if (!target) {\n return;\n }\n target.toggleAttribute('data-touched', this.touched());\n target.toggleAttribute('data-dirty', this.dirty());\n target.toggleAttribute('data-pending', this.pending());\n target.toggleAttribute('data-invalid', this.effectiveInvalid());\n });\n const fieldAdopted = this.fieldAdopted?.bind(this);\n injectFieldWiring({\n adopted: fieldAdopted ? computed(fieldAdopted) : undefined,\n invalid: computed(() => this.effectiveInvalid()),\n required: this.required,\n disabled: this.effectiveDisabled,\n touched: this.touched,\n errors: this.errors,\n labelledElement: computed(() => this.fieldLabelledElement()),\n labelledElementId: computed(() => this.fieldLabelledElementId() ?? undefined),\n activationTarget: computed(() => this.fieldActivationTarget()),\n focus: this.focus?.bind(this),\n });\n }\n}\n","import {\n Directive,\n ElementRef,\n booleanAttribute,\n computed,\n inject,\n input,\n signal,\n} from '@angular/core';\n\n/**\n * The \"visually hidden\" clip rectangle: an inline style declaration that\n * removes an element from the visual layout while keeping it in the\n * accessibility tree (unlike `display:none` / `visibility:hidden`, which both\n * also drop it from the a11y tree). Shared by {@link ForVisuallyHidden} and the\n * `LiveAnnouncer` so the clip CSS is defined in exactly one place.\n *\n * Internal tier, and not exported from the core\n * barrel: the published surface for this capability is {@link ForVisuallyHidden}\n * (blessed, shipped from `forty-cdk/visually-hidden`), which applies the clip\n * for the consumer. A raw style string covers no use case the directive does\n * not.\n */\nexport const VISUALLY_HIDDEN_STYLE =\n 'position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border:0;';\n\n/**\n * Visually hides its host while leaving it in the accessibility tree, applying\n * the clip rectangle inline (no global stylesheet). Use it for hidden labels,\n * descriptions, and live-region content that screen readers must reach but\n * sighted users should not see.\n *\n * With `focusable`, the host is revealed whenever it — or any descendant —\n * holds focus, then clips itself again on blur. This is the skip-link pattern:\n * a control that is invisible until a keyboard user tabs to it. Focus is\n * tracked through `focusin` / `focusout` rather than a `:focus-within` CSS\n * rule, because the clip is applied inline and an inline style cannot express a\n * pseudo-class.\n *\n * Part of the blessed core tier: consumers import it from the\n * `forty-cdk/visually-hidden` entry point, which carries the library's semver\n * guarantee.\n */\n@Directive({\n selector: '[forVisuallyHidden]',\n exportAs: 'forVisuallyHidden',\n host: {\n '[style]': 'styles()',\n '(focusin)': 'onFocusIn()',\n '(focusout)': 'onFocusOut($event)',\n },\n})\nexport class ForVisuallyHidden {\n readonly #host = inject<ElementRef<HTMLElement>>(ElementRef);\n\n /**\n * When `true`, the host un-clips while it (or a descendant) holds focus and\n * re-clips on blur — the skip-link \"visible on focus\" behavior. Defaults to\n * `false`, which keeps the host hidden at all times.\n */\n readonly focusable = input(false, { transform: booleanAttribute });\n\n readonly #focused = signal(false);\n\n private readonly styles = computed(() =>\n this.focusable() && this.#focused() ? null : VISUALLY_HIDDEN_STYLE,\n );\n\n private onFocusIn(): void {\n this.#focused.set(true);\n }\n\n private onFocusOut(event: FocusEvent): void {\n const next = event.relatedTarget as Node | null;\n if (next && this.#host.nativeElement.contains(next)) {\n return;\n }\n this.#focused.set(false);\n }\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n DOCUMENT,\n DestroyRef,\n effect,\n ElementRef,\n inject,\n PLATFORM_ID,\n type Signal,\n} from '@angular/core';\n\nimport { VISUALLY_HIDDEN_STYLE } from '../visually-hidden/visually-hidden';\n\n/**\n * The visually hidden clip with `position:fixed`, so the validation input never\n * extends the scrollable overflow of the document or of an unpositioned\n * scroller it sits in.\n */\nconst VALIDATION_INPUT_STYLE = `${VISUALLY_HIDDEN_STYLE}position:fixed;`;\n\nexport interface HiddenInputConfig<T = string> {\n /**\n * Form name. While empty, no hidden inputs are mounted — set a non-empty\n * `name` (typically via `[name]` on the host primitive) to opt in.\n */\n name: Signal<string>;\n\n /**\n * Reactive list of values to mirror. Each entry becomes a separate\n * `<input type=\"hidden\" name=\"…\" value=\"…\">`. Use:\n * - `['on']` (checked) / `[]` (unchecked) for boolean controls.\n * - `[value]` (selected) / `[]` (none) for single-value controls.\n * - the array as-is for multi-value controls.\n */\n values: Signal<readonly T[]>;\n\n /**\n * How to serialize each entry to a string for the hidden input's `value`\n * attribute. Defaults to `String(item)`, which is identity for strings.\n * Object-valued primitives (e.g. generic `[forCombobox]`) pass a custom\n * function — typically a consumer-provided `itemToFormValue` — so the\n * wire format is explicit (per-item id, per-item JSON, …).\n */\n serialize?: (item: T) => string;\n\n /**\n * Optional disabled mirror. Disabled hidden inputs are skipped by native\n * form serialization, matching the behavior of disabled visible controls.\n */\n disabled?: Signal<boolean>;\n\n /**\n * Optional required state. While it is `true` and `values` is empty, the\n * surrounding `<form>` fails native constraint validation: submission is\n * blocked and `form:invalid` matches, as for a native `<select required>`.\n * Independent of `name`. A disabled control never blocks.\n */\n required?: Signal<boolean>;\n\n /**\n * Moves focus into the control when the browser reports it invalid.\n * Defaults to focusing the host element.\n */\n focus?: () => void;\n}\n\n/**\n * Mirrors a headless form control's value into native\n * `<input type=\"hidden\">` siblings so the surrounding `<form>` picks it up\n * during native submission. Multiple values produce multiple inputs (used\n * by multi-select primitives like the listbox).\n *\n * Inputs are inserted right after the directive's host element so they\n * live inside whatever `<form>` the host lives in. Lifecycle is wired to\n * `DestroyRef`: the inputs are removed when the directive is destroyed.\n *\n * Browser-only: on the server this is a no-op — no `<input>` is created or\n * serialized. The hidden inputs are **client-only** siblings: they are net-new\n * nodes the server never rendered, so they are not part of the hydrated tree\n * and a full (non-incremental) hydration sees the same server markup (the host\n * primitive alone) with no mismatch and no duplicated / double-submitted field.\n *\n * Caveat: the initial mount runs inside the directive's first `effect()` pass,\n * which can fire before hydration finishes settling under incremental\n * hydration. That is harmless today because the inputs are always net-new\n * (never claimed from the server DOM), but it means the \"after hydration\"\n * guarantee is \"not part of the hydrated tree\", not \"strictly sequenced after\n * the hydration pass\". If incremental hydration ever needs the stricter\n * ordering, move the initial mount into `afterNextRender`.\n *\n * A hidden input is barred from constraint validation, so a `required` control\n * also gets one validation input: a visually hidden, fixed-positioned, unnamed\n * `<input required tabindex=\"-1\" aria-hidden=\"true\">` mounted after the host,\n * filled while `values` is non-empty. Being fixed, it never makes the document\n * or a scroll container taller, whatever the host's ancestors are. It submits nothing, and focusing it, which\n * the browser does when it reports the form, moves focus into the control.\n *\n * Returns a function that writes the current values into the hidden inputs\n * immediately. A control whose value changes in the same event that submits\n * the form calls it, so the submission carries the new value rather than the\n * one the next render would have written. It is a no-op on the server.\n */\nexport function injectHiddenInput<T = string>(config: HiddenInputConfig<T>): () => void {\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n return () => undefined;\n }\n\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const doc = inject(DOCUMENT);\n const inputs: HTMLInputElement[] = [];\n let validation: HTMLInputElement | null = null;\n let destroyed = false;\n\n const focusControl = (): void => {\n if (config.focus) {\n config.focus();\n } else {\n host.nativeElement.focus();\n }\n };\n\n const syncValidation = (disabled: boolean): void => {\n if (!(config.required?.() ?? false)) {\n validation?.remove();\n validation = null;\n return;\n }\n if (validation === null) {\n validation = doc.createElement('input');\n validation.required = true;\n validation.tabIndex = -1;\n validation.autocomplete = 'off';\n validation.setAttribute('aria-hidden', 'true');\n validation.setAttribute('style', VALIDATION_INPUT_STYLE);\n validation.addEventListener('focus', focusControl);\n host.nativeElement.insertAdjacentElement('afterend', validation);\n }\n const filled = config.values().length > 0 ? 'on' : '';\n if (validation.defaultValue !== filled) {\n validation.defaultValue = filled;\n }\n if (validation.value !== filled) {\n validation.value = filled;\n }\n validation.toggleAttribute('disabled', disabled);\n };\n\n const sync = (): void => {\n if (destroyed) {\n return;\n }\n const name = config.name();\n const values = name ? config.values() : ([] as readonly T[]);\n const disabled = config.disabled?.() ?? false;\n const serialize = config.serialize;\n syncValidation(disabled);\n\n while (inputs.length > values.length) {\n inputs.pop()?.remove();\n }\n while (inputs.length < values.length) {\n const input = doc.createElement('input');\n input.type = 'hidden';\n const anchor = inputs.length === 0 ? host.nativeElement : inputs[inputs.length - 1]!;\n anchor.insertAdjacentElement('afterend', input);\n inputs.push(input);\n }\n\n for (let i = 0; i < values.length; i++) {\n const input = inputs[i]!;\n if (input.name !== name) {\n input.name = name;\n }\n const item = values[i] as T;\n let next: string;\n if (serialize) {\n next = serialize(item);\n } else if (item == null) {\n next = '';\n } else {\n next = String(item);\n }\n if (input.value !== next) {\n input.value = next;\n }\n input.toggleAttribute('disabled', disabled);\n }\n };\n\n effect(sync);\n\n inject(DestroyRef).onDestroy(() => {\n destroyed = true;\n for (const input of inputs) {\n input.remove();\n }\n inputs.length = 0;\n validation?.remove();\n validation = null;\n });\n\n return sync;\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n afterNextRender,\n DestroyRef,\n effect,\n ElementRef,\n inject,\n Injector,\n PLATFORM_ID,\n untracked,\n type WritableSignal,\n} from '@angular/core';\n\ntype ValueElement = HTMLInputElement | HTMLTextAreaElement;\n\nfunction listenForFormReset(\n element: Element,\n form: () => HTMLFormElement | null,\n onReset: () => void,\n): () => void {\n const root = element.getRootNode();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const listener = (event: Event): void => {\n const owner = form();\n if (owner === null || event.target !== owner) {\n return;\n }\n clearTimeout(timer);\n timer = setTimeout(() => {\n timer = undefined;\n if (!event.defaultPrevented) {\n onReset();\n }\n }, 0);\n };\n root.addEventListener('reset', listener);\n return () => {\n root.removeEventListener('reset', listener);\n clearTimeout(timer);\n };\n}\n\nexport function injectNativeFormReset(\n el: () => ValueElement | null,\n onReset?: (text: string) => void,\n): void {\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n return;\n }\n const injector = inject(Injector);\n effect((onCleanup) => {\n const element = el();\n if (!element) {\n return;\n }\n let baseline: string | null = null;\n const ref = untracked(() =>\n afterNextRender(\n () => {\n baseline = element.value;\n },\n { injector },\n ),\n );\n const stop = listenForFormReset(\n element,\n () => element.form,\n () => {\n const text = baseline ?? element.value;\n if (element.value !== text) {\n element.value = text;\n }\n onReset?.(text);\n },\n );\n onCleanup(() => {\n ref.destroy();\n stop();\n });\n });\n}\n\nexport function injectNativeFormResetToInitial<T>(\n model: WritableSignal<T>,\n onReset?: () => void,\n): void {\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n return;\n }\n const host = inject<ElementRef<Element>>(ElementRef).nativeElement;\n let stop: (() => void) | undefined;\n afterNextRender(() => {\n const initial = model();\n stop = listenForFormReset(\n host,\n () => host.closest('form'),\n () => {\n model.set(initial);\n onReset?.();\n },\n );\n });\n inject(DestroyRef).onDestroy(() => stop?.());\n}\n","import { effect, ElementRef, inject, type Signal } from '@angular/core';\n\n/**\n * Non-destructively reflects a `disabled` signal onto the host element's native\n * `disabled` attribute.\n *\n * The naive host binding `'[attr.disabled]': 'disabled() ? \"\" : null'` is\n * destructive: its `null` branch removes the attribute on the first change\n * detection whenever the expression is falsy, clobbering a `disabled` attribute\n * the consumer set themselves (a static `disabled` in the template, or an\n * imperative `setAttribute('disabled', '')`) even though the primitive never\n * owned it. For a host whose disabled expression has no same-element `disabled`\n * input to seed, that markup silently disappears.\n *\n * This helper tracks ownership instead: it sets the attribute only when absent, and on the falsy\n * edge removes it only when it was the one that set it. A consumer-set `disabled` therefore\n * survives an enabled state, while a primitive-set one is cleaned up on re-enable.\n *\n * Must be called from an injection context.\n *\n * **Not the right tool for every clobber-capable host.** Two kinds of control reflect\n * `aria-disabled` + `data-disabled` with an in-handler activation guard instead: one carrying a\n * custom ARIA role, because the native attribute would drop it from the focus order where the APG\n * requires a disabled control to stay focusable; and one whose disabled state the primitive\n * auto-computes from its own position and can flip while the button holds focus, because the\n * attribute would eject focus to `<body>` at the moment the user reaches the bound. Native\n * `disabled` is correct only on genuine form elements and on single-purpose `<button>` triggers\n * whose disabled state the consumer drives through an input.\n *\n * **The two channels are mutually exclusive**: a host calling this helper must not also host-bind\n * `[attr.aria-disabled]` for the same state, since the native attribute already exposes it through\n * HTML-AAM and a second channel leaves consumers two selectors for one condition. `data-disabled`\n * stays as the styling hook. The exclusion is per state rather than per attribute — a host whose\n * `aria-disabled` encodes a *different* condition may keep it, provided it can never be `\"true\"`\n * while this helper owns the native attribute. `forty-cdk/no-doubled-disabled-reflection` enforces\n * the declarative form.\n *\n * @param disabled Signal whose truthiness drives the native `disabled`\n * attribute on the host element.\n */\nexport function reflectDisabled(disabled: Signal<boolean>): void {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n let owned = false;\n effect(() => {\n if (disabled()) {\n if (!host.hasAttribute('disabled')) {\n host.setAttribute('disabled', '');\n owned = true;\n }\n } else if (owned) {\n host.removeAttribute('disabled');\n owned = false;\n }\n });\n}\n","import { effect, ElementRef, inject, type Signal } from '@angular/core';\n\nexport function reflectRequired(\n required: Signal<boolean>,\n target?: () => HTMLElement | null,\n): void {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const resolve = target ?? (() => host);\n let owner: HTMLElement | null = null;\n effect(() => {\n const el = resolve();\n if (owner !== null && owner !== el) {\n owner.removeAttribute('required');\n owner = null;\n }\n if (!el) {\n return;\n }\n if (required()) {\n if (!el.hasAttribute('required')) {\n el.setAttribute('required', '');\n owner = el;\n }\n } else if (owner === el) {\n el.removeAttribute('required');\n owner = null;\n }\n });\n}\n","import { DOCUMENT, effect, inject } from '@angular/core';\n\nimport { resolveActiveElement } from '../composed-tree/composed-tree';\n\ntype ValueElement = HTMLInputElement | HTMLTextAreaElement;\n\n/**\n * Mirrors a value string onto a native `<input>` / `<textarea>`'s `.value`\n * whenever the two differ, focused or not, except while an IME composition is\n * in progress. It is for controls whose displayed text is the text being typed\n * (`ForInput`, `ForTextarea`, `ForOtpInput`'s clamped code): typing already\n * lands in the model, so the only writes this ever makes come from elsewhere —\n * a consumer clearing the field on submit, a `[formField]` reset, a reformat in\n * `(valueChange)` — and each one must reach the element before the next\n * keystroke reads the old text back.\n *\n * The `el` accessor returns `null` until the element exists (`ForOtpInput`\n * injects its real `<input>` after hydration); a `null` target is skipped and\n * the effect re-runs once the element appears, since it is read reactively.\n *\n * Must be called from an injection context. Internal core tier — exported from\n * `forty-cdk/core` for the library's own entry points, with no semver guarantee.\n *\n * @param el Accessor for the target element, or `null` until it exists.\n * @param value Accessor for the desired displayed text.\n * @param composing Whether an IME composition is in progress on the element.\n */\nexport function mirrorValue(\n el: () => ValueElement | null,\n value: () => string,\n composing: () => boolean,\n): void {\n effect(() => {\n const element = el();\n if (!element) {\n return;\n }\n const next = value();\n if (element.value !== next && !composing()) {\n element.value = next;\n }\n });\n}\n\nexport function mirrorExternalValue<T>(\n el: () => ValueElement,\n value: () => T,\n text: () => string,\n): (own: T) => void {\n const document = inject(DOCUMENT);\n let claimed: { readonly value: T } | null = null;\n effect(() => {\n const element = el();\n const current = value();\n const next = text();\n if (\n claimed !== null &&\n Object.is(claimed.value, current) &&\n resolveActiveElement(document) === element\n ) {\n return;\n }\n claimed = null;\n if (element.value !== next) {\n element.value = next;\n }\n });\n return (own) => {\n claimed = { value: own };\n };\n}\n","import { Directive, ElementRef, inject, model } from '@angular/core';\n\nimport { reflectDisabled } from '../host-attributes/disabled-reflection';\nimport { reflectRequired } from '../host-attributes/required-reflection';\nimport { FormUiControlBase } from './form-ui-control-base';\nimport { injectNativeFormReset } from './native-form-reset';\nimport { mirrorValue } from './value-mirror';\n\n/**\n * Shared base for the text-valued form controls `ForInput` and `ForTextarea`.\n * Owns the `value` model and the bridge between the native element's editing\n * (the `input` event) and that signal, layered on the universal form-control\n * inputs inherited from `FormUiControlBase`.\n *\n * The native `<input>` / `<textarea>` is itself the submittable element: each\n * concrete directive reflects `[attr.name]` on its host, so the browser\n * serializes the field natively. No hidden input is injected — one would\n * double-submit alongside the real control. This mirrors the OTP-input design\n * and diverges from `ForNumberInput`, whose displayed (formatted)\n * text differs from its submitted value.\n *\n * Implemented as an `@Directive()`-decorated abstract class so Angular detects\n * the inherited `value` model — the same mechanism `FormUiControlBase` relies\n * on. Internal core tier — no semver guarantee.\n */\n@Directive()\nexport abstract class TextValueControlBase extends FormUiControlBase {\n /**\n * Two-way bindable text value. Required by `FormValueControl<string>`.\n * Defaults to `''` — a text field is naturally empty, not absent, which\n * keeps the type non-nullable. Reflected as `data-empty` while `''`.\n */\n readonly value = model<string>('');\n\n readonly #host = inject<ElementRef<HTMLInputElement | HTMLTextAreaElement>>(ElementRef);\n\n #composing = false;\n\n constructor() {\n super();\n\n // Reflect the native `disabled` attribute non-destructively so a\n // consumer-set `disabled` on the same element survives an enabled state.\n reflectDisabled(this.effectiveDisabled);\n reflectRequired(this.required);\n\n mirrorValue(\n () => this.#host.nativeElement,\n this.value,\n () => this.#composing,\n );\n\n injectNativeFormReset(\n () => this.#host.nativeElement,\n (text) => this.value.set(text),\n );\n }\n\n /** Bridges the native `input` event into the `value` model. */\n protected onInput(event: Event): void {\n if (this.effectiveDisabled() || this.readonly()) {\n return;\n }\n // Suppress the intermediate text an IME emits between `compositionstart`\n // and `compositionend`; the final composed string is flushed once on\n // `compositionend`. Mirrors the OTP / Combobox guard so all three text\n // controls behave identically.\n if (this.#composing) {\n return;\n }\n this.value.set((event.target as HTMLInputElement | HTMLTextAreaElement).value);\n }\n\n /** Starts an IME composition; suppresses intermediate `input` propagation. */\n private onCompositionStart(): void {\n this.#composing = true;\n }\n\n /** Ends an IME composition and flushes the final composed value once. */\n private onCompositionEnd(): void {\n this.#composing = false;\n if (this.effectiveDisabled() || this.readonly()) {\n return;\n }\n this.value.set(this.#host.nativeElement.value);\n }\n\n /**\n * Marks the control touched and re-syncs the native element to `value()`,\n * discarding any text written to the element without an `input` event.\n */\n private onBlur(): void {\n this.markTouched();\n const el = this.#host.nativeElement;\n if (el.value !== this.value()) {\n el.value = this.value();\n }\n }\n}\n","/**\n * A user-driven dismissal of a form control's open surface, named by the\n * channel that requested it.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\nexport type TouchDismissal = 'escape' | 'pointerDownOutside' | 'focusOutside';\n\n/**\n * Whether a `focusout` leaves the control. Returns `false` when the element\n * receiving focus sits inside any of `boundaries`, the elements that together\n * make up the control (its host, an open surface, a composite root around a\n * trigger and a field), and `true` otherwise, including when focus leaves the\n * document.\n *\n * Every form control that marks itself touched from a `focusout` decides it\n * here, so a focus move between the parts of one control never touches it.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\nexport function leavesControl(\n event: FocusEvent,\n boundaries: readonly (Node | null | undefined)[],\n): boolean {\n const next = event.relatedTarget as Node | null;\n if (!next) {\n return true;\n }\n return !boundaries.some((boundary) => boundary?.contains(next) ?? false);\n}\n\n/**\n * Whether a dismissal marks the control touched. An outside interaction is the\n * control's blur and touches it; Escape leaves focus in the control and blurs\n * nothing, so it does not.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\nexport function dismissMarksTouched(dismissal: TouchDismissal): boolean {\n return dismissal !== 'escape';\n}\n","/**\n * Collapse a config's `class` / `classList` into a single space-separated\n * string suitable for an Angular `[class]` binding or an `el.className`\n * assignment. De-duplicates tokens and drops empty entries so the rendered\n * `class` attribute stays clean. Returns `null` when neither field carries a\n * class.\n *\n * Shared by every imperative overlay manager (`ForToastManager`,\n * `ForDialogManager`, `ForDrawerManager`, and any future one) so the\n * `class` / `classList` config resolves identically across primitives:\n * applied to the overlay root, merged with — never clobbering — the\n * directive's own host attributes (`data-state`, `data-side`, …).\n *\n * Internal composition surface shared across forty-cdk's entry points — no\n * semver guarantees.\n */\nexport function resolveConfigClass(config: {\n class?: string;\n classList?: string | readonly string[];\n}): string | null {\n const tokens: string[] = [];\n const push = (value: string | readonly string[] | undefined): void => {\n if (typeof value === 'string') {\n tokens.push(...value.split(/\\s+/));\n } else if (Array.isArray(value)) {\n for (const entry of value) {\n tokens.push(...entry.split(/\\s+/));\n }\n }\n };\n push(config.class);\n push(config.classList);\n const unique = [...new Set(tokens.filter(Boolean))];\n return unique.length > 0 ? unique.join(' ') : null;\n}\n","import { computed, DestroyRef, effect, ElementRef, inject, type Signal } from '@angular/core';\n\nimport { fortyWarn } from '../errors/errors';\nimport { composeIds, contributeDescribedBy } from './described-by-owner';\nimport { claimReplacedAttribute } from './replaced-attribute-owner';\n\n/**\n * Writes the `aria-labelledby` a piece exposes onto its host and returns it: the host element's\n * pre-existing **static** `aria-labelledby` when present, else the library's own generated\n * fallback (a trigger / heading / label id). The host must not also bind the attribute.\n *\n * A name has one owner, so a value the consumer wrote in the template always wins over the\n * fallback. A surface with no consumer value keeps its fallback verbatim.\n *\n * Only **static** values are adopted: a `[attr.aria-labelledby]=\"expr\"` binding evaluates after\n * directive construction, so it is invisible here and still fights the library's write. This\n * mirrors the static-only boundary of `resolveHostId` / `adoptHostId`.\n *\n * Must be invoked in an injection context.\n *\n * @param fallback The library-generated value, evaluated only when the host\n * carries no static `aria-labelledby`.\n */\nexport function hostLabelledBy(fallback: () => string | null): Signal<string | null> {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const claim = claimReplacedAttribute(host, 'aria-labelledby', fallback);\n effect(() => claim.write());\n inject(DestroyRef).onDestroy(() => claim.release());\n return computed(() => claim.consumer ?? fallback());\n}\n\n/**\n * Resolves the `aria-label` a piece should expose: the host element's\n * pre-existing **static** `aria-label` when present, else the library's own\n * value (an `ariaLabel` input, a scope default, or a computed name).\n *\n * Reuses {@link hostLabelledBy}'s replace semantics. Adoption matters more here: most of these host\n * bindings resolve to `null` when the library has no name of its own, and a `null` binding calls\n * `removeAttribute`, so without it a consumer's `aria-label` is deleted and the widget is left with\n * no accessible name at all.\n *\n * A piece emitting both channels must gate its {@link hostLabelledBy} fallback on this signal\n * rather than on the raw input, since `aria-labelledby` outranks `aria-label` in ARIA and a\n * generated fallback would otherwise beat the consumer's adopted name.\n *\n * Only **static** values are adopted; see {@link hostLabelledBy} for the boundary. In dev mode a\n * consumer `[attr.aria-label]` binding that the host binding is about to remove warns\n * `FORCDK-CORE-015`, once per host.\n *\n * Must be invoked in an injection context.\n *\n * @param fallback The library's own accessible name, evaluated only when the\n * host carries no static `aria-label`.\n */\nexport function hostAriaLabel(fallback: () => string | null): Signal<string | null> {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const consumer = host.getAttribute('aria-label') || null;\n const resolved = computed(() => consumer ?? fallback());\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n return warnOnRemovedBoundLabel(host, resolved);\n }\n return resolved;\n}\n\n/**\n * Passes `resolved` through, warning once when it resolves `null` while the host carries an\n * `aria-label` the library did not write: a consumer binding the host binding is about to remove.\n */\nfunction warnOnRemovedBoundLabel(\n host: HTMLElement,\n resolved: Signal<string | null>,\n): Signal<string | null> {\n let written: string | null = null;\n let warned = false;\n return computed(() => {\n const value = resolved();\n const current = host.getAttribute('aria-label');\n if (value === null && !warned && current && current !== written) {\n warned = true;\n fortyWarn({\n code: 'FORCDK-CORE-015',\n message: `The bound \\`aria-label\\` of <${describeHost(host)}> is removed by the library's \\`aria-label\\` host binding.`,\n cause:\n 'Only a static `aria-label` attribute is adopted. An `[attr.aria-label]` binding is ' +\n 'written before the host binding, which resolves no name and removes the attribute.',\n fix: 'Bind the name through the `[ariaLabel]` input, or write a static `aria-label` attribute.',\n });\n }\n written = value;\n return value;\n });\n}\n\nfunction describeHost(host: HTMLElement): string {\n const role = host.getAttribute('role');\n return role ? `${host.localName} role=\"${role}\"` : host.localName;\n}\n\n/**\n * Writes the library's own description ids into the host's `aria-describedby`,\n * **composed** after the host's pre-existing **static** value, consumer ids\n * first, and returns that composition. The host must not also bind the\n * attribute.\n *\n * Descriptions are additive — assistive tech reads every referenced element — so unlike\n * {@link hostLabelledBy} this composes instead of replacing, and a consumer's\n * `aria-describedby=\"hint\"` keeps announcing alongside a registered description piece.\n * Ids another library piece contributes to the same element (the surrounding\n * `[forField]` of a control that is also a tooltip trigger) are kept beside these.\n *\n * Only **static** values are adopted; see {@link hostLabelledBy} for the boundary.\n *\n * Must be invoked in an injection context.\n *\n * @param fallback The library-owned description ids, composed after the\n * consumer's own.\n */\nexport function hostDescribedBy(fallback: () => string | null): Signal<string | null> {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const contribution = contributeDescribedBy(host, fallback);\n effect(() => contribution.write());\n inject(DestroyRef).onDestroy(() => contribution.release());\n return computed(() => composeIds(contribution.consumer, fallback()));\n}\n","import { computed, ElementRef, inject, type Signal } from '@angular/core';\n\nexport function hostStaticAttribute(\n name: string,\n fallback: () => string | null,\n): Signal<string | null> {\n const consumer = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement.getAttribute(name);\n return computed(() => fallback() ?? (consumer || null));\n}\n","/** The `hidden` attribute value that keeps a panel searchable by find-in-page. */\nexport const HIDDEN_UNTIL_FOUND = 'until-found';\n\n/**\n * Puts `hidden=\"until-found\"` back on `host` after the browser strips it to reveal a\n * find-in-page match the owning piece declined to open, so the panel never shows while\n * its state says closed.\n *\n * Call it from the `beforematch` listener. The browser removes the attribute only after\n * the listener returns, so the restore waits for that removal. `stillHidden` is read at\n * that point and must answer whether the panel should still be hidden, which keeps a\n * restore that lands after a later legitimate open from hiding an open panel.\n */\nexport function keepHiddenUntilFound(host: HTMLElement, stillHidden: () => boolean): void {\n if (typeof MutationObserver === 'undefined') {\n return;\n }\n const observer = new MutationObserver((records) => {\n if (!records.some((record) => record.attributeName === 'hidden')) {\n return;\n }\n observer.disconnect();\n if (stillHidden() && host.getAttribute('hidden') !== HIDDEN_UNTIL_FOUND) {\n host.setAttribute('hidden', HIDDEN_UNTIL_FOUND);\n }\n });\n observer.observe(host, { attributes: true });\n}\n","import { ElementRef, inject, signal, type Signal } from '@angular/core';\n\n/**\n * Resolves the `type` attribute a piece must emit to force `type=\"button\"`:\n * `'button'` on a native `<button>` host, `null` on any other element.\n *\n * Pieces that want submit protection host-bind it as\n * `'[attr.type]': 'buttonType()'`. A host binding always beats a consumer's\n * static template attribute, so `<button forCheckbox type=\"submit\">` still emits\n * `type=\"button\"`.\n *\n * The consumer's own `type` is therefore **not** adopted — the inverse of the\n * `hostId` / `hostAriaLabel` / `hostLabelledBy` seams. A piece that forces\n * `type=\"button\"` treats a consumer `type=\"submit\"` as an authoring error rather\n * than an override, so activating the control never submits a form.\n * `[forButton]` is the one piece that preserves the consumer's `type` (a\n * `[forButton]` on a real submit button is valid usage): it binds no `type` at\n * all and only writes `type=\"button\"` at construction on a native button that\n * has none, so a consumer binding always wins.\n *\n * The host's tag name cannot change after construction, so the returned signal is\n * constant. Must be invoked in an injection context.\n */\nexport function hostButtonType(): Signal<string | null> {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n return signal(host.tagName === 'BUTTON' ? 'button' : null).asReadonly();\n}\n","import { Injectable } from '@angular/core';\n\n/**\n * Answers whether an `Escape` pressed inside a node belongs to an overlay layered above it.\n *\n * A widget that consumes `Escape` itself (a grid cell leaving interaction mode) asks first, so a\n * dismissible layer stacked over it (a tooltip on the cell's widget) is dismissed instead. The\n * dismissible-layer stack registers the query when it is created; with no stack there is no layer,\n * and the answer is `false`. Living in `forty-cdk/core` lets an entry point ask without importing\n * the overlay machinery.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own entry points, with\n * no semver guarantee.\n */\n@Injectable({ providedIn: 'root' })\nexport class EscapeArbiter {\n #query: ((node: Node) => boolean) | null = null;\n\n /**\n * Installs the query {@link hasEscapeLayerAbove} delegates to, replacing any earlier one.\n * Returns a function that removes it again.\n */\n register(query: (node: Node) => boolean): () => void {\n this.#query = query;\n return () => {\n if (this.#query === query) {\n this.#query = null;\n }\n };\n }\n\n /**\n * Whether an active layer sits above every layer containing `node`, so the stack would hand it\n * an `Escape` pressed inside `node`.\n */\n hasEscapeLayerAbove(node: Node): boolean {\n return this.#query?.(node) ?? false;\n }\n}\n","import { Injectable, inject } from '@angular/core';\n\nimport { composedContains } from '../composed-tree/composed-tree';\nimport { IdGenerator } from '../id-generator/id-generator';\n\ninterface AppliedOwnership {\n readonly owner: HTMLElement;\n readonly added: readonly string[];\n}\n\n/**\n * Keeps the regions that must stay readable over a modal inside the accessibility subtree of the\n * topmost `aria-modal` surface.\n *\n * A region lives outside every modal and still has to reach assistive technology while one is\n * open: each `LiveAnnouncer` region, and a toast viewport exempt from the modal. A screen reader\n * that hides everything outside an `aria-modal=\"true\"` element would drop whatever is written into\n * one, so the topmost claiming surface lists every registered region in its `aria-owns`.\n *\n * Only the topmost claim owns the regions, because an element can have one owner: a stacked modal\n * takes them over and hands them back when it releases, whatever the release order. The ids the\n * registry adds are merged with the surface's own `aria-owns`, and they are the only ones it\n * removes. A region with no `id` is given one the first time it is owned, and a region inside the\n * owning surface is left out.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own entry points, with\n * no semver guarantee.\n */\n@Injectable({ providedIn: 'root' })\nexport class ModalOwnedRegions {\n readonly #ids = inject(IdGenerator);\n readonly #regions: HTMLElement[] = [];\n readonly #claims: HTMLElement[] = [];\n #applied: AppliedOwnership | null = null;\n\n /** Adds `region` to what the topmost claiming surface owns. Returns the matching removal. */\n register(region: HTMLElement): () => void {\n return this.#track(this.#regions, region);\n }\n\n /** Makes `surface` the topmost owner of every registered region. Returns the matching release. */\n claim(surface: HTMLElement): () => void {\n return this.#track(this.#claims, surface);\n }\n\n #track(list: HTMLElement[], el: HTMLElement): () => void {\n list.push(el);\n this.#sync();\n let active = true;\n return () => {\n if (!active) {\n return;\n }\n active = false;\n list.splice(list.indexOf(el), 1);\n this.#sync();\n };\n }\n\n #sync(): void {\n if (this.#applied !== null) {\n removeOwnedIds(this.#applied.owner, this.#applied.added);\n this.#applied = null;\n }\n const owner = this.#claims.at(-1);\n if (owner === undefined) {\n return;\n }\n const ids = this.#regions\n .filter((region) => !composedContains(owner, region))\n .map((region) => this.#idOf(region));\n const added = addOwnedIds(owner, ids);\n if (added.length > 0) {\n this.#applied = { owner, added };\n }\n }\n\n #idOf(region: HTMLElement): string {\n if (region.id === '') {\n region.id = this.#ids.next('for-modal-owned');\n }\n return region.id;\n }\n}\n\nfunction ownedIds(el: HTMLElement): string[] {\n return (el.getAttribute('aria-owns') ?? '').split(/\\s+/).filter((id) => id !== '');\n}\n\nfunction addOwnedIds(el: HTMLElement, ids: readonly string[]): string[] {\n const current = ownedIds(el);\n const added = [...new Set(ids)].filter((id) => !current.includes(id));\n if (added.length > 0) {\n el.setAttribute('aria-owns', [...current, ...added].join(' '));\n }\n return added;\n}\n\nfunction removeOwnedIds(el: HTMLElement, ids: readonly string[]): void {\n const remaining = ownedIds(el).filter((id) => !ids.includes(id));\n if (remaining.length > 0) {\n el.setAttribute('aria-owns', remaining.join(' '));\n } else {\n el.removeAttribute('aria-owns');\n }\n}\n","import { DOCUMENT, DestroyRef, Injectable, PLATFORM_ID, inject } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\nimport { MODAL_EXEMPT_ATTRIBUTE } from '../host-attributes/modal-attributes';\nimport { ModalOwnedRegions } from '../modal-owned-regions/modal-owned-regions';\nimport { VISUALLY_HIDDEN_STYLE } from '../visually-hidden/visually-hidden';\n\ntype Politeness = 'polite' | 'assertive';\n\ninterface LiveRegion {\n readonly element: HTMLElement;\n readonly unregister: () => void;\n generation: number;\n timer: ReturnType<typeof setTimeout> | null;\n}\n\n/**\n * Tiny ARIA live-region helper. Injects two persistent off-screen regions\n * (`polite` and `assertive`) into `document.body` at construction, then\n * writes / clears messages on demand.\n *\n * Each region declares one channel — `aria-live` plus `aria-atomic`, never a `role`. A live role\n * buys nothing here: its advantage is being read when a node is *inserted* with its text already\n * present, and these regions are inserted empty and only ever rewritten.\n *\n * They are created up front rather than on first use, because a live region must already be in the\n * accessibility tree before its text changes for the change to be announced; creating one inside\n * the first `announce()` risks dropping the first message of a session.\n *\n * Every message is flushed through a deferred write so the region is briefly emptied first, since\n * screen readers ignore repeated text that has not changed. The delay is a macrotask on purpose —\n * with both writes in one microtask drain the empty state never reaches the accessibility tree, and\n * NVDA and VoiceOver miss the repeat.\n *\n * The two politeness regions own independent timers, so a `polite` announce cannot cancel a pending\n * `assertive` one. Within a single region a superseding `announce()` coalesces and the latest\n * message wins, so text that evolves across a change-detection pass is read out once, in full.\n *\n * Each region carries the `MODAL_EXEMPT_ATTRIBUTE`, so an open modal does not inert it and swallow\n * every announcement made over it. The marker is stamped before the region is appended, so a region\n * created while a modal is already open is skipped too. The topmost open `aria-modal` surface of\n * the library also lists each region in its `aria-owns`, so a screen reader that hides everything\n * outside that surface still reads it.\n *\n * The regions are detached and every pending write cancelled when the injector is destroyed. DOM\n * access is gated on `isPlatformBrowser`, so `announce()` and `clear()` are no-ops on the server.\n *\n * @example\n * ```ts\n * private readonly announcer = inject(LiveAnnouncer);\n *\n * onUploadComplete(): void {\n * this.announcer.announce('Upload complete', 'polite');\n * }\n * ```\n */\n@Injectable({ providedIn: 'root' })\nexport class LiveAnnouncer {\n readonly #document = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n readonly #regions = new Map<Politeness, LiveRegion>();\n readonly #modalOwned = inject(ModalOwnedRegions);\n\n constructor() {\n if (this.#isBrowser) {\n for (const politeness of ['polite', 'assertive'] as const) {\n this.#createRegion(politeness);\n }\n }\n inject(DestroyRef).onDestroy(() => {\n for (const region of this.#regions.values()) {\n this.#cancel(region);\n region.unregister();\n region.element.remove();\n }\n this.#regions.clear();\n });\n }\n\n /**\n * Announce a message in the requested politeness region. Defaults to\n * `polite`, which lets the screen reader finish what it is currently\n * reading; `assertive` interrupts immediately.\n *\n * A superseding announce to the same region coalesces (the latest message\n * wins); the two regions are independent, so a `polite` announce never\n * cancels a pending `assertive` one. Pass an empty string (or call `clear()`)\n * to silence a pending announcement. No-op on a non-browser platform.\n */\n announce(message: string, politeness: Politeness = 'polite'): void {\n if (!this.#isBrowser) {\n return;\n }\n const region = this.#regions.get(politeness)!;\n region.element.textContent = '';\n this.#cancel(region);\n const generation = region.generation;\n region.timer = setTimeout(() => {\n region.timer = null;\n if (generation !== region.generation) {\n return;\n }\n region.element.textContent = message;\n }, 0);\n }\n\n /** Empty all live regions and cancel any pending announce so it never paints. */\n clear(): void {\n if (!this.#isBrowser) {\n return;\n }\n for (const region of this.#regions.values()) {\n this.#cancel(region);\n region.element.textContent = '';\n }\n }\n\n #cancel(region: LiveRegion): void {\n region.generation++;\n if (region.timer !== null) {\n clearTimeout(region.timer);\n region.timer = null;\n }\n }\n\n #createRegion(politeness: Politeness): void {\n const region = this.#document.createElement('div');\n region.setAttribute('aria-live', politeness);\n region.setAttribute('aria-atomic', 'true');\n region.setAttribute(MODAL_EXEMPT_ATTRIBUTE, '');\n // Visually hidden but kept in the accessibility tree.\n region.style.cssText = VISUALLY_HIDDEN_STYLE;\n this.#document.body.appendChild(region);\n this.#regions.set(politeness, {\n element: region,\n unregister: this.#modalOwned.register(region),\n generation: 0,\n timer: null,\n });\n }\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n DOCUMENT,\n DestroyRef,\n Injectable,\n PLATFORM_ID,\n inject,\n signal,\n type Signal,\n} from '@angular/core';\n\n/**\n * Application-scoped `matchMedia` observer: one `MediaQueryList` and one\n * `change` listener per distinct query string, shared by every caller and\n * removed when the application is destroyed.\n *\n * SSR-safe: off the browser, where `matchMedia` is unavailable, or once the\n * application is destroyed, an unobserved query reads a frozen `false` and\n * `matchMedia` is never touched.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\n@Injectable({ providedIn: 'root' })\nexport class MediaQueryRegistry {\n readonly #win = inject(DOCUMENT).defaultView;\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n readonly #entries = new Map<string, Signal<boolean>>();\n readonly #teardowns: Array<() => void> = [];\n readonly #unmatched = signal(false).asReadonly();\n #destroyed = false;\n\n constructor() {\n inject(DestroyRef).onDestroy(() => {\n this.#destroyed = true;\n for (const teardown of this.#teardowns) {\n teardown();\n }\n this.#teardowns.length = 0;\n });\n }\n\n /**\n * Reflects `MediaQueryList.matches` for `query` as a signal. Repeated calls\n * with the same query return the same signal.\n */\n observe(query: string): Signal<boolean> {\n const cached = this.#entries.get(query);\n if (cached !== undefined) {\n return cached;\n }\n const win = this.#win;\n if (this.#destroyed || !this.#isBrowser || !win || typeof win.matchMedia !== 'function') {\n return this.#unmatched;\n }\n\n const mql = win.matchMedia(query);\n const matches = signal(mql.matches);\n const listener = (event: MediaQueryListEvent): void => {\n matches.set(event.matches);\n };\n mql.addEventListener('change', listener);\n this.#teardowns.push(() => mql.removeEventListener('change', listener));\n\n const result = matches.asReadonly();\n this.#entries.set(query, result);\n return result;\n }\n}\n\n/**\n * Reflects the result of `MediaQueryList.matches` for `query` as a signal,\n * staying in sync via `addEventListener('change')`. Every call reading the\n * same query shares one `MediaQueryList` and one listener, which live as long\n * as the application rather than the calling injection context.\n *\n * Must be called from an injection context. SSR-safe: when `PLATFORM_ID`\n * is not the browser the helper returns a frozen `signal(false)` and never\n * touches `matchMedia`. Browsers without `matchMedia` (extreme legacy) fall\n * into the same SSR path.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\nexport function injectMediaQuery(query: string): Signal<boolean> {\n return inject(MediaQueryRegistry).observe(query);\n}\n\n/**\n * Reflects the `prefers-reduced-motion: reduce` media query as a signal — the\n * standard hook for users who have asked their OS to suppress animations. The\n * signal flips reactively if the preference changes mid-session.\n *\n * Because forty-cdk ships no styles, every animation is the consumer's, and so\n * is honouring this preference. Treat a `true` result as a hard signal to skip\n * the animated path entirely, not just to shorten the duration. The primitives\n * whose own default behaviour involves motion (drag gestures, large transforms,\n * parallax) read the same signal.\n *\n * Must be called from an injection context. SSR-safe: on the server the\n * returned signal is a frozen `false`, so the server render takes the animated\n * path's markup and the preference is applied once the client observes it.\n *\n * @example\n * ```ts\n * private readonly reducedMotion = injectPrefersReducedMotion();\n *\n * protected readonly transition = computed(() =>\n * this.reducedMotion() ? 'none' : 'transform 200ms ease-out',\n * );\n * ```\n *\n * @returns A `Signal<boolean>` that is `true` while the user asks for reduced\n * motion.\n */\nexport function injectPrefersReducedMotion(): Signal<boolean> {\n return injectMediaQuery('(prefers-reduced-motion: reduce)');\n}\n","/** Clamps `value` into the inclusive `[min, max]` range. */\nexport function clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\n/**\n * The number of decimal places `n` carries, handling both plain (`0.1` → 1) and\n * exponential (`1e-7` → 7, `1.5e-7` → 8) notation — `String(n)` switches to\n * exponential form below ~`1e-7`, which a naive `indexOf('.')` would read as\n * zero decimals. Non-finite values report 0.\n */\nexport function decimalPlaces(n: number): number {\n if (!Number.isFinite(n)) {\n return 0;\n }\n const text = String(n);\n const exponentIndex = text.indexOf('e');\n if (exponentIndex < 0) {\n const dot = text.indexOf('.');\n return dot < 0 ? 0 : text.length - dot - 1;\n }\n const exponent = Number(text.slice(exponentIndex + 1));\n const mantissa = text.slice(0, exponentIndex);\n const mantissaDot = mantissa.indexOf('.');\n const mantissaDecimals = mantissaDot < 0 ? 0 : mantissa.length - mantissaDot - 1;\n return Math.max(0, mantissaDecimals - exponent);\n}\n\n/**\n * Rounds `value` to `decimals` decimal places. A non-positive `decimals` (an\n * integer-precision request) returns `value` unchanged.\n */\nexport function roundToDecimals(value: number, decimals: number): number {\n if (decimals <= 0) {\n return value;\n }\n const factor = 10 ** decimals;\n return Math.round(value * factor) / factor;\n}\n\n/**\n * Rounds `value` to the decimal precision a `step` carries, so repeated\n * `value ± step` arithmetic with a fractional step (e.g. `0.1`) cannot accumulate\n * float noise (`0.1 * 3 === 0.30000000000000004`) that defeats a `next === value`\n * change guard or leaks into `aria-valuenow`. Precision is derived via\n * {@link decimalPlaces}, so exponential steps (`1e-7`) round correctly; integer\n * steps return `value` unchanged.\n */\nexport function roundToStepPrecision(value: number, step: number): number {\n return roundToDecimals(value, decimalPlaces(step));\n}\n\n/**\n * Snaps `raw` onto the `[min, min + step, min + 2·step, …]` grid, then rounds the\n * result to the greater of the step's and `min`'s decimal precision so a\n * fractional step can't accumulate float noise and a `min` finer than `step`\n * still lands exactly on the grid (e.g. `min=0.05, step=0.1` keeps `0.15`\n * instead of rounding to the step's single decimal and drifting to `0.2`). A\n * non-positive `step` disables snapping and returns `raw` unchanged. Clamping to\n * an outer range is the caller's responsibility — pass the snapped result to\n * {@link clamp}.\n */\nexport function snapToStep(raw: number, step: number, min: number): number {\n if (step <= 0) {\n return raw;\n }\n return roundToDecimals(\n Math.round((raw - min) / step) * step + min,\n Math.max(decimalPlaces(step), decimalPlaces(min)),\n );\n}\n\n/** Configuration for a single {@link stepOnGrid} move. */\nexport interface StepOnGridOptions {\n /**\n * Grid spacing. The grid is `origin ± k · step`. A non-positive or\n * non-finite `step` disables snapping (see {@link stepOnGrid}).\n */\n readonly step: number;\n /** Direction of travel: `1` toward `+∞`, `-1` toward `-∞`. */\n readonly direction: 1 | -1;\n /**\n * Grid origin — the value the grid is measured from, normally the control's\n * `min`. Defaults to `0`.\n */\n readonly origin?: number;\n /**\n * Distance travelled from a value that is already on the grid (a page step,\n * or a caller-supplied amount finer than `step`). Defaults to `step`. It is\n * ignored when the value is off the grid.\n */\n readonly by?: number;\n}\n\n/**\n * Moves `value` one grid position in `direction` along the\n * `origin ± k · step` grid, matching the platform `stepUp()` / `stepDown()`\n * rule so a spinbutton and a slider answer the same key the same way:\n *\n * - **Off the grid** → the nearest grid point strictly in `direction`\n * (`0.55` with `step: 1` gives `1` up / `0` down, `0.36` with `step: 0.1`\n * gives `0.4` up / `0.3` down), so an arbitrary consumer value is corrected\n * onto the grid instead of carrying its offset forever.\n * `by` is ignored here — a page-sized jump from an off-grid\n * value still only lands on the adjacent grid point, exactly as\n * `HTMLInputElement.stepUp(n)` behaves.\n * - **On the grid** → `value ± by` (`1` with `step: 1` gives `2`, never `1`),\n * so a `by` finer than `step` keeps its own precision.\n *\n * The result is rounded to the greatest decimal precision of `step`, `by` and\n * `origin`, so repeated fractional stepping cannot accumulate float noise\n * (`0.1 + 0.2` stepped up by `0.1` yields `0.4`, not `0.4000000000000001`). A\n * value is on the grid when it sits within float noise of a grid point, so one\n * carrying that noise is still recognised as on-grid while one with more\n * decimals than the step is not. A `by` of `0` returns `value` unchanged; a\n * non-positive or non-finite `step` (and a non-finite `value` / `origin`)\n * disables snapping and falls back to plain `value + direction · by` at the\n * same precision. Clamping to an outer range\n * is the caller's responsibility — pass the result to {@link clamp}. Use\n * {@link snapToStep} instead when the input is a continuous measurement with\n * no direction of travel (a pointer drag), which snaps to the *nearest* grid\n * point rather than the next one.\n */\nexport function stepOnGrid(value: number, options: StepOnGridOptions): number {\n const { step, direction, origin = 0, by = step } = options;\n const precision = Math.max(decimalPlaces(step), decimalPlaces(by), decimalPlaces(origin));\n if (by === 0) {\n return value;\n }\n if (\n !(step > 0) ||\n !Number.isFinite(step) ||\n !Number.isFinite(value) ||\n !Number.isFinite(origin)\n ) {\n return roundToDecimals(value + direction * by, precision);\n }\n const index = (value - origin) / step;\n if (!Number.isFinite(index)) {\n return roundToDecimals(value + direction * by, precision);\n }\n const floatNoise = ((Math.abs(value) + Math.abs(origin)) / step) * Number.EPSILON * 1024;\n if (Math.abs(index - Math.round(index)) <= floatNoise) {\n return roundToDecimals(value + direction * by, precision);\n }\n const gridIndex = direction > 0 ? Math.ceil(index) : Math.floor(index);\n return roundToDecimals(gridIndex * step + origin, precision);\n}\n","import { DOCUMENT, DestroyRef, Injectable, PLATFORM_ID, inject } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\n/**\n * Refcounted `document.visibilitychange` subscription. Multiple toasts\n * (or any other primitive that wants to pause work while the page is in\n * the background) call `subscribe` independently — only the first\n * subscribe attaches the listener, only the last unsubscribe removes it.\n *\n * Each subscriber receives `true` while `document.visibilityState !== 'visible'`\n * (the page is hidden / backgrounded) and `false` when it becomes visible\n * again. Subscribers are not invoked synchronously on subscribe — they\n * only fire on transitions, so register them in a context where the\n * primitive's \"visible\" state is the implicit starting point.\n *\n * SSR: `providedIn: 'root'` so the listener set is scoped to one Angular\n * bootstrap. Server-side calls return a no-op unsubscribe.\n */\ntype VisibilityListener = (hidden: boolean) => void;\n\n@Injectable({ providedIn: 'root' })\nexport class VisibilityPause {\n readonly #document = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n readonly #listeners = new Set<VisibilityListener>();\n #domListener: (() => void) | null = null;\n\n constructor() {\n if (!this.#isBrowser) {\n return;\n }\n inject(DestroyRef).onDestroy(() => {\n this.#detachDomListener();\n this.#listeners.clear();\n });\n }\n\n /**\n * Whether the page is currently hidden / backgrounded\n * (`document.visibilityState !== 'visible'`). Returns `false` on the\n * server. Use this to seed initial pause state, since `subscribe` only\n * fires on transitions and never synchronously on subscribe.\n */\n currentlyHidden(): boolean {\n return this.#isBrowser ? this.#document.visibilityState !== 'visible' : false;\n }\n\n subscribe(listener: VisibilityListener): () => void {\n if (!this.#isBrowser) {\n return () => {};\n }\n if (this.#listeners.size === 0) {\n this.#attachDomListener();\n }\n this.#listeners.add(listener);\n\n return (): void => {\n if (!this.#listeners.delete(listener)) {\n return;\n }\n if (this.#listeners.size === 0) {\n this.#detachDomListener();\n }\n };\n }\n\n #attachDomListener(): void {\n this.#domListener = (): void => {\n const hidden = this.#document.visibilityState !== 'visible';\n for (const fn of this.#listeners) {\n fn(hidden);\n }\n };\n this.#document.addEventListener('visibilitychange', this.#domListener);\n }\n\n #detachDomListener(): void {\n if (this.#domListener) {\n this.#document.removeEventListener('visibilitychange', this.#domListener);\n this.#domListener = null;\n }\n }\n}\n\n/**\n * Convenience wrapper that resolves the application-scoped\n * `VisibilityPause` and subscribes. Must be called from an injection\n * context.\n */\nexport function subscribeVisibilityPause(listener: VisibilityListener): () => void {\n return inject(VisibilityPause).subscribe(listener);\n}\n\n/**\n * Convenience wrapper that resolves the application-scoped\n * `VisibilityPause` and reports whether the page is currently hidden.\n * Must be called from an injection context. Returns `false` on the server.\n */\nexport function isPageHidden(): boolean {\n return inject(VisibilityPause).currentlyHidden();\n}\n","import { DestroyRef, inject, type Signal, signal } from '@angular/core';\n\nimport { isPageHidden, subscribeVisibilityPause } from './visibility-pause';\n\n/**\n * Options for {@link injectPauseController}.\n */\nexport interface PauseControllerOptions {\n /**\n * When `true` (default), the controller auto-subscribes the shared\n * `visibility-pause` source: it applies the `'visibility'` reason while the\n * page is backgrounded (seeding from the current state on construction) and\n * releases it when the page becomes visible again. The reason key is always\n * the literal `'visibility'`, so the reason union `R` must include it — a\n * caller that leaves page-visibility tracking enabled (i.e. does not pass\n * `trackPageVisibility: false`) fails to compile unless `'visibility'` is\n * assignable to `R`. Pass `trackPageVisibility: false` to opt out, which also\n * exempts the caller from that constraint.\n */\n trackPageVisibility?: boolean;\n /**\n * Invoked synchronously on every `paused` transition (and only on a genuine\n * change), after the `paused` signal has been updated. Lets a consumer layer\n * imperative side effects on the edge — e.g. Toast captures the remaining\n * auto-dismiss time on pause and reschedules on resume — without putting its\n * timer on the reactive graph.\n */\n onChange?: (paused: boolean) => void;\n}\n\n/**\n * Multi-reason pause controller shared by Toast and Carousel.\n *\n * Holds the set of active pause reasons and a derived `paused` signal (`true`\n * while any reason is held). Several independent sources — pointer hover,\n * focus, page visibility — can each pause and resume independently; the work\n * stays paused until every reason is released. Toast and Carousel previously\n * hand-rolled byte-identical copies of the reason set plus `apply` / `release`\n * / `update` helpers, and the copies had already drifted (only Toast wired the\n * page-visibility source through it). Centralizing both restores parity.\n *\n * Must be called from an injection context (subscribes `visibility-pause` via\n * the injector-scoped source). Internal core tier — no semver guarantee.\n */\nexport interface PauseController<R extends string> {\n /** `true` while at least one pause reason is held. */\n readonly paused: Signal<boolean>;\n /** Hold `reason`. Idempotent — holding an already-held reason is a no-op. */\n apply(reason: R): void;\n /** Release `reason`. Idempotent — releasing a not-held reason is a no-op. */\n release(reason: R): void;\n}\n\n/**\n * Builds a {@link PauseController}. When `trackPageVisibility` is enabled the\n * `'visibility'` reason is wired to the shared `visibility-pause` source and\n * its subscription is torn down with the surrounding injector.\n *\n * The caller contract is compiler-checked: because page-visibility tracking\n * defaults on and always holds the literal `'visibility'` reason, a caller that\n * leaves it enabled must have `'visibility'` assignable to `R`. When it isn't,\n * the `options` argument becomes required and must be `{ trackPageVisibility:\n * false }`, so enabling the source without a matching reason union fails to\n * compile. Callers that pass `trackPageVisibility: false` are exempt (any `R`).\n */\nexport function injectPauseController<R extends string>(\n ...args: 'visibility' extends R\n ? [options?: PauseControllerOptions]\n : [options: PauseControllerOptions & { trackPageVisibility: false }]\n): PauseController<R> {\n const options: PauseControllerOptions = args[0] ?? {};\n const reasons = new Set<R>();\n const paused = signal(false);\n\n function update(): void {\n const next = reasons.size > 0;\n if (next === paused()) {\n return;\n }\n paused.set(next);\n options.onChange?.(next);\n }\n\n function apply(reason: R): void {\n reasons.add(reason);\n update();\n }\n\n function release(reason: R): void {\n reasons.delete(reason);\n update();\n }\n\n if (options.trackPageVisibility ?? true) {\n const visibilityReason = 'visibility' as R;\n const unsubscribe = subscribeVisibilityPause((hidden) => {\n if (hidden) {\n apply(visibilityReason);\n } else {\n release(visibilityReason);\n }\n });\n inject(DestroyRef).onDestroy(unsubscribe);\n if (isPageHidden()) {\n apply(visibilityReason);\n }\n }\n\n return {\n paused: paused.asReadonly(),\n apply,\n release,\n };\n}\n","/**\n * Whether a pointer event comes from a device that hovers.\n *\n * Hover-driven menu behaviour — sub-trigger hover-open / hover-close,\n * hover-follows-pointer highlighting, the submenu safe triangle, the menubar's\n * hover keepalive — is a mouse affordance: touch and pen are both reported as\n * non-hovering here, so on those pointer types the same primitives are driven\n * by tap (the native click) instead. The empty `pointerType` counts as\n * hover-capable: a synthetic `PointerEvent` leaves it `''` (browsers only\n * populate it for real input), and a synthetic hover must behave like a mouse\n * hover rather than being dropped.\n *\n * This is the stricter of the library's two hover vocabularies — see\n * {@link isNonTouchPointer} for the pen-inclusive twin used by the tooltip /\n * hover-card family. The two are kept apart: a pen genuinely\n * hovers a tooltip, and genuinely should not hover-open a submenu.\n *\n * @param event The pointer event to classify — only `pointerType` is read.\n * @returns `true` for `'mouse'` and for the empty synthetic `pointerType`,\n * `false` for `'touch'` / `'pen'` / any other value.\n */\nexport function isHoverCapablePointer(event: Pick<PointerEvent, 'pointerType'>): boolean {\n return event.pointerType === '' || event.pointerType === 'mouse';\n}\n\n/**\n * Whether a pointer event comes from a device whose hover is meaningful for\n * descriptive, supplementary content.\n *\n * Tooltip / hover-card triggers and the `injectHovered` hover state treat a pen\n * as a hovering device — a stylus reports `pointerover` / `pointerenter` while\n * it is detected above the digitizer, so a pen user gets the same preview a\n * mouse user does. Only `'touch'` is rejected: a tap emits an emulated\n * `pointerenter` that would otherwise leave the element stuck in a hovered\n * state after the finger lifts, and the APG flags hover-revealed content as\n * problematic on touch (no hover, no obvious dismiss). The empty synthetic\n * `pointerType` passes, matching {@link isHoverCapablePointer}.\n *\n * This is the pen-inclusive twin of {@link isHoverCapablePointer}, which is\n * mouse-only because the menu family drives submenu hover-open by tap on both\n * touch and pen. Pick the predicate that matches the family you are writing\n * for; do not fold one onto the other.\n *\n * Neither predicate covers the non-hover `pointerType` checks in the library —\n * the twelve primary-button guards (`pointerType === 'mouse' && button !== 0`\n * in `pressed`, the drag-session handle guard, swipe-dismiss, listbox reorder,\n * virtual reorder, table row reorder, tree node drag, the pane resizer, the\n * table column resizer, the slider, the scroll-area thumb and the scroll-area\n * track press) and the context-menu long-press gate\n * (`pointerType !== 'touch'`). Those classify a press, not a hover, so they\n * stay inline by design.\n *\n * @param event The pointer event to classify — only `pointerType` is read.\n * @returns `false` for `'touch'`, `true` for every other `pointerType`\n * (`'mouse'`, `'pen'`, the empty synthetic value, or a future device type).\n */\nexport function isNonTouchPointer(event: Pick<PointerEvent, 'pointerType'>): boolean {\n return event.pointerType !== 'touch';\n}\n","import { DestroyRef, ElementRef, inject } from '@angular/core';\n\nimport { composedParentElement, resolveEventTarget } from '../composed-tree/composed-tree';\nimport { FOCUSABLE_SELECTOR, isDisabledControl } from '../focus-trap/focusable-candidate';\n\nexport function preventPointerFocus(when: (event: MouseEvent) => boolean = () => true): void {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const onMouseDown = (event: MouseEvent): void => {\n if (when(event)) {\n event.preventDefault();\n }\n };\n host.addEventListener('mousedown', onMouseDown);\n inject(DestroyRef).onDestroy(() => host.removeEventListener('mousedown', onMouseDown));\n}\n\nexport function pressFocusesDescendant(event: Event, host: Element): boolean {\n return mouseFocusTarget(resolveEventTarget(event), host) !== null;\n}\n\nexport function mouseFocusTarget(\n node: Node | null,\n boundary: Element | null = null,\n): HTMLElement | null {\n for (let current = node; current !== null && current !== boundary;) {\n if (current.nodeType === current.ELEMENT_NODE && isMouseFocusable(current as Element)) {\n return current as HTMLElement;\n }\n current = composedParentElement(current);\n }\n return null;\n}\n\nfunction isMouseFocusable(el: Element): boolean {\n return (el.hasAttribute('tabindex') || el.matches(FOCUSABLE_SELECTOR)) && !isDisabledControl(el);\n}\n\nexport function focusAfterPress(host: HTMLElement): void {\n host.focus({ preventScroll: true });\n}\n\n/** How long (ms) after a press, or its release, a focus still counts as caused by it. */\nexport const DEFAULT_PRESS_FOCUS_WINDOW_MS = 500;\n\n/**\n * Tells a focus a pointer press caused from a keyboard focus, for a trigger that\n * opens on keyboard focus only.\n *\n * A press counts for a bounded window only, so a press that never focuses its\n * target (a `<button>` or `<a>` in macOS Safari and Firefox, a `mousedown` whose\n * default is prevented) cannot make a later keyboard focus read as\n * pointer-induced.\n */\nexport interface PressFocus {\n /** Records a press on the element. Call it from `pointerdown`. */\n press(): void;\n /**\n * Restarts the window when a recorded press ends, since a touch tap focuses\n * its target only after the release. Call it from `pointerup`; a no-op when\n * no press is recorded.\n */\n release(): void;\n /** Whether a focus arriving now was caused by the recorded press. Forgets the press. */\n consume(): boolean;\n /** Forgets the recorded press. Call it from `blur`. */\n reset(): void;\n}\n\n/**\n * Creates a {@link PressFocus} backed by a timestamp window.\n *\n * @param windowMs How long a press stays able to explain a focus. Defaults to\n * {@link DEFAULT_PRESS_FOCUS_WINDOW_MS}.\n */\nexport function createPressFocus(windowMs: number = DEFAULT_PRESS_FOCUS_WINDOW_MS): PressFocus {\n let pressed = false;\n let stampedAt = 0;\n return {\n press(): void {\n pressed = true;\n stampedAt = Date.now();\n },\n release(): void {\n if (pressed) {\n stampedAt = Date.now();\n }\n },\n consume(): boolean {\n const induced = pressed && Date.now() - stampedAt < windowMs;\n pressed = false;\n return induced;\n },\n reset(): void {\n pressed = false;\n },\n };\n}\n","/**\n * Pointer-suppression window.\n *\n * When keyboard navigation moves the active option of an\n * `aria-activedescendant` listbox and scrolls it into view, the scroll can\n * slide a *different* option under a stationary cursor. The browser then fires\n * a synthetic `pointermove` / `pointerover` for that option even though the\n * pointer never physically moved, and a naive hover handler would hijack the\n * active descendant onto the option the user merely scrolled past — fighting\n * the keyboard intent.\n *\n * The fix every native-feeling listbox uses is a brief window, opened the\n * moment the directive scrolls programmatically, during which hover-driven\n * activation is ignored. A genuine pointer move that lands after the window\n * elapses takes over again, so mouse and keyboard intent stay in sync without\n * the scroll stealing the active option.\n *\n * Pure and Angular-free: no DI, no timers, no globals touched at module load.\n * State is a single \"suppressed until\" timestamp compared against `Date.now()`\n * inside the (browser-only) event handlers that call it, so it is SSR-safe and\n * needs no teardown. Unit-tested in `pointer-suppression.spec.ts`.\n */\n\n/** Default suppression window, in milliseconds. */\nexport const DEFAULT_POINTER_SUPPRESSION_MS = 200;\n\n/**\n * Tracks a short window during which hover-driven activation should be ignored.\n * Created once per primitive instance; consulted synchronously inside pointer\n * event handlers.\n */\nexport interface PointerSuppression {\n /**\n * Open (or extend) the suppression window from the current instant. Call it\n * immediately before a programmatic scroll that could move options under a\n * stationary cursor.\n */\n suppress(): void;\n /**\n * Whether the suppression window is currently open. Hover handlers bail out\n * (leaving the active descendant unchanged) while this returns `true`.\n */\n isSuppressed(): boolean;\n}\n\n/**\n * Create a {@link PointerSuppression} backed by a timestamp window.\n *\n * @param windowMs How long the window stays open after each {@link\n * PointerSuppression.suppress} call. Defaults to\n * {@link DEFAULT_POINTER_SUPPRESSION_MS}.\n */\nexport function createPointerSuppression(\n windowMs: number = DEFAULT_POINTER_SUPPRESSION_MS,\n): PointerSuppression {\n let suppressedUntil = 0;\n return {\n suppress(): void {\n suppressedUntil = Date.now() + windowMs;\n },\n isSuppressed(): boolean {\n return Date.now() < suppressedUntil;\n },\n };\n}\n","import { DOCUMENT, inject, Injectable } from '@angular/core';\n\n@Injectable({ providedIn: 'root' })\nexport class StationaryPointerMoves {\n readonly #document = inject(DOCUMENT);\n readonly #verdicts = new WeakMap<Event, boolean>();\n #controller: AbortController | null = null;\n #users = 0;\n #pointerId = -1;\n #x = Number.NaN;\n #y = Number.NaN;\n #scrolled = false;\n\n acquire(): () => void {\n if (this.#users === 0) {\n this.#listen();\n }\n this.#users += 1;\n let released = false;\n return () => {\n if (released) {\n return;\n }\n released = true;\n this.#users -= 1;\n if (this.#users === 0) {\n this.#controller?.abort();\n this.#controller = null;\n }\n };\n }\n\n isStationary(event: PointerEvent): boolean {\n const known = this.#verdicts.get(event);\n if (known !== undefined) {\n return known;\n }\n const stationary =\n this.#scrolled &&\n event.pointerId === this.#pointerId &&\n event.clientX === this.#x &&\n event.clientY === this.#y;\n this.#verdicts.set(event, stationary);\n this.#scrolled = false;\n this.#pointerId = event.pointerId;\n this.#x = event.clientX;\n this.#y = event.clientY;\n return stationary;\n }\n\n #listen(): void {\n this.#controller = new AbortController();\n this.#pointerId = -1;\n this.#x = Number.NaN;\n this.#y = Number.NaN;\n this.#scrolled = false;\n this.#document.addEventListener(\n 'scroll',\n () => {\n this.#scrolled = true;\n },\n { capture: true, passive: true, signal: this.#controller.signal },\n );\n }\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n computed,\n DestroyRef,\n ElementRef,\n inject,\n PLATFORM_ID,\n signal,\n type Signal,\n untracked,\n} from '@angular/core';\n\nimport { KeyedFlag } from '../keyed-flag/keyed-flag';\nimport { createPointerSuppression } from './pointer-suppression';\nimport { StationaryPointerMoves } from './stationary-pointer-moves';\n\nexport function injectPointerMove(handler: (event: PointerEvent) => void): void {\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n return;\n }\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const moves = inject(StationaryPointerMoves);\n const release = moves.acquire();\n const controller = new AbortController();\n host.addEventListener(\n 'pointermove',\n (event) => {\n if (!moves.isStationary(event)) {\n handler(event);\n }\n },\n { signal: controller.signal },\n );\n inject(DestroyRef).onDestroy(() => {\n controller.abort();\n release();\n });\n}\n\nexport interface PointerHighlightItem {\n readonly host: HTMLElement;\n readonly disabled: Signal<boolean>;\n}\n\nexport interface PointerHighlightActiveDescendant {\n readonly active: () => boolean;\n readonly claim: (id: string) => void;\n}\n\nexport interface PointerHighlightConfig {\n readonly items: () => readonly PointerHighlightItem[];\n readonly activeDescendant?: PointerHighlightActiveDescendant;\n}\n\nexport interface PointerHighlight {\n readonly pointed: Signal<HTMLElement | null>;\n /**\n * Whether an enabled item is under the pointer. Notifies its readers only\n * when that answer changes, not when the pointer moves between enabled items.\n */\n hasPointed(): boolean;\n /** Whether `host` is the enabled item under the pointer. Reactive per host. */\n isPointed(host: HTMLElement): boolean;\n claim(host: HTMLElement, id?: string): void;\n release(): void;\n suppress(): void;\n isSuppressed(): boolean;\n}\n\nexport function createPointerHighlight(config: PointerHighlightConfig): PointerHighlight {\n const suppression = createPointerSuppression();\n const host = signal<HTMLElement | null>(null);\n const pointed = computed<HTMLElement | null>(() => {\n const current = host();\n if (current === null) {\n return null;\n }\n const item = config.items().find((candidate) => candidate.host === current);\n return item && !item.disabled() ? current : null;\n });\n const flag = new KeyedFlag<HTMLElement>();\n const epoch = signal(0);\n let tracksItems = false;\n const hasPointed = computed(() => {\n epoch();\n if (tracksItems) {\n for (const item of config.items()) {\n item.disabled();\n }\n }\n return untracked(pointed) !== null;\n });\n const point = (next: HTMLElement | null): void => {\n untracked(() => {\n if (host() === next) {\n return;\n }\n const before = hasPointed();\n flag.move(next);\n host.set(next);\n const subscribes = next !== null && !tracksItems;\n if (subscribes) {\n tracksItems = true;\n }\n if (subscribes || (pointed() !== null) !== before) {\n epoch.update((value) => value + 1);\n }\n });\n };\n return {\n pointed,\n hasPointed,\n isPointed(target: HTMLElement): boolean {\n return flag.has(target) && hasPointed();\n },\n claim(target: HTMLElement, id: string = target.id): void {\n if (suppression.isSuppressed()) {\n return;\n }\n const activeDescendant = config.activeDescendant;\n if (activeDescendant?.active()) {\n activeDescendant.claim(id);\n return;\n }\n point(target);\n },\n release(): void {\n point(null);\n },\n suppress(): void {\n suppression.suppress();\n },\n isSuppressed(): boolean {\n return suppression.isSuppressed();\n },\n };\n}\n","import {\n DOCUMENT,\n PLATFORM_ID,\n DestroyRef,\n ElementRef,\n effect,\n inject,\n signal,\n} from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\nimport { afterNextRenderCancellable } from '../after-next-render-cancellable/after-next-render-cancellable';\nimport { composedParentElement } from '../composed-tree/composed-tree';\nimport { injectDeclaredDirection, stampAmbientDirection } from '../text-direction/text-direction';\n\nexport interface PortalConfig {\n /**\n * Where to portal the host element. Defaults to `document.body`. Pass a\n * specific container for cases like fullscreen API stacking, scoped\n * testing harnesses, or shadow DOM hosts.\n *\n * A function form is also accepted; it is resolved lazily inside the\n * existing `afterNextRender` callback so a value that is not yet available\n * at construction time — for example a directive input — can be used.\n * Returns `null` or `undefined` to fall back to `document.body`.\n */\n readonly target?: HTMLElement | (() => HTMLElement | null | undefined);\n\n /**\n * Sibling the host is inserted immediately before, resolved in the same `afterNextRender`\n * callback as `target`. Honoured only while that element is a child of the target; otherwise,\n * or when it returns `null` / `undefined`, the host is appended.\n */\n readonly before?: () => Element | null | undefined;\n}\n\n/**\n * Moves the directive's host element to `target` (default `document.body`)\n * after the first render and removes it on destroy. Designed for primitives\n * that need to escape clipping / `transform` / `overflow: hidden` ancestors:\n * tooltips, popovers, dialogs, toasts.\n *\n * Must be called from an injection context. The directive's `ElementRef` is\n * the host that gets portaled. Angular destroy hooks still fire normally —\n * the view tree is unaffected, only the DOM position changes.\n *\n * The portaled host keeps the writing direction of the position it left: unless it already\n * carries a `dir` attribute when it moves, it is given the `dir` declared above its original\n * parent (the nearest `[dir]` ancestor, across open shadow roots, then `<html dir>`), and follows\n * runtime `dir` changes there. So content opened inside a `dir=\"rtl\"` subtree stays RTL, and a\n * floating `align` of `start` / `end` resolves against that direction rather than against\n * `<body>`'s. When no element declares a `dir`, the host is left without one and inherits its\n * direction where it lands, CSS `direction` included.\n *\n * Note: any styles scoped to the original parent (CSS modules, encapsulated\n * `:host` rules, descendant selectors) won't reach the portaled element.\n * Style it via global CSS or with classes on the host directive itself.\n *\n * SSR: the portal is a no-op on the server. Overlay primitives use\n * `afterNextRender` to wire side effects, which doesn't run server-side\n * either; static markup (role, aria-*, ids, data-state) renders normally\n * and the portaled position is established once the client takes over.\n *\n * Implementation note — destroy ordering. The deferred `appendChild` is\n * registered via `afterNextRenderCancellable`; the destroy hook runs\n * `el.remove()`. If the directive is torn down between construction and the\n * next render (rare, but happens in synchronous open/close test paths or fast\n * SPA navigations), the destroy hook sees a not-yet-portaled element and\n * `el.remove()` is effectively a no-op against the original parent. Without\n * defending against it, the queued `afterNextRender` would still fire after\n * destroy and re-attach the element to `target` with no remaining destroy\n * hook to clean it up — a leak. The shared `afterNextRenderCancellable`\n * helper cancels the queued callback on destroy (it captures the\n * `AfterRenderRef`, calls `.destroy()` from its own destroy hook, and guards\n * the callback with a `destroyed` flag), so the `appendChild` never runs once\n * the directive is gone.\n */\nexport function injectPortal(config: PortalConfig = {}): void {\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n return;\n }\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const destroyRef = inject(DestroyRef);\n const doc = inject(DOCUMENT);\n const el = host.nativeElement;\n const resolveTarget = (): HTMLElement => {\n const t = typeof config.target === 'function' ? config.target() : config.target;\n return t ?? doc.body;\n };\n\n const origin = signal<Element | null>(null);\n const declaredDir = injectDeclaredDirection(origin);\n\n afterNextRenderCancellable(() => {\n const target = resolveTarget();\n const sibling = config.before?.() ?? null;\n const anchor =\n sibling !== null && sibling !== el && sibling.parentNode === target ? sibling : null;\n if (el.parentNode === target && (anchor === null || el.nextSibling === anchor)) {\n return;\n }\n if (el.parentNode !== target && !el.hasAttribute('dir')) {\n const parent = composedParentElement(el);\n origin.set(parent);\n stampAmbientDirection(el, parent);\n }\n target.insertBefore(el, anchor);\n });\n\n effect(() => {\n const dir = declaredDir();\n if (origin() === null) {\n return;\n }\n if (dir === null) {\n el.removeAttribute('dir');\n } else if (el.getAttribute('dir') !== dir) {\n el.setAttribute('dir', dir);\n }\n });\n\n destroyRef.onDestroy(() => {\n if (typeof requestAnimationFrame === 'undefined' || typeof el.getAnimations !== 'function') {\n el.remove();\n return;\n }\n requestAnimationFrame(() => {\n const finite = el.getAnimations({ subtree: true }).filter(isFiniteAnimation);\n if (finite.length === 0) {\n el.remove();\n return;\n }\n Promise.all(finite.map((animation) => animation.finished.catch(() => undefined))).then(() =>\n el.remove(),\n );\n });\n });\n}\n\n/**\n * True when `animation` will actually finish — i.e. it does not run forever.\n * An infinite animation (a shimmer / pulse with `animation-iteration-count:\n * infinite`) reports `Infinity` iterations, and its `finished` promise never\n * resolves; awaiting it would strand deferred teardown and leak the node.\n * Filtering these out before awaiting `finished` lets teardown proceed once the\n * finite animations settle (or immediately, when none remain). Guards for a\n * possibly-null effect and for environments lacking `getComputedTiming`.\n */\nfunction isFiniteAnimation(animation: Animation): boolean {\n const effect = animation.effect;\n if (!effect || typeof effect.getComputedTiming !== 'function') {\n return true;\n }\n return effect.getComputedTiming().iterations !== Infinity;\n}\n","import { fortyError } from '../errors/errors';\n\n/**\n * Identity of the piece asserting its root context, plus the probe that tells\n * the root apart from any other value the token's public type admits.\n */\nexport interface RootContextAssertion {\n /** Entry-point name for the `[forty-cdk/<entryPoint>]` error prefix, e.g. `'accordion'`. */\n readonly entryPoint: string;\n /** Name of the token the piece resolved, e.g. `'FOR_ACCORDION_CONTEXT'`. */\n readonly token: string;\n /** Selector of the root the token must be aliased to, e.g. `'[forAccordion]'`. */\n readonly root: string;\n /** The piece the error names, e.g. `'ForAccordionTrigger'`. */\n readonly piece: string;\n /**\n * Reads one member the resolved context only has when it is the root: a\n * `register*` method the internal interface adds, or — where the internal\n * interface adds no method of its own and only widens a member, as in Select\n * — a nested member the public facade narrows away.\n *\n * The probe passes when it resolves to a function. A probe that *throws*\n * counts as a miss, so a value missing the whole nesting level fails with the\n * error below instead of with the raw `TypeError` the read produced.\n */\n readonly probe: () => unknown;\n}\n\n/** The probed member, or `undefined` when reading it threw. */\nfunction readProbe(probe: () => unknown): unknown {\n try {\n return probe();\n } catch {\n return undefined;\n }\n}\n\n/**\n * Dev-mode guard that the value behind a split root's context token really is\n * the root. Call it from the primitive's `inject<Primitive>Context` resolver,\n * immediately after the orphan branch.\n *\n * A split root provides **one** token, publicly typed as\n * the consumer read surface, which the resolver reads at the unexported\n * internal interface's type so the pieces reach the registration protocol.\n * Nothing checks that cast: a consumer who provides the token with any other\n * value satisfying the public type typechecks and resolves, then fails inside\n * the first piece to reach the protocol — with no `[forty-cdk/<entry>]` prefix\n * and a stack pointing at a library file for a mistake made in consumer\n * providers.\n *\n * There is no compile-time channel for this, which is why the check is a\n * runtime one: the roots declare `implements For<Primitive>Context` only, and a\n * `satisfies <Primitive>Context` cannot be added because the protocol members\n * are TS-`private` — keeping them out of the emitted `.d.ts` and coupling the\n * class to the internal interface are mutually exclusive.\n *\n * The gate lives inside the helper, so it travels with the check and no call\n * site can forget it. The resolver runs from a piece's constructor, so the\n * throw aborts the render and a consumer's `try` sees it — unlike an assertion\n * routed through an `effect()`.\n */\nexport function assertRootContext(assertion: RootContextAssertion): void {\n if (typeof ngDevMode !== 'undefined' && !ngDevMode) {\n return;\n }\n if (typeof readProbe(assertion.probe) === 'function') {\n return;\n }\n throw fortyError({\n code: 'FORCDK-CORE-007',\n scope: assertion.entryPoint,\n message: `${assertion.piece} resolved a ${assertion.token} provider that is not the ${assertion.root} root.`,\n cause:\n 'The token is publicly typed as the consumer read surface, but the pieces read it at the ' +\n \"root's internal registration protocol, which only the root implements.\",\n fix:\n `Alias the token to the root itself: { provide: ${assertion.token}, useExisting: MyRoot }, ` +\n `where MyRoot is ${assertion.root} or a subclass of it.`,\n });\n}\n","import { InjectionToken, type Signal } from '@angular/core';\n\nimport type { CollectionHandle } from '../collection/collection';\nimport type {\n ListNavigationAction,\n WritingDirection,\n} from '../keyboard-navigation/keyboard-navigation';\nimport type { RovingTabindex } from './roving-tabindex';\n\n/**\n * The handle an embedded item registers with a host-roving container: its\n * host element and a `disabled` signal the container reads to skip it during\n * arrow-key navigation. Container-specific extras, such as a toggle item's\n * `value`, live on the container's own handle.\n */\nexport interface HostRovingItemHandle extends CollectionHandle {\n /**\n * Narrowed from {@link CollectionHandle}'s `Node`: the host owns focus moves\n * and the roving tab stop, both of which are element operations.\n */\n readonly host: HTMLElement;\n readonly disabled: Signal<boolean>;\n}\n\n/**\n * Coordination contract of a container that owns the roving tab stop and\n * arrow-key navigation for the items it composes, including items that\n * belong to a nested primitive and delegate focus management upward.\n *\n * Embedded items inject the token with `{ optional: true, skipSelf: true }`:\n * `optional` because an item used outside any such container has none, and\n * `skipSelf` so a container implementing the contract never resolves its\n * own provider.\n */\nexport interface HostRovingContext {\n /** Layout direction the host wants its items to navigate along. */\n readonly orientation: Signal<'horizontal' | 'vertical'>;\n /** Reading direction. RTL swaps ArrowLeft / ArrowRight semantics. */\n readonly dir: Signal<WritingDirection>;\n /** When true, every embedded item is disabled regardless of its own state. */\n readonly disabled: Signal<boolean>;\n\n /**\n * Roving-tabindex tracker owned by the host. Embedded items call\n * `setActive` on `(focus)` and prefer `active()` in their tabindex\n * computed so the host's single tab stop follows the last focused item\n * (APG re-entry), exactly like Tabs / Tree. Before any focus `active()`\n * is `null` and the item falls back to {@link isFirstFocusableItem}.\n */\n readonly roving: RovingTabindex;\n\n /**\n * Predicate for the per-item `tabindex` host binding. Returns `true`\n * for the single item that should currently carry `tabindex=0`\n * (the host's \"entry point\"); every other registered item is `-1`.\n * Only consulted before the roving tracker has an active item.\n */\n isFirstFocusableItem(el: HTMLElement): boolean;\n\n /**\n * Move focus from `currentItem` to the next item in registration order\n * matching `action`, respecting the host's `loop` policy and skipping\n * disabled handles.\n */\n navigate(currentItem: HTMLElement, action: ListNavigationAction): void;\n\n registerItem(handle: HostRovingItemHandle): void;\n unregisterItem(handle: HostRovingItemHandle): void;\n}\n\n/**\n * Injection token for `HostRovingContext`. Internal to the library — must\n * NOT be re-exported from `public-api.ts`. Containers that implement the\n * contract provide it via `useExisting` alongside their own primitive\n * context token.\n */\nexport const FOR_HOST_ROVING_CONTEXT = new InjectionToken<HostRovingContext>(\n 'FOR_HOST_ROVING_CONTEXT',\n);\n","import { afterEveryRender, DestroyRef, DOCUMENT, ElementRef, inject } from '@angular/core';\n\nimport { resolveActiveElement } from '../composed-tree/composed-tree';\n\n/**\n * The owner of a roving group's tab stop, read by {@link injectRovingFocusRestore}:\n * a `RovingTabindex` built with `fallback: 'nearest'`, or the selection-driven\n * owner of a group that builds no tracker.\n */\nexport interface RovingFocusTarget {\n /** The element that owns the group's tab stop, or `null` when none does. */\n readonly active: () => HTMLElement | null;\n /** Receives the element holding DOM focus inside the group, or `null` once focus left it. */\n readonly noteFocus?: (el: Element | null) => void;\n}\n\n/** Options for {@link injectRovingFocusRestore}. */\nexport interface RovingFocusRestoreOptions {\n /** Whether the departure of `departed`, which held focus, moves no focus. */\n readonly skip?: (departed: Element) => boolean;\n}\n\n/**\n * Keeps DOM focus inside a roving group whose focused element leaves it. When a\n * render detaches the element that held DOM focus inside the group's host while\n * focus has fallen to `<body>`, focus moves to the host the tracker re-seeded to.\n * An element that did not hold focus when it left moves nothing, whatever the\n * tracker's pointer says, and focus anywhere else is left alone, so a consumer\n * control that removed or collapsed the item keeps it, and so does a targeted\n * focus move another render hook makes in the same render (a keyboard drop\n * focusing the moved node). It also reports the element holding focus inside\n * the group to the target's `noteFocus`, which a tracker reads to yield the tab\n * stop while a disabled item holds focus.\n *\n * Pair it with a tracker built with `fallback: 'nearest'`, so the new owner is\n * the item beside the one that left rather than the first in the group, or, for\n * a group whose tab stop follows its selection and builds no tracker, with the\n * owner that selection resolves. Call it in the injection context of the\n * group's host directive; it moves no focus during a server render.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\nexport function injectRovingFocusRestore(\n roving: RovingFocusTarget,\n options: RovingFocusRestoreOptions = {},\n): void {\n const document = inject(DOCUMENT);\n const root = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n let held: Element | null = null;\n\n const onFocusIn = (event: FocusEvent): void => {\n held = event.target instanceof Element ? event.target : null;\n roving.noteFocus?.(held);\n };\n const onFocusOut = (event: FocusEvent): void => {\n roving.noteFocus?.(null);\n const target = event.target;\n queueMicrotask(() => {\n if (held !== null && held === target && held.isConnected) {\n held = null;\n }\n });\n };\n const controller = new AbortController();\n root.addEventListener('focusin', onFocusIn, { signal: controller.signal });\n root.addEventListener('focusout', onFocusOut, { signal: controller.signal });\n inject(DestroyRef).onDestroy(() => controller.abort());\n\n afterEveryRender(() => {\n const departed = held;\n if (departed === null || departed.isConnected) {\n return;\n }\n held = null;\n if (options.skip?.(departed) === true) {\n return;\n }\n const active = roving.active();\n if (active === null) {\n return;\n }\n queueMicrotask(() => {\n const focused = resolveActiveElement(document);\n const lost =\n focused === null || focused === document.body || focused === document.documentElement;\n if (lost && active.isConnected && roving.active() === active) {\n active.focus();\n }\n });\n });\n}\n","import type { CollectionHandle } from '../collection/collection';\nimport {\n type ListNavigationAction,\n type ListNavigationOptions,\n moveIndex,\n resolveListNavigation,\n} from '../keyboard-navigation/keyboard-navigation';\nimport type { RovingTabindex } from './roving-tabindex';\n\n/** Options for {@link rovingListTarget}. */\nexport interface RovingListTargetOptions {\n /** Wrap around at the ends. Default `false`. */\n loop?: boolean;\n}\n\n/**\n * Resolves the handle a 1D list-navigation action lands on **without skipping\n * disabled items** — the disabled-inclusive twin of `nextEnabledHandle`. Used\n * by roving primitives that keep disabled items keyboard-reachable per the\n * WAI-ARIA APG (a disabled control stays focusable so assistive tech announces\n * it; activation is guarded separately by the caller).\n *\n * `current` may be the currently focused host element or an explicit index.\n * When a host is passed it is located via its `host` property; a host not\n * present in `items` is treated as index `0`. When an index is passed it is\n * used verbatim (no clamp).\n *\n * Returns the resolved handle, or `null` when the list is empty or no target\n * exists in the requested direction (e.g. `loop=false` past the end).\n */\nexport function rovingListTarget<H extends CollectionHandle>(\n items: readonly H[],\n current: HTMLElement | number,\n action: ListNavigationAction,\n options: RovingListTargetOptions = {},\n): H | null {\n if (items.length === 0) {\n return null;\n }\n let currentIndex: number;\n if (typeof current === 'number') {\n currentIndex = current;\n } else {\n const found = items.findIndex((item) => item.host === current);\n currentIndex = found < 0 ? 0 : found;\n }\n const next = moveIndex(currentIndex, items.length, action, { loop: options.loop ?? false });\n return next === null ? null : (items[next] ?? null);\n}\n\n/** Options for {@link selectionTabStop}. */\nexport interface SelectionTabStopOptions {\n /**\n * Whether this item is disabled. A disabled item never owns the Tab stop,\n * so it always resolves to `-1` (while staying arrow-reachable via\n * {@link rovingListTarget}).\n */\n disabled: boolean;\n /** Whether this item is the selected / current one. */\n selected: boolean;\n /** Whether some enabled item in the group is selected / current. */\n hasSelected: boolean;\n /** Whether this item is the first enabled entry-point fallback. */\n isFirstEnabled: boolean;\n /**\n * Whether every item of the group yields the Tab stop because a disabled item\n * holds DOM focus, so `Tab` leaves the group from it. Default `false`.\n */\n yields?: boolean;\n}\n\n/** Options for {@link rovingTabStop}. */\nexport interface RovingTabStopOptions extends SelectionTabStopOptions {\n /** The group's roving tracker. */\n roving: RovingTabindex;\n /** This item's host element (queried against the roving tracker). */\n host: HTMLElement;\n}\n\n/**\n * Computes the **selection-driven** half of the tab-stop ladder — the rungs a\n * group owns when its single Tab entry point is defined by its selection rather\n * than by which item the user last focused. Returns `0` (Tab entry point) or\n * `-1` (arrow-reachable only):\n *\n * - disabled, or the group yields to a focused disabled item → `-1`.\n * - selected / current → `0`.\n * - another item owns the current selection → `-1`.\n * - otherwise the first enabled item → `0`, else `-1`.\n *\n * The third rung is what keeps a selection pointing at a disabled or absent item from taking the\n * whole group out of the tab order.\n *\n * `[forRadio]` is the one caller that uses this alone. Selection follows focus\n * in the WAI-ARIA Radio Group pattern, so a radio group has no user-driven\n * roving pointer to consult — see {@link rovingTabStop} for the groups that do.\n */\nexport function selectionTabStop(options: SelectionTabStopOptions): 0 | -1 {\n const { disabled, selected, hasSelected, isFirstEnabled, yields } = options;\n if (disabled || yields === true) {\n return -1;\n }\n if (selected) {\n return 0;\n }\n if (hasSelected) {\n return -1;\n }\n return isFirstEnabled ? 0 : -1;\n}\n\n/**\n * Computes the roving-tabindex ladder shared by every roving list primitive:\n * {@link selectionTabStop}'s rungs with the user-driven roving pointer taking\n * precedence over them once any item has been focused.\n *\n * - disabled → `-1` (never the Tab entry point, but still arrow-reachable).\n * - the roving tracker owns the tab stop → `roving.tabindexFor(host)`.\n * - otherwise the selection rungs of {@link selectionTabStop}.\n */\nexport function rovingTabStop(options: RovingTabStopOptions): 0 | -1 {\n const { roving, host, ...selection } = options;\n if (selection.disabled) {\n return -1;\n }\n if (roving.hasActive()) {\n return roving.tabindexFor(host);\n }\n return selectionTabStop(selection);\n}\n\n/** Options for {@link navigateFromRovingItem}. */\nexport interface RovingItemNavigationOptions extends ListNavigationOptions {\n /**\n * Whether the whole group is disabled, which leaves every navigation key\n * unconsumed. The item's own disabled state is deliberately not an option.\n */\n groupDisabled: boolean;\n /** Moves focus from the item for the resolved action. */\n navigate: (action: ListNavigationAction) => void;\n}\n\n/**\n * Handles the list-navigation keys (arrows, `Home` / `End`, and `PageUp` /\n * `PageDown` when `pageKeys` is set) on a roving item: consumes the key and\n * hands the action to `navigate`. Returns whether the key was handled.\n *\n * Gated on the group only. A disabled item keeps focus, so an item that becomes\n * disabled while it holds focus must still let the keyboard user leave it;\n * every caller guards its own activation keys separately.\n */\nexport function navigateFromRovingItem(\n event: KeyboardEvent,\n options: RovingItemNavigationOptions,\n): boolean {\n if (options.groupDisabled) {\n return false;\n }\n const action = resolveListNavigation(event, options);\n if (action === null) {\n return false;\n }\n event.preventDefault();\n options.navigate(action);\n return true;\n}\n\n/** Options for {@link handleDisabledRovingItemKey}. */\nexport interface DisabledRovingItemKeyOptions extends RovingItemNavigationOptions {\n /**\n * Moves focus for a key no navigation action claimed, by typeahead or by an\n * item-specific move. Returns whether the key was handled.\n */\n typeahead: (event: KeyboardEvent) => boolean;\n}\n\n/**\n * Handles a key on an item that is disabled while it holds focus: the\n * list-navigation keys of {@link navigateFromRovingItem}, then `typeahead`.\n * Activation and commit keys are left unconsumed, so the caller handles\n * nothing else from a disabled item. Gated on the group only. Returns whether\n * the key was handled.\n */\nexport function handleDisabledRovingItemKey(\n event: KeyboardEvent,\n options: DisabledRovingItemKeyOptions,\n): boolean {\n if (navigateFromRovingItem(event, options)) {\n return true;\n }\n if (options.groupDisabled) {\n return false;\n }\n return options.typeahead(event);\n}\n","import { signal, type Signal } from '@angular/core';\n\nimport { nextEnabledHandle } from '../collection/enabled-handle-navigation';\nimport { appendMissing, isInArray, membership, toggleInArray } from './selection';\nimport { isUnset, type Unset } from '../unset-input/unset-input';\n\n/**\n * Minimal option-handle shape the range-selection algorithm needs: a host\n * element to focus, the option's `value` signal, and a `disabled` signal to\n * skip. Both `ForListboxOptionHandle` and `ForSelectOptionHandle` widen this\n * with their own per-option fields (id, label, posInSet, …).\n *\n * @typeParam T Option value type.\n */\nexport interface RangeSelectionOptionHandle<T> {\n readonly host: HTMLElement;\n readonly value: Signal<T | Unset>;\n readonly disabled: Signal<boolean>;\n}\n\n/**\n * Construction-time wiring for {@link RangeSelectionEngine}. Plain signals and\n * a value setter only — the engine never imports a primitive's context token,\n * mirroring the `ListboxOverlayController` precedent, so it stays orthogonal to\n * each root's surface.\n *\n * @typeParam T Option value type.\n * @typeParam H Primitive option-handle type.\n */\nexport interface RangeSelectionEngineDeps<T, H extends RangeSelectionOptionHandle<T>> {\n /** All registered options, in DOM (rendered) order. */\n readonly options: Signal<readonly H[]>;\n /** The control's current selection. */\n readonly value: Signal<readonly T[]>;\n /** Commit a new selection array. */\n readonly setValue: (value: readonly T[]) => void;\n /** Compare two items for equality (`===` for primitives, custom for objects). */\n readonly compareWith: Signal<(a: T, b: T) => boolean>;\n /** Whether multiple options can be selected. Range actions are no-ops in single mode. */\n readonly multiple: Signal<boolean>;\n /** The control's effective disabled — gates every action. */\n readonly effectiveDisabled: Signal<boolean>;\n /** Whether the control is read-only — focus still moves, selection mutation is blocked. */\n readonly readonly: Signal<boolean>;\n readonly reveal: (host: HTMLElement) => void;\n}\n\n/**\n * The APG multi-select range-selection state machine shared by `ForListbox` and\n * `ForSelect`. Owns the range anchor and implements the range keyboard actions\n * (Shift+Arrow, Shift+Space, Ctrl/Cmd+A, Ctrl+Shift+Home/End) plus the\n * single-mode idempotent select guard — the blocks both roots used to duplicate\n * verbatim. The option source and value model differ between the two roots, so\n * they are threaded in through {@link RangeSelectionEngineDeps}.\n *\n * Every action skips an option seeded with the `unsetInput` sentinel: its\n * `[value]` binding has not been written yet, so there is no value to select and\n * handing the sentinel to `compareWith` would leak it to the consumer.\n *\n * Internal — lives in `forty-cdk/core`, consumed only by the primitives that\n * compose it; carries no semver guarantees.\n *\n * @typeParam T Option value type.\n * @typeParam H Primitive option-handle type.\n */\nexport class RangeSelectionEngine<T, H extends RangeSelectionOptionHandle<T>> {\n readonly #deps: RangeSelectionEngineDeps<T, H>;\n\n /**\n * Anchor value for APG range-selection actions (Shift+Space). Stored as the\n * option's *value* (resolved to its current index at range time via\n * `compareWith`) rather than a DOM index, so reordering or removing\n * options before the anchor can't silently shift the range to the wrong span.\n */\n readonly #anchorValue = signal<T | null>(null);\n\n constructor(deps: RangeSelectionEngineDeps<T, H>) {\n this.#deps = deps;\n }\n\n /**\n * Set the range anchor. Both roots call this on every unmodified activation\n * (click / Space / Enter); it is not touched by Shift+Arrow, which APG defines\n * as a per-option toggle.\n */\n setAnchor(value: T): void {\n this.#anchorValue.set(value);\n }\n\n /**\n * Single-mode idempotent select: replace the selection with `[value]`, but\n * skip the redundant set (and its `valueChange` emission) when the same sole\n * value is already selected. No disabled / readonly guard — the caller applies\n * it before delegating.\n */\n selectSingle(value: T | Unset): void {\n if (isUnset(value)) {\n return;\n }\n const current = this.#deps.value();\n if (current.length === 1 && isInArray(current, value, this.#deps.compareWith())) {\n return;\n }\n this.#deps.setValue([value]);\n }\n\n /**\n * APG \"Shift+ArrowDown / Shift+ArrowUp\": move focus to the next / previous\n * enabled option and toggle its selected state, without moving the range\n * anchor. Non-wrapping. No-op in single mode or when disabled. Focus still\n * moves under `readonly`; only the selection mutation is blocked. Focus also\n * still moves onto an option whose `[value]` binding has not landed yet; only\n * its selection is skipped, since the value is not knowable.\n */\n extendByArrow(currentOption: HTMLElement, action: 'next' | 'prev'): void {\n if (this.#deps.effectiveDisabled() || !this.#deps.multiple()) {\n return;\n }\n const target = nextEnabledHandle(this.#deps.options(), currentOption, action, { loop: false });\n if (target === null) {\n return;\n }\n this.#deps.reveal(target.host);\n if (this.#deps.readonly()) {\n return;\n }\n const targetValue = target.value();\n if (isUnset(targetValue)) {\n return;\n }\n this.#deps.setValue(toggleInArray(this.#deps.value(), targetValue, this.#deps.compareWith()));\n }\n\n /**\n * APG \"Shift+Space\": select every enabled option from the anchor (set on the\n * most recent unmodified activation) up to and including `currentOption`,\n * preserving any selection outside the span. Falls back to selecting just the\n * focused option when no anchor exists. No-op in single mode, disabled, or\n * readonly.\n */\n selectRangeToFocused(currentOption: HTMLElement): void {\n if (this.#deps.effectiveDisabled() || this.#deps.readonly() || !this.#deps.multiple()) {\n return;\n }\n const options = this.#deps.options();\n const currentIndex = options.findIndex((o) => o.host === currentOption);\n if (currentIndex < 0) {\n return;\n }\n const anchorValue = this.#anchorValue();\n const equals = this.#deps.compareWith();\n const anchorIndex =\n anchorValue === null\n ? -1\n : options.findIndex((o) => {\n const v = o.value();\n return !isUnset(v) && equals(v, anchorValue);\n });\n const start = anchorIndex < 0 ? currentIndex : anchorIndex;\n const [lo, hi] = start <= currentIndex ? [start, currentIndex] : [currentIndex, start];\n\n const span: T[] = [];\n for (let i = lo; i <= hi; i++) {\n const opt = options[i];\n if (!opt || opt.disabled()) {\n continue;\n }\n const v = opt.value();\n if (!isUnset(v)) {\n span.push(v);\n }\n }\n this.#deps.setValue(appendMissing(this.#deps.value(), span, equals));\n }\n\n /**\n * APG \"Ctrl/Cmd+A\": add every enabled option to the selection, or remove them\n * when they are all already selected (toggle). Selected values that are not an\n * enabled rendered option (a disabled option, one hidden by a filter) are kept\n * either way. An option whose `[value]` binding has not landed yet is left\n * out. No-op in single mode, disabled, or readonly.\n */\n selectAll(): void {\n if (this.#deps.effectiveDisabled() || this.#deps.readonly() || !this.#deps.multiple()) {\n return;\n }\n const enabled: T[] = [];\n for (const opt of this.#deps.options()) {\n if (opt.disabled()) {\n continue;\n }\n const v = opt.value();\n if (isUnset(v)) {\n continue;\n }\n enabled.push(v);\n }\n if (enabled.length === 0) {\n return;\n }\n const equals = this.#deps.compareWith();\n const current = this.#deps.value();\n if (enabled.every(membership(current, equals))) {\n const isEnabled = membership(enabled, equals);\n this.#deps.setValue(current.filter((x) => !isEnabled(x)));\n return;\n }\n this.#deps.setValue(appendMissing(current, enabled, equals));\n }\n\n /**\n * APG \"Ctrl+Shift+Home / Ctrl+Shift+End\": select every enabled option from\n * `currentOption` (inclusive) to the first / last enabled option, and move\n * focus to that edge, preserving any selection outside the span. No-op in\n * single mode or when disabled. Focus still moves under `readonly`; only the\n * selection mutation is blocked.\n */\n selectFromCurrentToEdge(currentOption: HTMLElement, edge: 'first' | 'last'): void {\n if (this.#deps.effectiveDisabled() || !this.#deps.multiple()) {\n return;\n }\n const options = this.#deps.options();\n const currentIndex = options.findIndex((o) => o.host === currentOption);\n if (currentIndex < 0) {\n return;\n }\n const [lo, hi] = edge === 'first' ? [0, currentIndex] : [currentIndex, options.length - 1];\n\n const span: T[] = [];\n let firstEnabled: HTMLElement | null = null;\n let lastEnabled: HTMLElement | null = null;\n for (let i = lo; i <= hi; i++) {\n const opt = options[i];\n if (!opt || opt.disabled()) {\n continue;\n }\n const v = opt.value();\n if (!isUnset(v)) {\n span.push(v);\n }\n if (firstEnabled === null) {\n firstEnabled = opt.host;\n }\n lastEnabled = opt.host;\n }\n const edgeFocusTarget = edge === 'first' ? firstEnabled : lastEnabled;\n if (edgeFocusTarget !== null) {\n this.#deps.reveal(edgeFocusTarget);\n }\n if (this.#deps.readonly()) {\n return;\n }\n this.#deps.setValue(appendMissing(this.#deps.value(), span, this.#deps.compareWith()));\n }\n}\n","/**\n * Pointer-based swipe-to-dismiss helper.\n *\n * Used by `ForToast`, `ForDrawer` (via its drag engine), and `ForCarousel`\n * (via its drag directive): a horizontal / vertical drag that, released past\n * the configured threshold, triggers a dismissal.\n *\n * The helper keeps no Angular DI surface — it's a plain function that attaches\n * listeners to an `HTMLElement` and returns a cleanup function. Callers wire it\n * through the directive's `DestroyRef`.\n *\n * It is a thin **domain layer over `createPointerDragSession`**: the session\n * owns the transport (the host `pointerdown` capture, the document-level\n * `pointermove` / `pointerup` / `pointercancel` capture listeners, the\n * `pointerId` filter, pointer capture, and the post-drag click suppression),\n * while this helper owns the swipe semantics on top of it — dominant-axis\n * direction detection, the constrained delta, the release-threshold split, and\n * the reactive mid-gesture directions abort.\n *\n * Behavior summary:\n * - The start position is recorded on `pointerdown` but no swipe is announced\n * yet, so a plain tap fires nothing. A press with no allowed direction, and a\n * non-primary mouse button, are rejected before tracking begins.\n * - Once the drag travels past an internal arm distance the dominant axis picks\n * the candidate direction; if it is not in the allowed set the press keeps\n * watching — it stays tracked and unarmed, re-checking the dominant axis on\n * every further move — instead of arming. A mouse move seen with no button held\n * is a press released off-element (no `pointerup` reached it) and does not arm a\n * phantom swipe.\n * - On arming, `onSwipeStart` fires (with the constrained delta) and\n * `onSwipeMove` fires for every move including the arming one. `getDirections()`\n * is re-read on every armed move: if the active direction is toggled out of the\n * allowed set mid-gesture the swipe aborts (`onSwipeCancel` fires).\n * - On `pointerup`, if the projection along the active direction reaches\n * `getThreshold()`, `onSwipeEnd` fires; otherwise `onSwipeCancel` fires.\n * - On `pointercancel`, `onSwipeCancel` fires when the gesture had armed.\n *\n * Movement perpendicular to the active direction is clamped to `0`, and movement\n * opposite to the direction is clamped to `0` as well — the consumer's CSS only\n * ever sees a non-negative push along the dismissal axis, so animations stay\n * simple.\n */\n\nimport { resolveEventTarget } from '../composed-tree/composed-tree';\nimport { createPointerDragSession, type PointerDragSession } from '../drag-session/pointer-session';\nimport {\n type DragAxes,\n dragSurfaceTouchAction,\n type DragTouchAction,\n} from '../drag-session/drag-touch-action';\n\n/** A single swipe direction, named after the pointer-travel direction. */\nexport type SwipeDirection = 'left' | 'right' | 'up' | 'down';\n\nexport interface SwipeEventDetail {\n /** The active direction picked by the dominant-axis check. */\n readonly direction: SwipeDirection;\n /**\n * Movement vector relative to the swipe start, in CSS pixels.\n * Constrained: the perpendicular axis is always `0`, and the\n * primary axis is clamped to the half-line that points along\n * `direction` (e.g. `right` → `x >= 0`, `up` → `y <= 0`).\n */\n readonly delta: { readonly x: number; readonly y: number };\n /**\n * The element the press landed on, resolved through open shadow roots.\n * Answer \"where did this gesture start?\" with it rather than with\n * `originalEvent.target`, which belongs to the current move and may have\n * been retargeted to a shadow host.\n */\n readonly target: Element | null;\n /** The originating pointer event. */\n readonly originalEvent: PointerEvent;\n}\n\nexport interface SwipeDismissOptions {\n /** Element listening for pointer events. */\n readonly element: HTMLElement;\n /**\n * Reactive getter for the allowed swipe directions. Returning an\n * empty array disables swipe entirely (a dynamically-toggled\n * direction is the canonical \"off switch\").\n */\n readonly getDirections: () => readonly SwipeDirection[];\n /** Reactive getter for the dismiss threshold in CSS pixels. */\n readonly getThreshold: () => number;\n /**\n * Pre-arm predicate consulted once per gesture, after the dominant-axis\n * direction has been picked but before the session arms or captures the\n * pointer. Return `false` to decline this gesture: the underlying pointer\n * session is aborted, so the pointer is never captured and no post-release\n * click trap is installed, leaving native text selection / inner scrolling\n * intact for the rest of the press. Omit it to always begin.\n */\n readonly canBegin?: (detail: SwipeEventDetail) => boolean;\n readonly onSwipeStart?: (detail: SwipeEventDetail) => void;\n readonly onSwipeMove?: (detail: SwipeEventDetail) => void;\n /** Pointer-up while projection along direction `>= threshold`. */\n readonly onSwipeEnd?: (detail: SwipeEventDetail) => void;\n /** Pointer-up before threshold, or pointer-cancel. */\n readonly onSwipeCancel?: (detail: SwipeEventDetail) => void;\n}\n\nconst ARM_DISTANCE_PX = 4;\n\nfunction detectDirection(\n dx: number,\n dy: number,\n allowed: readonly SwipeDirection[],\n): SwipeDirection | null {\n const ax = Math.abs(dx);\n const ay = Math.abs(dy);\n if (ax < ARM_DISTANCE_PX && ay < ARM_DISTANCE_PX) {\n return null;\n }\n const candidate: SwipeDirection =\n ax >= ay ? (dx >= 0 ? 'right' : 'left') : dy >= 0 ? 'down' : 'up';\n return allowed.includes(candidate) ? candidate : null;\n}\n\nfunction projection(dx: number, dy: number, dir: SwipeDirection): number {\n switch (dir) {\n case 'right':\n return dx;\n case 'left':\n return -dx;\n case 'down':\n return dy;\n case 'up':\n return -dy;\n }\n}\n\nfunction constrainedDelta(dx: number, dy: number, dir: SwipeDirection): { x: number; y: number } {\n switch (dir) {\n case 'right':\n return { x: Math.max(0, dx), y: 0 };\n case 'left':\n return { x: Math.min(0, dx), y: 0 };\n case 'down':\n return { x: 0, y: Math.max(0, dy) };\n case 'up':\n return { x: 0, y: Math.min(0, dy) };\n }\n}\n\nfunction elementOf(node: Node | null): Element | null {\n return node === null || node instanceof Element ? node : node.parentElement;\n}\n\n/**\n * Cutoff (ms) past which a flick's last velocity sample is considered stale.\n * A release whose last `pointermove` sample is older than this — a fast final\n * move followed by a hold-still before lifting — must not carry the stale\n * sample into the release decision. Consumed by {@link flickVelocity}.\n */\nexport const FLICK_STALE_VELOCITY_MS = 100;\n\n/**\n * Release speed (CSS px/ms) past which a gesture counts as a deliberate flick\n * rather than a slow position drag. A release at or above it resolves toward\n * the flick direction from where the gesture was let go, instead of to the\n * nearest target.\n *\n * Shared by every swipe-driven resolution in the library — `ForCarousel`'s\n * drag directive (`resolveDragIndex`), `ForDrawer`'s no-snap-points dismiss\n * check, and `resolveSnapTarget`'s velocity bias — so the \"intentional flick\"\n * semantics stay identical across the library.\n */\nexport const FLICK_VELOCITY_PX_PER_MS = 0.4;\n\n/**\n * Zeroes the flick velocity when the release is stale — its last `pointermove`\n * sample is older than {@link FLICK_STALE_VELOCITY_MS} — so a fast final move\n * followed by a hold-still before lifting can't carry the stale sample into the\n * release decision. Returns the effective velocity the caller feeds into its\n * snap / dismiss resolution.\n *\n * Shared by the swipe-driven primitives (`ForDrawer`'s drag engine and\n * `ForCarousel`'s drag directive) so the staleness rule stays identical across\n * the library.\n */\nexport function flickVelocity(rawVelocity: number, stale: boolean): number {\n return stale ? 0 : rawVelocity;\n}\n\n/**\n * The `touch-action` a surface swiping in `directions` needs: the browser keeps\n * the axis no direction uses (`pan-y` for `left` / `right`, `pan-x` for `up` /\n * `down`, `none` once both axes swipe), so a finger moving along a swipe axis\n * reaches the pointer handlers instead of being claimed as a pan, which would\n * end the gesture with `pointercancel`. An axis the surface itself scrolls on\n * (`hostScrolls`, as `injectHostScrollAxes` measures it) stays with the browser\n * too, so a scrollable surface keeps its own touch scrolling. `null` when\n * there is no direction, so an idle surface leaves the browser's default in\n * place.\n */\nexport function swipeTouchAction(\n directions: readonly SwipeDirection[],\n hostScrolls: DragAxes,\n): DragTouchAction {\n return dragSurfaceTouchAction({\n armable: directions.length > 0,\n handles: false,\n axes: {\n x: directions.some((d) => d === 'left' || d === 'right'),\n y: directions.some((d) => d === 'up' || d === 'down'),\n },\n hostScrolls,\n });\n}\n\n/**\n * Attach swipe-dismiss listeners to `opts.element`. Returns a cleanup\n * function that tears down the underlying pointer-drag session (every\n * listener and any pending click trap).\n */\nexport function attachSwipeDismiss(opts: SwipeDismissOptions): () => void {\n const el = opts.element;\n let startX = 0;\n let startY = 0;\n let pressTarget: Element | null = null;\n let direction: SwipeDirection | null = null;\n\n const detailFor = (event: PointerEvent, dir: SwipeDirection): SwipeEventDetail => ({\n direction: dir,\n delta: constrainedDelta(event.clientX - startX, event.clientY - startY, dir),\n target: pressTarget,\n originalEvent: event,\n });\n\n const session: PointerDragSession = createPointerDragSession({\n host: el,\n document: el.ownerDocument,\n armThreshold: ARM_DISTANCE_PX,\n capturePointer: true,\n canStart: (event) => {\n if (event.pointerType === 'mouse' && event.button !== 0) {\n return false;\n }\n if (opts.getDirections().length === 0) {\n return false;\n }\n startX = event.clientX;\n startY = event.clientY;\n pressTarget = elementOf(resolveEventTarget(event));\n direction = null;\n return true;\n },\n onLift: (event) => {\n if (event.pointerType === 'mouse' && event.buttons === 0) {\n return false;\n }\n const dir = detectDirection(\n event.clientX - startX,\n event.clientY - startY,\n opts.getDirections(),\n );\n if (!dir) {\n return 'skip';\n }\n const detail = detailFor(event, dir);\n if (opts.canBegin && !opts.canBegin(detail)) {\n return false;\n }\n direction = dir;\n opts.onSwipeStart?.(detail);\n return true;\n },\n onMove: (event) => {\n if (!direction) {\n return;\n }\n if (!opts.getDirections().includes(direction)) {\n session.cancel(event);\n return;\n }\n opts.onSwipeMove?.(detailFor(event, direction));\n },\n onCommit: (event) => {\n if (!direction) {\n return;\n }\n const dir = direction;\n direction = null;\n const proj = projection(event.clientX - startX, event.clientY - startY, dir);\n if (proj >= opts.getThreshold()) {\n opts.onSwipeEnd?.(detailFor(event, dir));\n } else {\n opts.onSwipeCancel?.(detailFor(event, dir));\n }\n },\n onCancel: (event) => {\n if (direction && event) {\n opts.onSwipeCancel?.(detailFor(event, direction));\n }\n direction = null;\n },\n });\n\n return () => session.destroy();\n}\n","import { computed, type Signal } from '@angular/core';\n\nimport { injectPrefersReducedMotion } from '../media-query/media-query';\n\n/**\n * The reduced-motion policy shared by every surface built on\n * `attachSwipeDismiss`. Under `prefers-reduced-motion: reduce` the gesture\n * stays armed, commits on release (snap, dismiss, advance) and fires its swipe\n * outputs, but the surface publishes no movement that follows the finger: every\n * value routed through {@link SwipeMotion.follow} reads `0`.\n */\nexport interface SwipeMotion {\n /** `false` while the user asks for reduced motion. */\n readonly enabled: Signal<boolean>;\n /**\n * The value a surface publishes for a live, finger-following quantity (a\n * displacement in px, a progress fraction): `value` while motion is enabled,\n * `0` under reduced motion. Reads {@link enabled}, so a `computed` or host\n * binding calling it follows a runtime change of the preference.\n */\n readonly follow: (value: number) => number;\n}\n\n/**\n * Resolve the {@link SwipeMotion} policy for a swipe surface. Must be called\n * from an injection context. SSR-safe: the server reads motion as enabled.\n */\nexport function injectSwipeMotion(): SwipeMotion {\n const reducedMotion = injectPrefersReducedMotion();\n const enabled = computed(() => !reducedMotion());\n return { enabled, follow: (value) => (enabled() ? value : 0) };\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport { DestroyRef, ElementRef, PLATFORM_ID, inject, type Signal } from '@angular/core';\n\n/** Configuration for {@link injectDisabledClickGuard}. */\nexport interface DisabledClickGuardConfig {\n /** While truthy, a click on the host or on any of its descendants is cancelled. */\n disabled: Signal<boolean>;\n\n /**\n * Also cancel a middle-button `auxclick` while disabled, so a disabled link\n * cannot be opened in a new tab. Other buttons' `auxclick` pass through.\n */\n middleClick?: boolean;\n}\n\n/**\n * Cancels every click on a disabled host that stays focusable, which is why it\n * carries `aria-disabled` rather than the native `disabled` attribute.\n *\n * While `disabled()` is true, a capture-phase listener on the host calls\n * `preventDefault()` and `stopImmediatePropagation()` on each `click` (and, with\n * `middleClick`, each middle-button `auxclick`). Capture on the host runs before\n * every bubble-phase listener on the host and its descendants, so no `(click)`\n * binding on the element runs, whether a directive's host listener or the\n * consumer's template, and neither does any listener on an ancestor.\n *\n * Inert on the server. Must be called from an injection context.\n */\nexport function injectDisabledClickGuard(config: DisabledClickGuardConfig): void {\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n return;\n }\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const controller = new AbortController();\n const options = { capture: true, signal: controller.signal };\n\n const cancel = (event: MouseEvent): void => {\n if (!config.disabled()) {\n return;\n }\n event.preventDefault();\n event.stopImmediatePropagation();\n };\n\n host.addEventListener('click', cancel, options);\n if (config.middleClick) {\n host.addEventListener(\n 'auxclick',\n (event: MouseEvent) => {\n if (event.button === 1) {\n cancel(event);\n }\n },\n options,\n );\n }\n\n inject(DestroyRef).onDestroy(() => controller.abort());\n}\n","import { ElementRef, inject, signal, type Signal } from '@angular/core';\n\n/** Configuration for {@link injectSyntheticActivation}. */\nexport interface SyntheticActivationConfig {\n /**\n * Reactive disabled state gating the synthesized activation. While truthy the\n * handlers never click the host, but `Space` keydown still calls\n * `preventDefault()` so a disabled control does not scroll the page — the\n * behavior a native `<button>` with `aria-disabled` has.\n */\n disabled?: Signal<boolean>;\n}\n\n/** Surface returned by {@link injectSyntheticActivation}. */\nexport interface SyntheticActivation {\n /**\n * Whether the host is a native `<button>`. The platform then owns activation\n * and tab order, so the synthesis is inert and the caller emits no `role` /\n * `tabindex` of its own.\n */\n readonly nativeButton: boolean;\n\n /**\n * `'0'` on a non-native host, so it is reachable with `Tab`; `null` on a\n * native `<button>`, whose tab stop the platform already owns. Host-bind it\n * as `'[attr.tabindex]': 'tabindex()'`. Disabled hosts keep their tab stop:\n * custom-role controls stay focusable per the APG.\n */\n readonly tabindex: Signal<string | null>;\n\n /** Wire to the host's `(keydown)`. */\n keydown(event: KeyboardEvent): void;\n\n /** Wire to the host's `(keyup)`. */\n keyup(event: KeyboardEvent): void;\n\n /**\n * Wire to the host's `(blur)` / `(focusout)`. Drops a half-finished `Space`\n * press so a `keyup` arriving after focus left cannot activate the control.\n */\n reset(): void;\n}\n\n/**\n * Gives a host that may not be a `<button>` the activation semantics of one:\n * a tab stop plus `Enter` / `Space` synthesis. The keyboard path funnels\n * through `host.click()`, so the caller keeps a single activation handler (its\n * `(click)` listener) regardless of which host element the consumer picked.\n *\n * `Enter` activates on `keydown`, `Space` on `keyup` — matching native button\n * and APG behavior. `Space` keydown always calls `preventDefault()` (even while\n * disabled) to stop the page scrolling, and a `Space` press is only honored\n * when its `keydown` reached the same host.\n *\n * On a native `<button>` every handler returns immediately and `tabindex` is\n * `null`: the platform already synthesizes click from `Enter` / `Space`, so\n * doing it again would double-activate.\n *\n * Callers own their `role`: `[forButton]` emits `role=\"button\"` on a non-native\n * host, while the form primitives (`[forCheckbox]`, `[forSwitch]`) already\n * carry a static `role=\"checkbox\"` / `\"switch\"` on every host.\n *\n * @example\n * ```ts\n * @Directive({\n * selector: '[myControl]',\n * host: {\n * '[attr.tabindex]': 'tabindex()',\n * '(click)': 'onClick()',\n * '(keydown)': 'onKeydown($event)',\n * '(keyup)': 'onKeyup($event)',\n * '(blur)': 'onBlur()',\n * },\n * })\n * export class MyControl {\n * readonly #activation = injectSyntheticActivation({ disabled: this.disabled });\n * protected readonly tabindex = this.#activation.tabindex;\n * }\n * ```\n */\nexport function injectSyntheticActivation(\n config: SyntheticActivationConfig = {},\n): SyntheticActivation {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const nativeButton = host.tagName === 'BUTTON';\n const isDisabled = (): boolean => config.disabled?.() ?? false;\n let spaceHeld = false;\n\n return {\n nativeButton,\n tabindex: signal(nativeButton ? null : '0').asReadonly(),\n keydown(event: KeyboardEvent): void {\n if (nativeButton) {\n return;\n }\n if (event.key === 'Enter') {\n if (isDisabled()) {\n return;\n }\n event.preventDefault();\n host.click();\n return;\n }\n if (event.key === ' ') {\n event.preventDefault();\n if (isDisabled()) {\n return;\n }\n spaceHeld = true;\n }\n },\n keyup(event: KeyboardEvent): void {\n if (nativeButton || event.key !== ' ' || !spaceHeld) {\n return;\n }\n spaceHeld = false;\n if (isDisabled()) {\n return;\n }\n event.preventDefault();\n host.click();\n },\n reset(): void {\n spaceHeld = false;\n },\n };\n}\n","import { InjectionToken, type Signal } from '@angular/core';\n\n/**\n * Handle a `ForTableCell` registers with its parent `ForTableRow`, so the row can\n * order its cells (for `aria-colindex`) and the root can flatten them into the\n * roving-navigation grid (skipping disabled cells).\n */\nexport interface ForTableCellHandle {\n /** The cell's host element (`role=\"cell\"` / `\"gridcell\"`). */\n readonly host: HTMLElement;\n /** Whether this cell is disabled — skipped during arrow-key navigation. */\n readonly disabled: Signal<boolean>;\n}\n\n/**\n * Handle a `ForTableRow` registers with the root `ForTable`, so the root can order\n * rows (for `aria-rowindex`) and build the row-major flat cell grid for navigation.\n */\nexport interface ForTableRowHandle {\n /** The row's host element (`role=\"row\"`). */\n readonly host: HTMLElement;\n /** This row's data cells, in DOM order. */\n readonly cells: Signal<readonly ForTableCellHandle[]>;\n /** This row's selection identity, from its `[value]` input; `undefined` when unset (not selectable). */\n readonly value: Signal<unknown>;\n /** 1-based tree depth of this row (`aria-level`); always `1` outside treegrid mode. */\n readonly level: Signal<number>;\n /** Whether this row is an expandable parent (drives `aria-expanded` / `data-state`). */\n readonly expandable: Signal<boolean>;\n /** Absolute 0-based index of this row in the full (virtualized) dataset, or `null` when not virtualized. */\n readonly virtualIndex: Signal<number | null>;\n}\n\n/**\n * A single row in a {@link TableVirtualWindow}: its absolute dataset index and\n * pixel offset from the start of the scroll range.\n */\nexport interface TableVirtualRow {\n /** Absolute 0-based index of this row in the full dataset. */\n readonly index: number;\n /** Pixel offset of this row from the start of the scroll range. */\n readonly start: number;\n}\n\n/**\n * A rendered virtual window published by `[forTableVirtualized]` for the\n * declarative `<for-table-body>` to render. It lets the body render only the\n * windowed rows — each absolutely positioned inside a full-height sizer —\n * instead of iterating the whole `rows` input, without `forty-cdk/table`\n * importing the virtualization core. Mirrors {@link TableVirtualRowNavigation}:\n * the virtualization companion owns the windowing math and publishes the result\n * through the shared registration surface.\n */\nexport interface TableVirtualWindow {\n /**\n * The rows to render this frame — the visible window plus overscan and the\n * retained focused / reordering rows, each carrying its absolute dataset\n * `index` and pixel `start`. `<for-table-body>` indexes its `rows` input by\n * `index` and positions each row at `translateY(start)`.\n */\n readonly rows: Signal<readonly TableVirtualRow[]>;\n /**\n * Total scroll height of the full dataset in px. Applied to the body's\n * rowgroup so the scrollbar spans the whole set while only the window mounts.\n */\n readonly totalSize: Signal<number>;\n /**\n * Record a stamped row element's real measured height, so the virtualizer\n * replaces the `estimateRowSize` estimate with it and re-aligns the offsets of\n * the rows below. Implemented by `[forTableVirtualized]`; `<for-table-body>`\n * calls it once per stamped row (browser-only, after render) when its\n * `measureRows` input is set, so a window mixing row shapes (denser variant\n * rows, group separators) stays contiguous after scroll. The element must\n * carry the `data-index` attribute a `[forTableRow]` reflects from its\n * `virtualIndex`.\n *\n * `<for-table-body>` also calls it with `null` after measuring the rendered\n * rows to sweep detached rows recycled out of the window, evicting them from\n * the virtualizer's measurement cache so they are not retained/observed until\n * the directive is destroyed.\n */\n measureRow(element: HTMLElement | null): void;\n}\n\n/**\n * Cross-window row-navigation delegate registered by `[forTableVirtualized]`.\n * `ForTable` consults it when a grid keyboard action resolves a row outside the\n * rendered window, keeping the virtualization bridge out of `ForTable` itself.\n */\nexport interface TableVirtualRowNavigation {\n /**\n * Move roving focus to the data cell at the absolute `(rowIndex, 0-based\n * column)`, scrolling that row into the window first when it is not mounted.\n * `direction` (`+1` down / `-1` up) is the travel sense of the originating\n * grid action, so the bridge can step over full-span variant rows — which\n * register no cells — onto the adjacent data row.\n */\n navigateTo(rowIndex: number, column: number, direction: 1 | -1): void;\n /**\n * Scroll the virtualizer so the row at the absolute `index` is in the window.\n * Used by `[forTableRowReorder]` to follow a keyboard reorder target across\n * the rendered window without taking a direct dependency on `ForTableVirtualized`.\n */\n scrollToRow(index: number): void;\n /**\n * Stop a {@link scrollToRow} that is still running. `[forTableRowReorder]` calls it when a\n * pointer drag lifts a row, so the scroll no longer moves the rows under the pointer.\n */\n cancelScroll(): void;\n /**\n * Whether the virtualizer's own window covers the row at the absolute `index`. A row kept\n * mounted only because it is focused or being reordered does not count, so\n * `[forTableRowReorder]` can wait for a scroll it requested to land before it releases a pin.\n */\n isRowInWindow(index: number): boolean;\n /**\n * The bounding rect of the scroll container along the visible viewport, or\n * `null` before it is available. `[forTableRowReorder]` reads it to map a\n * modifier-held pointer drag onto an absolute dataset index (windowed-scrub\n * drop to a far row), without depending on `ForTableVirtualized` directly.\n */\n scrollViewportRect(): DOMRect | null;\n /**\n * The count of rows the virtualizer can place — `[virtualRowCount]`, else the\n * table's resolved row count, else `0`. `ForTable` bounds row-crossing grid\n * actions by it, and `[forTableRowReorder]` its keyboard reorder and drag\n * announcements, rather than by the `aria-rowcount` total, which stays unknown\n * for a windowed grid whose server reports no total.\n */\n placeableRowCount(): number;\n /**\n * Drop any stashed cross-window target. `ForTable` calls this on the next\n * keyboard interaction that reaches the grid, so a pending move set by an\n * earlier Ctrl+End / Page / Arrow is superseded rather than teleporting focus\n * when a far page later mounts.\n */\n clearPending(): void;\n}\n\n/**\n * The table's piece-registration protocol: how header rows, header cells, data\n * rows, the declarative body's row count, the virtualization seams and the\n * resized column widths wire themselves into the `[forTable]` root.\n *\n * **Not** part of `ForTableContext`, and never re-exported from a\n * stable entry point. It lives in the core internal tier — exported from\n * `forty-cdk/core` with no semver guarantee — because\n * `forty-cdk/table-virtualization`'s `[forTableVirtualized]` registers through it from\n * a second entry point, and a consumer must not be able to name — let alone\n * call — the wiring protocol the library refactors freely.\n */\nexport interface TableRegistrationContext {\n /** Registers the header row's host so the root can measure its height for the sticky-header CSS var. */\n registerHeaderRow(el: HTMLElement): void;\n /** Unregisters the header row's host. Reference-based; safe to call if never registered. */\n unregisterHeaderRow(el: HTMLElement): void;\n /**\n * Registers a header cell so it can join the roving-navigation grid as the grid's\n * first row, giving the table a single composite tab stop shared with the data\n * cells. Draggable header cells (`[forTableColumnReorder]`) register the same way so\n * a column-reorderable grid stays a single tab stop. Inert in `mode=\"table\"`, where\n * header cells stay static structure and the row does not join any grid.\n */\n registerHeaderCell(handle: ForTableCellHandle): void;\n /** Unregisters a header cell. Reference-based. */\n unregisterHeaderCell(handle: ForTableCellHandle): void;\n /**\n * Moves roving focus onto the header cell in the 0-based `column`, answering `true`\n * when the header row took the move and `false` when it does not join the composite\n * roving grid (`mode=\"table\"`, no header row, or an incomplete one).\n *\n * It is the header crossing `ForTable` resolves through its own flat cell grid when no\n * virtualizer is involved: `[forTableVirtualized]` calls it when an upward cross-window\n * walk steps over the last full-span variant row above the dataset, since the row above\n * absolute index `0` is the grid's header row.\n */\n focusHeaderCell(column: number): boolean;\n /** Registers a data row so it joins the row index space and the navigation grid. */\n registerRow(handle: ForTableRowHandle): void;\n /** Unregisters a data row. Reference-based. */\n unregisterRow(handle: ForTableRowHandle): void;\n /**\n * Live registered data rows in DOM order. `[forTableVirtualized]` reads this to\n * resolve a pending cross-window navigation once the target row mounts, and\n * `[forTableRowReorder]` to map a pointer target back onto a row handle.\n */\n readonly rows: Signal<readonly ForTableRowHandle[]>;\n /**\n * Registers (or clears, with `null`) the declarative `<for-table-body>`'s dataset\n * length as the body-derived total row count. `ForTableBody` registers\n * `computed(() => rows().length)` at construction and clears it on destroy, so a\n * declarative table needs no `[rowCount]` binding; an explicit `[rowCount]` input\n * still wins over it (for a server-known total larger than the loaded rows).\n */\n registerBodyRowCount(count: Signal<number> | null): void;\n /**\n * Registers (or clears, with `null`) the cross-window row-navigation delegate.\n * `[forTableVirtualized]` registers itself so row-crossing grid keyboard actions\n * targeting an unmounted row are handled by the virtualization bridge.\n */\n registerVirtualNavigation(navigation: TableVirtualRowNavigation | null): void;\n /**\n * The currently registered cross-window row-navigation delegate, or `null`\n * when the table is not virtualized. `[forTableRowReorder]` reads this to gate\n * keyboard reordering to virtualized tables and to scroll the reorder target\n * into view, without taking a direct dependency on `ForTableVirtualized`.\n */\n readonly virtualRowNavigation: Signal<TableVirtualRowNavigation | null>;\n /**\n * Registers (or clears, with `null`) the rendered virtual window.\n * `[forTableVirtualized]` registers itself so the declarative\n * `<for-table-body>` renders only the windowed rows without importing the\n * virtualization core. No-op for tables built from the raw `[forTableRow]`\n * primitives, which render their own window.\n */\n registerVirtualWindow(window: TableVirtualWindow | null): void;\n /**\n * The currently registered virtual window, or `null` when the table is not\n * virtualized (or is built from the raw `[forTableRow]` primitives directly).\n * `<for-table-body>` reads this to switch between rendering the full `rows`\n * input and rendering only the window inside a full-height sizer.\n */\n readonly virtualWindow: Signal<TableVirtualWindow | null>;\n /**\n * Sets (or clears, with `null`) the absolute index of the row being\n * pointer-reordered. Called by `[forTableRowReorder]`; read by\n * `[forTableVirtualized]` to retain the lifted row in the rendered window.\n */\n setReorderingRow(index: number | null): void;\n /**\n * Absolute index of the row currently being pointer-reordered (set by\n * `[forTableRowReorder]` on lift, cleared on release), or `null` when no row is\n * being reordered. `[forTableVirtualized]` keeps this row mounted for the\n * duration of the drag so auto-scroll cannot unmount the lifted row and desync\n * the emitted drop indices. `null` and unused outside a virtualized table.\n */\n readonly reorderingRowIndex: Signal<number | null>;\n /**\n * Publishes a column's resolved width as the CSS custom property\n * `--for-table-col-<column>-width` on the table root, so the consumer's layout\n * can apply it. Called by `[forTableColumnResizer]`.\n */\n setColumnWidth(column: string, width: number): void;\n /**\n * Removes a column's published `--for-table-col-<column>-width` custom property\n * from the table root. Called by `[forTableColumnResizer]` when its width resets\n * to `undefined` or the handle is destroyed, so a stale track var cannot survive\n * a width reset or resurrect when the column is re-added.\n */\n removeColumnWidth(column: string): void;\n}\n\n/**\n * A row's cell-registration protocol: how `[forTableCell]` joins its\n * `[forTableRow]` so the row can order its cells for `aria-colindex` and the\n * root can flatten them into the roving grid.\n *\n * Lives here beside {@link TableRegistrationContext} rather than in\n * `forty-cdk/table`, so `ForTableCellHandle` never has to surface in the table\n * entry point's emitted types — the row's public read surface stays free of it.\n */\nexport interface TableRowRegistrationContext {\n /** Registers a data cell with this row. */\n registerCell(handle: ForTableCellHandle): void;\n /** Unregisters a data cell. Reference-based. */\n unregisterCell(handle: ForTableCellHandle): void;\n}\n\n/** DI token carrying a row's {@link TableRowRegistrationContext}. Provided by `[forTableRow]`. */\nexport const TABLE_ROW_REGISTRATION_CONTEXT = new InjectionToken<TableRowRegistrationContext>(\n 'TABLE_ROW_REGISTRATION_CONTEXT',\n);\n\n/** DI token carrying the table's {@link TableRegistrationContext}. Provided by `[forTable]`. */\nexport const TABLE_REGISTRATION_CONTEXT = new InjectionToken<TableRegistrationContext>(\n 'TABLE_REGISTRATION_CONTEXT',\n);\n","/** State of the typeahead buffer at the moment a match is resolved. */\nexport interface TypeaheadMatchQuery {\n /** The accumulated typeahead buffer. Matched case- and diacritics-insensitively. */\n readonly buffer: string;\n /**\n * Whether the buffer is a single character pressed repeatedly (`\"c\"`,\n * `\"cc\"`, …), per `Typeahead.isRepeatedChar()`. When `true` the match cycles\n * to the next same-initial option after `anchorIndex`; when `false` it\n * prefix-matches from `anchorIndex` inclusive (or the top when unanchored).\n */\n readonly repeated: boolean;\n /**\n * Index of the currently-anchored option (the focused / active one), or `-1`\n * when nothing is anchored. The cycle starts just after it; the prefix scan\n * starts at it (clamped to `0`).\n */\n readonly anchorIndex: number;\n}\n\n/**\n * Folds text to a case- and diacritics-insensitive form for typeahead\n * matching: decomposes accented characters (`NFD`), strips the combining\n * diacritical marks, and lowercases, so `\"e\"` matches `\"Évora\"`. Shared by\n * `findTypeaheadMatch` and Combobox's inline autocomplete, the one call site\n * that runs its own prefix matching, so every collection typeahead and\n * Combobox behave alike for accented text.\n *\n * @param text Raw text to fold (an option label or the typed buffer).\n */\nexport function foldTypeaheadText(text: string): string {\n return text\n .normalize('NFD')\n .replace(/\\p{Diacritic}/gu, '')\n .toLowerCase();\n}\n\n/**\n * The option-level typeahead match shared by Select and Listbox (DOM-focus and\n * virtualized paths). Scans `options` from the anchor, skipping disabled\n * options, and returns the first whose text starts with the query — matching\n * the WAI-ARIA APG typeahead behaviour:\n *\n * - A single character pressed repeatedly (`repeated`) cycles to the next\n * same-initial option after the anchor and wraps around.\n * - A distinct multi-character prefix re-anchors on the current option\n * (inclusive) so a growing prefix keeps it when it still matches.\n * - Both fall back to the top when nothing is anchored (`anchorIndex < 0`).\n *\n * Text and query are compared trimmed, case-insensitively, and\n * diacritics-insensitively (accents are folded via `foldTypeaheadText`).\n * Returns the matching option, or `null` when none matches (or the buffer is\n * empty).\n *\n * @typeParam H Option handle type.\n * @param options Live options to scan, in document order.\n * @param query Buffer state at the moment of the match.\n * @param getText Resolves an option's match text (e.g. its `textContent`), or\n * several candidate texts, any of which may match.\n * @param isDisabled Whether an option is skipped.\n */\nexport function findTypeaheadMatch<H>(\n options: readonly H[],\n query: TypeaheadMatchQuery,\n getText: (option: H) => string | readonly string[],\n isDisabled: (option: H) => boolean,\n): H | null {\n const buffer = foldTypeaheadText(query.buffer);\n if (!buffer || options.length === 0) {\n return null;\n }\n const needle = query.repeated ? buffer[0]! : buffer;\n const start = query.repeated ? query.anchorIndex + 1 : Math.max(query.anchorIndex, 0);\n for (let offset = 0; offset < options.length; offset++) {\n const option = options[(start + offset) % options.length]!;\n if (isDisabled(option)) {\n continue;\n }\n const text = getText(option);\n const candidates = typeof text === 'string' ? [text] : text;\n if (candidates.some((c) => foldTypeaheadText(c.trim()).startsWith(needle))) {\n return option;\n }\n }\n return null;\n}\n","import { fortyError } from '../errors/errors';\nimport {\n type ListOrientation,\n resolveListNavigation,\n type WritingDirection,\n} from '../keyboard-navigation/keyboard-navigation';\nimport { findTypeaheadMatch } from './match-options';\nimport type { Typeahead } from './typeahead';\n\n/** Orientation / direction context {@link isRangeSelectShortcut} reads to resolve arrow intent. */\nexport interface RangeSelectShortcutContext {\n /** The list's navigation orientation. */\n readonly orientation: ListOrientation;\n /** The list's resolved writing direction. */\n readonly dir: WritingDirection;\n}\n\n/**\n * Whether a keydown is one of the APG multi-select range-selection shortcuts:\n * Ctrl/Cmd+A (select all), Ctrl+Shift+Home / End (range to edge), Shift+Space\n * (range to focused), or Shift+Arrow along the list axis (extend by one).\n * `Alt` disqualifies every combination. Shared by the virtualized keydown\n * handlers of Listbox and Select to detect an unsupported range action before\n * throwing.\n */\nexport function isRangeSelectShortcut(\n event: KeyboardEvent,\n context: RangeSelectShortcutContext,\n): boolean {\n if (event.altKey) {\n return false;\n }\n const mod = event.ctrlKey || event.metaKey;\n if (mod && !event.shiftKey) {\n return event.key === 'a' || event.key === 'A';\n }\n if (mod && event.shiftKey) {\n return event.key === 'Home' || event.key === 'End';\n }\n if (event.shiftKey) {\n if (event.key === ' ' || event.key === 'Spacebar') {\n return true;\n }\n const action = resolveListNavigation(event, {\n orientation: context.orientation,\n dir: context.dir,\n });\n return action === 'next' || action === 'prev';\n }\n return false;\n}\n\n/** Identity of the primitive throwing {@link throwUnsupportedVirtualizedRangeSelect}. */\nexport interface UnsupportedVirtualizedRangeSelectContext {\n /** Primitive name for the `[forty-cdk/<primitive>]` error prefix (e.g. `'listbox'`). */\n readonly primitive: string;\n /** Non-virtualized focus model named in the remediation hint (e.g. `'roving-tabindex'`). */\n readonly focusModel: string;\n /** Collection the hint names after the focus model (e.g. `'listbox'`, `'tree'`). */\n readonly collection: string;\n /**\n * The range shortcuts this primitive actually detects, as the message spells\n * them — `'Shift+Arrow, Shift+Space, Ctrl/Cmd+A, Ctrl+Shift+Home/End'` for the\n * listbox family, which routes through {@link isRangeSelectShortcut}. It is a\n * fragment rather than a shared literal because Tree's own predicate detects\n * the first three only: naming a fourth there would report a combination the\n * tree supports in neither the virtualized nor the non-virtualized path, so\n * the error would be describing a restriction that does not exist.\n */\n readonly shortcuts: string;\n /**\n * The primitive's own way of multi-selecting under virtualization, opening\n * the remediation hint — e.g. `'Toggle options individually with Enter,\n * Space, or click'` for the listbox family, `'Use selectionMode=\"checkbox\"'`\n * for a tree. The shared \"or drop `totalCount`\" clause follows it.\n */\n readonly alternative: string;\n}\n\n/**\n * Throws (in dev mode only) the standard error explaining that APG range\n * keyboard is unsupported together with virtualization, because range selection\n * needs the full set of enabled items across the range while the collection is\n * only partially mounted. Shared by Listbox, Select and Tree; the primitive\n * name, the shortcut list it detects, the two hint fragments and the\n * primitive's own multi-select\n * {@link UnsupportedVirtualizedRangeSelectContext.alternative} are the only\n * per-primitive differences — add a fourth collection by calling this, not by\n * copying it.\n */\nexport function throwUnsupportedVirtualizedRangeSelect(\n context: UnsupportedVirtualizedRangeSelectContext,\n): void {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n throw fortyError({\n code: 'FORCDK-CORE-008',\n scope: context.primitive,\n message:\n `Multi-select range keyboard (${context.shortcuts}) is not supported together with ` +\n 'virtualization (`totalCount` set).',\n cause:\n 'Range selection needs the full set of enabled items across the range, which is ' +\n 'unavailable while the collection is only partially mounted.',\n fix:\n `${context.alternative}, or drop \\`totalCount\\` to use the non-virtualized ` +\n `${context.focusModel} ${context.collection}.`,\n });\n }\n}\n\n/**\n * Identity of the primitive asserting\n * {@link assertVirtualizedSelectionFollowsFocusSupported}.\n */\nexport interface UnsupportedVirtualizedSelectionFollowsFocusContext {\n /** Primitive name for the `[forty-cdk/<primitive>]` error prefix (e.g. `'listbox'`). */\n readonly primitive: string;\n /** Non-virtualized focus model named in the remediation hint (e.g. `'roving-tabindex'`). */\n readonly focusModel: string;\n /** Collection the hint names after the focus model (e.g. `'listbox'`, `'tree'`). */\n readonly collection: string;\n}\n\n/** The root state {@link assertVirtualizedSelectionFollowsFocusSupported} decides from. */\nexport interface VirtualizedSelectionFollowsFocusState {\n /**\n * The `selectionFollowsFocus` value the element bound itself, `undefined` when\n * it inherits the scope default. A virtualized root ignores the scope default,\n * so only a binding on the element is a misconfiguration.\n */\n readonly bound: boolean | undefined;\n /** Whether more than one item can be selected, where the option is inert. */\n readonly multiple: boolean;\n}\n\n/**\n * Throws (in dev mode only) the standard error explaining that\n * `selectionFollowsFocus` is unsupported together with virtualization, because\n * the activedescendant path resolves off-window navigation targets\n * asynchronously and so cannot carry selection with focus.\n *\n * It decides when the guard applies, so no root restates it: only when the\n * element bound `selectionFollowsFocus` to `true` itself, and only in single\n * mode. A scope default never reaches a virtualized root, and a multi-select\n * root ignores the option, so neither degrades a move.\n *\n * Call it from **every keyboard move of the virtualized activedescendant**\n * rather than from a config-watching `effect`: the combination degrades a\n * keyboard move, so the move is the point at which a throw carries a stack the\n * consumer can act on. \"Every\" is load-bearing — arrow navigation is only one\n * of the moves, and a guard on that branch alone leaves a consumer who\n * navigates by typeahead (or, in a tree, by entering a child) with the same\n * silent degradation and no report. Each root routes its moves through one\n * private `#assertSelectionFollowsFocusSupported()` for that reason. Seeding\n * the activedescendant on focus / open is not a move and is\n * uncovered.\n *\n * Shared by Listbox, Select and Tree; the primitive name and the two hint\n * fragments are the only per-primitive differences.\n */\nexport function assertVirtualizedSelectionFollowsFocusSupported(\n state: VirtualizedSelectionFollowsFocusState,\n context: UnsupportedVirtualizedSelectionFollowsFocusContext,\n): void {\n if (typeof ngDevMode !== 'undefined' && !ngDevMode) {\n return;\n }\n if (state.bound !== true || state.multiple) {\n return;\n }\n throw fortyError({\n code: 'FORCDK-CORE-009',\n scope: context.primitive,\n message:\n '`selectionFollowsFocus` is not supported together with virtualization (`totalCount` set).',\n cause:\n 'The virtualized activedescendant path resolves off-window navigation targets ' +\n 'asynchronously, so selection cannot follow focus there.',\n fix:\n 'Remove one of the two: use `selectionFollowsFocus` only with the non-virtualized ' +\n `${context.focusModel} ${context.collection}.`,\n });\n}\n\n/** Per-call inputs {@link resolveListTypeahead} needs to run a match. */\nexport interface ListTypeaheadConfig<H> {\n /** Live options to scan, in document order. */\n readonly items: readonly H[];\n /** Index of the currently-anchored option, or `-1` when nothing is anchored. */\n readonly anchorIndex: number;\n /** Resolve an option's match text (e.g. its accessible `textContent`), or several candidates. */\n readonly getText: (item: H) => string | readonly string[];\n /** Whether an option is skipped. */\n readonly isDisabled: (item: H) => boolean;\n}\n\n/** Outcome of a {@link resolveListTypeahead} call. */\nexport interface ListTypeaheadResult<H> {\n /** Whether the key was a printable character the typeahead buffer consumed. */\n readonly handled: boolean;\n /** The matched option when the buffer resolved one, else `null`. */\n readonly match: H | null;\n}\n\n/**\n * The shared list-typeahead policy for the open (DOM-focus) and virtualized\n * (activedescendant) paths of Listbox and Select: feed the key to the\n * `Typeahead` buffer, and — when consumed — run `findTypeaheadMatch` always\n * threading `repeated: isRepeatedChar()` and the caller-resolved `anchorIndex`.\n * Callers decide what to do with the match (focus it, or move\n * `aria-activedescendant`). A consumed Space is already `preventDefault()`-ed\n * by the buffer, so a caller whose own Space branch activates offers the key\n * here first and activates only when `handled` is `false`.\n */\nexport function resolveListTypeahead<H>(\n typeahead: Typeahead,\n event: KeyboardEvent,\n config: ListTypeaheadConfig<H>,\n): ListTypeaheadResult<H> {\n if (!typeahead.handle(event)) {\n return { handled: false, match: null };\n }\n const match = findTypeaheadMatch(\n config.items,\n {\n buffer: typeahead.buffer(),\n repeated: typeahead.isRepeatedChar(),\n anchorIndex: config.anchorIndex,\n },\n config.getText,\n config.isDisabled,\n );\n return { handled: true, match };\n}\n","import { DestroyRef, inject, signal } from '@angular/core';\n\nimport { isImeComposing } from '../keyboard-navigation/ime-composition';\nimport { isShortcutChord } from '../keyboard-navigation/modifier-chord';\n\nexport interface TypeaheadOptions {\n /** Milliseconds before the buffer is reset. Default 500. */\n debounceMs?: number;\n}\n\n/**\n * Stateful typeahead helper. Accumulates printable single-character keypresses\n * into a debounced buffer. The consumer reads `buffer()` after each handled\n * key and uses it to find a matching item (case-insensitive prefix match,\n * usually).\n *\n * The instance owns a debounce timer — call `destroy()` to clear it, or use\n * `injectTypeahead()` to register cleanup automatically with `DestroyRef`.\n */\nexport class Typeahead {\n readonly #buffer = signal('');\n readonly buffer = this.#buffer.asReadonly();\n readonly #debounceMs: number;\n #timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n constructor(options: TypeaheadOptions = {}) {\n this.#debounceMs = options.debounceMs ?? 500;\n }\n\n /**\n * Handles a key event. Returns `true` and appends to the buffer if the key\n * is a printable single character; returns `false` otherwise so the caller\n * can let the event keep flowing.\n *\n * A shortcut chord is not typing and is rejected: anything with Meta held,\n * Ctrl without AltGr, or Alt without AltGr on an ASCII key (an accelerator\n * or `accesskey` on Windows and Linux). A character composed through AltGr\n * (`ł` on a Polish layout) or through the macOS Option key (`ø`) is typing\n * and is accepted.\n *\n * Space is accepted **only while the buffer already holds at least one\n * character**, so multi-word labels (\"New York\") can accumulate past the\n * first word. The first Space with an empty buffer is rejected so widgets\n * that use Space for activation keep that behavior when the user is not\n * mid-typing. A Space this method accepts is `preventDefault()`-ed, so a\n * native `<button>` host never turns it into a click on `keyup`. A caller\n * whose own Space branch activates must offer the key here first and\n * activate only when this returns `false`.\n */\n handle(event: KeyboardEvent): boolean {\n if (isImeComposing(event) || isShortcutChord(event)) {\n return false;\n }\n const ch = event.key;\n if (typeof ch !== 'string' || ch.length !== 1) {\n return false;\n }\n if (ch === ' ') {\n if (this.#buffer() === '') {\n return false;\n }\n event.preventDefault();\n }\n\n this.#buffer.update((current) => current + ch);\n this.#scheduleReset();\n return true;\n }\n\n /**\n * Whether the buffer is a single printable character, optionally pressed\n * repeatedly (every character identical — `\"c\"`, `\"cc\"`, `\"ccc\"`). Callers\n * use this to switch from prefix matching to cycling among same-initial\n * items, matching the WAI-ARIA APG menu typeahead behavior: pressing one key\n * (and re-pressing it) steps through every item that starts with it, instead\n * of looking for a literal `\"ccc\"` prefix that never exists.\n */\n isRepeatedChar(): boolean {\n const buffer = this.#buffer();\n return buffer.length >= 1 && [...buffer].every((ch) => ch === buffer[0]);\n }\n\n reset(): void {\n if (this.#timeoutId !== null) {\n clearTimeout(this.#timeoutId);\n this.#timeoutId = null;\n }\n this.#buffer.set('');\n }\n\n destroy(): void {\n if (this.#timeoutId !== null) {\n clearTimeout(this.#timeoutId);\n this.#timeoutId = null;\n }\n }\n\n #scheduleReset(): void {\n if (this.#timeoutId !== null) {\n clearTimeout(this.#timeoutId);\n }\n this.#timeoutId = setTimeout(() => {\n this.#buffer.set('');\n this.#timeoutId = null;\n }, this.#debounceMs);\n }\n}\n\n/**\n * Creates a `Typeahead` and registers `destroy()` with the current `DestroyRef`.\n * Must be called within an Angular injection context (constructor / field\n * initializer of a directive/component, or `runInInjectionContext`).\n */\nexport function injectTypeahead(options?: TypeaheadOptions): Typeahead {\n const typeahead = new Typeahead(options);\n inject(DestroyRef).onDestroy(() => typeahead.destroy());\n return typeahead;\n}\n","import { DestroyRef, inject, type OutputEmitterRef } from '@angular/core';\n\n/**\n * An event a consumer can veto by calling `preventDefault()`. The directive\n * inspects `defaultPrevented` after emitting and skips its default action\n * (close, focus move, etc.) when set.\n *\n * Replaces the prior pattern of passing a real DOM `CustomEvent`, which\n * was a poor fit: Angular `output()` is a synchronous in-process\n * emitter — events don't bubble, don't propagate, and have no `target` /\n * `currentTarget`. `CustomEvent` cost an allocation per emit and gave\n * consumers a misleading \"looks like a DOM event\" surface.\n */\nexport interface VetoableEvent {\n /** Mark this event as vetoed; the directive will skip its default action. */\n preventDefault(): void;\n /** True after `preventDefault()` has been called. */\n readonly defaultPrevented: boolean;\n}\n\n/**\n * Vetoable event that also carries the original DOM event that triggered\n * it. Used for outputs whose semantic action is anchored to a real\n * keyboard / pointer / focus event: `(escapeKeyDown)` (`KeyboardEvent`),\n * `(pointerDownOutside)` (`PointerEvent`), `(focusOutside)` (`FocusEvent`),\n * `(interactOutside)` (`PointerEvent | FocusEvent`).\n */\nexport interface VetoableNativeEvent<E extends Event> extends VetoableEvent {\n /** Original DOM event the directive received. */\n readonly event: E;\n}\n\n/**\n * Builds a `VetoableEvent` (no native payload). The returned object's\n * `defaultPrevented` flips to `true` once any handler calls `preventDefault()`.\n */\nexport function createVetoableEvent(): VetoableEvent {\n let prevented = false;\n return {\n preventDefault() {\n prevented = true;\n },\n get defaultPrevented() {\n return prevented;\n },\n };\n}\n\n/**\n * Builds a `VetoableNativeEvent` wrapping `event`. Useful when the same\n * physical interaction must be observable through more than one output —\n * e.g. a pointer-down-outside emits the same wrapper through\n * `(pointerDownOutside)` and `(interactOutside)` so a `preventDefault()`\n * in either handler vetoes the close.\n */\nexport function createVetoableNativeEvent<E extends Event>(event: E): VetoableNativeEvent<E> {\n let prevented = false;\n return {\n event,\n preventDefault() {\n prevented = true;\n },\n get defaultPrevented() {\n return prevented;\n },\n };\n}\n\n/**\n * Builds a fresh `VetoableEvent`, emits it through `emitter`, and returns\n * whether the consumer vetoed. Use for one-shot outputs whose veto state\n * doesn't need to be observed by sibling outputs (e.g. `(autoFocusOnOpen)`,\n * a menu item's `(activate)`).\n */\nexport function emitVetoableEvent(emitter: OutputEmitterRef<VetoableEvent>): boolean {\n const veto = createVetoableEvent();\n emitter.emit(veto);\n return veto.defaultPrevented;\n}\n\n/**\n * Builds a `VetoableNativeEvent` wrapping `event`, emits it through\n * `emitter`, and returns whether the consumer vetoed. Use for outputs\n * whose veto is scoped to a single emit (e.g. `(escapeKeyDown)`).\n */\nexport function emitVetoableNativeEvent<E extends Event>(\n emitter: OutputEmitterRef<VetoableNativeEvent<E>>,\n event: E,\n): boolean {\n const veto = createVetoableNativeEvent(event);\n emitter.emit(veto);\n return veto.defaultPrevented;\n}\n\n/**\n * Builds a veto resolver over `emitter` that answers `true` — vetoed — once the\n * directive declaring it is destroyed, instead of emitting.\n *\n * Use it for a vetoable hook the primitive also fires from a teardown path: the\n * consumer's handler is unreachable there, and a dropped emit would otherwise\n * read as \"not vetoed\" and run the default action.\n *\n * Call it from the injection context of the directive that declares `emitter`.\n */\nexport function injectVetoableEmitter(emitter: OutputEmitterRef<VetoableEvent>): () => boolean {\n const destroyRef = inject(DestroyRef);\n return () => (destroyRef.destroyed ? true : emitVetoableEvent(emitter));\n}\n","import { lookupByValue } from '../selection/selection';\nimport type { VirtualizedResumeEntry } from './virtualized-resume';\n\n/** What {@link resolveCommittedPosition} reads to place the committed selection. */\nexport interface CommittedPositionQuery<T> {\n /** The committed values, in selection order. */\n readonly values: readonly T[];\n /** The navigator's position snapshot. */\n readonly snapshotByPos: ReadonlyMap<number, VirtualizedResumeEntry<T>>;\n /** Item identity, used to match a committed value against a snapshot entry. */\n readonly compareWith: (a: T, b: T) => boolean;\n /** The consumer's absolute index hint for a selection that was never rendered. */\n readonly selectedIndex: number | undefined;\n /** Full source length; a hint at or past it is ignored. */\n readonly totalCount: number | undefined;\n}\n\n/**\n * The absolute position a virtualized activedescendant collection seeds when it\n * lands on its committed selection: the first committed value whose enabled\n * entry is in the position snapshot, else the consumer's `selectedIndex` hint\n * when it is in range, else `null`. An empty selection resolves to `null`, so a\n * stale hint never seeds a collection with nothing selected.\n *\n * The caller seeds the result through the navigator's `seedActive`, which emits\n * `(scrollToIndex)` when the position is outside the rendered window.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\nexport function resolveCommittedPosition<T>(query: CommittedPositionQuery<T>): number | null {\n if (query.values.length === 0) {\n return null;\n }\n const byValue = lookupByValue(\n [...query.snapshotByPos].filter(([, entry]) => !entry.disabled),\n ([, entry]) => entry.value,\n query.compareWith,\n );\n for (const value of query.values) {\n const hit = byValue(value);\n if (hit) {\n return hit[0];\n }\n }\n const { selectedIndex, totalCount } = query;\n if (\n selectedIndex === undefined ||\n totalCount === undefined ||\n selectedIndex < 0 ||\n selectedIndex >= totalCount\n ) {\n return null;\n }\n return selectedIndex;\n}\n","import { computed, linkedSignal, signal, type Signal } from '@angular/core';\n\nimport { type ListNavigationAction, moveIndex } from '../keyboard-navigation/keyboard-navigation';\nimport { resolveListTypeahead } from '../typeahead/list-typeahead';\nimport type { Typeahead } from '../typeahead/typeahead';\n\n/**\n * Minimal shape every position-snapshot entry must expose so the engine can\n * resolve the current absolute position from `aria-activedescendant` and skip\n * disabled positions outside the rendered window. Primitive adapters widen this\n * with their own per-entry fields (value, label, level, …).\n */\nexport interface VirtualizedNavigatorEntry {\n /** Stable host id — the activedescendant target. */\n readonly id: string;\n /** Whether the position is disabled, so `moveIndex` skips over it. */\n readonly disabled: boolean;\n}\n\n/**\n * Handle-shape adapters. Each primitive's option / node handle exposes its\n * absolute position, id, and host element under different accessor names; these\n * bridge the engine to whichever shape the primitive uses, so the navigation\n * algorithm itself stays handle-agnostic.\n */\nexport interface VirtualizedNavigatorAccessors<H, E extends VirtualizedNavigatorEntry> {\n /** Absolute position of a live handle, or `null` before it is assigned. */\n readonly posOf: (item: H) => number | null;\n /** Stable id of a live handle. */\n readonly idOf: (item: H) => string;\n /** Host element of a live handle, scrolled into view when it becomes active. */\n readonly hostOf: (item: H) => HTMLElement;\n /**\n * Whether a live handle is disabled, read without going through the position\n * snapshot. {@link VirtualizedNavigator.seedFirstRenderedEnabled} needs the\n * flag for handles the fold may have skipped, so the snapshot cannot answer\n * it: {@link readEntry} returns `null` for an option whose `[value]` binding\n * is not written yet, and such an option is still a legitimate seed target.\n */\n readonly isDisabled: (item: H) => boolean;\n /**\n * Build the position-snapshot entry for a live handle, or `null` to skip it\n * this fold. The unwritten-binding guard is injected here: a\n * statically-rendered option that registers before its `[value]` binding is\n * written reads the `unsetInput` sentinel, returns `null`, and is folded in\n * on the binding's re-run.\n */\n readonly readEntry: (item: H) => E | null;\n /**\n * Scroll the active host into view. Defaults to\n * `host.scrollIntoView?.({ block: 'nearest' })`; the combobox overrides it to\n * open its pointer-suppression window first.\n */\n readonly scrollIntoView?: (host: HTMLElement) => void;\n}\n\n/** Tunables for the position-snapshot fold. */\nexport interface VirtualizedNavigatorOptions {\n /**\n * Behaviour on a `totalCount` transition. `false` (default) restarts from an\n * empty map **and folds the current window in the same compute** (Select /\n * Listbox / Tree). `true` returns the empty map **without folding**, deferring\n * to the next run once `items` catches up — the stale-window invariant the\n * Combobox needs, because a `totalCount` flip (a query / source rebuild) can\n * fire while `items()` still holds the previous window.\n */\n readonly deferFoldOnTotalTransition?: boolean;\n}\n\n/**\n * Signal-graph wiring. The root directive owns the activedescendant and the\n * virtualizer bridge, so the engine reads / writes them through callbacks\n * instead of holding its own copies.\n */\nexport interface VirtualizedNavigatorDeps<H> {\n /** Live registered handles — the rendered window when virtualizing. */\n readonly items: Signal<readonly H[]>;\n /** Total handle count for the virtualized path. */\n readonly totalCount: Signal<number | undefined>;\n /** Inclusive-exclusive range of currently rendered handles when virtualizing. */\n readonly visibleRange: Signal<readonly [number, number] | undefined>;\n /** Whether keyboard navigation wraps at the ends. */\n readonly loop: () => boolean;\n /** Read the root's current activedescendant id. */\n readonly getActiveId: () => string | null;\n /** Write the root's activedescendant id. */\n readonly setActiveId: (id: string | null) => void;\n /** Forward a `(scrollToIndex)` request to the consumer's virtualizer. */\n readonly emitScrollToIndex: (idx: number) => void;\n /**\n * Optional resume position, consulted only when there is no active id. Lets a\n * primitive that clears its dangling `aria-activedescendant` on unmount (a\n * removed element is an invalid target) still resume navigation from the last\n * active absolute position instead of restarting at the edge. Returns `null`\n * when there is nothing to resume from.\n */\n readonly getResumePos?: () => number | null;\n /**\n * Optional monotonic \"the dataset changed\" signal. When provided and its\n * value changes between folds, the position snapshot rebuilds from empty —\n * exactly as a `totalCount` transition does — discarding carried-over\n * off-window entries. This is the consumer-facing counterpart to\n * {@link VirtualizedNavigator.invalidateSnapshot}: wire a signal that bumps on\n * a same-length dataset refresh (a re-sort / reload that keeps `totalCount`\n * unchanged) so navigation never resolves against a stale off-window entry.\n */\n readonly dataVersion?: Signal<unknown>;\n}\n\n/** Outcome of a {@link VirtualizedNavigator.resolveTypeahead} call. */\nexport interface VirtualizedTypeaheadResult {\n /** Whether the key was a printable character the typeahead buffer consumed. */\n readonly handled: boolean;\n /** Absolute position of the matched entry, or `null` when nothing matched. */\n readonly pos: number | null;\n}\n\n/**\n * Tracked source of the position-snapshot fold: the live window, its total, and\n * the merged data version (the consumer's `dataVersion` plus the imperative\n * {@link VirtualizedNavigator.invalidateSnapshot} counter). A change to the\n * version rebuilds from empty and folds the current window; a change to `total`\n * rebuilds from empty and folds or defers per `deferFoldOnTotalTransition`.\n */\ninterface SnapshotSource<H> {\n readonly total: number | undefined;\n readonly items: readonly H[];\n readonly version: unknown;\n}\n\n/**\n * The single activedescendant-over-absolute-index navigation engine shared by\n * every virtualized collection primitive (Select, Listbox, Combobox, Tree).\n * Constructed lazily by each primitive's root through its own accessor factory —\n * only once the consumer sets `totalCount()` — so a non-virtualized collection\n * never pulls this position-map machinery into its hot path. Encapsulates two\n * pieces of state that make keyboard navigation work across a virtualized window\n * where the active item may be unmounted at any time:\n *\n * - **Snapshot by position** — entry data keyed by absolute position. Drives\n * navigation past the rendered window so `moveIndex` knows about disabled\n * boundaries it cannot see, and lets adapters resolve off-window entries\n * (committed-index resolution, level-aware tree moves, label fallbacks). The\n * map is updated in place with each rendered window, so a fold costs\n * O(window), and restarts empty on a `totalCount` transition. A same-length\n * dataset refresh (invisible to the `totalCount` diff) can force the same\n * reset through {@link invalidateSnapshot} or the optional\n * `deps.dataVersion` signal.\n * - **Pending active position** — when navigation lands outside the visible\n * window, the engine emits `(scrollToIndex)` and remembers the target. The\n * root's bridge effect calls `tryResolvePending` once the freshly-mounted item\n * carries that position.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n *\n * @typeParam H Primitive handle type (option / node).\n * @typeParam E Position-snapshot entry; widens {@link VirtualizedNavigatorEntry}.\n */\nexport class VirtualizedNavigator<H, E extends VirtualizedNavigatorEntry> {\n readonly #deps: VirtualizedNavigatorDeps<H>;\n\n readonly #accessors: VirtualizedNavigatorAccessors<H, E>;\n\n readonly #snapshotByPos: Signal<Map<number, E>>;\n\n /**\n * Monotonic counter bumped by {@link invalidateSnapshot}. The snapshot fold\n * tracks it as a `dataVersion` alongside the consumer's own optional\n * `deps.dataVersion`, so an imperative call forces a from-empty rebuild on the\n * next fold even when `totalCount` is unchanged.\n */\n readonly #invalidationVersion = signal(0);\n\n /**\n * The pending navigation slot. Carries the requested absolute position, the\n * action that produced it, and whether a resolve landing on a disabled entry\n * should continue the walk. Directional navigation (`navigate` / `#moveFrom`)\n * sets `continueOnDisabled`, so it never settles activedescendant on a\n * disabled id; a directionless `seedActive` (committed-index / enter-child /\n * parent move — all targeting enabled positions in practice) settles on the\n * resolved item as before.\n */\n #pendingActivePos: {\n pos: number;\n action: ListNavigationAction;\n continueOnDisabled: boolean;\n } | null = null;\n\n constructor(\n deps: VirtualizedNavigatorDeps<H>,\n accessors: VirtualizedNavigatorAccessors<H, E>,\n options: VirtualizedNavigatorOptions = {},\n ) {\n this.#deps = deps;\n this.#accessors = accessors;\n\n const consumerVersion = deps.dataVersion;\n const version = computed(\n () => ({\n invalidation: this.#invalidationVersion(),\n consumer: consumerVersion ? consumerVersion() : undefined,\n }),\n { equal: (a, b) => a.invalidation === b.invalidation && a.consumer === b.consumer },\n );\n\n const defer = options.deferFoldOnTotalTransition === true;\n const fold = (snapshot: Map<number, E>, window: readonly H[]): Map<number, E> => {\n for (const item of window) {\n const pos = accessors.posOf(item);\n if (pos === null) continue;\n const entry = accessors.readEntry(item);\n if (entry === null) continue;\n snapshot.set(pos, entry);\n }\n return snapshot;\n };\n\n this.#snapshotByPos = linkedSignal<SnapshotSource<H>, Map<number, E>>({\n source: () => ({ total: deps.totalCount(), items: deps.items(), version: version() }),\n computation: ({ total, items: window, version: currentVersion }, prev) => {\n if (prev !== undefined && prev.source.version !== currentVersion) {\n return fold(new Map<number, E>(), window);\n }\n if (prev !== undefined && prev.source.total !== total) {\n return defer ? new Map<number, E>() : fold(new Map<number, E>(), window);\n }\n return fold(prev?.value ?? new Map<number, E>(), window);\n },\n equal: () => false,\n });\n }\n\n /**\n * Pull the position-map so its `linkedSignal` `prev` slot gets seeded while\n * the items are tracked. Called from the root's bridge effect.\n */\n prime(): void {\n this.#snapshotByPos();\n }\n\n /**\n * Read-only position snapshot, keyed by absolute position. Persists across\n * close → reopen while `totalCount` is unchanged. Adapters read it for\n * committed-index resolution, level-aware moves, and off-window label\n * fallbacks. Later folds update the returned map in place, so read it again\n * rather than holding it across a window change.\n */\n snapshotByPos(): ReadonlyMap<number, E> {\n return this.#snapshotByPos();\n }\n\n /**\n * Force the position snapshot to rebuild from empty on the next fold,\n * discarding every carried-over off-window entry. Call this after a\n * same-length dataset refresh — a re-sort / reload that keeps `totalCount`\n * unchanged — so navigation never resolves against a stale `id` / `disabled` /\n * `value` for a position outside the current `items()` window. Positions not\n * in the current window are gone after the rebuild; the current window folds\n * in as usual on the next `prime()`. The `deps.dataVersion` signal is the\n * reactive counterpart when the consumer already models \"the dataset changed\".\n */\n invalidateSnapshot(): void {\n this.#invalidationVersion.update((v) => v + 1);\n }\n\n /**\n * Try to resolve a pending virtualized navigation. Once an item carrying the\n * requested position mounts, seeds activedescendant to its id and scrolls it\n * into view. If the freshly-mounted entry turns out to be disabled, the walk\n * continues from that position in the pending direction rather than settling\n * activedescendant on a disabled id. Returns `true` if a pending request was\n * resolved (or continued), `false` otherwise.\n *\n * Called from the root's bridge effect, whose documented reactive trigger\n * is `items()`. The pending slot is a plain field, not a signal: this method\n * writes it back to `null` on a successful resolve, and a tracked slot would\n * make that write re-invalidate the calling effect — a self-invalidation that\n * double-runs the prime / fold pass in every consuming primitive.\n */\n tryResolvePending(): boolean {\n const pending = this.#pendingActivePos;\n if (pending === null) {\n return false;\n }\n const match = this.#deps.items().find((it) => this.#accessors.posOf(it) === pending.pos);\n if (!match) {\n return false;\n }\n if (pending.continueOnDisabled && this.#accessors.readEntry(match)?.disabled === true) {\n this.#pendingActivePos = null;\n this.#moveFrom(pending.pos, this.#continuationDirection(pending.action));\n return true;\n }\n this.#deps.setActiveId(this.#accessors.idOf(match));\n this.#pendingActivePos = null;\n this.#scrollIntoView(this.#accessors.hostOf(match));\n return true;\n }\n\n /**\n * Virtualized arrow / Home / End navigation. Resolves the current absolute\n * position from the active id (live item, else the snapshot) or the resume\n * position, then delegates the `moveIndex` walk to {@link #moveFrom}.\n *\n * An active item still in the rendered window resolves in O(window) via\n * `items`; one scrolled off it is matched against every snapshot entry, so\n * that branch costs O(total) once per keypress.\n */\n navigate(direction: ListNavigationAction): void {\n const total = this.#deps.totalCount();\n if (total === undefined || total <= 0) {\n return;\n }\n const indexed = this.#snapshotByPos();\n const items = this.#deps.items();\n\n const currentId = this.#deps.getActiveId();\n let currentPos = -1;\n if (currentId !== null) {\n const live = items.find((o) => this.#accessors.idOf(o) === currentId);\n const livePos = live ? this.#accessors.posOf(live) : null;\n if (livePos !== null) {\n currentPos = livePos;\n } else {\n for (const [pos, entry] of indexed) {\n if (entry.id === currentId) {\n currentPos = pos;\n break;\n }\n }\n }\n } else {\n const resume = this.#deps.getResumePos?.();\n if (resume !== undefined && resume !== null && resume >= 0 && resume < total) {\n currentPos = resume;\n }\n }\n\n let action = direction;\n if (currentPos < 0 && direction === 'next') {\n action = 'first';\n } else if (currentPos < 0 && direction === 'prev') {\n action = 'last';\n }\n\n this.#moveFrom(currentPos, action);\n }\n\n /**\n * Run a typeahead keystroke against the **position snapshot** rather than the\n * rendered window, so a match the consumer's virtualizer has unmounted is\n * still reachable. Entries are scanned in absolute-position order and the\n * anchor is the current activedescendant's entry, or the resume position\n * when there is no active id, so the repeated-character cycle and the\n * anchored prefix scan of `findTypeaheadMatch` mean the same thing they mean\n * in a fully-mounted collection.\n *\n * Returns the matched **absolute position** rather than moving to it: the\n * caller runs its own per-primitive guards first, then hands the position to\n * {@link seedActive}, which emits `(scrollToIndex)` when the match is outside\n * the rendered window.\n *\n * The reachable set is bounded by the snapshot, which only holds positions\n * that have been rendered at least once — a position the consumer's window has\n * never reached is invisible to the search, and each collection's README\n * states that limit for consumers.\n *\n * @param typeahead The root's buffer; the key is fed to it before matching.\n * @param event The keydown to match on.\n * @param getText Resolves an entry's match text.\n */\n resolveTypeahead(\n typeahead: Typeahead,\n event: KeyboardEvent,\n getText: (entry: E) => string,\n ): VirtualizedTypeaheadResult {\n const entries = [...this.#snapshotByPos().entries()].sort(([a], [b]) => a - b);\n const { handled, match } = resolveListTypeahead(typeahead, event, {\n items: entries,\n anchorIndex: this.#typeaheadAnchorIndex(entries),\n getText: ([, entry]) => getText(entry),\n isDisabled: ([, entry]) => entry.disabled,\n });\n return { handled, pos: match === null ? null : match[0] };\n }\n\n /**\n * Land the activedescendant on a specific absolute index (the committed item\n * on open, an enter-child / parent move, or a first / last fallback). If the\n * index is inside the rendered window and live, seeds activedescendant\n * directly; otherwise stashes it as pending and emits `(scrollToIndex)` so the\n * consumer's virtualizer mounts it. A seed has no inherent direction, so its\n * pending resolve settles on the resolved item even if disabled (callers\n * target enabled positions) rather than continuing a directional walk.\n */\n seedActive(index: number): void {\n if (this.#seedIfRendered(index)) {\n return;\n }\n this.#pendingActivePos = { pos: index, action: 'next', continueOnDisabled: false };\n this.#deps.emitScrollToIndex(index);\n }\n\n /**\n * Seed activedescendant on the first or last enabled handle that is\n * **currently rendered**, ordered by absolute position. No-op when\n * `totalCount` is unset / zero, when nothing is rendered, or when every\n * rendered handle is disabled.\n *\n * *Passive*: it only ever moves activedescendant, never the\n * consumer's scroll position, so it emits no `(scrollToIndex)`. The Combobox\n * auto-highlight bridge — its one caller — re-seeds every time the\n * activedescendant is cleared, and scrolling the active option out of the\n * rendered window clears it. A seed that targeted the absolute first position\n * would therefore snap the listbox back to the top on every wheel tick that\n * unmounted the active row. Off-window targets are reached only through\n * {@link navigate} / {@link seedActive}, which own scroll-into-view.\n */\n seedFirstRenderedEnabled(direction: 'first' | 'last'): void {\n const total = this.#deps.totalCount();\n if (total === undefined || total <= 0) {\n return;\n }\n const items = this.#deps.items();\n if (items.length === 0) {\n return;\n }\n const ordered = [...items].sort((a, b) => {\n const pa = this.#accessors.posOf(a) ?? 0;\n const pb = this.#accessors.posOf(b) ?? 0;\n return direction === 'last' ? pb - pa : pa - pb;\n });\n for (const item of ordered) {\n if (!this.#accessors.isDisabled(item)) {\n this.#deps.setActiveId(this.#accessors.idOf(item));\n return;\n }\n }\n }\n\n /** Clear any pending navigation (called by the root on close). */\n resetPending(): void {\n this.#pendingActivePos = null;\n }\n\n /**\n * Walk `moveIndex` from `fromPos` in `action`, using the indexed snapshot to\n * skip disabled items outside the rendered window. Seeds activedescendant when\n * the target is rendered; otherwise stashes it (with the action, so a\n * resolve-on-disabled can continue the walk) and emits `(scrollToIndex)`.\n */\n #moveFrom(fromPos: number, action: ListNavigationAction): void {\n const total = this.#deps.totalCount();\n if (total === undefined || total <= 0) {\n return;\n }\n const indexed = this.#snapshotByPos();\n const next = moveIndex(fromPos, total, action, {\n loop: this.#deps.loop(),\n isDisabled: (i) => indexed.get(i)?.disabled === true,\n });\n if (next === null) {\n return;\n }\n if (this.#seedIfRendered(next)) {\n return;\n }\n this.#pendingActivePos = { pos: next, action, continueOnDisabled: true };\n this.#deps.emitScrollToIndex(next);\n }\n\n #typeaheadAnchorIndex(entries: readonly (readonly [number, E])[]): number {\n const activeId = this.#deps.getActiveId();\n if (activeId !== null) {\n return entries.findIndex(([, entry]) => entry.id === activeId);\n }\n const resume = this.#deps.getResumePos?.() ?? null;\n return resume === null ? -1 : entries.findIndex(([pos]) => pos === resume);\n }\n\n #continuationDirection(action: ListNavigationAction): ListNavigationAction {\n return action === 'prev' || action === 'last' ? 'prev' : 'next';\n }\n\n #seedIfRendered(index: number): boolean {\n const range = this.#deps.visibleRange();\n const inRange = !range || (index >= range[0] && index < range[1]);\n if (inRange) {\n const live = this.#deps.items().find((it) => this.#accessors.posOf(it) === index);\n if (live) {\n this.#pendingActivePos = null;\n this.#deps.setActiveId(this.#accessors.idOf(live));\n this.#scrollIntoView(this.#accessors.hostOf(live));\n return true;\n }\n }\n return false;\n }\n\n #scrollIntoView(host: HTMLElement): void {\n if (this.#accessors.scrollIntoView) {\n this.#accessors.scrollIntoView(host);\n return;\n }\n host.scrollIntoView?.({ block: 'nearest' });\n }\n}\n","/**\n * The two members a bridge effect needs from the navigation engine: the\n * position-map pull and the pending-navigation resolve. Structural on purpose —\n * Select, Listbox and Combobox hold a {@link VirtualizedNavigator} directly,\n * while Tree reaches the same pair through its activedescendant focus model,\n * which wraps one.\n */\nexport interface VirtualizedNavigatorBridgeTarget {\n /** @see VirtualizedNavigator.prime */\n prime(): void;\n /** @see VirtualizedNavigator.tryResolvePending */\n tryResolvePending(): boolean;\n}\n\n/** Signal-graph wiring for {@link runVirtualizedNavigatorBridge}. */\nexport interface VirtualizedNavigatorBridgeDeps<N extends VirtualizedNavigatorBridgeTarget> {\n /**\n * The live handle window. Read for its dependency alone — the bridge never\n * looks at the value — so the effect re-runs whenever the consumer's\n * virtualizer mounts or unmounts a row.\n */\n readonly items: () => unknown;\n /** Whether the consumer set `totalCount` (the virtualized path). */\n readonly virtualized: () => boolean;\n /**\n * Resolve the navigation engine, constructing it on first use. Called only on\n * the virtualized branch so a plain collection never builds the position-map\n * machinery.\n */\n readonly requireNavigator: () => N;\n}\n\n/**\n * The position-map bridge every virtualized collection primitive runs from a\n * single `effect()`: it pulls the navigator's position snapshot while the\n * rendered window is tracked, then resolves any pending off-window navigation\n * the freshly-mounted window can now satisfy. Returns `true` when a pending\n * request was resolved (or continued), so a caller with further work — the\n * Combobox auto-highlight bridge — can stand down.\n *\n * The pull is the load-bearing half and is **not** redundant with the resolve\n * next to it: `tryResolvePending` reads `items()` and the matched handle, never\n * the snapshot, and returns early when nothing is pending. Without the pull the\n * snapshot is a lazy derivation over a transient source, so the positions of\n * every window the user scrolls past never enter the map and off-window\n * navigation stops resolving. The effect that runs this therefore carries the\n * sanctioned-pull marker naming `navigator-position-map` (spelled out only at\n * the marker itself, so the library's grep ledger stays exact), and any write\n * sharing that effect must already track `items` / `totalCount` / the data\n * version — the pull drags those in. The resolve's own activedescendant write\n * is such a write: the lint bans the pair outright rather than judging that\n * overlap, and this one passes only because it sits one file away, so every\n * bridge effect relies on the overlap argument the conventions spell out.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n */\nexport function runVirtualizedNavigatorBridge<N extends VirtualizedNavigatorBridgeTarget>(\n deps: VirtualizedNavigatorBridgeDeps<N>,\n): boolean {\n deps.items();\n if (!deps.virtualized()) {\n return false;\n }\n const navigator = deps.requireNavigator();\n navigator.prime();\n return navigator.tryResolvePending();\n}\n","import { signal, type Signal } from '@angular/core';\n\nimport { isUnset, type Unset } from '../unset-input/unset-input';\nimport type { VirtualizedNavigatorEntry } from './virtualized-navigator';\n\n/**\n * Position-snapshot entry a {@link VirtualizedResume} can validate: the\n * engine's minimal shape plus the value of the item at that position.\n */\nexport interface VirtualizedResumeEntry<T> extends VirtualizedNavigatorEntry {\n /** The item's value, matched against the retained one. */\n readonly value: T;\n}\n\n/** Wiring for {@link VirtualizedResume}. */\nexport interface VirtualizedResumeDeps<T, E extends VirtualizedResumeEntry<T>> {\n /** Total item count; a retained position at or past it resolves to nothing. */\n readonly totalCount: Signal<number | undefined>;\n /** The navigator's position snapshot. Read lazily, so the navigator may be built later. */\n readonly snapshotByPos: () => ReadonlyMap<number, E>;\n /** Item identity, used to match the retained value against the snapshot entry. */\n readonly compareWith: Signal<(a: T, b: T) => boolean>;\n}\n\n/** A retained position resolved against the current position snapshot. */\nexport interface VirtualizedResumeMatch<E> {\n /** Absolute position of the retained item. */\n readonly pos: number;\n /** The snapshot entry at that position. */\n readonly entry: E;\n}\n\n/**\n * The position a virtualized activedescendant collection resumes from once its\n * active item unmounts. A removed element is an invalid `aria-activedescendant`\n * target, so the root clears its active id when the active handle unregisters\n * and retains that handle's absolute position and value here. Wiring\n * {@link pos} as the navigator's `getResumePos` makes arrow navigation continue\n * from it, and {@link resolve} lets activation and Tab-commit act on the item\n * the user was on, re-seeding it through `seedActive`.\n *\n * The retained value is what makes the position answer for its own identity. A\n * snapshot rebuild (a `totalCount` transition, a data-version change or\n * `invalidateSnapshot()`) drops the off-window entry, and a refresh that put a\n * different item at the position fails the comparison, so both resolve to\n * nothing instead of resuming on whatever now occupies the slot.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee.\n *\n * @typeParam T Item value type.\n * @typeParam E Position-snapshot entry; widens {@link VirtualizedResumeEntry}.\n */\nexport class VirtualizedResume<T, E extends VirtualizedResumeEntry<T>> {\n readonly #deps: VirtualizedResumeDeps<T, E>;\n\n readonly #target = signal<{ readonly pos: number; readonly value: T } | null>(null);\n\n constructor(deps: VirtualizedResumeDeps<T, E>) {\n this.#deps = deps;\n }\n\n /**\n * Retain the position and value of the active item that is unmounting.\n * Retains nothing when the position is unknown or the value binding is not\n * written yet.\n */\n retain(pos: number | null, value: T | Unset): void {\n this.#target.set(pos === null || isUnset(value) ? null : { pos, value });\n }\n\n /** Forget the retained position. The root calls it whenever a new item becomes active. */\n clear(): void {\n this.#target.set(null);\n }\n\n /**\n * The retained position and its snapshot entry, or `null` when nothing is\n * retained or the position no longer holds the retained item.\n */\n resolve(): VirtualizedResumeMatch<E> | null {\n const target = this.#target();\n if (target === null || target.pos < 0) {\n return null;\n }\n const total = this.#deps.totalCount();\n if (total === undefined || target.pos >= total) {\n return null;\n }\n const entry = this.#deps.snapshotByPos().get(target.pos);\n if (!entry || !this.#deps.compareWith()(entry.value, target.value)) {\n return null;\n }\n return { pos: target.pos, entry };\n }\n\n retained(): { readonly pos: number; readonly value: T } | null {\n return this.#target();\n }\n\n /** The resolved position alone, in the shape the navigator's `getResumePos` takes. */\n pos(): number | null {\n return this.resolve()?.pos ?? null;\n }\n}\n"],"mappings":";;;;;AAoBA,SAAgB,sBAAsB,MAAU;CAC9C,IAAI,OAAO;CACX,KAAK,WAAW,SAAS,UAAS;EAChC,IAAI,MAAM,aAAa,MAAM,WAAW;GACtC,QAAQ,MAAM,aAAa;GAC3B;EACF;EACA,IAAI,MAAM,aAAa,MAAM,cAAc;GACzC,IAAK,MAAkB,aAAa,aAAa,MAAM,QACrD;GAEF,QAAQ,sBAAsB,KAAK;EACrC;CACF,CAAC;CACD,OAAO;AACT;ACCA,SAAgB,2BAA2B,IAAc;CACvD,MAAM,aAAa,OAAO,UAAU;CAEpC,IAAI,YAAY;CAEhB,MAAM,MAAM,sBAAqB;EAC/B,IAAI,WAAW;EACf,GAAE;CACJ,CAAC;CAED,WAAW,gBAAe;EACxB,YAAY;EACZ,IAAI,QAAO;CACb,CAAC;AACH;AC1BA,SAAS,aAAgB,GAAiB,GAAe;CACvD,IAAI,MAAM,GACR,OAAO;CAET,IAAI,EAAE,WAAW,EAAE,QACjB,OAAO;CAET,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAC5B,IAAI,EAAE,OAAO,EAAE,IACb,OAAO;CAGX,OAAO;AACT;AA0BA,IAAa,aAAb,MAAuB;CACZ,8BAAc,IAAI,IAAG;CACrB,gBAAgB,OAAO,GAAE,GAAA,YAAA,CAAA,EAAA,WAAA,gBAAA,CAAA,+BAAA,CAAA,CAAA;CACzB,YAAY,OAAO,GAAE,GAAA,YAAA,CAAA,EAAA,WAAA,YAAA,CAAA,+BAAA,CAAA,CAAA;CAE9B,YAAqC;CAC5B,iCAAiB,IAAI,IAAG;CACjC,aAAa;CACb,iBAAiB;CAEjB,cAAA;EACE,OAAO,UAAU,CAAC,CAAC,gBAAgB,KAAK,QAAO,CAAE;CACnD;CAmBS,QAA8B,eAChC;EACH,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