{"version":3,"file":"forty-cdk-core.mjs","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/keyboard-navigation.ts","../../../projects/forty-cdk/core/src/collection/enabled-handle-navigation.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/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/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/formatter-cache.ts","../../../projects/forty-cdk/core/src/datetime/literal-directive.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/datetime/unicode-digit.ts","../../../projects/forty-cdk/core/src/datetime/segment-directive.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/defaults.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-preview.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/pointer-session.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/host-attributes/host-aria.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/focus-trap/focus-trap.ts","../../../projects/forty-cdk/core/src/focus-trap/focusable-content.ts","../../../projects/forty-cdk/core/src/form-ui-control/form-ui-control-base.ts","../../../projects/forty-cdk/core/src/form-ui-control/hidden-input.ts","../../../projects/forty-cdk/core/src/host-attributes/disabled-reflection.ts","../../../projects/forty-cdk/core/src/form-ui-control/unfocused-value-mirror.ts","../../../projects/forty-cdk/core/src/form-ui-control/text-value-control-base.ts","../../../projects/forty-cdk/core/src/host-attributes/config-class.ts","../../../projects/forty-cdk/core/src/host-attributes/host-type.ts","../../../projects/forty-cdk/core/src/host-attributes/modal-attributes.ts","../../../projects/forty-cdk/core/src/visually-hidden/visually-hidden.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-suppression.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-list-navigation.ts","../../../projects/forty-cdk/core/src/selection/selection.ts","../../../projects/forty-cdk/core/src/selection/range-selection-engine.ts","../../../projects/forty-cdk/core/src/swipe-dismiss/scroll-boundary.ts","../../../projects/forty-cdk/core/src/swipe-dismiss/swipe-dismiss.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/text-direction/text-direction.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-navigator.ts","../../../projects/forty-cdk/core/src/virtualized-navigator/virtualized-navigator-bridge.ts","../../../projects/forty-cdk/core/src/public-api.ts","../../../projects/forty-cdk/core/src/forty-cdk-core.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 every overlay shell in `_internal/`\n * shares: a directive torn down between construction and the next render\n * (synchronous open/close test paths, fast SPA mount+unmount, a harness\n * flushing the render queue inside teardown), 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 * Note the second ordering this leaves intact: when destroy is fully\n * synchronous (the `fixture.destroy()` path), the pending callback flushes\n * *before* the `DestroyRef` hooks run — so `fn` executes once and the\n * `destroyed` flag is set afterwards. The adopters defend that path by tearing\n * the side effect down in their own `DestroyRef.onDestroy` (portal removes the\n * element, the modal shell deactivates inert / scroll lock / focus trap, the\n * overlay shell deactivates its dismissible layer), which runs right after the\n * callback. 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","/**\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\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. `'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  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. Plain `Home` / `End` 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 */\nexport function resolveGridNavigation(\n  event: KeyboardEvent,\n  options: GridNavigationOptions,\n): GridNavigationAction | null {\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 ? 'first' : 'first-in-row';\n    case 'End':\n      return event.ctrlKey ? '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`: treats the grid as a flat list — steps forward / backward\n *   by one cell and, when `loop=true`, wraps at the global ends (last cell\n *   back to the first, and vice versa), skipping disabled cells.\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      return scanNextEnabled(current, count, 1, loop, isDisabled);\n    case 'prev':\n      return scanNextEnabled(current, count, -1, loop, isDisabled);\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. The caller decides\n * whether the intent actually applies (row is an expandable parent in the right\n * open/closed state) and otherwise falls through to grid navigation.\n */\nexport function resolveTreegridExpandCollapse(\n  event: KeyboardEvent,\n  dir: WritingDirection = 'ltr',\n): ExpandCollapseAction | null {\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. The caller decides whether the intent actually applies (the\n * focused node is an expandable parent in the right open/closed state) and\n * otherwise falls through to list navigation.\n */\nexport function resolveTreeExpandCollapse(\n  event: KeyboardEvent,\n  options: TreeExpandCollapseOptions,\n): ExpandCollapseAction | null {\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 { isDevMode } from '@angular/core';\n\nconst 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 * Exposed separately from {@link fortyError} for the one seam that takes a\n * pre-built message string from its caller — `AnchorSlot`'s duplicate-anchor\n * guard, reached by Combobox, Select and TimePicker, each of which owns the\n * `FORCDK-*` code for its own anchor. Prefer `fortyError` / `fortyWarn`\n * everywhere else.\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 `isDevMode()`. 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 (!isDevMode()) {\n    return;\n  }\n  console.warn(formatFortyMessage(spec));\n}\n","import { effect, isDevMode, type Signal } from '@angular/core';\nimport { fortyError } from '../errors/errors';\n\nconst UNSET: unique symbol = Symbol('forty-cdk:unset-input');\n\n/**\n * The sentinel a piece seeds an otherwise-required input with, typed as the\n * input's own `T` so nothing downstream has to widen to `T | undefined`.\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`. The cast is the one place the library lies about the\n * input's type; keep it here rather than at the call sites, and never let the\n * sentinel reach a consumer callback (`compareWith`, `itemToLabel`, …): guard\n * with {@link isUnset} before the 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 = input(unsetInput<T>());\n * ```\n */\nexport function unsetInput<T>(): T {\n  return UNSET as unknown as T;\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): boolean {\n  return value === UNSET;\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 (!isDevMode()) {\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 { isUnset } 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. */\n  readonly value: Signal<T>;\n  /** The option's resolved display label. */\n  readonly label: 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  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 key fn. */\ninterface SelectionSource<T> {\n  readonly window: ReadonlyMap<string, LabelCacheEntry<T>>;\n  readonly value: readonly T[];\n  readonly toFormValue: (item: T) => string;\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 cache is keyed by. */\n  readonly itemToFormValue: Signal<(item: T) => string>;\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 #selectedByKey: 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.#selectedByKey = linkedSignal<SelectionSource<T>, ReadonlyMap<string, LabelCacheEntry<T>>>(\n      {\n        source: () => ({\n          window: this.#windowByKey(),\n          value: deps.value(),\n          toFormValue: deps.itemToFormValue(),\n        }),\n        computation: ({ window, value, toFormValue }, prev) => {\n          const selected = new Map<string, LabelCacheEntry<T>>();\n          for (const item of value) {\n            const key = toFormValue(item);\n            const entry = window.get(key) ?? prev?.value.get(key);\n            if (entry !== undefined) {\n              selected.set(key, entry);\n            }\n          }\n          return selected;\n        },\n      },\n    );\n    this.#selectedEntries = computed(() => [...this.#selectedByKey().values()]);\n    this.#windowEntries = computed(() => [...this.#windowByKey().values()]);\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.#selectedByKey();\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), { id, value, label: item.label(), disabled: item.disabled() });\n  }\n  return byKey;\n}\n","import { APP_ID, InjectionToken, Injectable, type Provider, inject } from '@angular/core';\n\n/**\n * Salt mixed into every id produced by {@link IdGenerator}.\n *\n * Defaults to `inject(APP_ID)` so the emitted ids are byte-identical to\n * Angular's application id out of the box — server and client renders of the\n * same app therefore agree, which is what hydration relies on.\n *\n * Override it per app with {@link provideForIdSalt} when running more than one\n * forty-cdk app on a single page, so each app's ids stay distinct without\n * having to change the global `APP_ID` (which also drives hydration store,\n * event replay, and other subsystems).\n *\n * Part of the blessed core tier: consumers import it from the\n * `forty-cdk/shared` entry point, which carries the library's semver\n * guarantee. Provide it directly only to read the resolved salt — to set one,\n * prefer {@link provideForIdSalt}.\n */\nexport const FOR_ID_SALT = new InjectionToken<string>('forty-cdk id salt', {\n  providedIn: 'root',\n  factory: () => inject(APP_ID),\n});\n\n/**\n * Provides a per-app salt for the ids forty-cdk primitives generate, without\n * touching the global `APP_ID`. Use this when mounting multiple forty-cdk apps\n * on one page so their `aria-controls` / `aria-labelledby` ids don't collide:\n *\n * ```ts\n * import { provideForIdSalt } from 'forty-cdk/shared';\n *\n * bootstrapApplication(AppA, { providers: [provideForIdSalt('a')] });\n * bootstrapApplication(AppB, { providers: [provideForIdSalt('b')] });\n * ```\n *\n * Without it both apps default their salt to `APP_ID` — Angular's default being the literal `'ng'`\n * — so they emit identical id sequences and the duplicate ids mis-resolve across app boundaries.\n *\n * The salt must be deterministic per app instance: a runtime random value would break SSR\n * hydration.\n *\n * @param salt A stable, app-unique salt.\n */\nexport function provideForIdSalt(salt: string): Provider {\n  return { provide: FOR_ID_SALT, useValue: salt };\n}\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 {@link 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.\n   *\n   * @param prefix Optional prefix for the generated ID. Defaults to `for`.\n   */\n  next(prefix = 'for'): string {\n    return `${prefix}-${this.#salt}-${++this.#counter}`;\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\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, 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 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. Warns in dev mode\n   * when it is not the first — a second occupant means the owner's single\n   * coordination surface is ambiguous.\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\n/**\n * Creates a {@link SingleSlot}. Pure signal state: safe in a field\n * initializer, safe under SSR, and needs no injection context.\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  return {\n    value,\n    register(occupant: T): void {\n      const next = [...occupants(), occupant];\n      occupants.set(next);\n      if (next.length > 1) {\n        fortyWarn({\n          code: 'FORCDK-CORE-005',\n          scope: config.primitive,\n          message: `A ${config.owner} coordinates a single ${config.claimant}, but ${next.length} 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    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","/**\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\nfunction shadowHostOf(node: Node): Element | null {\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, InjectionToken } from '@angular/core';\nimport { fortyError } from '../errors/errors';\n\n/**\n * Pluggable, date-library-agnostic seam for `ForCalendar`. Every internal\n * algorithm (paging, the day matrix, comparison, formatting) goes through a\n * `DateAdapter<D>`, so the primitive never hard-depends on a date library.\n *\n * The library ships two adapters behind {@link FOR_DATE_ADAPTER}:\n *\n * - `provideInternationalizedDateAdapter()` — over `@internationalized/date`'s\n *   immutable `CalendarDate`. Recommended for correct date-math and locale-aware\n *   formatting; `@internationalized/date` is an optional peer dependency. Both\n *   `@internationalized/date` adapters operate on the **Gregorian** calendar\n *   today — non-Gregorian calendar systems are deferred to the Temporal adapter\n *   track.\n * - `provideNativeDateAdapter()` — over the built-in `Date`. Zero-dependency\n *   fallback.\n *\n * A `Temporal.PlainDate` adapter is a planned non-breaking addition once the\n * Temporal API is broadly available across browsers.\n *\n * **Calendar system (Gregorian).** The seam abstracts the date *library* and locale-aware\n * *formatting*, not the calendar system's month structure. The calendar grid, month picker and date\n * field assume a Gregorian-structured year: twelve months, `month` in 1-12, the year ending at\n * month 12. An adapter over a different month structure is out of scope. The optional\n * {@link compareDate} hook overrides day-only *ordering* only.\n *\n * Implementations must be pure with respect to their date type: every operation returns a value and\n * never mutates its inputs, so reference equality changes on every change and the values stay\n * signal-friendly.\n *\n * @typeParam D The immutable date representation the adapter operates on.\n */\nexport interface DateAdapter<D> {\n  /**\n   * Today's date in the runtime time zone.\n   *\n   * **SSR / hydration caveat.** The result depends on the runtime time zone, so\n   * a server render and a client hydration can disagree by up to a day near\n   * midnight — the server may compute a different calendar day than the\n   * browser. `ForCalendar` reads this on each render to mark the `data-today` /\n   * `aria-current=\"date\"` cell, so a mismatch surfaces there as a hydration\n   * error and a flicker on the highlighted \"today\" cell.\n   *\n   * **SSR-safe pattern.** Have the consumer supply a fixed \"today\" (or pin a\n   * time zone) for the server render, or defer the today-highlight to\n   * `afterNextRender` so `today()` is only computed client-side. See the\n   * calendar README's \"SSR / hydration\" section.\n   */\n  today(): D;\n\n  /**\n   * Creates a date from its parts.\n   *\n   * @param year Full year (e.g. `2026`).\n   * @param month Month of year, **1-12**.\n   * @param day Day of month, **1-31** (constrained to the month's length).\n   */\n  createDate(year: number, month: number, day: number): D;\n\n  /** The full year of `date` (e.g. `2026`). */\n  getYear(date: D): number;\n\n  /** The month of `date`, **1-12**. */\n  getMonth(date: D): number;\n\n  /** The day of month of `date`, **1-31**. */\n  getDate(date: D): number;\n\n  /** The day of week of `date`, **0-6** where `0` is Sunday and `6` is Saturday. */\n  getDayOfWeek(date: D): number;\n\n  /** The number of days in `date`'s month. */\n  getDaysInMonth(date: D): number;\n\n  /**\n   * The first day of the week as a **0-6** index (`0` = Sunday). Used as the\n   * default when `ForCalendar`'s `firstDayOfWeek` input is `null`. Adapters\n   * return a locale-independent default (`0`); consumers localise it through\n   * the `firstDayOfWeek` input or `provideForCalendarDefaults`.\n   */\n  getFirstDayOfWeek(): number;\n\n  /** Returns a new date `n` days after `date` (negative goes backwards). */\n  addDays(date: D, n: number): D;\n\n  /**\n   * Returns a new date `n` months after `date` (negative goes backwards). The\n   * day of month is constrained to the target month's length (e.g. Jan 31 + 1\n   * month is Feb 28/29, never Mar 3).\n   */\n  addMonths(date: D, n: number): D;\n\n  /**\n   * Returns a new date `n` years after `date` (negative goes backwards). The\n   * day of month is constrained (e.g. Feb 29 + 1 year is Feb 28 in a common\n   * year).\n   */\n  addYears(date: D, n: number): D;\n\n  /**\n   * Compares two dates by their natural ordering — **the full instant**,\n   * including any time component the adapter's `D` carries. Returns a negative\n   * number when `a` is before `b`, `0` when they are equal, and a positive\n   * number when `a` is after `b`.\n   *\n   * This is the canonical comparator and the only one an adapter must\n   * implement. Time-capable adapters (`Date`, `@internationalized/date`'s\n   * `CalendarDateTime`) order by day *and* time; day-only adapters\n   * (`CalendarDate`) order by day alone because that is all their `D` carries.\n   *\n   * **Bounds granularity.** `minDate` / `maxDate` clamping in the date\n   * primitives compares the full instant through `compare`, so a date-time\n   * `min`/`max` clamps identically on every time-capable adapter (e.g. native\n   * `Date` and `CalendarDateTime` produce the same result for the same input).\n   * For the *calendar grid*, where availability is day-granular so the boundary\n   * day of a date-time `min`/`max` stays selectable, use {@link compareDateOf}\n   * (which honours {@link compareDate} when present and otherwise derives a\n   * day-only comparison from the y/m/d getters).\n   */\n  compare(a: D, b: D): number;\n\n  /**\n   * Optionally compares two dates by calendar day only, ignoring any time\n   * component. Returns a negative number when `a`'s day is before `b`'s, `0`\n   * when they fall on the same calendar day, and a positive number when `a`'s\n   * day is after `b`'s.\n   *\n   * Adapters may **omit** this method: {@link compareDateOf} then derives the\n   * day-only comparison from the {@link getYear} / {@link getMonth} /\n   * {@link getDate} getters, which is correct for any adapter. Implement it only\n   * to override that default (e.g. a bespoke day-granular ordering). This\n   * overrides day-only *ordering* only — it does not change the Gregorian month\n   * structure the grid assumes (see the *Calendar system* note on the interface).\n   * Day-only adapters whose {@link compare} already ignores time need not\n   * implement it.\n   */\n  compareDate?(a: D, b: D): number;\n\n  /** Whether `a` and `b` fall on the same calendar day. */\n  isSameDay(a: D, b: D): boolean;\n\n  /** Whether `date` is a valid date of this adapter's type. */\n  isValid(date: D): boolean;\n\n  /**\n   * Formats `date` for display. When `locale` is omitted the runtime's default\n   * locale is used; pass one to force a specific locale for month / weekday /\n   * day-period names.\n   *\n   * **SSR / hydration caveat.** With no `locale` the result resolves against the\n   * runtime's default locale, so a server render and a client hydration can\n   * produce different strings when the server and browser locales differ —\n   * surfacing as a hydration mismatch on every formatted value (heading, weekday\n   * headers, cell labels). The runtime time zone applies too for adapters that\n   * format through a wall-clock instant.\n   *\n   * **SSR-safe pattern.** Pin a `locale` (or format client-side) for the server\n   * render so both environments resolve the same locale. See the calendar\n   * README's \"SSR / hydration\" section.\n   *\n   * @param options Standard `Intl.DateTimeFormat` options (e.g.\n   *   `{ month: 'long', year: 'numeric' }` for a calendar heading,\n   *   `{ weekday: 'short' }` for a column header).\n   * @param locale Optional BCP 47 locale tag governing the formatted names;\n   *   falls back to the runtime's default locale when omitted.\n   */\n  format(date: D, options: Intl.DateTimeFormatOptions, locale?: string): string;\n\n  /**\n   * Whether this adapter's `D` can carry a wall-clock time component (hour /\n   * minute / second). Day-only adapters omit the optional time accessors below\n   * and return `false` (or omit this method); time-capable adapters implement\n   * them and return `true`. `ForTimeField` — and the time granularity of the\n   * date primitives — require a time-capable adapter.\n   */\n  supportsTime?(): boolean;\n\n  /** The hour of `date`, **0-23** (24-hour clock). Time-capable adapters only. */\n  getHours?(date: D): number;\n\n  /** The minute of `date`, **0-59**. Time-capable adapters only. */\n  getMinutes?(date: D): number;\n\n  /** The second of `date`, **0-59**. Time-capable adapters only. */\n  getSeconds?(date: D): number;\n\n  /**\n   * Returns a new date with its time set to the given parts, preserving the\n   * calendar day. Time-capable adapters only.\n   *\n   * @param hours Hour of day, **0-23**.\n   * @param minutes Minute of hour, **0-59**.\n   * @param seconds Second of minute, **0-59**.\n   */\n  setTime?(date: D, hours: number, minutes: number, seconds: number): D;\n}\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 * A {@link DateAdapter} narrowed to one that implements the optional time\n * accessors. Produced by {@link assertTimeCapable} so time primitives can call\n * `getHours` / `setTime` / etc. without optional-chaining.\n *\n * @typeParam D The adapter's immutable date-time representation.\n */\nexport type TimeCapableDateAdapter<D> = DateAdapter<D> &\n  Required<Pick<DateAdapter<D>, 'getHours' | 'getMinutes' | 'getSeconds' | 'setTime'>>;\n\n/**\n * Injection token holding the active {@link DateAdapter}. Provide it with\n * `provideInternationalizedDateAdapter()` or `provideNativeDateAdapter()`.\n * There is no application-wide default — a calendar with no adapter in scope\n * throws a descriptive error.\n */\nexport const FOR_DATE_ADAPTER = new InjectionToken<DateAdapter<unknown>>('FOR_DATE_ADAPTER');\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","const AM_TIME = new Date(2000, 0, 1, 1);\nconst PM_TIME = new Date(2000, 0, 1, 13);\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, { hour: 'numeric' }).resolvedOptions().hourCycle;\n  return cycle === 'h11' || cycle === 'h12' ? 12 : 24;\n}\n\n/** Maps a 0-23 hour to its 12-hour display value and AM/PM period. */\nexport function to12(hour: number): { h12: number; pm: boolean } {\n  return { h12: ((hour + 11) % 12) + 1, pm: hour >= 12 };\n}\n\n/** Combines a 1-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, { hour: 'numeric', hour12: true });\n  const read = (date: Date): string =>\n    fmt.formatToParts(date).find((part) => part.type === 'dayPeriod')?.value ?? '';\n  return { am: read(AM_TIME) || 'AM', pm: read(PM_TIME) || 'PM' };\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","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 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  /** Flushes any mid-typing transient and clears the typing buffer (blur). */\n  endTyping(): 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\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}\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).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 null;\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 typing.buffer;\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 String(value).padStart(type === 'year' ? 4 : 2, '0');\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  }\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   */\n  endTyping(): void {\n    if (this.#pendingSettle) {\n      this.#commit(this.#host.parts(), false);\n    }\n    this.#typing.set(null);\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      this.setDayPeriod(delta > 0 ? 'pm' : 'am');\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: number;\n    if (type === 'hour') {\n      next = this.#stepHour(current, delta);\n    } else if (type === 'minute' || type === 'second') {\n      next = (((current + delta) % 60) + 60) % 60;\n    } else if (type === 'year') {\n      next = Math.min(\n        this.#host.segmentMax(type),\n        Math.max(this.#host.segmentMin(type), current + delta),\n      );\n    } else {\n      const min = this.#host.segmentMin(type);\n      const range = this.#host.segmentMax(type) - min + 1;\n      next = min + ((((current - min + delta) % range) + range) % range);\n    }\n    this.#commit(this.#withPart(type, next), false);\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 { h12, pm } = to12(current);\n    const nextH12 = ((((h12 - 1 + delta) % 12) + 12) % 12) + 1;\n    return from12(nextH12, pm);\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, type Signal, type WritableSignal } from '@angular/core';\n\nimport type { RovingTabindex } from '../roving-tabindex/roving-tabindex';\nimport { dayPeriodNames, resolveHourCycle } 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  /** 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  /** BCP 47 locale driving segment order, separators, and AM/PM names. */\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  protected readonly config: BaseFieldEngineConfig<D>;\n\n  protected readonly cycle = computed(() =>\n    resolveHourCycle(this.config.locale() ?? undefined, this.config.hourCycle()),\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  protected 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  protected readonly periodNames = computed(() =>\n    dayPeriodNames(this.config.locale() ?? undefined),\n  );\n\n  protected editor!: SegmentEditor<P, T>;\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      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    });\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(): void {\n    this.editor.endTyping();\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  /**\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  protected 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    this.config.onCommit(this.composeFrom(next));\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// 1 Feb is deliberately distinct in day vs month so a locale that reuses a\n// digit can't mask the part ordering. The year (2000) is irrelevant — only the\n// `type` of each formatted part is read.\nconst REFERENCE_DATE = new Date(2000, 1, 1);\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.\nconst REFERENCE_DATE_TIME = new Date(2000, 1, 1, 13, 23, 45);\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    year: 'numeric',\n    month: '2-digit',\n    day: '2-digit',\n  }).formatToParts(REFERENCE_DATE);\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    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(REFERENCE_DATE_TIME);\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 { assertTimeCapable, type DateAdapter, type TimeCapableDateAdapter } 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 * 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 *\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 *   That error keeps the `[forty-cdk/core]` prefix rather than taking a `scope`\n *   of its own: a day-only adapter under a time granularity already threw from\n *   `DateFieldEngine.specs` — the derivation that asked for a time segment —\n *   before any value reaches serialization, so this branch is a second line of\n *   defence rather than a report a consumer reads first.\n */\nexport function serializeISODate<D>(\n  adapter: DateAdapter<D>,\n  date: D,\n  granularity: DateSerializeGranularity,\n  piece: 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);\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 * 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 { assertTimeCapable, type DateAdapter, type TimeCapableDateAdapter } 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 } 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 coarser 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.#config.locale() ?? undefined, granularity, this.cycle());\n  });\n\n  /**\n   * The entered parts. A `linkedSignal` keyed on `source`: a non-null write\n   * (consumer, `[formField]`, or our own compose) rehydrates the segments from\n   * the date. A `null` transition is disambiguated by the prior parts: an\n   * *internal* edit clearing one segment always leaves the others, so\n   * `previous` still carries a filled part and is preserved (clearing the day\n   * never wipes the month / year); an *external* reset of a complete value\n   * leaves `previous` fully filled, so the field clears.\n   */\n  protected readonly parts = linkedSignal<D | null, DateTimeParts>({\n    source: () => this.#config.source(),\n    computation: (current, previous) => {\n      if (current !== null) {\n        const adapter = this.#config.adapter;\n        const parts: DateTimeParts = {\n          day: adapter.getDate(current),\n          month: adapter.getMonth(current),\n          year: adapter.getYear(current),\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(current);\n          parts.minute = time.getMinutes(current);\n          parts.second = time.getSeconds(current);\n          parts.dayPeriod = time.getHours(current) >= 12 ? 1 : 0;\n        }\n        return parts;\n      }\n      const prior = previous?.value;\n      if (prior && this.#someEditableEmpty(prior)) {\n        return prior;\n      }\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\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.cycle() === 12 ? 1 : 0;\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 ? 12 : 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 source = this.#config.source();\n    if (source === 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      source,\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.#config.locale() ?? undefined,\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  #someEditableEmpty(parts: DateTimeParts): boolean {\n    return this.editableOrder().some((type) => parts[type] === null);\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  /** Composes a parts record into the value, clamped to the bounds, or `null` while incomplete. */\n  protected composeFrom(parts: DateTimeParts): D | null {\n    const granularity = this.#config.granularity();\n    const needHour = granularity !== 'day';\n    const needMinute = granularity === 'minute' || granularity === 'second';\n    const needSecond = granularity === 'second';\n    const complete =\n      parts.day !== null &&\n      parts.month !== null &&\n      parts.year !== null &&\n      (!needHour || parts.hour !== null) &&\n      (!needMinute || parts.minute !== null) &&\n      (!needSecond || parts.second !== null);\n    if (!complete) {\n      return null;\n    }\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","/**\n * Creates a memoized `Intl.DateTimeFormat` factory shared by the date adapters.\n *\n * Constructing an `Intl.DateTimeFormat` triggers an expensive ICU locale /\n * pattern resolution, so the adapters cache one instance per distinct\n * `(locale, options)` combination. The returned function derives its key from\n * the locale tag and the JSON-serialized options and does a get-or-create\n * against a private map, so repeated formatting with the same shape reuses the\n * same formatter.\n *\n * The cache is **unbounded**: its size is bounded by the app's distinct\n * formatting needs — roughly (locales in use) × (the small fixed set of option\n * shapes the primitives request) — not by the volume of dates formatted, so it\n * grows to at most a few dozen entries for the lifetime of the DI-scoped adapter\n * that owns it.\n *\n * @returns A function that returns the cached `Intl.DateTimeFormat` for the\n *   given `locale` (or the runtime default when omitted) and `options`.\n */\nexport function createFormatterCache(): (\n  locale: string | undefined,\n  options: Intl.DateTimeFormatOptions,\n) => Intl.DateTimeFormat {\n  const cache = new Map<string, Intl.DateTimeFormat>();\n  return (locale, options) => {\n    const key = `${locale ?? ''}${JSON.stringify(options)}`;\n    let formatter = cache.get(key);\n    if (formatter === undefined) {\n      formatter = new Intl.DateTimeFormat(locale, options);\n      cache.set(key, formatter);\n    }\n    return formatter;\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 { computed, linkedSignal, type Signal, signal } from '@angular/core';\n\nimport type { HostRovingItemHandle } from './host-roving-context';\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 `hasActive` / `tabindexFor`, so the\n * consumer's first-enabled fallback re-engages and the group keeps exactly\n * one tab stop even before reconciliation settles.\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 * `'first-enabled'` promotes the first enabled handle directly (push-based,\n * for a container whose item tabindex reads {@link active} and needs a\n * concrete owner rather than a null pointer, e.g. Tree). Omitting `items`\n * yields a pass-through of the raw pointer for consumers that own no roving\n * collection (date-field / time-field).\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  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  /**\n   * Whether a usable active element currently owns the tab stop. `false`\n   * when nothing is active **or** the active element is stale (detached /\n   * disabled), signalling the consumer to fall back to its first-enabled\n   * entry point. Reactive — wire the per-item `tabindex` gate to this rather\n   * than `active() !== null`.\n   */\n  readonly hasActive: Signal<boolean>;\n\n  constructor(\n    items?: () => readonly HostRovingItemHandle[],\n    options: { fallback?: 'none' | 'first-enabled' } = {},\n  ) {\n    const fallback = options.fallback ?? 'none';\n    this.#active = linkedSignal({\n      source: () => {\n        const raw = this.#rawActive();\n        return { items: items && raw !== null ? items() : null, raw };\n      },\n      computation: ({ items: list, raw }) => {\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        return fallback === 'first-enabled'\n          ? (list.find((item) => !item.disabled())?.host ?? null)\n          : null;\n      },\n    });\n    this.active = this.#active;\n    this.hasActive = computed(() => {\n      const el = this.#active();\n      return el !== null && !isStale(el);\n    });\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), returns\n   * `-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    const active = this.#active();\n    if (active === null || isStale(active)) {\n      return -1;\n    }\n    return active === el ? 0 : -1;\n  }\n\n  setActive(el: HTMLElement | null): void {\n    this.#rawActive.set(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.\n   */\n  unregister(el: HTMLElement): void {\n    if (this.#active() === el) {\n      this.#rawActive.set(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.#rawActive.set(target);\n    }\n    target.focus();\n  }\n}\n\nfunction isStale(el: HTMLElement): boolean {\n  return (\n    !el.isConnected || el.hasAttribute('disabled') || el.getAttribute('aria-disabled') === 'true'\n  );\n}\n","import { computed, linkedSignal, type Signal, signal, type WritableSignal } 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/** 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 (a Signal Forms reset or a consumer\n   * `[(value)]=\"null\"`, where the generation is unchanged) **clears** the\n   * endpoint. Each endpoint reads its own `previous`, so there is no\n   * 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   * 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      const endpoint = committed.range[which];\n      return this.#config.normalizeEndpointSource\n        ? this.#config.normalizeEndpointSource(endpoint)\n        : endpoint;\n    }\n    if (previous && committed.generation !== previous.source.generation) {\n      return previous.value;\n    }\n    return null;\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 value = 0;\n  for (let c = code - 1; value < 9 && DECIMAL_DIGIT.test(String.fromCodePoint(c)); c--) {\n    value++;\n  }\n  return value;\n}\n","import { computed, Directive, ElementRef, inject, type Signal } from '@angular/core';\n\nimport { registerHandle } from '../collection/register-handle';\nimport type { WritingDirection } from '../keyboard-navigation/keyboard-navigation';\nimport type { RovingTabindex } from '../roving-tabindex/roving-tabindex';\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. All state lives on the root via {@link SegmentEditorContext};\n * the segment only reads it and forwards 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.inputmode]': 'inputmode()',\n    '[attr.autocorrect]': '\"off\"',\n    '[attr.spellcheck]': '\"false\"',\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    '(focus)': 'onFocus()',\n    '(blur)': 'onBlur()',\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  protected 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  protected readonly valueNow = computed(() => this.ctx.delegate.segmentValue(this.segment()));\n\n  protected readonly inputmode = computed<'numeric' | null>(() =>\n    this.segment() === 'dayPeriod' ? null : 'numeric',\n  );\n\n  protected readonly highlighted = computed(\n    () => this.ctx.roving.active() === this.host.nativeElement,\n  );\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  protected 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  protected onFocus(): void {\n    this.ctx.delegate.focusSegment(this.segment());\n  }\n\n  protected onBlur(): void {\n    this.ctx.delegate.endTyping();\n  }\n\n  protected onKeyDown(event: KeyboardEvent): void {\n    if (this.ctx.effectiveDisabled()) {\n      return;\n    }\n    const type = this.segment();\n    const key = event.key;\n    const digit = unicodeDigitValue(key);\n    if (digit !== null) {\n      event.preventDefault();\n      this.ctx.delegate.typeDigit(type, digit);\n      return;\n    }\n    if (type === 'dayPeriod' && this.ctx.delegate.setDayPeriodFromKey(key)) {\n      event.preventDefault();\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","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// 1:23:45 PM — distinct hour / minute / second values and a PM reference so the\n// `dayPeriod` part is present to read back. Only each part's `type` (and the\n// separators) are used; the concrete value never surfaces.\nconst REFERENCE_TIME = new Date(2000, 0, 1, 13, 23, 45);\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 = { hour: '2-digit', hour12: hourCycle === 12 };\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(REFERENCE_TIME);\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 './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, 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.#config.locale() ?? undefined, 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 our own compose) rehydrates the segments from\n   * the date-time. A `null` transition is disambiguated by the prior parts: an\n   * *internal* edit clearing one segment leaves the others, so `previous` still\n   * carries a filled part and is preserved; an *external* reset of a complete\n   * value leaves `previous` fully filled, so the field clears.\n   */\n  protected readonly parts = linkedSignal<D | null, TimeParts>({\n    source: () => this.#config.source(),\n    computation: (current, previous) => {\n      if (current !== null) {\n        const adapter = this.#config.adapter;\n        return {\n          hour: adapter.getHours(current),\n          minute: adapter.getMinutes(current),\n          second: adapter.getSeconds(current),\n          dayPeriod: adapter.getHours(current) >= 12 ? 1 : 0,\n        };\n      }\n      const prior = previous?.value;\n      if (prior && (prior.hour === null || prior.minute === null || prior.second === null)) {\n        return prior;\n      }\n      return { hour: null, minute: null, second: null, dayPeriod: null };\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.cycle() === 12 ? 1 : 0;\n    }\n    return 0;\n  }\n\n  segmentMax(type: SegmentType): number {\n    if (type === 'hour') {\n      return this.cycle() === 12 ? 12 : 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, 1 AM in 12-hour), 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  /** Composes a parts record into the value, clamped to the bounds, or `null` while incomplete. */\n  protected composeFrom(parts: TimeParts): D | null {\n    const granularity = this.#config.granularity();\n    const needMinute = granularity !== 'hour';\n    const needSecond = granularity === 'second';\n    const complete =\n      parts.hour !== null &&\n      (!needMinute || parts.minute !== null) &&\n      (!needSecond || parts.second !== null);\n    if (!complete) {\n      return null;\n    }\n    const base = this.#config.source() ?? timeSentinel(this.#config.adapter);\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  #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 './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\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","import { InjectionToken, Optional, type Provider, SkipSelf } from '@angular/core';\n\n/**\n * Internal helper that builds the canonical defaults pair for a primitive:\n * an `InjectionToken<D>` and a paired `provideFor<X>Defaults(overrides)`\n * function. Every primitive in the library that exposes injector-scoped\n * defaults uses this — the convention is documented in `CLAUDE.md` under\n * \"Defaults providers\".\n *\n * Behavior of the generated provider function:\n *\n * - Reads the parent value of the same token via\n *   `[[new SkipSelf(), new Optional(), TOKEN]]` so each call inherits\n *   ancestor scopes.\n * - Per key, the value present-and-not-`undefined` in `overrides` wins, else\n *   the parent's value (when not `undefined`), else the library `fallback`.\n *   Only `undefined` is treated as \"key omitted\" — a deliberate `null` (or any\n *   other defined value) in `overrides` or `parent` is a real override and is\n *   kept. The parent's already-merged value beats the library fallback, which\n *   means a component-level `provideFor<X>Defaults({ a: 1 })` overlaid on an\n *   app-level `provideFor<X>Defaults({ a: 0, b: 2 })` resolves to\n *   `{ a: 1, b: 2 }` — partial overrides only touch the keys they list.\n * - Returns a `Provider[]` so callers can spread additional providers\n *   (e.g. a per-scope coordinator class) into the same array.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * entry points, with no semver guarantee. What consumers see is the generated\n * pair each primitive re-exports from its own barrel: `provideFor<X>Defaults`\n * and (when public) its token.\n *\n * @param name Display name of the token (used as the InjectionToken's\n *   description, e.g. `'FOR_TOOLTIP_DEFAULTS'`).\n * @param fallback Library defaults — read at the root of the injector tree\n *   when no consumer has called the provider helper. Returned by reference,\n *   so don't mutate it.\n */\nexport function createDefaults<D extends object>(\n  name: string,\n  fallback: D,\n): {\n  /** Token consumers inject to read the resolved defaults for the current scope. */\n  token: InjectionToken<D>;\n  /** Provider factory that merges overrides with the parent scope and the fallback. */\n  provideDefaults: (overrides?: Partial<D>) => Provider[];\n} {\n  const token = new InjectionToken<D>(name, {\n    providedIn: 'root',\n    factory: () => fallback,\n  });\n\n  const provideDefaults = (overrides: Partial<D> = {}): Provider[] => [\n    {\n      provide: token,\n      useFactory: (parent: D | null): D => mergeDefaults(overrides, parent, fallback),\n      deps: [[new SkipSelf(), new Optional(), token]],\n    },\n  ];\n\n  return { token, provideDefaults };\n}\n\nfunction mergeDefaults<D extends object>(overrides: Partial<D>, parent: D | null, fallback: D): D {\n  const result = { ...fallback } as D;\n  // Parent already merged its own overrides over the fallback, so it wins\n  // over the library fallback for any key it owns.\n  if (parent) {\n    for (const key of Object.keys(parent) as (keyof D)[]) {\n      const value = parent[key];\n      if (value !== undefined) {\n        result[key] = value;\n      }\n    }\n  }\n  // Overrides win over both parent and fallback for the keys they list.\n  for (const key of Object.keys(overrides) as (keyof D)[]) {\n    const value = overrides[key];\n    if (value !== undefined) {\n      result[key] = value as D[keyof D];\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}\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 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  let containerIndex = -1;\n\n  for (let i = 0; i < containers.length; i++) {\n    if (rectContains(containers[i]!.rect, point.x, point.y)) {\n      containerIndex = i;\n      break;\n    }\n  }\n\n  if (containerIndex < 0) {\n    let minDist = Infinity;\n    for (let i = 0; i < containers.length; i++) {\n      const d = clampedDistance(containers[i]!.rect, point.x, point.y);\n      if (d < minDist) {\n        minDist = d;\n        containerIndex = i;\n      }\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","/** A floating clone of the dragged element that follows the pointer. */\nexport interface DragPreview {\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 the transform\n   * transition ends (with a timeout fallback scaled from the element's computed\n   * `transition-duration` plus a small safety margin, so a transition longer than the old\n   * hard-coded 500 ms is not cut short). Marks the element `data-settling` so a consumer\n   * CSS rule keyed on it governs duration / easing. If no transition is configured, destroys\n   * immediately. Caller must pass the browser `Window`.\n   */\n  settle(x: number, y: number, win: Window): void;\n  /** Remove the preview from the DOM. Idempotent. */\n  destroy(): void;\n}\n\nconst SETTLE_TIMEOUT_SAFETY_MS = 50;\n\nfunction parseDurationMs(segment: string): number {\n  const value = parseFloat(segment);\n  if (!Number.isFinite(value) || value <= 0) {\n    return 0;\n  }\n  return segment.trim().endsWith('ms') ? value : value * 1000;\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    const duration = win.getComputedStyle(target).transitionDuration;\n    const firstSegment = duration.split(',')[0]?.trim() ?? '';\n    const durationMs = parseDurationMs(firstSegment);\n    if (!firstSegment || durationMs === 0) {\n      target.style.transform = `translate(${x}px, ${y}px)`;\n      destroyFn();\n      return;\n    }\n    let finished = false;\n    const controller = new AbortController();\n    const finish = (): void => {\n      if (finished) {\n        return;\n      }\n      finished = true;\n      controller.abort();\n      destroyFn();\n    };\n    const onEnd = (event: TransitionEvent): void => {\n      if (event.propertyName && event.propertyName !== 'transform') {\n        return;\n      }\n      finish();\n    };\n    target.addEventListener('transitionend', onEnd, { once: true, signal: controller.signal });\n    win.setTimeout(finish, durationMs + SETTLE_TIMEOUT_SAFETY_MS);\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\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. Caller must gate on a\n * 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 */\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  clone.removeAttribute('data-testid');\n  clone.removeAttribute('id');\n\n  const descendants = clone.querySelectorAll('[data-testid], [id]');\n  descendants.forEach((el) => {\n    el.removeAttribute('data-testid');\n    el.removeAttribute('id');\n  });\n\n  doc.body.appendChild(clone);\n\n  const destroy = (): void => {\n    clone.remove();\n  };\n\n  return {\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. Caller must gate on a browser platform.\n */\nexport function createTemplatePreview(\n  nodes: readonly Node[],\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  doc.body.appendChild(wrapper);\n\n  const destroy = (): void => {\n    onDestroy();\n    wrapper.remove();\n  };\n\n  return {\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","/**\n * Shared keyboard resolvers for container-level drag-reorder coordinators\n * (`ForTreeNodeDrag`, `ForListboxReorder`). Framework-free and unit-testable in\n * 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 chord**\n * (`Ctrl/Cmd+Space`) that never collides with native activation, plus a shared\n * commit / cancel vocabulary while a node is lifted.\n */\n\n/**\n * Whether a key press is the \"lift\" chord (`Ctrl+Space` or `Cmd+Space`) used to\n * pick up the focused item and start a keyboard drag.\n */\nexport function isDragLiftKey(event: KeyboardEvent): boolean {\n  return (event.ctrlKey || event.metaKey) && event.key === ' ';\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' || 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\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  /** The host's document. Read for `activeElement` when a `focusout` reports no destination. */\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.\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 * `document.activeElement` 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 = config.document.activeElement;\n    if (active !== null && host.contains(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","/**\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)` fires on the first move that crosses `armThreshold`, before the session\n *   arms or captures the pointer. Return `false` to abort the session in flight (e.g. the\n *   grabbed element has since vanished): the document listeners are torn down and no further\n *   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 * **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. Return `false` to abort the session in flight (the grabbed element vanished, etc.);\n   * the session tears its listeners down and fires no 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: (event: PointerEvent) => 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);\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    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      removeClickTrap();\n    };\n    const controller = new AbortController();\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') {\n          event.preventDefault();\n          event.stopPropagation();\n          abort();\n        }\n      };\n      document.addEventListener('keydown', escape, options);\n    }\n  };\n\n  const hostListener = new AbortController();\n  host.addEventListener('pointerdown', down, { 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","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 measured preview size, the resolved boundary, the axis-lock origin, and the\n * boundary/axis-lock clamp applied on every 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.#previewSize = { width: rect.width, height: rect.height };\n    this.#lockOrigin = { x: point.x - this.#grabOffsetX, y: point.y - this.#grabOffsetY };\n    this.#boundaryEl = boundary;\n    this.#lockAxis = lockAxis;\n    this.#preview = preview\n      ? 'settle' in preview\n        ? preview\n        : wrapPreview(preview)\n      : createDragPreview(source, doc);\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 whole dataset — the start\n * edge targets index `0`, the end edge the last index — independent of which rows\n * are currently rendered, so a concurrent 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 post-removal `from` / `to` pair (matching {@link translateWindowReorder}), so\n * `moveItemInArray` over the full array moves the right row.\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  const target = Math.round(fraction * (params.count - 1));\n  return { from: params.from, to: indexAfterRemoval(target, params.from) };\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  /** scrollWidth in CSS pixels. */\n  readonly scrollWidth: number;\n  /** scrollHeight in CSS pixels. */\n  readonly scrollHeight: number;\n}\n\n/**\n * Observes a target element's size with `ResizeObserver` and exposes the\n * result as a signal. Updates fire only when width/height/scrollWidth/\n * scrollHeight actually change.\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.\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 scrollWidth/Height changes via 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 { computed, ElementRef, inject, type Signal } from '@angular/core';\n\n/**\n * Resolves the `aria-labelledby` a piece should expose: the host element's\n * pre-existing **static** `aria-labelledby` when present, else the library's\n * own generated fallback (a trigger / heading / label id).\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 host binding. This mirrors\n * 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 consumer = staticHostAttribute('aria-labelledby');\n  return computed(() => 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 * Resolves the `aria-describedby` a piece should expose: the host element's\n * pre-existing **static** `aria-describedby` **composed** with the library's\n * own description ids, consumer ids first.\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 *\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 consumer = staticHostAttribute('aria-describedby');\n  return computed(() => composeIds(consumer, fallback()));\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\nfunction staticHostAttribute(name: string): string | null {\n  const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n  return host.getAttribute(name) || null;\n}\n","import { DestroyRef, effect, ElementRef, inject, InjectionToken, type Signal } from '@angular/core';\nimport type { ValidationError } from '@angular/forms/signals';\n\nimport { composeIds } from '../host-attributes/host-aria';\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 *\n * Lives in `_internal/` (not in `lib/field/`) so `FormUiControlBase` can wire\n * itself to a field without statically importing the field directives — that\n * would defeat tree-shaking (importing one form control would pull in the\n * whole `field` primitive) and invert the `lib → _internal` layering.\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   * 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 ValidationError.WithOptionalFieldTree[]>;\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   * 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 slot; returns an unregister callback. The field exposes a\n   * single `labelId` (not an id list), so one `[forLabel]` per field is the\n   * supported shape. Registrations are **counted** (not a boolean) so unmounting\n   * one of several accidental duplicates never drops the association while\n   * another is still mounted; a duplicate is flagged with a dev-mode warning.\n   */\n  registerLabel(): () => void;\n  /** Register a description slot; returns an unregister callback. Counted, single `[forFieldDescription]` per field — see {@link registerLabel}. */\n  registerDescription(): () => void;\n  /** Register an error slot; returns an unregister callback. Counted, single `[forFieldError]` per field — see {@link registerLabel}. */\n  registerError(): () => 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 a non-labelable element (the `role=\"group\"` of a\n   * segmented date / time field), so label-click activation stays consistent\n   * across host shapes and control anatomies.\n   */\n  clickControl(): void;\n}\n\n/** Injection token for the surrounding `ForField` coordination contract. */\nexport const FOR_FIELD_CONTEXT = new InjectionToken<ForFieldContext>('FOR_FIELD_CONTEXT');\n\nfunction applyAttr(el: HTMLElement, name: string, value: string | null): void {\n  if (value === null) {\n    el.removeAttribute(name);\n  } else if (el.getAttribute(name) !== value) {\n    el.setAttribute(name, value);\n  }\n}\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`;\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.\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  let previousTarget: HTMLElement | null = null;\n  let ownsId = false;\n  let consumerDescribedBy: string | 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 = labelledElement ? labelledElement() : el;\n\n    if (previousTarget !== target) {\n      if (previousTarget) {\n        clearFieldAttrs(previousTarget, ownsId, field.controlId(), consumerDescribedBy);\n        ownsId = false;\n      }\n      consumerDescribedBy = target ? target.getAttribute('aria-describedby') : 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    applyAttr(target, 'aria-labelledby', field.labelledBy());\n    applyAttr(target, 'aria-describedby', composeIds(consumerDescribedBy, field.describedBy()));\n    applyAttr(target, 'aria-errormessage', field.errorMessageId());\n  });\n\n  inject(DestroyRef).onDestroy(() => {\n    if (previousTarget) {\n      clearFieldAttrs(previousTarget, ownsId, field.controlId(), consumerDescribedBy);\n    }\n  });\n}\n\n/**\n * Removes the field's association attributes (`aria-labelledby` /\n * `aria-errormessage`) from a previously-targeted element, restores its\n * `aria-describedby` to the consumer's captured value (or removes it when there\n * was none), and drops the field-owned `id` when this helper set it. Symmetric\n * with the migration-cleanup branch so an arbitrary foreign `labelledElement`\n * is left clean once the control is destroyed or the target migrates.\n */\nfunction clearFieldAttrs(\n  target: HTMLElement,\n  ownsId: boolean,\n  controlId: string,\n  consumerDescribedBy: string | null,\n): void {\n  applyAttr(target, 'aria-labelledby', null);\n  applyAttr(target, 'aria-describedby', consumerDescribedBy);\n  applyAttr(target, 'aria-errormessage', null);\n  if (ownsId && target.getAttribute('id') === controlId) {\n    target.removeAttribute('id');\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 { composedParentElement } 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\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 = [\n  ...Object.entries(FOCUSABLE_LOCAL_NAME_QUALIFIERS).map(([name, qualifier]) => name + qualifier),\n  ...FOCUSABLE_ATTRIBUTE_CLAUSES,\n].join(',');\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 * - carries `[inert]` itself, or is nested under an `[inert]` ancestor below `root`;\n * - is hidden via CSS (`display: none` on the element or any ancestor below `root`, or\n *   `visibility: hidden` / `collapse` on the element itself).\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 !el.hasAttribute('hidden') && !hasInertAncestor(el, root) && !isCssHidden(el, root);\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 */\nexport function isTabbableCandidate(el: HTMLElement, root: HTMLElement): boolean {\n  return el.tabIndex >= 0 && isFocusableCandidate(el, root);\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 firstIndex = candidates.findIndex((el) => isTabbableCandidate(el, container));\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 (isTabbableCandidate(candidate, container)) {\n      return { first, last: candidate };\n    }\n  }\n  return { first, last: first };\n}\n\nconst FOCUSABLE_LOCAL_NAMES = new Set(Object.keys(FOCUSABLE_LOCAL_NAME_QUALIFIERS));\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 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')) {\n      return true;\n    }\n    cur = composedParentElement(cur);\n  }\n  return false;\n}\n\nfunction isCssHidden(el: HTMLElement, root: HTMLElement): boolean {\n  const win = el.ownerDocument.defaultView;\n  if (!win || typeof win.getComputedStyle !== 'function') {\n    return false;\n  }\n  let cur: HTMLElement | null = el;\n  while (cur && cur !== root) {\n    const style = win.getComputedStyle(cur);\n    if (style.display === 'none') {\n      return true;\n    }\n    if (cur === el && (style.visibility === 'hidden' || style.visibility === 'collapse')) {\n      return true;\n    }\n    cur = composedParentElement(cur);\n  }\n  return false;\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n  DestroyRef,\n  DOCUMENT,\n  ElementRef,\n  Injectable,\n  inject,\n  isDevMode,\n  PLATFORM_ID,\n} from '@angular/core';\n\nimport { composedContains, resolveActiveElement } from '../composed-tree/composed-tree';\nimport {\n  findTabbableEdges,\n  isFocusableCandidate,\n  queryFocusableCandidates,\n} from './focusable-candidate';\nimport { fortyWarn } from '../errors/errors';\n\n/**\n * Returns the first focusable descendant of `container`, or `null` if none exists.\n *\n * Excludes `[hidden]`, `[inert]` subtrees and elements hidden via CSS. A candidate carrying\n * `tabindex=\"-1\"` still qualifies — this is the focusable set, not the Tab cycle. Descends into\n * 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 * 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\n  readonly #onKeyDown = (event: KeyboardEvent): void => this.#handleKeyDown(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.#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.#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 { first, last } = findTabbableEdges(this.#container);\n    const active = resolveActiveElement(this.#document);\n    if (first === null || last === null) {\n      event.preventDefault();\n      if (!composedContains(this.#container, active)) {\n        this.#focusContainer();\n      }\n      return;\n    }\n\n    if (!composedContains(this.#container, active)) {\n      // Focus jumped outside the trap (e.g. user clicked address bar then\n      // tabbed back). Pull it back in.\n      event.preventDefault();\n      first.focus();\n      return;\n    }\n    if (event.shiftKey && active === first) {\n      event.preventDefault();\n      last.focus();\n    } else if (!event.shiftKey && active === last) {\n      event.preventDefault();\n      first.focus();\n    }\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 (isDevMode() && 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 { isFocusableCandidate, queryFocusableCandidates } 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]`, `[inert]` and\n * CSS-hidden elements do not count, and 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: ['disabled', 'hidden', 'inert', 'tabindex', 'type', 'contenteditable'],\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 {\n  booleanAttribute,\n  computed,\n  Directive,\n  effect,\n  ElementRef,\n  inject,\n  input,\n  model,\n  output,\n} from '@angular/core';\nimport type { ValidationError } from '@angular/forms/signals';\n\nimport { FOR_FIELDSET_CONTEXT } from '../field/fieldset-context';\nimport { 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  /** When true, interaction is ignored but the control stays focusable; `aria-readonly=\"true\"`. */\n  readonly readonly = input(false, { transform: booleanAttribute });\n\n  /** Reflected as `aria-required=\"true\"` when truthy. */\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 ValidationError.WithOptionalFieldTree[]>([]);\n\n  /**\n   * Set to true on blur (via {@link markTouched}). Two-way bindable for\n   * 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 (blur, dismiss,\n   * selection-commit) — including repeats once the control is already touched.\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  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]`. This is the value that gates interaction and drives\n   * `aria-disabled` / `data-disabled` — a native `<fieldset disabled>` does not\n   * reach custom-role controls (`forSwitch`, `forCheckbox`, …), so the group's\n   * disabled state must compose in here. Subclasses read this, never the raw\n   * {@link disabled} input.\n   */\n  readonly effectiveDisabled = computed(\n    () => this.disabled() || (this.#fieldset?.disabled() ?? 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  /**\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    injectFieldWiring({\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      focus: this.focus?.bind(this),\n    });\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\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/**\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 */\nexport function injectHiddenInput<T = string>(config: HiddenInputConfig<T>): void {\n  if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n    return;\n  }\n\n  const host = inject<ElementRef<HTMLElement>>(ElementRef);\n  const doc = inject(DOCUMENT);\n  const inputs: HTMLInputElement[] = [];\n\n  effect(() => {\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\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  inject(DestroyRef).onDestroy(() => {\n    for (const input of inputs) {\n      input.remove();\n    }\n    inputs.length = 0;\n  });\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 { DOCUMENT, effect, inject } from '@angular/core';\n\ntype ValueElement = HTMLInputElement | HTMLTextAreaElement;\n\n/**\n * Mirrors an external value string onto a native `<input>` / `<textarea>`'s\n * `.value`, but only while the element is **not** focused — assigning `.value`\n * mid-edit would jump the caret. Live typing flows in through the element's own\n * `input` listener, so this never fights the user's editing; it reconciles the\n * displayed text only for writes that originate outside the element (a consumer\n * `[(value)]` / `[formField]` push, or a post-commit reformat).\n *\n * The three text-valued controls all need this exact guard but obtain their\n * target element differently: `ForInput` / `ForTextarea` and `ForNumberInput`\n * own a host element present from construction, whereas `ForOtpInput` injects\n * its real `<input>` lazily after hydration. The `el` accessor therefore returns\n * `HTMLInputElement | HTMLTextAreaElement | null`; a `null` target is skipped and\n * the effect re-runs once the element appears (it is read reactively).\n *\n * Writing the DOM is a genuine side effect, not signal propagation, so this is a\n * sanctioned `effect()` use. Must be called from an injection context (it injects\n * `DOCUMENT` and creates an `effect`), typically a directive constructor.\n *\n * Internal core tier — exported from `forty-cdk/core` for the library's own\n * 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 */\nexport function mirrorUnfocusedValue(el: () => ValueElement | null, value: () => string): void {\n  const document = inject(DOCUMENT);\n  effect(() => {\n    const element = el();\n    if (!element) {\n      return;\n    }\n    const next = value();\n    if (document.activeElement !== element && element.value !== next) {\n      element.value = next;\n    }\n  });\n}\n","import { Directive, ElementRef, inject, model } from '@angular/core';\nimport type { FormValueControl } from '@angular/forms/signals';\n\nimport { reflectDisabled } from '../host-attributes/disabled-reflection';\nimport { FormUiControlBase } from './form-ui-control-base';\nimport { mirrorUnfocusedValue } from './unfocused-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\n  extends FormUiControlBase\n  implements FormValueControl<string>\n{\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\n    // Mirror external writes (consumer `[(value)]` or `[formField]`) back to\n    // the native element while it isn't focused. The user's own typing already\n    // flows in through the `(input)` listener, so this never fights live editing.\n    mirrorUnfocusedValue(() => this.#host.nativeElement, this.value);\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  protected onCompositionStart(): void {\n    this.#composing = true;\n  }\n\n  /** Ends an IME composition and flushes the final composed value once. */\n  protected 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   * The mirror effect skips writes while focused (to protect the caret), so an\n   * external write made during editing leaves stale text; blur is the moment to\n   * reconcile the visible text with the model.\n   */\n  protected 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 * 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 { 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) and resolves it through\n * its own `resolvedType` instead of this helper.\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","/**\n * Attribute that exempts a root-level child from the modal inert pass.\n * Carried by dialog / drawer backdrops (portaled alongside the modal)\n * and stamped by `injectOverlayShell` onto anchored-overlay hosts that were\n * opened from inside the protected root, so the initial sweep and the\n * late-sibling observer skip them instead of inerting them like background\n * siblings. The backdrops host-bind the literal; imperative callers use this\n * exported constant.\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 {\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  protected readonly styles = computed(() =>\n    this.focusable() && this.#focused() ? null : VISUALLY_HIDDEN_STYLE,\n  );\n\n  protected onFocusIn(): void {\n    this.#focused.set(true);\n  }\n\n  protected 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 { 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 { VISUALLY_HIDDEN_STYLE } from '../visually-hidden/visually-hidden';\n\ntype Politeness = 'polite' | 'assertive';\n\ninterface LiveRegion {\n  readonly element: HTMLElement;\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.\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\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.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, { element: region, generation: 0, timer: null });\n  }\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport { DOCUMENT, DestroyRef, PLATFORM_ID, inject, signal, type Signal } from '@angular/core';\n\n/**\n * Reflects the result of `MediaQueryList.matches` for `query` as a signal,\n * staying in sync via `addEventListener('change')`. The listener is removed\n * on the calling injection context's `DestroyRef.onDestroy`.\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  const isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n  const doc = inject(DOCUMENT);\n  const win = doc.defaultView;\n  if (!isBrowser || !win || typeof win.matchMedia !== 'function') {\n    return signal(false).asReadonly();\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  inject(DestroyRef).onDestroy(() => mql.removeEventListener('change', listener));\n\n  return matches.asReadonly();\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), so an arbitrary consumer\n *   value is corrected 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`) and\n * a value carrying that noise is still recognised as on-grid. A `by` of `0`\n * returns `value` unchanged; a non-positive or non-finite `step` (and a\n * non-finite `value` / `origin`) disables snapping and falls back to plain\n * `value + direction · by` at the 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 onGrid =\n    roundToDecimals(Math.round(index) * step + origin, precision) ===\n    roundToDecimals(value, precision);\n  if (onGrid) {\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","/**\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 { isDevMode } from '@angular/core';\nimport { 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 (!isDevMode()) {\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 * Per-item handle stored in a host-roving container's `Collection`. The\n * lifted shape is the intersection of what every embedded-roving item\n * needs to expose to its host: the DOM node (`host`) and a reactive\n * `disabled` signal so the host can skip disabled items during arrow-key\n * navigation. Container-specific extras (e.g. `value` on toggle items)\n * stay on the container's own handle interface.\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 owned by a \"host-with-roving\" container — a\n * primitive that owns the roving-tabindex policy and arrow-key navigation\n * for the embedded items it visually composes (which may be its own\n * children OR items belonging to a nested primitive that delegates\n * focus management upward).\n *\n * Today the only container that provides this token is\n * [`ForToolbar`](../../toolbar/toolbar.ts), and the only consumer is\n * [`ForToggleGroupItem`](../../toggle/toggle-group-item.ts) when nested\n * inside a toolbar. The contract is lifted to `_internal/` so that any\n * future host (e.g. Splitbar, a Tablist with side-actions, a Menubar\n * variant that composes embedded toggles) can opt in without\n * `toggle/` taking a static import dependency on `toolbar/` or any\n * other sibling primitive.\n *\n * **Inject contract.** Embedded items inject this token with\n * `{ optional: true, skipSelf: true }` — `optional` because not every\n * embedded-roving item lives inside a host-roving container (e.g. a\n * `[forToggleGroupItem]` used standalone has no toolbar), `skipSelf` so\n * a container that itself implements the contract (Toolbar) does not\n * accidentally inject its own provider when composing other items.\n *\n * The lifted shape is the intersection of what `ForToggleGroupItem`\n * actually consumes: the four signals it reads on the host\n * (`orientation`, `dir`, `disabled`), the navigation policy\n * (`navigate`, `isFirstFocusableItem`), and the registration pair\n * (`registerItem` / `unregisterItem`). Container-specific extras stay\n * on the container's own context interface.\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 type { CollectionHandle } from '../collection/collection';\nimport { type ListNavigationAction, moveIndex } 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\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 → `-1` (never the Tab entry point, but still arrow-reachable).\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 } = options;\n  if (disabled) {\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","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\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","import { signal, type Signal } from '@angular/core';\n\nimport { nextEnabledHandle } from '../collection/enabled-handle-navigation';\nimport { isInArray, toggleInArray } from './selection';\nimport { isUnset } 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>;\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}\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): void {\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    target.host.focus();\n    target.host.scrollIntoView?.({ block: 'nearest' });\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 next = [...this.#deps.value()];\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) && !next.some((x) => equals(x, v))) {\n        next.push(v);\n      }\n    }\n    this.#deps.setValue(next);\n  }\n\n  /**\n   * APG \"Ctrl/Cmd+A\": select every enabled option, or clear the selection when\n   * they are all already selected (toggle). An option whose `[value]` binding\n   * has not landed yet is left 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    const allSelected = enabled.every((v) => current.some((x) => equals(x, v)));\n    this.#deps.setValue(allSelected ? [] : enabled);\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 equals = this.#deps.compareWith();\n    const next = [...this.#deps.value()];\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) && !next.some((x) => equals(x, v))) {\n        next.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    edgeFocusTarget?.focus();\n    edgeFocusTarget?.scrollIntoView?.({ block: 'nearest' });\n    if (this.#deps.readonly()) {\n      return;\n    }\n    this.#deps.setValue(next);\n  }\n}\n","import type { SwipeDirection } from './swipe-dismiss';\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.\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 `scrollTop > 0`). Mirrored for the other\n * three.\n *\n * Conservative: an element with `overflow: hidden` is treated as\n * non-scrollable; an element scrolled to the 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): boolean {\n  let cur: Element | null = target;\n  while (cur && cur !== boundary) {\n    if (!(cur instanceof HTMLElement)) {\n      cur = cur.parentElement;\n      continue;\n    }\n    const style = cur.ownerDocument.defaultView?.getComputedStyle(cur);\n    const overflowX = style?.overflowX ?? '';\n    const overflowY = style?.overflowY ?? '';\n\n    const isVerticalScrollable =\n      (overflowY === 'auto' || overflowY === 'scroll' || overflowY === 'overlay') &&\n      cur.scrollHeight > cur.clientHeight;\n    const isHorizontalScrollable =\n      (overflowX === 'auto' || overflowX === 'scroll' || overflowX === 'overlay') &&\n      cur.scrollWidth > cur.clientWidth;\n\n    switch (direction) {\n      case 'down':\n        // Pointer moves down → scrollable container would be scrolled up.\n        // Has further content to scroll up if scrollTop > 0.\n        if (isVerticalScrollable && cur.scrollTop > 0) {\n          return true;\n        }\n        break;\n      case 'up':\n        if (isVerticalScrollable && cur.scrollTop + cur.clientHeight < cur.scrollHeight) {\n          return true;\n        }\n        break;\n      case 'right':\n        if (isHorizontalScrollable && cur.scrollLeft > 0) {\n          return true;\n        }\n        break;\n      case 'left':\n        if (isHorizontalScrollable && cur.scrollLeft + cur.clientWidth < cur.scrollWidth) {\n          return true;\n        }\n        break;\n    }\n    cur = cur.parentElement;\n  }\n  return false;\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 { createPointerDragSession, type PointerDragSession } from '../drag-session/pointer-session';\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  /** 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\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 biases the\n * resolution one step in the flick direction instead of snapping to nearest.\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 * 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 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    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      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, ElementRef, inject, 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: computed(() => (nativeButton ? null : '0')),\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 the body stamps.\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   * 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   * 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/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  /** 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","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 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 reflecting `[attr.dir]` on first render collapse into one\n * batched callback rather than the quadratic cascade of N per-instance observers each retriggering\n * on every other's reflection.\n *\n * Granularity is coarse: any `dir` mutation invalidates every dir-aware primitive,\n * each re-walking its own ancestor chain with a synchronous `closest('[dir]')`.\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 any `dir` attribute changes anywhere in the document.\n   * 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(() => this.#revision.update((v) => v + 1));\n      observer.observe(this.#doc.documentElement, {\n        attributes: true,\n        attributeFilter: ['dir'],\n        subtree: true,\n      });\n      this.#destroyRef.onDestroy(() => observer.disconnect());\n    }\n  }\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 reflects its own resolved\n * value — then to `<html dir>`, defaulting to `'ltr'`.\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 flip of any `dir` attribute 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 are observed, not `childList`. Moving the host into a\n * different-`dir` subtree without changing any `dir` attribute does not recompute the ambient;\n * set an explicit `[dir]` on the moved 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 doc = inject(DOCUMENT);\n  const direction = inject(AmbientDirection);\n\n  const ambient = computed<WritingDirection>(() => {\n    direction.revision();\n    const ancestor = host.parentElement?.closest('[dir]');\n    return normalizeDir(ancestor?.getAttribute('dir') ?? doc.documentElement?.dir);\n  });\n\n  return computed(() => explicitDir() ?? ambient());\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 the Select / Combobox call sites that run their own\n * prefix matching, so Select, Listbox, and Combobox behave alike for accented\n * 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`).\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,\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    if (foldTypeaheadText(getText(option).trim()).startsWith(needle)) {\n      return option;\n    }\n  }\n  return null;\n}\n","import { isDevMode } from '@angular/core';\n\nimport { 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 (isDevMode()) {\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 throwing\n * {@link throwUnsupportedVirtualizedSelectionFollowsFocus}.\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/**\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 * 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 throwUnsupportedVirtualizedSelectionFollowsFocus(\n  context: UnsupportedVirtualizedSelectionFollowsFocusContext,\n): void {\n  if (isDevMode()) {\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\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`). */\n  readonly getText: (item: H) => 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`) and whether the consumed key ends the event.\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\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   * Modifier-only events (Ctrl, Alt, Meta) are ignored even if `event.key`\n   * looks printable — the user is not typing.\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 (returns\n   * `false`) so widgets that use Space for activation keep that behavior\n   * when the user is not mid-typing. Consumers that own a Space activation\n   * path must therefore handle Space (or check `buffer()` non-empty) before\n   * delegating to `handle` if they need activation to win mid-typeahead;\n   * directives applied on native `<button>` activate on `keyup`, so a\n   * mid-buffer `keydown` Space accumulates here without blocking activation.\n   */\n  handle(event: KeyboardEvent): boolean {\n    if (event.isComposing) {\n      return false;\n    }\n    if (event.ctrlKey || event.altKey || event.metaKey) {\n      return false;\n    }\n    const ch = event.key;\n    if (typeof ch !== 'string' || ch.length !== 1) {\n      // Length-1 only (skips ArrowUp, Enter, Tab, etc.).\n      return false;\n    }\n    if (ch === ' ' && this.#buffer() === '') {\n      // First Space with an empty buffer is left for widget activation\n      // (Space is a common activation key); only mid-buffer Space accumulates.\n      return false;\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 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","import { computed, linkedSignal, signal, type Signal, untracked } from '@angular/core';\n\nimport { type ListNavigationAction, moveIndex } from '../keyboard-navigation/keyboard-navigation';\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/**\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 *   prior map is carried over on every reactive trigger except a `totalCount`\n *   transition, which restarts from an empty map. A same-length dataset refresh\n *   (invisible to the `totalCount` diff) can force the same reset through\n *   {@link invalidateSnapshot} or the optional `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  readonly #pendingActivePos = signal<{\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 = (prev: ReadonlyMap<number, E>, window: readonly H[]): Map<number, E> => {\n      const next = new Map(prev);\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        next.set(pos, entry);\n      }\n      return next;\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    });\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.\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 read **untracked**: this method writes it\n   * back to `null` on a successful resolve, and tracking the read would make\n   * 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 = untracked(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.set(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.set(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   * Resolving the current position when the active item is unmounted (scrolled\n   * off the rendered window) is an **O(total)** linear scan of the position\n   * snapshot: the active id is matched against every snapshot entry. This is\n   * deliberate and acceptable -- the scan runs only on that off-window branch\n   * (an active item still in the rendered window resolves in O(window) via\n   * `items`) and only once per keypress. The escape hatch, should profiling\n   * ever flag it at very large datasets (10k+ entries), is a companion\n   * `id -> position` map maintained alongside `#snapshotByPos` to make the\n   * lookup O(1); it is intentionally not built today because inverting the\n   * snapshot on every fold would trade this rare per-keypress cost for an\n   * O(total) rebuild on every scroll tick.\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   * 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.set({ 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.set(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.set({ pos: next, action, continueOnDisabled: true });\n    this.#deps.emitScrollToIndex(next);\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.set(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 lint bans the pair outright rather\n * than judging that overlap; Combobox's bridge is the one place it holds.\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","/*\n * Internal shared surface of forty-cdk — the `forty-cdk/core` entry point.\n *\n * This entry point holds the cross-primitive DI singletons (`LiveAnnouncer`,\n * the focus-trap stack, the id-generator salt, the defaults registry), the\n * framework-free geometry / interaction helpers, and the cross-cutting public\n * tokens.\n *\n * It exists so that every primitive entry point can import the shared core by\n * the `forty-cdk/core` specifier and the bundler compiles it exactly ONCE —\n * never duplicated per primitive, which would split the DI singletons into\n * multiple instances and break cross-primitive coordination.\n *\n * The overlay machinery — the positioning engine, both shells, the\n * dismissible-layer / inert-siblings / body-scroll-lock / drawer stacks, the\n * menu and listbox overlay controllers, the imperative manager core, the\n * portal and the hover-intent schedulers — is NOT here. It ships as\n * `forty-cdk/core-overlay`, whose barrel header records why\n * ([#1723](https://github.com/tutkli/forty-cdk/issues/1723)). The edge runs\n * one way only: that entry point imports this one, and nothing here may import\n * it back — a single reverse edge merges the two chunks and undoes the split.\n *\n * THIS ENTRY POINT IS NOT PUBLIC. It carries no semver guarantees and is\n * exported only so forty-cdk's own entry points share one compiled module.\n * Consumers never import from here: the contract types and tokens the library\n * commits to are published by `forty-cdk/shared`, and everything else is an\n * implementation surface refactorable without notice.\n *\n * Stability: this barrel is split into two tiers, and the boundary is\n * mechanical rather than advisory — and it spans `forty-cdk/core-overlay`'s\n * barrel too, which is why the gate reads both. The BLESSED tier is the\n * curated set listed\n * in `scripts/lib/core-blessed-tier.mjs` — contract types and tokens the\n * library commits to, each published by exactly one public entry point\n * (`forty-cdk/shared` for the cross-primitive ones; `forty-cdk/visually-hidden`,\n * `forty-cdk/breakpoints`, `forty-cdk/drawer`, and `forty-cdk/field` for the few\n * whose semantic home is a primitive). Everything else is INTERNAL.\n * `scripts/check-entrypoint-public-types.mjs` (run in `postbuild`) fails the\n * build when an internal-tier symbol reaches a public entry point's public\n * signature, when a blessed symbol is re-exported from an entry point other\n * than the one that publishes it, and when a blessed symbol's own JSDoc still\n * calls itself internal tier — so neither the tier, the canonical import path,\n * nor the promise the consumer reads can erode by accident.\n *\n * Class bases that public directives merely `extends` (`FormUiControlBase`,\n * `ModalSurfaceBase`, `MenuOverlayHost`, …) are internal —\n * subclassing them is not a supported contract.\n *\n * Scope: this barrel lists only what actually crosses the entry point's\n * boundary — which now includes what `forty-cdk/core-overlay` reads, so a\n * symbol exported solely for that entry point (`injectFocusTrap`, the\n * `composed-tree` walkers, `MODAL_PEER_ATTRIBUTE`) belongs here. Modules\n * inside `core` import each other by relative path, so a\n * symbol used only within `core` does not belong here — it would enlarge the\n * internal tier every audit has to read without making anything reachable.\n * A symbol that no entry point, spec or app imports stays exported only when\n * the emitted `.d.ts` must name it (an inferred member type), and then its\n * declaration's JSDoc says which signature forces it.\n *\n * Consume primitives from their own `forty-cdk/<primitive>` entry points, not\n * from here (the main `forty-cdk` barrel is intentionally empty — see the\n * package README). Growing the blessed tier is a deliberate, reviewed act\n * documented in `.claude/rules/conventions.md`.\n */\n\nexport { accessibleTextContent } from './accessible-text/accessible-text';\nexport { afterNextRenderCancellable } from './after-next-render-cancellable/after-next-render-cancellable';\nexport { Collection, type CollectionHandle } from './collection/collection';\nexport {\n  firstEnabledHandle,\n  firstEnabledHost,\n  lastEnabledHandle,\n  lastEnabledHost,\n  nextEnabledHandle,\n} from './collection/enabled-handle-navigation';\nexport {\n  LabelCache,\n  type LabelCacheDeps,\n  type LabelCacheEntry,\n  type LabelCacheHandle,\n} from './collection/label-cache';\nexport {\n  registerA11yDescription,\n  registerA11yName,\n  registerHandle,\n} from './collection/register-handle';\nexport { createSingleSlot } from './collection/single-slot';\nexport {\n  composedClosest,\n  composedContains,\n  composedParentElement,\n  resolveActiveElement,\n  resolveEventTarget,\n} from './composed-tree/composed-tree';\nexport {\n  assertTimeCapable,\n  compareDateOf,\n  type DateAdapter,\n  FOR_DATE_ADAPTER,\n  injectDateAdapter,\n  type TimeCapableDateAdapter,\n} from './datetime/date-adapter';\nexport { DateFieldEngine } from './datetime/date-field-engine';\nexport { type DateRange } from './datetime/date-range';\nexport { type FieldGranularity } from './datetime/date-segments';\nexport { createFormatterCache } from './datetime/formatter-cache';\nexport { ForDateTimeLiteralBase } from './datetime/literal-directive';\nexport { RangeFieldComposer } from './datetime/range-field-composer';\nexport { ForDateTimeSegmentBase, type SegmentEditorContext } from './datetime/segment-directive';\nexport {\n  type DateSegmentType,\n  type FieldSegment,\n  type SegmentEditorDelegate,\n  type SegmentHandle,\n  type SegmentType,\n} from './datetime/segment-editor';\nexport { type TimeSegmentType } from './datetime/segment-types';\nexport {\n  clampToBounds,\n  composeWithTime,\n  secondsOfDay,\n  serializeISODate,\n  serializeISOTime,\n  timeSentinel,\n} from './datetime/serialize';\nexport { TimeFieldEngine } from './datetime/time-field-engine';\nexport { type TimeGranularity } from './datetime/time-segments';\nexport { FOR_TIME_VALUE_SOURCE } from './datetime/time-value-source';\nexport { createDefaults } from './defaults/defaults';\nexport {\n  clampPreviewPosition,\n  type PreviewPoint,\n  resolveBoundaryElement,\n} from './drag-session/clamp-preview';\nexport {\n  type DragRect,\n  type DropContainerGeometry,\n  resolveDropTarget,\n} from './drag-session/drag-geometry';\nexport { createTemplatePreview, type DragPreview } from './drag-session/drag-preview';\nexport { isDragLiftKey, resolveLiftedDragControl } from './drag-session/keyboard-drag-keys';\nexport { createKeyboardDragMediator } from './drag-session/keyboard-drag-mediator';\nexport {\n  createPointerDragSession,\n  DRAG_DEAD_ZONE_PX,\n  type PointerDragSession,\n} from './drag-session/pointer-session';\nexport { PreviewController } from './drag-session/preview-controller';\nexport { resolveScrubReorder, translateWindowReorder } from './drag-session/window-index-map';\nexport { type ElementBox, injectElementSize } from './element-size/element-size';\nexport { formatFortyMessage, fortyError, type FortyMessageSpec, fortyWarn } from './errors/errors';\nexport {\n  orphanContextError,\n  type OrphanContextSpec,\n  unresolvedRootError,\n  type UnresolvedRootSpec,\n} from './errors/orphan-context';\nexport {\n  type FieldControlHandle,\n  FOR_FIELD_CONTEXT,\n  type ForFieldContext,\n  injectFieldWiring,\n} from './field/field-wiring';\nexport { FOR_FIELDSET_CONTEXT, type ForFieldsetContext } from './field/fieldset-context';\nexport { findFirstFocusable, injectFocusTrap } from './focus-trap/focus-trap';\nexport { injectHasFocusableContent } from './focus-trap/focusable-content';\nexport { FormUiControlBase } from './form-ui-control/form-ui-control-base';\nexport { injectHiddenInput } from './form-ui-control/hidden-input';\nexport { TextValueControlBase } from './form-ui-control/text-value-control-base';\nexport { mirrorUnfocusedValue } from './form-ui-control/unfocused-value-mirror';\nexport { resolveConfigClass } from './host-attributes/config-class';\nexport { reflectDisabled } from './host-attributes/disabled-reflection';\nexport { hostAriaLabel, hostDescribedBy, hostLabelledBy } from './host-attributes/host-aria';\nexport { adoptHostId, hostId, resolveHostId } from './host-attributes/host-id';\nexport { hostButtonType } from './host-attributes/host-type';\nexport { MODAL_EXEMPT_ATTRIBUTE, MODAL_PEER_ATTRIBUTE } from './host-attributes/modal-attributes';\nexport { FOR_ID_SALT, IdGenerator, provideForIdSalt } from './id-generator/id-generator';\nexport {\n  type GridNavigationAction,\n  type ListNavigationAction,\n  moveGridIndex,\n  moveIndex,\n  resolveGridNavigation,\n  resolveListNavigation,\n  resolveTreeExpandCollapse,\n  resolveTreegridExpandCollapse,\n  type WritingDirection,\n} from './keyboard-navigation/keyboard-navigation';\nexport { LiveAnnouncer } from './live-announcer/live-announcer';\nexport { injectMediaQuery, injectPrefersReducedMotion } from './media-query/media-query';\nexport {\n  clamp,\n  decimalPlaces,\n  roundToDecimals,\n  roundToStepPrecision,\n  snapToStep,\n  stepOnGrid,\n} from './numeric-step/numeric-step';\nexport { injectPauseController, type PauseController } from './pausable/pause-controller';\nexport { isHoverCapablePointer, isNonTouchPointer } from './pointer/pointer-capability';\nexport { createPointerSuppression, type PointerSuppression } from './pointer/pointer-suppression';\nexport { assertRootContext } from './root-context/root-context';\nexport {\n  FOR_HOST_ROVING_CONTEXT,\n  type HostRovingContext,\n  type HostRovingItemHandle,\n} from './roving-tabindex/host-roving-context';\nexport {\n  rovingListTarget,\n  rovingTabStop,\n  selectionTabStop,\n} from './roving-tabindex/roving-list-navigation';\nexport { RovingTabindex } from './roving-tabindex/roving-tabindex';\nexport { RangeSelectionEngine } from './selection/range-selection-engine';\nexport {\n  defaultItemToFormValue,\n  isInArray,\n  singleSelected,\n  toggleInArray,\n} from './selection/selection';\nexport { isScrollableAtEdge } from './swipe-dismiss/scroll-boundary';\nexport {\n  attachSwipeDismiss,\n  FLICK_STALE_VELOCITY_MS,\n  FLICK_VELOCITY_PX_PER_MS,\n  flickVelocity,\n  type SwipeDirection,\n  type SwipeEventDetail,\n} from './swipe-dismiss/swipe-dismiss';\nexport {\n  injectSyntheticActivation,\n  type SyntheticActivation,\n  type SyntheticActivationConfig,\n} from './synthetic-activation/synthetic-activation';\nexport {\n  type ForTableCellHandle,\n  type ForTableRowHandle,\n  TABLE_REGISTRATION_CONTEXT,\n  TABLE_ROW_REGISTRATION_CONTEXT,\n  type TableRegistrationContext,\n  type TableRowRegistrationContext,\n  type TableVirtualRow,\n  type TableVirtualRowNavigation,\n  type TableVirtualWindow,\n} from './table-registration/table-registration';\nexport { injectTextDirection } from './text-direction/text-direction';\nexport {\n  isRangeSelectShortcut,\n  resolveListTypeahead,\n  throwUnsupportedVirtualizedRangeSelect,\n  throwUnsupportedVirtualizedSelectionFollowsFocus,\n} from './typeahead/list-typeahead';\nexport { findTypeaheadMatch, foldTypeaheadText } from './typeahead/match-options';\nexport { injectTypeahead, type Typeahead } from './typeahead/typeahead';\nexport { assertInputBound, isUnset, unsetInput } from './unset-input/unset-input';\nexport {\n  createVetoableEvent,\n  createVetoableNativeEvent,\n  emitVetoableEvent,\n  emitVetoableNativeEvent,\n  type VetoableEvent,\n  type VetoableNativeEvent,\n} from './vetoable-event/vetoable-event';\nexport {\n  VirtualizedNavigator,\n  type VirtualizedNavigatorDeps,\n} from './virtualized-navigator/virtualized-navigator';\nexport {\n  runVirtualizedNavigatorBridge,\n  type VirtualizedNavigatorBridgeDeps,\n  type VirtualizedNavigatorBridgeTarget,\n} from './virtualized-navigator/virtualized-navigator-bridge';\nexport { ForVisuallyHidden } from './visually-hidden/visually-hidden';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":["DIGITS"],"mappings":";;;;AAAA;;;;;;;;;;;;;;;;;;;AAmBG;AACG,SAAU,qBAAqB,CAAC,IAAU,EAAA;IAC9C,IAAI,IAAI,GAAG,EAAE;IACb,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,KAAK,KAAI;QAChC,IAAI,KAAK,CAAC,QAAQ,KAAK,KAAK,CAAC,SAAS,EAAE;AACtC,YAAA,IAAI,IAAI,KAAK,CAAC,SAAS,IAAI,EAAE;YAC7B;QACF;QACA,IAAI,KAAK,CAAC,QAAQ,KAAK,KAAK,CAAC,YAAY,EAAE;YACzC,IAAK,KAAiB,CAAC,YAAY,CAAC,aAAa,CAAC,KAAK,MAAM,EAAE;gBAC7D;YACF;AACA,YAAA,IAAI,IAAI,qBAAqB,CAAC,KAAK,CAAC;QACtC;AACF,IAAA,CAAC,CAAC;AACF,IAAA,OAAO,IAAI;AACb;;ACjCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCG;AACG,SAAU,0BAA0B,CAAC,EAAc,EAAA;AACvD,IAAA,MAAM,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC;IAErC,IAAI,SAAS,GAAG,KAAK;AAErB,IAAA,MAAM,GAAG,GAAG,eAAe,CAAC,MAAK;AAC/B,QAAA,IAAI,SAAS;YAAE;AACf,QAAA,EAAE,EAAE;AACN,IAAA,CAAC,CAAC;AAEF,IAAA,UAAU,CAAC,SAAS,CAAC,MAAK;QACxB,SAAS,GAAG,IAAI;QAChB,GAAG,CAAC,OAAO,EAAE;AACf,IAAA,CAAC,CAAC;AACJ;;AC5BA,SAAS,YAAY,CAAI,CAAe,EAAE,CAAe,EAAA;AACvD,IAAA,IAAI,CAAC,KAAK,CAAC,EAAE;AACX,QAAA,OAAO,IAAI;IACb;IACA,IAAI,CAAC,CAAC,MAAM,KAAK,CAA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