forty-cdk 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/fesm2022/forty-cdk-core.mjs +34 -1
- package/fesm2022/forty-cdk-core.mjs.map +1 -1
- package/fesm2022/forty-cdk-drag-drop.mjs +49 -41
- package/fesm2022/forty-cdk-drag-drop.mjs.map +1 -1
- package/fesm2022/forty-cdk-listbox.mjs +15 -26
- package/fesm2022/forty-cdk-listbox.mjs.map +1 -1
- package/fesm2022/forty-cdk-table.mjs +10 -2
- package/fesm2022/forty-cdk-table.mjs.map +1 -1
- package/fesm2022/forty-cdk-tree.mjs +26 -34
- package/fesm2022/forty-cdk-tree.mjs.map +1 -1
- package/listbox/README.md +24 -0
- package/package.json +1 -1
- package/tree/README.md +27 -0
- package/types/forty-cdk-checkbox.d.ts +1 -1
- package/types/forty-cdk-combobox.d.ts +1 -1
- package/types/forty-cdk-core.d.ts +28 -2
- package/types/forty-cdk-listbox.d.ts +20 -0
- package/types/forty-cdk-table.d.ts +8 -1
- package/types/forty-cdk-tree.d.ts +28 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"forty-cdk-core.mjs","sources":["../../../projects/forty-cdk/core/src/body-scroll-lock/body-scroll-lock.ts","../../../projects/forty-cdk/core/src/class-list/resolve-config-class.ts","../../../projects/forty-cdk/core/src/collection/collection.ts","../../../projects/forty-cdk/core/src/collection/first-enabled-host.ts","../../../projects/forty-cdk/core/src/collection/fold-snapshot.ts","../../../projects/forty-cdk/core/src/id-generator/id-generator.ts","../../../projects/forty-cdk/core/src/host-id/host-id.ts","../../../projects/forty-cdk/core/src/collection/register-handle.ts","../../../projects/forty-cdk/core/src/date-adapter/date-adapter.ts","../../../projects/forty-cdk/core/src/datetime/hour-cycle.ts","../../../projects/forty-cdk/core/src/datetime/literal-directive.ts","../../../projects/forty-cdk/core/src/datetime/segment-directive.ts","../../../projects/forty-cdk/core/src/datetime/segment-editor.ts","../../../projects/forty-cdk/core/src/datetime/serialize.ts","../../../projects/forty-cdk/core/src/datetime/time-value-source.ts","../../../projects/forty-cdk/core/src/defaults/defaults.ts","../../../projects/forty-cdk/core/src/disabled-reflection/disabled-reflection.ts","../../../projects/forty-cdk/core/src/dismissable-layer/dismissable-layer.ts","../../../projects/forty-cdk/core/src/drag-session/auto-scroll.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-positions.ts","../../../projects/forty-cdk/core/src/drag-session/drag-preview.ts","../../../projects/forty-cdk/core/src/drag-session/flip.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/placeholder-position.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/tree-drop-resolver.ts","../../../projects/forty-cdk/core/src/drawer-stack/drawer-stack.ts","../../../projects/forty-cdk/core/src/media-query/media-query.ts","../../../projects/forty-cdk/core/src/drawer-scale/drawer-scale-coordinator.ts","../../../projects/forty-cdk/core/src/element-size/element-size.ts","../../../projects/forty-cdk/core/src/field/field-wiring.ts","../../../projects/forty-cdk/core/src/fieldset/fieldset-context.ts","../../../projects/forty-cdk/core/src/flat-hierarchy/flat-hierarchy.ts","../../../projects/forty-cdk/core/src/floating/anchored-positioning-inputs.ts","../../../projects/forty-cdk/core/src/after-next-render-cancellable/after-next-render-cancellable.ts","../../../projects/forty-cdk/core/src/portal/portal.ts","../../../projects/forty-cdk/core/src/floating/floating.ts","../../../projects/forty-cdk/core/src/focus-trap/focus-trap.ts","../../../projects/forty-cdk/core/src/focusable-content/focusable-content.ts","../../../projects/forty-cdk/core/src/form-ui-control/form-ui-control-base.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/hidden-input/hidden-input.ts","../../../projects/forty-cdk/core/src/hover-intent/debounced-action.ts","../../../projects/forty-cdk/core/src/hover-intent/force-close-when-disabled.ts","../../../projects/forty-cdk/core/src/hover-intent/hover-intent.ts","../../../projects/forty-cdk/core/src/hover-intent/skip-delay-coordinator.ts","../../../projects/forty-cdk/core/src/inert-siblings/inert-siblings.ts","../../../projects/forty-cdk/core/src/interactions/modality.ts","../../../projects/forty-cdk/core/src/interactions/focus-visible.ts","../../../projects/forty-cdk/core/src/interactions/hovered.ts","../../../projects/forty-cdk/core/src/interactions/pressed.ts","../../../projects/forty-cdk/core/src/keyboard-navigation/keyboard-navigation.ts","../../../projects/forty-cdk/core/src/keyboard-navigation/move-in-collection.ts","../../../projects/forty-cdk/core/src/vetoable-event/vetoable-event.ts","../../../projects/forty-cdk/core/src/listbox-overlay/listbox-overlay-controller.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/locale-number/locale-number.ts","../../../projects/forty-cdk/core/src/menu-overlay/menu-context.ts","../../../projects/forty-cdk/core/src/menu-overlay/menu-focus-state.ts","../../../projects/forty-cdk/core/src/typeahead/typeahead.ts","../../../projects/forty-cdk/core/src/menu-overlay/menu-item-list.ts","../../../projects/forty-cdk/core/src/menu-overlay/menu-overlay.ts","../../../projects/forty-cdk/core/src/menu-overlay/menu-overlay-host.ts","../../../projects/forty-cdk/core/src/menu-overlay/menu-positioning-inputs.ts","../../../projects/forty-cdk/core/src/modal-shell/modal-shell.ts","../../../projects/forty-cdk/core/src/numeric-step/numeric-step.ts","../../../projects/forty-cdk/core/src/overlay-manager/overlay-context-injector.ts","../../../projects/forty-cdk/core/src/overlay-manager/overlay-manager.ts","../../../projects/forty-cdk/core/src/overlay-manager/overlay-ref.ts","../../../projects/forty-cdk/core/src/floating/item-aligned.ts","../../../projects/forty-cdk/core/src/overlay-shell/overlay-shell.ts","../../../projects/forty-cdk/core/src/visibility-pause/visibility-pause.ts","../../../projects/forty-cdk/core/src/pausable/pause-controller.ts","../../../projects/forty-cdk/core/src/pointer-grace/pointer-grace.ts","../../../projects/forty-cdk/core/src/pointer-suppression/pointer-suppression.ts","../../../projects/forty-cdk/core/src/resize-geometry/resize-geometry.ts","../../../projects/forty-cdk/core/src/roving-tabindex/host-roving-context.ts","../../../projects/forty-cdk/core/src/roving-tabindex/reconcile-roving-active.ts","../../../projects/forty-cdk/core/src/roving-tabindex/roving-tabindex.ts","../../../projects/forty-cdk/core/src/scroll-boundary/scroll-boundary.ts","../../../projects/forty-cdk/core/src/selection-model/selection-model.ts","../../../projects/forty-cdk/core/src/selection/selection.ts","../../../projects/forty-cdk/core/src/signal-graph/read-handle.ts","../../../projects/forty-cdk/core/src/snap-points/snap-points.ts","../../../projects/forty-cdk/core/src/swipe-dismiss/swipe-dismiss.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/virtualized-navigator/virtualized-navigator.ts","../../../projects/forty-cdk/core/src/window-index-map/window-index-map.ts","../../../projects/forty-cdk/core/src/public-api.ts","../../../projects/forty-cdk/core/src/forty-cdk-core.ts"],"sourcesContent":["import { DOCUMENT, Injectable, PLATFORM_ID, inject } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\n/**\n * Refcounted scroll lock, keyed per target element (default `<body>`).\n * Multiple modal surfaces acquire and release locks independently — only the\n * first acquire for a given target mutates that target, only the last release\n * un-mutates it. Different targets (body vs a container element) are fully\n * independent: locking a container does not affect body scroll and vice versa.\n *\n * **Semantic: clear, do not restore.** On the first lock for a target the\n * service writes `overflow: hidden` and an optional scrollbar-compensating\n * `padding-right` inline on that target. On the final unlock it _clears_ the\n * inline styles it set (`target.style.overflow = ''`, and\n * `target.style.paddingRight = ''` only when this lock actually wrote it) and\n * lets the CSS cascade take over again. It does NOT snapshot the values at\n * lock time and rewrite them at unlock time.\n *\n * On overlay-scrollbar / mobile platforms there is no classic scrollbar\n * (`innerWidth - clientWidth === 0` for the body path), so the lock never\n * writes `padding-right`. In that case the final unlock leaves\n * `target.style.paddingRight` untouched, so a consumer's unrelated inline\n * `padding-right` survives. The clear-don't-restore contract only applies to\n * values the lock owns. See #391.\n *\n * Why: any code (route transition, theme toggle, the consumer themselves)\n * that mutates `target.style.overflow` between `lock()` and the final\n * `unlock()` would otherwise be silently clobbered when we restored the\n * stale snapshot. Clearing on unlock means the lock owns the inline style\n * only while it exists; intervening mutations win, and the resting state\n * is whatever stylesheet rules apply. See #149.\n *\n * The scrollbar-width compensation prevents content jumping when overflow\n * goes from `auto` (scrollbar shown) to `hidden` (scrollbar hidden).\n * For the body path the width is `window.innerWidth - documentElement.clientWidth`;\n * for an element path it is `target.offsetWidth - target.clientWidth`.\n *\n * SSR: the service is `providedIn: 'root'` so its counter map is scoped to a\n * single Angular bootstrap (one per SSR request). Server-side calls are\n * no-ops.\n */\n@Injectable({ providedIn: 'root' })\nexport class BodyScrollLock {\n readonly #document = inject(DOCUMENT);\n readonly #window = this.#document.defaultView;\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n\n readonly #targets = new Map<HTMLElement, { count: number; wrotePaddingRight: boolean }>();\n\n /**\n * Acquire the scroll lock on `target` (default `document.body`). The first\n * call for a given target sets `overflow: hidden` and compensates for the\n * scrollbar width; subsequent calls increment the refcount only.\n */\n lock(target: HTMLElement = this.#document.body): void {\n if (!this.#isBrowser) {\n return;\n }\n let record = this.#targets.get(target);\n if (!record) {\n record = { count: 0, wrotePaddingRight: false };\n this.#targets.set(target, record);\n }\n if (record.count === 0) {\n target.style.overflow = 'hidden';\n const isBody = target === this.#document.body;\n const win = this.#window;\n let scrollbarWidth: number;\n if (isBody) {\n const docEl = this.#document.documentElement;\n scrollbarWidth = win ? win.innerWidth - docEl.clientWidth : 0;\n if (scrollbarWidth > 0 && win && !this.#gutterIsStable(win, [docEl, target])) {\n const computed = win.getComputedStyle(target).paddingRight;\n const currentPx = parseFloat(computed) || 0;\n target.style.paddingRight = `${currentPx + scrollbarWidth}px`;\n record.wrotePaddingRight = true;\n }\n } else {\n scrollbarWidth = target.offsetWidth - target.clientWidth;\n if (scrollbarWidth > 0 && win && !this.#gutterIsStable(win, [target])) {\n const computed = win.getComputedStyle(target).paddingRight;\n const currentPx = parseFloat(computed) || 0;\n target.style.paddingRight = `${currentPx + scrollbarWidth}px`;\n record.wrotePaddingRight = true;\n }\n }\n }\n record.count++;\n }\n\n /**\n * Release the scroll lock on `target` (default `document.body`). The last\n * release clears the inline `overflow` (and `padding-right` if written) and\n * lets the CSS cascade take over.\n */\n unlock(target: HTMLElement = this.#document.body): void {\n if (!this.#isBrowser) {\n return;\n }\n const record = this.#targets.get(target);\n if (!record || record.count === 0) {\n return;\n }\n record.count--;\n if (record.count === 0) {\n target.style.overflow = '';\n if (record.wrotePaddingRight) {\n target.style.paddingRight = '';\n record.wrotePaddingRight = false;\n }\n this.#targets.delete(target);\n }\n }\n\n /**\n * True when any of the given elements reserves the scrollbar gutter via\n * `scrollbar-gutter: stable` (or `stable both-edges`). The gutter then\n * survives the `overflow: hidden` toggle, so no padding compensation is\n * needed.\n */\n #gutterIsStable(win: Window, els: readonly HTMLElement[]): boolean {\n for (const el of els) {\n const gutter = win.getComputedStyle(el).getPropertyValue('scrollbar-gutter');\n if (gutter.trim().split(/\\s+/).includes('stable')) {\n return true;\n }\n }\n return false;\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 { computed, DestroyRef, inject, signal, type Signal } from '@angular/core';\n\n/**\n * Minimal contract every `Collection` entry must satisfy: it carries the\n * host element so consumers can correlate handles with DOM nodes (e.g.\n * `findByHost`, focus moves, `aria-activedescendant` lookups).\n */\nexport interface CollectionHandle {\n readonly host: HTMLElement;\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`\n * element regardless of the order children registered in.\n *\n * Resolving document order (rather than registration order) keeps\n * `items()` / `indexOfHost` correct under templates that reorder a list at\n * runtime — `@for (... ; track id)` driven by a sort or drag-reorder moves\n * existing DOM nodes without re-running child constructors, so registration\n * order would otherwise freeze at the original sequence and corrupt\n * `aria-posinset` / `aria-setsize` and keyboard navigation order. The\n * resolution is reactive: an internal `MutationObserver` re-orders the\n * exposed array when nodes move, and consumers' `computed`s recompute\n * automatically.\n *\n * The observer watches `childList` (without `subtree`) on each distinct\n * **direct parent** of the registered hosts, so it only fires for additions,\n * removals, and reorders of this collection's own members. In a nested\n * composition (e.g. a Tree of `forTreeGroup` containers, each owning its own\n * `Collection`) a single mutation deep in the tree no longer cascades through\n * every ancestor's observer — only the owning collection is invalidated.\n *\n * The collection itself is not Angular-aware, but when instantiated inside an\n * Angular injection context (the common case — a field initializer on the\n * host directive) it registers `destroy()` with the ambient `DestroyRef`, so\n * the `MutationObserver` is disconnected when the owner is destroyed without\n * relying on every child unregistering first. Call `register` / `unregister`\n * from each child's constructor / `DestroyRef.onDestroy`; outside an injection\n * context, call `destroy()` manually.\n *\n * Membership is tracked in a `Set`, so `register` / `unregister` do an O(1)\n * duplicate check instead of scanning the array. Document order is computed\n * lazily and memoized: reading `items()` returns the cached (frozen) array\n * reference until membership or DOM order actually changes, so reads stay O(1)\n * and a single mutation is O(N log N) (the sort) in the current size.\n */\nexport class Collection<H extends CollectionHandle> {\n readonly #members = signal<ReadonlySet<H>>(new Set<H>());\n readonly #domEpoch = signal(0);\n\n #observer: MutationObserver | null = null;\n readonly #observedParents = new Set<Node>();\n #destroyed = false;\n\n constructor() {\n try {\n inject(DestroyRef).onDestroy(() => this.destroy());\n } catch {\n // Constructed outside an injection context (e.g. a bare `new Collection()`\n // in a unit test); the owner is responsible for calling `destroy()`.\n }\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 the shared parents'\n * children are reordered, so it stays correct under runtime reordering\n * (`@for` sort / drag-reorder), not just under static `@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 returned array is frozen — it is shared across reads and is the\n * memoized cache backing this `computed`, so callers must treat it as\n * read-only (copy before sorting / splicing).\n */\n readonly items: Signal<readonly H[]> = computed(() => {\n this.#domEpoch();\n return Object.freeze(this.#sortByDomOrder([...this.#members()]));\n });\n\n register(handle: H): void {\n if (this.#destroyed) {\n return;\n }\n const members = this.#members();\n if (members.has(handle)) {\n return;\n }\n const next = new Set(members);\n next.add(handle);\n this.#members.set(next);\n this.#syncObserver();\n }\n\n unregister(handle: H): void {\n const members = this.#members();\n if (!members.has(handle)) {\n return;\n }\n const next = new Set(members);\n next.delete(handle);\n this.#members.set(next);\n this.#syncObserver();\n }\n\n /** Lookup by host element. Returns `undefined` if no handle has that host. */\n findByHost(el: HTMLElement): H | undefined {\n return this.items().find((h) => h.host === el);\n }\n\n /** Index in DOM document order, or -1 if not registered. */\n indexOfHost(el: HTMLElement): number {\n return this.items().findIndex((h) => h.host === el);\n }\n\n /**\n * Disconnects the `MutationObserver` and clears membership. Idempotent and\n * safe to call from a `DestroyRef.onDestroy` hook — wired automatically when\n * the collection is constructed in an injection context. After `destroy()`,\n * further `register` calls are ignored.\n */\n destroy(): void {\n this.#destroyed = true;\n this.#observer?.disconnect();\n this.#observer = null;\n this.#observedParents.clear();\n if (this.#members().size > 0) {\n this.#members.set(new Set<H>());\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 #syncObserver(): void {\n if (typeof MutationObserver === 'undefined' || this.#destroyed) {\n return;\n }\n const parents = this.#resolveParents();\n if (this.#sameParents(parents)) {\n return;\n }\n this.#observer ??= new MutationObserver(() => this.#domEpoch.update((e) => e + 1));\n this.#observer.disconnect();\n this.#observedParents.clear();\n for (const parent of parents) {\n this.#observer.observe(parent, { childList: true });\n this.#observedParents.add(parent);\n }\n }\n\n #resolveParents(): Set<Node> {\n const parents = new Set<Node>();\n for (const member of this.#members()) {\n const parent = member.host.parentNode;\n if (parent) {\n parents.add(parent);\n }\n }\n return parents;\n }\n\n #sameParents(parents: Set<Node>): boolean {\n if (parents.size !== this.#observedParents.size) {\n return false;\n }\n for (const parent of parents) {\n if (!this.#observedParents.has(parent)) {\n return false;\n }\n }\n return true;\n }\n}\n","import type { Signal } from '@angular/core';\n\nimport type { CollectionHandle } from './collection';\n\n/**\n * Collection handle that also exposes a `disabled` signal. Required input\n * shape for {@link firstEnabledHost}.\n */\nexport interface DisableableHandle extends CollectionHandle {\n readonly disabled: Signal<boolean>;\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 for (const item of items) {\n if (!item.disabled()) {\n return item.host;\n }\n }\n return null;\n}\n","import { linkedSignal, type Signal, type WritableSignal } from '@angular/core';\n\n/** Source tracked by every snapshot fold: the live window + its total. */\ninterface FoldSource<H> {\n readonly total: number | undefined;\n readonly items: readonly H[];\n}\n\n/**\n * Builds the `linkedSignal` shared by the combobox label cache and the\n * virtualized navigators. Both fold the live `items()` window into an\n * accumulator that persists across listbox close / open cycles and resets when\n * the consumer's `totalCount` transitions.\n *\n * The stale-window invariant lives here, in one place: on a `totalCount`\n * transition the `items()` array may still hold the previous window (signal\n * commits run serially, so the `@for` re-render hasn't unregistered the old\n * options yet), so the fold restarts from `empty()` on that compute and the\n * next run — fired when `items` catches up — folds the fresh window into a\n * clean carry-over accumulator.\n *\n * @typeParam H Handle type folded into the accumulator.\n * @typeParam A Accumulator shape.\n * @param items Live registered handles. The same signal the host exposes.\n * @param totalCount Total handle count (virtualized) or `undefined`.\n * @param empty Produces a fresh, empty accumulator (used on a `totalCount`\n * transition and as the initial `prev`).\n * @param fold Overlays the current `items` window onto the carried-over\n * accumulator and returns the next accumulator.\n */\nexport function foldSnapshotOnTotalCountTransition<H, A>(\n items: Signal<readonly H[]>,\n totalCount: Signal<number | undefined>,\n empty: () => A,\n fold: (prev: A, items: readonly H[]) => A,\n): WritableSignal<A> {\n return linkedSignal<FoldSource<H>, A>({\n source: () => ({ total: totalCount(), items: items() }),\n computation: ({ total, items: window }, prev) => {\n if (prev && prev.source.total !== total) {\n return empty();\n }\n return fold(prev?.value ?? empty(), window);\n },\n });\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 */\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 * bootstrapApplication(AppA, { providers: [provideForIdSalt('a')] });\n * bootstrapApplication(AppB, { providers: [provideForIdSalt('b')] });\n * ```\n *\n * The salt must stay deterministic per app instance — a runtime random value\n * would break SSR hydration because the server and client renders would no\n * longer agree.\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 * Used by primitives that need to wire `aria-controls` / `aria-labelledby`\n * relationships between pieces — the IDs are stable for the lifetime of the\n * primitive instance.\n *\n * SSR: the generator is `providedIn: 'root'`, so a fresh instance is\n * created for each Angular application bootstrap (one per SSR request).\n * The IDs are salted with {@link FOR_ID_SALT} (which defaults to the\n * application's `APP_ID`) so the server and the client produce identical\n * strings for the same render order — the property hydration relies on.\n *\n * IMPORTANT — multiple apps on one page need distinct salts. The default salt\n * is `APP_ID`, and Angular's default `APP_ID` is the literal `'ng'`. Two\n * forty-cdk apps mounted side-by-side that both keep the default salt\n * therefore start from the same salt and the same counter, emitting identical\n * id sequences — duplicate DOM ids that mis-resolve `aria-labelledby` /\n * `aria-controls` across apps. A per-instance random nonce is deliberately\n * NOT mixed in: it would diverge the salt but break SSR hydration (the server\n * and client renders would no longer agree). When running more than one\n * forty-cdk app on a single page, give each a distinct salt via\n * {@link provideForIdSalt} (the per-app knob that leaves the global `APP_ID`\n * untouched). Overriding the global `APP_ID` works too, but it also drives\n * Angular's hydration store and event replay, so `provideForIdSalt` is the\n * narrower choice.\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. See `.claude/rules/conventions.md`.\n *\n * Must be invoked in an injection context — internally injects\n * {@link IdGenerator}.\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 * Replaces the hand-written `readonly id = signal(this.#idGen.next('…'))` so\n * the piece's `[id]` host binding re-emits a consumer-set static id instead of\n * clobbering it. Must be invoked in an injection context — internally injects\n * {@link ElementRef} and {@link IdGenerator}.\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 {\n afterNextRender,\n DestroyRef,\n ElementRef,\n inject,\n signal,\n type Signal,\n} from '@angular/core';\n\nimport { resolveHostId } from '../host-id/host-id';\nimport type { Collection } from './collection';\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 until Angular's\n * `afterNextRender` hook fires. Required when the parent's lookups read\n * `input.required` signals from the handle during host-binding evaluation\n * that interleaves with sibling directives' input-binding step (Tabs,\n * NavigationMenu). The `unregister` call always runs eagerly via\n * `DestroyRef.onDestroy`, so destroy-before-register is a safe no-op as\n * long as `unregister` is reference-based.\n */\nexport type RegistrationScheduling = 'sync' | 'afterNextRender';\n\n/**\n * Generic register-on-construct / unregister-on-destroy helper.\n *\n * Collapses the boilerplate every child directive used to write by hand:\n *\n * ```ts\n * constructor() {\n * const handle = { host: this.#host.nativeElement, value: this.value };\n * this.parent.registerXxx(handle);\n * inject(DestroyRef).onDestroy(() => this.parent.unregisterXxx(handle));\n * }\n * ```\n *\n * becomes\n *\n * ```ts\n * constructor() {\n * const handle = { host: this.#host.nativeElement, value: this.value };\n * registerHandle(handle, (h) => this.parent.registerXxx(h), (h) => this.parent.unregisterXxx(h));\n * }\n * ```\n *\n * Works for any target shape — object handles, raw `HTMLElement`s,\n * `aria-*` id strings — because the helper just hands `target` back to the\n * caller-supplied `register` / `unregister` callbacks.\n *\n * Must be invoked in an injection context (typically a directive\n * constructor) — internally calls `inject(DestroyRef)`.\n *\n * @param target The value to register. Passed verbatim to both callbacks.\n * @param register Called immediately (or deferred via `afterNextRender`,\n * per `scheduling`) to register the target with the owning parent.\n * @param unregister Called from `DestroyRef.onDestroy` to unregister. Must\n * be reference-based and tolerant of being called before `register` ever\n * ran (when `scheduling` is `'afterNextRender'` and the directive is\n * destroyed before the deferred 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 * Convenience overload of {@link registerHandle} for parents that expose\n * a raw `Collection<H>`. The handle is registered immediately and\n * unregistered on `DestroyRef.onDestroy`.\n *\n * Most parents wrap their `Collection` behind named methods (e.g.\n * `registerOption` / `unregisterOption`) — those callsites should use\n * {@link registerHandle} with the named methods. Reach for this helper only\n * when the parent exposes the bare `Collection` instance.\n *\n * Must be invoked in an injection context.\n */\nexport function registerCollectionHandle<H extends { readonly host: HTMLElement }>(\n collection: Collection<H>,\n handle: H,\n scheduling: RegistrationScheduling = 'sync',\n): void {\n registerHandle(\n handle,\n (h) => collection.register(h),\n (h) => collection.unregister(h),\n scheduling,\n );\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 * Generates a stable `id` for the host element and registers it with the\n * `owner`'s `aria-labelledby` collection (`registerLabel` /\n * `unregisterLabel`). Returns the id as a `Signal<string>` so the caller\n * can host-bind it via `'[id]': 'id()'` exactly like every other primitive.\n *\n * Replaces:\n *\n * ```ts\n * readonly id = signal(this.#idGen.next('for-dialog-title'));\n * constructor() {\n * const myId = this.id();\n * this.#ctx.registerLabel(myId);\n * inject(DestroyRef).onDestroy(() => this.#ctx.unregisterLabel(myId));\n * }\n * ```\n *\n * with:\n *\n * ```ts\n * readonly id = registerA11yName(this.#ctx, 'for-dialog-title');\n * ```\n *\n * A consumer-set **static** `id` on the host is adopted (and registered as the\n * accessible-name id) instead of being clobbered — the host element is read\n * optionally, so the helper still works when invoked outside a directive host\n * context (it falls back to a generated id). See {@link resolveHostId} for the\n * static-only boundary.\n *\n * Must be invoked in an injection context — internally calls `inject` for\n * `ElementRef`, `IdGenerator`, and `DestroyRef`.\n */\nexport function registerA11yName(owner: A11yLabelOwner, prefix: string): Signal<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 signal(id).asReadonly();\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(\n owner: A11yDescriptionOwner,\n prefix: string,\n): Signal<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 signal(id).asReadonly();\n}\n","import { inject, InjectionToken } from '@angular/core';\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 (#354).\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 (#354).\n *\n * Implementations must be pure with respect to their date type: every\n * operation returns a value and never mutates its inputs. The `D` produced by\n * mutating operations (`add*`, `createDate`) is a fresh value, which keeps it\n * signal-friendly (reference equality changes on every change).\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 once 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. for a non-Gregorian ordering). Day-only\n * adapters whose {@link compare} already ignores time need not 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 using the runtime's default locale.\n *\n * **SSR / hydration caveat.** The result resolves against the runtime's\n * default locale, so a server render and a client hydration can produce\n * different strings when the server and browser locales differ — surfacing as\n * a hydration mismatch on every formatted value (heading, weekday headers,\n * cell labels). The runtime time zone applies too for adapters that format\n * 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 */\n format(date: D, options: Intl.DateTimeFormatOptions): 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 */\nexport function injectDateAdapter<D>(piece: string): DateAdapter<D> {\n const adapter = inject(FOR_DATE_ADAPTER, { optional: true });\n if (!adapter) {\n throw new Error(\n `[forty-cdk/calendar] ${piece} requires a DateAdapter. Provide one with ` +\n `provideInternationalizedDateAdapter() or provideNativeDateAdapter() in 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 */\nexport function assertTimeCapable<D>(\n adapter: DateAdapter<D>,\n piece: 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 new Error(\n `[forty-cdk/date-adapter] ${piece} requires a time-capable DateAdapter. Provide one with ` +\n `provideNativeDateAdapter() or provideInternationalizedDateTimeAdapter() — the day-only ` +\n `provideInternationalizedDateAdapter() (CalendarDate) cannot carry a time.`,\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","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, 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 { SegmentHandle, SegmentType } from './segment-editor';\n\n/**\n * The coordination surface a date / time root exposes to its segment children,\n * as consumed by the shared {@link ForDateTimeSegmentBase}. The reactive per-part\n * accessors and the behavior methods are forwarded straight to the root's\n * {@link import('./segment-editor').SegmentEditor}; `disabled` / `readonly` /\n * `dir` / `roving` come off the root directly.\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\n segmentValue(type: SegmentType): number | null;\n segmentMin(type: SegmentType): number;\n segmentMax(type: SegmentType): number;\n segmentValueText(type: SegmentType): string | null;\n segmentDisplayText(type: SegmentType): string;\n isSegmentEmpty(type: SegmentType): boolean;\n isFirstSegmentType(type: SegmentType): boolean;\n\n registerSegment(handle: SegmentHandle): void;\n unregisterSegment(handle: SegmentHandle): void;\n\n focusSegment(type: SegmentType): void;\n typeDigit(type: SegmentType, digit: number): void;\n step(type: SegmentType, delta: number): void;\n goToBound(type: SegmentType, bound: 'min' | 'max'): void;\n setDayPeriod(period: 'am' | 'pm'): void;\n clear(type: SegmentType): void;\n focusSibling(type: SegmentType, step: -1 | 1): void;\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 * keyboard map (RTL-mirrored 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.segmentMin(segment())',\n '[attr.aria-valuemax]': 'ctx.segmentMax(segment())',\n '[attr.aria-valuenow]': 'valueNow()',\n '[attr.aria-valuetext]': 'ctx.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.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 },\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.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.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.registerSegment(h),\n (h) => this.ctx.unregisterSegment(h),\n 'afterNextRender',\n );\n }\n\n protected onFocus(): void {\n this.ctx.focusSegment(this.segment());\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 if (key.length === 1 && key >= '0' && key <= '9') {\n event.preventDefault();\n this.ctx.typeDigit(type, Number(key));\n return;\n }\n if (type === 'dayPeriod' && (key === 'a' || key === 'A' || key === 'p' || key === 'P')) {\n event.preventDefault();\n this.ctx.setDayPeriod(key === 'a' || key === 'A' ? 'am' : 'pm');\n return;\n }\n const rtl = this.ctx.dir() === 'rtl';\n switch (key) {\n case 'ArrowUp':\n event.preventDefault();\n this.ctx.step(type, 1);\n return;\n case 'ArrowDown':\n event.preventDefault();\n this.ctx.step(type, -1);\n return;\n case 'ArrowRight':\n event.preventDefault();\n this.ctx.focusSibling(type, rtl ? -1 : 1);\n return;\n case 'ArrowLeft':\n event.preventDefault();\n this.ctx.focusSibling(type, rtl ? 1 : -1);\n return;\n case 'Home':\n event.preventDefault();\n this.ctx.goToBound(type, 'min');\n return;\n case 'End':\n event.preventDefault();\n this.ctx.goToBound(type, 'max');\n return;\n case 'Backspace':\n case 'Delete':\n event.preventDefault();\n this.ctx.clear(type);\n return;\n default:\n return;\n }\n }\n}\n","import { computed, signal, type Signal } from '@angular/core';\n\nimport type { RovingTabindex } from '../roving-tabindex/roving-tabindex';\nimport { from12, 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 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 /** Composes the next parts into the field value (compose + clamp + write). */\n commit(next: P): 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 /**\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 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 }\n\n segmentValue(type: SegmentType): number | null {\n const parts = this.#host.parts();\n if (type === 'dayPeriod') {\n const hour = parts.hour;\n return hour == null ? null : hour >= 12 ? 1 : 0;\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 hour = this.#host.parts().hour;\n if (hour == null) {\n return null;\n }\n const names = this.#host.periodNames();\n return hour >= 12 ? 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 hour = this.#host.parts().hour;\n if (hour == null) {\n return this.#host.placeholderFor(type);\n }\n const names = this.#host.periodNames();\n return hour >= 12 ? 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 if (type === 'dayPeriod') {\n return this.#host.parts().hour == null;\n }\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 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 this.#typing.set({ type, buffer });\n this.#host.commit(this.#withPart(type, valid ? this.#toInternal(type, num) : null));\n const full = valid && (buffer.length >= spec.digits || num * 10 > max);\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.#host.commit(this.#withPart(type, this.#host.seed(type)));\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.#host.commit(this.#withPart(type, next));\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.#host.commit(this.#withPart(type, this.#toInternal(type, display)));\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 hour = this.#host.parts().hour ?? null;\n const pm = period === 'pm';\n const next = hour === null ? (pm ? 12 : 0) : pm ? (hour % 12) + 12 : hour % 12;\n this.#host.commit(this.#withPart('hour', next));\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.#host.commit(this.#withPart(type, null));\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 /** 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 hour = this.#host.parts().hour ?? null;\n const pm = hour !== null && 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 {\n assertTimeCapable,\n type DateAdapter,\n type TimeCapableDateAdapter,\n} from '../date-adapter/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 */\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 { InjectionToken, type ModelSignal } from '@angular/core';\nimport type { DateAdapter } from '../date-adapter/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 * The helper is internal — primitives re-export their generated\n * `provideFor<X>Defaults` and (when public) their token. Internal — not\n * re-exported from `public-api.ts`.\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 { 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 — the wrapper-friendliness\n * failure first fixed for the dropdown trigger in #640 / #651.\n *\n * This helper tracks ownership instead: it sets the attribute only when it is\n * absent (so a pre-existing consumer attribute is never re-stamped or claimed),\n * and on the falsy edge removes it only when this helper is the one that set it.\n * A consumer-set `disabled` therefore always survives an enabled state, while a\n * primitive-set one is cleaned up cleanly on re-enable.\n *\n * Mirrors the imperative reflection #651 introduced on `[forDropdownMenuTrigger]`\n * and is the single implementation every clobber-capable host shares.\n *\n * Writing the DOM attribute is a genuine side effect (it escapes the reactive\n * graph) and the ownership flag is a plain closure variable, not a signal — so\n * this is a sanctioned `effect()` use, not state propagation.\n *\n * Must be called from an injection context (it injects `ElementRef` and creates\n * an `effect`), typically a directive constructor.\n *\n * Internal — not re-exported from `public-api.ts`.\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, DestroyRef, ElementRef, Injectable, PLATFORM_ID, inject } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\n/**\n * Options passed to `DismissableLayer.activate`. Each handler receives the\n * native event and can call `preventDefault()` to veto the layer's\n * `onDismiss` callback. Handlers themselves are always invoked.\n */\nexport interface DismissableLayerActivateOptions {\n /** Fired when the user presses `Escape` while this is the topmost layer. */\n onEscapeKeyDown?: (event: KeyboardEvent) => void;\n\n /** Fired when the user pointer-downs outside this layer's host. */\n onPointerDownOutside?: (event: PointerEvent) => void;\n\n /** Fired when focus moves outside this layer's host. */\n onFocusOutside?: (event: FocusEvent) => void;\n\n /**\n * Fired in addition to `onPointerDownOutside` / `onFocusOutside` for\n * consumers that don't care which one occurred.\n */\n onInteractOutside?: (event: PointerEvent | FocusEvent) => void;\n\n /**\n * Default action invoked after each of the above fires when its event was\n * not `preventDefault()`-ed by the specific handler. This is where the\n * consumer wires \"close\" so the contract `preventDefault → stay open`\n * holds without manual flag-checking.\n */\n onDismiss?: () => void;\n\n /**\n * Extra elements whose subtrees count as \"inside\" for outside-pointer /\n * outside-focus checks (e.g. a portaled popover content owned by this\n * layer). Recomputed on every event so that DOM mutations are picked up.\n */\n exemptElements?: () => readonly Element[];\n}\n\n/**\n * Application-scoped registry that owns the document listeners used by\n * dismissable layers. Created once per Angular bootstrap (one per SSR\n * request), tied to the root injector lifetime.\n *\n * Why a service rather than module-level state:\n *\n * - SSR isolation: module-level globals leak between simultaneous server\n * requests in the same Node process. A `providedIn: 'root'` service is\n * instantiated per application injector.\n * - Bootstrap-safety: `TestBed.resetTestingModule()`, micro-frontend\n * reloads and any other code that destroys `ApplicationRef` should not\n * leave stale `document` listeners behind. The service registers its\n * listeners in the constructor and removes them via `DestroyRef` so\n * every bootstrap has exactly one set of listeners.\n * - SSR safety: `document` is inaccessible on the server. The service is a\n * no-op when `PLATFORM_ID` is not the browser; nothing about this code\n * path is reachable until an overlay calls `activate()`, which only\n * happens from `afterNextRender`.\n *\n * Listener phases — intentional asymmetry: `pointerdown` and `focusin`\n * register on the **capture** phase so outside-interaction is detected even\n * when overlay content stops bubbling propagation, but `keydown` (Escape)\n * registers on the **bubble** phase by design. The bubble phase is\n * load-bearing for Escape because the per-overlay `onEscapeKeyDown` handlers\n * (Dialog, Select, Menu, Popover, …) call `event.stopPropagation()` after they\n * close — that stops the same keydown from bubbling further up to an *ancestor*\n * overlay's keydown handler, which is how nested overlays avoid one Escape\n * closing two layers at once. Moving this listener to capture would fire it\n * before any of those handlers and defeat the stopPropagation-based\n * single-layer-per-Escape contract. The trade-off is that overlay content with\n * its own bubble-phase keydown handler that calls `stopPropagation()` can\n * swallow Escape before it reaches this listener; that is an accepted,\n * documented limitation rather than an accidental one.\n */\n@Injectable({ providedIn: 'root' })\nexport class DismissableLayerStack {\n readonly #document = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n\n readonly #stack: DismissableLayer[] = [];\n #suppressDepth = 0;\n\n readonly #onKeyDown = (event: KeyboardEvent): void => {\n if (event.key !== 'Escape') {\n return;\n }\n if (this.#suppressDepth > 0) {\n return;\n }\n this.#topmost()?.['handleEscape'](event);\n };\n readonly #onPointerDown = (event: Event): void => {\n if (this.#suppressDepth > 0) {\n return;\n }\n this.#topmost()?.['handlePointerDown'](event as PointerEvent);\n };\n readonly #onFocusIn = (event: Event): void => {\n if (this.#suppressDepth > 0) {\n return;\n }\n this.#topmost()?.['handleFocusIn'](event as FocusEvent);\n };\n\n constructor() {\n if (!this.#isBrowser) {\n return;\n }\n this.#document.addEventListener('keydown', this.#onKeyDown);\n this.#document.addEventListener('pointerdown', this.#onPointerDown, true);\n this.#document.addEventListener('focusin', this.#onFocusIn);\n\n inject(DestroyRef).onDestroy(() => {\n this.#document.removeEventListener('keydown', this.#onKeyDown);\n this.#document.removeEventListener('pointerdown', this.#onPointerDown, true);\n this.#document.removeEventListener('focusin', this.#onFocusIn);\n this.#stack.length = 0;\n this.#suppressDepth = 0;\n });\n }\n\n /** @internal */\n push(layer: DismissableLayer): void {\n this.#stack.push(layer);\n }\n\n /** @internal */\n remove(layer: DismissableLayer): void {\n const idx = this.#stack.indexOf(layer);\n if (idx >= 0) {\n this.#stack.splice(idx, 1);\n }\n }\n\n /**\n * Runs `fn` with the dispatcher suppressed. While suppressed, neither\n * Escape, pointer-down outside, nor focus-outside events are forwarded\n * to the topmost layer. Refcounted so nested teardowns nest correctly.\n */\n suppress<T>(fn: () => T): T {\n this.#suppressDepth++;\n try {\n return fn();\n } finally {\n this.#suppressDepth--;\n }\n }\n\n #topmost(): DismissableLayer | undefined {\n return this.#stack[this.#stack.length - 1];\n }\n}\n\n/**\n * Resolves the effective target of an interaction event for the\n * outside-detection containment check. Prefers `composedPath()[0]` so a\n * pointer-down / focus inside a shadow tree reports the real originating node\n * rather than the shadow host the event was retargeted to. Falls back to\n * `event.target` in environments without `composedPath`.\n */\nfunction 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 * Coordinates the standard \"dismissable surface\" interactions used by modal\n * dialogs, popovers, dropdown menus, drawers, and any other transient\n * overlay: Escape, pointer-down outside, focus-outside.\n *\n * Only the topmost active layer responds to events — nested layers (e.g. a\n * popover inside a dialog) shadow their parents until they deactivate.\n * Dispatch goes through a single shared document listener that always\n * targets the layer at the top of the stack, so synchronous changes to the\n * stack from a handler don't leak into sibling listeners.\n *\n * Each event handler can call `preventDefault()` on the native event to\n * cancel the layer's `onDismiss` action.\n */\nexport class DismissableLayer {\n readonly #host: HTMLElement;\n readonly #stack: DismissableLayerStack;\n #options: DismissableLayerActivateOptions = {};\n #active = false;\n\n constructor(host: HTMLElement, stack: DismissableLayerStack) {\n this.#host = host;\n this.#stack = stack;\n }\n\n get host(): HTMLElement {\n return this.#host;\n }\n\n get isActive(): boolean {\n return this.#active;\n }\n\n /**\n * Pushes this layer onto the dispatch stack. Calling `activate` twice\n * without an intervening `deactivate` is a no-op.\n */\n activate(options: DismissableLayerActivateOptions = {}): void {\n if (this.#active) {\n return;\n }\n this.#active = true;\n this.#options = options;\n this.#stack.push(this);\n }\n\n /** Removes this layer from the stack. */\n deactivate(): void {\n if (!this.#active) {\n return;\n }\n this.#active = false;\n this.#stack.remove(this);\n this.#options = {};\n }\n\n /**\n * Convenience wrapper around the stack's `suppress`. Lets owners\n * suppress the dispatcher without needing a fresh injection context\n * (e.g. inside `DestroyRef.onDestroy` or imperative teardown closures).\n */\n suppress<T>(fn: () => T): T {\n return this.#stack.suppress(fn);\n }\n\n protected handleEscape(event: KeyboardEvent): void {\n this.#options.onEscapeKeyDown?.(event);\n if (!event.defaultPrevented) {\n this.#options.onDismiss?.();\n }\n }\n\n protected handlePointerDown(event: PointerEvent): void {\n const target = resolveEventTarget(event);\n if (!target || this.#contains(target)) {\n return;\n }\n this.#options.onPointerDownOutside?.(event);\n this.#options.onInteractOutside?.(event);\n if (!event.defaultPrevented) {\n this.#options.onDismiss?.();\n }\n }\n\n protected handleFocusIn(event: FocusEvent): void {\n const target = resolveEventTarget(event);\n if (!target || this.#contains(target)) {\n return;\n }\n this.#options.onFocusOutside?.(event);\n this.#options.onInteractOutside?.(event);\n if (!event.defaultPrevented) {\n this.#options.onDismiss?.();\n }\n }\n\n #contains(target: Node): boolean {\n if (this.#host.contains(target)) {\n return true;\n }\n const exempt = this.#options.exemptElements?.();\n if (!exempt) {\n return false;\n }\n for (const el of exempt) {\n if (el.contains(target)) {\n return true;\n }\n }\n return false;\n }\n}\n\n/**\n * Creates a `DismissableLayer` for the directive's host element and wires\n * deactivation into `DestroyRef`. The host primitive owns activation\n * (typically via an `effect()` watching the open state).\n *\n * Use `layer.suppress(fn)` to run a callback with the dispatcher\n * suppressed (e.g. across a focus-return that would otherwise\n * cascade-dismiss the next topmost layer).\n */\nexport function injectDismissableLayer(): DismissableLayer {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const stack = inject(DismissableLayerStack);\n const layer = new DismissableLayer(host.nativeElement, stack);\n inject(DestroyRef).onDestroy(() => layer.deactivate());\n return layer;\n}\n","import { type DragRect } from './drag-geometry';\n\n/** A 2-D scroll velocity vector produced by `computeScrollVelocity`. */\nexport interface AutoScrollVelocity {\n readonly x: number;\n readonly y: number;\n}\n\nfunction axisVelocity(\n pos: number,\n start: number,\n end: number,\n edgeSize: number,\n maxSpeed: number,\n): number {\n if (edgeSize <= 0 || pos < start || pos > end) {\n return 0;\n }\n const distStart = pos - start;\n if (distStart <= edgeSize) {\n return -maxSpeed * (1 - distStart / edgeSize);\n }\n const distEnd = end - pos;\n if (distEnd <= edgeSize) {\n return maxSpeed * (1 - distEnd / edgeSize);\n }\n return 0;\n}\n\n/**\n * Computes a 2-D scroll velocity from the pointer position relative to a\n * scroll container's bounding rect. Each axis is computed independently:\n * negative values scroll toward the start edge, positive toward the end.\n * Velocity scales linearly with proximity; at the edge = ±`maxSpeed`, at\n * `edgeSize` pixels away = 0.\n */\nexport function computeScrollVelocity(\n rect: DragRect,\n point: { readonly x: number; readonly y: number },\n edgeSize: number,\n maxSpeed: number,\n): AutoScrollVelocity {\n return {\n x: axisVelocity(point.x, rect.left, rect.right, edgeSize, maxSpeed),\n y: axisVelocity(point.y, rect.top, rect.bottom, edgeSize, maxSpeed),\n };\n}\n\nfunction isScrollable(el: HTMLElement, win: Window): boolean {\n const style = win.getComputedStyle(el);\n const overflowY = style.overflowY;\n const overflowX = style.overflowX;\n const scrollsY =\n (overflowY === 'auto' || overflowY === 'scroll') && el.scrollHeight > el.clientHeight;\n const scrollsX =\n (overflowX === 'auto' || overflowX === 'scroll') && el.scrollWidth > el.clientWidth;\n return scrollsY || scrollsX;\n}\n\n/**\n * Walks up the DOM from `start` (inclusive) looking for the nearest scrollable\n * ancestor, stopping before `documentElement` and `body`. Returns the first\n * scrollable element, or `null` if none is found (the caller should fall back\n * to the viewport).\n */\nexport function findScrollContainer(start: HTMLElement | null, win: Window): HTMLElement | null {\n let el = start;\n while (el !== null && el !== win.document.documentElement && el !== win.document.body) {\n if (isScrollable(el, win)) {\n return el;\n }\n el = el.parentElement;\n }\n return null;\n}\n\n/** An active auto-scroll controller returned by `createAutoScroller`. */\nexport interface AutoScroller {\n /** Arms or disarms the rAF loop for the given pointer position. */\n update(point: { x: number; y: number }): void;\n /** Cancels the loop and clears cached state. Idempotent. */\n stop(): void;\n}\n\n/** Configuration passed to `createAutoScroller`. */\nexport interface AutoScrollerConfig {\n /** The list host element; used to find the nearest scrollable container. */\n readonly host: HTMLElement;\n /** The browser `Window`, or `null` in SSR / test environments without a DOM. */\n readonly win: Window | null;\n /** Pixel distance from the scroll edge that arms auto-scroll. */\n readonly edgeSize: number;\n /** Maximum scroll delta (px) applied per animation frame. */\n readonly maxSpeed: number;\n /** Called after each frame that actually scrolls, so callers can re-resolve the drop target. */\n readonly onFrame: () => void;\n}\n\ninterface ScrollTarget {\n rect(): DragRect;\n scrollBy(dx: number, dy: number): void;\n}\n\nfunction elementTarget(el: HTMLElement): ScrollTarget {\n return {\n rect(): DragRect {\n const r = el.getBoundingClientRect();\n return { left: r.left, top: r.top, right: r.right, bottom: r.bottom };\n },\n scrollBy(dx: number, dy: number): void {\n el.scrollLeft += dx;\n el.scrollTop += dy;\n },\n };\n}\n\nfunction viewportTarget(win: Window): ScrollTarget {\n return {\n rect(): DragRect {\n return { left: 0, top: 0, right: win.innerWidth, bottom: win.innerHeight };\n },\n scrollBy(dx: number, dy: number): void {\n win.scrollBy(dx, dy);\n },\n };\n}\n\n/**\n * Creates an auto-scroller that drives a `requestAnimationFrame` loop while a\n * pointer drag is near the edge of the nearest scrollable container (or the\n * viewport). Deltas are applied instantaneously per frame — no CSS smooth-scroll\n * easing — which is the `prefers-reduced-motion`-safe approach: scrolling is\n * functional, not decorative, so no reduced-motion branch is needed.\n *\n * Returns a no-op controller when `config.win` is falsy or lacks\n * `requestAnimationFrame` (SSR / environments without a window).\n */\nexport function createAutoScroller(config: AutoScrollerConfig): AutoScroller {\n const maybeWin = config.win;\n if (!maybeWin || typeof maybeWin.requestAnimationFrame !== 'function') {\n return { update() {}, stop() {} };\n }\n\n const win: Window = maybeWin;\n\n let target: ScrollTarget | null = null;\n let point: { x: number; y: number } | null = null;\n let rafId: number | null = null;\n\n function resolveTarget(): ScrollTarget {\n const el = findScrollContainer(config.host, win);\n return el ? elementTarget(el) : viewportTarget(win);\n }\n\n function tick(): void {\n rafId = null;\n if (point === null || target === null) {\n return;\n }\n const v = computeScrollVelocity(target.rect(), point, config.edgeSize, config.maxSpeed);\n if (v.x === 0 && v.y === 0) {\n target = null;\n return;\n }\n target.scrollBy(v.x, v.y);\n config.onFrame();\n rafId = win.requestAnimationFrame(tick);\n }\n\n return {\n update(next: { x: number; y: number }): void {\n point = next;\n if (target === null) {\n target = resolveTarget();\n }\n const v = computeScrollVelocity(target.rect(), point, config.edgeSize, config.maxSpeed);\n if (v.x === 0 && v.y === 0) {\n if (rafId !== null) {\n win.cancelAnimationFrame(rafId);\n rafId = null;\n }\n } else if (rafId === null) {\n rafId = win.requestAnimationFrame(tick);\n }\n },\n stop(): void {\n if (rafId !== null) {\n win.cancelAnimationFrame(rafId);\n rafId = null;\n }\n target = null;\n point = null;\n },\n };\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","/** 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\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 * @param point Viewport pointer coordinates.\n * @param containers Ordered `[source, ...connected]` container geometries.\n * @param orientation List axis — `'horizontal'`, `'vertical'`, or `'mixed'` (2D resolution for\n * wrapping grids of uniformly-sized items, considering both axes). `'mixed'` reduces to the\n * single-axis result when the items form a single row or a single column.\n * @param dir Writing direction for horizontal / mixed insertion-index math.\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 orientation: 'horizontal' | 'vertical' | 'mixed',\n dir: 'ltr' | 'rtl',\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(container.itemRects, point.x, point.y, orientation, dir);\n\n return { containerIndex, index };\n}\n","/** One reachable keyboard drop position: a container plus an insertion index within it. */\nexport interface DragSlot {\n /** Index into the ordered `[source, ...connected]` container list (0 = source). */\n readonly containerIndex: number;\n /** Insertion index within that container. */\n readonly index: number;\n}\n\n/**\n * Builds the flat, ordered sequence of reachable drop positions for a keyboard drag.\n * - The source container (index 0) contributes one slot per existing item\n * (`0 .. sourceCount - 1`): the dragged item is *reinserted* among the current items, so\n * the valid destination indices are exactly the existing positions.\n * - Each connected container contributes one slot per insertion gap (`0 .. count`,\n * inclusive of the append position), since the item is *added* to it.\n * Order: all source slots, then each connected container's slots in `connectedCounts` order.\n */\nexport function buildDragSlots(\n sourceCount: number,\n connectedCounts: readonly number[],\n): DragSlot[] {\n const slots: DragSlot[] = [];\n const clampedSource = Math.max(0, sourceCount);\n for (let i = 0; i < clampedSource; i++) {\n slots.push({ containerIndex: 0, index: i });\n }\n for (let ci = 0; ci < connectedCounts.length; ci++) {\n const count = Math.max(0, connectedCounts[ci]!);\n for (let i = 0; i <= count; i++) {\n slots.push({ containerIndex: ci + 1, index: i });\n }\n }\n return slots;\n}\n\n/** Flat-sequence position of `(containerIndex, index)`, or `-1` if not present. */\nexport function indexOfSlot(\n slots: readonly DragSlot[],\n containerIndex: number,\n index: number,\n): number {\n return slots.findIndex((s) => s.containerIndex === containerIndex && s.index === index);\n}\n\n/** Steps `current` by `delta` (±1), clamped to `[0, slots.length - 1]` (no wrap). */\nexport function stepSlot(slots: readonly DragSlot[], current: number, delta: 1 | -1): number {\n if (slots.length === 0) {\n return current;\n }\n return Math.max(0, Math.min(slots.length - 1, current + delta));\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). 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\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 if (!firstSegment || parseFloat(firstSegment) === 0) {\n target.style.transform = `translate(${x}px, ${y}px)`;\n destroyFn();\n return;\n }\n let finished = false;\n const finish = (): void => {\n if (finished) {\n return;\n }\n finished = true;\n target.removeEventListener('transitionend', onEnd);\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 });\n win.setTimeout(finish, 500);\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 */\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\n const descendants = clone.querySelectorAll('[data-testid]');\n descendants.forEach((el) => el.removeAttribute('data-testid'));\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","/** A minimal positioned rect — only the top-left corner is needed for a FLIP translate. */\nexport interface FlipRect {\n readonly left: number;\n readonly top: number;\n}\n\n/** The inverted translate (in px) that visually returns `last` to `first`. */\nexport interface FlipDelta {\n readonly dx: number;\n readonly dy: number;\n}\n\n/** Pure: the translate that moves an element from its Last position back to its First. */\nexport function flipDelta(first: FlipRect, last: FlipRect): FlipDelta {\n return { dx: first.left - last.left, dy: first.top - last.top };\n}\n\n/** Styling hook attribute set on each element while its FLIP transition plays. */\nexport const FLIP_ANIMATING_ATTR = 'data-drag-animating';\n\n/** Configuration for {@link playFlip}. */\nexport interface PlayFlipConfig {\n /** Element → its First (pre-change) rect, captured before the data change. */\n readonly first: ReadonlyMap<HTMLElement, FlipRect>;\n /** The browser window (for reflow + timeout), or `null` in SSR / non-DOM environments. */\n readonly win: Window | null;\n /** An element to leave untouched (the dragged host handled by drop-settle). */\n readonly exclude?: HTMLElement | null;\n /** Safety timeout (ms) after which the animating attribute is force-cleared. */\n readonly fallbackMs?: number;\n}\n\n/**\n * Runs the Invert + Play steps of a FLIP transition for every element in `first` that is still\n * connected and has moved. Measures Last via `getBoundingClientRect`, applies the inverted\n * transform with the transition suppressed, forces a reflow, then transitions back to identity\n * while `data-drag-animating` is present so a consumer CSS rule keyed on it governs duration /\n * easing. No-op when `win` is `null`. The library imposes no duration of its own.\n */\nexport function playFlip(config: PlayFlipConfig): void {\n const { first, win, exclude, fallbackMs: fallbackMsInput } = config;\n if (!win) {\n return;\n }\n const fallbackMs = fallbackMsInput ?? 500;\n\n const workList: { el: HTMLElement; d: FlipDelta }[] = [];\n for (const [el, firstRect] of first) {\n if (el === exclude) {\n continue;\n }\n if (!el.isConnected) {\n continue;\n }\n const r = el.getBoundingClientRect();\n const d = flipDelta(firstRect, r);\n if (d.dx === 0 && d.dy === 0) {\n continue;\n }\n workList.push({ el, d });\n }\n\n if (workList.length === 0) {\n return;\n }\n\n for (const { el, d } of workList) {\n el.style.transition = 'none';\n el.style.transform = `translate(${d.dx}px, ${d.dy}px)`;\n }\n\n void workList[0]!.el.offsetWidth;\n\n for (const { el } of workList) {\n el.setAttribute(FLIP_ANIMATING_ATTR, '');\n el.style.transition = '';\n el.style.transform = '';\n\n let done = false;\n const clear = (): void => {\n if (done) {\n return;\n }\n done = true;\n el.removeAttribute(FLIP_ANIMATING_ATTR);\n el.style.transform = '';\n el.style.transition = '';\n el.removeEventListener('transitionend', onEnd);\n };\n\n const onEnd = (event: TransitionEvent): void => {\n if (event.propertyName && event.propertyName !== 'transform') {\n return;\n }\n clear();\n };\n\n el.addEventListener('transitionend', onEnd, { once: true });\n win.setTimeout(clear, fallbackMs);\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*; the caller owns every *decision*.\n * `isLifted` is read on each keydown to route the event, and the two keydown\n * callbacks plus `onFocusOut` carry the caller's domain logic.\n */\nexport interface KeyboardDragMediatorConfig {\n /** Element the capture-phase `keydown` / `focusout` listeners attach to (the coordinator host). */\n readonly host: HTMLElement;\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 /** A `focusout` fired on the host. The caller decides whether it should cancel an in-flight drag. */\n onFocusOut(event: FocusEvent): void;\n}\n\n/**\n * Wires the capture-phase keyboard mediation shared by container-level drag-reorder\n * coordinators (`ForTreeNodeDrag`, `ForTableRowReorder`, `ForListboxReorder`).\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 symmetric `{ capture: true }` add / remove of the `keydown` listener (a\n * mismatched flag silently leaks the listener), the paired `focusout` listener, the\n * lifted-vs-idle routing decision, and teardown via `DestroyRef`. Domain behavior — what lifts,\n * what each key does, when a `focusout` cancels — stays with the caller through the callbacks.\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 const onKeydown = (event: KeyboardEvent): void => {\n if (config.isLifted()) {\n config.onLiftedKeydown(event);\n } else {\n config.onIdleKeydown(event);\n }\n };\n const onFocusOut = (event: FocusEvent): void => config.onFocusOut(event);\n\n host.addEventListener('keydown', onKeydown, { capture: true });\n host.addEventListener('focusout', onFocusOut);\n\n config.destroyRef.onDestroy(() => {\n host.removeEventListener('keydown', onKeydown, { capture: true });\n host.removeEventListener('focusout', onFocusOut);\n });\n}\n","/** Where to insert the live-sort placeholder: a parent node and the node to insert before. */\nexport interface PlaceholderInsertion {\n /** The DOM node the placeholder's nodes should be inserted into. */\n readonly parent: Node;\n /** The reference node to insert before; `null` means append to `parent`. */\n readonly ref: Node | null;\n}\n\n/**\n * Computes the DOM insertion point for the live-sort placeholder.\n *\n * @param hosts The target container's non-lifted item host elements, in DOM order.\n * @param index Insertion index within `hosts` (`0 .. hosts.length`, inclusive of append).\n * @param container Fallback parent used when the container has no items.\n * @returns The `parent` node and the `ref` node to insert before (`null` = append).\n */\nexport function placeholderInsertion(\n hosts: readonly HTMLElement[],\n index: number,\n container: HTMLElement,\n): PlaceholderInsertion {\n if (index < hosts.length) {\n const at = hosts[index]!;\n return { parent: at.parentNode ?? container, ref: at };\n }\n const last = hosts[hosts.length - 1];\n if (last) {\n return { parent: last.parentNode ?? container, ref: last.nextSibling };\n }\n return { parent: container, ref: null };\n}\n\n/**\n * Clamps a live-sort placeholder insertion index so it cannot cross a `dragDisabled`\n * (pinned) item. Each disabled host is a hard wall bounding the contiguous run of enabled\n * positions that contains `origin` — the gap the dragged item was lifted from — so the\n * placeholder stops at the first pinned item instead of travelling past it.\n *\n * Visual only: the committed drop index is resolved separately and is left unaffected. With\n * no disabled host the input index is returned unchanged (clamped to the valid range).\n *\n * @param index Raw insertion index resolved from pointer geometry (`0 .. disabled.length`).\n * @param disabled Disabled flag per non-lifted host, in DOM order.\n * @param origin Insertion index the dragged item was lifted from (its source gap).\n * @returns `index` clamped to the enabled run around `origin`.\n */\nexport function fencePlaceholderIndex(\n index: number,\n disabled: readonly boolean[],\n origin: number,\n): number {\n let lower = 0;\n for (let i = origin - 1; i >= 0; i--) {\n if (disabled[i]) {\n lower = i + 1;\n break;\n }\n }\n let upper = disabled.length;\n for (let i = origin; i < disabled.length; i++) {\n if (disabled[i]) {\n upper = i;\n break;\n }\n }\n return Math.max(lower, Math.min(upper, index));\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 once, on the first move that crosses `armThreshold`. Return\n * `false` to abort the session in flight (e.g. the grabbed element has since vanished):\n * the document listeners are torn down and no further callback fires.\n * - `onMove(event)` fires on every armed move after the lift.\n * - `onCommit(event)` fires on `pointerup` while armed.\n * - `onCancel()` fires on `pointercancel`, and on `Escape` when `cancelOnEscape` is set.\n *\n * Escape: with `cancelOnEscape`, a document `keydown` listener (alive only while a press is\n * tracked) aborts an armed drag on `Escape` — it tears the session down and fires `onCancel`,\n * just like a `pointercancel`. It is opt-in so callers that run their own keyboard-drag mode and\n * own the `Escape` handling themselves (e.g. `ForTreeNodeDrag`) stay unaffected.\n *\n * Click suppression: when a `pointerup` ends an armed drag, the next capture-phase `click`\n * on the document is swallowed (`stopPropagation` + `preventDefault`). The listener removes\n * itself after the first click, and a `suppressClickTimeoutMs` fallback removes it if no\n * click follows.\n */\n\n/** A live pointer-drag session. Call `destroy()` to remove every listener. */\nexport interface PointerDragSession {\n /** Remove the host listener, any active document listeners, and any pending click trap. */\n destroy(): void;\n}\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 once, on the first move past `armThreshold`. Return `false` to abort the session\n * in flight (the grabbed element vanished, etc.); the session tears its listeners down and\n * fires no further callback. Returning `true` or `void` keeps the session armed.\n */\n readonly onLift: (event: PointerEvent) => boolean | 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 /** Fires on `pointercancel`, and on `Escape` while armed when {@link cancelOnEscape} is set. */\n readonly onCancel: () => 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`, 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;\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 pointerId: number | null = null;\n\n let onDocumentMove: ((event: PointerEvent) => void) | null = null;\n let onDocumentUp: ((event: PointerEvent) => void) | null = null;\n let onDocumentCancel: ((event: PointerEvent) => void) | null = null;\n let onDocumentKeydown: ((event: KeyboardEvent) => void) | null = null;\n let onDocumentClick: ((event: MouseEvent) => void) | null = null;\n\n const removeDocumentListeners = (): void => {\n if (onDocumentMove) {\n document.removeEventListener('pointermove', onDocumentMove, { capture: true });\n onDocumentMove = null;\n }\n if (onDocumentUp) {\n document.removeEventListener('pointerup', onDocumentUp, { capture: true });\n onDocumentUp = null;\n }\n if (onDocumentCancel) {\n document.removeEventListener('pointercancel', onDocumentCancel, { capture: true });\n onDocumentCancel = null;\n }\n if (onDocumentKeydown) {\n document.removeEventListener('keydown', onDocumentKeydown);\n onDocumentKeydown = null;\n }\n };\n\n const removeClickTrap = (): void => {\n if (onDocumentClick) {\n document.removeEventListener('click', onDocumentClick, { capture: true });\n onDocumentClick = null;\n }\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 pointerId = null;\n removeDocumentListeners();\n };\n\n const move = (event: PointerEvent): void => {\n if (!start) {\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 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 if (opts.onLift(event) === false) {\n resetTracking();\n return;\n }\n }\n opts.onMove(event);\n };\n\n const installClickTrap = (): void => {\n const trap = (event: MouseEvent): void => {\n event.stopPropagation();\n event.preventDefault();\n removeClickTrap();\n };\n onDocumentClick = trap;\n document.addEventListener('click', trap, { capture: true });\n setTimeout(() => {\n if (onDocumentClick === trap) {\n removeClickTrap();\n }\n }, suppressTimeout);\n };\n\n const up = (event: PointerEvent): void => {\n const wasArmed = armed;\n if (wasArmed) {\n installClickTrap();\n }\n resetTracking();\n if (wasArmed) {\n opts.onCommit(event);\n }\n };\n\n const cancel = (): void => {\n resetTracking();\n opts.onCancel();\n };\n\n const down = (event: PointerEvent): void => {\n if (start !== null) {\n return;\n }\n if (!opts.canStart(event)) {\n return;\n }\n start = { x: event.clientX, y: event.clientY };\n armed = false;\n pointerId = event.pointerId;\n\n onDocumentMove = move;\n onDocumentUp = up;\n onDocumentCancel = cancel;\n document.addEventListener('pointermove', move, { capture: true });\n document.addEventListener('pointerup', up, { capture: true });\n document.addEventListener('pointercancel', cancel, { capture: true });\n\n if (opts.cancelOnEscape) {\n const escape = (event: KeyboardEvent): void => {\n if (armed && event.key === 'Escape') {\n cancel();\n }\n };\n onDocumentKeydown = escape;\n document.addEventListener('keydown', escape);\n }\n };\n\n host.addEventListener('pointerdown', down, { capture: true });\n\n return {\n destroy(): void {\n host.removeEventListener('pointerdown', down, { capture: true });\n releaseCapture();\n removeDocumentListeners();\n removeClickTrap();\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) so the floating\n * preview's orchestration lives in one place; it resolves the `DragPreview` discriminator\n * internally (the supplied preview is either already a full `DragPreview` or the minimal\n * `{ moveTo, destroy }` shape). 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","/** One visible tree row as the resolver sees it. Rects in viewport coords. */\nexport interface TreeDropRow {\n /** The node's string value. */\n readonly value: string;\n /** 1-based depth. */\n readonly level: number;\n /** rect.left — used to map levels to x. */\n readonly left: number;\n readonly top: number;\n readonly bottom: number;\n}\n\n/** Where a lifted node will land, for rendering an insertion indicator. */\nexport interface TreeDropIndicator {\n /** The visible row the indicator anchors to (the node value). */\n readonly anchor: string;\n /** Whether the line sits just before or just after the anchor row in DOM order. */\n readonly position: 'before' | 'after';\n /** Resolved 1-based depth of the drop. */\n readonly level: number;\n}\n\n/** A resolved tree drop position. */\nexport interface TreeDropTarget {\n /** New parent's value, or `null` for the root level. */\n readonly parentValue: string | null;\n /** Insertion index among the new parent's children (post-removal space). */\n readonly index: number;\n /** Resolved 1-based depth of the dropped node. */\n readonly level: number;\n /**\n * Number of existing children under `parentValue` at the resolved `level` (excluding the\n * dragged node, which is absent from `rows`). The dropped node will be sibling\n * `index + 1` of `siblingCount + 1` after the move — the numbers screen-reader\n * announcements report.\n */\n readonly siblingCount: number;\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\n/**\n * Resolves a tree drop from a flattened, DOM-ordered list of the currently visible rows\n * (EXCLUDING the dragged node, whose subtree is collapsed during the drag).\n *\n * @param rows Visible rows in DOM order, dragged node excluded.\n * @param gapIndex Insertion gap: the row index the dropped node would sit *before* (`rows.length`\n * = after the last row). For pointer, derive this from the vertical midpoint rule; for keyboard,\n * it is the running target the arrows step.\n * @param desiredLevel Caller's desired depth (pointer: nearest level to the pointer x; keyboard:\n * the running level the Left/Right arrows adjust). Clamped to the gap's allowed band.\n */\nexport function resolveTreeDrop(\n rows: readonly TreeDropRow[],\n gapIndex: number,\n desiredLevel: number,\n): TreeDropTarget {\n if (rows.length === 0) {\n return { parentValue: null, index: 0, level: 1, siblingCount: 0 };\n }\n\n const gap = clamp(gapIndex, 0, rows.length);\n const prev = gap > 0 ? (rows[gap - 1] ?? null) : null;\n const next = gap < rows.length ? (rows[gap] ?? null) : null;\n\n const maxLevel = prev ? prev.level + 1 : 1;\n let minLevel = next ? next.level : 1;\n if (minLevel > maxLevel) {\n minLevel = maxLevel;\n }\n\n const level = clamp(desiredLevel, minLevel, maxLevel);\n\n let parentValue: string | null = null;\n if (level > 1) {\n for (let i = gap - 1; i >= 0; i--) {\n if (rows[i]!.level === level - 1) {\n parentValue = rows[i]!.value;\n break;\n }\n }\n }\n\n let index = 0;\n let siblingCount = 0;\n for (let i = 0; i < rows.length; i++) {\n if (!isSiblingUnder(rows, i, level, parentValue)) {\n continue;\n }\n siblingCount++;\n if (i < gap) {\n index++;\n }\n }\n\n return { parentValue, index, level, siblingCount };\n}\n\n/**\n * Whether the row at `rowIndex` is a child of `parentValue` at depth `level` — i.e. it sits\n * at `level` and its nearest preceding row at `level - 1` is `parentValue` (root rows at\n * `level === 1` have no ancestor row, so they always qualify when their depth matches).\n */\nfunction isSiblingUnder(\n rows: readonly TreeDropRow[],\n rowIndex: number,\n level: number,\n parentValue: string | null,\n): boolean {\n const row = rows[rowIndex]!;\n if (row.level !== level) {\n return false;\n }\n if (level === 1) {\n return true;\n }\n for (let j = rowIndex - 1; j >= 0; j--) {\n if (rows[j]!.level === level - 1) {\n return rows[j]!.value === parentValue;\n }\n }\n return parentValue === null;\n}\n\n/**\n * Maps a pointer y coordinate to the insertion gap among `rows` using the vertical-midpoint\n * rule: the gap is the index of the first row whose vertical midpoint sits below `y`\n * (`rows.length` when `y` is below every row's midpoint).\n *\n * @param rows Visible rows in DOM order, dragged node excluded.\n * @param y Pointer y in viewport coordinates.\n */\nexport function gapFromPointerY(rows: readonly TreeDropRow[], y: number): number {\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i]!;\n const mid = (row.top + row.bottom) / 2;\n if (y < mid) {\n return i;\n }\n }\n return rows.length;\n}\n\n/**\n * Resolves the insertion-indicator anchor for a gap: the line sits `before` the row at\n * `gapIndex`, or `after` the last row when the gap is past the end. Returns `null` when there\n * are no rows to anchor to.\n *\n * @param rows Visible rows in DOM order, dragged node excluded.\n * @param gapIndex Insertion gap (same as passed to {@link resolveTreeDrop}).\n * @param level Resolved 1-based depth to report on the indicator.\n */\nexport function resolveDropIndicator(\n rows: readonly TreeDropRow[],\n gapIndex: number,\n level: number,\n): TreeDropIndicator | null {\n if (rows.length === 0) {\n return null;\n }\n const gap = clamp(gapIndex, 0, rows.length);\n if (gap >= rows.length) {\n return { anchor: rows[rows.length - 1]!.value, position: 'after', level };\n }\n return { anchor: rows[gap]!.value, position: 'before', level };\n}\n\n/**\n * Maps a pointer x coordinate to the nearest candidate level within the allowed band\n * at `gapIndex`. Uses each level's representative left (minimum left observed among rows\n * at that level) and falls back to linear interpolation when a level isn't present.\n *\n * @param rows Visible rows in DOM order, dragged node excluded.\n * @param gapIndex Gap index (same as passed to `resolveTreeDrop`).\n * @param x Pointer x in viewport coordinates.\n */\nexport function levelFromPointerX(\n rows: readonly TreeDropRow[],\n gapIndex: number,\n x: number,\n): number {\n if (rows.length === 0) {\n return 1;\n }\n\n const next = gapIndex < rows.length ? (rows[gapIndex] ?? null) : null;\n const minLevel = next ? next.level : 1;\n\n const levelLefts = new Map<number, number>();\n for (const row of rows) {\n const existing = levelLefts.get(row.level);\n if (existing === undefined || row.left < existing) {\n levelLefts.set(row.level, row.left);\n }\n }\n\n const candidateLevels = Array.from(levelLefts.keys()).sort((a, b) => a - b);\n\n if (candidateLevels.length === 0) {\n return minLevel;\n }\n\n let bestLevel = candidateLevels[0]!;\n let bestDist = Infinity;\n for (const lvl of candidateLevels) {\n const lx = levelLefts.get(lvl)!;\n const dist = Math.abs(x - lx);\n if (dist < bestDist) {\n bestDist = dist;\n bestLevel = lvl;\n }\n }\n\n return bestLevel;\n}\n","import { Injectable, type Signal, signal } from '@angular/core';\n\nimport { type ForDrawerSide } from './drawer-side';\n\n/**\n * Snapshot of a single drawer registered with {@link ForDrawerStack}. The\n * stack is LIFO ordered (root → topmost) and exposes only what other\n * coordinators need — `host` for ancestry checks, `side` for layout\n * heuristics, `scaleBackground` for visual composition, `parent` for\n * topology, `dragging` so visual coordinators (e.g.\n * `ForDrawerScaleCoordinator`'s nested-transform pass) can yield the\n * surface to imperative drag handlers, and the resolved nested-transform\n * tunables so the coordinator never needs to re-read scope-dependent\n * defaults.\n */\nexport interface DrawerStackNode {\n readonly host: HTMLElement;\n readonly side: ForDrawerSide;\n readonly scaleBackground: boolean;\n readonly parent: HTMLElement | null;\n /**\n * Reactive flag that flips to `true` while a swipe gesture is in flight\n * on this drawer's surface. Visual coordinators must yield the host's\n * inline transform to the drag handlers while this is `true`.\n */\n readonly dragging: Signal<boolean>;\n /**\n * Scale factor applied to *this* drawer's host while it owns one or\n * more direct child drawers (the nested-drawer visual). Resolved from\n * the drawer's own injector scope at push time so per-scope\n * `provideForDrawerDefaults` overrides flow through.\n */\n readonly nestedScaleAmount: number;\n /**\n * Pixels of translation applied to *this* drawer's host while it owns\n * one or more direct child drawers, in the direction *away* from its\n * anchored edge.\n */\n readonly nestedTranslateYpx: number;\n}\n\n/**\n * Returned by {@link ForDrawerStack.push}. `depth` is the number of\n * ancestor drawers currently registered above this one (0 for a root\n * drawer, 1 for a single-nested child, …). `cleanup` pops the node;\n * calling it while descendants are still registered throws so consumers\n * surface their own destroy-order bugs instead of silently leaking.\n */\nexport interface DrawerStackHandle {\n readonly depth: number;\n cleanup(): void;\n}\n\n/**\n * App-scoped LIFO registry of every active `[forDrawer]`. Mounted drawers\n * push themselves on first render and pop on destroy; the stack's signal\n * is the single source of truth for nesting topology consumed by:\n *\n * - `[forDrawer]` itself, to derive `data-depth` and `data-state-nested`\n * on its host (the latter when the stack contains a node whose\n * `parent` is this drawer's host).\n * - `ForDrawerScaleCoordinator`, when `scaleBackground` is opted in by\n * multiple levels of nesting and the visual effect must compose along\n * the LIFO topmost.\n *\n * The companion to {@link DismissableLayerStack} and `InertSiblingsStack`:\n * those keep the focus / dismiss / inert behaviour LIFO-correct, this one\n * keeps the *visual* / *topology* layer LIFO-correct. Both are read-only\n * to consumers — there is no public API for explicit ordering, the LIFO\n * is determined by mount order.\n *\n * SSR: `providedIn: 'root'` so state is per Angular bootstrap. The\n * directives that call `push` only do so from `afterNextRender`, which\n * doesn't run on the server, so there is nothing to guard here.\n *\n * Internal — not re-exported from `public-api.ts`.\n */\n@Injectable({ providedIn: 'root' })\nexport class ForDrawerStack {\n readonly #stack = signal<readonly DrawerStackNode[]>([]);\n\n /**\n * Reactive view of the current drawer stack (root → topmost). Reading\n * this from a `computed`/`effect` lets primitives react to nesting\n * changes synchronously when a child drawer mounts or unmounts.\n */\n readonly stack: Signal<readonly DrawerStackNode[]> = this.#stack.asReadonly();\n\n /**\n * Push a drawer onto the stack. Returns a {@link DrawerStackHandle}\n * carrying the computed `depth` and a `cleanup` that pops the same\n * node. `depth` is derived from the node's `parent` chain at push time:\n * a root drawer (no `parent`) is depth 0; a child of a depth-N drawer\n * is depth N+1.\n *\n * `cleanup` is idempotent on a node that's already gone, but throws if\n * the node still has descendants in the stack — the canonical signal\n * that the consumer's template tore down a parent before its child\n * (typically because the parent's `@if` flipped to `false` while the\n * child sits in a separate template branch). Nest the child's\n * `@if (childOpen())` *inside* the parent's `@if (parentOpen())` to\n * inherit Angular's bottom-up destroy order automatically.\n */\n push(node: DrawerStackNode): DrawerStackHandle {\n const depth = this.#computeDepth(node);\n this.#stack.update((s) => [...s, node]);\n return {\n depth,\n cleanup: () => this.#cleanup(node),\n };\n }\n\n #cleanup(node: DrawerStackNode): void {\n const current = this.#stack();\n const idx = current.indexOf(node);\n if (idx === -1) {\n return;\n }\n const hasDescendant = current.some(\n (other) => other !== node && this.#isDescendant(other, node, current),\n );\n if (hasDescendant) {\n throw new Error(\n '[forty-cdk/drawer] DrawerStack out-of-order cleanup: a parent drawer was destroyed while a nested child is still registered. Make sure the child @if is wrapped inside the parent @if so the child unmounts first.',\n );\n }\n const next = current.slice();\n next.splice(idx, 1);\n this.#stack.set(next);\n }\n\n #computeDepth(node: DrawerStackNode): number {\n if (node.parent === null) {\n return 0;\n }\n const stack = this.#stack();\n let depth = 0;\n let cursor: HTMLElement | null = node.parent;\n while (cursor) {\n depth += 1;\n const ancestor = stack.find((n) => n.host === cursor);\n if (!ancestor) {\n break;\n }\n cursor = ancestor.parent;\n }\n return depth;\n }\n\n #isDescendant(\n candidate: DrawerStackNode,\n ancestor: DrawerStackNode,\n stack: readonly DrawerStackNode[],\n ): boolean {\n let cursor: HTMLElement | null = candidate.parent;\n while (cursor) {\n if (cursor === ancestor.host) {\n return true;\n }\n const next = stack.find((n) => n.host === cursor);\n if (!next) {\n return false;\n }\n cursor = next.parent;\n }\n return false;\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 — not re-exported from `public-api.ts`.\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 * Convenience wrapper around {@link injectMediaQuery} for the\n * `prefers-reduced-motion: reduce` query — the standard hook for users who\n * have asked their OS to suppress animations. Returns a `Signal<boolean>`\n * that flips reactively if the preference changes mid-session.\n *\n * Used by primitives whose default behaviour involves motion that may be\n * hostile to vestibular sensitivity (drag gestures, large transforms,\n * parallax). Consumers should treat a `true` result as a hard signal to\n * skip the animated path entirely, not just to shorten the duration.\n *\n * Internal — not re-exported from `public-api.ts`.\n */\nexport function injectPrefersReducedMotion(): Signal<boolean> {\n return injectMediaQuery('(prefers-reduced-motion: reduce)');\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport { computed, DOCUMENT, effect, inject, Injectable, PLATFORM_ID, signal } from '@angular/core';\n\nimport { type ForDrawerSide } from '../drawer-stack/drawer-side';\nimport { ForDrawerStack } from '../drawer-stack/drawer-stack';\nimport { injectPrefersReducedMotion } from '../media-query/media-query';\n\n/**\n * Per-drawer configuration consumed by {@link ForDrawerScaleCoordinator}.\n * Resolved by `[forDrawer]` from inputs + defaults at register time so the\n * coordinator never needs to re-read scope-dependent values.\n *\n * `setBackgroundColorOnScale` controls whether `<body>` receives an inline\n * background colour while the wrapper is scaled — necessary to mask the\n * sliver of viewport that becomes visible between the scaled wrapper and\n * the viewport edge. Disabled by drawers that already paint a full-bleed\n * backdrop or apply their own body-level styling.\n *\n * The remaining keys default to a tuned set of values (scale `0.95`, +14 px Y,\n * 8 px corner radius, black body) but are tunable via\n * `provideForDrawerDefaults`.\n */\nexport interface ForDrawerScaleConfig {\n readonly setBackgroundColorOnScale: boolean;\n readonly scaleAmount: number;\n readonly scaleTranslateYpx: number;\n readonly scaleBorderRadiusPx: number;\n readonly scaleBackgroundColor: string;\n}\n\ninterface WrapperSnapshot {\n readonly transform: string;\n readonly transformOrigin: string;\n readonly borderRadius: string;\n readonly overflow: string;\n readonly transitionProperty: string;\n readonly transitionDuration: string;\n readonly transitionTimingFunction: string;\n}\n\ninterface BodySnapshot {\n readonly backgroundColor: string;\n}\n\nconst TRANSITION_DURATION_S = 0.5;\nconst TRANSITION_TIMING = 'cubic-bezier(0.32, 0.72, 0, 1)';\n\n/**\n * App-scoped coordinator that synchronises a registered\n * `[forDrawerWrapper]` element with the LIFO stack of active drawers\n * opted into the scale-background effect. The consumer chooses _which_\n * element wraps the rest of the app via explicit DI, instead of relying on a\n * global selector / data attribute.\n *\n * Stacking model: at most one wrapper is registered at any time; multiple\n * drawers may be registered concurrently. The topmost (most recently\n * registered) drawer's config commands the effective scale — when it\n * unregisters, the previous topmost takes over. Reverts to inline-style\n * snapshots only when the last drawer unregisters or the wrapper itself\n * is torn down.\n *\n * `prefers-reduced-motion: reduce` is treated as a hard kill switch:\n * while it is `true` the effect is suppressed entirely, the wrapper /\n * body styles are reverted, and the snapshot is cleared. When the\n * preference flips back to `false` with at least one active drawer, the\n * effect re-applies.\n *\n * SSR: providedIn `root` so its state is per Angular bootstrap. On the\n * server, `registerWrapper` / `registerDrawer` are no-ops since the\n * directives that call them only do so from `afterNextRender`.\n *\n * Internal — not re-exported from `public-api.ts`.\n */\n@Injectable({ providedIn: 'root' })\nexport class ForDrawerScaleCoordinator {\n readonly #document = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n readonly #prefersReducedMotion = injectPrefersReducedMotion();\n readonly #drawerStack = inject(ForDrawerStack);\n\n readonly #wrapperEl = signal<HTMLElement | null>(null);\n readonly #stack = signal<readonly ForDrawerScaleConfig[]>([]);\n\n #wrapperSnapshot: WrapperSnapshot | null = null;\n #bodySnapshot: BodySnapshot | null = null;\n /**\n * Hosts for which this coordinator currently owns an inline\n * `style.transform` from the nested-state pass. Used to ensure we only\n * clear transforms we ourselves applied — drag handlers also write to\n * `style.transform` and the coordinator must yield to them.\n */\n readonly #nestedTransformOwned = new WeakSet<HTMLElement>();\n\n /**\n * `true` when a wrapper is registered, at least one drawer is active,\n * and `prefers-reduced-motion: reduce` is not set. Drawers reflect this\n * on their host as `data-scale-background` when `scaleBackground()` is\n * also `true`; the wrapper reflects it as `data-state=\"scaled\"` /\n * `\"idle\"`.\n */\n readonly active = computed<boolean>(() => {\n return this.#wrapperEl() !== null && this.#stack().length > 0 && !this.#prefersReducedMotion();\n });\n\n readonly #activeConfig = computed<ForDrawerScaleConfig | null>(() => {\n const stack = this.#stack();\n return stack.length === 0 ? null : (stack[stack.length - 1] ?? null);\n });\n\n constructor() {\n effect(() => {\n const wrapper = this.#wrapperEl();\n const config = this.#activeConfig();\n const reducedMotion = this.#prefersReducedMotion();\n\n if (wrapper && config && !reducedMotion) {\n this.#apply(wrapper, config);\n } else {\n this.#revert();\n }\n });\n\n // Nested-state visual pass. Mirrors the pre-#180 in-drawer effect but\n // runs once for the whole stack: every node that has at least one\n // direct child in the stack gets a `scale + translate3d` applied to\n // its host, gated by `prefers-reduced-motion: reduce` and by the\n // node's own `dragging()` signal (the swipe handlers in `ForDrawer`\n // mutate `style.transform` imperatively during a gesture, so the\n // coordinator yields the host to them and reapplies on release as a\n // side effect of the `dragging` flip). Tracking ownership in\n // `#nestedTransformOwned` keeps cleanup honest — we only clear\n // transforms we ourselves applied.\n effect(() => {\n const stack = this.#drawerStack.stack();\n const reducedMotion = this.#prefersReducedMotion();\n\n // Two-pass: figure out which nodes currently want a nested\n // transform, then reconcile against ownership. Reduced-motion\n // forces an empty `wantsNested` set so previously-owned hosts get\n // released cleanly.\n const wantsNested = new Set<HTMLElement>();\n if (!reducedMotion) {\n for (const node of stack) {\n // Read each node's `dragging` signal so the effect re-runs when\n // any drawer's gesture flips on or off — yielding to the drag\n // handlers without dropping the reactive subscription on the\n // signal (Angular's effect tracking ignores signals only read\n // inside conditionals that short-circuited last run).\n const dragging = node.dragging();\n const hasChild = stack.some((n) => n.parent === node.host);\n if (hasChild && !dragging) {\n wantsNested.add(node.host);\n }\n }\n } else {\n // Subscribe to `dragging` even under reduced-motion so a flip back\n // to `false` for the preference re-runs this effect with full\n // reactivity. Cheap to read (no allocation) and keeps the\n // dependency graph predictable.\n for (const node of stack) {\n node.dragging();\n }\n }\n\n // Apply transforms for nodes that want them.\n for (const node of stack) {\n if (!wantsNested.has(node.host)) {\n continue;\n }\n node.host.style.transform = this.#nestedTransform(\n node.side,\n node.nestedScaleAmount,\n node.nestedTranslateYpx,\n );\n this.#nestedTransformOwned.add(node.host);\n }\n\n // Release ownership on hosts we previously applied to but that no\n // longer want a nested transform. The drag handler may have already\n // overwritten `style.transform` with its own translate; only clear\n // when the parent isn't currently dragging (otherwise we'd stomp\n // the drag mid-gesture).\n for (const node of stack) {\n if (\n this.#nestedTransformOwned.has(node.host) &&\n !wantsNested.has(node.host) &&\n !node.dragging()\n ) {\n node.host.style.transform = '';\n this.#nestedTransformOwned.delete(node.host);\n }\n }\n });\n }\n\n /**\n * Build the nested-state transform string for a given drawer side. The\n * surface translates *away* from its anchored edge:\n *\n * - `bottom` (default) → translate up (`-translatePx` on Y).\n * - `top` → translate down (`+translatePx` on Y).\n * - `left` → translate left (`-translatePx` on X).\n * - `right` → translate right (`+translatePx` on X).\n *\n * The scale factor is uniform.\n */\n #nestedTransform(side: ForDrawerSide, amount: number, translatePx: number): string {\n const sign = side === 'top' ? 1 : -1;\n const tx = side === 'left' ? -translatePx : side === 'right' ? translatePx : 0;\n const ty = side === 'left' || side === 'right' ? 0 : sign * translatePx;\n return `scale(${amount}) translate3d(${tx}px, ${ty}px, 0)`;\n }\n\n /**\n * Register the consumer's app-shell wrapper. Only one wrapper may be\n * registered at a time; a second registration throws — the multi-wrapper\n * case has no defined visual outcome. Returns a cleanup that the caller wires to its\n * `DestroyRef.onDestroy`.\n */\n registerWrapper(host: HTMLElement): () => void {\n if (!this.#isBrowser) {\n return () => {};\n }\n if (this.#wrapperEl() !== null && this.#wrapperEl() !== host) {\n throw new Error(\n '[forty-cdk/drawer] Multiple [forDrawerWrapper] registered; only one wrapper is allowed per viewport.',\n );\n }\n this.#wrapperEl.set(host);\n return () => {\n if (this.#wrapperEl() === host) {\n this.#wrapperEl.set(null);\n }\n };\n }\n\n /**\n * Register an active drawer's scale config on the LIFO stack. Returns\n * a cleanup that pops the same entry — call from\n * `DestroyRef.onDestroy`. Calling `registerDrawer` without a registered\n * wrapper is silently a no-op (no styles applied) so test composition\n * and consumer flows don't have to enforce ordering.\n */\n registerDrawer(config: ForDrawerScaleConfig): () => void {\n if (!this.#isBrowser) {\n return () => {};\n }\n this.#stack.update((s) => [...s, config]);\n return () => {\n this.#stack.update((s) => {\n const idx = s.lastIndexOf(config);\n if (idx === -1) {\n return s;\n }\n const next = s.slice();\n next.splice(idx, 1);\n return next;\n });\n };\n }\n\n #apply(wrapper: HTMLElement, config: ForDrawerScaleConfig): void {\n if (!this.#wrapperSnapshot) {\n this.#wrapperSnapshot = {\n transform: wrapper.style.transform,\n transformOrigin: wrapper.style.transformOrigin,\n borderRadius: wrapper.style.borderRadius,\n overflow: wrapper.style.overflow,\n transitionProperty: wrapper.style.transitionProperty,\n transitionDuration: wrapper.style.transitionDuration,\n transitionTimingFunction: wrapper.style.transitionTimingFunction,\n };\n }\n\n const translate = `calc(env(safe-area-inset-top) + ${config.scaleTranslateYpx}px)`;\n wrapper.style.transform = `scale(${config.scaleAmount}) translate3d(0, ${translate}, 0)`;\n wrapper.style.transformOrigin = 'top';\n wrapper.style.borderRadius = `${config.scaleBorderRadiusPx}px`;\n wrapper.style.overflow = 'hidden';\n wrapper.style.transitionProperty = 'transform, border-radius';\n wrapper.style.transitionDuration = `${TRANSITION_DURATION_S}s`;\n wrapper.style.transitionTimingFunction = TRANSITION_TIMING;\n\n if (config.setBackgroundColorOnScale) {\n const body = this.#document.body;\n if (!this.#bodySnapshot) {\n this.#bodySnapshot = { backgroundColor: body.style.backgroundColor };\n }\n body.style.backgroundColor = config.scaleBackgroundColor;\n } else if (this.#bodySnapshot) {\n // Topmost drawer opts out — release the body snapshot we may have\n // taken from a previous (now-popped) drawer.\n this.#document.body.style.backgroundColor = this.#bodySnapshot.backgroundColor;\n this.#bodySnapshot = null;\n }\n }\n\n #revert(): void {\n if (this.#wrapperSnapshot) {\n const wrapper = this.#wrapperEl();\n if (wrapper) {\n wrapper.style.transform = this.#wrapperSnapshot.transform;\n wrapper.style.transformOrigin = this.#wrapperSnapshot.transformOrigin;\n wrapper.style.borderRadius = this.#wrapperSnapshot.borderRadius;\n wrapper.style.overflow = this.#wrapperSnapshot.overflow;\n wrapper.style.transitionProperty = this.#wrapperSnapshot.transitionProperty;\n wrapper.style.transitionDuration = this.#wrapperSnapshot.transitionDuration;\n wrapper.style.transitionTimingFunction = this.#wrapperSnapshot.transitionTimingFunction;\n }\n this.#wrapperSnapshot = null;\n }\n if (this.#bodySnapshot) {\n this.#document.body.style.backgroundColor = this.#bodySnapshot.backgroundColor;\n this.#bodySnapshot = null;\n }\n }\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport { DestroyRef, effect, inject, PLATFORM_ID, type Signal, signal } from '@angular/core';\n\nexport interface ElementBox {\n /** Border-box width in CSS pixels. */\n readonly width: number;\n /** Border-box height in CSS pixels. */\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 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 { DestroyRef, effect, ElementRef, inject, InjectionToken, type Signal } from '@angular/core';\nimport type { ValidationError } from '@angular/forms/signals';\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 * focus-on-label-click, unless {@link labelledElement} nominates a distinct\n * element.\n */\n readonly host: HTMLElement;\n /**\n * The element that should actually carry the field's `aria-*` association\n * and receive focus on label click, when it differs from {@link host}. For\n * primitives whose host is a non-interactive wrapper (`<div forSelect>`,\n * `<div forCombobox>`) this nominates the focusable control inside it (the\n * trigger button / `role=\"combobox\"` input), which registers after the field\n * wiring runs — hence a signal. When omitted or resolving to `null` the field\n * falls back to {@link host} (the host-is-the-control case, e.g. `ForListbox`\n * or a native `<input forFieldControl>`).\n */\n readonly labelledElement?: Signal<HTMLElement | null>;\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 /** Register the control whose state the field reflects. */\n registerControl(handle: FieldControlHandle): void;\n /** Remove a previously registered control. */\n unregisterControl(handle: FieldControlHandle): void;\n /**\n * Mark the label slot present; returns an unregister callback. The field\n * exposes a single `labelId` (not an id list), so one `[forLabel]` per field\n * is the supported shape — presence is boolean, not a count.\n */\n registerLabel(): () => void;\n /** Mark the description slot present; returns an unregister callback. Single `[forFieldDescription]` per field (single `descriptionId`). */\n registerDescription(): () => void;\n /** Mark the error slot present; returns an unregister callback. Single `[forFieldError]` per field (single `errorId`). */\n registerError(): () => void;\n /**\n * Forward a click to the registered control's focusable element, then focus\n * it — the 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 non-`<label>` `[forLabel]`, which has no native `for` forwarding, so\n * label-click activation stays consistent across host shapes.\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`, `aria-describedby`, and\n * `aria-errormessage` on the target, kept in sync via a single `effect`.\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\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 && previousTarget !== target) {\n clearFieldAttrs(previousTarget, ownsId, field.controlId());\n ownsId = false;\n }\n previousTarget = target;\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', field.describedBy());\n applyAttr(target, 'aria-errormessage', field.errorMessageId());\n });\n\n inject(DestroyRef).onDestroy(() => {\n if (previousTarget) {\n clearFieldAttrs(previousTarget, ownsId, field.controlId());\n }\n });\n}\n\n/**\n * Removes the field's association attributes (`aria-labelledby` /\n * `aria-describedby` / `aria-errormessage`) from a previously-targeted element,\n * plus the field-owned `id` when this helper set it. Symmetric with the\n * migration-cleanup branch so an arbitrary foreign `labelledElement` is left\n * clean once the control is destroyed or the target migrates.\n */\nfunction clearFieldAttrs(target: HTMLElement, ownsId: boolean, controlId: string): void {\n applyAttr(target, 'aria-labelledby', null);\n applyAttr(target, 'aria-describedby', null);\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` and registers its presence so the fieldset can resolve its\n * `aria-labelledby`; a descendant form control optionally reads\n * `effectiveDisabled` and ORs it into its own 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 * 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","/**\n * Computes `aria-posinset` / `aria-setsize` for every node in a **flat** list of\n * hierarchical rows, where depth is given only by each node's 1-based `level`\n * (as in an ARIA treegrid: rows are DOM siblings, hierarchy lives in `aria-level`).\n *\n * For a node at level `L`, its siblings are the nodes at the same level under the\n * same parent: contiguous `level === L` entries, skipping any deeper descendants\n * between them and bounded by the first shallower (`level < L`) entry on each side.\n *\n * Returns one `{ posinset, setsize }` entry per input level, in the same order.\n * Both are 1-based. An empty input returns an empty array.\n */\nexport function computeFlatHierarchy(\n levels: readonly number[],\n): { posinset: number; setsize: number }[] {\n return levels.map((level, index) => {\n let before = 0;\n for (let i = index - 1; i >= 0; i--) {\n const l = levels[i]!;\n if (l < level) break;\n if (l === level) before++;\n }\n let after = 0;\n for (let i = index + 1; i < levels.length; i++) {\n const l = levels[i]!;\n if (l < level) break;\n if (l === level) after++;\n }\n return { posinset: before + 1, setsize: before + 1 + after };\n });\n}\n","import type { Signal } from '@angular/core';\nimport type { ReferenceElement } from '@floating-ui/dom';\n\nimport type { FloatingAlign, FloatingConfig, FloatingSide } from './floating';\n\n/**\n * Single source of truth for the floating-ui positioning defaults shared by\n * the three trigger-anchored overlay roots — `[forPopover]`, `[forTooltip]`,\n * and `[forHoverCard]`.\n *\n * Angular's compiler requires every `input()` to be declared directly in a\n * class member initializer (NG8110), so the inputs themselves can't be\n * produced by a shared factory. To stop the (already-drifted) defaults from\n * diverging again, each root reads its non-seed defaults from this object and\n * the `anchored-positioning-inputs.spec.ts` guard asserts the three roots keep\n * an identical positioning input set.\n *\n * Only `side` / `align` / `sideOffset` / `collisionPadding` are seeded from\n * each root's defaults provider (`provideForPopoverDefaults` /\n * `provideForTooltipDefaults` / `provideForHoverCardDefaults`) so a scope\n * override flows through — and of those only `side` legitimately varies per\n * root (popover anchors `'bottom'`, tooltip / hover-card `'top'`). Everything\n * below is identical across all three roots.\n */\nexport const ANCHORED_POSITIONING_DEFAULTS = {\n /** Default gap (px) along the cross axis (parallel to `side`). */\n alignOffset: 0,\n /** `flip` / `shift` keep the surface inside the viewport by default. */\n avoidCollisions: true,\n /** Default padding (px) for the `arrow` middleware. */\n arrowPadding: 0,\n /** Default stickiness behaviour for `shift`. */\n sticky: 'partial' as 'partial' | 'always' | false,\n /** `data-detached=\"\"` is not reflected by default. */\n hideWhenDetached: false,\n /** Content is clipped until floating-ui resolves its first position by default. */\n clipUntilPositioned: true,\n} as const;\n\n/**\n * The resolved floating-ui positioning surface every trigger-anchored overlay\n * root publishes on its context. `ForPopoverContext`, `ForTooltipContext`, and\n * `ForHoverCardContext` all `extends` this so the 12-member positioning half of\n * each context interface is single-sourced rather than copied verbatim.\n *\n * Each member is the *effective* value — the per-instance input merged with the\n * scope default — so a content directive forwards it straight into\n * `injectOverlayShell` via `toFloatingPositioner` without re-resolving defaults.\n *\n * `open` is included because the floating positioner gates `autoUpdate` on it;\n * it is published by every root's open `model()` (a `ModelSignal` is a\n * `Signal`), so a single `extends` covers the whole positioner surface.\n */\nexport interface AnchoredPositioningContext {\n readonly open: Signal<boolean>;\n readonly side: Signal<FloatingSide>;\n readonly align: Signal<FloatingAlign>;\n readonly sideOffset: Signal<number>;\n readonly alignOffset: Signal<number>;\n readonly avoidCollisions: Signal<boolean>;\n readonly collisionPadding: Signal<number>;\n readonly arrowPadding: Signal<number>;\n readonly sticky: Signal<'partial' | 'always' | false>;\n readonly hideWhenDetached: Signal<boolean>;\n readonly clipUntilPositioned: Signal<boolean>;\n readonly arrow: Signal<HTMLElement | null>;\n}\n\n/**\n * Builds the `injectOverlayShell` floating-positioner block from an\n * `AnchoredPositioningContext` and the element the overlay anchors against.\n * Each of the three content directives (`ForPopoverContent`,\n * `ForTooltipContent`, `ForHoverCardContent`) built this 13-field block\n * verbatim; the only difference is the `reference` source — popover anchors to\n * its registered `[forPopoverAnchor]` (falling back to the trigger), tooltip\n * and hover-card anchor directly to the trigger — so the caller passes it in.\n */\nexport function toFloatingPositioner(\n ctx: AnchoredPositioningContext,\n reference: Signal<ReferenceElement | null>,\n): { kind: 'floating' } & FloatingConfig {\n return {\n kind: 'floating',\n reference,\n open: ctx.open,\n side: ctx.side,\n align: ctx.align,\n sideOffset: ctx.sideOffset,\n alignOffset: ctx.alignOffset,\n avoidCollisions: ctx.avoidCollisions,\n collisionPadding: ctx.collisionPadding,\n arrowPadding: ctx.arrowPadding,\n sticky: ctx.sticky,\n hideWhenDetached: ctx.hideWhenDetached,\n clipUntilPositioned: ctx.clipUntilPositioned,\n arrow: ctx.arrow,\n };\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 dismissable-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 dismissable 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 { DOCUMENT, PLATFORM_ID, DestroyRef, ElementRef, inject } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\nimport { afterNextRenderCancellable } from '../after-next-render-cancellable/after-next-render-cancellable';\n\nexport interface PortalConfig {\n /**\n * Where to portal the host element. Defaults to `document.body`. Pass a\n * specific container for cases like fullscreen API stacking, scoped\n * testing harnesses, or shadow DOM hosts.\n *\n * A function form is also accepted; it is resolved lazily inside the\n * existing `afterNextRender` callback so a value that is not yet available\n * at construction time — for example a directive input — can be used.\n * Returns `null` or `undefined` to fall back to `document.body`.\n */\n readonly target?: HTMLElement | (() => HTMLElement | null | undefined);\n}\n\n/**\n * Moves the directive's host element to `target` (default `document.body`)\n * after the first render and removes it on destroy. Designed for primitives\n * that need to escape clipping / `transform` / `overflow: hidden` ancestors:\n * tooltips, popovers, dialogs, toasts.\n *\n * Must be called from an injection context. The directive's `ElementRef` is\n * the host that gets portaled. Angular destroy hooks still fire normally —\n * the view tree is unaffected, only the DOM position changes.\n *\n * Note: any styles scoped to the original parent (CSS modules, encapsulated\n * `:host` rules, descendant selectors) won't reach the portaled element.\n * Style it via global CSS or with classes on the host directive itself.\n *\n * SSR: the portal is a no-op on the server. Overlay primitives use\n * `afterNextRender` to wire side effects, which doesn't run server-side\n * either; static markup (role, aria-*, ids, data-state) renders normally\n * and the portaled position is established once the client takes over.\n *\n * Implementation note — destroy ordering. The deferred `appendChild` is\n * registered via `afterNextRenderCancellable`; the destroy hook runs\n * `el.remove()`. If the directive is torn down between construction and the\n * next render (rare, but happens in synchronous open/close test paths or fast\n * SPA navigations), the destroy hook sees a not-yet-portaled element and\n * `el.remove()` is effectively a no-op against the original parent. Without\n * defending against it, the queued `afterNextRender` would still fire after\n * destroy and re-attach the element to `target` with no remaining destroy\n * hook to clean it up — a leak. The shared `afterNextRenderCancellable`\n * helper cancels the queued callback on destroy (it captures the\n * `AfterRenderRef`, calls `.destroy()` from its own destroy hook, and guards\n * the callback with a `destroyed` flag), so the `appendChild` never runs once\n * the directive is gone.\n */\nexport function injectPortal(config: PortalConfig = {}): void {\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n return;\n }\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const destroyRef = inject(DestroyRef);\n const doc = inject(DOCUMENT);\n const el = host.nativeElement;\n const resolveTarget = (): HTMLElement => {\n const t = typeof config.target === 'function' ? config.target() : config.target;\n return t ?? doc.body;\n };\n\n afterNextRenderCancellable(() => {\n const target = resolveTarget();\n if (el.parentNode !== target) {\n target.appendChild(el);\n }\n });\n\n destroyRef.onDestroy(() => {\n if (typeof requestAnimationFrame === 'undefined' || typeof el.getAnimations !== 'function') {\n el.remove();\n return;\n }\n requestAnimationFrame(() => {\n const animations = el.getAnimations();\n if (animations.length === 0) {\n el.remove();\n return;\n }\n Promise.all(animations.map((animation) => animation.finished.catch(() => undefined))).then(\n () => el.remove(),\n );\n });\n });\n}\n","import { afterNextRender, effect, ElementRef, inject, type Signal } from '@angular/core';\nimport {\n arrow,\n autoUpdate,\n computePosition,\n flip,\n hide,\n type Middleware,\n offset,\n type Padding,\n type Placement,\n type ReferenceElement,\n shift,\n size,\n} from '@floating-ui/dom';\n\nimport { injectPortal } from '../portal/portal';\n\nconst PLACEMENT_OPPOSITE: Record<FloatingSide, FloatingSide> = {\n top: 'bottom',\n right: 'left',\n bottom: 'top',\n left: 'right',\n};\n\n/** The four cardinal sides a floating element can be anchored to. */\nexport type FloatingSide = 'top' | 'right' | 'bottom' | 'left';\n\n/** Alignment along the side axis: at the start edge, centered, or at the end edge. */\nexport type FloatingAlign = 'start' | 'center' | 'end';\n\nexport interface FloatingConfig {\n /**\n * The anchor. Either a real DOM element (e.g. a button trigger) or a\n * floating-ui `VirtualElement` (e.g. for context menus that anchor at the\n * pointer position). Reactive — should emit `null` until the anchor is\n * available; positioning is skipped while `null`.\n */\n readonly reference: Signal<ReferenceElement | null>;\n\n /**\n * Whether the floating element is currently visible. `autoUpdate` is\n * started when this becomes `true` and torn down when it goes back to\n * `false`, so consumers don't pay for positioning while closed.\n */\n readonly open: Signal<boolean>;\n\n /**\n * Side the floating element is anchored to (`'top'`/`'right'`/`'bottom'`/\n * `'left'`). When omitted (or the signal returns `undefined`), defaults\n * to `'bottom'`. Pair with `align` for the full positioning\n * API.\n */\n readonly side?: Signal<FloatingSide | undefined>;\n\n /**\n * Alignment along the chosen side. Defaults to `'center'`. With `side`\n * this composes the floating-ui placement (e.g. `side: 'bottom'` +\n * `align: 'start'` → placement `'bottom-start'`).\n */\n readonly align?: Signal<FloatingAlign | undefined>;\n\n /**\n * Distance (px) between reference and floating along the *main* axis\n * (perpendicular to `side`). Forwarded to floating-ui's `offset`\n * middleware. Defaults to `0`.\n */\n readonly sideOffset?: Signal<number | undefined>;\n\n /**\n * Distance (px) along the *cross* axis (parallel to `side`). Useful for\n * shifting an `align: 'start'` popover slightly past the trigger edge.\n */\n readonly alignOffset?: Signal<number | undefined>;\n\n /**\n * Optional arrow element. When non-null, the `arrow` middleware is\n * registered and the helper writes `position: absolute`, the resolved\n * `left` / `top` from floating-ui, and a side-aware\n * `var(--for-arrow-offset, 0px)` on the *opposite* axis once floating-ui\n * resolves a position. Consumers control how far the arrow pokes out of\n * the bubble by setting `--for-arrow-offset` (typically a negative `px`\n * value) on the arrow element or any ancestor — the helper ships no\n * default visual.\n */\n readonly arrow?: Signal<HTMLElement | null>;\n\n /**\n * When `true` (default), the floating element is moved to `document.body`\n * on first render and removed on destroy. Set to `false` to keep it in\n * its declared parent (rare — only for designs where positioning ancestors\n * are guaranteed safe).\n */\n readonly portal?: boolean;\n\n /**\n * When `true` (default), the `flip` and `shift` middlewares are active so\n * the floating element stays inside the viewport. Set to `false` to keep\n * the requested placement even when it overflows — useful for tooltips\n * inside scroll containers where the consumer wants strict positioning.\n */\n readonly avoidCollisions?: Signal<boolean>;\n\n /**\n * Padding (px or per-side rect) applied to both `flip` and `shift`. When\n * unset, `flip` uses padding 0 (legacy behavior) and `shift` uses\n * `shiftPadding` (default 8). Setting this overrides both uniformly.\n */\n readonly collisionPadding?: Signal<number | Padding>;\n\n /**\n * Boundary the collision middlewares (`flip`, `shift`, `size`) measure\n * against. Defaults to the viewport. Pass an element (or list) to keep\n * the floating element inside a scroll container.\n */\n readonly collisionBoundary?: Signal<Element | Element[] | null>;\n\n /** Padding (px) handed to the `arrow` middleware so the arrow stays inside the floating element's rounded corners. */\n readonly arrowPadding?: Signal<number>;\n\n /**\n * Stickiness behaviour for `shift`. `'partial'` (default behavior of\n * `shift`) lets the floating element shift to stay visible. `'always'`\n * disables `shift` so the floating element keeps its requested placement\n * even off-screen. `false` is equivalent to `'partial'`.\n */\n readonly sticky?: Signal<'partial' | 'always' | false>;\n\n /**\n * When `true`, sets `data-detached=\"\"` on the host while the reference\n * element has scrolled off all clipping ancestors (`hide({ strategy:\n * 'escaped' })`). Lets consumers fade out tooltips/popovers tied to\n * scrolled-away triggers.\n */\n readonly hideWhenDetached?: Signal<boolean>;\n\n /**\n * When `true` (default / omitted), the floating element is clipped with\n * `clip-path: inset(50%)` until `@floating-ui/dom` resolves its first\n * position, so a short enter animation never flashes at the viewport\n * corner before placement lands. Set to `false` to paint from the first\n * frame — useful for a dramatic `animate.enter` that would otherwise lose\n * its opening frames while the async `computePosition` resolves, at the\n * cost of a possible first-frame flash at the pre-resolved position.\n */\n readonly clipUntilPositioned?: Signal<boolean>;\n\n /**\n * Padding (px) handed to the `shift` middleware so the floating element\n * never crowds the viewport edge. Default `8`. Used as the fallback for\n * `collisionPadding` when that signal is not provided.\n */\n readonly shiftPadding?: number;\n}\n\nfunction joinPlacement(side: FloatingSide, align: FloatingAlign): Placement {\n return (align === 'center' ? side : `${side}-${align}`) as Placement;\n}\n\nfunction splitPlacement(p: Placement): { side: FloatingSide; align: FloatingAlign } {\n const [rawSide, rawAlign] = p.split('-') as [FloatingSide, 'start' | 'end' | undefined];\n return { side: rawSide, align: rawAlign ?? 'center' };\n}\n\n/**\n * Compute the CSS `transform-origin` so a CSS scale animates outward from\n * the anchor edge. With `side: 'bottom', align: 'start'` the origin is\n * `left top` — a `scale(0.95)` collapses toward the trigger's bottom-left\n * corner.\n */\nfunction transformOriginFor(side: FloatingSide, align: FloatingAlign): string {\n let x: 'left' | 'right' | 'center';\n let y: 'top' | 'bottom' | 'center';\n if (side === 'top' || side === 'bottom') {\n y = side === 'top' ? 'bottom' : 'top';\n x = align === 'start' ? 'left' : align === 'end' ? 'right' : 'center';\n } else {\n x = side === 'left' ? 'right' : 'left';\n y = align === 'start' ? 'top' : align === 'end' ? 'bottom' : 'center';\n }\n return `${x} ${y}`;\n}\n\n/**\n * Wires a floating UI element (tooltip, popover, menu...) to its anchor.\n * Must be called from an injection context. Pulls the `ElementRef` it lives\n * on as the floating element. Owns:\n *\n * 1. Optional portal — `appendChild` to `document.body` once mounted, `remove()`\n * on `DestroyRef.onDestroy`.\n * 2. A reactive effect that subscribes to `open`/`reference`/`placement`/\n * offsets/arrow and runs `autoUpdate` while open, cleaning up via the\n * effect's `onCleanup` when the deps change or the host destroys.\n * 3. Inside `autoUpdate`'s callback, calls `computePosition` and applies the\n * resolved position via the `translate` property (leaving `transform`\n * free for the consumer's animations), plus `data-placement`, `data-side`,\n * `data-align`, `data-occluded` (when the `hide` middleware reports the\n * reference is off-screen), and CSS variables (`--for-anchor-width/-height`,\n * `--for-available-width/-height`, `--for-content-transform-origin`).\n * On the first resolved position it also drops the `clip-path` baseline\n * so the surface is only painted once anchored — otherwise a CSS enter\n * animation would flash at the viewport's top-left corner before\n * `computePosition` (which is async) resolves.\n *\n * Cleanup is symmetric: when `open` flips back to `false` (or the host is\n * destroyed) the helper clears every style, CSS variable, and `data-*`\n * attribute it set, on both the floating element and the optional arrow.\n * That keeps the next open from inheriting stale geometry from the\n * previous mount.\n *\n * Stylistic concerns (which side gets the arrow offset via\n * `--for-arrow-offset`, pointer events, background, animations) stay with\n * the consumer.\n */\nexport function injectFloating(config: FloatingConfig): void {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const el = host.nativeElement;\n\n if (config.portal !== false) {\n injectPortal();\n }\n\n afterNextRender(() => {\n // Baseline styles required for positioning. Set imperatively so consumer\n // host bindings don't have to remember.\n //\n // `clip-path: inset(50%)` keeps the surface unpainted until floating-ui\n // resolves its first position. `computePosition` is async, so without\n // this a CSS enter animation (`animate.enter`) plays one or two frames\n // at the `left:0 / top:0` origin — before the resolved position lands —\n // and the overlay flashes at the viewport's top-left corner. `clip-path`\n // (rather than `visibility: hidden`) keeps the element focusable, so the\n // overlay shell's initial-focus move still lands while the surface is\n // unpainted. Dropped on the first resolved position below.\n Object.assign(el.style, {\n position: 'fixed',\n left: '0',\n top: '0',\n });\n if (config.clipUntilPositioned?.() !== false) {\n el.style.clipPath = 'inset(50%)';\n }\n });\n\n const fallbackShiftPadding = config.shiftPadding ?? 8;\n\n effect((onCleanup) => {\n // Read `open`/`reference` first and early-return before establishing\n // dependencies on the rest of the config. A closed overlay must only\n // track `open`/`reference` — reading the rest up front would re-run this\n // effect on any offset/side change while closed, defeating the \"don't\n // pay for positioning while closed\" intent.\n const isOpen = config.open();\n const reference = config.reference();\n\n if (!isOpen || !reference) {\n return;\n }\n\n const arrowEl = config.arrow?.() ?? null;\n\n // Re-arm the `clip-path: inset(50%)` baseline at the start of every open\n // effect run, not only in `afterNextRender`. A config change while open\n // re-runs this effect: `onCleanup` calls `resetFloatingStyles`, which\n // clears `clip-path`, so without re-arming the surface would paint at the\n // previous frame's stale `translate` until the async `computePosition`\n // resolves. Re-arming hides it until the first resolved position drops the\n // baseline again below.\n if (config.clipUntilPositioned?.() !== false) {\n el.style.clipPath = 'inset(50%)';\n }\n\n // Resolve placement from `side` + `align` with sensible defaults.\n const sideInput = config.side?.() ?? 'bottom';\n const alignInput = config.align?.() ?? 'center';\n const requestedPlacement: Placement = joinPlacement(sideInput, alignInput);\n\n const sideOffsetVal = config.sideOffset?.() ?? 0;\n const alignOffsetVal = config.alignOffset?.() ?? 0;\n const avoidCollisions = config.avoidCollisions?.() ?? true;\n // `collisionPadding`, when set, applies uniformly to flip + shift +\n // size. When unset, preserve the historical defaults:\n // `flip` had no padding, `shift` had `shiftPadding ?? 8`.\n const collisionPaddingExplicit = config.collisionPadding?.();\n const flipPaddingValue = collisionPaddingExplicit ?? 0;\n const shiftPaddingValue = collisionPaddingExplicit ?? fallbackShiftPadding;\n const sizePaddingValue = collisionPaddingExplicit ?? fallbackShiftPadding;\n const collisionBoundary = config.collisionBoundary?.() ?? null;\n const arrowPaddingVal = config.arrowPadding?.() ?? 0;\n const stickyVal = config.sticky?.() ?? false;\n const hideOnDetach = config.hideWhenDetached?.() ?? false;\n\n const middleware: Middleware[] = [\n offset({ mainAxis: sideOffsetVal, crossAxis: alignOffsetVal }),\n ];\n\n if (avoidCollisions) {\n const flipOptions: Parameters<typeof flip>[0] = { padding: flipPaddingValue };\n if (collisionBoundary) flipOptions.boundary = collisionBoundary;\n middleware.push(flip(flipOptions));\n\n if (stickyVal !== 'always') {\n const shiftOptions: Parameters<typeof shift>[0] = { padding: shiftPaddingValue };\n if (collisionBoundary) shiftOptions.boundary = collisionBoundary;\n middleware.push(shift(shiftOptions));\n }\n }\n\n // `size` exposes available width/height as CSS variables so the\n // consumer can `max-height: var(--for-available-height)` etc.\n const sizeOptions: Parameters<typeof size>[0] = {\n padding: sizePaddingValue,\n apply({ availableWidth, availableHeight }) {\n el.style.setProperty(\n '--for-available-width',\n `${Math.max(0, Math.round(availableWidth))}px`,\n );\n el.style.setProperty(\n '--for-available-height',\n `${Math.max(0, Math.round(availableHeight))}px`,\n );\n },\n };\n if (collisionBoundary) sizeOptions.boundary = collisionBoundary;\n middleware.push(size(sizeOptions));\n\n middleware.push(hide({ strategy: 'referenceHidden' }));\n if (hideOnDetach) {\n middleware.push(hide({ strategy: 'escaped' }));\n }\n\n if (arrowEl) {\n middleware.push(arrow({ element: arrowEl, padding: arrowPaddingVal }));\n }\n\n const cleanup = autoUpdate(reference, el, () => {\n computePosition(reference, el, {\n strategy: 'fixed',\n placement: requestedPlacement,\n middleware,\n })\n .then(({ x, y, placement: resolvedPlacement, middlewareData }) => {\n // The element may have been hidden again between schedule and\n // resolution — bail so styles aren't clobbered after close.\n if (!config.open()) {\n return;\n }\n\n const { side: resolvedSide, align: resolvedAlign } = splitPlacement(\n resolvedPlacement as Placement,\n );\n\n // Position via the `translate` property, NOT `transform`. CSS\n // composes the individual `translate` / `rotate` / `scale`\n // properties before the `transform` property, with `translate`\n // outermost — so a consumer's enter animation on `scale` (or\n // `transform`) pivots in place around `--for-content-transform-origin`\n // instead of scaling the position offset itself. Using `transform`\n // here made `scale(0.9)` shrink the translation too, dragging the\n // surface in from the viewport's top-left corner as it grew. Leaving\n // `transform` free for the consumer is the whole point.\n el.style.translate = `${Math.round(x)}px ${Math.round(y)}px`;\n el.dataset['placement'] = resolvedPlacement;\n el.dataset['side'] = resolvedSide;\n el.dataset['align'] = resolvedAlign;\n // First valid position resolved — reveal the surface by dropping\n // the `clip-path: inset(50%)` baseline. From here the consumer's\n // enter animation runs anchored to the trigger, with the scale\n // origin set by `--for-content-transform-origin` below.\n el.style.clipPath = '';\n\n // Anchor box → CSS vars so the consumer can size the floating\n // element relative to the anchor (`width: var(--for-anchor-width)`).\n // Both real `Element`s and floating-ui `VirtualElement`s expose\n // `getBoundingClientRect`, so the call is safe.\n const rect = reference.getBoundingClientRect();\n el.style.setProperty('--for-anchor-width', `${Math.round(rect.width)}px`);\n el.style.setProperty('--for-anchor-height', `${Math.round(rect.height)}px`);\n el.style.setProperty(\n '--for-content-transform-origin',\n transformOriginFor(resolvedSide, resolvedAlign),\n );\n\n // hide() with strategy 'referenceHidden' — anchor scrolled off-screen.\n if (middlewareData.hide?.['referenceHidden']) {\n el.dataset['occluded'] = '';\n } else {\n delete el.dataset['occluded'];\n }\n // hide() with strategy 'escaped' — only registered when\n // `hideWhenDetached` is on.\n if (hideOnDetach && middlewareData.hide?.['escaped']) {\n el.dataset['detached'] = '';\n } else {\n delete el.dataset['detached'];\n }\n\n if (arrowEl && middlewareData.arrow) {\n const { x: ax, y: ay } = middlewareData.arrow;\n const opposite = PLACEMENT_OPPOSITE[resolvedSide];\n Object.assign(arrowEl.style, {\n position: 'absolute',\n left: ax != null ? `${ax}px` : '',\n top: ay != null ? `${ay}px` : '',\n right: '',\n bottom: '',\n [opposite]: 'var(--for-arrow-offset, 0px)',\n });\n // `data-placement` on the arrow stores the *side* only, for\n // historical reasons (CSS like `[data-placement=\"top\"]`).\n // `data-side` is the new canonical attribute; both stay in\n // sync until consumers migrate.\n arrowEl.dataset['placement'] = resolvedSide;\n arrowEl.dataset['side'] = resolvedSide;\n }\n })\n // The reference can detach mid-frame during virtualization /\n // autoUpdate scrolls, which makes computePosition reject. Swallow\n // — autoUpdate will reschedule with the next live frame and the\n // previous styles are still on the element.\n .catch(() => {});\n });\n\n // Clean up symmetrically with what computePosition wrote so a re-open\n // doesn't inherit stale geometry from the previous mount.\n onCleanup(() => {\n cleanup();\n resetFloatingStyles(el);\n if (arrowEl) {\n resetArrowStyles(arrowEl);\n }\n });\n });\n}\n\n/**\n * Strip the transient sizing CSS custom properties, the occlusion `data-*`\n * attributes, and the `clip-path` hide baseline `injectFloating` writes to the\n * floating element. The resolved `translate` and the resolved-placement outputs\n * (`--for-content-transform-origin`, `data-placement`, `data-side`,\n * `data-align`) are intentionally retained so a closing surface stays anchored\n * to its trigger — and keeps pivoting its scale leave from the trigger edge —\n * through `animate.leave`; the next mount re-arms the `clip-path` baseline in\n * `afterNextRender` and recomputes all of them before painting, so a retained\n * value never produces a stale-position flash.\n */\nfunction resetFloatingStyles(el: HTMLElement): void {\n // Clearing (not re-arming) the hide baseline keeps a closing surface\n // visible for its `animate.leave`; the next mount re-applies the\n // `clip-path` baseline in `afterNextRender`.\n el.style.removeProperty('clip-path');\n el.style.removeProperty('--for-anchor-width');\n el.style.removeProperty('--for-anchor-height');\n el.style.removeProperty('--for-available-width');\n el.style.removeProperty('--for-available-height');\n el.removeAttribute('data-occluded');\n el.removeAttribute('data-detached');\n}\n\n/**\n * Strip every inline style and `data-*` attribute `injectFloating` writes\n * to the optional arrow element. Mirrors `resetFloatingStyles`.\n */\nfunction resetArrowStyles(arrowEl: HTMLElement): void {\n arrowEl.style.removeProperty('position');\n arrowEl.style.removeProperty('left');\n arrowEl.style.removeProperty('top');\n arrowEl.style.removeProperty('right');\n arrowEl.style.removeProperty('bottom');\n arrowEl.removeAttribute('data-placement');\n arrowEl.removeAttribute('data-side');\n}\n","import { DOCUMENT, ElementRef, Injectable, inject } from '@angular/core';\n\n/**\n * Shared CSS selector for tabbable 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 */\nexport const FOCUSABLE_SELECTOR = [\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 '[tabindex]:not([tabindex=\"-1\"])',\n '[contenteditable=\"true\"]',\n 'audio[controls]',\n 'video[controls]',\n].join(',');\n\n/**\n * Returns the first tabbable descendant of `container`, or `null` if none\n * exists. Mirrors the filter used by `FocusTrap` (excludes `[hidden]` and\n * descendants of `[inert]` ancestors below the container).\n */\nexport function findFirstFocusable(container: HTMLElement): HTMLElement | null {\n const candidates = Array.from(container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR));\n for (const el of candidates) {\n if (el.hasAttribute('hidden')) {\n continue;\n }\n if (hasInertAncestor(el, container)) {\n continue;\n }\n return el;\n }\n return null;\n}\n\nfunction hasInertAncestor(el: HTMLElement, root: HTMLElement): boolean {\n let cur: HTMLElement | null = el.parentElement;\n while (cur && cur !== root) {\n if (cur.hasAttribute('inert')) {\n return true;\n }\n cur = cur.parentElement;\n }\n return false;\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 * When `true`, sets up Tab cycling and captures the previously-focused\n * element for return on deactivate, but skips the imperative `.focus()`\n * call. Lets the consumer keep focus elsewhere on open while still\n * benefitting from the trap's keyboard cycling once focus enters the\n * surface. Default `false`.\n */\n preventInitialFocus?: boolean;\n /**\n * Explicit element to restore focus to on `deactivate({ returnFocus: true })`.\n * When omitted (default), the trap captures `document.activeElement` at\n * activation time. Pass this when the caller needs to lock the return\n * target *before* a side-effect that mutates focus — e.g. `ForDialog`\n * capturing the trigger before applying `inert` on siblings, since\n * WebKit auto-blurs descendants of a freshly-inert ancestor.\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 currently-active `FocusTrap`\n * instances. Each trap registers itself on `activate` and removes itself\n * on `deactivate`. The topmost trap is the only one that handles Tab — all\n * earlier (shallower) traps' keydown listeners are no-ops while shadowed,\n * which is what makes nested overlays (e.g. a drawer inside a drawer) trap\n * focus inside the topmost surface instead of the parent's \"focus jumped\n * outside\" guard yanking focus back to the parent.\n *\n * Why a service rather than module-level state:\n *\n * - Bootstrap-safety: a module-level array survives\n * `TestBed.resetTestingModule()`, micro-frontend reloads and any other\n * code that destroys `ApplicationRef`, so a stale LIFO can leak across\n * bootstraps. A `providedIn: 'root'` service is instantiated per\n * application injector and garbage-collected with it, so every bootstrap\n * starts with an empty stack.\n * - SSR isolation: module-level globals leak between simultaneous server\n * requests in the same Node process; a root-scoped service is per-request.\n *\n * This mirrors the storage strategy of `DismissableLayerStack`: all\n * overlay-nesting LIFO stacks are root-scoped DI services, never\n * module-level. The two remain separate services on purpose because they\n * own different responsibilities — `DismissableLayerStack` centrally owns\n * the shared `document` listeners for Escape / outside-interaction, whereas\n * each `FocusTrap` owns its own keydown listener and only consults this\n * registry to decide whether it is topmost. This holder therefore needs no\n * `DOCUMENT` / `PLATFORM_ID` / `DestroyRef` injection: it is a\n * dependency-free LIFO of trap instances.\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. Used by Dialog,\n * Drawer, Sheet, and any other primitive that needs to keep keyboard focus\n * scoped to a section of the page.\n *\n * When multiple traps are active simultaneously (nested overlays), only\n * the LIFO topmost trap handles Tab. Outer traps stay registered (so\n * cleanup ordering is preserved) but their keydown handlers are no-ops\n * until the deeper trap deactivates.\n *\n * Out of scope: marking the rest of the page `inert` (focus trap alone is\n * enough for keyboard users; pointer-isolation is the consumer's job via\n * a backdrop).\n */\nexport class FocusTrap {\n readonly #container: HTMLElement;\n readonly #stack: FocusTrapStack;\n readonly #document: Document;\n #returnTo: HTMLElement | null = null;\n #active = false;\n #containerHadTabindex = false;\n #focusablesCache: HTMLElement[] | null = null;\n #observer: MutationObserver | null = null;\n\n readonly #onKeyDown = (event: KeyboardEvent): void => this.#handleKeyDown(event);\n\n constructor(container: HTMLElement, stack: FocusTrapStack, doc?: Document) {\n this.#container = container;\n this.#stack = stack;\n this.#document = doc ?? container.ownerDocument;\n }\n\n get container(): HTMLElement {\n return this.#container;\n }\n\n get isActive(): boolean {\n return this.#active;\n }\n\n activate(options: FocusTrapActivateOptions = {}): void {\n if (this.#active) {\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 : ((this.#document.activeElement as HTMLElement | null) ?? null);\n this.#document.addEventListener('keydown', this.#onKeyDown, true);\n this.#stack.push(this);\n\n const win = this.#container.ownerDocument.defaultView;\n if (win && typeof win.MutationObserver === 'function') {\n this.#observer = new win.MutationObserver(() => {\n this.#focusablesCache = null;\n });\n this.#observer.observe(this.#container, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['disabled', 'hidden', 'inert', 'tabindex', 'type', 'contenteditable'],\n });\n }\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 = this.#focusables()[0];\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 deactivate(options: FocusTrapDeactivateOptions = {}): void {\n if (!this.#active) {\n return;\n }\n this.#active = false;\n this.#document.removeEventListener('keydown', this.#onKeyDown, true);\n this.#stack.remove(this);\n this.#observer?.disconnect();\n this.#observer = null;\n this.#focusablesCache = null;\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) {\n this.#returnTo.focus();\n }\n this.#returnTo = null;\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 focusables = this.#focusables();\n if (focusables.length === 0) {\n event.preventDefault();\n this.#focusContainer();\n return;\n }\n const first = focusables[0]!;\n const last = focusables[focusables.length - 1]!;\n const active = this.#document.activeElement;\n\n if (!this.#container.contains(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 #focusables(): HTMLElement[] {\n if (this.#focusablesCache !== null) {\n return this.#focusablesCache;\n }\n const all = Array.from(this.#container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR));\n this.#focusablesCache = all.filter(\n (el) => !el.hasAttribute('hidden') && !this.#hasInertAncestor(el),\n );\n return this.#focusablesCache;\n }\n\n #hasInertAncestor(el: HTMLElement): boolean {\n let cur: HTMLElement | null = el;\n while (cur && cur !== this.#container) {\n if (cur.hasAttribute('inert')) {\n return true;\n }\n cur = cur.parentElement;\n }\n return false;\n }\n}\n\n/**\n * Creates a `FocusTrap` for the directive's host element. Activation and\n * deactivation are the consumer's responsibility — call `trap.activate()`\n * when the surface opens and `trap.deactivate({ returnFocus })` from a\n * `DestroyRef.onDestroy` (or equivalent) when it closes.\n *\n * The helper deliberately does NOT register a safety-net teardown: forcing\n * `returnFocus: false` from the helper would race consumer cleanups that\n * want `returnFocus: true`, and an unconditional `returnFocus: true` could\n * dump focus on a removed element. The consumer always knows the right\n * answer; do the deactivate yourself.\n */\nexport function injectFocusTrap(): FocusTrap {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n return new FocusTrap(host.nativeElement, inject(FocusTrapStack), inject(DOCUMENT));\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 { FOCUSABLE_SELECTOR } from '../focus-trap/focus-trap';\n\n/**\n * Reports whether the host element currently has at least one focusable\n * descendant, reactive to subtree mutations.\n *\n * Used by `ForTabsContent` to implement the WAI-ARIA Tabs APG rule that a\n * `tabpanel` is itself a tab stop (`tabindex=\"0\"`) **only** when it has no\n * focusable content of its own; a panel containing buttons / links / form\n * controls must not add a redundant tab stop.\n *\n * Detection mirrors the `FocusTrap` filter: it queries the shared\n * `FOCUSABLE_SELECTOR` and ignores `[hidden]` candidates and any candidate\n * nested under an `[inert]` ancestor below the host (those are not reachable\n * by Tab). A single `MutationObserver` scoped to the host's subtree watches\n * for childList / attribute changes so a panel that gains or loses focusable\n * content after first render flips the result.\n *\n * SSR-safe: on the server no observer is created, the DOM is never touched,\n * and the signal stays `false` (the panel is treated as having no focusable\n * content until the first browser render measures it). Cleaned up via\n * `DestroyRef`.\n *\n * The observer callback writing the signal is the single, intentional\n * \"external imperative source → signal\" exception, isolated here.\n *\n * Must be called from an injection context (it injects `ElementRef`,\n * `PLATFORM_ID`, and `DestroyRef`).\n *\n * Internal — not re-exported from `public-api.ts`.\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 = host.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR);\n for (const el of candidates) {\n if (el.hasAttribute('hidden')) {\n continue;\n }\n if (hasInertAncestor(el, host)) {\n continue;\n }\n return true;\n }\n return false;\n}\n\nfunction hasInertAncestor(el: HTMLElement, root: HTMLElement): boolean {\n let cur: HTMLElement | null = el.parentElement;\n while (cur && cur !== root) {\n if (cur.hasAttribute('inert')) {\n return true;\n }\n cur = cur.parentElement;\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 '../fieldset/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 — not re-exported from `public-api.ts`.\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 alongside every internal `touched` flip (blur, dismiss,\n * selection-commit). `[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 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 */\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 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.invalid());\n });\n injectFieldWiring({\n invalid: this.invalid,\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 });\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 — not re-exported from `public-api.ts`.\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 '../disabled-reflection/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 deliberately 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 — not re-exported from `public-api.ts`.\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","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","/**\n * A single self-clearing debounce timer: the `Math.max(0, delay)` clamp, the\n * `delay === 0` synchronous fast-path, and the lone pending\n * `setTimeout` / `clearTimeout` pair.\n *\n * The hover-driven menus (`[forMenuSub]`, `[forMenubar]`, `[forNavigationMenu]`)\n * each hand-rolled this exact timer arming/clearing under their own divergent\n * open/close policy (chain keep-alive, hover-after-open, per-value cancel\n * guards, skip-delay). This factory owns only the timing mechanics so those\n * policies stay at the call site — the caller arms with `schedule(delay)`,\n * which clears any in-flight timer first, runs `run` immediately when the\n * clamped delay is `0`, else fires it once after the delay. Internal — not\n * re-exported from `public-api.ts`.\n */\nexport interface DebouncedAction {\n /**\n * Arm the action after `delay` ms (clamped to `>= 0`). Clears any pending\n * timer first; a clamped delay of `0` runs `run` synchronously.\n */\n schedule(delay: number): void;\n /** Cancel a pending action without running it. Safe with no pending timer. */\n cancel(): void;\n /** `true` while an action is armed but not yet fired. */\n isPending(): boolean;\n}\n\n/**\n * Builds a {@link DebouncedAction} around `run`. Framework-free.\n */\nexport function createDebouncedAction(run: () => void): DebouncedAction {\n let timer: ReturnType<typeof setTimeout> | null = null;\n\n function cancel(): void {\n if (timer !== null) {\n clearTimeout(timer);\n timer = null;\n }\n }\n\n function schedule(delay: number): void {\n cancel();\n const clamped = Math.max(0, delay);\n if (clamped === 0) {\n run();\n return;\n }\n timer = setTimeout(() => {\n timer = null;\n run();\n }, clamped);\n }\n\n return {\n schedule,\n cancel,\n isPending: () => timer !== null,\n };\n}\n","import { effect, type Signal, untracked, type WritableSignal } from '@angular/core';\n\n/**\n * Inputs for {@link forceCloseWhenDisabled}.\n */\nexport interface ForceCloseWhenDisabledOptions {\n /** Open-state signal that is force-closed when `disabled` flips to true. */\n open: WritableSignal<boolean>;\n /** Whether all hover / focus interaction is currently ignored. */\n disabled: Signal<boolean>;\n /** Imperative cleanup run before the force-close (cancel any pending timers). */\n onForceClose: () => void;\n}\n\n/**\n * The single audited place that force-closes a hover-driven overlay when its\n * `disabled` input flips to `true` while open.\n *\n * Tooltip and Hover-card each carried a byte-identical copy of this reaction;\n * it is the **one sanctioned exception** to the project's \"never propagate\n * state inside `effect()`\" rule, so it must live in exactly one place rather\n * than two carve-outs to audit. The hover scheduler already early-returns on\n * `disabled()`, so hover / focus can't open a disabled overlay; this isolated\n * reaction only covers the remaining path — an open overlay being disabled out\n * from under itself.\n *\n * The `open` read is `untracked` so the effect never re-runs as a function of\n * `open` (no read+write cycle on the same signal); it reacts to `disabled`\n * alone. It integrates the disabled gate with the public `model()` instead of\n * wrapping the model in a parallel signal.\n *\n * Must be called from an injection context (registers an `effect`). Internal —\n * not re-exported from `public-api.ts`.\n */\nexport function forceCloseWhenDisabled(options: ForceCloseWhenDisabledOptions): void {\n effect(() => {\n if (options.disabled() && untracked(options.open)) {\n options.onForceClose();\n options.open.set(false);\n }\n });\n}\n","import type { WritableSignal } from '@angular/core';\n\n/**\n * Per-injector-scope coordinator the hover-intent scheduler consults to decide\n * whether the open delay should be skipped, and to open the skip-delay window\n * when a primitive finishes closing. Both `TooltipCoordinator` and\n * `HoverCardCoordinator` satisfy this contract structurally.\n */\nexport interface HoverIntentCoordinator {\n /** True while a peer in this scope just closed and the next open is instant. */\n skipDelay(): boolean;\n /** Opens the skip-delay window. Called by the scheduler when it closes. */\n startSkipDelay(): void;\n}\n\n/**\n * Inputs for {@link createHoverIntent}. Delays are passed as accessor\n * functions so the scheduler reads resolved values (per-instance override or\n * scope default) at the moment a timer is armed.\n */\nexport interface HoverIntentOptions {\n /** Writable open-state signal the scheduler flips. */\n open: WritableSignal<boolean>;\n /** Whether all hover / focus interaction is currently ignored. */\n isDisabled: () => boolean;\n /** Resolved open delay (ms) to use when arming an open timer. */\n openDelay: () => number;\n /** Resolved close delay (ms) to use when arming a close timer. */\n closeDelay: () => number;\n /** Skip-delay coordinator shared by peers in the same scope. */\n coordinator: HoverIntentCoordinator;\n}\n\n/**\n * Hover-intent scheduler handle returned by {@link createHoverIntent}.\n */\nexport interface HoverIntentScheduler {\n /** Schedule the open after the resolved open delay (instant when delay is 0 or skipped). */\n scheduleOpen(): void;\n /** Schedule the close after the resolved close delay; `immediate` bypasses the delay. */\n scheduleClose(immediate: boolean): void;\n /** Cancel any pending open / close timer without changing state. */\n cancelPending(): void;\n}\n\n/**\n * Shared hover-intent scheduler for Tooltip and Hover-card.\n *\n * Both primitives carry an identical open / close timer with skip-delay\n * coordination and `Math.max(0, …)` guards; this framework-free factory holds\n * the single pending timer and the open / close logic, parameterized by the\n * resolved open / close delays plus a {@link HoverIntentCoordinator}. The\n * directive constructs it once (after its `open` signal exists) and delegates\n * its public scheduling methods to the returned handle. Internal — not\n * re-exported from `public-api.ts`.\n */\nexport function createHoverIntent(options: HoverIntentOptions): HoverIntentScheduler {\n let pendingTimer: ReturnType<typeof setTimeout> | null = null;\n\n function cancelPending(): void {\n if (pendingTimer !== null) {\n clearTimeout(pendingTimer);\n pendingTimer = null;\n }\n }\n\n function close(): void {\n options.open.set(false);\n options.coordinator.startSkipDelay();\n }\n\n function scheduleOpen(): void {\n cancelPending();\n if (options.isDisabled()) {\n return;\n }\n if (options.open()) {\n return;\n }\n const base = options.coordinator.skipDelay() ? 0 : options.openDelay();\n const delay = Math.max(0, base);\n if (delay === 0) {\n options.open.set(true);\n return;\n }\n pendingTimer = setTimeout(() => {\n pendingTimer = null;\n if (options.isDisabled()) {\n return;\n }\n options.open.set(true);\n }, delay);\n }\n\n function scheduleClose(immediate: boolean): void {\n cancelPending();\n if (!options.open()) {\n return;\n }\n if (immediate) {\n close();\n return;\n }\n const delay = Math.max(0, options.closeDelay());\n if (delay === 0) {\n close();\n return;\n }\n pendingTimer = setTimeout(() => {\n pendingTimer = null;\n close();\n }, delay);\n }\n\n return { scheduleOpen, scheduleClose, cancelPending };\n}\n","import { DestroyRef, inject, signal } from '@angular/core';\n\nimport type { HoverIntentCoordinator } from './hover-intent';\n\n/**\n * Resolved cadence the {@link SkipDelayCoordinator} needs from its primitive's\n * defaults scope. Tooltip and Hover-card resolve these from their respective\n * `ForTooltipDefaults` / `ForHoverCardDefaults` tokens and hand them down.\n */\nexport interface SkipDelayCoordinatorDefaults {\n /** Resolved default open delay (ms) for primitives in this scope. */\n openDelay: number;\n /** Resolved default close delay (ms) for primitives in this scope. */\n closeDelay: number;\n /** Resolved skip-delay window (ms) for primitives in this scope. */\n skipDelayDuration: number;\n}\n\n/**\n * Per-injector-scope skip-delay coordinator shared by Tooltip and Hover-card.\n *\n * Holds the single skip-delay flag and the timer that closes its window, plus\n * the resolved cadence its primitives read when arming open / close timers.\n * Both primitives previously hand-rolled byte-identical copies of this state\n * machine; this is the single class, subclassed once per primitive so each\n * keeps its own DI token (and therefore its own independent skip-delay scope).\n *\n * Satisfies {@link HoverIntentCoordinator} so the shared hover-intent\n * scheduler consumes it directly. Internal — not re-exported from\n * `public-api.ts`.\n */\nexport abstract class SkipDelayCoordinator implements HoverIntentCoordinator {\n readonly #skipDelay = signal(false);\n #timer: ReturnType<typeof setTimeout> | null = null;\n\n /** Resolved default open delay (ms) for primitives in this scope. */\n readonly openDelay: number;\n\n /** Resolved default close delay (ms) for primitives in this scope. */\n readonly closeDelay: number;\n\n /** Resolved skip-delay window (ms) for primitives in this scope. */\n readonly skipDelayDuration: number;\n\n /** True while a peer in this scope just closed and the next open is instant. */\n readonly skipDelay = this.#skipDelay.asReadonly();\n\n constructor(defaults: SkipDelayCoordinatorDefaults) {\n this.openDelay = defaults.openDelay;\n this.closeDelay = defaults.closeDelay;\n this.skipDelayDuration = defaults.skipDelayDuration;\n inject(DestroyRef).onDestroy(() => this.cancelSkipDelay());\n }\n\n /** Opens the skip-delay window. Called by primitives when they finish closing. */\n startSkipDelay(): void {\n this.cancelSkipDelay();\n this.#skipDelay.set(true);\n this.#timer = setTimeout(\n () => {\n this.#skipDelay.set(false);\n this.#timer = null;\n },\n Math.max(0, this.skipDelayDuration),\n );\n }\n\n /** Cancels any pending skip-delay window. */\n cancelSkipDelay(): void {\n if (this.#timer !== null) {\n clearTimeout(this.#timer);\n this.#timer = null;\n }\n this.#skipDelay.set(false);\n }\n}\n","import { DOCUMENT, Injectable, PLATFORM_ID, inject } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\n/**\n * Marks every direct child of a **root element** (default `document.body`,\n * or a positioned container when a region-scoped modal passes one — #819)\n * other than the topmost active owner (and any element flagged as a\n * peer-of-owner via the `data-for-modal-peer` attribute) as `inert` and\n * `aria-hidden=\"true\"` while at least one owner is active on that root.\n * Restores each touched element to its exact prior state once the last\n * owner deactivates.\n *\n * Why this exists: `aria-modal=\"true\"` alone is insufficient. Safari +\n * VoiceOver and several other AT combinations still announce siblings of an\n * aria-modal node unless the rest of the document is explicitly hidden. The\n * WAI-ARIA APG modal-dialog pattern recommends combining `aria-modal` with\n * isolating the rest of the page.\n *\n * Stacking model (LIFO with safe out-of-order teardown) — per root:\n *\n * - Each root has its own owner-stack, applied snapshot, and\n * `MutationObserver`. A `document.body` root and a container root are\n * fully independent — locking one does not affect the other.\n * - A stack of active owners is maintained per root. The element-level\n * outcome is computed from the *current topmost owner* every time the\n * stack changes.\n * - When the topmost owner changes, the previous outcome is fully reverted\n * to the snapshot captured before it was applied, then a fresh outcome is\n * computed and applied for the new topmost.\n * - This means closing dialogs out of LIFO order still leaves the document\n * in a coherent state: the topmost remaining dialog gets its expected\n * isolation, and full restoration runs only when the stack empties.\n *\n * Portal compatibility: the owner does not need to be a direct child of the\n * root. We resolve the *root-level child* that is an ancestor of the owner\n * and exclude that subtree, so an in-place (non-portaled) dialog still keeps\n * its enclosing app shell interactive while everything else is inerted.\n *\n * Peers: any element carrying the `data-for-modal-peer` attribute is\n * excluded from the snapshot (e.g. a dialog backdrop portaled to body\n * alongside the dialog).\n *\n * Late siblings: an element portaled to the root *after* the topmost owner\n * activated would otherwise escape the isolation, since the initial sweep\n * only sees the children present at activation. While any owner is active a\n * `MutationObserver` watches the root's child list and inerts each newly\n * added sibling under the same skip/snapshot rules, so it is restored on\n * teardown too. The observer starts on the 0→1 owner transition and\n * disconnects when the stack empties.\n *\n * SSR: the registry is `providedIn: 'root'` so its state is scoped to a\n * single Angular bootstrap (one per SSR request). On the server, every\n * operation is a no-op — overlays only call `activate()` from\n * `afterNextRender`, which doesn't run server-side.\n */\n\n/**\n * Attribute that exempts a root-level child from the modal inert pass.\n * Carried by dialog / drawer backdrops (portaled alongside the modal)\n * and stamped by `injectOverlayShell` onto anchored-overlay hosts that were\n * opened from inside the protected root (#676), 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 */\nexport const MODAL_PEER_ATTRIBUTE = 'data-for-modal-peer';\n\ninterface SnapshotEntry {\n readonly el: HTMLElement;\n readonly hadInert: boolean;\n readonly prevAriaHidden: string | null;\n}\n\nexport interface InertSiblingsHandle {\n /** Pop this owner off the stack and recompute. */\n deactivate(): void;\n /** Whether this handle is still on the stack. */\n readonly isActive: boolean;\n}\n\ninterface RootState {\n readonly root: HTMLElement;\n readonly stack: HTMLElement[];\n appliedSnapshot: SnapshotEntry[];\n observer: MutationObserver | null;\n}\n\n@Injectable({ providedIn: 'root' })\nexport class InertSiblingsStack {\n readonly #document = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n\n readonly #roots = new Map<HTMLElement, RootState>();\n\n /**\n * Push `owner` onto the inert-siblings stack for `root` (default\n * `document.body`) and (re)apply the isolation outcome for the new topmost\n * owner. Returns a handle whose `deactivate()` pops this specific owner —\n * order-safe, so closing out of LIFO order works.\n *\n * When `root` is a positioned container (e.g. a region-scoped modal), only\n * that container's other children are inerted; body siblings outside the\n * container stay fully interactive (#819).\n */\n activate(owner: HTMLElement, root: HTMLElement = this.#document.body): InertSiblingsHandle {\n if (!this.#isBrowser) {\n return {\n deactivate: () => {},\n get isActive(): boolean {\n return false;\n },\n };\n }\n const state = this.#stateFor(root);\n this.#revertAppliedSnapshot(state);\n if (state.stack.length === 0) {\n this.#startObserving(state);\n }\n state.stack.push(owner);\n this.#applyForCurrentTopmost(state);\n\n let active = true;\n return {\n get isActive(): boolean {\n return active;\n },\n deactivate: (): void => {\n if (!active) {\n return;\n }\n active = false;\n const idx = state.stack.indexOf(owner);\n if (idx === -1) {\n return;\n }\n this.#revertAppliedSnapshot(state);\n state.stack.splice(idx, 1);\n if (state.stack.length > 0) {\n this.#applyForCurrentTopmost(state);\n } else {\n this.#stopObserving(state);\n this.#roots.delete(root);\n }\n },\n };\n }\n\n /**\n * Whether an overlay anchored to `anchor` should be left interactive over\n * the active modal — i.e. treated as a peer of the topmost owner instead of\n * inerted. Returns `true` only while at least one owner is active AND\n * `anchor` lives inside the current protected root for any active root,\n * which means the overlay was opened from within a modal (e.g. a Select /\n * DropdownMenu opened from a form inside a Dialog).\n *\n * Returns `false` when no owner is active — so an overlay opened with no\n * modal present is never pre-marked, and a modal opened later inerts it like\n * any other background sibling — and when `anchor` sits in an already-inerted\n * background subtree (a toast or a tooltip anchored to a backdrop element).\n *\n * `injectOverlayShell` calls this when an anchored-overlay host is portaled,\n * to decide whether to stamp `MODAL_PEER_ATTRIBUTE` on it so the\n * inert-siblings observer skips forty's own overlays instead of swallowing\n * them (#676). SSR-safe: on the server the roots map is always empty (no\n * owner activates), so this returns `false`.\n */\n ownsAnchor(anchor: Element): boolean {\n for (const state of this.#roots.values()) {\n const protectedRoot = this.#currentProtectedRoot(state);\n if (protectedRoot !== null && protectedRoot.contains(anchor)) {\n return true;\n }\n }\n return false;\n }\n\n #stateFor(root: HTMLElement): RootState {\n let state = this.#roots.get(root);\n if (!state) {\n state = { root, stack: [], appliedSnapshot: [], observer: null };\n this.#roots.set(root, state);\n }\n return state;\n }\n\n #applyForCurrentTopmost(state: RootState): void {\n const protectedRoot = this.#currentProtectedRoot(state);\n if (!protectedRoot) {\n return;\n }\n\n for (const child of Array.from(state.root.children)) {\n this.#inertChild(child, protectedRoot, state);\n }\n }\n\n #inertChild(child: Element, protectedRoot: HTMLElement, state: RootState): void {\n if (!(child instanceof HTMLElement)) {\n return;\n }\n if (child === protectedRoot) {\n return;\n }\n if (child.hasAttribute(MODAL_PEER_ATTRIBUTE)) {\n return;\n }\n if (state.appliedSnapshot.some((entry) => entry.el === child)) {\n return;\n }\n\n state.appliedSnapshot.push({\n el: child,\n hadInert: child.hasAttribute('inert'),\n prevAriaHidden: child.getAttribute('aria-hidden'),\n });\n\n child.setAttribute('inert', '');\n child.setAttribute('aria-hidden', 'true');\n }\n\n #currentProtectedRoot(state: RootState): HTMLElement | null {\n const top = state.stack[state.stack.length - 1];\n if (!top) {\n return null;\n }\n return this.#rootLevelChild(top, state.root) ?? top;\n }\n\n #startObserving(state: RootState): void {\n const win = this.#document.defaultView;\n if (state.observer || !win || typeof win.MutationObserver !== 'function') {\n return;\n }\n state.observer = new win.MutationObserver((records) => {\n const protectedRoot = this.#currentProtectedRoot(state);\n if (!protectedRoot) {\n return;\n }\n for (const record of records) {\n for (const node of Array.from(record.addedNodes)) {\n if (node instanceof HTMLElement && node.parentElement === state.root) {\n this.#inertChild(node, protectedRoot, state);\n }\n }\n }\n });\n state.observer.observe(state.root, { childList: true });\n }\n\n #stopObserving(state: RootState): void {\n state.observer?.disconnect();\n state.observer = null;\n }\n\n #revertAppliedSnapshot(state: RootState): void {\n for (const entry of state.appliedSnapshot) {\n if (!entry.hadInert) {\n entry.el.removeAttribute('inert');\n }\n if (entry.prevAriaHidden === null) {\n entry.el.removeAttribute('aria-hidden');\n } else {\n entry.el.setAttribute('aria-hidden', entry.prevAriaHidden);\n }\n }\n state.appliedSnapshot = [];\n }\n\n #rootLevelChild(el: HTMLElement, root: HTMLElement): HTMLElement | null {\n let cur: HTMLElement | null = el;\n while (cur && cur.parentElement && cur.parentElement !== root) {\n cur = cur.parentElement;\n }\n return cur && cur.parentElement === root ? cur : null;\n }\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n DOCUMENT,\n DestroyRef,\n Injectable,\n PLATFORM_ID,\n inject,\n signal,\n type Signal,\n} from '@angular/core';\n\n/**\n * Application-scoped tracker for the last input modality the user employed —\n * the in-house implementation of input-modality (pointer vs keyboard)\n * detection. Created once per Angular bootstrap (one per SSR\n * request), tied to the root injector lifetime.\n *\n * It installs exactly **one** capture-phase `keydown` and **one** capture-phase\n * `pointerdown` listener on `document`, regardless of how many primitives read\n * its state — every `injectFocusVisible()` consumer shares this single\n * singleton, so the document is never listened to more than once. Capture phase\n * is used so the modality is settled before any overlay content can stop\n * propagation.\n *\n * Why a service rather than module-level state:\n *\n * - SSR isolation: module-level globals leak between simultaneous server\n * requests in the same Node process. A `providedIn: 'root'` service is\n * instantiated per application injector.\n * - Bootstrap-safety: `TestBed.resetTestingModule()`, micro-frontend reloads,\n * and anything else that destroys `ApplicationRef` must not leave stale\n * `document` listeners behind. The listeners are registered in the\n * constructor and removed via `DestroyRef`.\n * - SSR safety: `document` is inaccessible on the server. The service is a\n * no-op when `PLATFORM_ID` is not the browser; `keyboard` stays `false` and\n * no listener is installed.\n *\n * Internal — not re-exported from `public-api.ts`.\n */\n@Injectable({ providedIn: 'root' })\nexport class InputModality {\n readonly #document = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n\n readonly #keyboard = signal(false);\n\n /**\n * `true` when the most recent input modality was the keyboard, `false` after\n * a pointer interaction (or before any interaction). Stays `false` on the\n * server.\n */\n readonly keyboard: Signal<boolean> = this.#keyboard.asReadonly();\n\n readonly #onKeyDown = (): void => {\n this.#keyboard.set(true);\n };\n readonly #onPointerDown = (): void => {\n this.#keyboard.set(false);\n };\n\n constructor() {\n if (!this.#isBrowser) {\n return;\n }\n this.#document.addEventListener('keydown', this.#onKeyDown, true);\n this.#document.addEventListener('pointerdown', this.#onPointerDown, true);\n\n inject(DestroyRef).onDestroy(() => {\n this.#document.removeEventListener('keydown', this.#onKeyDown, true);\n this.#document.removeEventListener('pointerdown', this.#onPointerDown, true);\n });\n }\n}\n","import { inject, type Signal } from '@angular/core';\n\nimport { InputModality } from './modality';\n\n/**\n * Returns a `Signal<boolean>` that is `true` while the last global input\n * modality was the keyboard, and `false` after a pointer interaction (or\n * before any interaction). This is the modality half of `:focus-visible`\n * styling: a consumer that wants a focus ring only on keyboard focus combines\n * this with the element's own focused state (`:focus`, or a `focusin` /\n * `focusout` listener) — e.g. `host: { '[attr.data-focus-visible]':\n * \"focused() && focusVisible() ? '' : null\" }`.\n *\n * Backed by the application-scoped {@link InputModality} singleton, so every\n * consumer shares a single capture-phase `keydown` / `pointerdown` listener on\n * `document` no matter how many call this.\n *\n * SSR-safe: on the server the backing service installs no listener and the\n * signal stays `false`. Must be called from an injection context.\n *\n * Internal — not re-exported from `public-api.ts`.\n */\nexport function injectFocusVisible(): Signal<boolean> {\n return inject(InputModality).keyboard;\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n DestroyRef,\n ElementRef,\n PLATFORM_ID,\n computed,\n inject,\n signal,\n type Signal,\n} from '@angular/core';\n\n/** Options for {@link injectHovered}. */\nexport interface HoveredOptions {\n /**\n * When this signal reports `true`, the returned signal is forced to `false`\n * and no interaction can set it — a disabled control is never hovered.\n */\n disabled?: Signal<boolean>;\n}\n\n/**\n * Returns a `Signal<boolean>` reflecting whether a pointing device is currently\n * hovering the host element. State is set on `pointerenter` and cleared on\n * `pointerleave`.\n *\n * Touch is suppressed: a `pointerenter` whose `pointerType` is `'touch'` does\n * not set the hovered state, so the emulated mouse-enter a tap produces on a\n * touchscreen never leaves the element stuck in a hovered state after the\n * finger lifts. Only `'mouse'` / `'pen'` pointers report hover.\n *\n * Attaches `pointerenter` / `pointerleave` listeners to the host element. The\n * `disabled` option short-circuits the result reactively (a pure `computed`,\n * never an `effect`-written signal) and also stops hover from arming while\n * disabled.\n *\n * SSR-safe: on the server no listener is attached and the signal stays\n * `false`. Must be called from an injection context (injects `ElementRef`,\n * `PLATFORM_ID`, `DestroyRef`).\n *\n * Internal — not re-exported from `public-api.ts`.\n */\nexport function injectHovered(opts?: HoveredOptions): Signal<boolean> {\n const disabled = opts?.disabled;\n const isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n if (!isBrowser) {\n return signal(false).asReadonly();\n }\n\n const el = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const hovered = signal(false);\n\n const onPointerEnter = (event: PointerEvent): void => {\n if (event.pointerType === 'touch') {\n return;\n }\n if (disabled?.()) {\n return;\n }\n hovered.set(true);\n };\n const onPointerLeave = (): void => {\n hovered.set(false);\n };\n\n el.addEventListener('pointerenter', onPointerEnter);\n el.addEventListener('pointerleave', onPointerLeave);\n\n inject(DestroyRef).onDestroy(() => {\n el.removeEventListener('pointerenter', onPointerEnter);\n el.removeEventListener('pointerleave', onPointerLeave);\n });\n\n return computed(() => (disabled?.() ? false : hovered()));\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n DestroyRef,\n ElementRef,\n PLATFORM_ID,\n computed,\n inject,\n signal,\n type Signal,\n} from '@angular/core';\n\n/** Options for {@link injectPressed}. */\nexport interface PressedOptions {\n /**\n * When this signal reports `true`, the returned signal is forced to `false`\n * and no interaction can set it — a disabled control is never pressed.\n */\n disabled?: Signal<boolean>;\n}\n\n/**\n * Returns a `Signal<boolean>` reflecting whether the host element is currently\n * being pressed — held down via the primary pointer button, or via the\n * <kbd>Enter</kbd> / <kbd>Space</kbd> key while focused. The state clears on\n * pointer release, the pointer leaving the element mid-press, key release, or\n * `blur` (covers focus leaving the element while a key is held).\n *\n * Attaches `pointerdown` / `pointerup` / `pointerleave` / `keydown` / `keyup` /\n * `blur` listeners to the host element. The `disabled` option short-circuits\n * the result reactively (a pure `computed`, never an `effect`-written signal)\n * and also stops a fresh press from arming while disabled.\n *\n * SSR-safe: on the server no listener is attached and the signal stays\n * `false`. Must be called from an injection context (injects `ElementRef`,\n * `PLATFORM_ID`, `DestroyRef`).\n *\n * Internal — not re-exported from `public-api.ts`.\n */\nexport function injectPressed(opts?: PressedOptions): Signal<boolean> {\n const disabled = opts?.disabled;\n const isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n if (!isBrowser) {\n return signal(false).asReadonly();\n }\n\n const el = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const pressed = signal(false);\n\n const onPointerDown = (event: PointerEvent): void => {\n if (event.pointerType === 'mouse' && event.button !== 0) {\n return;\n }\n if (disabled?.()) {\n return;\n }\n pressed.set(true);\n };\n const onPointerEnd = (): void => {\n pressed.set(false);\n };\n const onKeyDown = (event: KeyboardEvent): void => {\n if (event.key !== 'Enter' && event.key !== ' ') {\n return;\n }\n if (disabled?.()) {\n return;\n }\n pressed.set(true);\n };\n const onKeyUp = (event: KeyboardEvent): void => {\n if (event.key !== 'Enter' && event.key !== ' ') {\n return;\n }\n pressed.set(false);\n };\n const onBlur = (): void => {\n pressed.set(false);\n };\n\n el.addEventListener('pointerdown', onPointerDown);\n el.addEventListener('pointerup', onPointerEnd);\n el.addEventListener('pointerleave', onPointerEnd);\n el.addEventListener('keydown', onKeyDown);\n el.addEventListener('keyup', onKeyUp);\n el.addEventListener('blur', onBlur);\n\n inject(DestroyRef).onDestroy(() => {\n el.removeEventListener('pointerdown', onPointerDown);\n el.removeEventListener('pointerup', onPointerEnd);\n el.removeEventListener('pointerleave', onPointerEnd);\n el.removeEventListener('keydown', onKeyDown);\n el.removeEventListener('keyup', onKeyUp);\n el.removeEventListener('blur', onBlur);\n });\n\n return computed(() => (disabled?.() ? false : pressed()));\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\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 /** PageUp / PageDown map to first / last when true. Default `false`. */\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 */\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 ? 'first' : null;\n case 'PageDown':\n return pageKeys ? 'last' : 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\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 * - `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 '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 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 { DisableableHandle } from '../collection/first-enabled-host';\nimport { type ListNavigationAction, moveIndex } from './keyboard-navigation';\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 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 {\n computed,\n type OutputEmitterRef,\n type Signal,\n signal,\n type WritableSignal,\n} from '@angular/core';\nimport type { ReferenceElement } from '@floating-ui/dom';\n\nimport { Collection } from '../collection/collection';\nimport { firstEnabledHost } from '../collection/first-enabled-host';\nimport { adoptHostId } from '../host-id/host-id';\nimport type { IdGenerator } from '../id-generator/id-generator';\nimport { type ListNavigationAction } from '../keyboard-navigation/keyboard-navigation';\nimport { nextEnabledHandle } from '../keyboard-navigation/move-in-collection';\nimport {\n emitVetoableEvent,\n emitVetoableNativeEvent,\n type VetoableEvent,\n type VetoableNativeEvent,\n} from '../vetoable-event/vetoable-event';\n\n/**\n * Minimal option-handle shape the controller's focus algorithm needs: a host\n * element to focus and a `disabled` signal to skip. Each primitive widens this\n * with its own per-option fields (value, label, id, posInSet, …) and registers\n * the widened handle through {@link ListboxOverlayController.registerOption}.\n */\nexport interface ListboxOverlayOptionHandle {\n readonly host: HTMLElement;\n readonly disabled: Signal<boolean>;\n}\n\n/**\n * The dismiss / auto-focus outputs the controller forwards to. Each primitive\n * owns the `output()` instances (they must be declared as class-field\n * initializers for the Angular compiler to detect them); the controller only\n * emits through them, so the shared dismiss pipeline lives in one place.\n */\nexport interface ListboxOverlayEmitTargets {\n readonly escapeKeyDown: OutputEmitterRef<VetoableNativeEvent<KeyboardEvent>>;\n readonly pointerDownOutside: OutputEmitterRef<VetoableNativeEvent<PointerEvent>>;\n readonly focusOutside: OutputEmitterRef<VetoableNativeEvent<FocusEvent>>;\n readonly interactOutside: OutputEmitterRef<VetoableNativeEvent<PointerEvent | FocusEvent>>;\n readonly autoFocusOnOpen: OutputEmitterRef<VetoableEvent>;\n readonly autoFocusOnClose: OutputEmitterRef<VetoableEvent>;\n}\n\n/**\n * Construction-time wiring for {@link ListboxOverlayController}. Plain signals\n * and callbacks only — the controller never imports a primitive's context\n * token, mirroring `injectOverlayShell`, so it stays orthogonal to each root's\n * surface.\n *\n * @typeParam H Primitive option-handle type.\n * @typeParam Focus Initial-focus union (identical `'first' | 'last' | 'selected'`\n * in both primitives, kept generic so each keeps its own named alias).\n * @typeParam CloseReason Close-reason union owned by the primitive.\n */\nexport interface ListboxOverlayControllerDeps<\n H extends ListboxOverlayOptionHandle,\n Focus,\n CloseReason,\n> {\n /** Id-generator prefix base, e.g. `'for-select'` (suffixed with `-trigger` / `-content`). */\n readonly idPrefix: string;\n /** Full `[forty-cdk/<primitive>]`-prefixed error thrown when a second anchor registers. */\n readonly multipleAnchorsError: string;\n /** Default initial-focus target when none is set explicitly. */\n readonly defaultInitialFocus: Focus;\n /** The control's effective disabled — gates open / navigate / toggle. */\n readonly effectiveDisabled: Signal<boolean>;\n /** The control's two-way `open` model — flipped by the open / close machine. */\n readonly setOpen: (open: boolean) => void;\n /** Read the control's current open state. */\n readonly isOpen: () => boolean;\n /** Dismiss / auto-focus outputs to forward to. */\n readonly emit: ListboxOverlayEmitTargets;\n /** Mark the control touched (mirrors the trigger blur) on Escape / outside dismissal. */\n readonly markTouched: () => void;\n /**\n * Per-primitive close side effect, run after the open model flips to `false`\n * (Select clears the virtualized activedescendant + pending navigation here).\n */\n readonly onClose?: (reason: CloseReason) => void;\n /**\n * Per-option focus side effect, run after `navigate` focuses the target\n * (Select scrolls the option into view and applies `selectionFollowsFocus`).\n */\n readonly onNavigateFocus?: (target: H) => void;\n /** Per-primitive option-unregister side effect (Select clears a stale activedescendant). */\n readonly onUnregisterOption?: (handle: H) => void;\n}\n\n/**\n * The overlay-listbox state machine shared by `ForSelect` and `ForTimePicker`\n * (the WAI-ARIA select-only combobox and the slot-listbox time picker). Owns\n * the option collection, the trigger / anchor / content element registries and\n * their ids, the DOM-focus navigation algorithm, the initial-focus /\n * close-reason state, the open / close machine, and the dismiss / auto-focus\n * emit forwarders — every method each root used to duplicate verbatim.\n *\n * Value-specific behaviour (selection equality, `activate`, `focusSelectedOption`,\n * typeahead, the virtualized activedescendant path, `commitOnTab`'s value set)\n * stays in the root and is threaded through {@link ListboxOverlayControllerDeps}\n * callbacks where it must run as a side effect of a shared transition.\n *\n * Internal — lives in `_internal/`, never re-exported from `public-api.ts`.\n *\n * @typeParam H Primitive option-handle type.\n * @typeParam Focus Initial-focus union.\n * @typeParam CloseReason Close-reason union.\n */\nexport class ListboxOverlayController<H extends ListboxOverlayOptionHandle, Focus, CloseReason> {\n readonly #deps: ListboxOverlayControllerDeps<H, Focus, CloseReason>;\n readonly #idGen: IdGenerator;\n readonly #items = new Collection<H>();\n\n readonly triggerId: WritableSignal<string>;\n readonly contentId: WritableSignal<string>;\n\n readonly #initialFocus: ReturnType<typeof signal<Focus>>;\n readonly initialFocus: Signal<Focus>;\n\n readonly #lastCloseReason = signal<CloseReason | null>(null);\n readonly lastCloseReason = this.#lastCloseReason.asReadonly();\n\n readonly #triggerEl = signal<HTMLElement | null>(null);\n readonly trigger = this.#triggerEl.asReadonly();\n\n readonly #anchorEl = signal<HTMLElement | null>(null);\n\n /**\n * Element floating-ui anchors the listbox against. Prefers an optional\n * registered anchor, otherwise falls back to the trigger so primitives\n * without an anchor keep their behavior.\n */\n readonly anchor: Signal<ReferenceElement | null>;\n\n readonly #contentEl = signal<HTMLElement | null>(null);\n readonly content = this.#contentEl.asReadonly();\n\n /** All registered options in DOM order. */\n readonly options: Signal<readonly H[]>;\n\n constructor(idGen: IdGenerator, deps: ListboxOverlayControllerDeps<H, Focus, CloseReason>) {\n this.#deps = deps;\n this.#idGen = idGen;\n this.triggerId = signal(this.#idGen.next(`${deps.idPrefix}-trigger`));\n this.contentId = signal(this.#idGen.next(`${deps.idPrefix}-content`));\n this.#initialFocus = signal<Focus>(deps.defaultInitialFocus);\n this.initialFocus = this.#initialFocus.asReadonly();\n this.anchor = computed<ReferenceElement | null>(() => this.#anchorEl() ?? this.#triggerEl());\n this.options = this.#items.items;\n }\n\n setInitialFocus(target: Focus): void {\n this.#initialFocus.set(target);\n }\n\n registerTrigger(el: HTMLElement): void {\n adoptHostId(el, this.triggerId);\n this.#triggerEl.set(el);\n }\n unregisterTrigger(el: HTMLElement): void {\n if (this.#triggerEl() === el) {\n this.#triggerEl.set(null);\n }\n }\n\n registerAnchor(el: HTMLElement): void {\n const current = this.#anchorEl();\n if (current !== null && current !== el) {\n throw new Error(this.#deps.multipleAnchorsError);\n }\n this.#anchorEl.set(el);\n }\n unregisterAnchor(el: HTMLElement): void {\n if (this.#anchorEl() === el) {\n this.#anchorEl.set(null);\n }\n }\n\n registerContent(el: HTMLElement): void {\n adoptHostId(el, this.contentId);\n this.#contentEl.set(el);\n }\n unregisterContent(el: HTMLElement): void {\n if (this.#contentEl() === el) {\n this.#contentEl.set(null);\n }\n }\n\n registerOption(handle: H): void {\n this.#items.register(handle);\n }\n unregisterOption(handle: H): void {\n this.#items.unregister(handle);\n this.#deps.onUnregisterOption?.(handle);\n }\n\n navigate(currentOption: HTMLElement, action: ListNavigationAction, loop: boolean): void {\n if (this.#deps.effectiveDisabled()) {\n return;\n }\n const target = nextEnabledHandle(this.#items.items(), currentOption, action, { loop });\n if (target === null) {\n return;\n }\n target.host.focus();\n this.#deps.onNavigateFocus?.(target);\n }\n\n focusFirstEnabledOption(): boolean {\n const host = firstEnabledHost(this.#items.items());\n if (!host) {\n return false;\n }\n host.focus();\n return true;\n }\n\n focusLastEnabledOption(): boolean {\n const items = this.#items.items();\n for (let i = items.length - 1; i >= 0; i--) {\n const item = items[i];\n if (item && !item.disabled()) {\n item.host.focus();\n return true;\n }\n }\n return false;\n }\n\n toggle(initialFocus: Focus): void {\n if (this.#deps.effectiveDisabled()) {\n return;\n }\n if (this.#deps.isOpen()) {\n this.closeMenu('programmatic' as CloseReason);\n } else {\n this.openMenu(initialFocus);\n }\n }\n\n openMenu(initialFocus: Focus): void {\n if (this.#deps.effectiveDisabled()) {\n return;\n }\n this.#initialFocus.set(initialFocus);\n this.#lastCloseReason.set(null);\n this.#deps.setOpen(true);\n }\n\n closeMenu(reason: CloseReason): void {\n this.#lastCloseReason.set(reason);\n this.#deps.setOpen(false);\n this.#deps.onClose?.(reason);\n }\n\n emitEscapeKeyDown(event: KeyboardEvent, dismissible: boolean, escapeReason: CloseReason): void {\n const vetoed = emitVetoableNativeEvent(this.#deps.emit.escapeKeyDown, event);\n if (!vetoed && dismissible) {\n event.stopPropagation();\n this.#deps.markTouched();\n this.closeMenu(escapeReason);\n }\n }\n\n emitPointerDownOutside(veto: VetoableNativeEvent<PointerEvent>): void {\n this.#deps.emit.pointerDownOutside.emit(veto);\n }\n emitFocusOutside(veto: VetoableNativeEvent<FocusEvent>): void {\n this.#deps.emit.focusOutside.emit(veto);\n }\n emitInteractOutside(veto: VetoableNativeEvent<PointerEvent | FocusEvent>): void {\n this.#deps.emit.interactOutside.emit(veto);\n }\n\n forwardEscapeKeyDown(veto: VetoableNativeEvent<KeyboardEvent>): void {\n this.#deps.emit.escapeKeyDown.emit(veto);\n }\n\n requestClose(reason: CloseReason): void {\n this.#deps.markTouched();\n this.closeMenu(reason);\n }\n\n emitAutoFocusOnOpen(): boolean {\n return emitVetoableEvent(this.#deps.emit.autoFocusOnOpen);\n }\n\n emitAutoFocusOnClose(): boolean {\n return emitVetoableEvent(this.#deps.emit.autoFocusOnClose);\n }\n\n /** Focus the trigger, e.g. on a Tab commit before the content unmounts. */\n focusTrigger(): void {\n this.#triggerEl()?.focus();\n }\n}\n","import {\n Directive,\n ElementRef,\n booleanAttribute,\n computed,\n inject,\n input,\n signal,\n} from '@angular/core';\n\n/**\n * The \"visually hidden\" clip rectangle: an inline style declaration that\n * removes an element from the visual layout while keeping it in the\n * accessibility tree (unlike `display:none` / `visibility:hidden`, which both\n * also drop it from the a11y tree). Shared by {@link ForVisuallyHidden} and the\n * `LiveAnnouncer` so the clip CSS is defined in exactly one place.\n */\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 * Internal — not re-exported from `public-api.ts`.\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 { VISUALLY_HIDDEN_STYLE } from '../visually-hidden/visually-hidden';\n\ntype Politeness = 'polite' | 'assertive';\n\n/**\n * Tiny ARIA live-region helper. Lazily injects two off-screen regions\n * (`polite` and `assertive`) into `document.body` the first time it is used,\n * then writes / clears messages on demand.\n *\n * Sequential identical announcements are flushed through a deferred write\n * (`setTimeout(…, 0)`) so the region is briefly emptied — without that, screen\n * readers ignore repeated text that hasn't actually changed. A macrotask (not a\n * microtask) is used deliberately: many screen readers (NVDA, VoiceOver) miss\n * the clear→repopulate cycle on repeat messages when both writes land in the\n * same microtask drain, because the empty state never reaches the\n * accessibility tree between them. Each write carries a generation token, so a\n * superseding `announce()` or a `clear()` cancels the prior pending write\n * before it can paint a stale message.\n *\n * The regions are detached again when the service's injector is destroyed\n * (one bootstrap per SSR request, or `TestBed.resetTestingModule()`), so a\n * torn-down application leaves no orphaned `[aria-live]` nodes behind. DOM\n * access is gated on `isPlatformBrowser`, so `announce()` / `clear()` are\n * 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, HTMLElement>();\n #generation = 0;\n\n constructor() {\n inject(DestroyRef).onDestroy(() => {\n for (const region of this.#regions.values()) {\n region.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 * Pass an empty string (or call `clear()`) to silence pending announcements.\n * 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.#getRegion(politeness);\n // Reset first so identical consecutive messages still trigger the reader.\n region.textContent = '';\n // Bump the generation so a superseding announce (or a clear) cancels this\n // pending write before it paints.\n const generation = ++this.#generation;\n setTimeout(() => {\n if (generation !== this.#generation) {\n return;\n }\n region.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 this.#generation++;\n for (const region of this.#regions.values()) {\n region.textContent = '';\n }\n }\n\n #getRegion(politeness: Politeness): HTMLElement {\n let region = this.#regions.get(politeness);\n if (region) {\n return region;\n }\n region = this.#document.createElement('div');\n region.setAttribute('aria-live', politeness);\n region.setAttribute('aria-atomic', 'true');\n region.setAttribute('role', politeness === 'assertive' ? 'alert' : 'status');\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, region);\n return region;\n }\n}\n","/** Group / decimal separators for a locale, as derived from `Intl`. */\nexport interface LocaleSeparators {\n /** The locale grouping (thousands) separator. */\n readonly group: string;\n /** The locale decimal separator. */\n readonly decimal: string;\n}\n\n/** Escapes a string for safe interpolation into a `RegExp` source. */\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * The space variants a locale may emit as a group separator, or that a user\n * may type in their place: ASCII space (U+0020), no-break space (U+00A0),\n * narrow no-break space (U+202F, fr-FR), and thin space (U+2009). Normalized to\n * the locale's canonical group separator before grouping validation so a\n * user-typed ASCII space still parses against an NBSP-emitting locale.\n */\nconst SPACE_GROUP_VARIANTS = /[ ]/g;\n\n/** Whether `separator` is one of the whitespace group-separator variants. */\nfunction isSpaceSeparator(separator: string): boolean {\n return /^[ ]$/.test(separator);\n}\n\n/**\n * Group / decimal separators for a given locale, derived once via `Intl`.\n * Falls back to `,` group / `.` decimal for an unknown or undefined locale.\n */\nexport function localeSeparators(locale: string | undefined): LocaleSeparators {\n let group = ',';\n let decimal = '.';\n for (const part of new Intl.NumberFormat(locale).formatToParts(11111.1)) {\n if (part.type === 'group') {\n group = part.value;\n } else if (part.type === 'decimal') {\n decimal = part.value;\n }\n }\n return { group, decimal };\n}\n\n/**\n * Parse locale-formatted numeric `text` into a number, or `null` when it is not\n * a valid plain decimal for the given `separators`. The locale decimal separator\n * is normalized to `.`, group separators are validated for placement then\n * stripped, and the canonical form is validated against a strict numeric regex\n * (optional sign + digits + a single optional decimal) before `Number()`.\n *\n * Grouping placement is strict: a group separator may appear only in the\n * integer part and only at 3-digit boundaries, so a correctly grouped\n * `\"1,234,567\"` parses while a misgrouped `\"1,2,3\"` is rejected (`null`)\n * rather than silently collapsing to `123`.\n *\n * For locales that group with a space (the NBSP / NNBSP fr-style locales),\n * whitespace-space variants — including the plain ASCII space a user is most\n * likely to type — are normalized to the locale's canonical separator first,\n * so a correctly-spaced number parses regardless of which space was typed.\n *\n * Exponent notation is intentionally rejected — `2e3` is not valid spinbutton\n * input and silently parsing it to `2000` is surprising. So are malformed forms\n * such as multiple signs (`+-5`) or multiple decimals (`1.2.3`); all map to\n * `null`, the same outcome callers already treat as \"keep the last valid value\".\n */\nexport function parseLocaleNumber(text: string, separators: LocaleSeparators): number | null {\n const { group, decimal } = separators;\n // When the locale groups with a space (NBSP / NNBSP in fr-style locales),\n // normalize every whitespace-space variant the user might type — including a\n // plain ASCII space — to the canonical separator, so grouping validation\n // doesn't reject a correctly-spaced number just because the typed space\n // differs from the one `Intl` emits.\n const input = isSpaceSeparator(group) ? text.replace(SPACE_GROUP_VARIANTS, group) : text;\n // Strip currency symbols, percent signs, and any other non-numeric noise\n // the locale may include, leaving digits, sign, the locale group/decimal\n // separators, and the exponent letters — the strict gates below reject\n // exponent notation, so stripping `eE` here would let `2e3` slip through\n // as `23` instead of being seen (and refused) as malformed.\n const noise = new RegExp(`[^\\\\d${escapeRegExp(group)}${escapeRegExp(decimal)}eE+-]`, 'g');\n const cleaned = input.trim().replace(noise, '');\n if (cleaned.includes(group) && !groupingIsValid(cleaned, group, decimal)) {\n return null;\n }\n let normalized = cleaned.split(group).join('');\n if (decimal !== '.') {\n normalized = normalized.split(decimal).join('.');\n }\n if (!/^[+-]?\\d+(?:\\.\\d+)?$/.test(normalized)) {\n return null;\n }\n const parsed = Number(normalized);\n return Number.isFinite(parsed) ? parsed : null;\n}\n\n/**\n * Validates that every group separator in `cleaned` sits at a legal 3-digit\n * boundary within the integer part (none in the fractional part). Permits a\n * leading sign and a shorter leading group (`1,234` / `12,345` / `123,456`).\n */\nfunction groupingIsValid(cleaned: string, group: string, decimal: string): boolean {\n const integerPart = cleaned.split(decimal)[0] ?? '';\n const sign = /^[+-]/.test(integerPart) ? integerPart[0]! : '';\n const digitsWithGroups = sign ? integerPart.slice(1) : integerPart;\n const g = escapeRegExp(group);\n return new RegExp(`^\\\\d{1,3}(?:${g}\\\\d{3})+$`).test(digitsWithGroups);\n}\n","import { inject, InjectionToken, type Signal } from '@angular/core';\nimport type { ReferenceElement } from '@floating-ui/dom';\n\nimport type { CollectionHandle } from '../collection/collection';\nimport type { FloatingAlign, FloatingSide } from '../floating/floating';\nimport type { MenuActivationModality } from './menu-overlay';\nimport type {\n ListNavigationAction,\n WritingDirection,\n} from '../keyboard-navigation/keyboard-navigation';\nimport type { Point } from '../pointer-grace/pointer-grace';\nimport type { VetoableNativeEvent } from '../vetoable-event/vetoable-event';\n\n/**\n * Minimal upward contract a menu uses to move between sibling menus of an\n * enclosing menubar. Implemented by the menubar root; keeps the generic menu\n * layer free of any concrete-root import.\n */\nexport interface MenuSiblingNavigator {\n /** Move focus/open to the previous or next sibling menu. */\n switchToSibling(direction: 'next' | 'prev'): void;\n}\n\n/**\n * Why a menu requested close. Enumerates the close reasons without the\n * focus-routing decision baked in. `'programmatic'` also\n * covers the user-initiated trigger toggle-close (clicking an open menu's\n * trigger): the toggle path reuses this reason by design rather than\n * exposing a distinct `'trigger'` reason.\n */\nexport type ForMenuCloseReason =\n | 'escape'\n | 'pointerDownOutside'\n | 'focusOutside'\n | 'select'\n | 'tab'\n | 'programmatic';\n\n/**\n * Handle every item type (`menuitem`, `menuitemcheckbox`, `menuitemradio`)\n * registers with the parent menu. The collection orders them by DOM\n * position so groups, separators, and `@for` loops don't affect navigation.\n *\n * `textValue`, when present and non-empty, overrides `host.textContent` for\n * typeahead matching — useful when the item's DOM contains icons, kbd\n * shortcuts, badges, or SVG titles that would otherwise bleed into the\n * match string. Empty / unset means \"fall back to the host's text content\".\n */\nexport interface ForMenuItemHandle extends CollectionHandle {\n readonly disabled: Signal<boolean>;\n readonly textValue?: Signal<string>;\n /**\n * Tells the item that the next focus it receives is a programmatic move\n * that must not reflect `data-highlighted` (the initial focus of a\n * pointer-driven open). One-shot: the item consumes the suppression on its\n * next `focus` event. Optional — items that don't reflect a highlight\n * (e.g. `[forMenuSubTrigger]`) simply omit it.\n */\n suppressHighlightOnNextFocus?(): void;\n /**\n * Drops the item's `data-highlighted` without moving DOM focus. The menu\n * surface calls this on `pointerleave` so the hover highlight stops once the\n * pointer leaves, while keyboard navigation stays anchored on the item.\n * Optional — items that don't reflect a highlight (e.g.\n * `[forMenuSubTrigger]`) simply omit it.\n */\n clearHighlight?(): void;\n}\n\n/**\n * Coordination contract owned by the root that opens the menu —\n * `[forDropdownMenu]` (button trigger) or `[forContextMenu]`\n * (right-click / `Shift+F10`). Items, content, separators, etc. inject\n * this contract so they don't depend on a specific root flavor.\n */\nexport interface ForMenuContext {\n /**\n * Whether the menu is currently shown. Read-only at the contract level —\n * concrete roots (`[forDropdownMenu]`, `[forContextMenu]`, `[forMenuSub]`)\n * back this with their own `model<boolean>` and write through their own\n * `openMenu` / `closeMenu` plumbing. Pieces consuming this contract\n * (`[forMenuContent]`, the trigger directives) only ever read.\n */\n readonly open: Signal<boolean>;\n readonly disabled: Signal<boolean>;\n readonly dismissible: Signal<boolean>;\n readonly returnFocus: Signal<boolean>;\n /**\n * Writing direction. Drives ArrowLeft / ArrowRight semantics on submenu\n * triggers and items, and the default `side` of submenus (`'right'` in\n * LTR, `'left'` in RTL). On `[forMenuSub]` defaults to the parent menu's\n * `dir` and can be overridden per-submenu.\n */\n readonly dir: Signal<WritingDirection>;\n readonly side: Signal<FloatingSide | undefined>;\n readonly align: Signal<FloatingAlign | undefined>;\n readonly sideOffset: Signal<number>;\n readonly alignOffset: Signal<number>;\n readonly avoidCollisions: Signal<boolean>;\n readonly collisionPadding: Signal<number>;\n readonly arrowPadding: Signal<number>;\n readonly sticky: Signal<'partial' | 'always' | false>;\n readonly hideWhenDetached: Signal<boolean>;\n readonly clipUntilPositioned: Signal<boolean>;\n readonly loop: Signal<boolean>;\n\n /** Where focus should land after the menu mounts. Set by triggers before flipping `open`. */\n readonly initialFocus: Signal<'first' | 'last'>;\n setInitialFocus(target: 'first' | 'last'): void;\n\n readonly triggerId: Signal<string>;\n readonly contentId: Signal<string>;\n readonly ariaLabel: Signal<string | null>;\n\n /** Anchor passed to floating-ui — `HTMLElement` (Dropdown) or `VirtualElement` (Context). */\n readonly anchor: Signal<ReferenceElement | null>;\n\n /** The focusable element that receives focus on close (the trigger button or right-click target). */\n readonly trigger: Signal<HTMLElement | null>;\n registerTrigger(el: HTMLElement): void;\n unregisterTrigger(el: HTMLElement): void;\n\n /** The mounted `[forMenuContent]` element. Submenus exempt their parent's content. */\n readonly content: Signal<HTMLElement | null>;\n registerContent(el: HTMLElement): void;\n unregisterContent(el: HTMLElement): void;\n\n /**\n * The enclosing menu, when this context is a `[forMenuSub]`. `null` for\n * top-level roots (`[forDropdownMenu]`, `[forContextMenu]`, and the\n * `[forMenubar]`-flavored ctx). Items use it to route ArrowLeft /\n * item-activation upward.\n */\n readonly parentMenu: ForMenuContext | null;\n\n /**\n * The enclosing menubar, when this context is the top-level menu of a\n * `[forMenubar]`. `null` otherwise. `[forMenuItem]` and `[forMenuContent]`\n * route ArrowLeft / ArrowRight up to it for cross-menu navigation when\n * there's no parent submenu. Typed as the minimal `MenuSiblingNavigator`\n * so the generic menu layer stays free of any concrete-root import.\n */\n readonly menubar?: MenuSiblingNavigator | null;\n\n /**\n * Elements treated as \"inside\" by the dismissable layer. DropdownMenu\n * exempts the trigger button (clicks on it toggle via the trigger\n * directive — without exemption they'd also fire pointer-down-outside\n * and double-close). ContextMenu exempts nothing — a left-click on the\n * region while the menu is open should close it.\n */\n readonly dismissableExemptions: Signal<readonly HTMLElement[]>;\n\n registerItem(handle: ForMenuItemHandle): void;\n unregisterItem(handle: ForMenuItemHandle): void;\n\n /** Move focus inside the menu in response to an arrow / Home / End key. */\n navigate(currentItem: HTMLElement, action: ListNavigationAction): void;\n /** Prefix-match against item text content and focus the first match. */\n handleTypeahead(event: KeyboardEvent): void;\n /**\n * Clear `data-highlighted` from every item without moving focus. Called by\n * `[forMenuContent]` on `pointerleave` so the hover highlight follows the\n * pointer off the surface (hover-follows-pointer).\n */\n clearItemHighlights(): void;\n /** Returns `true` if focus moved; `false` when no enabled items exist. */\n focusFirstEnabledItem(): boolean;\n focusLastEnabledItem(): boolean;\n\n /**\n * Trigger entry points — toggle/open honour `disabled`. `modality`\n * (default `'keyboard'`) records how the open was activated: a `'pointer'`\n * open keeps the programmatic initial focus from reflecting\n * `data-highlighted` on the focused item, while a `'keyboard'` open\n * highlights it per the APG menu-button pattern. The DOM focus move itself\n * is identical in both modalities.\n */\n toggle(initialFocus?: 'first' | 'last', modality?: MenuActivationModality): void;\n openMenu(initialFocus?: 'first' | 'last', modality?: MenuActivationModality): void;\n closeMenu(reason: ForMenuCloseReason): void;\n\n /**\n * Reason of the most recent close, or `null` while the menu is open / has\n * never closed. Reset to `null` on every open. `[forMenuContent]` reads it\n * to skip its return-focus when the close was a `'tab'` — letting Tab move\n * focus out of the menu (per WAI-ARIA APG) instead of snapping it back to\n * the trigger.\n */\n readonly lastCloseReason: Signal<ForMenuCloseReason | null>;\n\n /**\n * Abort a pending pointer-driven (hover) close on this menu, if one is\n * scheduled. A descendant submenu walks up the `parentMenu` chain calling\n * this so the whole open chain stays alive while the pointer travels\n * between levels. Optional — only `[forMenuSub]` schedules hover-closes, so\n * top-level roots (Dropdown / Context / Menubar) need not implement it.\n */\n cancelPendingClose?(): void;\n\n /**\n * Schedule a pointer-driven (hover) open of this menu. Optional — only\n * `[forMenuSub]` opens on hover; top-level roots open on click / right-click.\n * The sub-trigger calls it on `pointerenter` via optional chaining.\n */\n scheduleOpenByPointer?(): void;\n\n /**\n * The pointer left this menu's trigger (client coordinates of the leave).\n * Optional — only `[forMenuSub]` reacts, arming the pointer-grace \"safe\n * triangle\" toward its content. The sub-trigger calls it on `pointerleave`.\n */\n onTriggerPointerLeave?(cursor: Point): void;\n\n /**\n * Escape is consumer-owned (its close emits `(escapeKeyDown)`, stops\n * propagation, and closes with reason `'escape'`); Content forwards the raw\n * `KeyboardEvent`.\n */\n emitEscapeKeyDown(event: KeyboardEvent): void;\n /**\n * Outside-interaction emit forwarders. `injectOverlayShell` builds and\n * reuses one `VetoableNativeEvent` across the specific and composite\n * channels, then hands it to these forwarders to fire the matching output\n * and calls `requestClose` when un-vetoed.\n */\n emitPointerDownOutside(veto: VetoableNativeEvent<PointerEvent>): void;\n emitFocusOutside(veto: VetoableNativeEvent<FocusEvent>): void;\n emitInteractOutside(veto: VetoableNativeEvent<PointerEvent | FocusEvent>): void;\n /** Implicit close requested by the shell after an un-vetoed outside interaction. */\n requestClose(reason: 'pointerDownOutside' | 'focusOutside'): void;\n\n /**\n * Hooks into the auto-focus pipeline. Content fires these just before\n * its imperative `.focus()` (open) or the trigger return-focus (close);\n * `event.preventDefault()` skips the move. Returns `true` when the\n * consumer vetoed.\n */\n emitAutoFocusOnOpen(): boolean;\n emitAutoFocusOnClose(): boolean;\n}\n\nexport type { MenuActivationModality };\n\nexport const FOR_MENU_CONTEXT = new InjectionToken<ForMenuContext>('FOR_MENU_CONTEXT');\n\nexport function injectMenuContext(piece: string): ForMenuContext {\n const ctx = inject(FOR_MENU_CONTEXT, { optional: true });\n if (!ctx) {\n throw new Error(\n `[forty-cdk/menu] ${piece} must be used inside a [forDropdownMenu], [forContextMenu], [forMenubar], or [forMenuSub] element. ` +\n \"If it is declared inside an ng-template, DI resolves at the template's declaration site — \" +\n 'not where it is stamped (e.g. via ngTemplateOutlet) — so declare the template inside the menu root.',\n );\n }\n return ctx;\n}\n","import { type Signal, signal } from '@angular/core';\n\n/**\n * Tracks where a menu's initial focus should land on the next open and whether\n * that one programmatic move should reflect `data-highlighted` on the focused\n * item.\n *\n * `target` is set by triggers before they flip the menu open (ArrowDown →\n * `'first'`, ArrowUp → `'last'`). `highlightOnNextFocus` is armed per open via\n * {@link prepareOpen}: a `'keyboard'` activation highlights the focused item per\n * the APG menu-button pattern; a `'pointer'` activation (click, hover-after-open)\n * suppresses the highlight so a mouse-opened menu doesn't read as \"preselected\".\n * {@link consumeHighlight} reads the flag once and re-arms it to `true`, so the\n * suppression applies only to the single initial-focus move that follows an open.\n *\n * Plain class (no `inject()`) so both `MenuOverlay` and `[forMenubar]`'s\n * multiplexed menu context compose the same one-shot protocol instead of each\n * hand-copying it.\n */\nexport class InitialFocusState {\n readonly #target = signal<'first' | 'last'>('first');\n #highlightOnNextFocus = true;\n\n /** Where focus should land when the menu mounts. */\n readonly target: Signal<'first' | 'last'> = this.#target.asReadonly();\n\n setTarget(target: 'first' | 'last'): void {\n this.#target.set(target);\n }\n\n /**\n * Arms the state for the next open: records the initial-focus target and\n * whether the upcoming initial-focus move should highlight the focused item\n * (`true` for keyboard activation, `false` for pointer activation).\n */\n prepareOpen(target: 'first' | 'last', highlight: boolean): void {\n this.#target.set(target);\n this.#highlightOnNextFocus = highlight;\n }\n\n /**\n * Returns whether the next initial-focus move should highlight, then re-arms\n * the flag to `true` so the suppression is one-shot.\n */\n consumeHighlight(): boolean {\n const highlight = this.#highlightOnNextFocus;\n this.#highlightOnNextFocus = true;\n return highlight;\n }\n}\n\n/**\n * Records the reason of a menu's most recent close. Reset to `null` on every\n * open; the shared `[forMenuContent]` reads it to skip its return-focus on a\n * `'tab'` close (so Tab advances focus out of the menu instead of snapping back\n * to the trigger).\n *\n * Generic over the reason union so `MenuOverlay` (`MenuOverlayCloseReason`) and\n * `[forMenubar]`'s menu context (`ForMenuCloseReason`) — structurally identical\n * unions — share one implementation. Plain class (no `inject()`) so both compose\n * it instead of each hand-copying the signal.\n */\nexport class CloseReasonState<R extends string> {\n readonly #reason = signal<R | null>(null);\n\n /**\n * Reason of the most recent close, or `null` while the menu is open / has\n * never closed.\n */\n readonly reason: Signal<R | null> = this.#reason.asReadonly();\n\n set(reason: R): void {\n this.#reason.set(reason);\n }\n\n reset(): void {\n this.#reason.set(null);\n }\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.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 Signal } from '@angular/core';\n\nimport { Collection, type CollectionHandle } from '../collection/collection';\nimport { type ListNavigationAction } from '../keyboard-navigation/keyboard-navigation';\nimport { nextEnabledHandle } from '../keyboard-navigation/move-in-collection';\nimport { injectTypeahead, type Typeahead } from '../typeahead/typeahead';\n\n/**\n * Item handle the list's `Collection` registers. Structurally compatible\n * with primitives' `ForMenuItemHandle` — typing is generic so the unit\n * stays orthogonal to `_internal/menu-overlay/menu-context.ts` (no cycle into a primitive).\n */\nexport interface MenuItemHandle extends CollectionHandle {\n readonly disabled: Signal<boolean>;\n readonly textValue?: Signal<string>;\n /**\n * Tells the item that the next focus it receives is a programmatic move\n * that must not reflect `data-highlighted` (the initial focus of a\n * pointer-driven open). One-shot: the item consumes the suppression on its\n * next `focus` event. Optional — items that don't reflect a highlight\n * (e.g. `[forMenuSubTrigger]`) simply omit it.\n */\n suppressHighlightOnNextFocus?(): void;\n /**\n * Drops the item's `data-highlighted` without moving DOM focus. Called when\n * the pointer leaves the menu surface so the hovered item stops reading as\n * the active candidate while keyboard navigation stays anchored on it.\n * Optional — items that don't reflect a highlight omit it.\n */\n clearHighlight?(): void;\n}\n\n/**\n * The keyboard-focus mechanics shared by every menu surface that holds a\n * vertical list of `menuitem`s: the item `Collection`, a typeahead buffer,\n * arrow / Home / End navigation, prefix-match typeahead, and the\n * first/last-enabled focus moves used on mount.\n *\n * Both `MenuOverlay` (for `[forDropdownMenu]` / `[forContextMenu]` /\n * `[forMenuSub]`) and `[forMenubar]`'s multiplexed menu context delegate to\n * this unit, so the verbatim navigate / typeahead / focus copies that used\n * to live in each don't drift.\n *\n * `loop` is read through an accessor so the owner can forward its own\n * reactive `loop` input without the unit depending on a specific source.\n *\n * Construct via `createMenuItemList` from a directive / helper field\n * initializer so the `injectTypeahead()` `DestroyRef` hookup resolves\n * through the surrounding injector.\n */\nexport class MenuItemList<H extends MenuItemHandle = MenuItemHandle> {\n readonly #items = new Collection<H>();\n readonly #typeahead: Typeahead;\n readonly #loop: () => boolean;\n\n constructor(loop: () => boolean, typeahead: Typeahead) {\n this.#loop = loop;\n this.#typeahead = typeahead;\n }\n\n registerItem(handle: H): void {\n this.#items.register(handle);\n }\n\n unregisterItem(handle: H): void {\n this.#items.unregister(handle);\n }\n\n /** Items registered with the menu, in DOM order. Exposed for tests / sub-menu wiring. */\n items(): readonly H[] {\n return this.#items.items();\n }\n\n navigate(currentItem: HTMLElement, action: ListNavigationAction): void {\n const target = nextEnabledHandle(this.#items.items(), currentItem, action, {\n loop: this.#loop(),\n });\n target?.host.focus();\n }\n\n handleTypeahead(event: KeyboardEvent): void {\n if (!this.#typeahead.handle(event)) {\n return;\n }\n const buffer = this.#typeahead.buffer().toLowerCase();\n if (!buffer) {\n return;\n }\n const items = this.#items.items();\n if (items.length === 0) {\n return;\n }\n\n const cycle = this.#typeahead.isRepeatedChar();\n const query = cycle ? buffer[0]! : buffer;\n const currentIndex = items.findIndex((i) => i.host === event.target);\n // Single-character typeahead cycles: each (re-)press of one key steps to the\n // next same-initial item after the current focus and wraps around (APG menu\n // typeahead). A distinct multi-character prefix re-anchors on the current\n // focus (inclusive) so a growing prefix keeps the current item when it still\n // matches; both fall back to the top when nothing is focused.\n const anchor = currentIndex >= 0 ? currentIndex : -1;\n const start = cycle ? anchor + 1 : Math.max(anchor, 0);\n\n for (let offset = 0; offset < items.length; offset++) {\n const item = items[(start + offset) % items.length]!;\n if (item.disabled()) {\n continue;\n }\n const override = item.textValue?.() ?? '';\n const source = override !== '' ? override : (item.host.textContent ?? '');\n if (source.trim().toLowerCase().startsWith(query)) {\n item.host.focus();\n return;\n }\n }\n }\n\n /**\n * Focuses the first enabled item. Pass `highlight: false` when the move is\n * the programmatic initial focus of a pointer-driven open, so the item\n * receives DOM focus without reflecting `data-highlighted`.\n */\n focusFirstEnabledItem(highlight = true): boolean {\n const target = this.#items.items().find((i) => !i.disabled());\n if (!target) {\n return false;\n }\n this.#focusItem(target, highlight);\n return true;\n }\n\n /**\n * Focuses the last enabled item. Pass `highlight: false` when the move is\n * the programmatic initial focus of a pointer-driven open, so the item\n * receives DOM focus without reflecting `data-highlighted`.\n */\n focusLastEnabledItem(highlight = true): boolean {\n const items = this.#items.items();\n for (let i = items.length - 1; i >= 0; i--) {\n const item = items[i];\n if (item && !item.disabled()) {\n this.#focusItem(item, highlight);\n return true;\n }\n }\n return false;\n }\n\n #focusItem(item: H, highlight: boolean): void {\n if (!highlight) {\n item.suppressHighlightOnNextFocus?.();\n }\n item.host.focus();\n }\n\n /**\n * Drops `data-highlighted` from every registered item without touching DOM\n * focus. Used when the pointer leaves the menu surface so no item keeps\n * reading as the active candidate.\n */\n clearHighlights(): void {\n for (const item of this.#items.items()) {\n item.clearHighlight?.();\n }\n }\n}\n\n/**\n * Creates a `MenuItemList` from a directive / helper field initializer.\n * `loop` is the owner's reactive loop accessor; the typeahead instance is\n * created with `injectTypeahead()` so its debounce timer is torn down with\n * the surrounding `DestroyRef`.\n */\nexport function createMenuItemList<H extends MenuItemHandle = MenuItemHandle>(\n loop: () => boolean,\n): MenuItemList<H> {\n return new MenuItemList<H>(loop, injectTypeahead());\n}\n","import {\n inject,\n type ModelSignal,\n type OutputEmitterRef,\n type Signal,\n signal,\n type WritableSignal,\n} from '@angular/core';\n\nimport { adoptHostId } from '../host-id/host-id';\nimport { IdGenerator } from '../id-generator/id-generator';\nimport type { ListNavigationAction } from '../keyboard-navigation/keyboard-navigation';\nimport {\n emitVetoableEvent,\n emitVetoableNativeEvent,\n type VetoableEvent,\n type VetoableNativeEvent,\n} from '../vetoable-event/vetoable-event';\nimport { CloseReasonState, InitialFocusState } from './menu-focus-state';\nimport { createMenuItemList, type MenuItemHandle, type MenuItemList } from './menu-item-list';\n\n/**\n * Reason a menu requested close. Mirrors `ForMenuCloseReason` from\n * `_internal/menu-overlay/menu-context.ts` structurally so primitives can pass either type\n * across the helper boundary without re-declaration.\n */\nexport type MenuOverlayCloseReason =\n | 'escape'\n | 'pointerDownOutside'\n | 'focusOutside'\n | 'select'\n | 'tab'\n | 'programmatic';\n\n/**\n * Item handle the helper's item list registers. Re-exported alias of the\n * shared `MenuItemHandle` — structurally compatible with primitives'\n * `ForMenuItemHandle` and kept under this name for backward compatibility\n * with the helper's existing consumers / specs.\n */\nexport type MenuOverlayItemHandle = MenuItemHandle;\n\n/**\n * How a menu open was activated. `'keyboard'` (the default) highlights the\n * initially focused item per the APG menu-button pattern; `'pointer'` keeps\n * the programmatic initial focus from reflecting `data-highlighted` so a\n * mouse-opened menu doesn't read as \"preselected\". The DOM focus move itself\n * is identical in both modalities.\n */\nexport type MenuActivationModality = 'pointer' | 'keyboard';\n\n/**\n * Wiring the directive forwards into the helper. Inputs / outputs / models\n * stay declared on the directive (Angular needs them as fields for template\n * binding); the helper reads them through these references so the close\n * decisions, navigation, and veto plumbing live in one place.\n */\nexport interface MenuOverlayHooks {\n readonly open: ModelSignal<boolean>;\n readonly disabled: Signal<boolean>;\n readonly dismissible: Signal<boolean>;\n readonly loop: Signal<boolean>;\n readonly escapeKeyDown: OutputEmitterRef<VetoableNativeEvent<KeyboardEvent>>;\n readonly pointerDownOutside: OutputEmitterRef<VetoableNativeEvent<PointerEvent>>;\n readonly focusOutside: OutputEmitterRef<VetoableNativeEvent<FocusEvent>>;\n readonly interactOutside: OutputEmitterRef<VetoableNativeEvent<PointerEvent | FocusEvent>>;\n readonly autoFocusOnOpen: OutputEmitterRef<VetoableEvent>;\n readonly autoFocusOnClose: OutputEmitterRef<VetoableEvent>;\n\n /**\n * Optional side effect run after `openMenu` flips `open` to `true`,\n * receiving the resolved initial-focus target. `[forMenuSub]` uses it to\n * cancel in-flight hover scheduling and reset its focus-suppression flag\n * (a keyboard / click open supersedes hover). Top-level roots\n * (`[forDropdownMenu]` / `[forContextMenu]`) pass neither hook.\n */\n readonly onOpen?: (initialFocus: 'first' | 'last') => void;\n\n /**\n * Optional side effect run after `closeMenu` flips `open` to `false`,\n * receiving the close reason. `[forMenuSub]` uses it to cancel in-flight\n * hover scheduling, reset its focus-suppression flag, and propagate the\n * close upward through the menu chain for every reason except `'escape'`\n * / `'programmatic'`. Top-level roots pass neither hook.\n */\n readonly onClose?: (reason: MenuOverlayCloseReason) => void;\n}\n\n/**\n * Shared coordination behaviour between `ForDropdownMenu` and `ForContextMenu`\n * (and any future menu overlay root with the same item-collection / typeahead /\n * navigate / dismissable shape — Menubar's per-bar menu, a future free-floating\n * SubMenu).\n *\n * The helper owns:\n *\n * - id generation for trigger / content,\n * - the item list (`MenuItemList`: the item `Collection` + typeahead +\n * `navigate` / `handleTypeahead` / `focusFirst/LastEnabledItem`), shared\n * with `[forMenubar]`'s multiplexed menu context,\n * - trigger / content / initial-focus signals,\n * - `toggle` / `openMenu` / `closeMenu` (honouring `disabled`),\n * - the consumer-owned Escape close (`emitEscapeKeyDown`) and the\n * `requestClose` the shell invokes after an un-vetoed outside interaction.\n * The shared `#pendingOutsideVeto` reuse between the specific outside\n * listeners and the composite `interactOutside` lives in\n * `injectOverlayShell`, not here,\n * - the `(autoFocusOnOpen)` / `(autoFocusOnClose)` veto pass-throughs.\n *\n * It deliberately does NOT own:\n *\n * - the `anchor` signal — DropdownMenu derives it from the trigger element,\n * ContextMenu drives it via a `VirtualElement`,\n * - `dismissableExemptions` — DropdownMenu exempts the trigger button so the\n * trigger's click toggle doesn't double-fire as a pointer-down-outside;\n * ContextMenu exempts nothing,\n * - the `input()` / `output()` / `model()` declarations — they remain on the\n * directive class because Angular's template binding system reads inputs /\n * outputs off the directive's compiled metadata.\n *\n * Class form (rather than a function-based factory) is deliberate: the\n * helper has private mutable state (the trigger / content signals, the\n * initial-focus signal) that maps cleanly to instance fields, and the\n * directives read several of its fields back through getter\n * forwarding. Encapsulating that as a class keeps the directive's surface\n * obvious at the call site and matches the Angular idiom for cross-cutting\n * mutable state co-located with DI.\n *\n * Construct via `createMenuOverlay` from a directive's field initializer so\n * the helper's `inject()` calls (id generator, typeahead destroyRef hookup)\n * resolve through the directive's injector.\n */\nexport class MenuOverlay<H extends MenuOverlayItemHandle = MenuOverlayItemHandle> {\n readonly #idGen = inject(IdGenerator);\n readonly #itemList: MenuItemList<H>;\n readonly #hooks: MenuOverlayHooks;\n\n readonly #triggerId: WritableSignal<string>;\n readonly #contentId: WritableSignal<string>;\n\n /** Unique id for the trigger element. Stable across the menu's lifetime. */\n readonly triggerId: Signal<string>;\n\n /** Unique id for the content element. Stable across the menu's lifetime. */\n readonly contentId: Signal<string>;\n\n readonly #initialFocusState = new InitialFocusState();\n\n /** Where focus should land when the menu mounts. Set by triggers before flipping `open`. */\n readonly initialFocus = this.#initialFocusState.target;\n\n readonly #closeReasonState = new CloseReasonState<MenuOverlayCloseReason>();\n\n /**\n * Reason of the most recent close, or `null` while the menu is open / has\n * never closed. Reset to `null` on every open. The shared `[forMenuContent]`\n * reads this to skip its return-focus on `'tab'` so Tab can advance focus\n * out of the menu instead of snapping back to the trigger.\n */\n readonly lastCloseReason = this.#closeReasonState.reason;\n\n readonly #triggerEl = signal<HTMLElement | null>(null);\n\n /** The focusable element the menu should return focus to on close. */\n readonly trigger = this.#triggerEl.asReadonly();\n\n readonly #contentEl = signal<HTMLElement | null>(null);\n\n /** The mounted `[forMenuContent]` element, or `null` while the menu is closed. */\n readonly content = this.#contentEl.asReadonly();\n\n constructor(idPrefix: string, hooks: MenuOverlayHooks) {\n this.#hooks = hooks;\n this.#itemList = createMenuItemList<H>(() => hooks.loop());\n this.#triggerId = signal(this.#idGen.next(`${idPrefix}-trigger`));\n this.#contentId = signal(this.#idGen.next(`${idPrefix}-content`));\n this.triggerId = this.#triggerId.asReadonly();\n this.contentId = this.#contentId.asReadonly();\n }\n\n setInitialFocus(target: 'first' | 'last'): void {\n this.#initialFocusState.setTarget(target);\n }\n\n registerTrigger(el: HTMLElement): void {\n adoptHostId(el, this.#triggerId);\n this.#triggerEl.set(el);\n }\n\n unregisterTrigger(el: HTMLElement): void {\n if (this.#triggerEl() === el) {\n this.#triggerEl.set(null);\n }\n }\n\n registerContent(el: HTMLElement): void {\n adoptHostId(el, this.#contentId);\n this.#contentEl.set(el);\n }\n\n unregisterContent(el: HTMLElement): void {\n if (this.#contentEl() === el) {\n this.#contentEl.set(null);\n }\n }\n\n registerItem(handle: H): void {\n this.#itemList.registerItem(handle);\n }\n\n unregisterItem(handle: H): void {\n this.#itemList.unregisterItem(handle);\n }\n\n /** Items registered with the menu, in DOM order. Exposed for tests / sub-menu wiring. */\n items(): readonly H[] {\n return this.#itemList.items();\n }\n\n navigate(currentItem: HTMLElement, action: ListNavigationAction): void {\n this.#itemList.navigate(currentItem, action);\n }\n\n handleTypeahead(event: KeyboardEvent): void {\n this.#itemList.handleTypeahead(event);\n }\n\n /**\n * Clears `data-highlighted` from every item without moving focus. The shared\n * `[forMenuContent]` calls this on `pointerleave` so the hover highlight\n * follows the pointer off the surface.\n */\n clearItemHighlights(): void {\n this.#itemList.clearHighlights();\n }\n\n /**\n * Focuses the first enabled item. When the most recent `openMenu` was\n * pointer-activated, this one move suppresses the item's focus-driven\n * `data-highlighted` (one-shot — later calls highlight normally).\n */\n focusFirstEnabledItem(): boolean {\n return this.#itemList.focusFirstEnabledItem(this.#initialFocusState.consumeHighlight());\n }\n\n /**\n * Focuses the last enabled item. When the most recent `openMenu` was\n * pointer-activated, this one move suppresses the item's focus-driven\n * `data-highlighted` (one-shot — later calls highlight normally).\n */\n focusLastEnabledItem(): boolean {\n return this.#itemList.focusLastEnabledItem(this.#initialFocusState.consumeHighlight());\n }\n\n /**\n * Toggle the menu open/closed from the trigger. The close branch reuses the\n * `'programmatic'` close reason by design — there is no distinct `'trigger'`\n * reason for the user-initiated toggle-close path.\n */\n toggle(\n initialFocus: 'first' | 'last' = 'first',\n modality: MenuActivationModality = 'keyboard',\n ): void {\n if (this.#hooks.disabled()) {\n return;\n }\n if (this.#hooks.open()) {\n this.closeMenu('programmatic');\n } else {\n this.openMenu(initialFocus, modality);\n }\n }\n\n /**\n * Opens the menu, recording where the initial focus should land and how\n * the open was activated. A `'pointer'` modality keeps that one initial\n * focus move from reflecting `data-highlighted` on the focused item.\n */\n openMenu(\n initialFocus: 'first' | 'last' = 'first',\n modality: MenuActivationModality = 'keyboard',\n ): void {\n if (this.#hooks.disabled()) {\n return;\n }\n this.#initialFocusState.prepareOpen(initialFocus, modality === 'keyboard');\n this.#closeReasonState.reset();\n this.#hooks.open.set(true);\n this.#hooks.onOpen?.(initialFocus);\n }\n\n closeMenu(reason: MenuOverlayCloseReason): void {\n this.#closeReasonState.set(reason);\n this.#hooks.open.set(false);\n this.#hooks.onClose?.(reason);\n }\n\n emitEscapeKeyDown(event: KeyboardEvent): void {\n const vetoed = emitVetoableNativeEvent(this.#hooks.escapeKeyDown, event);\n if (!vetoed && this.#hooks.dismissible()) {\n // Load-bearing, not redundant: the bubble-phase Escape handler stops the\n // same keydown from reaching an *ancestor* overlay's keydown listener,\n // which is how nested overlays close one layer per Escape (see the\n // listener-phase note in `_internal/dismissable-layer/dismissable-layer.ts`).\n event.stopPropagation();\n this.closeMenu('escape');\n }\n }\n\n /**\n * Outside-interaction emit forwarders. The shared `#pendingOutsideVeto`\n * reuse between the specific outside channels and the composite\n * `interactOutside` lives in `injectOverlayShell`; these only fire the\n * matching output with the veto the shell built.\n */\n emitPointerDownOutside(veto: VetoableNativeEvent<PointerEvent>): void {\n this.#hooks.pointerDownOutside.emit(veto);\n }\n emitFocusOutside(veto: VetoableNativeEvent<FocusEvent>): void {\n this.#hooks.focusOutside.emit(veto);\n }\n emitInteractOutside(veto: VetoableNativeEvent<PointerEvent | FocusEvent>): void {\n this.#hooks.interactOutside.emit(veto);\n }\n\n /**\n * Implicit close requested by `injectOverlayShell` after an un-vetoed\n * outside interaction. The shell owns the shared `#pendingOutsideVeto`\n * reuse between the specific outside channels and the composite\n * `interactOutside`; this helper only owns the close. The `open()` guard\n * keeps a stale event from re-closing an already-closed menu and clobbering\n * its `lastCloseReason` (e.g. a `'tab'` close must survive so the content\n * skips its return-focus).\n */\n requestClose(reason: 'pointerDownOutside' | 'focusOutside'): void {\n if (!this.#hooks.open()) {\n return;\n }\n this.closeMenu(reason);\n }\n\n emitAutoFocusOnOpen(): boolean {\n return emitVetoableEvent(this.#hooks.autoFocusOnOpen);\n }\n\n emitAutoFocusOnClose(): boolean {\n return emitVetoableEvent(this.#hooks.autoFocusOnClose);\n }\n}\n\n/**\n * Creates a `MenuOverlay` from a directive field initializer. `idPrefix`\n * is the namespace fed to the shared `IdGenerator` (e.g.\n * `'for-dropdown-menu'`, `'for-context-menu'`); the helper generates\n * `<idPrefix>-trigger` and `<idPrefix>-content` ids off it.\n */\nexport function createMenuOverlay<H extends MenuOverlayItemHandle = MenuOverlayItemHandle>(\n idPrefix: string,\n hooks: MenuOverlayHooks,\n): MenuOverlay<H> {\n return new MenuOverlay<H>(idPrefix, hooks);\n}\n","import { type Signal } from '@angular/core';\n\nimport type { ListNavigationAction } from '../keyboard-navigation/keyboard-navigation';\nimport type { VetoableNativeEvent } from '../vetoable-event/vetoable-event';\nimport type {\n MenuActivationModality,\n MenuOverlay,\n MenuOverlayCloseReason,\n MenuOverlayItemHandle,\n} from './menu-overlay';\n\n/**\n * Abstract base that forwards the `MenuOverlay` coordination slice every menu\n * root re-exposes — `[forDropdownMenu]`, `[forContextMenu]`, and `[forMenuSub]`\n * all extend it. Each subclass owns its own `MenuOverlay` instance (created\n * with its own id prefix and lifecycle hooks) and exposes it through the\n * abstract `_overlay` accessor; the base implements the trigger / content /\n * item registration, navigation, open/close, and veto pass-throughs once.\n *\n * This is the single place to add a member that is a pure pass-through to\n * `MenuOverlay`: declaring it here gives all three directives the method\n * without hand-written `.bind()` forwarding in each. Subclasses override only\n * the members that need extra behaviour (e.g. `[forMenuSub]` wraps\n * `registerContent` to attach pointer listeners and overrides the auto-focus\n * emitters to honour its hover focus-suppression flag).\n *\n * Kept generic over the item handle so the subclass's `MenuOverlay<H>` flows\n * through `registerItem` / `unregisterItem` without a cast.\n */\nexport abstract class MenuOverlayHost<H extends MenuOverlayItemHandle = MenuOverlayItemHandle> {\n /** The subclass's `MenuOverlay` instance the base forwards to. */\n protected abstract readonly _overlay: MenuOverlay<H>;\n\n get triggerId(): Signal<string> {\n return this._overlay.triggerId;\n }\n\n get contentId(): Signal<string> {\n return this._overlay.contentId;\n }\n\n get initialFocus(): Signal<'first' | 'last'> {\n return this._overlay.initialFocus;\n }\n\n get lastCloseReason(): Signal<MenuOverlayCloseReason | null> {\n return this._overlay.lastCloseReason;\n }\n\n get trigger(): Signal<HTMLElement | null> {\n return this._overlay.trigger;\n }\n\n get content(): Signal<HTMLElement | null> {\n return this._overlay.content;\n }\n\n setInitialFocus(target: 'first' | 'last'): void {\n this._overlay.setInitialFocus(target);\n }\n\n registerTrigger(el: HTMLElement): void {\n this._overlay.registerTrigger(el);\n }\n\n unregisterTrigger(el: HTMLElement): void {\n this._overlay.unregisterTrigger(el);\n }\n\n registerContent(el: HTMLElement): void {\n this._overlay.registerContent(el);\n }\n\n unregisterContent(el: HTMLElement): void {\n this._overlay.unregisterContent(el);\n }\n\n registerItem(handle: H): void {\n this._overlay.registerItem(handle);\n }\n\n unregisterItem(handle: H): void {\n this._overlay.unregisterItem(handle);\n }\n\n navigate(currentItem: HTMLElement, action: ListNavigationAction): void {\n this._overlay.navigate(currentItem, action);\n }\n\n handleTypeahead(event: KeyboardEvent): void {\n this._overlay.handleTypeahead(event);\n }\n\n clearItemHighlights(): void {\n this._overlay.clearItemHighlights();\n }\n\n focusFirstEnabledItem(): boolean {\n return this._overlay.focusFirstEnabledItem();\n }\n\n focusLastEnabledItem(): boolean {\n return this._overlay.focusLastEnabledItem();\n }\n\n toggle(\n initialFocus: 'first' | 'last' = 'first',\n modality: MenuActivationModality = 'keyboard',\n ): void {\n this._overlay.toggle(initialFocus, modality);\n }\n\n openMenu(\n initialFocus: 'first' | 'last' = 'first',\n modality: MenuActivationModality = 'keyboard',\n ): void {\n this._overlay.openMenu(initialFocus, modality);\n }\n\n closeMenu(reason: MenuOverlayCloseReason): void {\n this._overlay.closeMenu(reason);\n }\n\n requestClose(reason: 'pointerDownOutside' | 'focusOutside'): void {\n this._overlay.requestClose(reason);\n }\n\n emitEscapeKeyDown(event: KeyboardEvent): void {\n this._overlay.emitEscapeKeyDown(event);\n }\n\n emitPointerDownOutside(veto: VetoableNativeEvent<PointerEvent>): void {\n this._overlay.emitPointerDownOutside(veto);\n }\n\n emitFocusOutside(veto: VetoableNativeEvent<FocusEvent>): void {\n this._overlay.emitFocusOutside(veto);\n }\n\n emitInteractOutside(veto: VetoableNativeEvent<PointerEvent | FocusEvent>): void {\n this._overlay.emitInteractOutside(veto);\n }\n\n emitAutoFocusOnOpen(): boolean {\n return this._overlay.emitAutoFocusOnOpen();\n }\n\n emitAutoFocusOnClose(): boolean {\n return this._overlay.emitAutoFocusOnClose();\n }\n}\n","import type { FloatingAlign, FloatingSide } from '../floating/floating';\n\n/**\n * Single source of truth for the floating-ui positioning defaults shared by the\n * three menu roots — `[forDropdownMenu]`, `[forContextMenu]`, and `[forMenuSub]`.\n *\n * Angular's compiler requires every `input()` to be declared directly in a class\n * member initializer (NG8110), so the inputs themselves can't be produced by a\n * shared factory. To stop the (already-drifted) defaults from diverging again,\n * each root reads its non-seed defaults from this object and the\n * `menu-positioning-inputs.spec.ts` guard asserts the three roots keep an\n * identical positioning input set.\n *\n * Only `side` / `sideOffset` / `collisionPadding` legitimately vary per root:\n *\n * - `side` — DropdownMenu / ContextMenu anchor `'bottom'`; the submenu resolves\n * its side from the writing direction (`'right'` LTR / `'left'` RTL).\n * - `sideOffset` / `collisionPadding` — seeded from each root's defaults\n * provider (`provideForDropdownMenuDefaults` / `provideForContextMenuDefaults`\n * / `provideForMenuDefaults`) so a scope override flows through.\n *\n * Everything below is identical across all three roots.\n */\nexport const MENU_POSITIONING_DEFAULTS = {\n /** Default anchor side for the two top-level roots. */\n side: 'bottom' as FloatingSide | undefined,\n /** Default alignment along the chosen `side`. */\n align: 'start' as FloatingAlign | undefined,\n /** Default gap (px) along the cross axis. */\n alignOffset: 0,\n /** `flip` / `shift` keep the surface inside the viewport by default. */\n avoidCollisions: true,\n /** Default padding (px) for the `arrow` middleware. */\n arrowPadding: 0,\n /** Default stickiness behaviour for `shift`. */\n sticky: 'partial' as 'partial' | 'always' | false,\n /** `data-detached=\"\"` is not reflected by default. */\n hideWhenDetached: false,\n /** Content is clipped until floating-ui resolves its first position by default. */\n clipUntilPositioned: true,\n} as const;\n","import { DestroyRef, DOCUMENT, ElementRef, inject, type Signal } from '@angular/core';\n\nimport { afterNextRenderCancellable } from '../after-next-render-cancellable/after-next-render-cancellable';\nimport { BodyScrollLock } from '../body-scroll-lock/body-scroll-lock';\nimport { injectDismissableLayer } from '../dismissable-layer/dismissable-layer';\nimport { findFirstFocusable, injectFocusTrap } from '../focus-trap/focus-trap';\nimport { type InertSiblingsHandle, InertSiblingsStack } from '../inert-siblings/inert-siblings';\nimport { injectPortal } from '../portal/portal';\nimport {\n createVetoableEvent,\n createVetoableNativeEvent,\n type VetoableEvent,\n type VetoableNativeEvent,\n} from '../vetoable-event/vetoable-event';\n\n/**\n * Dismiss-bundle wiring. The shell owns the triple-veto + composite\n * `interactOutside` orchestration that Dialog and Drawer used to duplicate\n * verbatim:\n *\n * - Each \"specific\" channel (Escape / pointer-down-outside / focus-outside)\n * builds a `VetoableNativeEvent`, hands it to the consumer's emitter, and —\n * for pointer / focus — stores it so the immediately-following composite\n * `onInteractOutside` reuses the same veto state. A `preventDefault()` from\n * either the specific or the composite handler suppresses the implicit\n * close.\n * - When the consumer doesn't veto AND `dismissible()` is `true`, the shell\n * calls `requestClose(reason)` with the reason that matches the channel\n * (`'escape' | 'pointerDownOutside' | 'focusOutside'`).\n * - `exemptElements` is recomputed on every event so DOM mutations (newly\n * portaled siblings — Drawer's backdrop is the live example) are picked up.\n *\n * `requestClose` is the consumer's existing implementation; the shell never\n * touches the directive's `(dismiss)` output directly. This keeps the shell\n * orthogonal to each primitive's own close-reason union.\n */\nexport interface ModalShellDismissConfig {\n /** Whether dismissals via the layer fire the implicit `requestClose`. */\n readonly dismissible: Signal<boolean>;\n /** Called with the matching reason when the consumer doesn't veto. */\n readonly requestClose: (reason: 'escape' | 'pointerDownOutside' | 'focusOutside') => void;\n /** Forwards the Escape `VetoableNativeEvent` to the directive's `(escapeKeyDown)` output. */\n readonly emitEscapeKeyDown: (veto: VetoableNativeEvent<KeyboardEvent>) => void;\n /** Forwards the pointer-down-outside veto to the directive's `(pointerDownOutside)` output. */\n readonly emitPointerDownOutside: (veto: VetoableNativeEvent<PointerEvent>) => void;\n /** Forwards the focus-outside veto to the directive's `(focusOutside)` output. */\n readonly emitFocusOutside: (veto: VetoableNativeEvent<FocusEvent>) => void;\n /** Forwards the composite veto to the directive's `(interactOutside)` output. */\n readonly emitInteractOutside: (veto: VetoableNativeEvent<PointerEvent | FocusEvent>) => void;\n /**\n * Live \"elements that count as inside\" set — Drawer uses this to exempt\n * its portaled backdrop so a backdrop click routes through the backdrop's\n * own `requestClose('backdrop')` path instead of `pointerDownOutside`.\n */\n readonly exemptElements?: () => readonly Element[];\n}\n\n/**\n * Primitive-owned initial-focus algorithm for the surface. The richer\n * alternative to the `'first' | 'container'` literal: the shell sets up the\n * focus trap (Tab cycling + return capture) WITHOUT its own imperative focus\n * move, runs the optional `veto`, and — unless vetoed — calls `move()`. When\n * `move()` returns `false` (no candidate found) focus falls back to the trap\n * container (modal) or the first focusable descendant (non-modal).\n *\n * Mirrors `OverlayShellInitialFocusConfig` so a content directive can hand the\n * same focus algorithm to either shell. Used by Select (selected → first →\n * last option) and available for a future date-picker calendar-cell move.\n */\nexport interface ModalShellInitialFocusConfig {\n /** Primitive focus algorithm. Returns `true` on success, `false` to fall back. */\n readonly move: () => boolean;\n /** `(autoFocusOnOpen)` veto. Returning `true` skips the imperative focus move. */\n readonly veto?: () => boolean;\n}\n\n/**\n * Single config for the free-floating modal-overlay lifecycle. Mirrors the\n * `injectOverlayShell` shape on the trigger-anchored side. Each sub-bundle\n * is individually optional so a primitive can opt out of the channels it\n * doesn't need (e.g. a dismiss-less confirm dialog, though none ship today).\n */\nexport interface ModalShellConfig {\n /** Whether the surface activates focus-trap + scroll-lock + inert siblings. */\n readonly modal: Signal<boolean>;\n /**\n * Whether focus returns to the previously-focused element on destroy.\n * Read inside the modal teardown (focus-trap deactivate). Has no effect\n * in non-modal mode (the shell never moves focus on close in that mode).\n */\n readonly returnFocus: Signal<boolean>;\n /**\n * Where to send focus on mount. Two shapes:\n * - `Signal<'first' | 'container'>` — `'first'` = first focusable descendant\n * (falls back to host); `'container'` = host element. Same vocabulary as\n * `FocusTrap.activate({ initialFocus })`. Used by Dialog / Drawer /\n * date-picker.\n * - {@link ModalShellInitialFocusConfig} — a primitive-owned `move()`\n * algorithm (e.g. Select's selected → first → last option) with its own\n * open-veto, falling back to the container / first focusable on a miss.\n */\n readonly initialFocus: Signal<'first' | 'container'> | ModalShellInitialFocusConfig;\n /**\n * `(autoFocusOnOpen)` veto. Bound as a function reference (not as an\n * Angular `output()`) so the shell can invoke it during the destroy hook\n * without depending on `OutputEmitterRef` lifecycle. Read at every mount;\n * a `preventDefault()` on the emitted event skips the imperative initial\n * focus move while still leaving the focus-trap (Tab cycling, return\n * capture) wired in modal mode.\n */\n readonly autoFocusOnOpen?: () => ((event: VetoableEvent) => void) | undefined;\n /**\n * `(autoFocusOnClose)` veto. Same shape as `autoFocusOnOpen`. Fired\n * synchronously from the `DestroyRef.onDestroy` hook, BEFORE the modal /\n * non-modal teardown so it runs reliably on every close path — including a\n * direct `open.set(false)` from the consumer that bypasses any\n * close-output emission.\n */\n readonly autoFocusOnClose?: () => ((event: VetoableEvent) => void) | undefined;\n /**\n * Portal target for the surface. A signal so it is read once at the first\n * render (the portal moves the host once), after the consumer's input is\n * bound. `undefined` / a signal yielding `null` ⇒ `document.body`.\n */\n readonly container?: Signal<HTMLElement | null>;\n /** Optional dismiss bundle. Absent for primitives that don't dismiss via the layer. */\n readonly dismiss?: ModalShellDismissConfig;\n}\n\n/** Imperative handle returned by `injectModalShell`. */\nexport interface ModalShellHandle {\n /** True while the shell activated focus-trap + scroll-lock + inert (modal mode). */\n readonly isModal: () => boolean;\n}\n\n/**\n * Single source of truth for the free-floating modal-overlay lifecycle.\n * Drives every directive in the library that mounts a modal surface as its\n * own root — `[forDialog]` and `[forDrawer]` today, future modal Toast /\n * full-screen sheet / command palette tomorrow. The shell owns:\n *\n * 1. Return-focus target capture. Synchronously, in the consumer's\n * constructor (BEFORE `afterNextRender` fires). Required for WebKit\n * correctness (#136): WebKit blurs the previously-focused element when\n * an ancestor receives `inert`, so by the time `afterNextRender` runs\n * (where inert is activated) reading `document.activeElement` from the\n * focus trap would yield `<body>`. Capturing it now locks the trigger\n * in as the return target before any side effect mutates focus.\n *\n * 2. Portal. `injectPortal()` moves the host to `document.body` after the\n * first render and removes it on destroy.\n *\n * 3. Dismissable layer. Activates inside `afterNextRender` with the\n * triple-veto + composite `interactOutside` pattern that Dialog and\n * Drawer duplicated verbatim. The pattern: a single\n * `VetoableNativeEvent` is built per physical interaction and reused\n * for the specific channel (`pointerDownOutside` / `focusOutside`) and\n * the composite (`interactOutside`), so a `preventDefault()` from\n * either suppresses the implicit `requestClose`. Escape uses its own\n * one-shot veto.\n *\n * 4. Modal vs non-modal branching.\n * - Modal: pushes the inert-siblings stack BEFORE the focus trap fires\n * (so the trap's imperative focus move lands on an already-isolated\n * tree), activates the trap with `initialFocus` + `preventInitialFocus`\n * (the `(autoFocusOnOpen)` veto) + the synchronously-captured\n * `returnFocus` target, then locks scroll. When `config.container` is\n * set, inert-siblings is scoped to that container (only the container's\n * other children are inerted; body siblings stay interactive) and scroll\n * lock targets the container instead of `<body>` (#819). Focus trap is\n * already subtree-scoped to the host regardless of portal target — no\n * change there. When `initialFocus` is a\n * {@link ModalShellInitialFocusConfig}, the trap is activated with\n * `preventInitialFocus: true` and the shell runs the primitive's\n * `move()` instead (falling back to the container on a miss).\n * - Non-modal: skips trap / inert / scroll lock; if `(autoFocusOnOpen)`\n * didn't veto, focuses the first focusable descendant (or host when\n * `initialFocus = 'container'`).\n *\n * 5. Destroy ordering. All steps below run inside ONE\n * `DestroyRef.onDestroy` hook, so they execute as plain sequential\n * statements — the sequence is fixed by the code, not by Angular's\n * (FIFO) hook-registration order. Within the hook the side-effects are\n * torn down in the inverse order they were activated:\n * - `dismissable.deactivate()` first (it was activated first in the setup\n * `afterNextRender`).\n * - `(autoFocusOnClose)` veto fires BEFORE either modal/non-modal\n * teardown so it runs on every close path regardless of mode.\n * - Modal only: `inertHandle.deactivate()` (so the return-focus target\n * is not blocked by an inert ancestor) →\n * `dismissable.suppress(focusTrap.deactivate)` (so the synthetic\n * `focusin` from `.focus()`-ing the previous element doesn't\n * cascade-dismiss whatever layer is now topmost) →\n * `bodyScrollLock.unlock()`.\n *\n * Must be called from an injection context (typically the directive\n * constructor). Forwards the host's `ElementRef` to the portal, dismissable\n * layer, focus trap, and inert-siblings stack — the consumer never has to\n * touch them directly.\n *\n * @example\n * // ForDialog constructor body collapses to:\n * injectModalShell({\n * modal: this.modal,\n * returnFocus: this.returnFocus,\n * initialFocus: this.initialFocus,\n * autoFocusOnOpen: () => this.autoFocusOnOpen(),\n * autoFocusOnClose: () => this.autoFocusOnClose(),\n * dismiss: {\n * dismissible: this.dismissible,\n * requestClose: (reason) => this.requestClose(reason),\n * emitEscapeKeyDown: (veto) => this.escapeKeyDown.emit(veto),\n * emitPointerDownOutside: (veto) => this.pointerDownOutside.emit(veto),\n * emitFocusOutside: (veto) => this.focusOutside.emit(veto),\n * emitInteractOutside: (veto) => this.interactOutside.emit(veto),\n * },\n * });\n */\nexport function injectModalShell(config: ModalShellConfig): ModalShellHandle {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const document = inject(DOCUMENT);\n const focusTrap = injectFocusTrap();\n const dismissable = injectDismissableLayer();\n const inertStack = inject(InertSiblingsStack);\n const scrollLock = inject(BodyScrollLock);\n\n // 1. Capture the return-focus target SYNCHRONOUSLY, before any side effect\n // runs. WebKit (#136) blurs the previously-focused element as soon as\n // `inert` is applied to an ancestor, so by the time `afterNextRender`\n // fires the focus trap could no longer read the trigger from\n // `document.activeElement`. Reading it now locks the trigger in.\n const returnFocusTarget: HTMLElement | null =\n document.activeElement instanceof HTMLElement ? document.activeElement : null;\n\n // 2. Portal — moves the host to `document.body` after first render and\n // cleans up on destroy. `DestroyRef.onDestroy` callbacks fire in\n // registration order (FIFO), and the portal registers its hook here,\n // before the shell's own destroy hook below — so on teardown the portal\n // removes the host from the DOM FIRST, then the shell runs return-focus.\n // The ordering is harmless either way: return-focus targets the\n // previously-focused element (the trigger, captured synchronously above),\n // which lives OUTSIDE the portaled host, so removing the host first never\n // affects it.\n injectPortal(config.container ? { target: config.container } : {});\n\n // Captured at mount time so the destroy path can mirror the same mode the\n // shell activated, regardless of any `modal()` toggle on a doomed\n // instance.\n let activatedAsModal = false;\n let inertHandle: InertSiblingsHandle | null = null;\n let activatedContainer: HTMLElement | null = null;\n\n // 3. Side-effect setup runs after Angular has applied input bindings.\n // Reading `config.modal()` etc. in the constructor would always see the\n // default value because the input writes haven't flowed through yet.\n // `afterNextRenderCancellable` makes the destroy-before-render path safe.\n // On the true-async path (queued render after destroy) the callback is\n // cancelled, so inert siblings / focus trap / scroll lock / dismissable\n // layer are never activated (`activatedAsModal` stays false). On the\n // synchronous-teardown path the callback flushes just before the destroy\n // hook, so it sets `activatedAsModal = true` and the destroy hook below\n // tears the side-effect stack back down. Either way nothing leaks.\n afterNextRenderCancellable(() => {\n const isModal = config.modal();\n activatedAsModal = isModal;\n\n // 3a. Dismissable layer. Pushed onto the stack BEFORE moving focus so\n // focusin events triggered by our own focus management land on this\n // layer, not on whatever lower layer was previously topmost.\n //\n // Triple-veto + composite `interactOutside`: pointer-down-outside\n // and focus-outside both fire on the same physical interaction. The\n // dismissable layer always invokes the specific listener before the\n // composite one, so we build a single veto wrapper on the specific\n // call and reuse it for the composite call. A `preventDefault()` in\n // either handler vetoes the close.\n const dismissCfg = config.dismiss;\n if (dismissCfg !== undefined) {\n let pendingOutsideVeto: VetoableNativeEvent<PointerEvent | FocusEvent> | null = null;\n dismissable.activate({\n ...(dismissCfg.exemptElements ? { exemptElements: dismissCfg.exemptElements } : {}),\n onEscapeKeyDown: (event) => {\n const veto = createVetoableNativeEvent(event);\n dismissCfg.emitEscapeKeyDown(veto);\n if (!veto.defaultPrevented && dismissCfg.dismissible()) {\n event.stopPropagation();\n dismissCfg.requestClose('escape');\n }\n },\n onPointerDownOutside: (event) => {\n pendingOutsideVeto = createVetoableNativeEvent<PointerEvent | FocusEvent>(event);\n dismissCfg.emitPointerDownOutside(\n pendingOutsideVeto as VetoableNativeEvent<PointerEvent>,\n );\n },\n onFocusOutside: (event) => {\n pendingOutsideVeto = createVetoableNativeEvent<PointerEvent | FocusEvent>(event);\n dismissCfg.emitFocusOutside(pendingOutsideVeto as VetoableNativeEvent<FocusEvent>);\n },\n onInteractOutside: (event) => {\n const veto =\n pendingOutsideVeto ?? createVetoableNativeEvent<PointerEvent | FocusEvent>(event);\n pendingOutsideVeto = null;\n dismissCfg.emitInteractOutside(veto);\n if (!veto.defaultPrevented && dismissCfg.dismissible()) {\n dismissCfg.requestClose(\n event.type === 'pointerdown' ? 'pointerDownOutside' : 'focusOutside',\n );\n }\n },\n });\n }\n\n // 3b. Resolve the initial-focus config. The simple form is a\n // `Signal<'first' | 'container'>` (Dialog / Drawer / date-picker); the\n // richer form carries a primitive-owned `move()` algorithm (Select's\n // selected → first → last option) plus its own veto. A `Signal` is\n // callable, so `typeof === 'function'` distinguishes the two shapes;\n // the literal mode is read eagerly only in the simple form.\n const initialFocusCfg = config.initialFocus;\n const moveCfg: ModalShellInitialFocusConfig | null =\n typeof initialFocusCfg === 'function' ? null : initialFocusCfg;\n const literalFocus: 'first' | 'container' | null =\n typeof initialFocusCfg === 'function' ? initialFocusCfg() : null;\n\n // 3c. `(autoFocusOnOpen)` veto — read once for this mount. The move-config\n // carries its own boolean veto (mirroring `injectOverlayShell`); the\n // simple form routes through the top-level `autoFocusOnOpen` callback.\n let skipInitialFocus: boolean;\n if (moveCfg) {\n skipInitialFocus = moveCfg.veto?.() ?? false;\n } else {\n const autoFocusOpenEvent = createVetoableEvent();\n config.autoFocusOnOpen?.()?.(autoFocusOpenEvent);\n skipInitialFocus = autoFocusOpenEvent.defaultPrevented;\n }\n\n if (isModal) {\n // 3d. Modal mode. Inert + aria-hide siblings BEFORE the focus trap\n // activates so the trap's `focus()` call lands on an\n // already-isolated tree. The return-focus target was captured\n // synchronously above (#136).\n const containerEl = config.container?.() ?? null;\n inertHandle = inertStack.activate(host.nativeElement, containerEl ?? undefined);\n activatedContainer = containerEl;\n if (moveCfg) {\n // The primitive owns the focus move. Set up Tab cycling + return\n // capture WITHOUT the trap's own imperative focus, then run the\n // algorithm; fall back to the container when it finds no candidate.\n focusTrap.activate({\n preventInitialFocus: true,\n returnFocus: returnFocusTarget,\n });\n if (!skipInitialFocus && !moveCfg.move()) {\n focusTrap.container.focus();\n }\n } else {\n focusTrap.activate({\n initialFocus: literalFocus ?? 'first',\n preventInitialFocus: skipInitialFocus,\n returnFocus: returnFocusTarget,\n });\n }\n scrollLock.lock(containerEl ?? undefined);\n } else if (!skipInitialFocus) {\n // 3e. Non-modal mode. No trap, no scroll lock, no inert. Still respect\n // the configured initial focus: the primitive's `move()` algorithm\n // (falling back to the first focusable on a miss), the first\n // focusable descendant ('first'), or the host ('container').\n const el = focusTrap.container;\n if (moveCfg) {\n if (!moveCfg.move()) {\n (findFirstFocusable(el) ?? el).focus();\n }\n } else if (literalFocus === 'container') {\n el.focus();\n } else {\n (findFirstFocusable(el) ?? el).focus();\n }\n }\n });\n\n // 4. Destroy. Hooks fire in registration order; the portal's destroy hook\n // was registered inside `injectPortal()` (above) so it runs BEFORE\n // ours, removing the element from the DOM first. We tear down the\n // side-effect stack here in the inverse order it was activated.\n inject(DestroyRef).onDestroy(() => {\n dismissable.deactivate();\n // Invoke `(autoFocusOnClose)` synchronously, BEFORE either the modal or\n // non-modal teardown runs. Fires on every close path regardless of mode\n // (the consumer's `(dismiss)` flow AND a direct `open.set(false)` that\n // bypasses any close-output emission). The callback is a plain function\n // reference — input signals stay readable during destroy and there is no\n // dependency on `OutputEmitterRef` lifecycle. Non-modal mode never moves\n // focus on close, so `skipReturnFocus` is only consulted in the modal\n // branch — but the hook still fires for symmetry with the manager and so\n // consumers can wire their own focus moves on close in non-modal mode.\n const autoFocusCloseEvent = createVetoableEvent();\n config.autoFocusOnClose?.()?.(autoFocusCloseEvent);\n const skipReturnFocus = autoFocusCloseEvent.defaultPrevented;\n if (activatedAsModal) {\n // Lift inert + aria-hide BEFORE moving focus back: an `inert` ancestor\n // blocks `.focus()` on its descendants, so the return-focus target\n // needs to be live again first.\n inertHandle?.deactivate();\n inertHandle = null;\n // Suppress the dismissable-layer dispatcher across focus-return so the\n // synthetic `focusin` triggered by `.focus()`-ing the previous element\n // does not cascade-dismiss whatever modal is now topmost (a stacked\n // dialog opened above this one).\n dismissable.suppress(() => {\n focusTrap.deactivate({\n returnFocus: config.returnFocus() && !skipReturnFocus,\n });\n });\n scrollLock.unlock(activatedContainer ?? undefined);\n }\n });\n\n return {\n isModal: () => activatedAsModal,\n };\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 * 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`. Integer steps return `value`\n * unchanged.\n */\nexport function roundToStepPrecision(value: number, step: number): number {\n const stepText = String(step);\n const dot = stepText.indexOf('.');\n if (dot < 0) {\n return value;\n }\n const factor = 10 ** (stepText.length - dot - 1);\n return Math.round(value * factor) / factor;\n}\n\n/**\n * Snaps `raw` onto the `[min, min + step, min + 2·step, …]` grid, then rounds the\n * result to the step's decimal precision (via {@link roundToStepPrecision}) so a\n * fractional step can't accumulate float noise. A non-positive `step` disables\n * snapping and returns `raw` unchanged. Clamping to an outer range is the\n * caller's responsibility — pass the snapped result to {@link clamp}.\n */\nexport function snapToStep(raw: number, step: number, min: number): number {\n if (step <= 0) {\n return raw;\n }\n return roundToStepPrecision(Math.round((raw - min) / step) * step + min, step);\n}\n","import { inject, Injector } from '@angular/core';\n\n/**\n * Internal composition surface (no semver guarantees). Base for an overlay\n * outlet's context-injector directive. It sits\n * inside the row's `[forDialog]` / `[forDrawer]` element, so its own element\n * injector already resolves that primitive's `FOR_<PRIMITIVE>_CONTEXT`. The\n * outlet feeds this injector to `entry.injectorFor(ctx.injector)`, making the\n * user component rendered via `NgComponentOutlet` inherit the context\n * alongside the data token / ref / consumer providers — so every piece\n * (`[forDialogClose]`, `[forDialogTitle]`, …) resolves exactly as in the\n * declarative path.\n *\n * Each manager subclasses this with its own `for-`-prefixed selector +\n * `exportAs` (the directive selector must be static at decoration time, and\n * the per-primitive template references it by `exportAs`), so the shared body\n * lives here once.\n */\nexport abstract class OverlayContextInjector {\n readonly injector = inject(Injector);\n}\n","import {\n ApplicationRef,\n type ComponentRef,\n computed,\n DOCUMENT,\n EnvironmentInjector,\n inject,\n Injector,\n type Provider,\n type Signal,\n signal,\n} from '@angular/core';\n\nimport { IdGenerator } from '../id-generator/id-generator';\nimport type { OverlayRef } from './overlay-ref';\n\n/**\n * Minimal shape every overlay entry must satisfy so the shared core can index,\n * render, and tear it down. Per-primitive entries (`ForDialogEntry`,\n * `ForDrawerEntry`) extend this with their own directive-input fields.\n *\n * Internal — not re-exported from `public-api.ts`.\n */\nexport interface OverlayManagerEntry {\n readonly id: string;\n readonly ref: OverlayRef<unknown>;\n}\n\n/**\n * The reactive surface a manager's outlet component is wired with on first\n * `open()`. Mirrors `ForDialogOutletHost` / `ForDrawerOutletHost`.\n *\n * Internal — not re-exported from `public-api.ts`.\n */\nexport interface OverlayManagerOutletHost<TEntry extends OverlayManagerEntry> {\n readonly entries: Signal<readonly TEntry[]>;\n closeAllForDestroy(): void;\n}\n\n/**\n * The minimal surface a manager's outlet component exposes so the core can\n * wire it on first `open()`. Mirrors `ForDialogOutlet` / `ForDrawerOutlet`.\n *\n * Internal — not re-exported from `public-api.ts`.\n */\nexport interface OverlayManagerOutlet<TEntry extends OverlayManagerEntry> {\n init(host: OverlayManagerOutletHost<TEntry>): void;\n}\n\n/**\n * Per-primitive bindings the shared core needs: how to name ids and the\n * exit-animation host / backdrop attributes, and how to create the outlet\n * component that renders the entries.\n *\n * Internal — not re-exported from `public-api.ts`.\n */\nexport interface OverlayManagerConfig<TEntry extends OverlayManagerEntry> {\n /**\n * Per-instance id prefix passed to `IdGenerator.next` (e.g.\n * `'for-dialog-instance'`).\n */\n readonly idPrefix: string;\n /**\n * Attribute the overlay root + backdrop reflect their per-instance id on\n * (e.g. `'data-for-dialog-id'`), matched during exit animation.\n */\n readonly idAttribute: string;\n /**\n * Attribute marking the portaled backdrop element (e.g.\n * `'data-for-dialog-backdrop'`), matched during exit animation.\n */\n readonly backdropAttribute: string;\n /** Creates the manager-owned outlet component (e.g. `ForDialogOutlet`). */\n createOutlet(\n environmentInjector: EnvironmentInjector,\n ): ComponentRef<OverlayManagerOutlet<TEntry>>;\n}\n\n/**\n * Shared imperative-overlay engine behind `ForDialogManager` and\n * `ForDrawerManager`. Owns the entries signal, the reactive `openCount`, the\n * lazily-created outlet, the destroy-time close-all sweep, the exit-animation\n * `beginLeave` driver, and the parent-cached per-component `Injector` factory.\n * The two managers differ only in their entry shape and directive-input\n * mapping; everything structural lives here once.\n *\n * Internal — not re-exported from `public-api.ts`; the public surface is\n * `ForDialogManager` / `ForDrawerManager`.\n */\nexport class OverlayManagerCore<TEntry extends OverlayManagerEntry> {\n readonly #appRef = inject(ApplicationRef);\n readonly #envInjector = inject(EnvironmentInjector);\n readonly #document = inject(DOCUMENT);\n protected readonly idGen = inject(IdGenerator);\n\n readonly #entries = signal<readonly TEntry[]>([]);\n readonly #config: OverlayManagerConfig<TEntry>;\n\n /** Reactive count of currently open programmatic overlays. */\n readonly openCount = computed(() => this.#entries().length);\n\n #outletRef: ComponentRef<OverlayManagerOutlet<TEntry>> | null = null;\n #destroying = false;\n\n constructor(config: OverlayManagerConfig<TEntry>) {\n this.#config = config;\n }\n\n /**\n * Generates the next per-instance id and a paired idempotent\n * `remove` that drops the entry. The caller builds the `ref` with a teardown\n * that drives the exit animation before invoking `remove`.\n */\n protected nextId(): { id: string; remove: () => void } {\n const id = this.idGen.next(this.#config.idPrefix);\n let removed = false;\n const remove = (): void => {\n if (removed) {\n return;\n }\n removed = true;\n this.#entries.update((arr) => arr.filter((e) => e.id !== id));\n };\n return { id, remove };\n }\n\n /**\n * Drives the exit animation on the overlay root and, in lockstep,\n * on the portaled backdrop (matched by the same per-instance id, because the\n * backdrop's template `animate.leave` never fires under the manager's\n * `ngComponentOutlet` mount), then calls `remove`. Runs `remove` immediately\n * when destroying, when `requestAnimationFrame` is unavailable, or when there\n * is nothing to animate.\n */\n protected beginLeave(\n id: string,\n leaveClass: string | undefined,\n backdropLeaveClass: string | undefined,\n remove: () => void,\n ): void {\n if (this.#destroying || typeof requestAnimationFrame === 'undefined') {\n remove();\n return;\n }\n const { idAttribute, backdropAttribute } = this.#config;\n const targets: HTMLElement[] = [];\n if (leaveClass) {\n const host = this.#document.querySelector<HTMLElement>(\n `[${idAttribute}=\"${id}\"]:not([${backdropAttribute}])`,\n );\n if (host && typeof host.getAnimations === 'function') {\n host.classList.add(leaveClass);\n targets.push(host);\n }\n }\n if (backdropLeaveClass) {\n const backdrop = this.#document.querySelector<HTMLElement>(\n `[${backdropAttribute}][${idAttribute}=\"${id}\"]`,\n );\n if (backdrop && typeof backdrop.getAnimations === 'function') {\n backdrop.classList.add(backdropLeaveClass);\n targets.push(backdrop);\n }\n }\n if (targets.length === 0) {\n remove();\n return;\n }\n requestAnimationFrame(() => {\n const animations = targets.flatMap((el) => el.getAnimations());\n if (animations.length === 0) {\n remove();\n return;\n }\n Promise.all(animations.map((animation) => animation.finished.catch(() => undefined))).then(\n () => remove(),\n );\n });\n }\n\n /**\n * Builds a parent-cached per-component `Injector`. The returned\n * factory recreates the injector only when its parent changes, so re-renders\n * with the same enclosing `[forDialog]` / `[forDrawer]` host reuse it.\n */\n protected createInjectorFactory(providers: readonly Provider[]): (parent: Injector) => Injector {\n let cachedInjector: Injector | null = null;\n let cachedParent: Injector | null = null;\n return (parent: Injector): Injector => {\n if (cachedInjector && cachedParent === parent) {\n return cachedInjector;\n }\n cachedParent = parent;\n cachedInjector = Injector.create({ parent, providers: [...providers] });\n return cachedInjector;\n };\n }\n\n /**\n * Registers a fully-built entry, ensures the outlet exists, and\n * ticks so the `@for` renders it.\n */\n protected register(entry: TEntry): void {\n this.#ensureOutlet();\n this.#entries.update((arr) => [...arr, entry]);\n this.#appRef.tick();\n }\n\n #closeAllForDestroy(): void {\n this.#destroying = true;\n for (const entry of this.#entries()) {\n entry.ref.close();\n }\n }\n\n #ensureOutlet(): void {\n if (this.#outletRef) {\n return;\n }\n const outletRef = this.#config.createOutlet(this.#envInjector);\n this.#appRef.attachView(outletRef.hostView);\n outletRef.instance.init({\n entries: this.#entries.asReadonly(),\n closeAllForDestroy: () => this.#closeAllForDestroy(),\n });\n this.#outletRef = outletRef;\n }\n}\n","import { signal } from '@angular/core';\n\n/**\n * Shared handle returned by an imperative overlay manager's `open()`.\n * `ForDialogRef` / `ForDrawerRef` extend this verbatim to keep their public\n * class identity (and DI token) while the close engine lives here once.\n *\n * Both reactive (`isClosed`, `result`) and awaitable (`closed`) APIs are\n * exposed — pick what fits the call site. `R` is the close-result type.\n *\n * Internal — not re-exported from `public-api.ts`; the public surface is\n * `ForDialogRef` / `ForDrawerRef`.\n */\nexport class OverlayRef<R = unknown> {\n readonly #result = signal<R | undefined>(undefined);\n readonly #closed = signal(false);\n\n /** Reactive: `true` once `close()` has been called. */\n readonly isClosed = this.#closed.asReadonly();\n\n /** Reactive: the close result. `undefined` while open. */\n readonly result = this.#result.asReadonly();\n\n /** Awaitable: resolves with the close result the first time `close()` runs. */\n readonly closed: Promise<R | undefined>;\n\n #resolveClosed!: (r: R | undefined) => void;\n readonly #teardown: () => void;\n\n /** Internal composition surface (no semver guarantees). */\n constructor(teardown: () => void) {\n this.#teardown = teardown;\n this.closed = new Promise((resolve) => {\n this.#resolveClosed = resolve;\n });\n }\n\n /**\n * Close the overlay, optionally returning a result. Idempotent — calling\n * twice is a no-op.\n */\n close(result?: R): void {\n if (this.#closed()) {\n return;\n }\n this.#result.set(result);\n this.#closed.set(true);\n this.#resolveClosed(result);\n this.#teardown();\n }\n}\n","import { afterNextRender, effect, ElementRef, inject, type Signal } from '@angular/core';\nimport {\n autoUpdate,\n computePosition,\n type Middleware,\n type Padding,\n type ReferenceElement,\n} from '@floating-ui/dom';\n\nimport { injectPortal } from '../portal/portal';\n\nexport interface ItemAlignedConfig {\n /**\n * The anchor (typically a `<button>` trigger). Reactive — should emit\n * `null` until the anchor is available; positioning is skipped while\n * `null` or `open` is `false`.\n */\n readonly reference: Signal<ReferenceElement | null>;\n\n /**\n * Whether the listbox is currently visible. `autoUpdate` is started when\n * this becomes `true` and torn down when it goes back to `false`.\n */\n readonly open: Signal<boolean>;\n\n /**\n * The selected option element to anchor over the trigger. When `null`,\n * the algorithm falls back to the first enabled `[role=\"option\"]` inside\n * the listbox. Reactive — re-running `computePosition` if the selection\n * changes while open.\n */\n readonly selectedOption: Signal<HTMLElement | null>;\n\n /**\n * Padding (px) the listbox keeps from the viewport edge. Default `8`.\n * Drives both the viewport clamp on the listbox top/bottom and the\n * `--for-select-content-available-height` CSS variable.\n */\n readonly collisionPadding?: Signal<number | Padding>;\n\n /**\n * When `true` (default), the floating element is moved to `document.body`\n * on first render and removed on destroy. Set to `false` when the caller\n * already invokes `injectPortal()` on its own.\n */\n readonly portal?: boolean;\n}\n\nfunction paddingTop(padding: number | Padding | undefined, fallback: number): number {\n if (padding == null) {\n return fallback;\n }\n if (typeof padding === 'number') {\n return padding;\n }\n return padding.top ?? fallback;\n}\n\nfunction findFirstEnabledOption(listbox: HTMLElement): HTMLElement | null {\n const options = listbox.querySelectorAll<HTMLElement>('[role=\"option\"]');\n for (let i = 0; i < options.length; i++) {\n const opt = options[i]!;\n if (opt.getAttribute('aria-disabled') === 'true' || opt.hasAttribute('disabled')) {\n continue;\n }\n return opt;\n }\n return null;\n}\n\n/**\n * Custom floating-ui middleware. Computes raw `x`/`y` so the *target option's\n * vertical center* lines up with the *trigger's vertical center*, then clamps\n * the listbox inside the viewport with `padding`. Cross-axis: listbox left\n * edge aligned to the trigger left edge.\n *\n * Falls back to the first enabled option inside the listbox when no option\n * is selected — matches the macOS `<select>` behavior.\n */\nfunction itemAligned(\n selectedOption: () => HTMLElement | null,\n paddingFn: () => number,\n): Middleware {\n return {\n name: 'item-aligned',\n fn(state) {\n const reference = state.elements.reference;\n const floating = state.elements.floating;\n const triggerRect = reference.getBoundingClientRect();\n const listboxRect = floating.getBoundingClientRect();\n const target = selectedOption() ?? findFirstEnabledOption(floating);\n const padding = paddingFn();\n // Read the viewport height through the floating element's own\n // window so the middleware works in iframes / multiple-document\n // contexts and stays SSR-safe (the middleware itself only runs\n // inside a `computePosition` callback, which is browser-only).\n const viewportHeight = floating.ownerDocument.defaultView?.innerHeight ?? 0;\n\n let y: number;\n if (target) {\n const optRect = target.getBoundingClientRect();\n const targetCenterRelToListbox = optRect.top - listboxRect.top + optRect.height / 2;\n const desiredY = triggerRect.top + triggerRect.height / 2 - targetCenterRelToListbox;\n const minY = padding;\n const maxY = viewportHeight - listboxRect.height - padding;\n y = maxY > minY ? Math.max(minY, Math.min(desiredY, maxY)) : minY;\n } else {\n y = Math.max(\n padding,\n Math.min(triggerRect.top, viewportHeight - listboxRect.height - padding),\n );\n }\n\n return { x: triggerRect.left, y };\n },\n };\n}\n\n/**\n * Item-aligned positioner for `[forSelectContent]` (the `position=\"item-aligned\"`\n * mode). The listbox overlays the trigger so the *selected option*'s center\n * lines up with the trigger's center on the cross axis — visually the menu\n * \"snaps over\" the trigger when opened, mirroring macOS native `<select>`\n * dropdowns.\n *\n * Owns:\n * 1. Optional portal — `appendChild` to `document.body` on first render,\n * `remove()` on destroy.\n * 2. A reactive effect that runs `autoUpdate(reference, listbox, …)` while\n * `open` is true. Inside, calls `computePosition` with the custom\n * `itemAligned` middleware and writes the resolved position via the\n * `translate` property (leaving `transform` free for the consumer),\n * `data-position=\"item-aligned\"`, anchor-width / anchor-height /\n * available-height CSS vars. On the first resolved position it drops the\n * `clip-path` hide baseline so the listbox is only painted once anchored.\n * 3. After the first position resolves, scrolls the target option into view\n * via `scrollIntoView({ block: 'nearest' })` so the visual anchor stays\n * correct when the listbox is taller than the viewport.\n *\n * `side`, `align`, `sideOffset`, `alignOffset`, `placement`, `flip`, `shift`,\n * and `arrow` are intentionally **not** part of this API — item-aligned mode\n * treats them as no-ops.\n */\nexport function injectItemAlignedPositioner(config: ItemAlignedConfig): void {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const el = host.nativeElement;\n\n if (config.portal !== false) {\n injectPortal();\n }\n\n afterNextRender(() => {\n // `clip-path: inset(50%)` keeps the listbox unpainted until the first\n // position resolves, so a CSS enter animation never flashes a frame at\n // the `left:0 / top:0` origin before the async `computePosition().then()`\n // writes the real `transform`. `clip-path` (not `visibility: hidden`)\n // keeps the element focusable so the overlay shell's initial-focus move\n // (selected option) still lands. Dropped on the first resolved position.\n Object.assign(el.style, {\n position: 'fixed',\n left: '0',\n top: '0',\n clipPath: 'inset(50%)',\n });\n });\n\n effect((onCleanup) => {\n const isOpen = config.open();\n const reference = config.reference();\n\n if (!isOpen || !reference) {\n return;\n }\n\n const collisionPadding = paddingTop(config.collisionPadding?.(), 8);\n\n // Re-arm the `clip-path: inset(50%)` baseline on every open effect run.\n // `onCleanup` now calls `resetItemAlignedStyles` which clears it, so\n // without re-arming a reopen / selection change would paint at the\n // previous frame's stale `translate` until `computePosition` re-resolves.\n el.style.clipPath = 'inset(50%)';\n\n let initialScrollDone = false;\n\n const cleanup = autoUpdate(reference, el, () => {\n computePosition(reference, el, {\n strategy: 'fixed',\n // Placement is irrelevant — `itemAligned` overrides x/y outright —\n // but `computePosition` requires *some* placement. Pick a stable one\n // so middleware data stays predictable.\n placement: 'bottom-start',\n middleware: [\n itemAligned(\n () => config.selectedOption(),\n () => collisionPadding,\n ),\n ],\n }).then(({ x, y }) => {\n if (!config.open()) {\n return;\n }\n\n // Position via the `translate` property (not `transform`) so a\n // consumer's enter animation on `scale` / `transform` pivots in place\n // instead of scaling the position offset — see the note in\n // `injectFloating`. Leaves `transform` free for the consumer.\n el.style.translate = `${Math.round(x)}px ${Math.round(y)}px`;\n el.dataset['position'] = 'item-aligned';\n // First valid position resolved — reveal the listbox by dropping the\n // `clip-path: inset(50%)` baseline.\n el.style.clipPath = '';\n\n const triggerRect = reference.getBoundingClientRect();\n el.style.setProperty('--for-anchor-width', `${Math.round(triggerRect.width)}px`);\n el.style.setProperty('--for-anchor-height', `${Math.round(triggerRect.height)}px`);\n\n const innerHeight = el.ownerDocument.defaultView?.innerHeight ?? 0;\n const availableHeight = Math.max(0, innerHeight - 2 * collisionPadding);\n el.style.setProperty(\n '--for-select-content-available-height',\n `${Math.round(availableHeight)}px`,\n );\n\n if (!initialScrollDone) {\n initialScrollDone = true;\n const target = config.selectedOption() ?? findFirstEnabledOption(el);\n // jsdom (test env) doesn't implement scrollIntoView — guard the\n // call so the helper stays usable in non-browser environments.\n target?.scrollIntoView?.({ block: 'nearest' });\n }\n });\n });\n\n // Clean up symmetrically with what computePosition wrote — mirrors\n // `injectFloating` — so a same-instance reopen doesn't inherit stale\n // `translate` / `--for-*` / `data-position` or a dropped anti-flash\n // baseline.\n onCleanup(() => {\n cleanup();\n resetItemAlignedStyles(el);\n });\n });\n}\n\n/**\n * Strip every inline style, CSS custom property, and `data-*` attribute\n * `injectItemAlignedPositioner` writes to the listbox (including the\n * `clip-path` hide baseline). Mirrors `resetFloatingStyles` in `floating.ts`\n * so a closed-then-reopened listbox starts from a clean slate — no leftover\n * `translate` jumping the next open, no stale `--for-*` poisoning size\n * styles, no orphaned `data-position`.\n */\nfunction resetItemAlignedStyles(el: HTMLElement): void {\n el.style.removeProperty('translate');\n el.style.removeProperty('clip-path');\n el.style.removeProperty('--for-anchor-width');\n el.style.removeProperty('--for-anchor-height');\n el.style.removeProperty('--for-select-content-available-height');\n el.removeAttribute('data-position');\n}\n","import { DestroyRef, ElementRef, inject, isDevMode, type Signal } from '@angular/core';\n\nimport { afterNextRenderCancellable } from '../after-next-render-cancellable/after-next-render-cancellable';\nimport {\n injectDismissableLayer,\n type DismissableLayerActivateOptions,\n} from '../dismissable-layer/dismissable-layer';\nimport { findFirstFocusable } from '../focus-trap/focus-trap';\nimport { injectFloating, type FloatingConfig } from '../floating/floating';\nimport { InertSiblingsStack, MODAL_PEER_ATTRIBUTE } from '../inert-siblings/inert-siblings';\nimport { injectItemAlignedPositioner, type ItemAlignedConfig } from '../floating/item-aligned';\nimport {\n createVetoableNativeEvent,\n type VetoableNativeEvent,\n} from '../vetoable-event/vetoable-event';\n\n/**\n * Tagged-union positioner config. The shell delegates to either\n * `injectFloating` (the standard anchored placement) or\n * `injectItemAlignedPositioner` (the macOS-style overlay used by Select's\n * `position=\"item-aligned\"` mode). Both helpers portal by default, so the\n * shell never calls `injectPortal` itself — that responsibility stays with\n * the positioner.\n */\nexport type OverlayShellPositionerConfig =\n | ({ readonly kind: 'floating' } & FloatingConfig)\n | ({ readonly kind: 'item-aligned' } & ItemAlignedConfig);\n\n/**\n * Dismissable-layer wiring. The shell owns the pointer/focus/interact veto\n * reuse that every trigger-anchored overlay (Popover, Menu / MenuSub /\n * ContextMenu / DropdownMenu, Combobox, Select, date-picker) used to\n * duplicate verbatim as a per-primitive `#pendingOutsideVeto` field:\n *\n * - The specific outside channels (pointer-down-outside / focus-outside) fire\n * on the same physical interaction as the composite `interactOutside`, and\n * the dismissable layer always invokes the specific listener first. The\n * shell builds a single `VetoableNativeEvent` on the specific call, hands it\n * to the consumer's emitter, and reuses it for the immediately-following\n * composite call so a `preventDefault()` from either handler vetoes the\n * close.\n * - When the consumer doesn't veto AND `dismissible()` is `true`, the shell\n * calls `requestClose(reason)` with the channel's reason\n * (`'pointerDownOutside' | 'focusOutside'`) from the composite handler.\n * `dismissible` / `requestClose` are required whenever any outside channel\n * is wired and unused otherwise.\n * - `exemptElements` is recomputed on every event so DOM mutations (newly\n * portaled siblings, swapped triggers) are picked up live.\n *\n * Escape stays a one-shot, consumer-owned channel (`emitEscapeKeyDown`\n * receives the raw `KeyboardEvent` and forwards verbatim to the layer): it\n * never participates in the shared `#pendingOutsideVeto` reuse, and its close\n * behaviour differs per primitive (hover-card schedules a close, the input-\n * focused combobox owns Escape on its input directive and omits it here). The\n * shell therefore leaves Escape's emit + close decision entirely to the\n * consumer.\n *\n * Each callback is individually optional so a primitive can opt out of a\n * single channel; the shell registers a layer listener only for the channels\n * the consumer actually forwards.\n */\nexport interface OverlayShellDismissConfig {\n /**\n * Whether an un-vetoed outside interaction fires the implicit\n * `requestClose`. Required when any outside channel\n * (`emitPointerDownOutside` / `emitFocusOutside` / `emitInteractOutside`)\n * is wired.\n */\n readonly dismissible?: Signal<boolean>;\n /**\n * Called with the matching reason when the consumer doesn't veto an outside\n * interaction. The consumer owns the close (and any bookkeeping such as\n * marking the control touched); the shell never touches the directive's\n * close output directly. Required alongside `dismissible`. The implicit close\n * fires from the composite `emitInteractOutside` channel only, so a wiring\n * that provides `requestClose` MUST also wire `emitInteractOutside` — the\n * shell throws a dev-mode error otherwise.\n */\n readonly requestClose?: (reason: 'pointerDownOutside' | 'focusOutside') => void;\n /** Forwards the raw Escape `KeyboardEvent` to the consumer; close is consumer-owned. */\n readonly emitEscapeKeyDown?: (event: KeyboardEvent) => void;\n /** Forwards the pointer-down-outside veto to the directive's `(pointerDownOutside)` output. */\n readonly emitPointerDownOutside?: (veto: VetoableNativeEvent<PointerEvent>) => void;\n /** Forwards the focus-outside veto to the directive's `(focusOutside)` output. */\n readonly emitFocusOutside?: (veto: VetoableNativeEvent<FocusEvent>) => void;\n /** Forwards the composite veto to the directive's `(interactOutside)` output. */\n readonly emitInteractOutside?: (veto: VetoableNativeEvent<PointerEvent | FocusEvent>) => void;\n /**\n * Extra elements whose subtrees count as \"inside\" for outside-pointer /\n * outside-focus checks (e.g. an anchored trigger that lives outside the\n * portaled content). Recomputed on every event so DOM mutations are\n * picked up.\n */\n readonly exemptElements?: () => readonly Element[];\n}\n\n/**\n * Where initial focus should land when the surface mounts.\n *\n * - `'first'` — first focusable descendant of the host (uses the shared\n * `findFirstFocusable` selector). Falls back to the host element itself.\n * - `'container'` — host element (gets `tabindex=\"-1\"` semantics from the\n * primitive's host bindings).\n * - `move()` — primitive-owned focus algorithm (e.g. Menu's\n * `focusFirstEnabledItem`, Select's `focusSelectedOption`). Should return\n * `true` on success and `false` if no candidate was found, so the shell can\n * fall back to focusing the host element.\n */\nexport type OverlayShellInitialFocusMove = 'first' | 'container' | (() => boolean);\n\n/**\n * Optional initial-focus wiring. Absent when the consumer wants focus to\n * stay where it is (Combobox keeps focus in the input; Tooltip / HoverCard\n * have no focus moves).\n *\n * `veto` corresponds to the `(autoFocusOnOpen)` output: returning `true`\n * skips the imperative focus move.\n */\nexport interface OverlayShellInitialFocusConfig {\n readonly move: OverlayShellInitialFocusMove;\n readonly veto?: () => boolean;\n}\n\n/**\n * Optional return-focus wiring. Absent when the consumer never wants to\n * return focus on destroy (Combobox closes back into the input via its own\n * keydown / blur paths; Tooltip / HoverCard are non-focusing).\n *\n * - `enabled` — the primitive's `[returnFocus]` input. When `false`, the\n * shell skips the return-focus call entirely.\n * - `target` — the element to focus on destroy (typically the trigger).\n * Returning `null` is a safe no-op (the trigger may have unmounted).\n * - `veto` — `(autoFocusOnClose)` veto. Returning `true` skips the focus\n * call.\n * - `skip` — additional opt-out. Used by Select to skip return-focus when\n * `lastCloseReason() === 'tab'` (Tab already moved focus to the trigger\n * and let the browser advance from there).\n */\nexport interface OverlayShellReturnFocusConfig {\n readonly enabled: Signal<boolean>;\n readonly target: () => HTMLElement | null;\n readonly veto?: () => boolean;\n readonly skip?: () => boolean;\n}\n\n/**\n * Single config for the overlay-content lifecycle. Each sub-bundle is\n * individually optional so the nine concrete primitives (Popover, Menu,\n * MenuSub, ContextMenu, DropdownMenu, Combobox, Select, Tooltip, HoverCard)\n * can opt in to only the pieces they need.\n *\n * The shell never reads any of the primitive's own context tokens — the\n * caller forwards each piece as plain signals / callbacks so the shell stays\n * orthogonal to the primitive surface and trivially mockable in tests.\n */\nexport interface OverlayShellConfig {\n readonly positioner: OverlayShellPositionerConfig;\n readonly dismiss?: OverlayShellDismissConfig;\n readonly initialFocus?: OverlayShellInitialFocusConfig;\n readonly returnFocus?: OverlayShellReturnFocusConfig;\n}\n\n/**\n * Single source of truth for the floating-overlay content lifecycle. Drives\n * every `*-content.ts` directive in the library that mounts a portaled\n * surface (`Popover`, `Menu` / `MenuSub` / `ContextMenu` via the shared\n * `[forMenuContent]`, `Combobox`, `Select`, `Tooltip`, `HoverCard`). The\n * shell owns:\n *\n * 1. Positioning. Delegates to `injectFloating` (default) or\n * `injectItemAlignedPositioner` (Select's `position=\"item-aligned\"`).\n * Both positioners portal by default, so the shell never calls\n * `injectPortal` itself — the consumer must NOT either, on pain of\n * double-portaling (see #106).\n * 2. Dismissable layer. When `dismiss` is configured, creates a layer for\n * the host element and activates it inside `afterNextRender`. The shell\n * owns the triple-veto + composite `interactOutside` bookkeeping: it\n * builds one `VetoableNativeEvent` per physical interaction and reuses it\n * across the specific (`pointerDownOutside` / `focusOutside`) and composite\n * (`interactOutside`) channels, so a `preventDefault()` from either\n * suppresses the implicit close. When the consumer doesn't veto and\n * `dismissible()` is `true`, the shell calls `requestClose(reason)`.\n * Deactivation runs from the shell's `DestroyRef.onDestroy` hook.\n * 3. Initial focus. When `initialFocus` is configured, runs `veto()` first;\n * if it returns truthy the imperative focus move is skipped (this is the\n * `(autoFocusOnOpen)` veto). Otherwise the shell either calls the\n * primitive-owned `move()` callback (Menu / Select), focuses the first\n * focusable descendant via the shared `findFirstFocusable` from\n * `focus-trap.ts` (Popover's `'first'` mode), or focuses the host\n * container directly (Popover's `'container'` mode). When the chosen\n * move returns `false` (no candidate), focus falls back to the host so\n * keyboard users always land somewhere predictable.\n * 4. Return focus. When `returnFocus` is configured and `enabled()` is true,\n * on destroy the shell consults `skip()` and `veto()` (`(autoFocusOnClose)`)\n * and, if neither vetoes, calls `target()?.focus()`.\n *\n * Destroy ordering matches the per-primitive code that this helper replaced.\n * Hooks fire in registration order: `injectDismissableLayer` runs first\n * (deactivate + remove from stack), then the positioner's portal helper\n * (`el.remove()`), and the return-focus hook is registered last so it runs\n * after the portaled DOM node is detached — the trigger receives the focus\n * event in a stable layout.\n *\n * Must be called from an injection context (typically the directive\n * constructor). Forwards the host's `ElementRef` to the dismissable layer\n * and the positioner; the consumer never has to touch them.\n *\n * @example\n * // Popover-content\n * injectOverlayShell({\n * positioner: { kind: 'floating', reference: ctx.reference, open: ctx.open, ... },\n * dismiss: {\n * dismissible: ctx.dismissible,\n * requestClose: () => ctx.open.set(false),\n * emitEscapeKeyDown: (event) => ctx.emitEscapeKeyDown(event),\n * emitPointerDownOutside: (veto) => ctx.pointerDownOutside.emit(veto),\n * emitFocusOutside: (veto) => ctx.focusOutside.emit(veto),\n * emitInteractOutside: (veto) => ctx.interactOutside.emit(veto),\n * exemptElements: () => (ctx.trigger() ? [ctx.trigger()!] : []),\n * },\n * initialFocus: {\n * move: ctx.initialFocus() === 'container' ? 'container' : 'first',\n * veto: () => ctx.emitAutoFocusOnOpen(),\n * },\n * returnFocus: {\n * enabled: ctx.returnFocus,\n * target: () => ctx.trigger(),\n * veto: () => ctx.emitAutoFocusOnClose(),\n * },\n * });\n */\nexport function injectOverlayShell(config: OverlayShellConfig): void {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const el = host.nativeElement;\n const inertStack = inject(InertSiblingsStack);\n\n // 1. Dismissable layer. Created BEFORE the positioner so its\n // `DestroyRef.onDestroy` (dismissable.deactivate) registers first and\n // therefore runs first on teardown — i.e. the layer is removed from\n // the stack before the positioner's portal removes the node from the\n // DOM. That ordering matches every pre-shell *-content directive and\n // avoids a window where a focusin fired during DOM removal could\n // route through `handleFocusIn` and trigger a spurious onFocusOutside.\n const dismissCfg = config.dismiss;\n const layer = dismissCfg !== undefined ? injectDismissableLayer() : null;\n\n // 2. Positioner. The kind is read once at construction; switching modes\n // at runtime would require unmounting + remounting the directive,\n // which is the expected pattern for primitives whose positioning\n // algorithm is structurally different (Select's two modes).\n if (config.positioner.kind === 'item-aligned') {\n const { kind: _ignored, ...rest } = config.positioner;\n injectItemAlignedPositioner(rest);\n } else {\n const { kind: _ignored, ...rest } = config.positioner;\n injectFloating(rest);\n }\n\n // 3. afterNextRender — activate the layer and run initial focus once\n // input bindings have settled. Both pieces depend on having a\n // fully-rendered host element (exempt-element queries, focus targets).\n // `afterNextRenderCancellable` makes the destroy-before-render path safe.\n // On the true-async path (queued render after destroy) the callback is\n // cancelled, so the dismissable layer is never pushed onto the stack. On\n // the synchronous-teardown path the callback flushes just before the\n // layer's own `DestroyRef.onDestroy` (registered above via\n // `injectDismissableLayer`, so it runs first among the destroy hooks),\n // which pops the just-pushed layer. Either way the stack is left without\n // a dead topmost entry that would swallow every later Escape /\n // pointer-down-outside.\n afterNextRenderCancellable(() => {\n // Modal-peer marking (#676). When this overlay is anchored to an element\n // inside an active modal's protected root — i.e. it was opened from inside\n // a Dialog / Drawer (a Select in a form, a context menu on dialog content)\n // — stamp the freshly portaled host so the inert-siblings pass / observer\n // skips it. Without this the body-level inert sweep swallows forty's own\n // overlay, leaving it painted (z-index) but `inert` + `aria-hidden`: clicks\n // fall through to the controls behind it and the surface reads as hidden to\n // assistive tech (#676). `ownsAnchor` returns false when no modal is active,\n // so an overlay with no surrounding modal is never pre-marked (a modal\n // opened later inerts it like any background sibling), and false when the\n // anchor sits in an inerted background subtree, so a toast / background\n // overlay stays isolated (#388 semantics). The positioner's portal ran in\n // an earlier hook of this same render batch, so the host is already in\n // `body`; the attribute is set before the observer's microtask runs, so the\n // host is flagged by the time the observer inspects it.\n const anchor = resolveModalAnchor(config);\n if (anchor && inertStack.ownsAnchor(anchor)) {\n el.setAttribute(MODAL_PEER_ATTRIBUTE, '');\n }\n\n if (layer && dismissCfg) {\n // Pointer-down-outside and focus-outside both fire on the same physical\n // interaction as the composite `interactOutside`, and the dismissable\n // layer always invokes the specific listener before the composite one.\n // We build a single veto wrapper on the specific call and reuse it for\n // the composite call, so a `preventDefault()` in either handler vetoes\n // the close. Escape never enters this reuse — it is a one-shot,\n // consumer-owned channel forwarded verbatim below.\n let pendingOutsideVeto: VetoableNativeEvent<PointerEvent | FocusEvent> | null = null;\n const requestClose = dismissCfg.requestClose;\n const dismissible = dismissCfg.dismissible;\n const options: DismissableLayerActivateOptions = {};\n\n // The implicit outside-close fires from the composite `onInteractOutside`\n // handler only (the specific pointer/focus handlers just emit). A wiring\n // that provides `requestClose` but omits `emitInteractOutside` would emit\n // its outside outputs yet never close — fail loudly in dev rather than\n // ship that silent gap.\n if (isDevMode() && requestClose && !dismissCfg.emitInteractOutside) {\n throw new Error(\n '[forty-cdk/overlay-shell] dismiss.requestClose requires dismiss.emitInteractOutside to be wired; the implicit outside-close fires from the composite interactOutside channel.',\n );\n }\n\n if (dismissCfg.exemptElements) {\n options.exemptElements = dismissCfg.exemptElements;\n }\n // Escape: forwarded verbatim. The consumer owns the emit + close\n // decision (combobox routes it through its input directive instead and\n // omits this channel; hover-card schedules a timed close).\n if (dismissCfg.emitEscapeKeyDown) {\n options.onEscapeKeyDown = dismissCfg.emitEscapeKeyDown;\n }\n if (dismissCfg.emitPointerDownOutside) {\n const emit = dismissCfg.emitPointerDownOutside;\n options.onPointerDownOutside = (event) => {\n pendingOutsideVeto = createVetoableNativeEvent<PointerEvent | FocusEvent>(event);\n emit(pendingOutsideVeto as VetoableNativeEvent<PointerEvent>);\n };\n }\n if (dismissCfg.emitFocusOutside) {\n const emit = dismissCfg.emitFocusOutside;\n options.onFocusOutside = (event) => {\n pendingOutsideVeto = createVetoableNativeEvent<PointerEvent | FocusEvent>(event);\n emit(pendingOutsideVeto as VetoableNativeEvent<FocusEvent>);\n };\n }\n if (dismissCfg.emitInteractOutside) {\n const emit = dismissCfg.emitInteractOutside;\n options.onInteractOutside = (event) => {\n const veto =\n pendingOutsideVeto ?? createVetoableNativeEvent<PointerEvent | FocusEvent>(event);\n pendingOutsideVeto = null;\n emit(veto);\n if (!veto.defaultPrevented && dismissible?.() && requestClose) {\n requestClose(event.type === 'pointerdown' ? 'pointerDownOutside' : 'focusOutside');\n }\n };\n }\n\n layer.activate(options);\n }\n\n const focusCfg = config.initialFocus;\n if (focusCfg) {\n // Veto first — the `(autoFocusOnOpen)` output's `preventDefault`\n // returns true here, mirroring what the per-primitive code did.\n if (focusCfg.veto?.()) {\n return;\n }\n const move = focusCfg.move;\n if (move === 'first') {\n (findFirstFocusable(el) ?? el).focus();\n } else if (move === 'container') {\n el.focus();\n } else {\n // Primitive-owned focus algorithm (Menu's first/last item, Select's\n // selected option, etc.). Returns true on success; on miss we fall\n // back to the host so keyboard users land somewhere predictable.\n const moved = move();\n if (!moved) {\n el.focus();\n }\n }\n }\n });\n\n // 4. Return focus on destroy. The hook is registered AFTER the layer's\n // destroy hook (created above) and AFTER the positioner's portal hook\n // (created inside injectFloating / injectItemAlignedPositioner) so it\n // runs last — same ordering as the pre-shell hand-rolled code.\n const rfCfg = config.returnFocus;\n if (rfCfg) {\n inject(DestroyRef).onDestroy(() => {\n if (rfCfg.skip?.()) {\n return;\n }\n if (rfCfg.veto?.()) {\n return;\n }\n if (!rfCfg.enabled()) {\n return;\n }\n rfCfg.target()?.focus();\n });\n }\n}\n\n/**\n * Resolve the real DOM element an overlay is anchored to, for the modal-peer\n * ownership check (#676). Most overlays anchor to a real element (the trigger\n * button / input), exposed directly via the positioner `reference`.\n * Pointer-positioned overlays (ContextMenu) anchor to a floating-ui\n * `VirtualElement`: we read its `contextElement` when present, then fall back\n * to the return-focus target — the logical trigger the overlay was opened\n * from, which for ContextMenu is the registered right-click region. Returns\n * `null` when no backing element can be found (the overlay is then never\n * marked, falling back to the pre-#676 behaviour for that surface).\n */\nfunction resolveModalAnchor(config: OverlayShellConfig): Element | null {\n const ref = config.positioner.reference();\n if (ref instanceof Element) {\n return ref;\n }\n const contextElement = ref?.contextElement;\n if (contextElement instanceof Element) {\n return contextElement;\n }\n return config.returnFocus?.target() ?? null;\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/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 must include it.\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 — not re-exported from `public-api.ts`.\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 */\nexport function injectPauseController<R extends string>(\n options: PauseControllerOptions = {},\n): PauseController<R> {\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","import type { FloatingSide } from '../floating/floating';\n\n/**\n * Pointer-grace (\"safe triangle\") helper.\n *\n * When a mouse leaves a submenu trigger heading toward the submenu content,\n * a naive \"close on pointer-leave\" would dismiss the submenu the moment the\n * cursor crosses the gap between the trigger and the content. The fix native\n * desktop menus use is a *safe triangle*: a polygon drawn\n * from the cursor's exit point to the near edge of the submenu content. While\n * the pointer stays inside that polygon it is assumed to be travelling toward\n * the submenu, so the close is held off.\n *\n * This module keeps no Angular DI surface — the geometry is pure functions\n * (unit-tested in `pointer-grace.spec.ts`) and {@link attachPointerGrace} is a\n * plain `addEventListener` wrapper returning a cleanup, wired by the directive\n * through its `DestroyRef`. The DOM-measured inputs (cursor position, content\n * rect, resolved side) are supplied by the caller, so the geometry stays\n * testable without faking layout.\n */\n\n/** A point in client (viewport) coordinates. */\nexport interface Point {\n readonly x: number;\n readonly y: number;\n}\n\n/** The subset of `DOMRect` the grace polygon needs. */\nexport interface GraceRect {\n readonly top: number;\n readonly right: number;\n readonly bottom: number;\n readonly left: number;\n}\n\n/**\n * Resolves which side a submenu actually rendered on by comparing the\n * geometry of the trigger and content rects, independent of any requested\n * placement. Picks the axis (horizontal vs vertical) with the larger\n * centre-to-centre separation, then the direction along it.\n *\n * This is the load-bearing fix for the safe-triangle: `injectFloating` only\n * writes the resolved `data-side` inside the async `computePosition().then()`,\n * so on the first hover-open it is still `undefined` and a `flip` near a\n * viewport edge would have armed the grace polygon toward the *requested*\n * side. Deriving the side from the live rects at arm time reflects the real\n * placement even before positioning settles.\n *\n * @param trigger Sub-trigger rect (client coords), from `getBoundingClientRect`.\n * @param content Submenu content rect (client coords), from `getBoundingClientRect`.\n */\nexport function resolveGraceSide(trigger: GraceRect, content: GraceRect): FloatingSide {\n const triggerCenterX = (trigger.left + trigger.right) / 2;\n const triggerCenterY = (trigger.top + trigger.bottom) / 2;\n const contentCenterX = (content.left + content.right) / 2;\n const contentCenterY = (content.top + content.bottom) / 2;\n const dx = contentCenterX - triggerCenterX;\n const dy = contentCenterY - triggerCenterY;\n if (Math.abs(dx) >= Math.abs(dy)) {\n return dx >= 0 ? 'right' : 'left';\n }\n return dy >= 0 ? 'bottom' : 'top';\n}\n\n/** An ordered list of vertices describing a simple (non-self-intersecting) polygon. */\nexport type Polygon = readonly Point[];\n\n/**\n * Pixels the cursor apex is pulled *back* (away from the content) when the\n * polygon is built, so the exit point sits reliably inside the polygon even\n * after sub-pixel rounding of the pointer-leave coordinates.\n */\nconst GRACE_BLEED_PX = 5;\n\n/**\n * Standard even-odd ray-casting point-in-polygon test. Returns `true` when\n * {@link point} lies inside {@link polygon}. Points exactly on an edge are\n * reported inconsistently (as with any ray-cast) — that is acceptable here\n * because the bleed keeps the cursor apex strictly inside and the close path\n * is delay-guarded, so a single ambiguous edge sample never decides the\n * outcome.\n */\nexport function isPointInPolygon(point: Point, polygon: Polygon): boolean {\n let inside = false;\n for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {\n const vi = polygon[i];\n const vj = polygon[j];\n const intersects =\n vi.y > point.y !== vj.y > point.y &&\n point.x < ((vj.x - vi.x) * (point.y - vi.y)) / (vj.y - vi.y) + vi.x;\n if (intersects) {\n inside = !inside;\n }\n }\n return inside;\n}\n\n/**\n * Builds the safe-triangle polygon for a submenu opening on {@link side}.\n *\n * The polygon is a pentagon: the (bleeded) cursor apex plus the four corners\n * of the content rect, ordered so the cursor is adjacent to the two corners of\n * the content edge *nearest* the trigger. That shape covers both the triangle\n * the pointer travels through and the content itself, so the pointer is \"in\n * the grace area\" right up until it reaches the content.\n *\n * @param cursor Pointer position (client coords) captured at pointer-leave.\n * @param rect Submenu content rect (client coords), from `getBoundingClientRect`.\n * @param side Resolved side the content actually rendered on, from {@link resolveGraceSide}.\n */\nexport function buildSubmenuGracePolygon(\n cursor: Point,\n rect: GraceRect,\n side: FloatingSide,\n): Polygon {\n const { top, right, bottom, left } = rect;\n switch (side) {\n // Content to the right; near edge = content's left edge.\n case 'right':\n return [\n { x: cursor.x - GRACE_BLEED_PX, y: cursor.y },\n { x: left, y: top },\n { x: right, y: top },\n { x: right, y: bottom },\n { x: left, y: bottom },\n ];\n // Content to the left; near edge = content's right edge.\n case 'left':\n return [\n { x: cursor.x + GRACE_BLEED_PX, y: cursor.y },\n { x: right, y: top },\n { x: left, y: top },\n { x: left, y: bottom },\n { x: right, y: bottom },\n ];\n // Content below; near edge = content's top edge.\n case 'bottom':\n return [\n { x: cursor.x, y: cursor.y - GRACE_BLEED_PX },\n { x: left, y: top },\n { x: left, y: bottom },\n { x: right, y: bottom },\n { x: right, y: top },\n ];\n // Content above; near edge = content's bottom edge.\n case 'top':\n return [\n { x: cursor.x, y: cursor.y + GRACE_BLEED_PX },\n { x: left, y: bottom },\n { x: left, y: top },\n { x: right, y: top },\n { x: right, y: bottom },\n ];\n }\n}\n\n/**\n * Attaches a document-level `pointermove` listener that calls {@link onExit}\n * the first time the mouse leaves {@link polygon}. The caller arms this on a\n * trigger pointer-leave and disarms it (via the returned cleanup) once the\n * pointer reaches the content, the grace window elapses, or the submenu is\n * otherwise resolved.\n *\n * Touch / pen moves are ignored — the safe triangle models a hovering mouse;\n * touch interaction opens submenus by tap, never by hover.\n *\n * Static-polygon assumption: {@link polygon} is captured once at arm time and\n * never re-measured for the lifetime of this listener. If the submenu content\n * repositions (a flip, a scroll, a resize) while the grace window is open, the\n * polygon goes stale and no longer matches the content's live rect. This is an\n * accepted trade-off: the grace window is short (a single pointer traversal\n * from trigger to content) and is itself delay-guarded downstream, so a\n * mid-window reposition is out of scope. Callers that need re-measurement\n * should re-arm (call the cleanup, then re-attach with a fresh polygon) rather\n * than expecting this handler to track layout.\n *\n * @returns A cleanup that removes the listener. Idempotent-safe to store and\n * call once from a `DestroyRef` hook.\n */\nexport function attachPointerGrace(\n doc: Document,\n polygon: Polygon,\n onExit: () => void,\n): () => void {\n const onMove = (event: PointerEvent): void => {\n if (event.pointerType !== '' && event.pointerType !== 'mouse') {\n return;\n }\n if (!isPointInPolygon({ x: event.clientX, y: event.clientY }, polygon)) {\n onExit();\n }\n };\n doc.addEventListener('pointermove', onMove);\n return () => doc.removeEventListener('pointermove', onMove);\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 { clamp } from '../numeric-step/numeric-step';\n\nexport { roundToStepPrecision } from '../numeric-step/numeric-step';\n\n/** Pointer travel (px) required before a resize drag starts mutating the value. */\nexport const DRAG_DEAD_ZONE_PX = 3;\n\n/** Clamps `value` into the inclusive `[min, max]` range. */\nexport function clampToRange(value: number, min: number, max: number): number {\n return clamp(value, min, max);\n}\n\n/** Configuration for {@link startPointerResize}. */\nexport interface PointerResizeConfig {\n /** Element that captures the pointer and receives the move / up / cancel listeners. */\n readonly host: HTMLElement;\n /** Axis the drag reads: `'x'` uses `clientX`, `'y'` uses `clientY`. */\n readonly axis: 'x' | 'y';\n /** Value at gesture start; raw pixel deltas are added to this. */\n readonly startValue: number;\n /** When `true`, the pixel delta sign is inverted (RTL on the `x` axis). */\n readonly invert: boolean;\n /** Maps a raw candidate value to its constrained value (clamp / round). */\n readonly constrain: (next: number) => number;\n /** Called with the new constrained value on every armed move that changes it. */\n readonly onResize: (value: number) => void;\n /**\n * Called once at gesture end (pointer-up / cancel) with the final value, but only\n * if the drag armed (crossed the dead-zone). A plain click never commits.\n */\n readonly onCommit: (value: number) => void;\n}\n\n/**\n * Starts a pointer-capture resize drag from a `pointerdown` event. Owns the\n * pointer-capture lifecycle, the dead-zone arming (a sub-threshold move never\n * mutates the value, so a jittery click is a no-op), the axis delta math with\n * optional RTL inversion, and the commit-once-on-release contract.\n *\n * Returns a teardown that detaches all listeners and releases the capture — call\n * it from the host's `DestroyRef` to clean up a drag interrupted by destruction.\n */\nexport function startPointerResize(event: PointerEvent, config: PointerResizeConfig): () => void {\n const { host, axis } = config;\n const startCoord = axis === 'x' ? event.clientX : event.clientY;\n let current = config.startValue;\n let armed = false;\n let active = true;\n\n function onMove(move: PointerEvent): void {\n if (!active) {\n return;\n }\n const raw = axis === 'x' ? move.clientX : move.clientY;\n let delta = raw - startCoord;\n if (!armed) {\n if (Math.abs(delta) < DRAG_DEAD_ZONE_PX) {\n return;\n }\n armed = true;\n }\n if (config.invert) {\n delta = -delta;\n }\n const next = config.constrain(config.startValue + delta);\n if (next === current) {\n return;\n }\n current = next;\n config.onResize(next);\n }\n\n function onUp(up: PointerEvent): void {\n if (!active) {\n return;\n }\n active = false;\n host.removeEventListener('pointermove', onMove);\n host.removeEventListener('pointerup', onUp);\n host.removeEventListener('pointercancel', onUp);\n if (host.hasPointerCapture(up.pointerId)) {\n host.releasePointerCapture(up.pointerId);\n }\n if (armed) {\n config.onCommit(current);\n }\n }\n\n host.setPointerCapture(event.pointerId);\n host.addEventListener('pointermove', onMove);\n host.addEventListener('pointerup', onUp);\n host.addEventListener('pointercancel', onUp);\n\n return () => {\n if (!active) {\n return;\n }\n active = false;\n host.removeEventListener('pointermove', onMove);\n host.removeEventListener('pointerup', onUp);\n host.removeEventListener('pointercancel', onUp);\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 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 { effect, type Signal } from '@angular/core';\n\nimport type { HostRovingItemHandle } from './host-roving-context';\nimport type { RovingTabindex } from './roving-tabindex';\n\n/**\n * Reactively reset a {@link RovingTabindex} active pointer when the active\n * host leaves the group's usable set — it unregisters, becomes disabled, or\n * detaches from the document. Nulling the pointer lets each item's\n * first-enabled fallback re-engage so the group keeps exactly one tab stop\n * after a routine UI op (remove the focused item, disable it, filter a\n * dynamic list).\n *\n * Pairs with {@link RovingTabindex.unregister} (the deterministic teardown\n * path): this effect covers the runtime-disable case, where the host stays\n * registered but should no longer own the tab stop.\n *\n * Must be called in an injection context (a container directive's field\n * initializer or constructor) — internally calls `effect`.\n *\n * @param roving The tracker to reconcile.\n * @param items Reactive list of the group's registered handles (typically\n * `Collection.items()`); each must expose `host` and a `disabled` signal.\n */\nexport function reconcileRovingActive(\n roving: RovingTabindex,\n items: Signal<readonly HostRovingItemHandle[]>,\n): void {\n effect(() => {\n const active = roving.active();\n if (active === null) {\n return;\n }\n const handle = items().find((item) => item.host === active);\n if (!handle || handle.disabled() || !active.isConnected) {\n roving.setActive(null);\n }\n });\n}\n","import { computed, type Signal, signal } from '@angular/core';\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 deliberately 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**: a stale active element — one that\n * has detached from the document, or carries `disabled` / `aria-disabled`\n * (every primitive reflects its disabled state to one of those attributes) —\n * is treated as \"no active\", so the consumer's first-enabled fallback\n * re-engages and the group keeps exactly one tab stop. This guards the\n * single-frame window before the container's reconciliation nulls the\n * pointer; containers should still call {@link unregister} on teardown and\n * reconcile against their visible set for a clean, reactive reset.\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 #active = signal<HTMLElement | null>(null);\n\n /**\n * The raw active element, or `null`. Reflects the last {@link setActive}\n * call verbatim, including a now-stale element — use it for \"is this the\n * focused candidate\" styling (`data-highlighted`). For the tab-stop gate,\n * prefer {@link hasActive}, which discounts a stale active.\n */\n readonly active: Signal<HTMLElement | null> = this.#active.asReadonly();\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> = computed(() => {\n const el = this.#active();\n return el !== null && !isStale(el);\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.#active.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.#active.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.#active.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 type { SwipeDirection } from '../swipe-dismiss/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","import { isSignal, type Signal, signal, type WritableSignal } from '@angular/core';\n\n/** Options for {@link SelectionModel}. */\nexport interface SelectionModelOptions<T> {\n /**\n * Allow more than one selected value. `false` (default) is single-select:\n * `select` / `setSelection` replace the prior value. Accepts a `Signal` so a\n * consumer whose mode is reactive (e.g. a table's `selectionMode`) can drive\n * it without reconstructing the model.\n */\n readonly multiple?: boolean | Signal<boolean>;\n /**\n * Equality comparator used for membership and de-duplication. Defaults to\n * `===` (correct for primitive values); supply an id-based comparator for\n * object values: `(a, b) => a.id === b.id`.\n */\n readonly compareWith?: (a: T, b: T) => boolean;\n}\n\n/**\n * Signal-first selection state shared across primitives (table rows today;\n * listbox / tree can converge later). Single- or multi-select, equality-aware\n * membership, and `added` / `removed` deltas from the last mutation. Every\n * mutating method returns whether the selection actually changed.\n *\n * The model does **not** own its backing store: callers pass a\n * `WritableSignal<readonly T[]>` (typically their own `model()`), so there is a\n * single source of truth and no `effect()`-based sync. `selected` is a readonly\n * view of that source; mutators write through it.\n */\nexport class SelectionModel<T> {\n readonly #source: WritableSignal<readonly T[]>;\n readonly #multiple: Signal<boolean>;\n readonly #compareWith: (a: T, b: T) => boolean;\n\n readonly #added = signal<readonly T[]>([]);\n readonly #removed = signal<readonly T[]>([]);\n\n /** The current selection, in insertion order. Readonly view of the backing source. */\n readonly selected: Signal<readonly T[]>;\n /** Values added by the most recent mutation through this model. */\n readonly added: Signal<readonly T[]> = this.#added.asReadonly();\n /** Values removed by the most recent mutation through this model. */\n readonly removed: Signal<readonly T[]> = this.#removed.asReadonly();\n\n constructor(source: WritableSignal<readonly T[]>, options?: SelectionModelOptions<T>) {\n this.#source = source;\n this.selected = source.asReadonly();\n const multiple = options?.multiple ?? false;\n this.#multiple = isSignal(multiple) ? multiple : signal(multiple);\n this.#compareWith = options?.compareWith ?? ((a, b) => a === b);\n }\n\n /** Whether `value` is currently selected (under the comparator). */\n isSelected(value: T): boolean {\n return this.#has(this.#source(), value);\n }\n\n /**\n * Select `values`. In single mode keeps only the last given value; in multi\n * mode appends those not already present. Returns whether anything changed.\n */\n select(...values: T[]): boolean {\n if (values.length === 0) {\n return false;\n }\n if (!this.#multiple()) {\n return this.#commit([values[values.length - 1]!]);\n }\n const next = [...this.#source()];\n for (const v of values) {\n if (!this.#has(next, v)) {\n next.push(v);\n }\n }\n return this.#commit(next);\n }\n\n /** Deselect `values`. Returns whether anything changed. */\n deselect(...values: T[]): boolean {\n if (values.length === 0) {\n return false;\n }\n const next = this.#source().filter((v) => !values.some((d) => this.#compareWith(v, d)));\n return this.#commit(next);\n }\n\n /** Toggle a single value. Returns whether anything changed (always `true`). */\n toggle(value: T): boolean {\n return this.isSelected(value) ? this.deselect(value) : this.select(value);\n }\n\n /**\n * Replace the entire selection with `values` (de-duplicated). In single mode\n * keeps only the last. Returns whether anything changed.\n */\n setSelection(...values: T[]): boolean {\n if (!this.#multiple() && values.length > 1) {\n return this.#commit([values[values.length - 1]!]);\n }\n const next: T[] = [];\n for (const v of values) {\n if (!this.#has(next, v)) {\n next.push(v);\n }\n }\n return this.#commit(next);\n }\n\n /** Clear the selection. Returns whether anything changed. */\n clear(): boolean {\n return this.#commit([]);\n }\n\n #has(arr: readonly T[], value: T): boolean {\n return arr.some((x) => this.#compareWith(x, value));\n }\n\n #commit(next: readonly T[]): boolean {\n const current = this.#source();\n const added = next.filter((v) => !this.#has(current, v));\n const removed = current.filter((v) => !this.#has(next, v));\n if (added.length === 0 && removed.length === 0) {\n return false;\n }\n this.#added.set(added);\n this.#removed.set(removed);\n this.#source.set(next);\n return true;\n }\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. Other\n * array-backed primitives keep their own selection/expansion logic — `ForTree`\n * (string-keyed select / expand / extend-by-arrow), `Accordion`, and\n * `ToggleGroup` all manage their arrays directly rather than routing through\n * here, because their value semantics (string keys, no equality comparator, no\n * single-mode `T | null` view) differ. Treat this module as \"the\n * Select/Listbox/Combobox helper set\", not \"the library's one true selection\n * source\".\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","/**\n * Whether `error` is the NG0950 `RuntimeError(-950)` Angular throws when an\n * `input.required` is read before its binding is written. Detected via the\n * stable numeric `code` rather than the message text (stripped in production\n * builds). Returns `false` for any other throw, including non-`Error` values.\n */\nexport function isRequiredInputUnset(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n const code = (error as Error & { code?: unknown }).code;\n return typeof code === 'number' && Math.abs(code) === 950;\n}\n\n/**\n * Read a handle's inputs inside a snapshot fold, tolerating the NG0950 thrown\n * while a statically-rendered option is in the gap between registering (its\n * constructor, during the content view's *creation* pass) and having its\n * `input.required` binding written (that view's *update* pass). A fold-priming\n * effect flush runs in that gap, so a static option above a `@for` list would\n * otherwise hard-crash on open.\n *\n * Returns `null` in that window; the caller skips the handle for this fold. The\n * required-input signal's producer is accessed *before* the read throws, so the\n * dependency is still tracked: writing the binding marks the fold's\n * `linkedSignal` dirty and it re-runs, folding the handle in once its value is\n * set. Any non-NG0950 error propagates unchanged.\n */\nexport function tryReadHandle<R>(read: () => R): R | null {\n try {\n return read();\n } catch (error) {\n if (isRequiredInputUnset(error)) {\n return null;\n }\n throw error;\n }\n}\n","/**\n * Resolved snap target. The caller decides what to do with it: either close\n * the drawer (`willClose: true`) or transition to `nextSnapPoint` and update\n * the consumer's `[(activeSnapPoint)]`.\n */\nexport interface SnapResolution<S> {\n readonly willClose: boolean;\n /** The snap point to transition to. `null` when `willClose` is `true`. */\n readonly nextSnapPoint: S | null;\n}\n\nexport interface ResolveSnapTargetOptions<S> {\n /**\n * The snap points provided by the consumer, in the order they appear in\n * the input array (low → high — i.e. closest-to-anchor → furthest-from-anchor).\n * Each entry corresponds 1:1 with an entry in {@link snapPositions}.\n */\n readonly snapPoints: ReadonlyArray<S>;\n /**\n * The pixel position (along the dismissal axis, measured from the anchored\n * edge) of each snap point. Same length and ordering as {@link snapPoints}.\n * Computed from the live drawer dimension and the snap-point semantics by\n * the caller.\n */\n readonly snapPositions: ReadonlyArray<number>;\n /** The currently-active snap point. Match the elements of `snapPoints` by reference. */\n readonly activeSnapPoint: S | null;\n /**\n * Final pointer position along the dismissal axis, measured from the\n * anchored edge in CSS pixels. Larger means further from the edge.\n */\n readonly position: number;\n /**\n * Pointer velocity at release in CSS pixels per millisecond, signed so\n * positive == moving away from the anchored edge (i.e. toward larger\n * `position`). The threshold for \"fast flick\" is hard-coded to\n * `0.4` px/ms inside the helper.\n */\n readonly velocity: number;\n /**\n * Fraction of the **lowest snap point's** extent past which a\n * release from that snap dismisses the drawer. Default `0.25` — a release\n * that has dragged more than 25% of the lowest snap's size past it (toward\n * the edge) closes. Measuring against the lowest snap rather than the full\n * drawer dimension keeps dismissal reachable when the lowest snap is a\n * small \"peek\" relative to the full surface.\n */\n readonly closeThreshold: number;\n}\n\nconst VELOCITY_THRESHOLD_PX_PER_MS = 0.4;\n\n/**\n * Pure function that picks the snap target for a release gesture, combining\n * the final pointer position with the gesture velocity. Pulled into\n * `_internal/` so the Drawer directive doesn't have to embed the algorithm\n * (which is mildly involved and well-tested in isolation).\n *\n * Algorithm:\n *\n * 1. Pick the snap point with `snapPositions[i]` closest to `position`.\n * 2. If the velocity is fast enough (`|velocity| >= 0.4 px/ms`), bias one\n * step in the velocity direction. Negative velocity = toward edge,\n * positive = away from edge. Clamped at the array bounds.\n * 3. If the chosen target is the closest-to-edge snap point AND the gesture\n * ended *past* (closer to the edge than) that snap by more than\n * `closeThreshold` of the lowest snap's own extent, return\n * `willClose: true`. Scaling by the lowest snap rather than the full\n * drawer dimension keeps a small \"peek\" snap dismissable without having\n * to drag it entirely off-screen.\n *\n * Snap points are passed by the caller already converted to pixel positions\n * (`snapPositions`); the algorithm does not know whether they came from a\n * fraction, percentage string, or pixel string.\n *\n * Contract: callers must guard `snapPoints.length > 0` before calling this —\n * the no-snap-points dismissal is owned entirely by the caller (the Drawer\n * computes it directly from its drag offset and `closeThreshold`), so the\n * helper does not duplicate that branch with a second, inconsistent threshold\n * formula. Passing an empty `snapPoints` throws.\n */\nexport function resolveSnapTarget<S>(opts: ResolveSnapTargetOptions<S>): SnapResolution<S> {\n const { snapPoints, snapPositions, activeSnapPoint, position, velocity } = opts;\n if (snapPositions.length !== snapPoints.length) {\n throw new Error(\n '[forty-cdk/snap-points] resolveSnapTarget: snapPoints and snapPositions must have the same length.',\n );\n }\n if (snapPoints.length === 0) {\n throw new Error(\n '[forty-cdk/snap-points] resolveSnapTarget: requires at least one snap point; callers must guard snapPoints.length > 0 (the no-snap-points dismissal is the caller’s responsibility).',\n );\n }\n\n // 1) Closest snap by position.\n let closestIdx = 0;\n let closestDist = Math.abs(snapPositions[0]! - position);\n for (let i = 1; i < snapPositions.length; i++) {\n const dist = Math.abs(snapPositions[i]! - position);\n if (dist < closestDist) {\n closestDist = dist;\n closestIdx = i;\n }\n }\n\n // 2) Velocity bias. The active snap point is the anchor for the velocity\n // step — bias relative to where the user *was* before the gesture,\n // not relative to the geometric closest. Falls back to closestIdx if the\n // active is unknown.\n const activeIdx = activeSnapPoint != null ? snapPoints.indexOf(activeSnapPoint) : -1;\n const anchorIdx = activeIdx >= 0 ? activeIdx : closestIdx;\n\n let targetIdx = closestIdx;\n if (Math.abs(velocity) >= VELOCITY_THRESHOLD_PX_PER_MS) {\n if (velocity < 0) {\n // Fast move toward edge — bias one snap closer.\n targetIdx = Math.max(0, anchorIdx - 1);\n } else {\n // Fast move away from edge — bias one snap further.\n targetIdx = Math.min(snapPoints.length - 1, anchorIdx + 1);\n }\n }\n\n // 3) Dismiss check: only the closest-to-edge snap (index 0) gates dismissal.\n // Position past the threshold (i.e. closer to the edge) means the user\n // has dragged the drawer far enough off-screen to count as a dismiss.\n if (targetIdx === 0) {\n const lowestPos = snapPositions[0]!;\n const dismissThreshold = lowestPos * (1 - opts.closeThreshold);\n if (position < dismissThreshold) {\n return { willClose: true, nextSnapPoint: null };\n }\n }\n\n return { willClose: false, nextSnapPoint: snapPoints[targetIdx] ?? null };\n}\n","/**\n * Pointer-based swipe-to-dismiss helper.\n *\n * Used by `ForToast` (and any future primitive that wants swipe-to-dismiss\n * semantics: a horizontal/vertical drag that, when released past\n * the configured threshold, triggers a dismissal).\n *\n * The helper keeps no Angular DI surface — it's a plain function that\n * attaches pointer listeners to an `HTMLElement` and returns a cleanup\n * function. Callers wire it through the directive's `DestroyRef`.\n *\n * Behavior summary:\n * - On `pointerdown` the start position is recorded but no swipe is\n * announced yet. This avoids fake start/cancel pairs on plain clicks.\n * A second `pointerdown` while a pointer is already tracked is ignored,\n * so the first pointer keeps its capture and its `pointerup` still ends\n * the gesture (no orphaned capture on multi-touch).\n * - On `pointermove` the helper waits until the drag exceeds an internal\n * \"arm\" distance (a few pixels), picks the dominant axis, and decides\n * the candidate direction. If that direction is not in the allowed\n * set the gesture is dropped silently.\n * - Once armed, `onSwipeStart` fires (with the constrained delta) and\n * `onSwipeMove` fires for every subsequent move including the arming\n * one. Pointer capture is requested so events keep flowing if the\n * pointer leaves the element. `getDirections()` is re-read on every\n * armed move: if the active direction is toggled out of the allowed\n * set mid-gesture, the swipe is aborted (`onSwipeCancel` fires and the\n * captured pointer is released).\n * - On `pointerup`, if the projection along the active direction\n * reaches `getThreshold()`, `onSwipeEnd` fires; otherwise\n * `onSwipeCancel` fires.\n * - On `pointercancel`, `onSwipeCancel` always fires.\n * - `pointerup`, `pointercancel`, mid-gesture abort, and cleanup all\n * release the requested pointer capture symmetrically.\n *\n * Movement perpendicular to the active direction is clamped to `0`,\n * and movement opposite to the direction is clamped to `0` as well —\n * the consumer's CSS only ever sees a non-negative push along the\n * dismissal axis, so animations stay simple.\n */\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 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 * Attach swipe-dismiss listeners to `opts.element`. Returns a cleanup\n * function that removes every listener and releases pointer capture.\n *\n * @throws never. Capture / release calls are wrapped in try/catch so\n * environments without `PointerCapture` (jsdom) don't break.\n */\nexport function attachSwipeDismiss(opts: SwipeDismissOptions): () => void {\n const el = opts.element;\n let active = false;\n let direction: SwipeDirection | null = null;\n let pointerId: number | null = null;\n let startX = 0;\n let startY = 0;\n\n const reset = (): void => {\n active = false;\n direction = null;\n pointerId = null;\n };\n\n const releaseCapture = (id: number): void => {\n try {\n if (el.hasPointerCapture?.(id)) {\n el.releasePointerCapture?.(id);\n }\n } catch {\n // Some environments (jsdom) reject release on detached nodes.\n }\n };\n\n const onPointerDown = (event: PointerEvent): void => {\n // Mouse: only the primary button arms a potential swipe.\n if (event.pointerType === 'mouse' && event.button !== 0) {\n return;\n }\n // A pointer is already being tracked (the gesture is armed, or pending\n // arm): ignore the second pointerdown so its id/start don't overwrite the\n // first pointer's state and orphan its capture. The first pointer's\n // pointerup is then still honored.\n if (pointerId !== null) {\n return;\n }\n if (opts.getDirections().length === 0) {\n return;\n }\n pointerId = event.pointerId;\n startX = event.clientX;\n startY = event.clientY;\n active = false;\n direction = null;\n };\n\n const onPointerMove = (event: PointerEvent): void => {\n if (pointerId === null || event.pointerId !== pointerId) {\n return;\n }\n const dx = event.clientX - startX;\n const dy = event.clientY - startY;\n\n if (!active) {\n const detected = detectDirection(dx, dy, opts.getDirections());\n if (!detected) {\n return;\n }\n active = true;\n direction = detected;\n try {\n el.setPointerCapture?.(event.pointerId);\n } catch {\n // Some environments (jsdom) reject capture on detached nodes.\n }\n const detail: SwipeEventDetail = {\n direction: detected,\n delta: constrainedDelta(dx, dy, detected),\n originalEvent: event,\n };\n opts.onSwipeStart?.(detail);\n opts.onSwipeMove?.(detail);\n return;\n }\n\n if (!direction) {\n return;\n }\n // The allowed set can toggle mid-gesture (the \"off switch\"). If the active\n // direction is no longer allowed, abort the armed swipe: release capture\n // and fire onSwipeCancel so the consumer can settle back.\n if (!opts.getDirections().includes(direction)) {\n const detail: SwipeEventDetail = {\n direction,\n delta: constrainedDelta(dx, dy, direction),\n originalEvent: event,\n };\n releaseCapture(event.pointerId);\n reset();\n opts.onSwipeCancel?.(detail);\n return;\n }\n opts.onSwipeMove?.({\n direction,\n delta: constrainedDelta(dx, dy, direction),\n originalEvent: event,\n });\n };\n\n const onPointerUp = (event: PointerEvent): void => {\n if (pointerId === null || event.pointerId !== pointerId) {\n return;\n }\n if (active && direction) {\n const dx = event.clientX - startX;\n const dy = event.clientY - startY;\n const detail: SwipeEventDetail = {\n direction,\n delta: constrainedDelta(dx, dy, direction),\n originalEvent: event,\n };\n const proj = projection(dx, dy, direction);\n if (proj >= opts.getThreshold()) {\n opts.onSwipeEnd?.(detail);\n } else {\n opts.onSwipeCancel?.(detail);\n }\n releaseCapture(event.pointerId);\n }\n reset();\n };\n\n const onPointerCancel = (event: PointerEvent): void => {\n if (pointerId === null || event.pointerId !== pointerId) {\n return;\n }\n if (active && direction) {\n const dx = event.clientX - startX;\n const dy = event.clientY - startY;\n opts.onSwipeCancel?.({\n direction,\n delta: constrainedDelta(dx, dy, direction),\n originalEvent: event,\n });\n releaseCapture(event.pointerId);\n }\n reset();\n };\n\n el.addEventListener('pointerdown', onPointerDown);\n el.addEventListener('pointermove', onPointerMove);\n el.addEventListener('pointerup', onPointerUp);\n el.addEventListener('pointercancel', onPointerCancel);\n\n return () => {\n el.removeEventListener('pointerdown', onPointerDown);\n el.removeEventListener('pointermove', onPointerMove);\n el.removeEventListener('pointerup', onPointerUp);\n el.removeEventListener('pointercancel', onPointerCancel);\n if (pointerId !== null) {\n releaseCapture(pointerId);\n }\n };\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` that watches `dir`\n * attribute changes across the whole document, and exposes them as a\n * monotonically increasing `revision` tick.\n *\n * One observer covers every primitive: `injectTextDirection` derives each\n * host's ambient direction from a `computed` keyed on `revision`, so N\n * primitives reflecting `[attr.dir]` on first render coalesce into a single\n * observer callback (microtask-batched) → one `revision` bump → N ambient\n * recomputes — O(N), not the O(N²) cascade of N per-instance observers each\n * retriggering on every other's reflection.\n *\n * SSR-safe: on the server no observer is created, the DOM is never touched,\n * and `revision` stays `0`.\n *\n * The observer callback writing `#revision` is the single, intentional\n * \"external imperative source → signal\" exception, isolated here.\n *\n * Recompute granularity (intentional trade-off): a single `dir` mutation\n * anywhere in the document bumps the one shared `revision`, which invalidates\n * the ambient `computed` of **every** mounted dir-aware primitive — each then\n * re-walks its own ancestor chain. This is deliberately coarse: it keeps the\n * library at one document observer instead of one per primitive, and the\n * recompute is a cheap synchronous `closest('[dir]')` walk per host. With the\n * modest number of dir-aware primitives a typical page mounts, the\n * recompute-all cost is well below the cost of N per-instance observers each\n * retriggering on every other's reflection. If profiling ever flags it, cache\n * the ambient per *ancestor* (siblings under the same `[dir]` share a result)\n * or push the resolved ambient from this callback so a recompute becomes a\n * signal read rather than a DOM walk.\n *\n * Internal — not re-exported from `public-api.ts`.\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 * Returns a `Signal<WritingDirection>` equal to `explicitDir() ?? <ambient>`:\n * an explicit `[dir]` always wins, and when it is `null` the value falls back\n * to the **nearest ancestor carrying a `dir` attribute** (the host itself is\n * skipped — it reflects its own resolved `dir`), then to `<html dir>`,\n * defaulting to `'ltr'`.\n * Direction is read from the semantic `dir` attribute, not from CSS\n * `direction`; consumers who need a specific direction should set the `dir`\n * attribute on an ancestor (the standard `<html dir=\"rtl\">` setup) rather than\n * relying on `direction` in a stylesheet.\n *\n * SSR-safe: with no browser platform the ambient value is `'ltr'` and the DOM\n * is never touched. Reactive: a single application-wide `MutationObserver`\n * (owned by the root `AmbientDirection` service) watches `dir` attribute\n * changes across the whole document and publishes them as a shared `revision`\n * tick; the ambient is a `computed` keyed on that tick that reads the host's\n * ancestor chain synchronously. A runtime flip (e.g. a locale switch toggling\n * `<html dir>`, or an ancestor wrapper toggling its `dir`) bumps the tick and\n * recomputes the returned signal — regardless of how many primitives are\n * mounted, there is exactly one observer.\n *\n * Limitation: the shared observer watches `dir` attribute mutations only\n * (`attributeFilter: ['dir']`), not `childList`. The ambient therefore does\n * **not** recompute when the host is moved into a different-`dir` subtree\n * without any `dir` attribute itself changing (e.g. a parent re-parents the\n * element under an existing `[dir=\"rtl\"]` ancestor). Detecting that would need\n * a `childList`/`subtree` observer over the whole document — far costlier than\n * this case warrants. Reparenting between subtrees with different ambient\n * directions is rare; consumers who hit it should set an explicit `[dir]` on\n * the moved element or trigger any `dir` mutation to force a recompute.\n *\n * Must be called from an injection context (it injects `ElementRef`,\n * `DOCUMENT`, `PLATFORM_ID`, and `AmbientDirection`).\n *\n * Internal — not re-exported from `public-api.ts`.\n */\nexport function injectTextDirection(\n explicitDir: Signal<WritingDirection | null>,\n): Signal<WritingDirection> {\n const isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\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 if (!isBrowser) {\n return 'ltr';\n }\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-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 * 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 and case-insensitively. Returns the\n * matching option, or `null` when none matches (or the buffer is 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 = query.buffer.toLowerCase();\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 (getText(option).trim().toLowerCase().startsWith(needle)) {\n return option;\n }\n }\n return null;\n}\n","import { linkedSignal, signal, type Signal } from '@angular/core';\n\nimport { type ListNavigationAction, moveIndex } from '../keyboard-navigation/keyboard-navigation';\n\n/**\n * Re-export of the shared NG0950 read guard under the navigator's historical\n * name. The single source lives in `_internal/signal-graph/read-handle.ts`;\n * adapters wiring `readEntry` keep importing it from here.\n */\nexport { tryReadHandle as readEntryGuarded } from '../signal-graph/read-handle';\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 * Build the position-snapshot entry for a live handle, or `null` to skip it\n * this fold. The single NG0950 read guard (`readEntryGuarded`) is injected\n * here: a statically-rendered option that registers before its\n * `input.required` binding is written returns `null` and is folded in on the\n * 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\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 thin adapter — only once the consumer\n * sets `totalCount()` — so a non-virtualized collection never pulls this\n * position-map machinery into its hot path. Encapsulates two pieces of state\n * that make keyboard navigation work across a virtualized window where the\n * 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.\n * - **Pending active position** — when navigation lands outside the visible\n * window, the engine emits `(scrollToIndex)` and remembers the target. The\n * adapter's bridge effect calls `tryResolvePending` once the freshly-mounted\n * item carries that position.\n *\n * Internal — lives in `_internal/`, never re-exported from `public-api.ts`.\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 readonly #pendingActivePos = signal<number | 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 deferFold = options.deferFoldOnTotalTransition === true;\n\n this.#snapshotByPos = linkedSignal<\n { total: number | undefined; items: readonly H[] },\n Map<number, E>\n >({\n source: () => ({ total: deps.totalCount(), items: deps.items() }),\n computation: (src, prev) => {\n const totalChanged = prev !== undefined && prev.source.total !== src.total;\n if (deferFold && totalChanged) {\n return new Map<number, E>();\n }\n const next =\n totalChanged || prev === undefined ? new Map<number, E>() : new Map(prev.value);\n for (const item of src.items) {\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 }\n\n /**\n * Pull the position-map so its `linkedSignal` `prev` slot gets seeded while\n * the items are tracked. Called from the adapter'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 * 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. Returns `true` if a pending request was resolved, `false`\n * otherwise.\n */\n tryResolvePending(): boolean {\n const pendingPos = this.#pendingActivePos();\n if (pendingPos === null) {\n return false;\n }\n const match = this.#deps.items().find((it) => this.#accessors.posOf(it) === pendingPos);\n if (!match) {\n return false;\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. Walks `moveIndex` against the\n * absolute total, using the indexed snapshot to learn about disabled items\n * outside the rendered window. When the target is in the visible range and a\n * live item is present, seeds activedescendant directly; otherwise stashes the\n * target in the pending slot and emits `(scrollToIndex)`.\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 }\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 const isDisabled = (i: number) => indexed.get(i)?.disabled === true;\n\n const next = moveIndex(currentPos, total, action, {\n loop: this.#deps.loop(),\n isDisabled,\n });\n if (next === null) {\n return;\n }\n\n if (this.#seedIfRendered(next)) {\n return;\n }\n this.#pendingActivePos.set(next);\n this.#deps.emitScrollToIndex(next);\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.\n */\n seedActive(index: number): void {\n if (this.#seedIfRendered(index)) {\n return;\n }\n this.#pendingActivePos.set(index);\n this.#deps.emitScrollToIndex(index);\n }\n\n /** Clear any pending navigation (called by the adapter on close). */\n resetPending(): void {\n this.#pendingActivePos.set(null);\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","/** 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\n * one place rather than being re-derived per branch (the off-by-one shape behind\n * the #808 `gapIndex` overflow).\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 * Internal shared surface of forty-cdk — the `forty-cdk/core` entry point.\n *\n * This entry point holds everything formerly under `src/lib/_internal/`: the\n * cross-primitive DI singletons (`LiveAnnouncer`, focus-trap / dismissable-layer\n * / inert-siblings / drawer stacks, the id-generator salt, the defaults\n * registry), the framework-free geometry / interaction / overlay helpers, and\n * the cross-cutting public 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 * Stability: the symbols re-exported here carry NO semver guarantees. They are\n * an internal composition surface shared between forty-cdk's own entry points,\n * not a supported public API. Consume primitives from their own\n * `forty-cdk/<primitive>` entry points (or the main `forty-cdk` barrel), not\n * from here.\n */\n\nexport * from './body-scroll-lock/body-scroll-lock';\nexport * from './class-list/resolve-config-class';\nexport * from './collection/collection';\nexport * from './collection/first-enabled-host';\nexport * from './collection/fold-snapshot';\nexport * from './collection/register-handle';\nexport * from './date-adapter/date-adapter';\nexport * from './datetime/hour-cycle';\nexport * from './datetime/literal-directive';\nexport * from './datetime/segment-directive';\nexport * from './datetime/segment-editor';\nexport * from './datetime/segment-types';\nexport * from './datetime/serialize';\nexport * from './datetime/time-value-source';\nexport * from './defaults/defaults';\nexport * from './disabled-reflection/disabled-reflection';\nexport * from './dismissable-layer/dismissable-layer';\nexport * from './drag-session/auto-scroll';\nexport * from './drag-session/clamp-preview';\nexport * from './drag-session/drag-geometry';\nexport * from './drag-session/drag-positions';\nexport * from './drag-session/drag-preview';\nexport * from './drag-session/flip';\nexport * from './drag-session/keyboard-drag-keys';\nexport * from './drag-session/keyboard-drag-mediator';\nexport * from './drag-session/placeholder-position';\nexport * from './drag-session/pointer-session';\nexport * from './drag-session/preview-controller';\nexport * from './drag-session/tree-drop-resolver';\nexport * from './drawer-scale/drawer-scale-coordinator';\nexport * from './drawer-stack/drawer-side';\nexport * from './drawer-stack/drawer-stack';\nexport * from './element-size/element-size';\nexport * from './field/field-wiring';\nexport * from './fieldset/fieldset-context';\nexport * from './flat-hierarchy/flat-hierarchy';\nexport * from './floating/anchored-positioning-inputs';\nexport * from './floating/floating';\nexport * from './focusable-content/focusable-content';\nexport * from './form-ui-control/form-ui-control-base';\nexport * from './form-ui-control/unfocused-value-mirror';\nexport * from './form-ui-control/text-value-control-base';\nexport * from './hidden-input/hidden-input';\nexport * from './host-id/host-id';\nexport * from './hover-intent/debounced-action';\nexport * from './hover-intent/force-close-when-disabled';\nexport * from './hover-intent/hover-intent';\nexport * from './hover-intent/skip-delay-coordinator';\nexport * from './id-generator/id-generator';\nexport * from './inert-siblings/inert-siblings';\nexport * from './interactions/focus-visible';\nexport * from './interactions/hovered';\nexport * from './interactions/pressed';\nexport * from './keyboard-navigation/keyboard-navigation';\nexport * from './keyboard-navigation/move-in-collection';\nexport * from './listbox-overlay/listbox-overlay-controller';\nexport * from './live-announcer/live-announcer';\nexport * from './locale-number/locale-number';\nexport * from './media-query/media-query';\nexport * from './menu-overlay/menu-context';\nexport * from './menu-overlay/menu-focus-state';\nexport * from './menu-overlay/menu-item-list';\nexport * from './menu-overlay/menu-overlay';\nexport * from './menu-overlay/menu-overlay-host';\nexport * from './menu-overlay/menu-positioning-inputs';\nexport * from './modal-shell/modal-shell';\nexport * from './numeric-step/numeric-step';\nexport * from './overlay-manager/overlay-context-injector';\nexport * from './overlay-manager/overlay-manager';\nexport * from './overlay-manager/overlay-ref';\nexport * from './overlay-shell/overlay-shell';\nexport * from './pausable/pause-controller';\nexport * from './pointer-grace/pointer-grace';\nexport * from './pointer-suppression/pointer-suppression';\nexport * from './portal/portal';\nexport * from './resize-geometry/resize-geometry';\nexport * from './roving-tabindex/host-roving-context';\nexport * from './roving-tabindex/reconcile-roving-active';\nexport * from './roving-tabindex/roving-tabindex';\nexport * from './scroll-boundary/scroll-boundary';\nexport * from './selection-model/selection-model';\nexport * from './selection/selection';\nexport * from './signal-graph/read-handle';\nexport * from './snap-points/snap-points';\nexport * from './swipe-dismiss/swipe-dismiss';\nexport * from './text-direction/text-direction';\nexport * from './typeahead/match-options';\nexport * from './typeahead/typeahead';\nexport * from './vetoable-event/vetoable-event';\nexport * from './virtualized-navigator/virtualized-navigator';\nexport * from './visually-hidden/visually-hidden';\nexport * from './window-index-map/window-index-map';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":["clamp","hasInertAncestor"],"mappings":";;;;;AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCG;MAEU,cAAc,CAAA;AAChB,IAAA,SAAS,GAAG,MAAM,CAAC,QAAQ,CAAC;AAC5B,IAAA,OAAO,GAAG,IAAI,CAAC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AI,EAAE,EAAE,EAAE,iBAAiB,CAAC,MAAM,EAAE,IAAI,CAAC,EAAE;AACtD;;AC9CA;;;;;;;;;;;;;;;;;;;AAmBG;;ACnBH;;AAEG;;;;"}
|
|
1
|
+
{"version":3,"file":"forty-cdk-core.mjs","sources":["../../../projects/forty-cdk/core/src/body-scroll-lock/body-scroll-lock.ts","../../../projects/forty-cdk/core/src/class-list/resolve-config-class.ts","../../../projects/forty-cdk/core/src/collection/collection.ts","../../../projects/forty-cdk/core/src/collection/first-enabled-host.ts","../../../projects/forty-cdk/core/src/collection/fold-snapshot.ts","../../../projects/forty-cdk/core/src/id-generator/id-generator.ts","../../../projects/forty-cdk/core/src/host-id/host-id.ts","../../../projects/forty-cdk/core/src/collection/register-handle.ts","../../../projects/forty-cdk/core/src/date-adapter/date-adapter.ts","../../../projects/forty-cdk/core/src/datetime/hour-cycle.ts","../../../projects/forty-cdk/core/src/datetime/literal-directive.ts","../../../projects/forty-cdk/core/src/datetime/segment-directive.ts","../../../projects/forty-cdk/core/src/datetime/segment-editor.ts","../../../projects/forty-cdk/core/src/datetime/serialize.ts","../../../projects/forty-cdk/core/src/datetime/time-value-source.ts","../../../projects/forty-cdk/core/src/defaults/defaults.ts","../../../projects/forty-cdk/core/src/disabled-reflection/disabled-reflection.ts","../../../projects/forty-cdk/core/src/dismissable-layer/dismissable-layer.ts","../../../projects/forty-cdk/core/src/drag-session/auto-scroll.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-positions.ts","../../../projects/forty-cdk/core/src/drag-session/drag-preview.ts","../../../projects/forty-cdk/core/src/drag-session/flip.ts","../../../projects/forty-cdk/core/src/drag-session/handle-guard.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/placeholder-position.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/tree-drop-resolver.ts","../../../projects/forty-cdk/core/src/drawer-stack/drawer-stack.ts","../../../projects/forty-cdk/core/src/media-query/media-query.ts","../../../projects/forty-cdk/core/src/drawer-scale/drawer-scale-coordinator.ts","../../../projects/forty-cdk/core/src/element-size/element-size.ts","../../../projects/forty-cdk/core/src/field/field-wiring.ts","../../../projects/forty-cdk/core/src/fieldset/fieldset-context.ts","../../../projects/forty-cdk/core/src/flat-hierarchy/flat-hierarchy.ts","../../../projects/forty-cdk/core/src/floating/anchored-positioning-inputs.ts","../../../projects/forty-cdk/core/src/after-next-render-cancellable/after-next-render-cancellable.ts","../../../projects/forty-cdk/core/src/portal/portal.ts","../../../projects/forty-cdk/core/src/floating/floating.ts","../../../projects/forty-cdk/core/src/focus-trap/focus-trap.ts","../../../projects/forty-cdk/core/src/focusable-content/focusable-content.ts","../../../projects/forty-cdk/core/src/form-ui-control/form-ui-control-base.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/hidden-input/hidden-input.ts","../../../projects/forty-cdk/core/src/hover-intent/debounced-action.ts","../../../projects/forty-cdk/core/src/hover-intent/force-close-when-disabled.ts","../../../projects/forty-cdk/core/src/hover-intent/hover-intent.ts","../../../projects/forty-cdk/core/src/hover-intent/skip-delay-coordinator.ts","../../../projects/forty-cdk/core/src/inert-siblings/inert-siblings.ts","../../../projects/forty-cdk/core/src/interactions/modality.ts","../../../projects/forty-cdk/core/src/interactions/focus-visible.ts","../../../projects/forty-cdk/core/src/interactions/hovered.ts","../../../projects/forty-cdk/core/src/interactions/pressed.ts","../../../projects/forty-cdk/core/src/keyboard-navigation/keyboard-navigation.ts","../../../projects/forty-cdk/core/src/keyboard-navigation/move-in-collection.ts","../../../projects/forty-cdk/core/src/vetoable-event/vetoable-event.ts","../../../projects/forty-cdk/core/src/listbox-overlay/listbox-overlay-controller.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/locale-number/locale-number.ts","../../../projects/forty-cdk/core/src/menu-overlay/menu-context.ts","../../../projects/forty-cdk/core/src/menu-overlay/menu-focus-state.ts","../../../projects/forty-cdk/core/src/typeahead/typeahead.ts","../../../projects/forty-cdk/core/src/menu-overlay/menu-item-list.ts","../../../projects/forty-cdk/core/src/menu-overlay/menu-overlay.ts","../../../projects/forty-cdk/core/src/menu-overlay/menu-overlay-host.ts","../../../projects/forty-cdk/core/src/menu-overlay/menu-positioning-inputs.ts","../../../projects/forty-cdk/core/src/modal-shell/modal-shell.ts","../../../projects/forty-cdk/core/src/numeric-step/numeric-step.ts","../../../projects/forty-cdk/core/src/overlay-manager/overlay-context-injector.ts","../../../projects/forty-cdk/core/src/overlay-manager/overlay-manager.ts","../../../projects/forty-cdk/core/src/overlay-manager/overlay-ref.ts","../../../projects/forty-cdk/core/src/floating/item-aligned.ts","../../../projects/forty-cdk/core/src/overlay-shell/overlay-shell.ts","../../../projects/forty-cdk/core/src/visibility-pause/visibility-pause.ts","../../../projects/forty-cdk/core/src/pausable/pause-controller.ts","../../../projects/forty-cdk/core/src/pointer-grace/pointer-grace.ts","../../../projects/forty-cdk/core/src/pointer-suppression/pointer-suppression.ts","../../../projects/forty-cdk/core/src/resize-geometry/resize-geometry.ts","../../../projects/forty-cdk/core/src/roving-tabindex/host-roving-context.ts","../../../projects/forty-cdk/core/src/roving-tabindex/reconcile-roving-active.ts","../../../projects/forty-cdk/core/src/roving-tabindex/roving-tabindex.ts","../../../projects/forty-cdk/core/src/scroll-boundary/scroll-boundary.ts","../../../projects/forty-cdk/core/src/selection-model/selection-model.ts","../../../projects/forty-cdk/core/src/selection/selection.ts","../../../projects/forty-cdk/core/src/signal-graph/read-handle.ts","../../../projects/forty-cdk/core/src/snap-points/snap-points.ts","../../../projects/forty-cdk/core/src/swipe-dismiss/swipe-dismiss.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/virtualized-navigator/virtualized-navigator.ts","../../../projects/forty-cdk/core/src/window-index-map/window-index-map.ts","../../../projects/forty-cdk/core/src/public-api.ts","../../../projects/forty-cdk/core/src/forty-cdk-core.ts"],"sourcesContent":["import { DOCUMENT, Injectable, PLATFORM_ID, inject } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\n/**\n * Refcounted scroll lock, keyed per target element (default `<body>`).\n * Multiple modal surfaces acquire and release locks independently — only the\n * first acquire for a given target mutates that target, only the last release\n * un-mutates it. Different targets (body vs a container element) are fully\n * independent: locking a container does not affect body scroll and vice versa.\n *\n * **Semantic: clear, do not restore.** On the first lock for a target the\n * service writes `overflow: hidden` and an optional scrollbar-compensating\n * `padding-right` inline on that target. On the final unlock it _clears_ the\n * inline styles it set (`target.style.overflow = ''`, and\n * `target.style.paddingRight = ''` only when this lock actually wrote it) and\n * lets the CSS cascade take over again. It does NOT snapshot the values at\n * lock time and rewrite them at unlock time.\n *\n * On overlay-scrollbar / mobile platforms there is no classic scrollbar\n * (`innerWidth - clientWidth === 0` for the body path), so the lock never\n * writes `padding-right`. In that case the final unlock leaves\n * `target.style.paddingRight` untouched, so a consumer's unrelated inline\n * `padding-right` survives. The clear-don't-restore contract only applies to\n * values the lock owns. See #391.\n *\n * Why: any code (route transition, theme toggle, the consumer themselves)\n * that mutates `target.style.overflow` between `lock()` and the final\n * `unlock()` would otherwise be silently clobbered when we restored the\n * stale snapshot. Clearing on unlock means the lock owns the inline style\n * only while it exists; intervening mutations win, and the resting state\n * is whatever stylesheet rules apply. See #149.\n *\n * The scrollbar-width compensation prevents content jumping when overflow\n * goes from `auto` (scrollbar shown) to `hidden` (scrollbar hidden).\n * For the body path the width is `window.innerWidth - documentElement.clientWidth`;\n * for an element path it is `target.offsetWidth - target.clientWidth`.\n *\n * SSR: the service is `providedIn: 'root'` so its counter map is scoped to a\n * single Angular bootstrap (one per SSR request). Server-side calls are\n * no-ops.\n */\n@Injectable({ providedIn: 'root' })\nexport class BodyScrollLock {\n readonly #document = inject(DOCUMENT);\n readonly #window = this.#document.defaultView;\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n\n readonly #targets = new Map<HTMLElement, { count: number; wrotePaddingRight: boolean }>();\n\n /**\n * Acquire the scroll lock on `target` (default `document.body`). The first\n * call for a given target sets `overflow: hidden` and compensates for the\n * scrollbar width; subsequent calls increment the refcount only.\n */\n lock(target: HTMLElement = this.#document.body): void {\n if (!this.#isBrowser) {\n return;\n }\n let record = this.#targets.get(target);\n if (!record) {\n record = { count: 0, wrotePaddingRight: false };\n this.#targets.set(target, record);\n }\n if (record.count === 0) {\n target.style.overflow = 'hidden';\n const isBody = target === this.#document.body;\n const win = this.#window;\n let scrollbarWidth: number;\n if (isBody) {\n const docEl = this.#document.documentElement;\n scrollbarWidth = win ? win.innerWidth - docEl.clientWidth : 0;\n if (scrollbarWidth > 0 && win && !this.#gutterIsStable(win, [docEl, target])) {\n const computed = win.getComputedStyle(target).paddingRight;\n const currentPx = parseFloat(computed) || 0;\n target.style.paddingRight = `${currentPx + scrollbarWidth}px`;\n record.wrotePaddingRight = true;\n }\n } else {\n scrollbarWidth = target.offsetWidth - target.clientWidth;\n if (scrollbarWidth > 0 && win && !this.#gutterIsStable(win, [target])) {\n const computed = win.getComputedStyle(target).paddingRight;\n const currentPx = parseFloat(computed) || 0;\n target.style.paddingRight = `${currentPx + scrollbarWidth}px`;\n record.wrotePaddingRight = true;\n }\n }\n }\n record.count++;\n }\n\n /**\n * Release the scroll lock on `target` (default `document.body`). The last\n * release clears the inline `overflow` (and `padding-right` if written) and\n * lets the CSS cascade take over.\n */\n unlock(target: HTMLElement = this.#document.body): void {\n if (!this.#isBrowser) {\n return;\n }\n const record = this.#targets.get(target);\n if (!record || record.count === 0) {\n return;\n }\n record.count--;\n if (record.count === 0) {\n target.style.overflow = '';\n if (record.wrotePaddingRight) {\n target.style.paddingRight = '';\n record.wrotePaddingRight = false;\n }\n this.#targets.delete(target);\n }\n }\n\n /**\n * True when any of the given elements reserves the scrollbar gutter via\n * `scrollbar-gutter: stable` (or `stable both-edges`). The gutter then\n * survives the `overflow: hidden` toggle, so no padding compensation is\n * needed.\n */\n #gutterIsStable(win: Window, els: readonly HTMLElement[]): boolean {\n for (const el of els) {\n const gutter = win.getComputedStyle(el).getPropertyValue('scrollbar-gutter');\n if (gutter.trim().split(/\\s+/).includes('stable')) {\n return true;\n }\n }\n return false;\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 { computed, DestroyRef, inject, signal, type Signal } from '@angular/core';\n\n/**\n * Minimal contract every `Collection` entry must satisfy: it carries the\n * host element so consumers can correlate handles with DOM nodes (e.g.\n * `findByHost`, focus moves, `aria-activedescendant` lookups).\n */\nexport interface CollectionHandle {\n readonly host: HTMLElement;\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`\n * element regardless of the order children registered in.\n *\n * Resolving document order (rather than registration order) keeps\n * `items()` / `indexOfHost` correct under templates that reorder a list at\n * runtime — `@for (... ; track id)` driven by a sort or drag-reorder moves\n * existing DOM nodes without re-running child constructors, so registration\n * order would otherwise freeze at the original sequence and corrupt\n * `aria-posinset` / `aria-setsize` and keyboard navigation order. The\n * resolution is reactive: an internal `MutationObserver` re-orders the\n * exposed array when nodes move, and consumers' `computed`s recompute\n * automatically.\n *\n * The observer watches `childList` (without `subtree`) on each distinct\n * **direct parent** of the registered hosts, so it only fires for additions,\n * removals, and reorders of this collection's own members. In a nested\n * composition (e.g. a Tree of `forTreeGroup` containers, each owning its own\n * `Collection`) a single mutation deep in the tree no longer cascades through\n * every ancestor's observer — only the owning collection is invalidated.\n *\n * The collection itself is not Angular-aware, but when instantiated inside an\n * Angular injection context (the common case — a field initializer on the\n * host directive) it registers `destroy()` with the ambient `DestroyRef`, so\n * the `MutationObserver` is disconnected when the owner is destroyed without\n * relying on every child unregistering first. Call `register` / `unregister`\n * from each child's constructor / `DestroyRef.onDestroy`; outside an injection\n * context, call `destroy()` manually.\n *\n * Membership is tracked in a `Set`, so `register` / `unregister` do an O(1)\n * duplicate check instead of scanning the array. Document order is computed\n * lazily and memoized: reading `items()` returns the cached (frozen) array\n * reference until membership or DOM order actually changes, so reads stay O(1)\n * and a single mutation is O(N log N) (the sort) in the current size.\n */\nexport class Collection<H extends CollectionHandle> {\n readonly #members = signal<ReadonlySet<H>>(new Set<H>());\n readonly #domEpoch = signal(0);\n\n #observer: MutationObserver | null = null;\n readonly #observedParents = new Set<Node>();\n #destroyed = false;\n\n constructor() {\n try {\n inject(DestroyRef).onDestroy(() => this.destroy());\n } catch {\n // Constructed outside an injection context (e.g. a bare `new Collection()`\n // in a unit test); the owner is responsible for calling `destroy()`.\n }\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 the shared parents'\n * children are reordered, so it stays correct under runtime reordering\n * (`@for` sort / drag-reorder), not just under static `@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 returned array is frozen — it is shared across reads and is the\n * memoized cache backing this `computed`, so callers must treat it as\n * read-only (copy before sorting / splicing).\n */\n readonly items: Signal<readonly H[]> = computed(() => {\n this.#domEpoch();\n return Object.freeze(this.#sortByDomOrder([...this.#members()]));\n });\n\n register(handle: H): void {\n if (this.#destroyed) {\n return;\n }\n const members = this.#members();\n if (members.has(handle)) {\n return;\n }\n const next = new Set(members);\n next.add(handle);\n this.#members.set(next);\n this.#syncObserver();\n }\n\n unregister(handle: H): void {\n const members = this.#members();\n if (!members.has(handle)) {\n return;\n }\n const next = new Set(members);\n next.delete(handle);\n this.#members.set(next);\n this.#syncObserver();\n }\n\n /** Lookup by host element. Returns `undefined` if no handle has that host. */\n findByHost(el: HTMLElement): H | undefined {\n return this.items().find((h) => h.host === el);\n }\n\n /** Index in DOM document order, or -1 if not registered. */\n indexOfHost(el: HTMLElement): number {\n return this.items().findIndex((h) => h.host === el);\n }\n\n /**\n * Disconnects the `MutationObserver` and clears membership. Idempotent and\n * safe to call from a `DestroyRef.onDestroy` hook — wired automatically when\n * the collection is constructed in an injection context. After `destroy()`,\n * further `register` calls are ignored.\n */\n destroy(): void {\n this.#destroyed = true;\n this.#observer?.disconnect();\n this.#observer = null;\n this.#observedParents.clear();\n if (this.#members().size > 0) {\n this.#members.set(new Set<H>());\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 #syncObserver(): void {\n if (typeof MutationObserver === 'undefined' || this.#destroyed) {\n return;\n }\n const parents = this.#resolveParents();\n if (this.#sameParents(parents)) {\n return;\n }\n this.#observer ??= new MutationObserver(() => this.#domEpoch.update((e) => e + 1));\n this.#observer.disconnect();\n this.#observedParents.clear();\n for (const parent of parents) {\n this.#observer.observe(parent, { childList: true });\n this.#observedParents.add(parent);\n }\n }\n\n #resolveParents(): Set<Node> {\n const parents = new Set<Node>();\n for (const member of this.#members()) {\n const parent = member.host.parentNode;\n if (parent) {\n parents.add(parent);\n }\n }\n return parents;\n }\n\n #sameParents(parents: Set<Node>): boolean {\n if (parents.size !== this.#observedParents.size) {\n return false;\n }\n for (const parent of parents) {\n if (!this.#observedParents.has(parent)) {\n return false;\n }\n }\n return true;\n }\n}\n","import type { Signal } from '@angular/core';\n\nimport type { CollectionHandle } from './collection';\n\n/**\n * Collection handle that also exposes a `disabled` signal. Required input\n * shape for {@link firstEnabledHost}.\n */\nexport interface DisableableHandle extends CollectionHandle {\n readonly disabled: Signal<boolean>;\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 for (const item of items) {\n if (!item.disabled()) {\n return item.host;\n }\n }\n return null;\n}\n","import { linkedSignal, type Signal, type WritableSignal } from '@angular/core';\n\n/** Source tracked by every snapshot fold: the live window + its total. */\ninterface FoldSource<H> {\n readonly total: number | undefined;\n readonly items: readonly H[];\n}\n\n/**\n * Builds the `linkedSignal` shared by the combobox label cache and the\n * virtualized navigators. Both fold the live `items()` window into an\n * accumulator that persists across listbox close / open cycles and resets when\n * the consumer's `totalCount` transitions.\n *\n * The stale-window invariant lives here, in one place: on a `totalCount`\n * transition the `items()` array may still hold the previous window (signal\n * commits run serially, so the `@for` re-render hasn't unregistered the old\n * options yet), so the fold restarts from `empty()` on that compute and the\n * next run — fired when `items` catches up — folds the fresh window into a\n * clean carry-over accumulator.\n *\n * @typeParam H Handle type folded into the accumulator.\n * @typeParam A Accumulator shape.\n * @param items Live registered handles. The same signal the host exposes.\n * @param totalCount Total handle count (virtualized) or `undefined`.\n * @param empty Produces a fresh, empty accumulator (used on a `totalCount`\n * transition and as the initial `prev`).\n * @param fold Overlays the current `items` window onto the carried-over\n * accumulator and returns the next accumulator.\n */\nexport function foldSnapshotOnTotalCountTransition<H, A>(\n items: Signal<readonly H[]>,\n totalCount: Signal<number | undefined>,\n empty: () => A,\n fold: (prev: A, items: readonly H[]) => A,\n): WritableSignal<A> {\n return linkedSignal<FoldSource<H>, A>({\n source: () => ({ total: totalCount(), items: items() }),\n computation: ({ total, items: window }, prev) => {\n if (prev && prev.source.total !== total) {\n return empty();\n }\n return fold(prev?.value ?? empty(), window);\n },\n });\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 */\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 * bootstrapApplication(AppA, { providers: [provideForIdSalt('a')] });\n * bootstrapApplication(AppB, { providers: [provideForIdSalt('b')] });\n * ```\n *\n * The salt must stay deterministic per app instance — a runtime random value\n * would break SSR hydration because the server and client renders would no\n * longer agree.\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 * Used by primitives that need to wire `aria-controls` / `aria-labelledby`\n * relationships between pieces — the IDs are stable for the lifetime of the\n * primitive instance.\n *\n * SSR: the generator is `providedIn: 'root'`, so a fresh instance is\n * created for each Angular application bootstrap (one per SSR request).\n * The IDs are salted with {@link FOR_ID_SALT} (which defaults to the\n * application's `APP_ID`) so the server and the client produce identical\n * strings for the same render order — the property hydration relies on.\n *\n * IMPORTANT — multiple apps on one page need distinct salts. The default salt\n * is `APP_ID`, and Angular's default `APP_ID` is the literal `'ng'`. Two\n * forty-cdk apps mounted side-by-side that both keep the default salt\n * therefore start from the same salt and the same counter, emitting identical\n * id sequences — duplicate DOM ids that mis-resolve `aria-labelledby` /\n * `aria-controls` across apps. A per-instance random nonce is deliberately\n * NOT mixed in: it would diverge the salt but break SSR hydration (the server\n * and client renders would no longer agree). When running more than one\n * forty-cdk app on a single page, give each a distinct salt via\n * {@link provideForIdSalt} (the per-app knob that leaves the global `APP_ID`\n * untouched). Overriding the global `APP_ID` works too, but it also drives\n * Angular's hydration store and event replay, so `provideForIdSalt` is the\n * narrower choice.\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. See `.claude/rules/conventions.md`.\n *\n * Must be invoked in an injection context — internally injects\n * {@link IdGenerator}.\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 * Replaces the hand-written `readonly id = signal(this.#idGen.next('…'))` so\n * the piece's `[id]` host binding re-emits a consumer-set static id instead of\n * clobbering it. Must be invoked in an injection context — internally injects\n * {@link ElementRef} and {@link IdGenerator}.\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 {\n afterNextRender,\n DestroyRef,\n ElementRef,\n inject,\n signal,\n type Signal,\n} from '@angular/core';\n\nimport { resolveHostId } from '../host-id/host-id';\nimport type { Collection } from './collection';\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 until Angular's\n * `afterNextRender` hook fires. Required when the parent's lookups read\n * `input.required` signals from the handle during host-binding evaluation\n * that interleaves with sibling directives' input-binding step (Tabs,\n * NavigationMenu). The `unregister` call always runs eagerly via\n * `DestroyRef.onDestroy`, so destroy-before-register is a safe no-op as\n * long as `unregister` is reference-based.\n */\nexport type RegistrationScheduling = 'sync' | 'afterNextRender';\n\n/**\n * Generic register-on-construct / unregister-on-destroy helper.\n *\n * Collapses the boilerplate every child directive used to write by hand:\n *\n * ```ts\n * constructor() {\n * const handle = { host: this.#host.nativeElement, value: this.value };\n * this.parent.registerXxx(handle);\n * inject(DestroyRef).onDestroy(() => this.parent.unregisterXxx(handle));\n * }\n * ```\n *\n * becomes\n *\n * ```ts\n * constructor() {\n * const handle = { host: this.#host.nativeElement, value: this.value };\n * registerHandle(handle, (h) => this.parent.registerXxx(h), (h) => this.parent.unregisterXxx(h));\n * }\n * ```\n *\n * Works for any target shape — object handles, raw `HTMLElement`s,\n * `aria-*` id strings — because the helper just hands `target` back to the\n * caller-supplied `register` / `unregister` callbacks.\n *\n * Must be invoked in an injection context (typically a directive\n * constructor) — internally calls `inject(DestroyRef)`.\n *\n * @param target The value to register. Passed verbatim to both callbacks.\n * @param register Called immediately (or deferred via `afterNextRender`,\n * per `scheduling`) to register the target with the owning parent.\n * @param unregister Called from `DestroyRef.onDestroy` to unregister. Must\n * be reference-based and tolerant of being called before `register` ever\n * ran (when `scheduling` is `'afterNextRender'` and the directive is\n * destroyed before the deferred 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 * Convenience overload of {@link registerHandle} for parents that expose\n * a raw `Collection<H>`. The handle is registered immediately and\n * unregistered on `DestroyRef.onDestroy`.\n *\n * Most parents wrap their `Collection` behind named methods (e.g.\n * `registerOption` / `unregisterOption`) — those callsites should use\n * {@link registerHandle} with the named methods. Reach for this helper only\n * when the parent exposes the bare `Collection` instance.\n *\n * Must be invoked in an injection context.\n */\nexport function registerCollectionHandle<H extends { readonly host: HTMLElement }>(\n collection: Collection<H>,\n handle: H,\n scheduling: RegistrationScheduling = 'sync',\n): void {\n registerHandle(\n handle,\n (h) => collection.register(h),\n (h) => collection.unregister(h),\n scheduling,\n );\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 * Generates a stable `id` for the host element and registers it with the\n * `owner`'s `aria-labelledby` collection (`registerLabel` /\n * `unregisterLabel`). Returns the id as a `Signal<string>` so the caller\n * can host-bind it via `'[id]': 'id()'` exactly like every other primitive.\n *\n * Replaces:\n *\n * ```ts\n * readonly id = signal(this.#idGen.next('for-dialog-title'));\n * constructor() {\n * const myId = this.id();\n * this.#ctx.registerLabel(myId);\n * inject(DestroyRef).onDestroy(() => this.#ctx.unregisterLabel(myId));\n * }\n * ```\n *\n * with:\n *\n * ```ts\n * readonly id = registerA11yName(this.#ctx, 'for-dialog-title');\n * ```\n *\n * A consumer-set **static** `id` on the host is adopted (and registered as the\n * accessible-name id) instead of being clobbered — the host element is read\n * optionally, so the helper still works when invoked outside a directive host\n * context (it falls back to a generated id). See {@link resolveHostId} for the\n * static-only boundary.\n *\n * Must be invoked in an injection context — internally calls `inject` for\n * `ElementRef`, `IdGenerator`, and `DestroyRef`.\n */\nexport function registerA11yName(owner: A11yLabelOwner, prefix: string): Signal<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 signal(id).asReadonly();\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(\n owner: A11yDescriptionOwner,\n prefix: string,\n): Signal<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 signal(id).asReadonly();\n}\n","import { inject, InjectionToken } from '@angular/core';\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 (#354).\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 (#354).\n *\n * Implementations must be pure with respect to their date type: every\n * operation returns a value and never mutates its inputs. The `D` produced by\n * mutating operations (`add*`, `createDate`) is a fresh value, which keeps it\n * signal-friendly (reference equality changes on every change).\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 once 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. for a non-Gregorian ordering). Day-only\n * adapters whose {@link compare} already ignores time need not 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 using the runtime's default locale.\n *\n * **SSR / hydration caveat.** The result resolves against the runtime's\n * default locale, so a server render and a client hydration can produce\n * different strings when the server and browser locales differ — surfacing as\n * a hydration mismatch on every formatted value (heading, weekday headers,\n * cell labels). The runtime time zone applies too for adapters that format\n * 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 */\n format(date: D, options: Intl.DateTimeFormatOptions): 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 */\nexport function injectDateAdapter<D>(piece: string): DateAdapter<D> {\n const adapter = inject(FOR_DATE_ADAPTER, { optional: true });\n if (!adapter) {\n throw new Error(\n `[forty-cdk/calendar] ${piece} requires a DateAdapter. Provide one with ` +\n `provideInternationalizedDateAdapter() or provideNativeDateAdapter() in 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 */\nexport function assertTimeCapable<D>(\n adapter: DateAdapter<D>,\n piece: 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 new Error(\n `[forty-cdk/date-adapter] ${piece} requires a time-capable DateAdapter. Provide one with ` +\n `provideNativeDateAdapter() or provideInternationalizedDateTimeAdapter() — the day-only ` +\n `provideInternationalizedDateAdapter() (CalendarDate) cannot carry a time.`,\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","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, 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 { SegmentHandle, SegmentType } from './segment-editor';\n\n/**\n * The coordination surface a date / time root exposes to its segment children,\n * as consumed by the shared {@link ForDateTimeSegmentBase}. The reactive per-part\n * accessors and the behavior methods are forwarded straight to the root's\n * {@link import('./segment-editor').SegmentEditor}; `disabled` / `readonly` /\n * `dir` / `roving` come off the root directly.\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\n segmentValue(type: SegmentType): number | null;\n segmentMin(type: SegmentType): number;\n segmentMax(type: SegmentType): number;\n segmentValueText(type: SegmentType): string | null;\n segmentDisplayText(type: SegmentType): string;\n isSegmentEmpty(type: SegmentType): boolean;\n isFirstSegmentType(type: SegmentType): boolean;\n\n registerSegment(handle: SegmentHandle): void;\n unregisterSegment(handle: SegmentHandle): void;\n\n focusSegment(type: SegmentType): void;\n typeDigit(type: SegmentType, digit: number): void;\n step(type: SegmentType, delta: number): void;\n goToBound(type: SegmentType, bound: 'min' | 'max'): void;\n setDayPeriod(period: 'am' | 'pm'): void;\n clear(type: SegmentType): void;\n focusSibling(type: SegmentType, step: -1 | 1): void;\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 * keyboard map (RTL-mirrored 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.segmentMin(segment())',\n '[attr.aria-valuemax]': 'ctx.segmentMax(segment())',\n '[attr.aria-valuenow]': 'valueNow()',\n '[attr.aria-valuetext]': 'ctx.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.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 },\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.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.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.registerSegment(h),\n (h) => this.ctx.unregisterSegment(h),\n 'afterNextRender',\n );\n }\n\n protected onFocus(): void {\n this.ctx.focusSegment(this.segment());\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 if (key.length === 1 && key >= '0' && key <= '9') {\n event.preventDefault();\n this.ctx.typeDigit(type, Number(key));\n return;\n }\n if (type === 'dayPeriod' && (key === 'a' || key === 'A' || key === 'p' || key === 'P')) {\n event.preventDefault();\n this.ctx.setDayPeriod(key === 'a' || key === 'A' ? 'am' : 'pm');\n return;\n }\n const rtl = this.ctx.dir() === 'rtl';\n switch (key) {\n case 'ArrowUp':\n event.preventDefault();\n this.ctx.step(type, 1);\n return;\n case 'ArrowDown':\n event.preventDefault();\n this.ctx.step(type, -1);\n return;\n case 'ArrowRight':\n event.preventDefault();\n this.ctx.focusSibling(type, rtl ? -1 : 1);\n return;\n case 'ArrowLeft':\n event.preventDefault();\n this.ctx.focusSibling(type, rtl ? 1 : -1);\n return;\n case 'Home':\n event.preventDefault();\n this.ctx.goToBound(type, 'min');\n return;\n case 'End':\n event.preventDefault();\n this.ctx.goToBound(type, 'max');\n return;\n case 'Backspace':\n case 'Delete':\n event.preventDefault();\n this.ctx.clear(type);\n return;\n default:\n return;\n }\n }\n}\n","import { computed, signal, type Signal } from '@angular/core';\n\nimport type { RovingTabindex } from '../roving-tabindex/roving-tabindex';\nimport { from12, 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 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 /** Composes the next parts into the field value (compose + clamp + write). */\n commit(next: P): 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 /**\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 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 }\n\n segmentValue(type: SegmentType): number | null {\n const parts = this.#host.parts();\n if (type === 'dayPeriod') {\n const hour = parts.hour;\n return hour == null ? null : hour >= 12 ? 1 : 0;\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 hour = this.#host.parts().hour;\n if (hour == null) {\n return null;\n }\n const names = this.#host.periodNames();\n return hour >= 12 ? 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 hour = this.#host.parts().hour;\n if (hour == null) {\n return this.#host.placeholderFor(type);\n }\n const names = this.#host.periodNames();\n return hour >= 12 ? 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 if (type === 'dayPeriod') {\n return this.#host.parts().hour == null;\n }\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 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 this.#typing.set({ type, buffer });\n this.#host.commit(this.#withPart(type, valid ? this.#toInternal(type, num) : null));\n const full = valid && (buffer.length >= spec.digits || num * 10 > max);\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.#host.commit(this.#withPart(type, this.#host.seed(type)));\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.#host.commit(this.#withPart(type, next));\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.#host.commit(this.#withPart(type, this.#toInternal(type, display)));\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 hour = this.#host.parts().hour ?? null;\n const pm = period === 'pm';\n const next = hour === null ? (pm ? 12 : 0) : pm ? (hour % 12) + 12 : hour % 12;\n this.#host.commit(this.#withPart('hour', next));\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.#host.commit(this.#withPart(type, null));\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 /** 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 hour = this.#host.parts().hour ?? null;\n const pm = hour !== null && 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 {\n assertTimeCapable,\n type DateAdapter,\n type TimeCapableDateAdapter,\n} from '../date-adapter/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 */\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 { InjectionToken, type ModelSignal } from '@angular/core';\nimport type { DateAdapter } from '../date-adapter/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 * The helper is internal — primitives re-export their generated\n * `provideFor<X>Defaults` and (when public) their token. Internal — not\n * re-exported from `public-api.ts`.\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 { 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 — the wrapper-friendliness\n * failure first fixed for the dropdown trigger in #640 / #651.\n *\n * This helper tracks ownership instead: it sets the attribute only when it is\n * absent (so a pre-existing consumer attribute is never re-stamped or claimed),\n * and on the falsy edge removes it only when this helper is the one that set it.\n * A consumer-set `disabled` therefore always survives an enabled state, while a\n * primitive-set one is cleaned up cleanly on re-enable.\n *\n * Mirrors the imperative reflection #651 introduced on `[forDropdownMenuTrigger]`\n * and is the single implementation every clobber-capable host shares.\n *\n * Writing the DOM attribute is a genuine side effect (it escapes the reactive\n * graph) and the ownership flag is a plain closure variable, not a signal — so\n * this is a sanctioned `effect()` use, not state propagation.\n *\n * Must be called from an injection context (it injects `ElementRef` and creates\n * an `effect`), typically a directive constructor.\n *\n * Internal — not re-exported from `public-api.ts`.\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, DestroyRef, ElementRef, Injectable, PLATFORM_ID, inject } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\n/**\n * Options passed to `DismissableLayer.activate`. Each handler receives the\n * native event and can call `preventDefault()` to veto the layer's\n * `onDismiss` callback. Handlers themselves are always invoked.\n */\nexport interface DismissableLayerActivateOptions {\n /** Fired when the user presses `Escape` while this is the topmost layer. */\n onEscapeKeyDown?: (event: KeyboardEvent) => void;\n\n /** Fired when the user pointer-downs outside this layer's host. */\n onPointerDownOutside?: (event: PointerEvent) => void;\n\n /** Fired when focus moves outside this layer's host. */\n onFocusOutside?: (event: FocusEvent) => void;\n\n /**\n * Fired in addition to `onPointerDownOutside` / `onFocusOutside` for\n * consumers that don't care which one occurred.\n */\n onInteractOutside?: (event: PointerEvent | FocusEvent) => void;\n\n /**\n * Default action invoked after each of the above fires when its event was\n * not `preventDefault()`-ed by the specific handler. This is where the\n * consumer wires \"close\" so the contract `preventDefault → stay open`\n * holds without manual flag-checking.\n */\n onDismiss?: () => void;\n\n /**\n * Extra elements whose subtrees count as \"inside\" for outside-pointer /\n * outside-focus checks (e.g. a portaled popover content owned by this\n * layer). Recomputed on every event so that DOM mutations are picked up.\n */\n exemptElements?: () => readonly Element[];\n}\n\n/**\n * Application-scoped registry that owns the document listeners used by\n * dismissable layers. Created once per Angular bootstrap (one per SSR\n * request), tied to the root injector lifetime.\n *\n * Why a service rather than module-level state:\n *\n * - SSR isolation: module-level globals leak between simultaneous server\n * requests in the same Node process. A `providedIn: 'root'` service is\n * instantiated per application injector.\n * - Bootstrap-safety: `TestBed.resetTestingModule()`, micro-frontend\n * reloads and any other code that destroys `ApplicationRef` should not\n * leave stale `document` listeners behind. The service registers its\n * listeners in the constructor and removes them via `DestroyRef` so\n * every bootstrap has exactly one set of listeners.\n * - SSR safety: `document` is inaccessible on the server. The service is a\n * no-op when `PLATFORM_ID` is not the browser; nothing about this code\n * path is reachable until an overlay calls `activate()`, which only\n * happens from `afterNextRender`.\n *\n * Listener phases — intentional asymmetry: `pointerdown` and `focusin`\n * register on the **capture** phase so outside-interaction is detected even\n * when overlay content stops bubbling propagation, but `keydown` (Escape)\n * registers on the **bubble** phase by design. The bubble phase is\n * load-bearing for Escape because the per-overlay `onEscapeKeyDown` handlers\n * (Dialog, Select, Menu, Popover, …) call `event.stopPropagation()` after they\n * close — that stops the same keydown from bubbling further up to an *ancestor*\n * overlay's keydown handler, which is how nested overlays avoid one Escape\n * closing two layers at once. Moving this listener to capture would fire it\n * before any of those handlers and defeat the stopPropagation-based\n * single-layer-per-Escape contract. The trade-off is that overlay content with\n * its own bubble-phase keydown handler that calls `stopPropagation()` can\n * swallow Escape before it reaches this listener; that is an accepted,\n * documented limitation rather than an accidental one.\n */\n@Injectable({ providedIn: 'root' })\nexport class DismissableLayerStack {\n readonly #document = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n\n readonly #stack: DismissableLayer[] = [];\n #suppressDepth = 0;\n\n readonly #onKeyDown = (event: KeyboardEvent): void => {\n if (event.key !== 'Escape') {\n return;\n }\n if (this.#suppressDepth > 0) {\n return;\n }\n this.#topmost()?.['handleEscape'](event);\n };\n readonly #onPointerDown = (event: Event): void => {\n if (this.#suppressDepth > 0) {\n return;\n }\n this.#topmost()?.['handlePointerDown'](event as PointerEvent);\n };\n readonly #onFocusIn = (event: Event): void => {\n if (this.#suppressDepth > 0) {\n return;\n }\n this.#topmost()?.['handleFocusIn'](event as FocusEvent);\n };\n\n constructor() {\n if (!this.#isBrowser) {\n return;\n }\n this.#document.addEventListener('keydown', this.#onKeyDown);\n this.#document.addEventListener('pointerdown', this.#onPointerDown, true);\n this.#document.addEventListener('focusin', this.#onFocusIn);\n\n inject(DestroyRef).onDestroy(() => {\n this.#document.removeEventListener('keydown', this.#onKeyDown);\n this.#document.removeEventListener('pointerdown', this.#onPointerDown, true);\n this.#document.removeEventListener('focusin', this.#onFocusIn);\n this.#stack.length = 0;\n this.#suppressDepth = 0;\n });\n }\n\n /** @internal */\n push(layer: DismissableLayer): void {\n this.#stack.push(layer);\n }\n\n /** @internal */\n remove(layer: DismissableLayer): void {\n const idx = this.#stack.indexOf(layer);\n if (idx >= 0) {\n this.#stack.splice(idx, 1);\n }\n }\n\n /**\n * Runs `fn` with the dispatcher suppressed. While suppressed, neither\n * Escape, pointer-down outside, nor focus-outside events are forwarded\n * to the topmost layer. Refcounted so nested teardowns nest correctly.\n */\n suppress<T>(fn: () => T): T {\n this.#suppressDepth++;\n try {\n return fn();\n } finally {\n this.#suppressDepth--;\n }\n }\n\n #topmost(): DismissableLayer | undefined {\n return this.#stack[this.#stack.length - 1];\n }\n}\n\n/**\n * Resolves the effective target of an interaction event for the\n * outside-detection containment check. Prefers `composedPath()[0]` so a\n * pointer-down / focus inside a shadow tree reports the real originating node\n * rather than the shadow host the event was retargeted to. Falls back to\n * `event.target` in environments without `composedPath`.\n */\nfunction 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 * Coordinates the standard \"dismissable surface\" interactions used by modal\n * dialogs, popovers, dropdown menus, drawers, and any other transient\n * overlay: Escape, pointer-down outside, focus-outside.\n *\n * Only the topmost active layer responds to events — nested layers (e.g. a\n * popover inside a dialog) shadow their parents until they deactivate.\n * Dispatch goes through a single shared document listener that always\n * targets the layer at the top of the stack, so synchronous changes to the\n * stack from a handler don't leak into sibling listeners.\n *\n * Each event handler can call `preventDefault()` on the native event to\n * cancel the layer's `onDismiss` action.\n */\nexport class DismissableLayer {\n readonly #host: HTMLElement;\n readonly #stack: DismissableLayerStack;\n #options: DismissableLayerActivateOptions = {};\n #active = false;\n\n constructor(host: HTMLElement, stack: DismissableLayerStack) {\n this.#host = host;\n this.#stack = stack;\n }\n\n get host(): HTMLElement {\n return this.#host;\n }\n\n get isActive(): boolean {\n return this.#active;\n }\n\n /**\n * Pushes this layer onto the dispatch stack. Calling `activate` twice\n * without an intervening `deactivate` is a no-op.\n */\n activate(options: DismissableLayerActivateOptions = {}): void {\n if (this.#active) {\n return;\n }\n this.#active = true;\n this.#options = options;\n this.#stack.push(this);\n }\n\n /** Removes this layer from the stack. */\n deactivate(): void {\n if (!this.#active) {\n return;\n }\n this.#active = false;\n this.#stack.remove(this);\n this.#options = {};\n }\n\n /**\n * Convenience wrapper around the stack's `suppress`. Lets owners\n * suppress the dispatcher without needing a fresh injection context\n * (e.g. inside `DestroyRef.onDestroy` or imperative teardown closures).\n */\n suppress<T>(fn: () => T): T {\n return this.#stack.suppress(fn);\n }\n\n protected handleEscape(event: KeyboardEvent): void {\n this.#options.onEscapeKeyDown?.(event);\n if (!event.defaultPrevented) {\n this.#options.onDismiss?.();\n }\n }\n\n protected handlePointerDown(event: PointerEvent): void {\n const target = resolveEventTarget(event);\n if (!target || this.#contains(target)) {\n return;\n }\n this.#options.onPointerDownOutside?.(event);\n this.#options.onInteractOutside?.(event);\n if (!event.defaultPrevented) {\n this.#options.onDismiss?.();\n }\n }\n\n protected handleFocusIn(event: FocusEvent): void {\n const target = resolveEventTarget(event);\n if (!target || this.#contains(target)) {\n return;\n }\n this.#options.onFocusOutside?.(event);\n this.#options.onInteractOutside?.(event);\n if (!event.defaultPrevented) {\n this.#options.onDismiss?.();\n }\n }\n\n #contains(target: Node): boolean {\n if (this.#host.contains(target)) {\n return true;\n }\n const exempt = this.#options.exemptElements?.();\n if (!exempt) {\n return false;\n }\n for (const el of exempt) {\n if (el.contains(target)) {\n return true;\n }\n }\n return false;\n }\n}\n\n/**\n * Creates a `DismissableLayer` for the directive's host element and wires\n * deactivation into `DestroyRef`. The host primitive owns activation\n * (typically via an `effect()` watching the open state).\n *\n * Use `layer.suppress(fn)` to run a callback with the dispatcher\n * suppressed (e.g. across a focus-return that would otherwise\n * cascade-dismiss the next topmost layer).\n */\nexport function injectDismissableLayer(): DismissableLayer {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const stack = inject(DismissableLayerStack);\n const layer = new DismissableLayer(host.nativeElement, stack);\n inject(DestroyRef).onDestroy(() => layer.deactivate());\n return layer;\n}\n","import { type DragRect } from './drag-geometry';\n\n/** A 2-D scroll velocity vector produced by `computeScrollVelocity`. */\nexport interface AutoScrollVelocity {\n readonly x: number;\n readonly y: number;\n}\n\nfunction axisVelocity(\n pos: number,\n start: number,\n end: number,\n edgeSize: number,\n maxSpeed: number,\n): number {\n if (edgeSize <= 0 || pos < start || pos > end) {\n return 0;\n }\n const distStart = pos - start;\n if (distStart <= edgeSize) {\n return -maxSpeed * (1 - distStart / edgeSize);\n }\n const distEnd = end - pos;\n if (distEnd <= edgeSize) {\n return maxSpeed * (1 - distEnd / edgeSize);\n }\n return 0;\n}\n\n/**\n * Computes a 2-D scroll velocity from the pointer position relative to a\n * scroll container's bounding rect. Each axis is computed independently:\n * negative values scroll toward the start edge, positive toward the end.\n * Velocity scales linearly with proximity; at the edge = ±`maxSpeed`, at\n * `edgeSize` pixels away = 0.\n */\nexport function computeScrollVelocity(\n rect: DragRect,\n point: { readonly x: number; readonly y: number },\n edgeSize: number,\n maxSpeed: number,\n): AutoScrollVelocity {\n return {\n x: axisVelocity(point.x, rect.left, rect.right, edgeSize, maxSpeed),\n y: axisVelocity(point.y, rect.top, rect.bottom, edgeSize, maxSpeed),\n };\n}\n\nfunction isScrollable(el: HTMLElement, win: Window): boolean {\n const style = win.getComputedStyle(el);\n const overflowY = style.overflowY;\n const overflowX = style.overflowX;\n const scrollsY =\n (overflowY === 'auto' || overflowY === 'scroll') && el.scrollHeight > el.clientHeight;\n const scrollsX =\n (overflowX === 'auto' || overflowX === 'scroll') && el.scrollWidth > el.clientWidth;\n return scrollsY || scrollsX;\n}\n\n/**\n * Walks up the DOM from `start` (inclusive) looking for the nearest scrollable\n * ancestor, stopping before `documentElement` and `body`. Returns the first\n * scrollable element, or `null` if none is found (the caller should fall back\n * to the viewport).\n */\nexport function findScrollContainer(start: HTMLElement | null, win: Window): HTMLElement | null {\n let el = start;\n while (el !== null && el !== win.document.documentElement && el !== win.document.body) {\n if (isScrollable(el, win)) {\n return el;\n }\n el = el.parentElement;\n }\n return null;\n}\n\n/** An active auto-scroll controller returned by `createAutoScroller`. */\nexport interface AutoScroller {\n /** Arms or disarms the rAF loop for the given pointer position. */\n update(point: { x: number; y: number }): void;\n /** Cancels the loop and clears cached state. Idempotent. */\n stop(): void;\n}\n\n/** Configuration passed to `createAutoScroller`. */\nexport interface AutoScrollerConfig {\n /** The list host element; used to find the nearest scrollable container. */\n readonly host: HTMLElement;\n /** The browser `Window`, or `null` in SSR / test environments without a DOM. */\n readonly win: Window | null;\n /** Pixel distance from the scroll edge that arms auto-scroll. */\n readonly edgeSize: number;\n /** Maximum scroll delta (px) applied per animation frame. */\n readonly maxSpeed: number;\n /** Called after each frame that actually scrolls, so callers can re-resolve the drop target. */\n readonly onFrame: () => void;\n}\n\ninterface ScrollTarget {\n rect(): DragRect;\n scrollBy(dx: number, dy: number): void;\n}\n\nfunction elementTarget(el: HTMLElement): ScrollTarget {\n return {\n rect(): DragRect {\n const r = el.getBoundingClientRect();\n return { left: r.left, top: r.top, right: r.right, bottom: r.bottom };\n },\n scrollBy(dx: number, dy: number): void {\n el.scrollLeft += dx;\n el.scrollTop += dy;\n },\n };\n}\n\nfunction viewportTarget(win: Window): ScrollTarget {\n return {\n rect(): DragRect {\n return { left: 0, top: 0, right: win.innerWidth, bottom: win.innerHeight };\n },\n scrollBy(dx: number, dy: number): void {\n win.scrollBy(dx, dy);\n },\n };\n}\n\n/**\n * Creates an auto-scroller that drives a `requestAnimationFrame` loop while a\n * pointer drag is near the edge of the nearest scrollable container (or the\n * viewport). Deltas are applied instantaneously per frame — no CSS smooth-scroll\n * easing — which is the `prefers-reduced-motion`-safe approach: scrolling is\n * functional, not decorative, so no reduced-motion branch is needed.\n *\n * Returns a no-op controller when `config.win` is falsy or lacks\n * `requestAnimationFrame` (SSR / environments without a window).\n */\nexport function createAutoScroller(config: AutoScrollerConfig): AutoScroller {\n const maybeWin = config.win;\n if (!maybeWin || typeof maybeWin.requestAnimationFrame !== 'function') {\n return { update() {}, stop() {} };\n }\n\n const win: Window = maybeWin;\n\n let target: ScrollTarget | null = null;\n let point: { x: number; y: number } | null = null;\n let rafId: number | null = null;\n\n function resolveTarget(): ScrollTarget {\n const el = findScrollContainer(config.host, win);\n return el ? elementTarget(el) : viewportTarget(win);\n }\n\n function tick(): void {\n rafId = null;\n if (point === null || target === null) {\n return;\n }\n const v = computeScrollVelocity(target.rect(), point, config.edgeSize, config.maxSpeed);\n if (v.x === 0 && v.y === 0) {\n target = null;\n return;\n }\n target.scrollBy(v.x, v.y);\n config.onFrame();\n rafId = win.requestAnimationFrame(tick);\n }\n\n return {\n update(next: { x: number; y: number }): void {\n point = next;\n if (target === null) {\n target = resolveTarget();\n }\n const v = computeScrollVelocity(target.rect(), point, config.edgeSize, config.maxSpeed);\n if (v.x === 0 && v.y === 0) {\n if (rafId !== null) {\n win.cancelAnimationFrame(rafId);\n rafId = null;\n }\n } else if (rafId === null) {\n rafId = win.requestAnimationFrame(tick);\n }\n },\n stop(): void {\n if (rafId !== null) {\n win.cancelAnimationFrame(rafId);\n rafId = null;\n }\n target = null;\n point = null;\n },\n };\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","/** 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\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 * @param point Viewport pointer coordinates.\n * @param containers Ordered `[source, ...connected]` container geometries.\n * @param orientation List axis — `'horizontal'`, `'vertical'`, or `'mixed'` (2D resolution for\n * wrapping grids of uniformly-sized items, considering both axes). `'mixed'` reduces to the\n * single-axis result when the items form a single row or a single column.\n * @param dir Writing direction for horizontal / mixed insertion-index math.\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 orientation: 'horizontal' | 'vertical' | 'mixed',\n dir: 'ltr' | 'rtl',\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(container.itemRects, point.x, point.y, orientation, dir);\n\n return { containerIndex, index };\n}\n","/** One reachable keyboard drop position: a container plus an insertion index within it. */\nexport interface DragSlot {\n /** Index into the ordered `[source, ...connected]` container list (0 = source). */\n readonly containerIndex: number;\n /** Insertion index within that container. */\n readonly index: number;\n}\n\n/**\n * Builds the flat, ordered sequence of reachable drop positions for a keyboard drag.\n * - The source container (index 0) contributes one slot per existing item\n * (`0 .. sourceCount - 1`): the dragged item is *reinserted* among the current items, so\n * the valid destination indices are exactly the existing positions.\n * - Each connected container contributes one slot per insertion gap (`0 .. count`,\n * inclusive of the append position), since the item is *added* to it.\n * Order: all source slots, then each connected container's slots in `connectedCounts` order.\n */\nexport function buildDragSlots(\n sourceCount: number,\n connectedCounts: readonly number[],\n): DragSlot[] {\n const slots: DragSlot[] = [];\n const clampedSource = Math.max(0, sourceCount);\n for (let i = 0; i < clampedSource; i++) {\n slots.push({ containerIndex: 0, index: i });\n }\n for (let ci = 0; ci < connectedCounts.length; ci++) {\n const count = Math.max(0, connectedCounts[ci]!);\n for (let i = 0; i <= count; i++) {\n slots.push({ containerIndex: ci + 1, index: i });\n }\n }\n return slots;\n}\n\n/** Flat-sequence position of `(containerIndex, index)`, or `-1` if not present. */\nexport function indexOfSlot(\n slots: readonly DragSlot[],\n containerIndex: number,\n index: number,\n): number {\n return slots.findIndex((s) => s.containerIndex === containerIndex && s.index === index);\n}\n\n/** Steps `current` by `delta` (±1), clamped to `[0, slots.length - 1]` (no wrap). */\nexport function stepSlot(slots: readonly DragSlot[], current: number, delta: 1 | -1): number {\n if (slots.length === 0) {\n return current;\n }\n return Math.max(0, Math.min(slots.length - 1, current + delta));\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). 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\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 if (!firstSegment || parseFloat(firstSegment) === 0) {\n target.style.transform = `translate(${x}px, ${y}px)`;\n destroyFn();\n return;\n }\n let finished = false;\n const finish = (): void => {\n if (finished) {\n return;\n }\n finished = true;\n target.removeEventListener('transitionend', onEnd);\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 });\n win.setTimeout(finish, 500);\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 */\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\n const descendants = clone.querySelectorAll('[data-testid]');\n descendants.forEach((el) => el.removeAttribute('data-testid'));\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","/** A minimal positioned rect — only the top-left corner is needed for a FLIP translate. */\nexport interface FlipRect {\n readonly left: number;\n readonly top: number;\n}\n\n/** The inverted translate (in px) that visually returns `last` to `first`. */\nexport interface FlipDelta {\n readonly dx: number;\n readonly dy: number;\n}\n\n/** Pure: the translate that moves an element from its Last position back to its First. */\nexport function flipDelta(first: FlipRect, last: FlipRect): FlipDelta {\n return { dx: first.left - last.left, dy: first.top - last.top };\n}\n\n/** Styling hook attribute set on each element while its FLIP transition plays. */\nexport const FLIP_ANIMATING_ATTR = 'data-drag-animating';\n\n/** Configuration for {@link playFlip}. */\nexport interface PlayFlipConfig {\n /** Element → its First (pre-change) rect, captured before the data change. */\n readonly first: ReadonlyMap<HTMLElement, FlipRect>;\n /** The browser window (for reflow + timeout), or `null` in SSR / non-DOM environments. */\n readonly win: Window | null;\n /** An element to leave untouched (the dragged host handled by drop-settle). */\n readonly exclude?: HTMLElement | null;\n /** Safety timeout (ms) after which the animating attribute is force-cleared. */\n readonly fallbackMs?: number;\n}\n\n/**\n * Runs the Invert + Play steps of a FLIP transition for every element in `first` that is still\n * connected and has moved. Measures Last via `getBoundingClientRect`, applies the inverted\n * transform with the transition suppressed, forces a reflow, then transitions back to identity\n * while `data-drag-animating` is present so a consumer CSS rule keyed on it governs duration /\n * easing. No-op when `win` is `null`. The library imposes no duration of its own.\n */\nexport function playFlip(config: PlayFlipConfig): void {\n const { first, win, exclude, fallbackMs: fallbackMsInput } = config;\n if (!win) {\n return;\n }\n const fallbackMs = fallbackMsInput ?? 500;\n\n const workList: { el: HTMLElement; d: FlipDelta }[] = [];\n for (const [el, firstRect] of first) {\n if (el === exclude) {\n continue;\n }\n if (!el.isConnected) {\n continue;\n }\n const r = el.getBoundingClientRect();\n const d = flipDelta(firstRect, r);\n if (d.dx === 0 && d.dy === 0) {\n continue;\n }\n workList.push({ el, d });\n }\n\n if (workList.length === 0) {\n return;\n }\n\n for (const { el, d } of workList) {\n el.style.transition = 'none';\n el.style.transform = `translate(${d.dx}px, ${d.dy}px)`;\n }\n\n void workList[0]!.el.offsetWidth;\n\n for (const { el } of workList) {\n el.setAttribute(FLIP_ANIMATING_ATTR, '');\n el.style.transition = '';\n el.style.transform = '';\n\n let done = false;\n const clear = (): void => {\n if (done) {\n return;\n }\n done = true;\n el.removeAttribute(FLIP_ANIMATING_ATTR);\n el.style.transform = '';\n el.style.transition = '';\n el.removeEventListener('transitionend', onEnd);\n };\n\n const onEnd = (event: TransitionEvent): void => {\n if (event.propertyName && event.propertyName !== 'transform') {\n return;\n }\n clear();\n };\n\n el.addEventListener('transitionend', onEnd, { once: true });\n win.setTimeout(clear, fallbackMs);\n }\n}\n","import { computed, type Signal } from '@angular/core';\n\n/**\n * Per-directive pointer drag-start guard shared by `ForDraggable` and\n * `ForFreeDrag`: tracks `[forDragHandle]` elements, decides whether a\n * `pointerdown` may begin a drag (left mouse button only; if any handle is\n * registered the press must originate inside one), and derives the\n * `touch-action` style that suppresses native scrolling on a handle-less host.\n */\nexport interface PointerHandleGuard {\n /** `'none'` while the host should suppress native touch scrolling, else `null`. */\n readonly touchAction: Signal<'none' | null>;\n /** Register a `[forDragHandle]` element. */\n register(el: HTMLElement): void;\n /** Unregister a previously registered handle element. */\n unregister(el: HTMLElement): void;\n /** Whether a `pointerdown` event is allowed to start a drag. */\n canStart(event: PointerEvent): boolean;\n}\n\n/**\n * Builds a {@link PointerHandleGuard}. Call from a directive's injection\n * context (field initializer or constructor) so `touchAction`'s `computed`\n * registers correctly.\n *\n * @param disabled Signal reporting whether dragging is currently disabled.\n */\nexport function createPointerHandleGuard(disabled: Signal<boolean>): PointerHandleGuard {\n const handles = new Set<HTMLElement>();\n return {\n touchAction: computed<'none' | null>(() => (!disabled() && handles.size === 0 ? 'none' : null)),\n register(el: HTMLElement): void {\n handles.add(el);\n },\n unregister(el: HTMLElement): void {\n handles.delete(el);\n },\n canStart(event: PointerEvent): boolean {\n if (disabled()) {\n return false;\n }\n if (event.pointerType === 'mouse' && event.button !== 0) {\n return false;\n }\n if (handles.size === 0) {\n return true;\n }\n const target = event.target as Node | null;\n return target !== null && [...handles].some((h) => h.contains(target));\n },\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*; the caller owns every *decision*.\n * `isLifted` is read on each keydown to route the event, and the two keydown\n * callbacks plus `onFocusOut` carry the caller's domain logic.\n */\nexport interface KeyboardDragMediatorConfig {\n /** Element the capture-phase `keydown` / `focusout` listeners attach to (the coordinator host). */\n readonly host: HTMLElement;\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 /** A `focusout` fired on the host. The caller decides whether it should cancel an in-flight drag. */\n onFocusOut(event: FocusEvent): void;\n}\n\n/**\n * Wires the capture-phase keyboard mediation shared by container-level drag-reorder\n * coordinators (`ForTreeNodeDrag`, `ForTableRowReorder`, `ForListboxReorder`).\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 symmetric `{ capture: true }` add / remove of the `keydown` listener (a\n * mismatched flag silently leaks the listener), the paired `focusout` listener, the\n * lifted-vs-idle routing decision, and teardown via `DestroyRef`. Domain behavior — what lifts,\n * what each key does, when a `focusout` cancels — stays with the caller through the callbacks.\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 const onKeydown = (event: KeyboardEvent): void => {\n if (config.isLifted()) {\n config.onLiftedKeydown(event);\n } else {\n config.onIdleKeydown(event);\n }\n };\n const onFocusOut = (event: FocusEvent): void => config.onFocusOut(event);\n\n host.addEventListener('keydown', onKeydown, { capture: true });\n host.addEventListener('focusout', onFocusOut);\n\n config.destroyRef.onDestroy(() => {\n host.removeEventListener('keydown', onKeydown, { capture: true });\n host.removeEventListener('focusout', onFocusOut);\n });\n}\n","/** Where to insert the live-sort placeholder: a parent node and the node to insert before. */\nexport interface PlaceholderInsertion {\n /** The DOM node the placeholder's nodes should be inserted into. */\n readonly parent: Node;\n /** The reference node to insert before; `null` means append to `parent`. */\n readonly ref: Node | null;\n}\n\n/**\n * Computes the DOM insertion point for the live-sort placeholder.\n *\n * @param hosts The target container's non-lifted item host elements, in DOM order.\n * @param index Insertion index within `hosts` (`0 .. hosts.length`, inclusive of append).\n * @param container Fallback parent used when the container has no items.\n * @returns The `parent` node and the `ref` node to insert before (`null` = append).\n */\nexport function placeholderInsertion(\n hosts: readonly HTMLElement[],\n index: number,\n container: HTMLElement,\n): PlaceholderInsertion {\n if (index < hosts.length) {\n const at = hosts[index]!;\n return { parent: at.parentNode ?? container, ref: at };\n }\n const last = hosts[hosts.length - 1];\n if (last) {\n return { parent: last.parentNode ?? container, ref: last.nextSibling };\n }\n return { parent: container, ref: null };\n}\n\n/**\n * Clamps a live-sort placeholder insertion index so it cannot cross a `dragDisabled`\n * (pinned) item. Each disabled host is a hard wall bounding the contiguous run of enabled\n * positions that contains `origin` — the gap the dragged item was lifted from — so the\n * placeholder stops at the first pinned item instead of travelling past it.\n *\n * Visual only: the committed drop index is resolved separately and is left unaffected. With\n * no disabled host the input index is returned unchanged (clamped to the valid range).\n *\n * @param index Raw insertion index resolved from pointer geometry (`0 .. disabled.length`).\n * @param disabled Disabled flag per non-lifted host, in DOM order.\n * @param origin Insertion index the dragged item was lifted from (its source gap).\n * @returns `index` clamped to the enabled run around `origin`.\n */\nexport function fencePlaceholderIndex(\n index: number,\n disabled: readonly boolean[],\n origin: number,\n): number {\n let lower = 0;\n for (let i = origin - 1; i >= 0; i--) {\n if (disabled[i]) {\n lower = i + 1;\n break;\n }\n }\n let upper = disabled.length;\n for (let i = origin; i < disabled.length; i++) {\n if (disabled[i]) {\n upper = i;\n break;\n }\n }\n return Math.max(lower, Math.min(upper, index));\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 once, on the first move that crosses `armThreshold`. Return\n * `false` to abort the session in flight (e.g. the grabbed element has since vanished):\n * the document listeners are torn down and no further callback fires.\n * - `onMove(event)` fires on every armed move after the lift.\n * - `onCommit(event)` fires on `pointerup` while armed.\n * - `onCancel()` fires on `pointercancel`, and on `Escape` when `cancelOnEscape` is set.\n *\n * Escape: with `cancelOnEscape`, a document `keydown` listener (alive only while a press is\n * tracked) aborts an armed drag on `Escape` — it tears the session down and fires `onCancel`,\n * just like a `pointercancel`. It is opt-in so callers that run their own keyboard-drag mode and\n * own the `Escape` handling themselves (e.g. `ForTreeNodeDrag`) stay unaffected.\n *\n * Click suppression: when a `pointerup` ends an armed drag, the next capture-phase `click`\n * on the document is swallowed (`stopPropagation` + `preventDefault`). The listener removes\n * itself after the first click, and a `suppressClickTimeoutMs` fallback removes it if no\n * click follows.\n */\n\n/** A live pointer-drag session. Call `destroy()` to remove every listener. */\nexport interface PointerDragSession {\n /** Remove the host listener, any active document listeners, and any pending click trap. */\n destroy(): void;\n}\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 once, on the first move past `armThreshold`. Return `false` to abort the session\n * in flight (the grabbed element vanished, etc.); the session tears its listeners down and\n * fires no further callback. Returning `true` or `void` keeps the session armed.\n */\n readonly onLift: (event: PointerEvent) => boolean | 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 /** Fires on `pointercancel`, and on `Escape` while armed when {@link cancelOnEscape} is set. */\n readonly onCancel: () => 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`, 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;\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 pointerId: number | null = null;\n\n let onDocumentMove: ((event: PointerEvent) => void) | null = null;\n let onDocumentUp: ((event: PointerEvent) => void) | null = null;\n let onDocumentCancel: ((event: PointerEvent) => void) | null = null;\n let onDocumentKeydown: ((event: KeyboardEvent) => void) | null = null;\n let onDocumentClick: ((event: MouseEvent) => void) | null = null;\n\n const removeDocumentListeners = (): void => {\n if (onDocumentMove) {\n document.removeEventListener('pointermove', onDocumentMove, { capture: true });\n onDocumentMove = null;\n }\n if (onDocumentUp) {\n document.removeEventListener('pointerup', onDocumentUp, { capture: true });\n onDocumentUp = null;\n }\n if (onDocumentCancel) {\n document.removeEventListener('pointercancel', onDocumentCancel, { capture: true });\n onDocumentCancel = null;\n }\n if (onDocumentKeydown) {\n document.removeEventListener('keydown', onDocumentKeydown);\n onDocumentKeydown = null;\n }\n };\n\n const removeClickTrap = (): void => {\n if (onDocumentClick) {\n document.removeEventListener('click', onDocumentClick, { capture: true });\n onDocumentClick = null;\n }\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 pointerId = null;\n removeDocumentListeners();\n };\n\n const move = (event: PointerEvent): void => {\n if (!start) {\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 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 if (opts.onLift(event) === false) {\n resetTracking();\n return;\n }\n }\n opts.onMove(event);\n };\n\n const installClickTrap = (): void => {\n const trap = (event: MouseEvent): void => {\n event.stopPropagation();\n event.preventDefault();\n removeClickTrap();\n };\n onDocumentClick = trap;\n document.addEventListener('click', trap, { capture: true });\n setTimeout(() => {\n if (onDocumentClick === trap) {\n removeClickTrap();\n }\n }, suppressTimeout);\n };\n\n const up = (event: PointerEvent): void => {\n const wasArmed = armed;\n if (wasArmed) {\n installClickTrap();\n }\n resetTracking();\n if (wasArmed) {\n opts.onCommit(event);\n }\n };\n\n const cancel = (): void => {\n resetTracking();\n opts.onCancel();\n };\n\n const down = (event: PointerEvent): void => {\n if (start !== null) {\n return;\n }\n if (!opts.canStart(event)) {\n return;\n }\n start = { x: event.clientX, y: event.clientY };\n armed = false;\n pointerId = event.pointerId;\n\n onDocumentMove = move;\n onDocumentUp = up;\n onDocumentCancel = cancel;\n document.addEventListener('pointermove', move, { capture: true });\n document.addEventListener('pointerup', up, { capture: true });\n document.addEventListener('pointercancel', cancel, { capture: true });\n\n if (opts.cancelOnEscape) {\n const escape = (event: KeyboardEvent): void => {\n if (armed && event.key === 'Escape') {\n cancel();\n }\n };\n onDocumentKeydown = escape;\n document.addEventListener('keydown', escape);\n }\n };\n\n host.addEventListener('pointerdown', down, { capture: true });\n\n return {\n destroy(): void {\n host.removeEventListener('pointerdown', down, { capture: true });\n releaseCapture();\n removeDocumentListeners();\n removeClickTrap();\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) so the floating\n * preview's orchestration lives in one place; it resolves the `DragPreview` discriminator\n * internally (the supplied preview is either already a full `DragPreview` or the minimal\n * `{ moveTo, destroy }` shape). 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","/** One visible tree row as the resolver sees it. Rects in viewport coords. */\nexport interface TreeDropRow {\n /** The node's string value. */\n readonly value: string;\n /** 1-based depth. */\n readonly level: number;\n /** rect.left — used to map levels to x. */\n readonly left: number;\n readonly top: number;\n readonly bottom: number;\n}\n\n/** Where a lifted node will land, for rendering an insertion indicator. */\nexport interface TreeDropIndicator {\n /** The visible row the indicator anchors to (the node value). */\n readonly anchor: string;\n /** Whether the line sits just before or just after the anchor row in DOM order. */\n readonly position: 'before' | 'after';\n /** Resolved 1-based depth of the drop. */\n readonly level: number;\n}\n\n/** A resolved tree drop position. */\nexport interface TreeDropTarget {\n /** New parent's value, or `null` for the root level. */\n readonly parentValue: string | null;\n /** Insertion index among the new parent's children (post-removal space). */\n readonly index: number;\n /** Resolved 1-based depth of the dropped node. */\n readonly level: number;\n /**\n * Number of existing children under `parentValue` at the resolved `level` (excluding the\n * dragged node, which is absent from `rows`). The dropped node will be sibling\n * `index + 1` of `siblingCount + 1` after the move — the numbers screen-reader\n * announcements report.\n */\n readonly siblingCount: number;\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\n/**\n * Resolves a tree drop from a flattened, DOM-ordered list of the currently visible rows\n * (EXCLUDING the dragged node, whose subtree is collapsed during the drag).\n *\n * @param rows Visible rows in DOM order, dragged node excluded.\n * @param gapIndex Insertion gap: the row index the dropped node would sit *before* (`rows.length`\n * = after the last row). For pointer, derive this from the vertical midpoint rule; for keyboard,\n * it is the running target the arrows step.\n * @param desiredLevel Caller's desired depth (pointer: nearest level to the pointer x; keyboard:\n * the running level the Left/Right arrows adjust). Clamped to the gap's allowed band.\n */\nexport function resolveTreeDrop(\n rows: readonly TreeDropRow[],\n gapIndex: number,\n desiredLevel: number,\n): TreeDropTarget {\n if (rows.length === 0) {\n return { parentValue: null, index: 0, level: 1, siblingCount: 0 };\n }\n\n const gap = clamp(gapIndex, 0, rows.length);\n const prev = gap > 0 ? (rows[gap - 1] ?? null) : null;\n const next = gap < rows.length ? (rows[gap] ?? null) : null;\n\n const maxLevel = prev ? prev.level + 1 : 1;\n let minLevel = next ? next.level : 1;\n if (minLevel > maxLevel) {\n minLevel = maxLevel;\n }\n\n const level = clamp(desiredLevel, minLevel, maxLevel);\n\n let parentValue: string | null = null;\n if (level > 1) {\n for (let i = gap - 1; i >= 0; i--) {\n if (rows[i]!.level === level - 1) {\n parentValue = rows[i]!.value;\n break;\n }\n }\n }\n\n let index = 0;\n let siblingCount = 0;\n for (let i = 0; i < rows.length; i++) {\n if (!isSiblingUnder(rows, i, level, parentValue)) {\n continue;\n }\n siblingCount++;\n if (i < gap) {\n index++;\n }\n }\n\n return { parentValue, index, level, siblingCount };\n}\n\n/**\n * Whether the row at `rowIndex` is a child of `parentValue` at depth `level` — i.e. it sits\n * at `level` and its nearest preceding row at `level - 1` is `parentValue` (root rows at\n * `level === 1` have no ancestor row, so they always qualify when their depth matches).\n */\nfunction isSiblingUnder(\n rows: readonly TreeDropRow[],\n rowIndex: number,\n level: number,\n parentValue: string | null,\n): boolean {\n const row = rows[rowIndex]!;\n if (row.level !== level) {\n return false;\n }\n if (level === 1) {\n return true;\n }\n for (let j = rowIndex - 1; j >= 0; j--) {\n if (rows[j]!.level === level - 1) {\n return rows[j]!.value === parentValue;\n }\n }\n return parentValue === null;\n}\n\n/**\n * Maps a pointer y coordinate to the insertion gap among `rows` using the vertical-midpoint\n * rule: the gap is the index of the first row whose vertical midpoint sits below `y`\n * (`rows.length` when `y` is below every row's midpoint).\n *\n * @param rows Visible rows in DOM order, dragged node excluded.\n * @param y Pointer y in viewport coordinates.\n */\nexport function gapFromPointerY(rows: readonly TreeDropRow[], y: number): number {\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i]!;\n const mid = (row.top + row.bottom) / 2;\n if (y < mid) {\n return i;\n }\n }\n return rows.length;\n}\n\n/**\n * Resolves the insertion-indicator anchor for a gap: the line sits `before` the row at\n * `gapIndex`, or `after` the last row when the gap is past the end. Returns `null` when there\n * are no rows to anchor to.\n *\n * @param rows Visible rows in DOM order, dragged node excluded.\n * @param gapIndex Insertion gap (same as passed to {@link resolveTreeDrop}).\n * @param level Resolved 1-based depth to report on the indicator.\n */\nexport function resolveDropIndicator(\n rows: readonly TreeDropRow[],\n gapIndex: number,\n level: number,\n): TreeDropIndicator | null {\n if (rows.length === 0) {\n return null;\n }\n const gap = clamp(gapIndex, 0, rows.length);\n if (gap >= rows.length) {\n return { anchor: rows[rows.length - 1]!.value, position: 'after', level };\n }\n return { anchor: rows[gap]!.value, position: 'before', level };\n}\n\n/**\n * Maps a pointer x coordinate to the nearest candidate level within the allowed band\n * at `gapIndex`. Uses each level's representative left (minimum left observed among rows\n * at that level) and falls back to linear interpolation when a level isn't present.\n *\n * @param rows Visible rows in DOM order, dragged node excluded.\n * @param gapIndex Gap index (same as passed to `resolveTreeDrop`).\n * @param x Pointer x in viewport coordinates.\n */\nexport function levelFromPointerX(\n rows: readonly TreeDropRow[],\n gapIndex: number,\n x: number,\n): number {\n if (rows.length === 0) {\n return 1;\n }\n\n const next = gapIndex < rows.length ? (rows[gapIndex] ?? null) : null;\n const minLevel = next ? next.level : 1;\n\n const levelLefts = new Map<number, number>();\n for (const row of rows) {\n const existing = levelLefts.get(row.level);\n if (existing === undefined || row.left < existing) {\n levelLefts.set(row.level, row.left);\n }\n }\n\n const candidateLevels = Array.from(levelLefts.keys()).sort((a, b) => a - b);\n\n if (candidateLevels.length === 0) {\n return minLevel;\n }\n\n let bestLevel = candidateLevels[0]!;\n let bestDist = Infinity;\n for (const lvl of candidateLevels) {\n const lx = levelLefts.get(lvl)!;\n const dist = Math.abs(x - lx);\n if (dist < bestDist) {\n bestDist = dist;\n bestLevel = lvl;\n }\n }\n\n return bestLevel;\n}\n","import { Injectable, type Signal, signal } from '@angular/core';\n\nimport { type ForDrawerSide } from './drawer-side';\n\n/**\n * Snapshot of a single drawer registered with {@link ForDrawerStack}. The\n * stack is LIFO ordered (root → topmost) and exposes only what other\n * coordinators need — `host` for ancestry checks, `side` for layout\n * heuristics, `scaleBackground` for visual composition, `parent` for\n * topology, `dragging` so visual coordinators (e.g.\n * `ForDrawerScaleCoordinator`'s nested-transform pass) can yield the\n * surface to imperative drag handlers, and the resolved nested-transform\n * tunables so the coordinator never needs to re-read scope-dependent\n * defaults.\n */\nexport interface DrawerStackNode {\n readonly host: HTMLElement;\n readonly side: ForDrawerSide;\n readonly scaleBackground: boolean;\n readonly parent: HTMLElement | null;\n /**\n * Reactive flag that flips to `true` while a swipe gesture is in flight\n * on this drawer's surface. Visual coordinators must yield the host's\n * inline transform to the drag handlers while this is `true`.\n */\n readonly dragging: Signal<boolean>;\n /**\n * Scale factor applied to *this* drawer's host while it owns one or\n * more direct child drawers (the nested-drawer visual). Resolved from\n * the drawer's own injector scope at push time so per-scope\n * `provideForDrawerDefaults` overrides flow through.\n */\n readonly nestedScaleAmount: number;\n /**\n * Pixels of translation applied to *this* drawer's host while it owns\n * one or more direct child drawers, in the direction *away* from its\n * anchored edge.\n */\n readonly nestedTranslateYpx: number;\n}\n\n/**\n * Returned by {@link ForDrawerStack.push}. `depth` is the number of\n * ancestor drawers currently registered above this one (0 for a root\n * drawer, 1 for a single-nested child, …). `cleanup` pops the node;\n * calling it while descendants are still registered throws so consumers\n * surface their own destroy-order bugs instead of silently leaking.\n */\nexport interface DrawerStackHandle {\n readonly depth: number;\n cleanup(): void;\n}\n\n/**\n * App-scoped LIFO registry of every active `[forDrawer]`. Mounted drawers\n * push themselves on first render and pop on destroy; the stack's signal\n * is the single source of truth for nesting topology consumed by:\n *\n * - `[forDrawer]` itself, to derive `data-depth` and `data-state-nested`\n * on its host (the latter when the stack contains a node whose\n * `parent` is this drawer's host).\n * - `ForDrawerScaleCoordinator`, when `scaleBackground` is opted in by\n * multiple levels of nesting and the visual effect must compose along\n * the LIFO topmost.\n *\n * The companion to {@link DismissableLayerStack} and `InertSiblingsStack`:\n * those keep the focus / dismiss / inert behaviour LIFO-correct, this one\n * keeps the *visual* / *topology* layer LIFO-correct. Both are read-only\n * to consumers — there is no public API for explicit ordering, the LIFO\n * is determined by mount order.\n *\n * SSR: `providedIn: 'root'` so state is per Angular bootstrap. The\n * directives that call `push` only do so from `afterNextRender`, which\n * doesn't run on the server, so there is nothing to guard here.\n *\n * Internal — not re-exported from `public-api.ts`.\n */\n@Injectable({ providedIn: 'root' })\nexport class ForDrawerStack {\n readonly #stack = signal<readonly DrawerStackNode[]>([]);\n\n /**\n * Reactive view of the current drawer stack (root → topmost). Reading\n * this from a `computed`/`effect` lets primitives react to nesting\n * changes synchronously when a child drawer mounts or unmounts.\n */\n readonly stack: Signal<readonly DrawerStackNode[]> = this.#stack.asReadonly();\n\n /**\n * Push a drawer onto the stack. Returns a {@link DrawerStackHandle}\n * carrying the computed `depth` and a `cleanup` that pops the same\n * node. `depth` is derived from the node's `parent` chain at push time:\n * a root drawer (no `parent`) is depth 0; a child of a depth-N drawer\n * is depth N+1.\n *\n * `cleanup` is idempotent on a node that's already gone, but throws if\n * the node still has descendants in the stack — the canonical signal\n * that the consumer's template tore down a parent before its child\n * (typically because the parent's `@if` flipped to `false` while the\n * child sits in a separate template branch). Nest the child's\n * `@if (childOpen())` *inside* the parent's `@if (parentOpen())` to\n * inherit Angular's bottom-up destroy order automatically.\n */\n push(node: DrawerStackNode): DrawerStackHandle {\n const depth = this.#computeDepth(node);\n this.#stack.update((s) => [...s, node]);\n return {\n depth,\n cleanup: () => this.#cleanup(node),\n };\n }\n\n #cleanup(node: DrawerStackNode): void {\n const current = this.#stack();\n const idx = current.indexOf(node);\n if (idx === -1) {\n return;\n }\n const hasDescendant = current.some(\n (other) => other !== node && this.#isDescendant(other, node, current),\n );\n if (hasDescendant) {\n throw new Error(\n '[forty-cdk/drawer] DrawerStack out-of-order cleanup: a parent drawer was destroyed while a nested child is still registered. Make sure the child @if is wrapped inside the parent @if so the child unmounts first.',\n );\n }\n const next = current.slice();\n next.splice(idx, 1);\n this.#stack.set(next);\n }\n\n #computeDepth(node: DrawerStackNode): number {\n if (node.parent === null) {\n return 0;\n }\n const stack = this.#stack();\n let depth = 0;\n let cursor: HTMLElement | null = node.parent;\n while (cursor) {\n depth += 1;\n const ancestor = stack.find((n) => n.host === cursor);\n if (!ancestor) {\n break;\n }\n cursor = ancestor.parent;\n }\n return depth;\n }\n\n #isDescendant(\n candidate: DrawerStackNode,\n ancestor: DrawerStackNode,\n stack: readonly DrawerStackNode[],\n ): boolean {\n let cursor: HTMLElement | null = candidate.parent;\n while (cursor) {\n if (cursor === ancestor.host) {\n return true;\n }\n const next = stack.find((n) => n.host === cursor);\n if (!next) {\n return false;\n }\n cursor = next.parent;\n }\n return false;\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 — not re-exported from `public-api.ts`.\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 * Convenience wrapper around {@link injectMediaQuery} for the\n * `prefers-reduced-motion: reduce` query — the standard hook for users who\n * have asked their OS to suppress animations. Returns a `Signal<boolean>`\n * that flips reactively if the preference changes mid-session.\n *\n * Used by primitives whose default behaviour involves motion that may be\n * hostile to vestibular sensitivity (drag gestures, large transforms,\n * parallax). Consumers should treat a `true` result as a hard signal to\n * skip the animated path entirely, not just to shorten the duration.\n *\n * Internal — not re-exported from `public-api.ts`.\n */\nexport function injectPrefersReducedMotion(): Signal<boolean> {\n return injectMediaQuery('(prefers-reduced-motion: reduce)');\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport { computed, DOCUMENT, effect, inject, Injectable, PLATFORM_ID, signal } from '@angular/core';\n\nimport { type ForDrawerSide } from '../drawer-stack/drawer-side';\nimport { ForDrawerStack } from '../drawer-stack/drawer-stack';\nimport { injectPrefersReducedMotion } from '../media-query/media-query';\n\n/**\n * Per-drawer configuration consumed by {@link ForDrawerScaleCoordinator}.\n * Resolved by `[forDrawer]` from inputs + defaults at register time so the\n * coordinator never needs to re-read scope-dependent values.\n *\n * `setBackgroundColorOnScale` controls whether `<body>` receives an inline\n * background colour while the wrapper is scaled — necessary to mask the\n * sliver of viewport that becomes visible between the scaled wrapper and\n * the viewport edge. Disabled by drawers that already paint a full-bleed\n * backdrop or apply their own body-level styling.\n *\n * The remaining keys default to a tuned set of values (scale `0.95`, +14 px Y,\n * 8 px corner radius, black body) but are tunable via\n * `provideForDrawerDefaults`.\n */\nexport interface ForDrawerScaleConfig {\n readonly setBackgroundColorOnScale: boolean;\n readonly scaleAmount: number;\n readonly scaleTranslateYpx: number;\n readonly scaleBorderRadiusPx: number;\n readonly scaleBackgroundColor: string;\n}\n\ninterface WrapperSnapshot {\n readonly transform: string;\n readonly transformOrigin: string;\n readonly borderRadius: string;\n readonly overflow: string;\n readonly transitionProperty: string;\n readonly transitionDuration: string;\n readonly transitionTimingFunction: string;\n}\n\ninterface BodySnapshot {\n readonly backgroundColor: string;\n}\n\nconst TRANSITION_DURATION_S = 0.5;\nconst TRANSITION_TIMING = 'cubic-bezier(0.32, 0.72, 0, 1)';\n\n/**\n * App-scoped coordinator that synchronises a registered\n * `[forDrawerWrapper]` element with the LIFO stack of active drawers\n * opted into the scale-background effect. The consumer chooses _which_\n * element wraps the rest of the app via explicit DI, instead of relying on a\n * global selector / data attribute.\n *\n * Stacking model: at most one wrapper is registered at any time; multiple\n * drawers may be registered concurrently. The topmost (most recently\n * registered) drawer's config commands the effective scale — when it\n * unregisters, the previous topmost takes over. Reverts to inline-style\n * snapshots only when the last drawer unregisters or the wrapper itself\n * is torn down.\n *\n * `prefers-reduced-motion: reduce` is treated as a hard kill switch:\n * while it is `true` the effect is suppressed entirely, the wrapper /\n * body styles are reverted, and the snapshot is cleared. When the\n * preference flips back to `false` with at least one active drawer, the\n * effect re-applies.\n *\n * SSR: providedIn `root` so its state is per Angular bootstrap. On the\n * server, `registerWrapper` / `registerDrawer` are no-ops since the\n * directives that call them only do so from `afterNextRender`.\n *\n * Internal — not re-exported from `public-api.ts`.\n */\n@Injectable({ providedIn: 'root' })\nexport class ForDrawerScaleCoordinator {\n readonly #document = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n readonly #prefersReducedMotion = injectPrefersReducedMotion();\n readonly #drawerStack = inject(ForDrawerStack);\n\n readonly #wrapperEl = signal<HTMLElement | null>(null);\n readonly #stack = signal<readonly ForDrawerScaleConfig[]>([]);\n\n #wrapperSnapshot: WrapperSnapshot | null = null;\n #bodySnapshot: BodySnapshot | null = null;\n /**\n * Hosts for which this coordinator currently owns an inline\n * `style.transform` from the nested-state pass. Used to ensure we only\n * clear transforms we ourselves applied — drag handlers also write to\n * `style.transform` and the coordinator must yield to them.\n */\n readonly #nestedTransformOwned = new WeakSet<HTMLElement>();\n\n /**\n * `true` when a wrapper is registered, at least one drawer is active,\n * and `prefers-reduced-motion: reduce` is not set. Drawers reflect this\n * on their host as `data-scale-background` when `scaleBackground()` is\n * also `true`; the wrapper reflects it as `data-state=\"scaled\"` /\n * `\"idle\"`.\n */\n readonly active = computed<boolean>(() => {\n return this.#wrapperEl() !== null && this.#stack().length > 0 && !this.#prefersReducedMotion();\n });\n\n readonly #activeConfig = computed<ForDrawerScaleConfig | null>(() => {\n const stack = this.#stack();\n return stack.length === 0 ? null : (stack[stack.length - 1] ?? null);\n });\n\n constructor() {\n effect(() => {\n const wrapper = this.#wrapperEl();\n const config = this.#activeConfig();\n const reducedMotion = this.#prefersReducedMotion();\n\n if (wrapper && config && !reducedMotion) {\n this.#apply(wrapper, config);\n } else {\n this.#revert();\n }\n });\n\n // Nested-state visual pass. Mirrors the pre-#180 in-drawer effect but\n // runs once for the whole stack: every node that has at least one\n // direct child in the stack gets a `scale + translate3d` applied to\n // its host, gated by `prefers-reduced-motion: reduce` and by the\n // node's own `dragging()` signal (the swipe handlers in `ForDrawer`\n // mutate `style.transform` imperatively during a gesture, so the\n // coordinator yields the host to them and reapplies on release as a\n // side effect of the `dragging` flip). Tracking ownership in\n // `#nestedTransformOwned` keeps cleanup honest — we only clear\n // transforms we ourselves applied.\n effect(() => {\n const stack = this.#drawerStack.stack();\n const reducedMotion = this.#prefersReducedMotion();\n\n // Two-pass: figure out which nodes currently want a nested\n // transform, then reconcile against ownership. Reduced-motion\n // forces an empty `wantsNested` set so previously-owned hosts get\n // released cleanly.\n const wantsNested = new Set<HTMLElement>();\n if (!reducedMotion) {\n for (const node of stack) {\n // Read each node's `dragging` signal so the effect re-runs when\n // any drawer's gesture flips on or off — yielding to the drag\n // handlers without dropping the reactive subscription on the\n // signal (Angular's effect tracking ignores signals only read\n // inside conditionals that short-circuited last run).\n const dragging = node.dragging();\n const hasChild = stack.some((n) => n.parent === node.host);\n if (hasChild && !dragging) {\n wantsNested.add(node.host);\n }\n }\n } else {\n // Subscribe to `dragging` even under reduced-motion so a flip back\n // to `false` for the preference re-runs this effect with full\n // reactivity. Cheap to read (no allocation) and keeps the\n // dependency graph predictable.\n for (const node of stack) {\n node.dragging();\n }\n }\n\n // Apply transforms for nodes that want them.\n for (const node of stack) {\n if (!wantsNested.has(node.host)) {\n continue;\n }\n node.host.style.transform = this.#nestedTransform(\n node.side,\n node.nestedScaleAmount,\n node.nestedTranslateYpx,\n );\n this.#nestedTransformOwned.add(node.host);\n }\n\n // Release ownership on hosts we previously applied to but that no\n // longer want a nested transform. The drag handler may have already\n // overwritten `style.transform` with its own translate; only clear\n // when the parent isn't currently dragging (otherwise we'd stomp\n // the drag mid-gesture).\n for (const node of stack) {\n if (\n this.#nestedTransformOwned.has(node.host) &&\n !wantsNested.has(node.host) &&\n !node.dragging()\n ) {\n node.host.style.transform = '';\n this.#nestedTransformOwned.delete(node.host);\n }\n }\n });\n }\n\n /**\n * Build the nested-state transform string for a given drawer side. The\n * surface translates *away* from its anchored edge:\n *\n * - `bottom` (default) → translate up (`-translatePx` on Y).\n * - `top` → translate down (`+translatePx` on Y).\n * - `left` → translate left (`-translatePx` on X).\n * - `right` → translate right (`+translatePx` on X).\n *\n * The scale factor is uniform.\n */\n #nestedTransform(side: ForDrawerSide, amount: number, translatePx: number): string {\n const sign = side === 'top' ? 1 : -1;\n const tx = side === 'left' ? -translatePx : side === 'right' ? translatePx : 0;\n const ty = side === 'left' || side === 'right' ? 0 : sign * translatePx;\n return `scale(${amount}) translate3d(${tx}px, ${ty}px, 0)`;\n }\n\n /**\n * Register the consumer's app-shell wrapper. Only one wrapper may be\n * registered at a time; a second registration throws — the multi-wrapper\n * case has no defined visual outcome. Returns a cleanup that the caller wires to its\n * `DestroyRef.onDestroy`.\n */\n registerWrapper(host: HTMLElement): () => void {\n if (!this.#isBrowser) {\n return () => {};\n }\n if (this.#wrapperEl() !== null && this.#wrapperEl() !== host) {\n throw new Error(\n '[forty-cdk/drawer] Multiple [forDrawerWrapper] registered; only one wrapper is allowed per viewport.',\n );\n }\n this.#wrapperEl.set(host);\n return () => {\n if (this.#wrapperEl() === host) {\n this.#wrapperEl.set(null);\n }\n };\n }\n\n /**\n * Register an active drawer's scale config on the LIFO stack. Returns\n * a cleanup that pops the same entry — call from\n * `DestroyRef.onDestroy`. Calling `registerDrawer` without a registered\n * wrapper is silently a no-op (no styles applied) so test composition\n * and consumer flows don't have to enforce ordering.\n */\n registerDrawer(config: ForDrawerScaleConfig): () => void {\n if (!this.#isBrowser) {\n return () => {};\n }\n this.#stack.update((s) => [...s, config]);\n return () => {\n this.#stack.update((s) => {\n const idx = s.lastIndexOf(config);\n if (idx === -1) {\n return s;\n }\n const next = s.slice();\n next.splice(idx, 1);\n return next;\n });\n };\n }\n\n #apply(wrapper: HTMLElement, config: ForDrawerScaleConfig): void {\n if (!this.#wrapperSnapshot) {\n this.#wrapperSnapshot = {\n transform: wrapper.style.transform,\n transformOrigin: wrapper.style.transformOrigin,\n borderRadius: wrapper.style.borderRadius,\n overflow: wrapper.style.overflow,\n transitionProperty: wrapper.style.transitionProperty,\n transitionDuration: wrapper.style.transitionDuration,\n transitionTimingFunction: wrapper.style.transitionTimingFunction,\n };\n }\n\n const translate = `calc(env(safe-area-inset-top) + ${config.scaleTranslateYpx}px)`;\n wrapper.style.transform = `scale(${config.scaleAmount}) translate3d(0, ${translate}, 0)`;\n wrapper.style.transformOrigin = 'top';\n wrapper.style.borderRadius = `${config.scaleBorderRadiusPx}px`;\n wrapper.style.overflow = 'hidden';\n wrapper.style.transitionProperty = 'transform, border-radius';\n wrapper.style.transitionDuration = `${TRANSITION_DURATION_S}s`;\n wrapper.style.transitionTimingFunction = TRANSITION_TIMING;\n\n if (config.setBackgroundColorOnScale) {\n const body = this.#document.body;\n if (!this.#bodySnapshot) {\n this.#bodySnapshot = { backgroundColor: body.style.backgroundColor };\n }\n body.style.backgroundColor = config.scaleBackgroundColor;\n } else if (this.#bodySnapshot) {\n // Topmost drawer opts out — release the body snapshot we may have\n // taken from a previous (now-popped) drawer.\n this.#document.body.style.backgroundColor = this.#bodySnapshot.backgroundColor;\n this.#bodySnapshot = null;\n }\n }\n\n #revert(): void {\n if (this.#wrapperSnapshot) {\n const wrapper = this.#wrapperEl();\n if (wrapper) {\n wrapper.style.transform = this.#wrapperSnapshot.transform;\n wrapper.style.transformOrigin = this.#wrapperSnapshot.transformOrigin;\n wrapper.style.borderRadius = this.#wrapperSnapshot.borderRadius;\n wrapper.style.overflow = this.#wrapperSnapshot.overflow;\n wrapper.style.transitionProperty = this.#wrapperSnapshot.transitionProperty;\n wrapper.style.transitionDuration = this.#wrapperSnapshot.transitionDuration;\n wrapper.style.transitionTimingFunction = this.#wrapperSnapshot.transitionTimingFunction;\n }\n this.#wrapperSnapshot = null;\n }\n if (this.#bodySnapshot) {\n this.#document.body.style.backgroundColor = this.#bodySnapshot.backgroundColor;\n this.#bodySnapshot = null;\n }\n }\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport { DestroyRef, effect, inject, PLATFORM_ID, type Signal, signal } from '@angular/core';\n\nexport interface ElementBox {\n /** Border-box width in CSS pixels. */\n readonly width: number;\n /** Border-box height in CSS pixels. */\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 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 { DestroyRef, effect, ElementRef, inject, InjectionToken, type Signal } from '@angular/core';\nimport type { ValidationError } from '@angular/forms/signals';\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 * focus-on-label-click, unless {@link labelledElement} nominates a distinct\n * element.\n */\n readonly host: HTMLElement;\n /**\n * The element that should actually carry the field's `aria-*` association\n * and receive focus on label click, when it differs from {@link host}. For\n * primitives whose host is a non-interactive wrapper (`<div forSelect>`,\n * `<div forCombobox>`) this nominates the focusable control inside it (the\n * trigger button / `role=\"combobox\"` input), which registers after the field\n * wiring runs — hence a signal. When omitted or resolving to `null` the field\n * falls back to {@link host} (the host-is-the-control case, e.g. `ForListbox`\n * or a native `<input forFieldControl>`).\n */\n readonly labelledElement?: Signal<HTMLElement | null>;\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 /** Register the control whose state the field reflects. */\n registerControl(handle: FieldControlHandle): void;\n /** Remove a previously registered control. */\n unregisterControl(handle: FieldControlHandle): void;\n /**\n * Mark the label slot present; returns an unregister callback. The field\n * exposes a single `labelId` (not an id list), so one `[forLabel]` per field\n * is the supported shape — presence is boolean, not a count.\n */\n registerLabel(): () => void;\n /** Mark the description slot present; returns an unregister callback. Single `[forFieldDescription]` per field (single `descriptionId`). */\n registerDescription(): () => void;\n /** Mark the error slot present; returns an unregister callback. Single `[forFieldError]` per field (single `errorId`). */\n registerError(): () => void;\n /**\n * Forward a click to the registered control's focusable element, then focus\n * it — the 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 non-`<label>` `[forLabel]`, which has no native `for` forwarding, so\n * label-click activation stays consistent across host shapes.\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`, `aria-describedby`, and\n * `aria-errormessage` on the target, kept in sync via a single `effect`.\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\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 && previousTarget !== target) {\n clearFieldAttrs(previousTarget, ownsId, field.controlId());\n ownsId = false;\n }\n previousTarget = target;\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', field.describedBy());\n applyAttr(target, 'aria-errormessage', field.errorMessageId());\n });\n\n inject(DestroyRef).onDestroy(() => {\n if (previousTarget) {\n clearFieldAttrs(previousTarget, ownsId, field.controlId());\n }\n });\n}\n\n/**\n * Removes the field's association attributes (`aria-labelledby` /\n * `aria-describedby` / `aria-errormessage`) from a previously-targeted element,\n * plus the field-owned `id` when this helper set it. Symmetric with the\n * migration-cleanup branch so an arbitrary foreign `labelledElement` is left\n * clean once the control is destroyed or the target migrates.\n */\nfunction clearFieldAttrs(target: HTMLElement, ownsId: boolean, controlId: string): void {\n applyAttr(target, 'aria-labelledby', null);\n applyAttr(target, 'aria-describedby', null);\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` and registers its presence so the fieldset can resolve its\n * `aria-labelledby`; a descendant form control optionally reads\n * `effectiveDisabled` and ORs it into its own 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 * 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","/**\n * Computes `aria-posinset` / `aria-setsize` for every node in a **flat** list of\n * hierarchical rows, where depth is given only by each node's 1-based `level`\n * (as in an ARIA treegrid: rows are DOM siblings, hierarchy lives in `aria-level`).\n *\n * For a node at level `L`, its siblings are the nodes at the same level under the\n * same parent: contiguous `level === L` entries, skipping any deeper descendants\n * between them and bounded by the first shallower (`level < L`) entry on each side.\n *\n * Returns one `{ posinset, setsize }` entry per input level, in the same order.\n * Both are 1-based. An empty input returns an empty array.\n */\nexport function computeFlatHierarchy(\n levels: readonly number[],\n): { posinset: number; setsize: number }[] {\n return levels.map((level, index) => {\n let before = 0;\n for (let i = index - 1; i >= 0; i--) {\n const l = levels[i]!;\n if (l < level) break;\n if (l === level) before++;\n }\n let after = 0;\n for (let i = index + 1; i < levels.length; i++) {\n const l = levels[i]!;\n if (l < level) break;\n if (l === level) after++;\n }\n return { posinset: before + 1, setsize: before + 1 + after };\n });\n}\n","import type { Signal } from '@angular/core';\nimport type { ReferenceElement } from '@floating-ui/dom';\n\nimport type { FloatingAlign, FloatingConfig, FloatingSide } from './floating';\n\n/**\n * Single source of truth for the floating-ui positioning defaults shared by\n * the three trigger-anchored overlay roots — `[forPopover]`, `[forTooltip]`,\n * and `[forHoverCard]`.\n *\n * Angular's compiler requires every `input()` to be declared directly in a\n * class member initializer (NG8110), so the inputs themselves can't be\n * produced by a shared factory. To stop the (already-drifted) defaults from\n * diverging again, each root reads its non-seed defaults from this object and\n * the `anchored-positioning-inputs.spec.ts` guard asserts the three roots keep\n * an identical positioning input set.\n *\n * Only `side` / `align` / `sideOffset` / `collisionPadding` are seeded from\n * each root's defaults provider (`provideForPopoverDefaults` /\n * `provideForTooltipDefaults` / `provideForHoverCardDefaults`) so a scope\n * override flows through — and of those only `side` legitimately varies per\n * root (popover anchors `'bottom'`, tooltip / hover-card `'top'`). Everything\n * below is identical across all three roots.\n */\nexport const ANCHORED_POSITIONING_DEFAULTS = {\n /** Default gap (px) along the cross axis (parallel to `side`). */\n alignOffset: 0,\n /** `flip` / `shift` keep the surface inside the viewport by default. */\n avoidCollisions: true,\n /** Default padding (px) for the `arrow` middleware. */\n arrowPadding: 0,\n /** Default stickiness behaviour for `shift`. */\n sticky: 'partial' as 'partial' | 'always' | false,\n /** `data-detached=\"\"` is not reflected by default. */\n hideWhenDetached: false,\n /** Content is clipped until floating-ui resolves its first position by default. */\n clipUntilPositioned: true,\n} as const;\n\n/**\n * The resolved floating-ui positioning surface every trigger-anchored overlay\n * root publishes on its context. `ForPopoverContext`, `ForTooltipContext`, and\n * `ForHoverCardContext` all `extends` this so the 12-member positioning half of\n * each context interface is single-sourced rather than copied verbatim.\n *\n * Each member is the *effective* value — the per-instance input merged with the\n * scope default — so a content directive forwards it straight into\n * `injectOverlayShell` via `toFloatingPositioner` without re-resolving defaults.\n *\n * `open` is included because the floating positioner gates `autoUpdate` on it;\n * it is published by every root's open `model()` (a `ModelSignal` is a\n * `Signal`), so a single `extends` covers the whole positioner surface.\n */\nexport interface AnchoredPositioningContext {\n readonly open: Signal<boolean>;\n readonly side: Signal<FloatingSide>;\n readonly align: Signal<FloatingAlign>;\n readonly sideOffset: Signal<number>;\n readonly alignOffset: Signal<number>;\n readonly avoidCollisions: Signal<boolean>;\n readonly collisionPadding: Signal<number>;\n readonly arrowPadding: Signal<number>;\n readonly sticky: Signal<'partial' | 'always' | false>;\n readonly hideWhenDetached: Signal<boolean>;\n readonly clipUntilPositioned: Signal<boolean>;\n readonly arrow: Signal<HTMLElement | null>;\n}\n\n/**\n * Builds the `injectOverlayShell` floating-positioner block from an\n * `AnchoredPositioningContext` and the element the overlay anchors against.\n * Each of the three content directives (`ForPopoverContent`,\n * `ForTooltipContent`, `ForHoverCardContent`) built this 13-field block\n * verbatim; the only difference is the `reference` source — popover anchors to\n * its registered `[forPopoverAnchor]` (falling back to the trigger), tooltip\n * and hover-card anchor directly to the trigger — so the caller passes it in.\n */\nexport function toFloatingPositioner(\n ctx: AnchoredPositioningContext,\n reference: Signal<ReferenceElement | null>,\n): { kind: 'floating' } & FloatingConfig {\n return {\n kind: 'floating',\n reference,\n open: ctx.open,\n side: ctx.side,\n align: ctx.align,\n sideOffset: ctx.sideOffset,\n alignOffset: ctx.alignOffset,\n avoidCollisions: ctx.avoidCollisions,\n collisionPadding: ctx.collisionPadding,\n arrowPadding: ctx.arrowPadding,\n sticky: ctx.sticky,\n hideWhenDetached: ctx.hideWhenDetached,\n clipUntilPositioned: ctx.clipUntilPositioned,\n arrow: ctx.arrow,\n };\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 dismissable-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 dismissable 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 { DOCUMENT, PLATFORM_ID, DestroyRef, ElementRef, inject } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\nimport { afterNextRenderCancellable } from '../after-next-render-cancellable/after-next-render-cancellable';\n\nexport interface PortalConfig {\n /**\n * Where to portal the host element. Defaults to `document.body`. Pass a\n * specific container for cases like fullscreen API stacking, scoped\n * testing harnesses, or shadow DOM hosts.\n *\n * A function form is also accepted; it is resolved lazily inside the\n * existing `afterNextRender` callback so a value that is not yet available\n * at construction time — for example a directive input — can be used.\n * Returns `null` or `undefined` to fall back to `document.body`.\n */\n readonly target?: HTMLElement | (() => HTMLElement | null | undefined);\n}\n\n/**\n * Moves the directive's host element to `target` (default `document.body`)\n * after the first render and removes it on destroy. Designed for primitives\n * that need to escape clipping / `transform` / `overflow: hidden` ancestors:\n * tooltips, popovers, dialogs, toasts.\n *\n * Must be called from an injection context. The directive's `ElementRef` is\n * the host that gets portaled. Angular destroy hooks still fire normally —\n * the view tree is unaffected, only the DOM position changes.\n *\n * Note: any styles scoped to the original parent (CSS modules, encapsulated\n * `:host` rules, descendant selectors) won't reach the portaled element.\n * Style it via global CSS or with classes on the host directive itself.\n *\n * SSR: the portal is a no-op on the server. Overlay primitives use\n * `afterNextRender` to wire side effects, which doesn't run server-side\n * either; static markup (role, aria-*, ids, data-state) renders normally\n * and the portaled position is established once the client takes over.\n *\n * Implementation note — destroy ordering. The deferred `appendChild` is\n * registered via `afterNextRenderCancellable`; the destroy hook runs\n * `el.remove()`. If the directive is torn down between construction and the\n * next render (rare, but happens in synchronous open/close test paths or fast\n * SPA navigations), the destroy hook sees a not-yet-portaled element and\n * `el.remove()` is effectively a no-op against the original parent. Without\n * defending against it, the queued `afterNextRender` would still fire after\n * destroy and re-attach the element to `target` with no remaining destroy\n * hook to clean it up — a leak. The shared `afterNextRenderCancellable`\n * helper cancels the queued callback on destroy (it captures the\n * `AfterRenderRef`, calls `.destroy()` from its own destroy hook, and guards\n * the callback with a `destroyed` flag), so the `appendChild` never runs once\n * the directive is gone.\n */\nexport function injectPortal(config: PortalConfig = {}): void {\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n return;\n }\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const destroyRef = inject(DestroyRef);\n const doc = inject(DOCUMENT);\n const el = host.nativeElement;\n const resolveTarget = (): HTMLElement => {\n const t = typeof config.target === 'function' ? config.target() : config.target;\n return t ?? doc.body;\n };\n\n afterNextRenderCancellable(() => {\n const target = resolveTarget();\n if (el.parentNode !== target) {\n target.appendChild(el);\n }\n });\n\n destroyRef.onDestroy(() => {\n if (typeof requestAnimationFrame === 'undefined' || typeof el.getAnimations !== 'function') {\n el.remove();\n return;\n }\n requestAnimationFrame(() => {\n const animations = el.getAnimations();\n if (animations.length === 0) {\n el.remove();\n return;\n }\n Promise.all(animations.map((animation) => animation.finished.catch(() => undefined))).then(\n () => el.remove(),\n );\n });\n });\n}\n","import { afterNextRender, effect, ElementRef, inject, type Signal } from '@angular/core';\nimport {\n arrow,\n autoUpdate,\n computePosition,\n flip,\n hide,\n type Middleware,\n offset,\n type Padding,\n type Placement,\n type ReferenceElement,\n shift,\n size,\n} from '@floating-ui/dom';\n\nimport { injectPortal } from '../portal/portal';\n\nconst PLACEMENT_OPPOSITE: Record<FloatingSide, FloatingSide> = {\n top: 'bottom',\n right: 'left',\n bottom: 'top',\n left: 'right',\n};\n\n/** The four cardinal sides a floating element can be anchored to. */\nexport type FloatingSide = 'top' | 'right' | 'bottom' | 'left';\n\n/** Alignment along the side axis: at the start edge, centered, or at the end edge. */\nexport type FloatingAlign = 'start' | 'center' | 'end';\n\nexport interface FloatingConfig {\n /**\n * The anchor. Either a real DOM element (e.g. a button trigger) or a\n * floating-ui `VirtualElement` (e.g. for context menus that anchor at the\n * pointer position). Reactive — should emit `null` until the anchor is\n * available; positioning is skipped while `null`.\n */\n readonly reference: Signal<ReferenceElement | null>;\n\n /**\n * Whether the floating element is currently visible. `autoUpdate` is\n * started when this becomes `true` and torn down when it goes back to\n * `false`, so consumers don't pay for positioning while closed.\n */\n readonly open: Signal<boolean>;\n\n /**\n * Side the floating element is anchored to (`'top'`/`'right'`/`'bottom'`/\n * `'left'`). When omitted (or the signal returns `undefined`), defaults\n * to `'bottom'`. Pair with `align` for the full positioning\n * API.\n */\n readonly side?: Signal<FloatingSide | undefined>;\n\n /**\n * Alignment along the chosen side. Defaults to `'center'`. With `side`\n * this composes the floating-ui placement (e.g. `side: 'bottom'` +\n * `align: 'start'` → placement `'bottom-start'`).\n */\n readonly align?: Signal<FloatingAlign | undefined>;\n\n /**\n * Distance (px) between reference and floating along the *main* axis\n * (perpendicular to `side`). Forwarded to floating-ui's `offset`\n * middleware. Defaults to `0`.\n */\n readonly sideOffset?: Signal<number | undefined>;\n\n /**\n * Distance (px) along the *cross* axis (parallel to `side`). Useful for\n * shifting an `align: 'start'` popover slightly past the trigger edge.\n */\n readonly alignOffset?: Signal<number | undefined>;\n\n /**\n * Optional arrow element. When non-null, the `arrow` middleware is\n * registered and the helper writes `position: absolute`, the resolved\n * `left` / `top` from floating-ui, and a side-aware\n * `var(--for-arrow-offset, 0px)` on the *opposite* axis once floating-ui\n * resolves a position. Consumers control how far the arrow pokes out of\n * the bubble by setting `--for-arrow-offset` (typically a negative `px`\n * value) on the arrow element or any ancestor — the helper ships no\n * default visual.\n */\n readonly arrow?: Signal<HTMLElement | null>;\n\n /**\n * When `true` (default), the floating element is moved to `document.body`\n * on first render and removed on destroy. Set to `false` to keep it in\n * its declared parent (rare — only for designs where positioning ancestors\n * are guaranteed safe).\n */\n readonly portal?: boolean;\n\n /**\n * When `true` (default), the `flip` and `shift` middlewares are active so\n * the floating element stays inside the viewport. Set to `false` to keep\n * the requested placement even when it overflows — useful for tooltips\n * inside scroll containers where the consumer wants strict positioning.\n */\n readonly avoidCollisions?: Signal<boolean>;\n\n /**\n * Padding (px or per-side rect) applied to both `flip` and `shift`. When\n * unset, `flip` uses padding 0 (legacy behavior) and `shift` uses\n * `shiftPadding` (default 8). Setting this overrides both uniformly.\n */\n readonly collisionPadding?: Signal<number | Padding>;\n\n /**\n * Boundary the collision middlewares (`flip`, `shift`, `size`) measure\n * against. Defaults to the viewport. Pass an element (or list) to keep\n * the floating element inside a scroll container.\n */\n readonly collisionBoundary?: Signal<Element | Element[] | null>;\n\n /** Padding (px) handed to the `arrow` middleware so the arrow stays inside the floating element's rounded corners. */\n readonly arrowPadding?: Signal<number>;\n\n /**\n * Stickiness behaviour for `shift`. `'partial'` (default behavior of\n * `shift`) lets the floating element shift to stay visible. `'always'`\n * disables `shift` so the floating element keeps its requested placement\n * even off-screen. `false` is equivalent to `'partial'`.\n */\n readonly sticky?: Signal<'partial' | 'always' | false>;\n\n /**\n * When `true`, sets `data-detached=\"\"` on the host while the reference\n * element has scrolled off all clipping ancestors (`hide({ strategy:\n * 'escaped' })`). Lets consumers fade out tooltips/popovers tied to\n * scrolled-away triggers.\n */\n readonly hideWhenDetached?: Signal<boolean>;\n\n /**\n * When `true` (default / omitted), the floating element is clipped with\n * `clip-path: inset(50%)` until `@floating-ui/dom` resolves its first\n * position, so a short enter animation never flashes at the viewport\n * corner before placement lands. Set to `false` to paint from the first\n * frame — useful for a dramatic `animate.enter` that would otherwise lose\n * its opening frames while the async `computePosition` resolves, at the\n * cost of a possible first-frame flash at the pre-resolved position.\n */\n readonly clipUntilPositioned?: Signal<boolean>;\n\n /**\n * Padding (px) handed to the `shift` middleware so the floating element\n * never crowds the viewport edge. Default `8`. Used as the fallback for\n * `collisionPadding` when that signal is not provided.\n */\n readonly shiftPadding?: number;\n}\n\nfunction joinPlacement(side: FloatingSide, align: FloatingAlign): Placement {\n return (align === 'center' ? side : `${side}-${align}`) as Placement;\n}\n\nfunction splitPlacement(p: Placement): { side: FloatingSide; align: FloatingAlign } {\n const [rawSide, rawAlign] = p.split('-') as [FloatingSide, 'start' | 'end' | undefined];\n return { side: rawSide, align: rawAlign ?? 'center' };\n}\n\n/**\n * Compute the CSS `transform-origin` so a CSS scale animates outward from\n * the anchor edge. With `side: 'bottom', align: 'start'` the origin is\n * `left top` — a `scale(0.95)` collapses toward the trigger's bottom-left\n * corner.\n */\nfunction transformOriginFor(side: FloatingSide, align: FloatingAlign): string {\n let x: 'left' | 'right' | 'center';\n let y: 'top' | 'bottom' | 'center';\n if (side === 'top' || side === 'bottom') {\n y = side === 'top' ? 'bottom' : 'top';\n x = align === 'start' ? 'left' : align === 'end' ? 'right' : 'center';\n } else {\n x = side === 'left' ? 'right' : 'left';\n y = align === 'start' ? 'top' : align === 'end' ? 'bottom' : 'center';\n }\n return `${x} ${y}`;\n}\n\n/**\n * Wires a floating UI element (tooltip, popover, menu...) to its anchor.\n * Must be called from an injection context. Pulls the `ElementRef` it lives\n * on as the floating element. Owns:\n *\n * 1. Optional portal — `appendChild` to `document.body` once mounted, `remove()`\n * on `DestroyRef.onDestroy`.\n * 2. A reactive effect that subscribes to `open`/`reference`/`placement`/\n * offsets/arrow and runs `autoUpdate` while open, cleaning up via the\n * effect's `onCleanup` when the deps change or the host destroys.\n * 3. Inside `autoUpdate`'s callback, calls `computePosition` and applies the\n * resolved position via the `translate` property (leaving `transform`\n * free for the consumer's animations), plus `data-placement`, `data-side`,\n * `data-align`, `data-occluded` (when the `hide` middleware reports the\n * reference is off-screen), and CSS variables (`--for-anchor-width/-height`,\n * `--for-available-width/-height`, `--for-content-transform-origin`).\n * On the first resolved position it also drops the `clip-path` baseline\n * so the surface is only painted once anchored — otherwise a CSS enter\n * animation would flash at the viewport's top-left corner before\n * `computePosition` (which is async) resolves.\n *\n * Cleanup is symmetric: when `open` flips back to `false` (or the host is\n * destroyed) the helper clears every style, CSS variable, and `data-*`\n * attribute it set, on both the floating element and the optional arrow.\n * That keeps the next open from inheriting stale geometry from the\n * previous mount.\n *\n * Stylistic concerns (which side gets the arrow offset via\n * `--for-arrow-offset`, pointer events, background, animations) stay with\n * the consumer.\n */\nexport function injectFloating(config: FloatingConfig): void {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const el = host.nativeElement;\n\n if (config.portal !== false) {\n injectPortal();\n }\n\n afterNextRender(() => {\n // Baseline styles required for positioning. Set imperatively so consumer\n // host bindings don't have to remember.\n //\n // `clip-path: inset(50%)` keeps the surface unpainted until floating-ui\n // resolves its first position. `computePosition` is async, so without\n // this a CSS enter animation (`animate.enter`) plays one or two frames\n // at the `left:0 / top:0` origin — before the resolved position lands —\n // and the overlay flashes at the viewport's top-left corner. `clip-path`\n // (rather than `visibility: hidden`) keeps the element focusable, so the\n // overlay shell's initial-focus move still lands while the surface is\n // unpainted. Dropped on the first resolved position below.\n Object.assign(el.style, {\n position: 'fixed',\n left: '0',\n top: '0',\n });\n if (config.clipUntilPositioned?.() !== false) {\n el.style.clipPath = 'inset(50%)';\n }\n });\n\n const fallbackShiftPadding = config.shiftPadding ?? 8;\n\n effect((onCleanup) => {\n // Read `open`/`reference` first and early-return before establishing\n // dependencies on the rest of the config. A closed overlay must only\n // track `open`/`reference` — reading the rest up front would re-run this\n // effect on any offset/side change while closed, defeating the \"don't\n // pay for positioning while closed\" intent.\n const isOpen = config.open();\n const reference = config.reference();\n\n if (!isOpen || !reference) {\n return;\n }\n\n const arrowEl = config.arrow?.() ?? null;\n\n // Re-arm the `clip-path: inset(50%)` baseline at the start of every open\n // effect run, not only in `afterNextRender`. A config change while open\n // re-runs this effect: `onCleanup` calls `resetFloatingStyles`, which\n // clears `clip-path`, so without re-arming the surface would paint at the\n // previous frame's stale `translate` until the async `computePosition`\n // resolves. Re-arming hides it until the first resolved position drops the\n // baseline again below.\n if (config.clipUntilPositioned?.() !== false) {\n el.style.clipPath = 'inset(50%)';\n }\n\n // Resolve placement from `side` + `align` with sensible defaults.\n const sideInput = config.side?.() ?? 'bottom';\n const alignInput = config.align?.() ?? 'center';\n const requestedPlacement: Placement = joinPlacement(sideInput, alignInput);\n\n const sideOffsetVal = config.sideOffset?.() ?? 0;\n const alignOffsetVal = config.alignOffset?.() ?? 0;\n const avoidCollisions = config.avoidCollisions?.() ?? true;\n // `collisionPadding`, when set, applies uniformly to flip + shift +\n // size. When unset, preserve the historical defaults:\n // `flip` had no padding, `shift` had `shiftPadding ?? 8`.\n const collisionPaddingExplicit = config.collisionPadding?.();\n const flipPaddingValue = collisionPaddingExplicit ?? 0;\n const shiftPaddingValue = collisionPaddingExplicit ?? fallbackShiftPadding;\n const sizePaddingValue = collisionPaddingExplicit ?? fallbackShiftPadding;\n const collisionBoundary = config.collisionBoundary?.() ?? null;\n const arrowPaddingVal = config.arrowPadding?.() ?? 0;\n const stickyVal = config.sticky?.() ?? false;\n const hideOnDetach = config.hideWhenDetached?.() ?? false;\n\n const middleware: Middleware[] = [\n offset({ mainAxis: sideOffsetVal, crossAxis: alignOffsetVal }),\n ];\n\n if (avoidCollisions) {\n const flipOptions: Parameters<typeof flip>[0] = { padding: flipPaddingValue };\n if (collisionBoundary) flipOptions.boundary = collisionBoundary;\n middleware.push(flip(flipOptions));\n\n if (stickyVal !== 'always') {\n const shiftOptions: Parameters<typeof shift>[0] = { padding: shiftPaddingValue };\n if (collisionBoundary) shiftOptions.boundary = collisionBoundary;\n middleware.push(shift(shiftOptions));\n }\n }\n\n // `size` exposes available width/height as CSS variables so the\n // consumer can `max-height: var(--for-available-height)` etc.\n const sizeOptions: Parameters<typeof size>[0] = {\n padding: sizePaddingValue,\n apply({ availableWidth, availableHeight }) {\n el.style.setProperty(\n '--for-available-width',\n `${Math.max(0, Math.round(availableWidth))}px`,\n );\n el.style.setProperty(\n '--for-available-height',\n `${Math.max(0, Math.round(availableHeight))}px`,\n );\n },\n };\n if (collisionBoundary) sizeOptions.boundary = collisionBoundary;\n middleware.push(size(sizeOptions));\n\n middleware.push(hide({ strategy: 'referenceHidden' }));\n if (hideOnDetach) {\n middleware.push(hide({ strategy: 'escaped' }));\n }\n\n if (arrowEl) {\n middleware.push(arrow({ element: arrowEl, padding: arrowPaddingVal }));\n }\n\n const cleanup = autoUpdate(reference, el, () => {\n computePosition(reference, el, {\n strategy: 'fixed',\n placement: requestedPlacement,\n middleware,\n })\n .then(({ x, y, placement: resolvedPlacement, middlewareData }) => {\n // The element may have been hidden again between schedule and\n // resolution — bail so styles aren't clobbered after close.\n if (!config.open()) {\n return;\n }\n\n const { side: resolvedSide, align: resolvedAlign } = splitPlacement(\n resolvedPlacement as Placement,\n );\n\n // Position via the `translate` property, NOT `transform`. CSS\n // composes the individual `translate` / `rotate` / `scale`\n // properties before the `transform` property, with `translate`\n // outermost — so a consumer's enter animation on `scale` (or\n // `transform`) pivots in place around `--for-content-transform-origin`\n // instead of scaling the position offset itself. Using `transform`\n // here made `scale(0.9)` shrink the translation too, dragging the\n // surface in from the viewport's top-left corner as it grew. Leaving\n // `transform` free for the consumer is the whole point.\n el.style.translate = `${Math.round(x)}px ${Math.round(y)}px`;\n el.dataset['placement'] = resolvedPlacement;\n el.dataset['side'] = resolvedSide;\n el.dataset['align'] = resolvedAlign;\n // First valid position resolved — reveal the surface by dropping\n // the `clip-path: inset(50%)` baseline. From here the consumer's\n // enter animation runs anchored to the trigger, with the scale\n // origin set by `--for-content-transform-origin` below.\n el.style.clipPath = '';\n\n // Anchor box → CSS vars so the consumer can size the floating\n // element relative to the anchor (`width: var(--for-anchor-width)`).\n // Both real `Element`s and floating-ui `VirtualElement`s expose\n // `getBoundingClientRect`, so the call is safe.\n const rect = reference.getBoundingClientRect();\n el.style.setProperty('--for-anchor-width', `${Math.round(rect.width)}px`);\n el.style.setProperty('--for-anchor-height', `${Math.round(rect.height)}px`);\n el.style.setProperty(\n '--for-content-transform-origin',\n transformOriginFor(resolvedSide, resolvedAlign),\n );\n\n // hide() with strategy 'referenceHidden' — anchor scrolled off-screen.\n if (middlewareData.hide?.['referenceHidden']) {\n el.dataset['occluded'] = '';\n } else {\n delete el.dataset['occluded'];\n }\n // hide() with strategy 'escaped' — only registered when\n // `hideWhenDetached` is on.\n if (hideOnDetach && middlewareData.hide?.['escaped']) {\n el.dataset['detached'] = '';\n } else {\n delete el.dataset['detached'];\n }\n\n if (arrowEl && middlewareData.arrow) {\n const { x: ax, y: ay } = middlewareData.arrow;\n const opposite = PLACEMENT_OPPOSITE[resolvedSide];\n Object.assign(arrowEl.style, {\n position: 'absolute',\n left: ax != null ? `${ax}px` : '',\n top: ay != null ? `${ay}px` : '',\n right: '',\n bottom: '',\n [opposite]: 'var(--for-arrow-offset, 0px)',\n });\n // `data-placement` on the arrow stores the *side* only, for\n // historical reasons (CSS like `[data-placement=\"top\"]`).\n // `data-side` is the new canonical attribute; both stay in\n // sync until consumers migrate.\n arrowEl.dataset['placement'] = resolvedSide;\n arrowEl.dataset['side'] = resolvedSide;\n }\n })\n // The reference can detach mid-frame during virtualization /\n // autoUpdate scrolls, which makes computePosition reject. Swallow\n // — autoUpdate will reschedule with the next live frame and the\n // previous styles are still on the element.\n .catch(() => {});\n });\n\n // Clean up symmetrically with what computePosition wrote so a re-open\n // doesn't inherit stale geometry from the previous mount.\n onCleanup(() => {\n cleanup();\n resetFloatingStyles(el);\n if (arrowEl) {\n resetArrowStyles(arrowEl);\n }\n });\n });\n}\n\n/**\n * Strip the transient sizing CSS custom properties, the occlusion `data-*`\n * attributes, and the `clip-path` hide baseline `injectFloating` writes to the\n * floating element. The resolved `translate` and the resolved-placement outputs\n * (`--for-content-transform-origin`, `data-placement`, `data-side`,\n * `data-align`) are intentionally retained so a closing surface stays anchored\n * to its trigger — and keeps pivoting its scale leave from the trigger edge —\n * through `animate.leave`; the next mount re-arms the `clip-path` baseline in\n * `afterNextRender` and recomputes all of them before painting, so a retained\n * value never produces a stale-position flash.\n */\nfunction resetFloatingStyles(el: HTMLElement): void {\n // Clearing (not re-arming) the hide baseline keeps a closing surface\n // visible for its `animate.leave`; the next mount re-applies the\n // `clip-path` baseline in `afterNextRender`.\n el.style.removeProperty('clip-path');\n el.style.removeProperty('--for-anchor-width');\n el.style.removeProperty('--for-anchor-height');\n el.style.removeProperty('--for-available-width');\n el.style.removeProperty('--for-available-height');\n el.removeAttribute('data-occluded');\n el.removeAttribute('data-detached');\n}\n\n/**\n * Strip every inline style and `data-*` attribute `injectFloating` writes\n * to the optional arrow element. Mirrors `resetFloatingStyles`.\n */\nfunction resetArrowStyles(arrowEl: HTMLElement): void {\n arrowEl.style.removeProperty('position');\n arrowEl.style.removeProperty('left');\n arrowEl.style.removeProperty('top');\n arrowEl.style.removeProperty('right');\n arrowEl.style.removeProperty('bottom');\n arrowEl.removeAttribute('data-placement');\n arrowEl.removeAttribute('data-side');\n}\n","import { DOCUMENT, ElementRef, Injectable, inject } from '@angular/core';\n\n/**\n * Shared CSS selector for tabbable 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 */\nexport const FOCUSABLE_SELECTOR = [\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 '[tabindex]:not([tabindex=\"-1\"])',\n '[contenteditable=\"true\"]',\n 'audio[controls]',\n 'video[controls]',\n].join(',');\n\n/**\n * Returns the first tabbable descendant of `container`, or `null` if none\n * exists. Mirrors the filter used by `FocusTrap` (excludes `[hidden]` and\n * descendants of `[inert]` ancestors below the container).\n */\nexport function findFirstFocusable(container: HTMLElement): HTMLElement | null {\n const candidates = Array.from(container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR));\n for (const el of candidates) {\n if (el.hasAttribute('hidden')) {\n continue;\n }\n if (hasInertAncestor(el, container)) {\n continue;\n }\n return el;\n }\n return null;\n}\n\nfunction hasInertAncestor(el: HTMLElement, root: HTMLElement): boolean {\n let cur: HTMLElement | null = el.parentElement;\n while (cur && cur !== root) {\n if (cur.hasAttribute('inert')) {\n return true;\n }\n cur = cur.parentElement;\n }\n return false;\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 * When `true`, sets up Tab cycling and captures the previously-focused\n * element for return on deactivate, but skips the imperative `.focus()`\n * call. Lets the consumer keep focus elsewhere on open while still\n * benefitting from the trap's keyboard cycling once focus enters the\n * surface. Default `false`.\n */\n preventInitialFocus?: boolean;\n /**\n * Explicit element to restore focus to on `deactivate({ returnFocus: true })`.\n * When omitted (default), the trap captures `document.activeElement` at\n * activation time. Pass this when the caller needs to lock the return\n * target *before* a side-effect that mutates focus — e.g. `ForDialog`\n * capturing the trigger before applying `inert` on siblings, since\n * WebKit auto-blurs descendants of a freshly-inert ancestor.\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 currently-active `FocusTrap`\n * instances. Each trap registers itself on `activate` and removes itself\n * on `deactivate`. The topmost trap is the only one that handles Tab — all\n * earlier (shallower) traps' keydown listeners are no-ops while shadowed,\n * which is what makes nested overlays (e.g. a drawer inside a drawer) trap\n * focus inside the topmost surface instead of the parent's \"focus jumped\n * outside\" guard yanking focus back to the parent.\n *\n * Why a service rather than module-level state:\n *\n * - Bootstrap-safety: a module-level array survives\n * `TestBed.resetTestingModule()`, micro-frontend reloads and any other\n * code that destroys `ApplicationRef`, so a stale LIFO can leak across\n * bootstraps. A `providedIn: 'root'` service is instantiated per\n * application injector and garbage-collected with it, so every bootstrap\n * starts with an empty stack.\n * - SSR isolation: module-level globals leak between simultaneous server\n * requests in the same Node process; a root-scoped service is per-request.\n *\n * This mirrors the storage strategy of `DismissableLayerStack`: all\n * overlay-nesting LIFO stacks are root-scoped DI services, never\n * module-level. The two remain separate services on purpose because they\n * own different responsibilities — `DismissableLayerStack` centrally owns\n * the shared `document` listeners for Escape / outside-interaction, whereas\n * each `FocusTrap` owns its own keydown listener and only consults this\n * registry to decide whether it is topmost. This holder therefore needs no\n * `DOCUMENT` / `PLATFORM_ID` / `DestroyRef` injection: it is a\n * dependency-free LIFO of trap instances.\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. Used by Dialog,\n * Drawer, Sheet, and any other primitive that needs to keep keyboard focus\n * scoped to a section of the page.\n *\n * When multiple traps are active simultaneously (nested overlays), only\n * the LIFO topmost trap handles Tab. Outer traps stay registered (so\n * cleanup ordering is preserved) but their keydown handlers are no-ops\n * until the deeper trap deactivates.\n *\n * Out of scope: marking the rest of the page `inert` (focus trap alone is\n * enough for keyboard users; pointer-isolation is the consumer's job via\n * a backdrop).\n */\nexport class FocusTrap {\n readonly #container: HTMLElement;\n readonly #stack: FocusTrapStack;\n readonly #document: Document;\n #returnTo: HTMLElement | null = null;\n #active = false;\n #containerHadTabindex = false;\n #focusablesCache: HTMLElement[] | null = null;\n #observer: MutationObserver | null = null;\n\n readonly #onKeyDown = (event: KeyboardEvent): void => this.#handleKeyDown(event);\n\n constructor(container: HTMLElement, stack: FocusTrapStack, doc?: Document) {\n this.#container = container;\n this.#stack = stack;\n this.#document = doc ?? container.ownerDocument;\n }\n\n get container(): HTMLElement {\n return this.#container;\n }\n\n get isActive(): boolean {\n return this.#active;\n }\n\n activate(options: FocusTrapActivateOptions = {}): void {\n if (this.#active) {\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 : ((this.#document.activeElement as HTMLElement | null) ?? null);\n this.#document.addEventListener('keydown', this.#onKeyDown, true);\n this.#stack.push(this);\n\n const win = this.#container.ownerDocument.defaultView;\n if (win && typeof win.MutationObserver === 'function') {\n this.#observer = new win.MutationObserver(() => {\n this.#focusablesCache = null;\n });\n this.#observer.observe(this.#container, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['disabled', 'hidden', 'inert', 'tabindex', 'type', 'contenteditable'],\n });\n }\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 = this.#focusables()[0];\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 deactivate(options: FocusTrapDeactivateOptions = {}): void {\n if (!this.#active) {\n return;\n }\n this.#active = false;\n this.#document.removeEventListener('keydown', this.#onKeyDown, true);\n this.#stack.remove(this);\n this.#observer?.disconnect();\n this.#observer = null;\n this.#focusablesCache = null;\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) {\n this.#returnTo.focus();\n }\n this.#returnTo = null;\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 focusables = this.#focusables();\n if (focusables.length === 0) {\n event.preventDefault();\n this.#focusContainer();\n return;\n }\n const first = focusables[0]!;\n const last = focusables[focusables.length - 1]!;\n const active = this.#document.activeElement;\n\n if (!this.#container.contains(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 #focusables(): HTMLElement[] {\n if (this.#focusablesCache !== null) {\n return this.#focusablesCache;\n }\n const all = Array.from(this.#container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR));\n this.#focusablesCache = all.filter(\n (el) => !el.hasAttribute('hidden') && !this.#hasInertAncestor(el),\n );\n return this.#focusablesCache;\n }\n\n #hasInertAncestor(el: HTMLElement): boolean {\n let cur: HTMLElement | null = el;\n while (cur && cur !== this.#container) {\n if (cur.hasAttribute('inert')) {\n return true;\n }\n cur = cur.parentElement;\n }\n return false;\n }\n}\n\n/**\n * Creates a `FocusTrap` for the directive's host element. Activation and\n * deactivation are the consumer's responsibility — call `trap.activate()`\n * when the surface opens and `trap.deactivate({ returnFocus })` from a\n * `DestroyRef.onDestroy` (or equivalent) when it closes.\n *\n * The helper deliberately does NOT register a safety-net teardown: forcing\n * `returnFocus: false` from the helper would race consumer cleanups that\n * want `returnFocus: true`, and an unconditional `returnFocus: true` could\n * dump focus on a removed element. The consumer always knows the right\n * answer; do the deactivate yourself.\n */\nexport function injectFocusTrap(): FocusTrap {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n return new FocusTrap(host.nativeElement, inject(FocusTrapStack), inject(DOCUMENT));\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 { FOCUSABLE_SELECTOR } from '../focus-trap/focus-trap';\n\n/**\n * Reports whether the host element currently has at least one focusable\n * descendant, reactive to subtree mutations.\n *\n * Used by `ForTabsContent` to implement the WAI-ARIA Tabs APG rule that a\n * `tabpanel` is itself a tab stop (`tabindex=\"0\"`) **only** when it has no\n * focusable content of its own; a panel containing buttons / links / form\n * controls must not add a redundant tab stop.\n *\n * Detection mirrors the `FocusTrap` filter: it queries the shared\n * `FOCUSABLE_SELECTOR` and ignores `[hidden]` candidates and any candidate\n * nested under an `[inert]` ancestor below the host (those are not reachable\n * by Tab). A single `MutationObserver` scoped to the host's subtree watches\n * for childList / attribute changes so a panel that gains or loses focusable\n * content after first render flips the result.\n *\n * SSR-safe: on the server no observer is created, the DOM is never touched,\n * and the signal stays `false` (the panel is treated as having no focusable\n * content until the first browser render measures it). Cleaned up via\n * `DestroyRef`.\n *\n * The observer callback writing the signal is the single, intentional\n * \"external imperative source → signal\" exception, isolated here.\n *\n * Must be called from an injection context (it injects `ElementRef`,\n * `PLATFORM_ID`, and `DestroyRef`).\n *\n * Internal — not re-exported from `public-api.ts`.\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 = host.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR);\n for (const el of candidates) {\n if (el.hasAttribute('hidden')) {\n continue;\n }\n if (hasInertAncestor(el, host)) {\n continue;\n }\n return true;\n }\n return false;\n}\n\nfunction hasInertAncestor(el: HTMLElement, root: HTMLElement): boolean {\n let cur: HTMLElement | null = el.parentElement;\n while (cur && cur !== root) {\n if (cur.hasAttribute('inert')) {\n return true;\n }\n cur = cur.parentElement;\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 '../fieldset/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 — not re-exported from `public-api.ts`.\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 alongside every internal `touched` flip (blur, dismiss,\n * selection-commit). `[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 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 */\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 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.invalid());\n });\n injectFieldWiring({\n invalid: this.invalid,\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 });\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 — not re-exported from `public-api.ts`.\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 '../disabled-reflection/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 deliberately 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 — not re-exported from `public-api.ts`.\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","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","/**\n * A single self-clearing debounce timer: the `Math.max(0, delay)` clamp, the\n * `delay === 0` synchronous fast-path, and the lone pending\n * `setTimeout` / `clearTimeout` pair.\n *\n * The hover-driven menus (`[forMenuSub]`, `[forMenubar]`, `[forNavigationMenu]`)\n * each hand-rolled this exact timer arming/clearing under their own divergent\n * open/close policy (chain keep-alive, hover-after-open, per-value cancel\n * guards, skip-delay). This factory owns only the timing mechanics so those\n * policies stay at the call site — the caller arms with `schedule(delay)`,\n * which clears any in-flight timer first, runs `run` immediately when the\n * clamped delay is `0`, else fires it once after the delay. Internal — not\n * re-exported from `public-api.ts`.\n */\nexport interface DebouncedAction {\n /**\n * Arm the action after `delay` ms (clamped to `>= 0`). Clears any pending\n * timer first; a clamped delay of `0` runs `run` synchronously.\n */\n schedule(delay: number): void;\n /** Cancel a pending action without running it. Safe with no pending timer. */\n cancel(): void;\n /** `true` while an action is armed but not yet fired. */\n isPending(): boolean;\n}\n\n/**\n * Builds a {@link DebouncedAction} around `run`. Framework-free.\n */\nexport function createDebouncedAction(run: () => void): DebouncedAction {\n let timer: ReturnType<typeof setTimeout> | null = null;\n\n function cancel(): void {\n if (timer !== null) {\n clearTimeout(timer);\n timer = null;\n }\n }\n\n function schedule(delay: number): void {\n cancel();\n const clamped = Math.max(0, delay);\n if (clamped === 0) {\n run();\n return;\n }\n timer = setTimeout(() => {\n timer = null;\n run();\n }, clamped);\n }\n\n return {\n schedule,\n cancel,\n isPending: () => timer !== null,\n };\n}\n","import { effect, type Signal, untracked, type WritableSignal } from '@angular/core';\n\n/**\n * Inputs for {@link forceCloseWhenDisabled}.\n */\nexport interface ForceCloseWhenDisabledOptions {\n /** Open-state signal that is force-closed when `disabled` flips to true. */\n open: WritableSignal<boolean>;\n /** Whether all hover / focus interaction is currently ignored. */\n disabled: Signal<boolean>;\n /** Imperative cleanup run before the force-close (cancel any pending timers). */\n onForceClose: () => void;\n}\n\n/**\n * The single audited place that force-closes a hover-driven overlay when its\n * `disabled` input flips to `true` while open.\n *\n * Tooltip and Hover-card each carried a byte-identical copy of this reaction;\n * it is the **one sanctioned exception** to the project's \"never propagate\n * state inside `effect()`\" rule, so it must live in exactly one place rather\n * than two carve-outs to audit. The hover scheduler already early-returns on\n * `disabled()`, so hover / focus can't open a disabled overlay; this isolated\n * reaction only covers the remaining path — an open overlay being disabled out\n * from under itself.\n *\n * The `open` read is `untracked` so the effect never re-runs as a function of\n * `open` (no read+write cycle on the same signal); it reacts to `disabled`\n * alone. It integrates the disabled gate with the public `model()` instead of\n * wrapping the model in a parallel signal.\n *\n * Must be called from an injection context (registers an `effect`). Internal —\n * not re-exported from `public-api.ts`.\n */\nexport function forceCloseWhenDisabled(options: ForceCloseWhenDisabledOptions): void {\n effect(() => {\n if (options.disabled() && untracked(options.open)) {\n options.onForceClose();\n options.open.set(false);\n }\n });\n}\n","import type { WritableSignal } from '@angular/core';\n\n/**\n * Per-injector-scope coordinator the hover-intent scheduler consults to decide\n * whether the open delay should be skipped, and to open the skip-delay window\n * when a primitive finishes closing. Both `TooltipCoordinator` and\n * `HoverCardCoordinator` satisfy this contract structurally.\n */\nexport interface HoverIntentCoordinator {\n /** True while a peer in this scope just closed and the next open is instant. */\n skipDelay(): boolean;\n /** Opens the skip-delay window. Called by the scheduler when it closes. */\n startSkipDelay(): void;\n}\n\n/**\n * Inputs for {@link createHoverIntent}. Delays are passed as accessor\n * functions so the scheduler reads resolved values (per-instance override or\n * scope default) at the moment a timer is armed.\n */\nexport interface HoverIntentOptions {\n /** Writable open-state signal the scheduler flips. */\n open: WritableSignal<boolean>;\n /** Whether all hover / focus interaction is currently ignored. */\n isDisabled: () => boolean;\n /** Resolved open delay (ms) to use when arming an open timer. */\n openDelay: () => number;\n /** Resolved close delay (ms) to use when arming a close timer. */\n closeDelay: () => number;\n /** Skip-delay coordinator shared by peers in the same scope. */\n coordinator: HoverIntentCoordinator;\n}\n\n/**\n * Hover-intent scheduler handle returned by {@link createHoverIntent}.\n */\nexport interface HoverIntentScheduler {\n /** Schedule the open after the resolved open delay (instant when delay is 0 or skipped). */\n scheduleOpen(): void;\n /** Schedule the close after the resolved close delay; `immediate` bypasses the delay. */\n scheduleClose(immediate: boolean): void;\n /** Cancel any pending open / close timer without changing state. */\n cancelPending(): void;\n}\n\n/**\n * Shared hover-intent scheduler for Tooltip and Hover-card.\n *\n * Both primitives carry an identical open / close timer with skip-delay\n * coordination and `Math.max(0, …)` guards; this framework-free factory holds\n * the single pending timer and the open / close logic, parameterized by the\n * resolved open / close delays plus a {@link HoverIntentCoordinator}. The\n * directive constructs it once (after its `open` signal exists) and delegates\n * its public scheduling methods to the returned handle. Internal — not\n * re-exported from `public-api.ts`.\n */\nexport function createHoverIntent(options: HoverIntentOptions): HoverIntentScheduler {\n let pendingTimer: ReturnType<typeof setTimeout> | null = null;\n\n function cancelPending(): void {\n if (pendingTimer !== null) {\n clearTimeout(pendingTimer);\n pendingTimer = null;\n }\n }\n\n function close(): void {\n options.open.set(false);\n options.coordinator.startSkipDelay();\n }\n\n function scheduleOpen(): void {\n cancelPending();\n if (options.isDisabled()) {\n return;\n }\n if (options.open()) {\n return;\n }\n const base = options.coordinator.skipDelay() ? 0 : options.openDelay();\n const delay = Math.max(0, base);\n if (delay === 0) {\n options.open.set(true);\n return;\n }\n pendingTimer = setTimeout(() => {\n pendingTimer = null;\n if (options.isDisabled()) {\n return;\n }\n options.open.set(true);\n }, delay);\n }\n\n function scheduleClose(immediate: boolean): void {\n cancelPending();\n if (!options.open()) {\n return;\n }\n if (immediate) {\n close();\n return;\n }\n const delay = Math.max(0, options.closeDelay());\n if (delay === 0) {\n close();\n return;\n }\n pendingTimer = setTimeout(() => {\n pendingTimer = null;\n close();\n }, delay);\n }\n\n return { scheduleOpen, scheduleClose, cancelPending };\n}\n","import { DestroyRef, inject, signal } from '@angular/core';\n\nimport type { HoverIntentCoordinator } from './hover-intent';\n\n/**\n * Resolved cadence the {@link SkipDelayCoordinator} needs from its primitive's\n * defaults scope. Tooltip and Hover-card resolve these from their respective\n * `ForTooltipDefaults` / `ForHoverCardDefaults` tokens and hand them down.\n */\nexport interface SkipDelayCoordinatorDefaults {\n /** Resolved default open delay (ms) for primitives in this scope. */\n openDelay: number;\n /** Resolved default close delay (ms) for primitives in this scope. */\n closeDelay: number;\n /** Resolved skip-delay window (ms) for primitives in this scope. */\n skipDelayDuration: number;\n}\n\n/**\n * Per-injector-scope skip-delay coordinator shared by Tooltip and Hover-card.\n *\n * Holds the single skip-delay flag and the timer that closes its window, plus\n * the resolved cadence its primitives read when arming open / close timers.\n * Both primitives previously hand-rolled byte-identical copies of this state\n * machine; this is the single class, subclassed once per primitive so each\n * keeps its own DI token (and therefore its own independent skip-delay scope).\n *\n * Satisfies {@link HoverIntentCoordinator} so the shared hover-intent\n * scheduler consumes it directly. Internal — not re-exported from\n * `public-api.ts`.\n */\nexport abstract class SkipDelayCoordinator implements HoverIntentCoordinator {\n readonly #skipDelay = signal(false);\n #timer: ReturnType<typeof setTimeout> | null = null;\n\n /** Resolved default open delay (ms) for primitives in this scope. */\n readonly openDelay: number;\n\n /** Resolved default close delay (ms) for primitives in this scope. */\n readonly closeDelay: number;\n\n /** Resolved skip-delay window (ms) for primitives in this scope. */\n readonly skipDelayDuration: number;\n\n /** True while a peer in this scope just closed and the next open is instant. */\n readonly skipDelay = this.#skipDelay.asReadonly();\n\n constructor(defaults: SkipDelayCoordinatorDefaults) {\n this.openDelay = defaults.openDelay;\n this.closeDelay = defaults.closeDelay;\n this.skipDelayDuration = defaults.skipDelayDuration;\n inject(DestroyRef).onDestroy(() => this.cancelSkipDelay());\n }\n\n /** Opens the skip-delay window. Called by primitives when they finish closing. */\n startSkipDelay(): void {\n this.cancelSkipDelay();\n this.#skipDelay.set(true);\n this.#timer = setTimeout(\n () => {\n this.#skipDelay.set(false);\n this.#timer = null;\n },\n Math.max(0, this.skipDelayDuration),\n );\n }\n\n /** Cancels any pending skip-delay window. */\n cancelSkipDelay(): void {\n if (this.#timer !== null) {\n clearTimeout(this.#timer);\n this.#timer = null;\n }\n this.#skipDelay.set(false);\n }\n}\n","import { DOCUMENT, Injectable, PLATFORM_ID, inject } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\n/**\n * Marks every direct child of a **root element** (default `document.body`,\n * or a positioned container when a region-scoped modal passes one — #819)\n * other than the topmost active owner (and any element flagged as a\n * peer-of-owner via the `data-for-modal-peer` attribute) as `inert` and\n * `aria-hidden=\"true\"` while at least one owner is active on that root.\n * Restores each touched element to its exact prior state once the last\n * owner deactivates.\n *\n * Why this exists: `aria-modal=\"true\"` alone is insufficient. Safari +\n * VoiceOver and several other AT combinations still announce siblings of an\n * aria-modal node unless the rest of the document is explicitly hidden. The\n * WAI-ARIA APG modal-dialog pattern recommends combining `aria-modal` with\n * isolating the rest of the page.\n *\n * Stacking model (LIFO with safe out-of-order teardown) — per root:\n *\n * - Each root has its own owner-stack, applied snapshot, and\n * `MutationObserver`. A `document.body` root and a container root are\n * fully independent — locking one does not affect the other.\n * - A stack of active owners is maintained per root. The element-level\n * outcome is computed from the *current topmost owner* every time the\n * stack changes.\n * - When the topmost owner changes, the previous outcome is fully reverted\n * to the snapshot captured before it was applied, then a fresh outcome is\n * computed and applied for the new topmost.\n * - This means closing dialogs out of LIFO order still leaves the document\n * in a coherent state: the topmost remaining dialog gets its expected\n * isolation, and full restoration runs only when the stack empties.\n *\n * Portal compatibility: the owner does not need to be a direct child of the\n * root. We resolve the *root-level child* that is an ancestor of the owner\n * and exclude that subtree, so an in-place (non-portaled) dialog still keeps\n * its enclosing app shell interactive while everything else is inerted.\n *\n * Peers: any element carrying the `data-for-modal-peer` attribute is\n * excluded from the snapshot (e.g. a dialog backdrop portaled to body\n * alongside the dialog).\n *\n * Late siblings: an element portaled to the root *after* the topmost owner\n * activated would otherwise escape the isolation, since the initial sweep\n * only sees the children present at activation. While any owner is active a\n * `MutationObserver` watches the root's child list and inerts each newly\n * added sibling under the same skip/snapshot rules, so it is restored on\n * teardown too. The observer starts on the 0→1 owner transition and\n * disconnects when the stack empties.\n *\n * SSR: the registry is `providedIn: 'root'` so its state is scoped to a\n * single Angular bootstrap (one per SSR request). On the server, every\n * operation is a no-op — overlays only call `activate()` from\n * `afterNextRender`, which doesn't run server-side.\n */\n\n/**\n * Attribute that exempts a root-level child from the modal inert pass.\n * Carried by dialog / drawer backdrops (portaled alongside the modal)\n * and stamped by `injectOverlayShell` onto anchored-overlay hosts that were\n * opened from inside the protected root (#676), 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 */\nexport const MODAL_PEER_ATTRIBUTE = 'data-for-modal-peer';\n\ninterface SnapshotEntry {\n readonly el: HTMLElement;\n readonly hadInert: boolean;\n readonly prevAriaHidden: string | null;\n}\n\nexport interface InertSiblingsHandle {\n /** Pop this owner off the stack and recompute. */\n deactivate(): void;\n /** Whether this handle is still on the stack. */\n readonly isActive: boolean;\n}\n\ninterface RootState {\n readonly root: HTMLElement;\n readonly stack: HTMLElement[];\n appliedSnapshot: SnapshotEntry[];\n observer: MutationObserver | null;\n}\n\n@Injectable({ providedIn: 'root' })\nexport class InertSiblingsStack {\n readonly #document = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n\n readonly #roots = new Map<HTMLElement, RootState>();\n\n /**\n * Push `owner` onto the inert-siblings stack for `root` (default\n * `document.body`) and (re)apply the isolation outcome for the new topmost\n * owner. Returns a handle whose `deactivate()` pops this specific owner —\n * order-safe, so closing out of LIFO order works.\n *\n * When `root` is a positioned container (e.g. a region-scoped modal), only\n * that container's other children are inerted; body siblings outside the\n * container stay fully interactive (#819).\n */\n activate(owner: HTMLElement, root: HTMLElement = this.#document.body): InertSiblingsHandle {\n if (!this.#isBrowser) {\n return {\n deactivate: () => {},\n get isActive(): boolean {\n return false;\n },\n };\n }\n const state = this.#stateFor(root);\n this.#revertAppliedSnapshot(state);\n if (state.stack.length === 0) {\n this.#startObserving(state);\n }\n state.stack.push(owner);\n this.#applyForCurrentTopmost(state);\n\n let active = true;\n return {\n get isActive(): boolean {\n return active;\n },\n deactivate: (): void => {\n if (!active) {\n return;\n }\n active = false;\n const idx = state.stack.indexOf(owner);\n if (idx === -1) {\n return;\n }\n this.#revertAppliedSnapshot(state);\n state.stack.splice(idx, 1);\n if (state.stack.length > 0) {\n this.#applyForCurrentTopmost(state);\n } else {\n this.#stopObserving(state);\n this.#roots.delete(root);\n }\n },\n };\n }\n\n /**\n * Whether an overlay anchored to `anchor` should be left interactive over\n * the active modal — i.e. treated as a peer of the topmost owner instead of\n * inerted. Returns `true` only while at least one owner is active AND\n * `anchor` lives inside the current protected root for any active root,\n * which means the overlay was opened from within a modal (e.g. a Select /\n * DropdownMenu opened from a form inside a Dialog).\n *\n * Returns `false` when no owner is active — so an overlay opened with no\n * modal present is never pre-marked, and a modal opened later inerts it like\n * any other background sibling — and when `anchor` sits in an already-inerted\n * background subtree (a toast or a tooltip anchored to a backdrop element).\n *\n * `injectOverlayShell` calls this when an anchored-overlay host is portaled,\n * to decide whether to stamp `MODAL_PEER_ATTRIBUTE` on it so the\n * inert-siblings observer skips forty's own overlays instead of swallowing\n * them (#676). SSR-safe: on the server the roots map is always empty (no\n * owner activates), so this returns `false`.\n */\n ownsAnchor(anchor: Element): boolean {\n for (const state of this.#roots.values()) {\n const protectedRoot = this.#currentProtectedRoot(state);\n if (protectedRoot !== null && protectedRoot.contains(anchor)) {\n return true;\n }\n }\n return false;\n }\n\n #stateFor(root: HTMLElement): RootState {\n let state = this.#roots.get(root);\n if (!state) {\n state = { root, stack: [], appliedSnapshot: [], observer: null };\n this.#roots.set(root, state);\n }\n return state;\n }\n\n #applyForCurrentTopmost(state: RootState): void {\n const protectedRoot = this.#currentProtectedRoot(state);\n if (!protectedRoot) {\n return;\n }\n\n for (const child of Array.from(state.root.children)) {\n this.#inertChild(child, protectedRoot, state);\n }\n }\n\n #inertChild(child: Element, protectedRoot: HTMLElement, state: RootState): void {\n if (!(child instanceof HTMLElement)) {\n return;\n }\n if (child === protectedRoot) {\n return;\n }\n if (child.hasAttribute(MODAL_PEER_ATTRIBUTE)) {\n return;\n }\n if (state.appliedSnapshot.some((entry) => entry.el === child)) {\n return;\n }\n\n state.appliedSnapshot.push({\n el: child,\n hadInert: child.hasAttribute('inert'),\n prevAriaHidden: child.getAttribute('aria-hidden'),\n });\n\n child.setAttribute('inert', '');\n child.setAttribute('aria-hidden', 'true');\n }\n\n #currentProtectedRoot(state: RootState): HTMLElement | null {\n const top = state.stack[state.stack.length - 1];\n if (!top) {\n return null;\n }\n return this.#rootLevelChild(top, state.root) ?? top;\n }\n\n #startObserving(state: RootState): void {\n const win = this.#document.defaultView;\n if (state.observer || !win || typeof win.MutationObserver !== 'function') {\n return;\n }\n state.observer = new win.MutationObserver((records) => {\n const protectedRoot = this.#currentProtectedRoot(state);\n if (!protectedRoot) {\n return;\n }\n for (const record of records) {\n for (const node of Array.from(record.addedNodes)) {\n if (node instanceof HTMLElement && node.parentElement === state.root) {\n this.#inertChild(node, protectedRoot, state);\n }\n }\n }\n });\n state.observer.observe(state.root, { childList: true });\n }\n\n #stopObserving(state: RootState): void {\n state.observer?.disconnect();\n state.observer = null;\n }\n\n #revertAppliedSnapshot(state: RootState): void {\n for (const entry of state.appliedSnapshot) {\n if (!entry.hadInert) {\n entry.el.removeAttribute('inert');\n }\n if (entry.prevAriaHidden === null) {\n entry.el.removeAttribute('aria-hidden');\n } else {\n entry.el.setAttribute('aria-hidden', entry.prevAriaHidden);\n }\n }\n state.appliedSnapshot = [];\n }\n\n #rootLevelChild(el: HTMLElement, root: HTMLElement): HTMLElement | null {\n let cur: HTMLElement | null = el;\n while (cur && cur.parentElement && cur.parentElement !== root) {\n cur = cur.parentElement;\n }\n return cur && cur.parentElement === root ? cur : null;\n }\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n DOCUMENT,\n DestroyRef,\n Injectable,\n PLATFORM_ID,\n inject,\n signal,\n type Signal,\n} from '@angular/core';\n\n/**\n * Application-scoped tracker for the last input modality the user employed —\n * the in-house implementation of input-modality (pointer vs keyboard)\n * detection. Created once per Angular bootstrap (one per SSR\n * request), tied to the root injector lifetime.\n *\n * It installs exactly **one** capture-phase `keydown` and **one** capture-phase\n * `pointerdown` listener on `document`, regardless of how many primitives read\n * its state — every `injectFocusVisible()` consumer shares this single\n * singleton, so the document is never listened to more than once. Capture phase\n * is used so the modality is settled before any overlay content can stop\n * propagation.\n *\n * Why a service rather than module-level state:\n *\n * - SSR isolation: module-level globals leak between simultaneous server\n * requests in the same Node process. A `providedIn: 'root'` service is\n * instantiated per application injector.\n * - Bootstrap-safety: `TestBed.resetTestingModule()`, micro-frontend reloads,\n * and anything else that destroys `ApplicationRef` must not leave stale\n * `document` listeners behind. The listeners are registered in the\n * constructor and removed via `DestroyRef`.\n * - SSR safety: `document` is inaccessible on the server. The service is a\n * no-op when `PLATFORM_ID` is not the browser; `keyboard` stays `false` and\n * no listener is installed.\n *\n * Internal — not re-exported from `public-api.ts`.\n */\n@Injectable({ providedIn: 'root' })\nexport class InputModality {\n readonly #document = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n\n readonly #keyboard = signal(false);\n\n /**\n * `true` when the most recent input modality was the keyboard, `false` after\n * a pointer interaction (or before any interaction). Stays `false` on the\n * server.\n */\n readonly keyboard: Signal<boolean> = this.#keyboard.asReadonly();\n\n readonly #onKeyDown = (): void => {\n this.#keyboard.set(true);\n };\n readonly #onPointerDown = (): void => {\n this.#keyboard.set(false);\n };\n\n constructor() {\n if (!this.#isBrowser) {\n return;\n }\n this.#document.addEventListener('keydown', this.#onKeyDown, true);\n this.#document.addEventListener('pointerdown', this.#onPointerDown, true);\n\n inject(DestroyRef).onDestroy(() => {\n this.#document.removeEventListener('keydown', this.#onKeyDown, true);\n this.#document.removeEventListener('pointerdown', this.#onPointerDown, true);\n });\n }\n}\n","import { inject, type Signal } from '@angular/core';\n\nimport { InputModality } from './modality';\n\n/**\n * Returns a `Signal<boolean>` that is `true` while the last global input\n * modality was the keyboard, and `false` after a pointer interaction (or\n * before any interaction). This is the modality half of `:focus-visible`\n * styling: a consumer that wants a focus ring only on keyboard focus combines\n * this with the element's own focused state (`:focus`, or a `focusin` /\n * `focusout` listener) — e.g. `host: { '[attr.data-focus-visible]':\n * \"focused() && focusVisible() ? '' : null\" }`.\n *\n * Backed by the application-scoped {@link InputModality} singleton, so every\n * consumer shares a single capture-phase `keydown` / `pointerdown` listener on\n * `document` no matter how many call this.\n *\n * SSR-safe: on the server the backing service installs no listener and the\n * signal stays `false`. Must be called from an injection context.\n *\n * Internal — not re-exported from `public-api.ts`.\n */\nexport function injectFocusVisible(): Signal<boolean> {\n return inject(InputModality).keyboard;\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n DestroyRef,\n ElementRef,\n PLATFORM_ID,\n computed,\n inject,\n signal,\n type Signal,\n} from '@angular/core';\n\n/** Options for {@link injectHovered}. */\nexport interface HoveredOptions {\n /**\n * When this signal reports `true`, the returned signal is forced to `false`\n * and no interaction can set it — a disabled control is never hovered.\n */\n disabled?: Signal<boolean>;\n}\n\n/**\n * Returns a `Signal<boolean>` reflecting whether a pointing device is currently\n * hovering the host element. State is set on `pointerenter` and cleared on\n * `pointerleave`.\n *\n * Touch is suppressed: a `pointerenter` whose `pointerType` is `'touch'` does\n * not set the hovered state, so the emulated mouse-enter a tap produces on a\n * touchscreen never leaves the element stuck in a hovered state after the\n * finger lifts. Only `'mouse'` / `'pen'` pointers report hover.\n *\n * Attaches `pointerenter` / `pointerleave` listeners to the host element. The\n * `disabled` option short-circuits the result reactively (a pure `computed`,\n * never an `effect`-written signal) and also stops hover from arming while\n * disabled.\n *\n * SSR-safe: on the server no listener is attached and the signal stays\n * `false`. Must be called from an injection context (injects `ElementRef`,\n * `PLATFORM_ID`, `DestroyRef`).\n *\n * Internal — not re-exported from `public-api.ts`.\n */\nexport function injectHovered(opts?: HoveredOptions): Signal<boolean> {\n const disabled = opts?.disabled;\n const isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n if (!isBrowser) {\n return signal(false).asReadonly();\n }\n\n const el = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const hovered = signal(false);\n\n const onPointerEnter = (event: PointerEvent): void => {\n if (event.pointerType === 'touch') {\n return;\n }\n if (disabled?.()) {\n return;\n }\n hovered.set(true);\n };\n const onPointerLeave = (): void => {\n hovered.set(false);\n };\n\n el.addEventListener('pointerenter', onPointerEnter);\n el.addEventListener('pointerleave', onPointerLeave);\n\n inject(DestroyRef).onDestroy(() => {\n el.removeEventListener('pointerenter', onPointerEnter);\n el.removeEventListener('pointerleave', onPointerLeave);\n });\n\n return computed(() => (disabled?.() ? false : hovered()));\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n DestroyRef,\n ElementRef,\n PLATFORM_ID,\n computed,\n inject,\n signal,\n type Signal,\n} from '@angular/core';\n\n/** Options for {@link injectPressed}. */\nexport interface PressedOptions {\n /**\n * When this signal reports `true`, the returned signal is forced to `false`\n * and no interaction can set it — a disabled control is never pressed.\n */\n disabled?: Signal<boolean>;\n}\n\n/**\n * Returns a `Signal<boolean>` reflecting whether the host element is currently\n * being pressed — held down via the primary pointer button, or via the\n * <kbd>Enter</kbd> / <kbd>Space</kbd> key while focused. The state clears on\n * pointer release, the pointer leaving the element mid-press, key release, or\n * `blur` (covers focus leaving the element while a key is held).\n *\n * Attaches `pointerdown` / `pointerup` / `pointerleave` / `keydown` / `keyup` /\n * `blur` listeners to the host element. The `disabled` option short-circuits\n * the result reactively (a pure `computed`, never an `effect`-written signal)\n * and also stops a fresh press from arming while disabled.\n *\n * SSR-safe: on the server no listener is attached and the signal stays\n * `false`. Must be called from an injection context (injects `ElementRef`,\n * `PLATFORM_ID`, `DestroyRef`).\n *\n * Internal — not re-exported from `public-api.ts`.\n */\nexport function injectPressed(opts?: PressedOptions): Signal<boolean> {\n const disabled = opts?.disabled;\n const isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n if (!isBrowser) {\n return signal(false).asReadonly();\n }\n\n const el = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const pressed = signal(false);\n\n const onPointerDown = (event: PointerEvent): void => {\n if (event.pointerType === 'mouse' && event.button !== 0) {\n return;\n }\n if (disabled?.()) {\n return;\n }\n pressed.set(true);\n };\n const onPointerEnd = (): void => {\n pressed.set(false);\n };\n const onKeyDown = (event: KeyboardEvent): void => {\n if (event.key !== 'Enter' && event.key !== ' ') {\n return;\n }\n if (disabled?.()) {\n return;\n }\n pressed.set(true);\n };\n const onKeyUp = (event: KeyboardEvent): void => {\n if (event.key !== 'Enter' && event.key !== ' ') {\n return;\n }\n pressed.set(false);\n };\n const onBlur = (): void => {\n pressed.set(false);\n };\n\n el.addEventListener('pointerdown', onPointerDown);\n el.addEventListener('pointerup', onPointerEnd);\n el.addEventListener('pointerleave', onPointerEnd);\n el.addEventListener('keydown', onKeyDown);\n el.addEventListener('keyup', onKeyUp);\n el.addEventListener('blur', onBlur);\n\n inject(DestroyRef).onDestroy(() => {\n el.removeEventListener('pointerdown', onPointerDown);\n el.removeEventListener('pointerup', onPointerEnd);\n el.removeEventListener('pointerleave', onPointerEnd);\n el.removeEventListener('keydown', onKeyDown);\n el.removeEventListener('keyup', onKeyUp);\n el.removeEventListener('blur', onBlur);\n });\n\n return computed(() => (disabled?.() ? false : pressed()));\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\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 /** PageUp / PageDown map to first / last when true. Default `false`. */\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 */\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 ? 'first' : null;\n case 'PageDown':\n return pageKeys ? 'last' : 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\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 * - `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 '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 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 { DisableableHandle } from '../collection/first-enabled-host';\nimport { type ListNavigationAction, moveIndex } from './keyboard-navigation';\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 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 {\n computed,\n type OutputEmitterRef,\n type Signal,\n signal,\n type WritableSignal,\n} from '@angular/core';\nimport type { ReferenceElement } from '@floating-ui/dom';\n\nimport { Collection } from '../collection/collection';\nimport { firstEnabledHost } from '../collection/first-enabled-host';\nimport { adoptHostId } from '../host-id/host-id';\nimport type { IdGenerator } from '../id-generator/id-generator';\nimport { type ListNavigationAction } from '../keyboard-navigation/keyboard-navigation';\nimport { nextEnabledHandle } from '../keyboard-navigation/move-in-collection';\nimport {\n emitVetoableEvent,\n emitVetoableNativeEvent,\n type VetoableEvent,\n type VetoableNativeEvent,\n} from '../vetoable-event/vetoable-event';\n\n/**\n * Minimal option-handle shape the controller's focus algorithm needs: a host\n * element to focus and a `disabled` signal to skip. Each primitive widens this\n * with its own per-option fields (value, label, id, posInSet, …) and registers\n * the widened handle through {@link ListboxOverlayController.registerOption}.\n */\nexport interface ListboxOverlayOptionHandle {\n readonly host: HTMLElement;\n readonly disabled: Signal<boolean>;\n}\n\n/**\n * The dismiss / auto-focus outputs the controller forwards to. Each primitive\n * owns the `output()` instances (they must be declared as class-field\n * initializers for the Angular compiler to detect them); the controller only\n * emits through them, so the shared dismiss pipeline lives in one place.\n */\nexport interface ListboxOverlayEmitTargets {\n readonly escapeKeyDown: OutputEmitterRef<VetoableNativeEvent<KeyboardEvent>>;\n readonly pointerDownOutside: OutputEmitterRef<VetoableNativeEvent<PointerEvent>>;\n readonly focusOutside: OutputEmitterRef<VetoableNativeEvent<FocusEvent>>;\n readonly interactOutside: OutputEmitterRef<VetoableNativeEvent<PointerEvent | FocusEvent>>;\n readonly autoFocusOnOpen: OutputEmitterRef<VetoableEvent>;\n readonly autoFocusOnClose: OutputEmitterRef<VetoableEvent>;\n}\n\n/**\n * Construction-time wiring for {@link ListboxOverlayController}. Plain signals\n * and callbacks only — the controller never imports a primitive's context\n * token, mirroring `injectOverlayShell`, so it stays orthogonal to each root's\n * surface.\n *\n * @typeParam H Primitive option-handle type.\n * @typeParam Focus Initial-focus union (identical `'first' | 'last' | 'selected'`\n * in both primitives, kept generic so each keeps its own named alias).\n * @typeParam CloseReason Close-reason union owned by the primitive.\n */\nexport interface ListboxOverlayControllerDeps<\n H extends ListboxOverlayOptionHandle,\n Focus,\n CloseReason,\n> {\n /** Id-generator prefix base, e.g. `'for-select'` (suffixed with `-trigger` / `-content`). */\n readonly idPrefix: string;\n /** Full `[forty-cdk/<primitive>]`-prefixed error thrown when a second anchor registers. */\n readonly multipleAnchorsError: string;\n /** Default initial-focus target when none is set explicitly. */\n readonly defaultInitialFocus: Focus;\n /** The control's effective disabled — gates open / navigate / toggle. */\n readonly effectiveDisabled: Signal<boolean>;\n /** The control's two-way `open` model — flipped by the open / close machine. */\n readonly setOpen: (open: boolean) => void;\n /** Read the control's current open state. */\n readonly isOpen: () => boolean;\n /** Dismiss / auto-focus outputs to forward to. */\n readonly emit: ListboxOverlayEmitTargets;\n /** Mark the control touched (mirrors the trigger blur) on Escape / outside dismissal. */\n readonly markTouched: () => void;\n /**\n * Per-primitive close side effect, run after the open model flips to `false`\n * (Select clears the virtualized activedescendant + pending navigation here).\n */\n readonly onClose?: (reason: CloseReason) => void;\n /**\n * Per-option focus side effect, run after `navigate` focuses the target\n * (Select scrolls the option into view and applies `selectionFollowsFocus`).\n */\n readonly onNavigateFocus?: (target: H) => void;\n /** Per-primitive option-unregister side effect (Select clears a stale activedescendant). */\n readonly onUnregisterOption?: (handle: H) => void;\n}\n\n/**\n * The overlay-listbox state machine shared by `ForSelect` and `ForTimePicker`\n * (the WAI-ARIA select-only combobox and the slot-listbox time picker). Owns\n * the option collection, the trigger / anchor / content element registries and\n * their ids, the DOM-focus navigation algorithm, the initial-focus /\n * close-reason state, the open / close machine, and the dismiss / auto-focus\n * emit forwarders — every method each root used to duplicate verbatim.\n *\n * Value-specific behaviour (selection equality, `activate`, `focusSelectedOption`,\n * typeahead, the virtualized activedescendant path, `commitOnTab`'s value set)\n * stays in the root and is threaded through {@link ListboxOverlayControllerDeps}\n * callbacks where it must run as a side effect of a shared transition.\n *\n * Internal — lives in `_internal/`, never re-exported from `public-api.ts`.\n *\n * @typeParam H Primitive option-handle type.\n * @typeParam Focus Initial-focus union.\n * @typeParam CloseReason Close-reason union.\n */\nexport class ListboxOverlayController<H extends ListboxOverlayOptionHandle, Focus, CloseReason> {\n readonly #deps: ListboxOverlayControllerDeps<H, Focus, CloseReason>;\n readonly #idGen: IdGenerator;\n readonly #items = new Collection<H>();\n\n readonly triggerId: WritableSignal<string>;\n readonly contentId: WritableSignal<string>;\n\n readonly #initialFocus: ReturnType<typeof signal<Focus>>;\n readonly initialFocus: Signal<Focus>;\n\n readonly #lastCloseReason = signal<CloseReason | null>(null);\n readonly lastCloseReason = this.#lastCloseReason.asReadonly();\n\n readonly #triggerEl = signal<HTMLElement | null>(null);\n readonly trigger = this.#triggerEl.asReadonly();\n\n readonly #anchorEl = signal<HTMLElement | null>(null);\n\n /**\n * Element floating-ui anchors the listbox against. Prefers an optional\n * registered anchor, otherwise falls back to the trigger so primitives\n * without an anchor keep their behavior.\n */\n readonly anchor: Signal<ReferenceElement | null>;\n\n readonly #contentEl = signal<HTMLElement | null>(null);\n readonly content = this.#contentEl.asReadonly();\n\n /** All registered options in DOM order. */\n readonly options: Signal<readonly H[]>;\n\n constructor(idGen: IdGenerator, deps: ListboxOverlayControllerDeps<H, Focus, CloseReason>) {\n this.#deps = deps;\n this.#idGen = idGen;\n this.triggerId = signal(this.#idGen.next(`${deps.idPrefix}-trigger`));\n this.contentId = signal(this.#idGen.next(`${deps.idPrefix}-content`));\n this.#initialFocus = signal<Focus>(deps.defaultInitialFocus);\n this.initialFocus = this.#initialFocus.asReadonly();\n this.anchor = computed<ReferenceElement | null>(() => this.#anchorEl() ?? this.#triggerEl());\n this.options = this.#items.items;\n }\n\n setInitialFocus(target: Focus): void {\n this.#initialFocus.set(target);\n }\n\n registerTrigger(el: HTMLElement): void {\n adoptHostId(el, this.triggerId);\n this.#triggerEl.set(el);\n }\n unregisterTrigger(el: HTMLElement): void {\n if (this.#triggerEl() === el) {\n this.#triggerEl.set(null);\n }\n }\n\n registerAnchor(el: HTMLElement): void {\n const current = this.#anchorEl();\n if (current !== null && current !== el) {\n throw new Error(this.#deps.multipleAnchorsError);\n }\n this.#anchorEl.set(el);\n }\n unregisterAnchor(el: HTMLElement): void {\n if (this.#anchorEl() === el) {\n this.#anchorEl.set(null);\n }\n }\n\n registerContent(el: HTMLElement): void {\n adoptHostId(el, this.contentId);\n this.#contentEl.set(el);\n }\n unregisterContent(el: HTMLElement): void {\n if (this.#contentEl() === el) {\n this.#contentEl.set(null);\n }\n }\n\n registerOption(handle: H): void {\n this.#items.register(handle);\n }\n unregisterOption(handle: H): void {\n this.#items.unregister(handle);\n this.#deps.onUnregisterOption?.(handle);\n }\n\n navigate(currentOption: HTMLElement, action: ListNavigationAction, loop: boolean): void {\n if (this.#deps.effectiveDisabled()) {\n return;\n }\n const target = nextEnabledHandle(this.#items.items(), currentOption, action, { loop });\n if (target === null) {\n return;\n }\n target.host.focus();\n this.#deps.onNavigateFocus?.(target);\n }\n\n focusFirstEnabledOption(): boolean {\n const host = firstEnabledHost(this.#items.items());\n if (!host) {\n return false;\n }\n host.focus();\n return true;\n }\n\n focusLastEnabledOption(): boolean {\n const items = this.#items.items();\n for (let i = items.length - 1; i >= 0; i--) {\n const item = items[i];\n if (item && !item.disabled()) {\n item.host.focus();\n return true;\n }\n }\n return false;\n }\n\n toggle(initialFocus: Focus): void {\n if (this.#deps.effectiveDisabled()) {\n return;\n }\n if (this.#deps.isOpen()) {\n this.closeMenu('programmatic' as CloseReason);\n } else {\n this.openMenu(initialFocus);\n }\n }\n\n openMenu(initialFocus: Focus): void {\n if (this.#deps.effectiveDisabled()) {\n return;\n }\n this.#initialFocus.set(initialFocus);\n this.#lastCloseReason.set(null);\n this.#deps.setOpen(true);\n }\n\n closeMenu(reason: CloseReason): void {\n this.#lastCloseReason.set(reason);\n this.#deps.setOpen(false);\n this.#deps.onClose?.(reason);\n }\n\n emitEscapeKeyDown(event: KeyboardEvent, dismissible: boolean, escapeReason: CloseReason): void {\n const vetoed = emitVetoableNativeEvent(this.#deps.emit.escapeKeyDown, event);\n if (!vetoed && dismissible) {\n event.stopPropagation();\n this.#deps.markTouched();\n this.closeMenu(escapeReason);\n }\n }\n\n emitPointerDownOutside(veto: VetoableNativeEvent<PointerEvent>): void {\n this.#deps.emit.pointerDownOutside.emit(veto);\n }\n emitFocusOutside(veto: VetoableNativeEvent<FocusEvent>): void {\n this.#deps.emit.focusOutside.emit(veto);\n }\n emitInteractOutside(veto: VetoableNativeEvent<PointerEvent | FocusEvent>): void {\n this.#deps.emit.interactOutside.emit(veto);\n }\n\n forwardEscapeKeyDown(veto: VetoableNativeEvent<KeyboardEvent>): void {\n this.#deps.emit.escapeKeyDown.emit(veto);\n }\n\n requestClose(reason: CloseReason): void {\n this.#deps.markTouched();\n this.closeMenu(reason);\n }\n\n emitAutoFocusOnOpen(): boolean {\n return emitVetoableEvent(this.#deps.emit.autoFocusOnOpen);\n }\n\n emitAutoFocusOnClose(): boolean {\n return emitVetoableEvent(this.#deps.emit.autoFocusOnClose);\n }\n\n /** Focus the trigger, e.g. on a Tab commit before the content unmounts. */\n focusTrigger(): void {\n this.#triggerEl()?.focus();\n }\n}\n","import {\n Directive,\n ElementRef,\n booleanAttribute,\n computed,\n inject,\n input,\n signal,\n} from '@angular/core';\n\n/**\n * The \"visually hidden\" clip rectangle: an inline style declaration that\n * removes an element from the visual layout while keeping it in the\n * accessibility tree (unlike `display:none` / `visibility:hidden`, which both\n * also drop it from the a11y tree). Shared by {@link ForVisuallyHidden} and the\n * `LiveAnnouncer` so the clip CSS is defined in exactly one place.\n */\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 * Internal — not re-exported from `public-api.ts`.\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 { VISUALLY_HIDDEN_STYLE } from '../visually-hidden/visually-hidden';\n\ntype Politeness = 'polite' | 'assertive';\n\n/**\n * Tiny ARIA live-region helper. Lazily injects two off-screen regions\n * (`polite` and `assertive`) into `document.body` the first time it is used,\n * then writes / clears messages on demand.\n *\n * Sequential identical announcements are flushed through a deferred write\n * (`setTimeout(…, 0)`) so the region is briefly emptied — without that, screen\n * readers ignore repeated text that hasn't actually changed. A macrotask (not a\n * microtask) is used deliberately: many screen readers (NVDA, VoiceOver) miss\n * the clear→repopulate cycle on repeat messages when both writes land in the\n * same microtask drain, because the empty state never reaches the\n * accessibility tree between them. Each write carries a generation token, so a\n * superseding `announce()` or a `clear()` cancels the prior pending write\n * before it can paint a stale message.\n *\n * The regions are detached again when the service's injector is destroyed\n * (one bootstrap per SSR request, or `TestBed.resetTestingModule()`), so a\n * torn-down application leaves no orphaned `[aria-live]` nodes behind. DOM\n * access is gated on `isPlatformBrowser`, so `announce()` / `clear()` are\n * 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, HTMLElement>();\n #generation = 0;\n\n constructor() {\n inject(DestroyRef).onDestroy(() => {\n for (const region of this.#regions.values()) {\n region.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 * Pass an empty string (or call `clear()`) to silence pending announcements.\n * 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.#getRegion(politeness);\n // Reset first so identical consecutive messages still trigger the reader.\n region.textContent = '';\n // Bump the generation so a superseding announce (or a clear) cancels this\n // pending write before it paints.\n const generation = ++this.#generation;\n setTimeout(() => {\n if (generation !== this.#generation) {\n return;\n }\n region.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 this.#generation++;\n for (const region of this.#regions.values()) {\n region.textContent = '';\n }\n }\n\n #getRegion(politeness: Politeness): HTMLElement {\n let region = this.#regions.get(politeness);\n if (region) {\n return region;\n }\n region = this.#document.createElement('div');\n region.setAttribute('aria-live', politeness);\n region.setAttribute('aria-atomic', 'true');\n region.setAttribute('role', politeness === 'assertive' ? 'alert' : 'status');\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, region);\n return region;\n }\n}\n","/** Group / decimal separators for a locale, as derived from `Intl`. */\nexport interface LocaleSeparators {\n /** The locale grouping (thousands) separator. */\n readonly group: string;\n /** The locale decimal separator. */\n readonly decimal: string;\n}\n\n/** Escapes a string for safe interpolation into a `RegExp` source. */\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * The space variants a locale may emit as a group separator, or that a user\n * may type in their place: ASCII space (U+0020), no-break space (U+00A0),\n * narrow no-break space (U+202F, fr-FR), and thin space (U+2009). Normalized to\n * the locale's canonical group separator before grouping validation so a\n * user-typed ASCII space still parses against an NBSP-emitting locale.\n */\nconst SPACE_GROUP_VARIANTS = /[ ]/g;\n\n/** Whether `separator` is one of the whitespace group-separator variants. */\nfunction isSpaceSeparator(separator: string): boolean {\n return /^[ ]$/.test(separator);\n}\n\n/**\n * Group / decimal separators for a given locale, derived once via `Intl`.\n * Falls back to `,` group / `.` decimal for an unknown or undefined locale.\n */\nexport function localeSeparators(locale: string | undefined): LocaleSeparators {\n let group = ',';\n let decimal = '.';\n for (const part of new Intl.NumberFormat(locale).formatToParts(11111.1)) {\n if (part.type === 'group') {\n group = part.value;\n } else if (part.type === 'decimal') {\n decimal = part.value;\n }\n }\n return { group, decimal };\n}\n\n/**\n * Parse locale-formatted numeric `text` into a number, or `null` when it is not\n * a valid plain decimal for the given `separators`. The locale decimal separator\n * is normalized to `.`, group separators are validated for placement then\n * stripped, and the canonical form is validated against a strict numeric regex\n * (optional sign + digits + a single optional decimal) before `Number()`.\n *\n * Grouping placement is strict: a group separator may appear only in the\n * integer part and only at 3-digit boundaries, so a correctly grouped\n * `\"1,234,567\"` parses while a misgrouped `\"1,2,3\"` is rejected (`null`)\n * rather than silently collapsing to `123`.\n *\n * For locales that group with a space (the NBSP / NNBSP fr-style locales),\n * whitespace-space variants — including the plain ASCII space a user is most\n * likely to type — are normalized to the locale's canonical separator first,\n * so a correctly-spaced number parses regardless of which space was typed.\n *\n * Exponent notation is intentionally rejected — `2e3` is not valid spinbutton\n * input and silently parsing it to `2000` is surprising. So are malformed forms\n * such as multiple signs (`+-5`) or multiple decimals (`1.2.3`); all map to\n * `null`, the same outcome callers already treat as \"keep the last valid value\".\n */\nexport function parseLocaleNumber(text: string, separators: LocaleSeparators): number | null {\n const { group, decimal } = separators;\n // When the locale groups with a space (NBSP / NNBSP in fr-style locales),\n // normalize every whitespace-space variant the user might type — including a\n // plain ASCII space — to the canonical separator, so grouping validation\n // doesn't reject a correctly-spaced number just because the typed space\n // differs from the one `Intl` emits.\n const input = isSpaceSeparator(group) ? text.replace(SPACE_GROUP_VARIANTS, group) : text;\n // Strip currency symbols, percent signs, and any other non-numeric noise\n // the locale may include, leaving digits, sign, the locale group/decimal\n // separators, and the exponent letters — the strict gates below reject\n // exponent notation, so stripping `eE` here would let `2e3` slip through\n // as `23` instead of being seen (and refused) as malformed.\n const noise = new RegExp(`[^\\\\d${escapeRegExp(group)}${escapeRegExp(decimal)}eE+-]`, 'g');\n const cleaned = input.trim().replace(noise, '');\n if (cleaned.includes(group) && !groupingIsValid(cleaned, group, decimal)) {\n return null;\n }\n let normalized = cleaned.split(group).join('');\n if (decimal !== '.') {\n normalized = normalized.split(decimal).join('.');\n }\n if (!/^[+-]?\\d+(?:\\.\\d+)?$/.test(normalized)) {\n return null;\n }\n const parsed = Number(normalized);\n return Number.isFinite(parsed) ? parsed : null;\n}\n\n/**\n * Validates that every group separator in `cleaned` sits at a legal 3-digit\n * boundary within the integer part (none in the fractional part). Permits a\n * leading sign and a shorter leading group (`1,234` / `12,345` / `123,456`).\n */\nfunction groupingIsValid(cleaned: string, group: string, decimal: string): boolean {\n const integerPart = cleaned.split(decimal)[0] ?? '';\n const sign = /^[+-]/.test(integerPart) ? integerPart[0]! : '';\n const digitsWithGroups = sign ? integerPart.slice(1) : integerPart;\n const g = escapeRegExp(group);\n return new RegExp(`^\\\\d{1,3}(?:${g}\\\\d{3})+$`).test(digitsWithGroups);\n}\n","import { inject, InjectionToken, type Signal } from '@angular/core';\nimport type { ReferenceElement } from '@floating-ui/dom';\n\nimport type { CollectionHandle } from '../collection/collection';\nimport type { FloatingAlign, FloatingSide } from '../floating/floating';\nimport type { MenuActivationModality } from './menu-overlay';\nimport type {\n ListNavigationAction,\n WritingDirection,\n} from '../keyboard-navigation/keyboard-navigation';\nimport type { Point } from '../pointer-grace/pointer-grace';\nimport type { VetoableNativeEvent } from '../vetoable-event/vetoable-event';\n\n/**\n * Minimal upward contract a menu uses to move between sibling menus of an\n * enclosing menubar. Implemented by the menubar root; keeps the generic menu\n * layer free of any concrete-root import.\n */\nexport interface MenuSiblingNavigator {\n /** Move focus/open to the previous or next sibling menu. */\n switchToSibling(direction: 'next' | 'prev'): void;\n}\n\n/**\n * Why a menu requested close. Enumerates the close reasons without the\n * focus-routing decision baked in. `'programmatic'` also\n * covers the user-initiated trigger toggle-close (clicking an open menu's\n * trigger): the toggle path reuses this reason by design rather than\n * exposing a distinct `'trigger'` reason.\n */\nexport type ForMenuCloseReason =\n | 'escape'\n | 'pointerDownOutside'\n | 'focusOutside'\n | 'select'\n | 'tab'\n | 'programmatic';\n\n/**\n * Handle every item type (`menuitem`, `menuitemcheckbox`, `menuitemradio`)\n * registers with the parent menu. The collection orders them by DOM\n * position so groups, separators, and `@for` loops don't affect navigation.\n *\n * `textValue`, when present and non-empty, overrides `host.textContent` for\n * typeahead matching — useful when the item's DOM contains icons, kbd\n * shortcuts, badges, or SVG titles that would otherwise bleed into the\n * match string. Empty / unset means \"fall back to the host's text content\".\n */\nexport interface ForMenuItemHandle extends CollectionHandle {\n readonly disabled: Signal<boolean>;\n readonly textValue?: Signal<string>;\n /**\n * Tells the item that the next focus it receives is a programmatic move\n * that must not reflect `data-highlighted` (the initial focus of a\n * pointer-driven open). One-shot: the item consumes the suppression on its\n * next `focus` event. Optional — items that don't reflect a highlight\n * (e.g. `[forMenuSubTrigger]`) simply omit it.\n */\n suppressHighlightOnNextFocus?(): void;\n /**\n * Drops the item's `data-highlighted` without moving DOM focus. The menu\n * surface calls this on `pointerleave` so the hover highlight stops once the\n * pointer leaves, while keyboard navigation stays anchored on the item.\n * Optional — items that don't reflect a highlight (e.g.\n * `[forMenuSubTrigger]`) simply omit it.\n */\n clearHighlight?(): void;\n}\n\n/**\n * Coordination contract owned by the root that opens the menu —\n * `[forDropdownMenu]` (button trigger) or `[forContextMenu]`\n * (right-click / `Shift+F10`). Items, content, separators, etc. inject\n * this contract so they don't depend on a specific root flavor.\n */\nexport interface ForMenuContext {\n /**\n * Whether the menu is currently shown. Read-only at the contract level —\n * concrete roots (`[forDropdownMenu]`, `[forContextMenu]`, `[forMenuSub]`)\n * back this with their own `model<boolean>` and write through their own\n * `openMenu` / `closeMenu` plumbing. Pieces consuming this contract\n * (`[forMenuContent]`, the trigger directives) only ever read.\n */\n readonly open: Signal<boolean>;\n readonly disabled: Signal<boolean>;\n readonly dismissible: Signal<boolean>;\n readonly returnFocus: Signal<boolean>;\n /**\n * Writing direction. Drives ArrowLeft / ArrowRight semantics on submenu\n * triggers and items, and the default `side` of submenus (`'right'` in\n * LTR, `'left'` in RTL). On `[forMenuSub]` defaults to the parent menu's\n * `dir` and can be overridden per-submenu.\n */\n readonly dir: Signal<WritingDirection>;\n readonly side: Signal<FloatingSide | undefined>;\n readonly align: Signal<FloatingAlign | undefined>;\n readonly sideOffset: Signal<number>;\n readonly alignOffset: Signal<number>;\n readonly avoidCollisions: Signal<boolean>;\n readonly collisionPadding: Signal<number>;\n readonly arrowPadding: Signal<number>;\n readonly sticky: Signal<'partial' | 'always' | false>;\n readonly hideWhenDetached: Signal<boolean>;\n readonly clipUntilPositioned: Signal<boolean>;\n readonly loop: Signal<boolean>;\n\n /** Where focus should land after the menu mounts. Set by triggers before flipping `open`. */\n readonly initialFocus: Signal<'first' | 'last'>;\n setInitialFocus(target: 'first' | 'last'): void;\n\n readonly triggerId: Signal<string>;\n readonly contentId: Signal<string>;\n readonly ariaLabel: Signal<string | null>;\n\n /** Anchor passed to floating-ui — `HTMLElement` (Dropdown) or `VirtualElement` (Context). */\n readonly anchor: Signal<ReferenceElement | null>;\n\n /** The focusable element that receives focus on close (the trigger button or right-click target). */\n readonly trigger: Signal<HTMLElement | null>;\n registerTrigger(el: HTMLElement): void;\n unregisterTrigger(el: HTMLElement): void;\n\n /** The mounted `[forMenuContent]` element. Submenus exempt their parent's content. */\n readonly content: Signal<HTMLElement | null>;\n registerContent(el: HTMLElement): void;\n unregisterContent(el: HTMLElement): void;\n\n /**\n * The enclosing menu, when this context is a `[forMenuSub]`. `null` for\n * top-level roots (`[forDropdownMenu]`, `[forContextMenu]`, and the\n * `[forMenubar]`-flavored ctx). Items use it to route ArrowLeft /\n * item-activation upward.\n */\n readonly parentMenu: ForMenuContext | null;\n\n /**\n * The enclosing menubar, when this context is the top-level menu of a\n * `[forMenubar]`. `null` otherwise. `[forMenuItem]` and `[forMenuContent]`\n * route ArrowLeft / ArrowRight up to it for cross-menu navigation when\n * there's no parent submenu. Typed as the minimal `MenuSiblingNavigator`\n * so the generic menu layer stays free of any concrete-root import.\n */\n readonly menubar?: MenuSiblingNavigator | null;\n\n /**\n * Elements treated as \"inside\" by the dismissable layer. DropdownMenu\n * exempts the trigger button (clicks on it toggle via the trigger\n * directive — without exemption they'd also fire pointer-down-outside\n * and double-close). ContextMenu exempts nothing — a left-click on the\n * region while the menu is open should close it.\n */\n readonly dismissableExemptions: Signal<readonly HTMLElement[]>;\n\n registerItem(handle: ForMenuItemHandle): void;\n unregisterItem(handle: ForMenuItemHandle): void;\n\n /** Move focus inside the menu in response to an arrow / Home / End key. */\n navigate(currentItem: HTMLElement, action: ListNavigationAction): void;\n /** Prefix-match against item text content and focus the first match. */\n handleTypeahead(event: KeyboardEvent): void;\n /**\n * Clear `data-highlighted` from every item without moving focus. Called by\n * `[forMenuContent]` on `pointerleave` so the hover highlight follows the\n * pointer off the surface (hover-follows-pointer).\n */\n clearItemHighlights(): void;\n /** Returns `true` if focus moved; `false` when no enabled items exist. */\n focusFirstEnabledItem(): boolean;\n focusLastEnabledItem(): boolean;\n\n /**\n * Trigger entry points — toggle/open honour `disabled`. `modality`\n * (default `'keyboard'`) records how the open was activated: a `'pointer'`\n * open keeps the programmatic initial focus from reflecting\n * `data-highlighted` on the focused item, while a `'keyboard'` open\n * highlights it per the APG menu-button pattern. The DOM focus move itself\n * is identical in both modalities.\n */\n toggle(initialFocus?: 'first' | 'last', modality?: MenuActivationModality): void;\n openMenu(initialFocus?: 'first' | 'last', modality?: MenuActivationModality): void;\n closeMenu(reason: ForMenuCloseReason): void;\n\n /**\n * Reason of the most recent close, or `null` while the menu is open / has\n * never closed. Reset to `null` on every open. `[forMenuContent]` reads it\n * to skip its return-focus when the close was a `'tab'` — letting Tab move\n * focus out of the menu (per WAI-ARIA APG) instead of snapping it back to\n * the trigger.\n */\n readonly lastCloseReason: Signal<ForMenuCloseReason | null>;\n\n /**\n * Abort a pending pointer-driven (hover) close on this menu, if one is\n * scheduled. A descendant submenu walks up the `parentMenu` chain calling\n * this so the whole open chain stays alive while the pointer travels\n * between levels. Optional — only `[forMenuSub]` schedules hover-closes, so\n * top-level roots (Dropdown / Context / Menubar) need not implement it.\n */\n cancelPendingClose?(): void;\n\n /**\n * Schedule a pointer-driven (hover) open of this menu. Optional — only\n * `[forMenuSub]` opens on hover; top-level roots open on click / right-click.\n * The sub-trigger calls it on `pointerenter` via optional chaining.\n */\n scheduleOpenByPointer?(): void;\n\n /**\n * The pointer left this menu's trigger (client coordinates of the leave).\n * Optional — only `[forMenuSub]` reacts, arming the pointer-grace \"safe\n * triangle\" toward its content. The sub-trigger calls it on `pointerleave`.\n */\n onTriggerPointerLeave?(cursor: Point): void;\n\n /**\n * Escape is consumer-owned (its close emits `(escapeKeyDown)`, stops\n * propagation, and closes with reason `'escape'`); Content forwards the raw\n * `KeyboardEvent`.\n */\n emitEscapeKeyDown(event: KeyboardEvent): void;\n /**\n * Outside-interaction emit forwarders. `injectOverlayShell` builds and\n * reuses one `VetoableNativeEvent` across the specific and composite\n * channels, then hands it to these forwarders to fire the matching output\n * and calls `requestClose` when un-vetoed.\n */\n emitPointerDownOutside(veto: VetoableNativeEvent<PointerEvent>): void;\n emitFocusOutside(veto: VetoableNativeEvent<FocusEvent>): void;\n emitInteractOutside(veto: VetoableNativeEvent<PointerEvent | FocusEvent>): void;\n /** Implicit close requested by the shell after an un-vetoed outside interaction. */\n requestClose(reason: 'pointerDownOutside' | 'focusOutside'): void;\n\n /**\n * Hooks into the auto-focus pipeline. Content fires these just before\n * its imperative `.focus()` (open) or the trigger return-focus (close);\n * `event.preventDefault()` skips the move. Returns `true` when the\n * consumer vetoed.\n */\n emitAutoFocusOnOpen(): boolean;\n emitAutoFocusOnClose(): boolean;\n}\n\nexport type { MenuActivationModality };\n\nexport const FOR_MENU_CONTEXT = new InjectionToken<ForMenuContext>('FOR_MENU_CONTEXT');\n\nexport function injectMenuContext(piece: string): ForMenuContext {\n const ctx = inject(FOR_MENU_CONTEXT, { optional: true });\n if (!ctx) {\n throw new Error(\n `[forty-cdk/menu] ${piece} must be used inside a [forDropdownMenu], [forContextMenu], [forMenubar], or [forMenuSub] element. ` +\n \"If it is declared inside an ng-template, DI resolves at the template's declaration site — \" +\n 'not where it is stamped (e.g. via ngTemplateOutlet) — so declare the template inside the menu root.',\n );\n }\n return ctx;\n}\n","import { type Signal, signal } from '@angular/core';\n\n/**\n * Tracks where a menu's initial focus should land on the next open and whether\n * that one programmatic move should reflect `data-highlighted` on the focused\n * item.\n *\n * `target` is set by triggers before they flip the menu open (ArrowDown →\n * `'first'`, ArrowUp → `'last'`). `highlightOnNextFocus` is armed per open via\n * {@link prepareOpen}: a `'keyboard'` activation highlights the focused item per\n * the APG menu-button pattern; a `'pointer'` activation (click, hover-after-open)\n * suppresses the highlight so a mouse-opened menu doesn't read as \"preselected\".\n * {@link consumeHighlight} reads the flag once and re-arms it to `true`, so the\n * suppression applies only to the single initial-focus move that follows an open.\n *\n * Plain class (no `inject()`) so both `MenuOverlay` and `[forMenubar]`'s\n * multiplexed menu context compose the same one-shot protocol instead of each\n * hand-copying it.\n */\nexport class InitialFocusState {\n readonly #target = signal<'first' | 'last'>('first');\n #highlightOnNextFocus = true;\n\n /** Where focus should land when the menu mounts. */\n readonly target: Signal<'first' | 'last'> = this.#target.asReadonly();\n\n setTarget(target: 'first' | 'last'): void {\n this.#target.set(target);\n }\n\n /**\n * Arms the state for the next open: records the initial-focus target and\n * whether the upcoming initial-focus move should highlight the focused item\n * (`true` for keyboard activation, `false` for pointer activation).\n */\n prepareOpen(target: 'first' | 'last', highlight: boolean): void {\n this.#target.set(target);\n this.#highlightOnNextFocus = highlight;\n }\n\n /**\n * Returns whether the next initial-focus move should highlight, then re-arms\n * the flag to `true` so the suppression is one-shot.\n */\n consumeHighlight(): boolean {\n const highlight = this.#highlightOnNextFocus;\n this.#highlightOnNextFocus = true;\n return highlight;\n }\n}\n\n/**\n * Records the reason of a menu's most recent close. Reset to `null` on every\n * open; the shared `[forMenuContent]` reads it to skip its return-focus on a\n * `'tab'` close (so Tab advances focus out of the menu instead of snapping back\n * to the trigger).\n *\n * Generic over the reason union so `MenuOverlay` (`MenuOverlayCloseReason`) and\n * `[forMenubar]`'s menu context (`ForMenuCloseReason`) — structurally identical\n * unions — share one implementation. Plain class (no `inject()`) so both compose\n * it instead of each hand-copying the signal.\n */\nexport class CloseReasonState<R extends string> {\n readonly #reason = signal<R | null>(null);\n\n /**\n * Reason of the most recent close, or `null` while the menu is open / has\n * never closed.\n */\n readonly reason: Signal<R | null> = this.#reason.asReadonly();\n\n set(reason: R): void {\n this.#reason.set(reason);\n }\n\n reset(): void {\n this.#reason.set(null);\n }\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.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 Signal } from '@angular/core';\n\nimport { Collection, type CollectionHandle } from '../collection/collection';\nimport { type ListNavigationAction } from '../keyboard-navigation/keyboard-navigation';\nimport { nextEnabledHandle } from '../keyboard-navigation/move-in-collection';\nimport { injectTypeahead, type Typeahead } from '../typeahead/typeahead';\n\n/**\n * Item handle the list's `Collection` registers. Structurally compatible\n * with primitives' `ForMenuItemHandle` — typing is generic so the unit\n * stays orthogonal to `_internal/menu-overlay/menu-context.ts` (no cycle into a primitive).\n */\nexport interface MenuItemHandle extends CollectionHandle {\n readonly disabled: Signal<boolean>;\n readonly textValue?: Signal<string>;\n /**\n * Tells the item that the next focus it receives is a programmatic move\n * that must not reflect `data-highlighted` (the initial focus of a\n * pointer-driven open). One-shot: the item consumes the suppression on its\n * next `focus` event. Optional — items that don't reflect a highlight\n * (e.g. `[forMenuSubTrigger]`) simply omit it.\n */\n suppressHighlightOnNextFocus?(): void;\n /**\n * Drops the item's `data-highlighted` without moving DOM focus. Called when\n * the pointer leaves the menu surface so the hovered item stops reading as\n * the active candidate while keyboard navigation stays anchored on it.\n * Optional — items that don't reflect a highlight omit it.\n */\n clearHighlight?(): void;\n}\n\n/**\n * The keyboard-focus mechanics shared by every menu surface that holds a\n * vertical list of `menuitem`s: the item `Collection`, a typeahead buffer,\n * arrow / Home / End navigation, prefix-match typeahead, and the\n * first/last-enabled focus moves used on mount.\n *\n * Both `MenuOverlay` (for `[forDropdownMenu]` / `[forContextMenu]` /\n * `[forMenuSub]`) and `[forMenubar]`'s multiplexed menu context delegate to\n * this unit, so the verbatim navigate / typeahead / focus copies that used\n * to live in each don't drift.\n *\n * `loop` is read through an accessor so the owner can forward its own\n * reactive `loop` input without the unit depending on a specific source.\n *\n * Construct via `createMenuItemList` from a directive / helper field\n * initializer so the `injectTypeahead()` `DestroyRef` hookup resolves\n * through the surrounding injector.\n */\nexport class MenuItemList<H extends MenuItemHandle = MenuItemHandle> {\n readonly #items = new Collection<H>();\n readonly #typeahead: Typeahead;\n readonly #loop: () => boolean;\n\n constructor(loop: () => boolean, typeahead: Typeahead) {\n this.#loop = loop;\n this.#typeahead = typeahead;\n }\n\n registerItem(handle: H): void {\n this.#items.register(handle);\n }\n\n unregisterItem(handle: H): void {\n this.#items.unregister(handle);\n }\n\n /** Items registered with the menu, in DOM order. Exposed for tests / sub-menu wiring. */\n items(): readonly H[] {\n return this.#items.items();\n }\n\n navigate(currentItem: HTMLElement, action: ListNavigationAction): void {\n const target = nextEnabledHandle(this.#items.items(), currentItem, action, {\n loop: this.#loop(),\n });\n target?.host.focus();\n }\n\n handleTypeahead(event: KeyboardEvent): void {\n if (!this.#typeahead.handle(event)) {\n return;\n }\n const buffer = this.#typeahead.buffer().toLowerCase();\n if (!buffer) {\n return;\n }\n const items = this.#items.items();\n if (items.length === 0) {\n return;\n }\n\n const cycle = this.#typeahead.isRepeatedChar();\n const query = cycle ? buffer[0]! : buffer;\n const currentIndex = items.findIndex((i) => i.host === event.target);\n // Single-character typeahead cycles: each (re-)press of one key steps to the\n // next same-initial item after the current focus and wraps around (APG menu\n // typeahead). A distinct multi-character prefix re-anchors on the current\n // focus (inclusive) so a growing prefix keeps the current item when it still\n // matches; both fall back to the top when nothing is focused.\n const anchor = currentIndex >= 0 ? currentIndex : -1;\n const start = cycle ? anchor + 1 : Math.max(anchor, 0);\n\n for (let offset = 0; offset < items.length; offset++) {\n const item = items[(start + offset) % items.length]!;\n if (item.disabled()) {\n continue;\n }\n const override = item.textValue?.() ?? '';\n const source = override !== '' ? override : (item.host.textContent ?? '');\n if (source.trim().toLowerCase().startsWith(query)) {\n item.host.focus();\n return;\n }\n }\n }\n\n /**\n * Focuses the first enabled item. Pass `highlight: false` when the move is\n * the programmatic initial focus of a pointer-driven open, so the item\n * receives DOM focus without reflecting `data-highlighted`.\n */\n focusFirstEnabledItem(highlight = true): boolean {\n const target = this.#items.items().find((i) => !i.disabled());\n if (!target) {\n return false;\n }\n this.#focusItem(target, highlight);\n return true;\n }\n\n /**\n * Focuses the last enabled item. Pass `highlight: false` when the move is\n * the programmatic initial focus of a pointer-driven open, so the item\n * receives DOM focus without reflecting `data-highlighted`.\n */\n focusLastEnabledItem(highlight = true): boolean {\n const items = this.#items.items();\n for (let i = items.length - 1; i >= 0; i--) {\n const item = items[i];\n if (item && !item.disabled()) {\n this.#focusItem(item, highlight);\n return true;\n }\n }\n return false;\n }\n\n #focusItem(item: H, highlight: boolean): void {\n if (!highlight) {\n item.suppressHighlightOnNextFocus?.();\n }\n item.host.focus();\n }\n\n /**\n * Drops `data-highlighted` from every registered item without touching DOM\n * focus. Used when the pointer leaves the menu surface so no item keeps\n * reading as the active candidate.\n */\n clearHighlights(): void {\n for (const item of this.#items.items()) {\n item.clearHighlight?.();\n }\n }\n}\n\n/**\n * Creates a `MenuItemList` from a directive / helper field initializer.\n * `loop` is the owner's reactive loop accessor; the typeahead instance is\n * created with `injectTypeahead()` so its debounce timer is torn down with\n * the surrounding `DestroyRef`.\n */\nexport function createMenuItemList<H extends MenuItemHandle = MenuItemHandle>(\n loop: () => boolean,\n): MenuItemList<H> {\n return new MenuItemList<H>(loop, injectTypeahead());\n}\n","import {\n inject,\n type ModelSignal,\n type OutputEmitterRef,\n type Signal,\n signal,\n type WritableSignal,\n} from '@angular/core';\n\nimport { adoptHostId } from '../host-id/host-id';\nimport { IdGenerator } from '../id-generator/id-generator';\nimport type { ListNavigationAction } from '../keyboard-navigation/keyboard-navigation';\nimport {\n emitVetoableEvent,\n emitVetoableNativeEvent,\n type VetoableEvent,\n type VetoableNativeEvent,\n} from '../vetoable-event/vetoable-event';\nimport { CloseReasonState, InitialFocusState } from './menu-focus-state';\nimport { createMenuItemList, type MenuItemHandle, type MenuItemList } from './menu-item-list';\n\n/**\n * Reason a menu requested close. Mirrors `ForMenuCloseReason` from\n * `_internal/menu-overlay/menu-context.ts` structurally so primitives can pass either type\n * across the helper boundary without re-declaration.\n */\nexport type MenuOverlayCloseReason =\n | 'escape'\n | 'pointerDownOutside'\n | 'focusOutside'\n | 'select'\n | 'tab'\n | 'programmatic';\n\n/**\n * Item handle the helper's item list registers. Re-exported alias of the\n * shared `MenuItemHandle` — structurally compatible with primitives'\n * `ForMenuItemHandle` and kept under this name for backward compatibility\n * with the helper's existing consumers / specs.\n */\nexport type MenuOverlayItemHandle = MenuItemHandle;\n\n/**\n * How a menu open was activated. `'keyboard'` (the default) highlights the\n * initially focused item per the APG menu-button pattern; `'pointer'` keeps\n * the programmatic initial focus from reflecting `data-highlighted` so a\n * mouse-opened menu doesn't read as \"preselected\". The DOM focus move itself\n * is identical in both modalities.\n */\nexport type MenuActivationModality = 'pointer' | 'keyboard';\n\n/**\n * Wiring the directive forwards into the helper. Inputs / outputs / models\n * stay declared on the directive (Angular needs them as fields for template\n * binding); the helper reads them through these references so the close\n * decisions, navigation, and veto plumbing live in one place.\n */\nexport interface MenuOverlayHooks {\n readonly open: ModelSignal<boolean>;\n readonly disabled: Signal<boolean>;\n readonly dismissible: Signal<boolean>;\n readonly loop: Signal<boolean>;\n readonly escapeKeyDown: OutputEmitterRef<VetoableNativeEvent<KeyboardEvent>>;\n readonly pointerDownOutside: OutputEmitterRef<VetoableNativeEvent<PointerEvent>>;\n readonly focusOutside: OutputEmitterRef<VetoableNativeEvent<FocusEvent>>;\n readonly interactOutside: OutputEmitterRef<VetoableNativeEvent<PointerEvent | FocusEvent>>;\n readonly autoFocusOnOpen: OutputEmitterRef<VetoableEvent>;\n readonly autoFocusOnClose: OutputEmitterRef<VetoableEvent>;\n\n /**\n * Optional side effect run after `openMenu` flips `open` to `true`,\n * receiving the resolved initial-focus target. `[forMenuSub]` uses it to\n * cancel in-flight hover scheduling and reset its focus-suppression flag\n * (a keyboard / click open supersedes hover). Top-level roots\n * (`[forDropdownMenu]` / `[forContextMenu]`) pass neither hook.\n */\n readonly onOpen?: (initialFocus: 'first' | 'last') => void;\n\n /**\n * Optional side effect run after `closeMenu` flips `open` to `false`,\n * receiving the close reason. `[forMenuSub]` uses it to cancel in-flight\n * hover scheduling, reset its focus-suppression flag, and propagate the\n * close upward through the menu chain for every reason except `'escape'`\n * / `'programmatic'`. Top-level roots pass neither hook.\n */\n readonly onClose?: (reason: MenuOverlayCloseReason) => void;\n}\n\n/**\n * Shared coordination behaviour between `ForDropdownMenu` and `ForContextMenu`\n * (and any future menu overlay root with the same item-collection / typeahead /\n * navigate / dismissable shape — Menubar's per-bar menu, a future free-floating\n * SubMenu).\n *\n * The helper owns:\n *\n * - id generation for trigger / content,\n * - the item list (`MenuItemList`: the item `Collection` + typeahead +\n * `navigate` / `handleTypeahead` / `focusFirst/LastEnabledItem`), shared\n * with `[forMenubar]`'s multiplexed menu context,\n * - trigger / content / initial-focus signals,\n * - `toggle` / `openMenu` / `closeMenu` (honouring `disabled`),\n * - the consumer-owned Escape close (`emitEscapeKeyDown`) and the\n * `requestClose` the shell invokes after an un-vetoed outside interaction.\n * The shared `#pendingOutsideVeto` reuse between the specific outside\n * listeners and the composite `interactOutside` lives in\n * `injectOverlayShell`, not here,\n * - the `(autoFocusOnOpen)` / `(autoFocusOnClose)` veto pass-throughs.\n *\n * It deliberately does NOT own:\n *\n * - the `anchor` signal — DropdownMenu derives it from the trigger element,\n * ContextMenu drives it via a `VirtualElement`,\n * - `dismissableExemptions` — DropdownMenu exempts the trigger button so the\n * trigger's click toggle doesn't double-fire as a pointer-down-outside;\n * ContextMenu exempts nothing,\n * - the `input()` / `output()` / `model()` declarations — they remain on the\n * directive class because Angular's template binding system reads inputs /\n * outputs off the directive's compiled metadata.\n *\n * Class form (rather than a function-based factory) is deliberate: the\n * helper has private mutable state (the trigger / content signals, the\n * initial-focus signal) that maps cleanly to instance fields, and the\n * directives read several of its fields back through getter\n * forwarding. Encapsulating that as a class keeps the directive's surface\n * obvious at the call site and matches the Angular idiom for cross-cutting\n * mutable state co-located with DI.\n *\n * Construct via `createMenuOverlay` from a directive's field initializer so\n * the helper's `inject()` calls (id generator, typeahead destroyRef hookup)\n * resolve through the directive's injector.\n */\nexport class MenuOverlay<H extends MenuOverlayItemHandle = MenuOverlayItemHandle> {\n readonly #idGen = inject(IdGenerator);\n readonly #itemList: MenuItemList<H>;\n readonly #hooks: MenuOverlayHooks;\n\n readonly #triggerId: WritableSignal<string>;\n readonly #contentId: WritableSignal<string>;\n\n /** Unique id for the trigger element. Stable across the menu's lifetime. */\n readonly triggerId: Signal<string>;\n\n /** Unique id for the content element. Stable across the menu's lifetime. */\n readonly contentId: Signal<string>;\n\n readonly #initialFocusState = new InitialFocusState();\n\n /** Where focus should land when the menu mounts. Set by triggers before flipping `open`. */\n readonly initialFocus = this.#initialFocusState.target;\n\n readonly #closeReasonState = new CloseReasonState<MenuOverlayCloseReason>();\n\n /**\n * Reason of the most recent close, or `null` while the menu is open / has\n * never closed. Reset to `null` on every open. The shared `[forMenuContent]`\n * reads this to skip its return-focus on `'tab'` so Tab can advance focus\n * out of the menu instead of snapping back to the trigger.\n */\n readonly lastCloseReason = this.#closeReasonState.reason;\n\n readonly #triggerEl = signal<HTMLElement | null>(null);\n\n /** The focusable element the menu should return focus to on close. */\n readonly trigger = this.#triggerEl.asReadonly();\n\n readonly #contentEl = signal<HTMLElement | null>(null);\n\n /** The mounted `[forMenuContent]` element, or `null` while the menu is closed. */\n readonly content = this.#contentEl.asReadonly();\n\n constructor(idPrefix: string, hooks: MenuOverlayHooks) {\n this.#hooks = hooks;\n this.#itemList = createMenuItemList<H>(() => hooks.loop());\n this.#triggerId = signal(this.#idGen.next(`${idPrefix}-trigger`));\n this.#contentId = signal(this.#idGen.next(`${idPrefix}-content`));\n this.triggerId = this.#triggerId.asReadonly();\n this.contentId = this.#contentId.asReadonly();\n }\n\n setInitialFocus(target: 'first' | 'last'): void {\n this.#initialFocusState.setTarget(target);\n }\n\n registerTrigger(el: HTMLElement): void {\n adoptHostId(el, this.#triggerId);\n this.#triggerEl.set(el);\n }\n\n unregisterTrigger(el: HTMLElement): void {\n if (this.#triggerEl() === el) {\n this.#triggerEl.set(null);\n }\n }\n\n registerContent(el: HTMLElement): void {\n adoptHostId(el, this.#contentId);\n this.#contentEl.set(el);\n }\n\n unregisterContent(el: HTMLElement): void {\n if (this.#contentEl() === el) {\n this.#contentEl.set(null);\n }\n }\n\n registerItem(handle: H): void {\n this.#itemList.registerItem(handle);\n }\n\n unregisterItem(handle: H): void {\n this.#itemList.unregisterItem(handle);\n }\n\n /** Items registered with the menu, in DOM order. Exposed for tests / sub-menu wiring. */\n items(): readonly H[] {\n return this.#itemList.items();\n }\n\n navigate(currentItem: HTMLElement, action: ListNavigationAction): void {\n this.#itemList.navigate(currentItem, action);\n }\n\n handleTypeahead(event: KeyboardEvent): void {\n this.#itemList.handleTypeahead(event);\n }\n\n /**\n * Clears `data-highlighted` from every item without moving focus. The shared\n * `[forMenuContent]` calls this on `pointerleave` so the hover highlight\n * follows the pointer off the surface.\n */\n clearItemHighlights(): void {\n this.#itemList.clearHighlights();\n }\n\n /**\n * Focuses the first enabled item. When the most recent `openMenu` was\n * pointer-activated, this one move suppresses the item's focus-driven\n * `data-highlighted` (one-shot — later calls highlight normally).\n */\n focusFirstEnabledItem(): boolean {\n return this.#itemList.focusFirstEnabledItem(this.#initialFocusState.consumeHighlight());\n }\n\n /**\n * Focuses the last enabled item. When the most recent `openMenu` was\n * pointer-activated, this one move suppresses the item's focus-driven\n * `data-highlighted` (one-shot — later calls highlight normally).\n */\n focusLastEnabledItem(): boolean {\n return this.#itemList.focusLastEnabledItem(this.#initialFocusState.consumeHighlight());\n }\n\n /**\n * Toggle the menu open/closed from the trigger. The close branch reuses the\n * `'programmatic'` close reason by design — there is no distinct `'trigger'`\n * reason for the user-initiated toggle-close path.\n */\n toggle(\n initialFocus: 'first' | 'last' = 'first',\n modality: MenuActivationModality = 'keyboard',\n ): void {\n if (this.#hooks.disabled()) {\n return;\n }\n if (this.#hooks.open()) {\n this.closeMenu('programmatic');\n } else {\n this.openMenu(initialFocus, modality);\n }\n }\n\n /**\n * Opens the menu, recording where the initial focus should land and how\n * the open was activated. A `'pointer'` modality keeps that one initial\n * focus move from reflecting `data-highlighted` on the focused item.\n */\n openMenu(\n initialFocus: 'first' | 'last' = 'first',\n modality: MenuActivationModality = 'keyboard',\n ): void {\n if (this.#hooks.disabled()) {\n return;\n }\n this.#initialFocusState.prepareOpen(initialFocus, modality === 'keyboard');\n this.#closeReasonState.reset();\n this.#hooks.open.set(true);\n this.#hooks.onOpen?.(initialFocus);\n }\n\n closeMenu(reason: MenuOverlayCloseReason): void {\n this.#closeReasonState.set(reason);\n this.#hooks.open.set(false);\n this.#hooks.onClose?.(reason);\n }\n\n emitEscapeKeyDown(event: KeyboardEvent): void {\n const vetoed = emitVetoableNativeEvent(this.#hooks.escapeKeyDown, event);\n if (!vetoed && this.#hooks.dismissible()) {\n // Load-bearing, not redundant: the bubble-phase Escape handler stops the\n // same keydown from reaching an *ancestor* overlay's keydown listener,\n // which is how nested overlays close one layer per Escape (see the\n // listener-phase note in `_internal/dismissable-layer/dismissable-layer.ts`).\n event.stopPropagation();\n this.closeMenu('escape');\n }\n }\n\n /**\n * Outside-interaction emit forwarders. The shared `#pendingOutsideVeto`\n * reuse between the specific outside channels and the composite\n * `interactOutside` lives in `injectOverlayShell`; these only fire the\n * matching output with the veto the shell built.\n */\n emitPointerDownOutside(veto: VetoableNativeEvent<PointerEvent>): void {\n this.#hooks.pointerDownOutside.emit(veto);\n }\n emitFocusOutside(veto: VetoableNativeEvent<FocusEvent>): void {\n this.#hooks.focusOutside.emit(veto);\n }\n emitInteractOutside(veto: VetoableNativeEvent<PointerEvent | FocusEvent>): void {\n this.#hooks.interactOutside.emit(veto);\n }\n\n /**\n * Implicit close requested by `injectOverlayShell` after an un-vetoed\n * outside interaction. The shell owns the shared `#pendingOutsideVeto`\n * reuse between the specific outside channels and the composite\n * `interactOutside`; this helper only owns the close. The `open()` guard\n * keeps a stale event from re-closing an already-closed menu and clobbering\n * its `lastCloseReason` (e.g. a `'tab'` close must survive so the content\n * skips its return-focus).\n */\n requestClose(reason: 'pointerDownOutside' | 'focusOutside'): void {\n if (!this.#hooks.open()) {\n return;\n }\n this.closeMenu(reason);\n }\n\n emitAutoFocusOnOpen(): boolean {\n return emitVetoableEvent(this.#hooks.autoFocusOnOpen);\n }\n\n emitAutoFocusOnClose(): boolean {\n return emitVetoableEvent(this.#hooks.autoFocusOnClose);\n }\n}\n\n/**\n * Creates a `MenuOverlay` from a directive field initializer. `idPrefix`\n * is the namespace fed to the shared `IdGenerator` (e.g.\n * `'for-dropdown-menu'`, `'for-context-menu'`); the helper generates\n * `<idPrefix>-trigger` and `<idPrefix>-content` ids off it.\n */\nexport function createMenuOverlay<H extends MenuOverlayItemHandle = MenuOverlayItemHandle>(\n idPrefix: string,\n hooks: MenuOverlayHooks,\n): MenuOverlay<H> {\n return new MenuOverlay<H>(idPrefix, hooks);\n}\n","import { type Signal } from '@angular/core';\n\nimport type { ListNavigationAction } from '../keyboard-navigation/keyboard-navigation';\nimport type { VetoableNativeEvent } from '../vetoable-event/vetoable-event';\nimport type {\n MenuActivationModality,\n MenuOverlay,\n MenuOverlayCloseReason,\n MenuOverlayItemHandle,\n} from './menu-overlay';\n\n/**\n * Abstract base that forwards the `MenuOverlay` coordination slice every menu\n * root re-exposes — `[forDropdownMenu]`, `[forContextMenu]`, and `[forMenuSub]`\n * all extend it. Each subclass owns its own `MenuOverlay` instance (created\n * with its own id prefix and lifecycle hooks) and exposes it through the\n * abstract `_overlay` accessor; the base implements the trigger / content /\n * item registration, navigation, open/close, and veto pass-throughs once.\n *\n * This is the single place to add a member that is a pure pass-through to\n * `MenuOverlay`: declaring it here gives all three directives the method\n * without hand-written `.bind()` forwarding in each. Subclasses override only\n * the members that need extra behaviour (e.g. `[forMenuSub]` wraps\n * `registerContent` to attach pointer listeners and overrides the auto-focus\n * emitters to honour its hover focus-suppression flag).\n *\n * Kept generic over the item handle so the subclass's `MenuOverlay<H>` flows\n * through `registerItem` / `unregisterItem` without a cast.\n */\nexport abstract class MenuOverlayHost<H extends MenuOverlayItemHandle = MenuOverlayItemHandle> {\n /** The subclass's `MenuOverlay` instance the base forwards to. */\n protected abstract readonly _overlay: MenuOverlay<H>;\n\n get triggerId(): Signal<string> {\n return this._overlay.triggerId;\n }\n\n get contentId(): Signal<string> {\n return this._overlay.contentId;\n }\n\n get initialFocus(): Signal<'first' | 'last'> {\n return this._overlay.initialFocus;\n }\n\n get lastCloseReason(): Signal<MenuOverlayCloseReason | null> {\n return this._overlay.lastCloseReason;\n }\n\n get trigger(): Signal<HTMLElement | null> {\n return this._overlay.trigger;\n }\n\n get content(): Signal<HTMLElement | null> {\n return this._overlay.content;\n }\n\n setInitialFocus(target: 'first' | 'last'): void {\n this._overlay.setInitialFocus(target);\n }\n\n registerTrigger(el: HTMLElement): void {\n this._overlay.registerTrigger(el);\n }\n\n unregisterTrigger(el: HTMLElement): void {\n this._overlay.unregisterTrigger(el);\n }\n\n registerContent(el: HTMLElement): void {\n this._overlay.registerContent(el);\n }\n\n unregisterContent(el: HTMLElement): void {\n this._overlay.unregisterContent(el);\n }\n\n registerItem(handle: H): void {\n this._overlay.registerItem(handle);\n }\n\n unregisterItem(handle: H): void {\n this._overlay.unregisterItem(handle);\n }\n\n navigate(currentItem: HTMLElement, action: ListNavigationAction): void {\n this._overlay.navigate(currentItem, action);\n }\n\n handleTypeahead(event: KeyboardEvent): void {\n this._overlay.handleTypeahead(event);\n }\n\n clearItemHighlights(): void {\n this._overlay.clearItemHighlights();\n }\n\n focusFirstEnabledItem(): boolean {\n return this._overlay.focusFirstEnabledItem();\n }\n\n focusLastEnabledItem(): boolean {\n return this._overlay.focusLastEnabledItem();\n }\n\n toggle(\n initialFocus: 'first' | 'last' = 'first',\n modality: MenuActivationModality = 'keyboard',\n ): void {\n this._overlay.toggle(initialFocus, modality);\n }\n\n openMenu(\n initialFocus: 'first' | 'last' = 'first',\n modality: MenuActivationModality = 'keyboard',\n ): void {\n this._overlay.openMenu(initialFocus, modality);\n }\n\n closeMenu(reason: MenuOverlayCloseReason): void {\n this._overlay.closeMenu(reason);\n }\n\n requestClose(reason: 'pointerDownOutside' | 'focusOutside'): void {\n this._overlay.requestClose(reason);\n }\n\n emitEscapeKeyDown(event: KeyboardEvent): void {\n this._overlay.emitEscapeKeyDown(event);\n }\n\n emitPointerDownOutside(veto: VetoableNativeEvent<PointerEvent>): void {\n this._overlay.emitPointerDownOutside(veto);\n }\n\n emitFocusOutside(veto: VetoableNativeEvent<FocusEvent>): void {\n this._overlay.emitFocusOutside(veto);\n }\n\n emitInteractOutside(veto: VetoableNativeEvent<PointerEvent | FocusEvent>): void {\n this._overlay.emitInteractOutside(veto);\n }\n\n emitAutoFocusOnOpen(): boolean {\n return this._overlay.emitAutoFocusOnOpen();\n }\n\n emitAutoFocusOnClose(): boolean {\n return this._overlay.emitAutoFocusOnClose();\n }\n}\n","import type { FloatingAlign, FloatingSide } from '../floating/floating';\n\n/**\n * Single source of truth for the floating-ui positioning defaults shared by the\n * three menu roots — `[forDropdownMenu]`, `[forContextMenu]`, and `[forMenuSub]`.\n *\n * Angular's compiler requires every `input()` to be declared directly in a class\n * member initializer (NG8110), so the inputs themselves can't be produced by a\n * shared factory. To stop the (already-drifted) defaults from diverging again,\n * each root reads its non-seed defaults from this object and the\n * `menu-positioning-inputs.spec.ts` guard asserts the three roots keep an\n * identical positioning input set.\n *\n * Only `side` / `sideOffset` / `collisionPadding` legitimately vary per root:\n *\n * - `side` — DropdownMenu / ContextMenu anchor `'bottom'`; the submenu resolves\n * its side from the writing direction (`'right'` LTR / `'left'` RTL).\n * - `sideOffset` / `collisionPadding` — seeded from each root's defaults\n * provider (`provideForDropdownMenuDefaults` / `provideForContextMenuDefaults`\n * / `provideForMenuDefaults`) so a scope override flows through.\n *\n * Everything below is identical across all three roots.\n */\nexport const MENU_POSITIONING_DEFAULTS = {\n /** Default anchor side for the two top-level roots. */\n side: 'bottom' as FloatingSide | undefined,\n /** Default alignment along the chosen `side`. */\n align: 'start' as FloatingAlign | undefined,\n /** Default gap (px) along the cross axis. */\n alignOffset: 0,\n /** `flip` / `shift` keep the surface inside the viewport by default. */\n avoidCollisions: true,\n /** Default padding (px) for the `arrow` middleware. */\n arrowPadding: 0,\n /** Default stickiness behaviour for `shift`. */\n sticky: 'partial' as 'partial' | 'always' | false,\n /** `data-detached=\"\"` is not reflected by default. */\n hideWhenDetached: false,\n /** Content is clipped until floating-ui resolves its first position by default. */\n clipUntilPositioned: true,\n} as const;\n","import { DestroyRef, DOCUMENT, ElementRef, inject, type Signal } from '@angular/core';\n\nimport { afterNextRenderCancellable } from '../after-next-render-cancellable/after-next-render-cancellable';\nimport { BodyScrollLock } from '../body-scroll-lock/body-scroll-lock';\nimport { injectDismissableLayer } from '../dismissable-layer/dismissable-layer';\nimport { findFirstFocusable, injectFocusTrap } from '../focus-trap/focus-trap';\nimport { type InertSiblingsHandle, InertSiblingsStack } from '../inert-siblings/inert-siblings';\nimport { injectPortal } from '../portal/portal';\nimport {\n createVetoableEvent,\n createVetoableNativeEvent,\n type VetoableEvent,\n type VetoableNativeEvent,\n} from '../vetoable-event/vetoable-event';\n\n/**\n * Dismiss-bundle wiring. The shell owns the triple-veto + composite\n * `interactOutside` orchestration that Dialog and Drawer used to duplicate\n * verbatim:\n *\n * - Each \"specific\" channel (Escape / pointer-down-outside / focus-outside)\n * builds a `VetoableNativeEvent`, hands it to the consumer's emitter, and —\n * for pointer / focus — stores it so the immediately-following composite\n * `onInteractOutside` reuses the same veto state. A `preventDefault()` from\n * either the specific or the composite handler suppresses the implicit\n * close.\n * - When the consumer doesn't veto AND `dismissible()` is `true`, the shell\n * calls `requestClose(reason)` with the reason that matches the channel\n * (`'escape' | 'pointerDownOutside' | 'focusOutside'`).\n * - `exemptElements` is recomputed on every event so DOM mutations (newly\n * portaled siblings — Drawer's backdrop is the live example) are picked up.\n *\n * `requestClose` is the consumer's existing implementation; the shell never\n * touches the directive's `(dismiss)` output directly. This keeps the shell\n * orthogonal to each primitive's own close-reason union.\n */\nexport interface ModalShellDismissConfig {\n /** Whether dismissals via the layer fire the implicit `requestClose`. */\n readonly dismissible: Signal<boolean>;\n /** Called with the matching reason when the consumer doesn't veto. */\n readonly requestClose: (reason: 'escape' | 'pointerDownOutside' | 'focusOutside') => void;\n /** Forwards the Escape `VetoableNativeEvent` to the directive's `(escapeKeyDown)` output. */\n readonly emitEscapeKeyDown: (veto: VetoableNativeEvent<KeyboardEvent>) => void;\n /** Forwards the pointer-down-outside veto to the directive's `(pointerDownOutside)` output. */\n readonly emitPointerDownOutside: (veto: VetoableNativeEvent<PointerEvent>) => void;\n /** Forwards the focus-outside veto to the directive's `(focusOutside)` output. */\n readonly emitFocusOutside: (veto: VetoableNativeEvent<FocusEvent>) => void;\n /** Forwards the composite veto to the directive's `(interactOutside)` output. */\n readonly emitInteractOutside: (veto: VetoableNativeEvent<PointerEvent | FocusEvent>) => void;\n /**\n * Live \"elements that count as inside\" set — Drawer uses this to exempt\n * its portaled backdrop so a backdrop click routes through the backdrop's\n * own `requestClose('backdrop')` path instead of `pointerDownOutside`.\n */\n readonly exemptElements?: () => readonly Element[];\n}\n\n/**\n * Primitive-owned initial-focus algorithm for the surface. The richer\n * alternative to the `'first' | 'container'` literal: the shell sets up the\n * focus trap (Tab cycling + return capture) WITHOUT its own imperative focus\n * move, runs the optional `veto`, and — unless vetoed — calls `move()`. When\n * `move()` returns `false` (no candidate found) focus falls back to the trap\n * container (modal) or the first focusable descendant (non-modal).\n *\n * Mirrors `OverlayShellInitialFocusConfig` so a content directive can hand the\n * same focus algorithm to either shell. Used by Select (selected → first →\n * last option) and available for a future date-picker calendar-cell move.\n */\nexport interface ModalShellInitialFocusConfig {\n /** Primitive focus algorithm. Returns `true` on success, `false` to fall back. */\n readonly move: () => boolean;\n /** `(autoFocusOnOpen)` veto. Returning `true` skips the imperative focus move. */\n readonly veto?: () => boolean;\n}\n\n/**\n * Single config for the free-floating modal-overlay lifecycle. Mirrors the\n * `injectOverlayShell` shape on the trigger-anchored side. Each sub-bundle\n * is individually optional so a primitive can opt out of the channels it\n * doesn't need (e.g. a dismiss-less confirm dialog, though none ship today).\n */\nexport interface ModalShellConfig {\n /** Whether the surface activates focus-trap + scroll-lock + inert siblings. */\n readonly modal: Signal<boolean>;\n /**\n * Whether focus returns to the previously-focused element on destroy.\n * Read inside the modal teardown (focus-trap deactivate). Has no effect\n * in non-modal mode (the shell never moves focus on close in that mode).\n */\n readonly returnFocus: Signal<boolean>;\n /**\n * Where to send focus on mount. Two shapes:\n * - `Signal<'first' | 'container'>` — `'first'` = first focusable descendant\n * (falls back to host); `'container'` = host element. Same vocabulary as\n * `FocusTrap.activate({ initialFocus })`. Used by Dialog / Drawer /\n * date-picker.\n * - {@link ModalShellInitialFocusConfig} — a primitive-owned `move()`\n * algorithm (e.g. Select's selected → first → last option) with its own\n * open-veto, falling back to the container / first focusable on a miss.\n */\n readonly initialFocus: Signal<'first' | 'container'> | ModalShellInitialFocusConfig;\n /**\n * `(autoFocusOnOpen)` veto. Bound as a function reference (not as an\n * Angular `output()`) so the shell can invoke it during the destroy hook\n * without depending on `OutputEmitterRef` lifecycle. Read at every mount;\n * a `preventDefault()` on the emitted event skips the imperative initial\n * focus move while still leaving the focus-trap (Tab cycling, return\n * capture) wired in modal mode.\n */\n readonly autoFocusOnOpen?: () => ((event: VetoableEvent) => void) | undefined;\n /**\n * `(autoFocusOnClose)` veto. Same shape as `autoFocusOnOpen`. Fired\n * synchronously from the `DestroyRef.onDestroy` hook, BEFORE the modal /\n * non-modal teardown so it runs reliably on every close path — including a\n * direct `open.set(false)` from the consumer that bypasses any\n * close-output emission.\n */\n readonly autoFocusOnClose?: () => ((event: VetoableEvent) => void) | undefined;\n /**\n * Portal target for the surface. A signal so it is read once at the first\n * render (the portal moves the host once), after the consumer's input is\n * bound. `undefined` / a signal yielding `null` ⇒ `document.body`.\n */\n readonly container?: Signal<HTMLElement | null>;\n /** Optional dismiss bundle. Absent for primitives that don't dismiss via the layer. */\n readonly dismiss?: ModalShellDismissConfig;\n}\n\n/** Imperative handle returned by `injectModalShell`. */\nexport interface ModalShellHandle {\n /** True while the shell activated focus-trap + scroll-lock + inert (modal mode). */\n readonly isModal: () => boolean;\n}\n\n/**\n * Single source of truth for the free-floating modal-overlay lifecycle.\n * Drives every directive in the library that mounts a modal surface as its\n * own root — `[forDialog]` and `[forDrawer]` today, future modal Toast /\n * full-screen sheet / command palette tomorrow. The shell owns:\n *\n * 1. Return-focus target capture. Synchronously, in the consumer's\n * constructor (BEFORE `afterNextRender` fires). Required for WebKit\n * correctness (#136): WebKit blurs the previously-focused element when\n * an ancestor receives `inert`, so by the time `afterNextRender` runs\n * (where inert is activated) reading `document.activeElement` from the\n * focus trap would yield `<body>`. Capturing it now locks the trigger\n * in as the return target before any side effect mutates focus.\n *\n * 2. Portal. `injectPortal()` moves the host to `document.body` after the\n * first render and removes it on destroy.\n *\n * 3. Dismissable layer. Activates inside `afterNextRender` with the\n * triple-veto + composite `interactOutside` pattern that Dialog and\n * Drawer duplicated verbatim. The pattern: a single\n * `VetoableNativeEvent` is built per physical interaction and reused\n * for the specific channel (`pointerDownOutside` / `focusOutside`) and\n * the composite (`interactOutside`), so a `preventDefault()` from\n * either suppresses the implicit `requestClose`. Escape uses its own\n * one-shot veto.\n *\n * 4. Modal vs non-modal branching.\n * - Modal: pushes the inert-siblings stack BEFORE the focus trap fires\n * (so the trap's imperative focus move lands on an already-isolated\n * tree), activates the trap with `initialFocus` + `preventInitialFocus`\n * (the `(autoFocusOnOpen)` veto) + the synchronously-captured\n * `returnFocus` target, then locks scroll. When `config.container` is\n * set, inert-siblings is scoped to that container (only the container's\n * other children are inerted; body siblings stay interactive) and scroll\n * lock targets the container instead of `<body>` (#819). Focus trap is\n * already subtree-scoped to the host regardless of portal target — no\n * change there. When `initialFocus` is a\n * {@link ModalShellInitialFocusConfig}, the trap is activated with\n * `preventInitialFocus: true` and the shell runs the primitive's\n * `move()` instead (falling back to the container on a miss).\n * - Non-modal: skips trap / inert / scroll lock; if `(autoFocusOnOpen)`\n * didn't veto, focuses the first focusable descendant (or host when\n * `initialFocus = 'container'`).\n *\n * 5. Destroy ordering. All steps below run inside ONE\n * `DestroyRef.onDestroy` hook, so they execute as plain sequential\n * statements — the sequence is fixed by the code, not by Angular's\n * (FIFO) hook-registration order. Within the hook the side-effects are\n * torn down in the inverse order they were activated:\n * - `dismissable.deactivate()` first (it was activated first in the setup\n * `afterNextRender`).\n * - `(autoFocusOnClose)` veto fires BEFORE either modal/non-modal\n * teardown so it runs on every close path regardless of mode.\n * - Modal only: `inertHandle.deactivate()` (so the return-focus target\n * is not blocked by an inert ancestor) →\n * `dismissable.suppress(focusTrap.deactivate)` (so the synthetic\n * `focusin` from `.focus()`-ing the previous element doesn't\n * cascade-dismiss whatever layer is now topmost) →\n * `bodyScrollLock.unlock()`.\n *\n * Must be called from an injection context (typically the directive\n * constructor). Forwards the host's `ElementRef` to the portal, dismissable\n * layer, focus trap, and inert-siblings stack — the consumer never has to\n * touch them directly.\n *\n * @example\n * // ForDialog constructor body collapses to:\n * injectModalShell({\n * modal: this.modal,\n * returnFocus: this.returnFocus,\n * initialFocus: this.initialFocus,\n * autoFocusOnOpen: () => this.autoFocusOnOpen(),\n * autoFocusOnClose: () => this.autoFocusOnClose(),\n * dismiss: {\n * dismissible: this.dismissible,\n * requestClose: (reason) => this.requestClose(reason),\n * emitEscapeKeyDown: (veto) => this.escapeKeyDown.emit(veto),\n * emitPointerDownOutside: (veto) => this.pointerDownOutside.emit(veto),\n * emitFocusOutside: (veto) => this.focusOutside.emit(veto),\n * emitInteractOutside: (veto) => this.interactOutside.emit(veto),\n * },\n * });\n */\nexport function injectModalShell(config: ModalShellConfig): ModalShellHandle {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const document = inject(DOCUMENT);\n const focusTrap = injectFocusTrap();\n const dismissable = injectDismissableLayer();\n const inertStack = inject(InertSiblingsStack);\n const scrollLock = inject(BodyScrollLock);\n\n // 1. Capture the return-focus target SYNCHRONOUSLY, before any side effect\n // runs. WebKit (#136) blurs the previously-focused element as soon as\n // `inert` is applied to an ancestor, so by the time `afterNextRender`\n // fires the focus trap could no longer read the trigger from\n // `document.activeElement`. Reading it now locks the trigger in.\n const returnFocusTarget: HTMLElement | null =\n document.activeElement instanceof HTMLElement ? document.activeElement : null;\n\n // 2. Portal — moves the host to `document.body` after first render and\n // cleans up on destroy. `DestroyRef.onDestroy` callbacks fire in\n // registration order (FIFO), and the portal registers its hook here,\n // before the shell's own destroy hook below — so on teardown the portal\n // removes the host from the DOM FIRST, then the shell runs return-focus.\n // The ordering is harmless either way: return-focus targets the\n // previously-focused element (the trigger, captured synchronously above),\n // which lives OUTSIDE the portaled host, so removing the host first never\n // affects it.\n injectPortal(config.container ? { target: config.container } : {});\n\n // Captured at mount time so the destroy path can mirror the same mode the\n // shell activated, regardless of any `modal()` toggle on a doomed\n // instance.\n let activatedAsModal = false;\n let inertHandle: InertSiblingsHandle | null = null;\n let activatedContainer: HTMLElement | null = null;\n\n // 3. Side-effect setup runs after Angular has applied input bindings.\n // Reading `config.modal()` etc. in the constructor would always see the\n // default value because the input writes haven't flowed through yet.\n // `afterNextRenderCancellable` makes the destroy-before-render path safe.\n // On the true-async path (queued render after destroy) the callback is\n // cancelled, so inert siblings / focus trap / scroll lock / dismissable\n // layer are never activated (`activatedAsModal` stays false). On the\n // synchronous-teardown path the callback flushes just before the destroy\n // hook, so it sets `activatedAsModal = true` and the destroy hook below\n // tears the side-effect stack back down. Either way nothing leaks.\n afterNextRenderCancellable(() => {\n const isModal = config.modal();\n activatedAsModal = isModal;\n\n // 3a. Dismissable layer. Pushed onto the stack BEFORE moving focus so\n // focusin events triggered by our own focus management land on this\n // layer, not on whatever lower layer was previously topmost.\n //\n // Triple-veto + composite `interactOutside`: pointer-down-outside\n // and focus-outside both fire on the same physical interaction. The\n // dismissable layer always invokes the specific listener before the\n // composite one, so we build a single veto wrapper on the specific\n // call and reuse it for the composite call. A `preventDefault()` in\n // either handler vetoes the close.\n const dismissCfg = config.dismiss;\n if (dismissCfg !== undefined) {\n let pendingOutsideVeto: VetoableNativeEvent<PointerEvent | FocusEvent> | null = null;\n dismissable.activate({\n ...(dismissCfg.exemptElements ? { exemptElements: dismissCfg.exemptElements } : {}),\n onEscapeKeyDown: (event) => {\n const veto = createVetoableNativeEvent(event);\n dismissCfg.emitEscapeKeyDown(veto);\n if (!veto.defaultPrevented && dismissCfg.dismissible()) {\n event.stopPropagation();\n dismissCfg.requestClose('escape');\n }\n },\n onPointerDownOutside: (event) => {\n pendingOutsideVeto = createVetoableNativeEvent<PointerEvent | FocusEvent>(event);\n dismissCfg.emitPointerDownOutside(\n pendingOutsideVeto as VetoableNativeEvent<PointerEvent>,\n );\n },\n onFocusOutside: (event) => {\n pendingOutsideVeto = createVetoableNativeEvent<PointerEvent | FocusEvent>(event);\n dismissCfg.emitFocusOutside(pendingOutsideVeto as VetoableNativeEvent<FocusEvent>);\n },\n onInteractOutside: (event) => {\n const veto =\n pendingOutsideVeto ?? createVetoableNativeEvent<PointerEvent | FocusEvent>(event);\n pendingOutsideVeto = null;\n dismissCfg.emitInteractOutside(veto);\n if (!veto.defaultPrevented && dismissCfg.dismissible()) {\n dismissCfg.requestClose(\n event.type === 'pointerdown' ? 'pointerDownOutside' : 'focusOutside',\n );\n }\n },\n });\n }\n\n // 3b. Resolve the initial-focus config. The simple form is a\n // `Signal<'first' | 'container'>` (Dialog / Drawer / date-picker); the\n // richer form carries a primitive-owned `move()` algorithm (Select's\n // selected → first → last option) plus its own veto. A `Signal` is\n // callable, so `typeof === 'function'` distinguishes the two shapes;\n // the literal mode is read eagerly only in the simple form.\n const initialFocusCfg = config.initialFocus;\n const moveCfg: ModalShellInitialFocusConfig | null =\n typeof initialFocusCfg === 'function' ? null : initialFocusCfg;\n const literalFocus: 'first' | 'container' | null =\n typeof initialFocusCfg === 'function' ? initialFocusCfg() : null;\n\n // 3c. `(autoFocusOnOpen)` veto — read once for this mount. The move-config\n // carries its own boolean veto (mirroring `injectOverlayShell`); the\n // simple form routes through the top-level `autoFocusOnOpen` callback.\n let skipInitialFocus: boolean;\n if (moveCfg) {\n skipInitialFocus = moveCfg.veto?.() ?? false;\n } else {\n const autoFocusOpenEvent = createVetoableEvent();\n config.autoFocusOnOpen?.()?.(autoFocusOpenEvent);\n skipInitialFocus = autoFocusOpenEvent.defaultPrevented;\n }\n\n if (isModal) {\n // 3d. Modal mode. Inert + aria-hide siblings BEFORE the focus trap\n // activates so the trap's `focus()` call lands on an\n // already-isolated tree. The return-focus target was captured\n // synchronously above (#136).\n const containerEl = config.container?.() ?? null;\n inertHandle = inertStack.activate(host.nativeElement, containerEl ?? undefined);\n activatedContainer = containerEl;\n if (moveCfg) {\n // The primitive owns the focus move. Set up Tab cycling + return\n // capture WITHOUT the trap's own imperative focus, then run the\n // algorithm; fall back to the container when it finds no candidate.\n focusTrap.activate({\n preventInitialFocus: true,\n returnFocus: returnFocusTarget,\n });\n if (!skipInitialFocus && !moveCfg.move()) {\n focusTrap.container.focus();\n }\n } else {\n focusTrap.activate({\n initialFocus: literalFocus ?? 'first',\n preventInitialFocus: skipInitialFocus,\n returnFocus: returnFocusTarget,\n });\n }\n scrollLock.lock(containerEl ?? undefined);\n } else if (!skipInitialFocus) {\n // 3e. Non-modal mode. No trap, no scroll lock, no inert. Still respect\n // the configured initial focus: the primitive's `move()` algorithm\n // (falling back to the first focusable on a miss), the first\n // focusable descendant ('first'), or the host ('container').\n const el = focusTrap.container;\n if (moveCfg) {\n if (!moveCfg.move()) {\n (findFirstFocusable(el) ?? el).focus();\n }\n } else if (literalFocus === 'container') {\n el.focus();\n } else {\n (findFirstFocusable(el) ?? el).focus();\n }\n }\n });\n\n // 4. Destroy. Hooks fire in registration order; the portal's destroy hook\n // was registered inside `injectPortal()` (above) so it runs BEFORE\n // ours, removing the element from the DOM first. We tear down the\n // side-effect stack here in the inverse order it was activated.\n inject(DestroyRef).onDestroy(() => {\n dismissable.deactivate();\n // Invoke `(autoFocusOnClose)` synchronously, BEFORE either the modal or\n // non-modal teardown runs. Fires on every close path regardless of mode\n // (the consumer's `(dismiss)` flow AND a direct `open.set(false)` that\n // bypasses any close-output emission). The callback is a plain function\n // reference — input signals stay readable during destroy and there is no\n // dependency on `OutputEmitterRef` lifecycle. Non-modal mode never moves\n // focus on close, so `skipReturnFocus` is only consulted in the modal\n // branch — but the hook still fires for symmetry with the manager and so\n // consumers can wire their own focus moves on close in non-modal mode.\n const autoFocusCloseEvent = createVetoableEvent();\n config.autoFocusOnClose?.()?.(autoFocusCloseEvent);\n const skipReturnFocus = autoFocusCloseEvent.defaultPrevented;\n if (activatedAsModal) {\n // Lift inert + aria-hide BEFORE moving focus back: an `inert` ancestor\n // blocks `.focus()` on its descendants, so the return-focus target\n // needs to be live again first.\n inertHandle?.deactivate();\n inertHandle = null;\n // Suppress the dismissable-layer dispatcher across focus-return so the\n // synthetic `focusin` triggered by `.focus()`-ing the previous element\n // does not cascade-dismiss whatever modal is now topmost (a stacked\n // dialog opened above this one).\n dismissable.suppress(() => {\n focusTrap.deactivate({\n returnFocus: config.returnFocus() && !skipReturnFocus,\n });\n });\n scrollLock.unlock(activatedContainer ?? undefined);\n }\n });\n\n return {\n isModal: () => activatedAsModal,\n };\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 * 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`. Integer steps return `value`\n * unchanged.\n */\nexport function roundToStepPrecision(value: number, step: number): number {\n const stepText = String(step);\n const dot = stepText.indexOf('.');\n if (dot < 0) {\n return value;\n }\n const factor = 10 ** (stepText.length - dot - 1);\n return Math.round(value * factor) / factor;\n}\n\n/**\n * Snaps `raw` onto the `[min, min + step, min + 2·step, …]` grid, then rounds the\n * result to the step's decimal precision (via {@link roundToStepPrecision}) so a\n * fractional step can't accumulate float noise. A non-positive `step` disables\n * snapping and returns `raw` unchanged. Clamping to an outer range is the\n * caller's responsibility — pass the snapped result to {@link clamp}.\n */\nexport function snapToStep(raw: number, step: number, min: number): number {\n if (step <= 0) {\n return raw;\n }\n return roundToStepPrecision(Math.round((raw - min) / step) * step + min, step);\n}\n","import { inject, Injector } from '@angular/core';\n\n/**\n * Internal composition surface (no semver guarantees). Base for an overlay\n * outlet's context-injector directive. It sits\n * inside the row's `[forDialog]` / `[forDrawer]` element, so its own element\n * injector already resolves that primitive's `FOR_<PRIMITIVE>_CONTEXT`. The\n * outlet feeds this injector to `entry.injectorFor(ctx.injector)`, making the\n * user component rendered via `NgComponentOutlet` inherit the context\n * alongside the data token / ref / consumer providers — so every piece\n * (`[forDialogClose]`, `[forDialogTitle]`, …) resolves exactly as in the\n * declarative path.\n *\n * Each manager subclasses this with its own `for-`-prefixed selector +\n * `exportAs` (the directive selector must be static at decoration time, and\n * the per-primitive template references it by `exportAs`), so the shared body\n * lives here once.\n */\nexport abstract class OverlayContextInjector {\n readonly injector = inject(Injector);\n}\n","import {\n ApplicationRef,\n type ComponentRef,\n computed,\n DOCUMENT,\n EnvironmentInjector,\n inject,\n Injector,\n type Provider,\n type Signal,\n signal,\n} from '@angular/core';\n\nimport { IdGenerator } from '../id-generator/id-generator';\nimport type { OverlayRef } from './overlay-ref';\n\n/**\n * Minimal shape every overlay entry must satisfy so the shared core can index,\n * render, and tear it down. Per-primitive entries (`ForDialogEntry`,\n * `ForDrawerEntry`) extend this with their own directive-input fields.\n *\n * Internal — not re-exported from `public-api.ts`.\n */\nexport interface OverlayManagerEntry {\n readonly id: string;\n readonly ref: OverlayRef<unknown>;\n}\n\n/**\n * The reactive surface a manager's outlet component is wired with on first\n * `open()`. Mirrors `ForDialogOutletHost` / `ForDrawerOutletHost`.\n *\n * Internal — not re-exported from `public-api.ts`.\n */\nexport interface OverlayManagerOutletHost<TEntry extends OverlayManagerEntry> {\n readonly entries: Signal<readonly TEntry[]>;\n closeAllForDestroy(): void;\n}\n\n/**\n * The minimal surface a manager's outlet component exposes so the core can\n * wire it on first `open()`. Mirrors `ForDialogOutlet` / `ForDrawerOutlet`.\n *\n * Internal — not re-exported from `public-api.ts`.\n */\nexport interface OverlayManagerOutlet<TEntry extends OverlayManagerEntry> {\n init(host: OverlayManagerOutletHost<TEntry>): void;\n}\n\n/**\n * Per-primitive bindings the shared core needs: how to name ids and the\n * exit-animation host / backdrop attributes, and how to create the outlet\n * component that renders the entries.\n *\n * Internal — not re-exported from `public-api.ts`.\n */\nexport interface OverlayManagerConfig<TEntry extends OverlayManagerEntry> {\n /**\n * Per-instance id prefix passed to `IdGenerator.next` (e.g.\n * `'for-dialog-instance'`).\n */\n readonly idPrefix: string;\n /**\n * Attribute the overlay root + backdrop reflect their per-instance id on\n * (e.g. `'data-for-dialog-id'`), matched during exit animation.\n */\n readonly idAttribute: string;\n /**\n * Attribute marking the portaled backdrop element (e.g.\n * `'data-for-dialog-backdrop'`), matched during exit animation.\n */\n readonly backdropAttribute: string;\n /** Creates the manager-owned outlet component (e.g. `ForDialogOutlet`). */\n createOutlet(\n environmentInjector: EnvironmentInjector,\n ): ComponentRef<OverlayManagerOutlet<TEntry>>;\n}\n\n/**\n * Shared imperative-overlay engine behind `ForDialogManager` and\n * `ForDrawerManager`. Owns the entries signal, the reactive `openCount`, the\n * lazily-created outlet, the destroy-time close-all sweep, the exit-animation\n * `beginLeave` driver, and the parent-cached per-component `Injector` factory.\n * The two managers differ only in their entry shape and directive-input\n * mapping; everything structural lives here once.\n *\n * Internal — not re-exported from `public-api.ts`; the public surface is\n * `ForDialogManager` / `ForDrawerManager`.\n */\nexport class OverlayManagerCore<TEntry extends OverlayManagerEntry> {\n readonly #appRef = inject(ApplicationRef);\n readonly #envInjector = inject(EnvironmentInjector);\n readonly #document = inject(DOCUMENT);\n protected readonly idGen = inject(IdGenerator);\n\n readonly #entries = signal<readonly TEntry[]>([]);\n readonly #config: OverlayManagerConfig<TEntry>;\n\n /** Reactive count of currently open programmatic overlays. */\n readonly openCount = computed(() => this.#entries().length);\n\n #outletRef: ComponentRef<OverlayManagerOutlet<TEntry>> | null = null;\n #destroying = false;\n\n constructor(config: OverlayManagerConfig<TEntry>) {\n this.#config = config;\n }\n\n /**\n * Generates the next per-instance id and a paired idempotent\n * `remove` that drops the entry. The caller builds the `ref` with a teardown\n * that drives the exit animation before invoking `remove`.\n */\n protected nextId(): { id: string; remove: () => void } {\n const id = this.idGen.next(this.#config.idPrefix);\n let removed = false;\n const remove = (): void => {\n if (removed) {\n return;\n }\n removed = true;\n this.#entries.update((arr) => arr.filter((e) => e.id !== id));\n };\n return { id, remove };\n }\n\n /**\n * Drives the exit animation on the overlay root and, in lockstep,\n * on the portaled backdrop (matched by the same per-instance id, because the\n * backdrop's template `animate.leave` never fires under the manager's\n * `ngComponentOutlet` mount), then calls `remove`. Runs `remove` immediately\n * when destroying, when `requestAnimationFrame` is unavailable, or when there\n * is nothing to animate.\n */\n protected beginLeave(\n id: string,\n leaveClass: string | undefined,\n backdropLeaveClass: string | undefined,\n remove: () => void,\n ): void {\n if (this.#destroying || typeof requestAnimationFrame === 'undefined') {\n remove();\n return;\n }\n const { idAttribute, backdropAttribute } = this.#config;\n const targets: HTMLElement[] = [];\n if (leaveClass) {\n const host = this.#document.querySelector<HTMLElement>(\n `[${idAttribute}=\"${id}\"]:not([${backdropAttribute}])`,\n );\n if (host && typeof host.getAnimations === 'function') {\n host.classList.add(leaveClass);\n targets.push(host);\n }\n }\n if (backdropLeaveClass) {\n const backdrop = this.#document.querySelector<HTMLElement>(\n `[${backdropAttribute}][${idAttribute}=\"${id}\"]`,\n );\n if (backdrop && typeof backdrop.getAnimations === 'function') {\n backdrop.classList.add(backdropLeaveClass);\n targets.push(backdrop);\n }\n }\n if (targets.length === 0) {\n remove();\n return;\n }\n requestAnimationFrame(() => {\n const animations = targets.flatMap((el) => el.getAnimations());\n if (animations.length === 0) {\n remove();\n return;\n }\n Promise.all(animations.map((animation) => animation.finished.catch(() => undefined))).then(\n () => remove(),\n );\n });\n }\n\n /**\n * Builds a parent-cached per-component `Injector`. The returned\n * factory recreates the injector only when its parent changes, so re-renders\n * with the same enclosing `[forDialog]` / `[forDrawer]` host reuse it.\n */\n protected createInjectorFactory(providers: readonly Provider[]): (parent: Injector) => Injector {\n let cachedInjector: Injector | null = null;\n let cachedParent: Injector | null = null;\n return (parent: Injector): Injector => {\n if (cachedInjector && cachedParent === parent) {\n return cachedInjector;\n }\n cachedParent = parent;\n cachedInjector = Injector.create({ parent, providers: [...providers] });\n return cachedInjector;\n };\n }\n\n /**\n * Registers a fully-built entry, ensures the outlet exists, and\n * ticks so the `@for` renders it.\n */\n protected register(entry: TEntry): void {\n this.#ensureOutlet();\n this.#entries.update((arr) => [...arr, entry]);\n this.#appRef.tick();\n }\n\n #closeAllForDestroy(): void {\n this.#destroying = true;\n for (const entry of this.#entries()) {\n entry.ref.close();\n }\n }\n\n #ensureOutlet(): void {\n if (this.#outletRef) {\n return;\n }\n const outletRef = this.#config.createOutlet(this.#envInjector);\n this.#appRef.attachView(outletRef.hostView);\n outletRef.instance.init({\n entries: this.#entries.asReadonly(),\n closeAllForDestroy: () => this.#closeAllForDestroy(),\n });\n this.#outletRef = outletRef;\n }\n}\n","import { signal } from '@angular/core';\n\n/**\n * Shared handle returned by an imperative overlay manager's `open()`.\n * `ForDialogRef` / `ForDrawerRef` extend this verbatim to keep their public\n * class identity (and DI token) while the close engine lives here once.\n *\n * Both reactive (`isClosed`, `result`) and awaitable (`closed`) APIs are\n * exposed — pick what fits the call site. `R` is the close-result type.\n *\n * Internal — not re-exported from `public-api.ts`; the public surface is\n * `ForDialogRef` / `ForDrawerRef`.\n */\nexport class OverlayRef<R = unknown> {\n readonly #result = signal<R | undefined>(undefined);\n readonly #closed = signal(false);\n\n /** Reactive: `true` once `close()` has been called. */\n readonly isClosed = this.#closed.asReadonly();\n\n /** Reactive: the close result. `undefined` while open. */\n readonly result = this.#result.asReadonly();\n\n /** Awaitable: resolves with the close result the first time `close()` runs. */\n readonly closed: Promise<R | undefined>;\n\n #resolveClosed!: (r: R | undefined) => void;\n readonly #teardown: () => void;\n\n /** Internal composition surface (no semver guarantees). */\n constructor(teardown: () => void) {\n this.#teardown = teardown;\n this.closed = new Promise((resolve) => {\n this.#resolveClosed = resolve;\n });\n }\n\n /**\n * Close the overlay, optionally returning a result. Idempotent — calling\n * twice is a no-op.\n */\n close(result?: R): void {\n if (this.#closed()) {\n return;\n }\n this.#result.set(result);\n this.#closed.set(true);\n this.#resolveClosed(result);\n this.#teardown();\n }\n}\n","import { afterNextRender, effect, ElementRef, inject, type Signal } from '@angular/core';\nimport {\n autoUpdate,\n computePosition,\n type Middleware,\n type Padding,\n type ReferenceElement,\n} from '@floating-ui/dom';\n\nimport { injectPortal } from '../portal/portal';\n\nexport interface ItemAlignedConfig {\n /**\n * The anchor (typically a `<button>` trigger). Reactive — should emit\n * `null` until the anchor is available; positioning is skipped while\n * `null` or `open` is `false`.\n */\n readonly reference: Signal<ReferenceElement | null>;\n\n /**\n * Whether the listbox is currently visible. `autoUpdate` is started when\n * this becomes `true` and torn down when it goes back to `false`.\n */\n readonly open: Signal<boolean>;\n\n /**\n * The selected option element to anchor over the trigger. When `null`,\n * the algorithm falls back to the first enabled `[role=\"option\"]` inside\n * the listbox. Reactive — re-running `computePosition` if the selection\n * changes while open.\n */\n readonly selectedOption: Signal<HTMLElement | null>;\n\n /**\n * Padding (px) the listbox keeps from the viewport edge. Default `8`.\n * Drives both the viewport clamp on the listbox top/bottom and the\n * `--for-select-content-available-height` CSS variable.\n */\n readonly collisionPadding?: Signal<number | Padding>;\n\n /**\n * When `true` (default), the floating element is moved to `document.body`\n * on first render and removed on destroy. Set to `false` when the caller\n * already invokes `injectPortal()` on its own.\n */\n readonly portal?: boolean;\n}\n\nfunction paddingTop(padding: number | Padding | undefined, fallback: number): number {\n if (padding == null) {\n return fallback;\n }\n if (typeof padding === 'number') {\n return padding;\n }\n return padding.top ?? fallback;\n}\n\nfunction findFirstEnabledOption(listbox: HTMLElement): HTMLElement | null {\n const options = listbox.querySelectorAll<HTMLElement>('[role=\"option\"]');\n for (let i = 0; i < options.length; i++) {\n const opt = options[i]!;\n if (opt.getAttribute('aria-disabled') === 'true' || opt.hasAttribute('disabled')) {\n continue;\n }\n return opt;\n }\n return null;\n}\n\n/**\n * Custom floating-ui middleware. Computes raw `x`/`y` so the *target option's\n * vertical center* lines up with the *trigger's vertical center*, then clamps\n * the listbox inside the viewport with `padding`. Cross-axis: listbox left\n * edge aligned to the trigger left edge.\n *\n * Falls back to the first enabled option inside the listbox when no option\n * is selected — matches the macOS `<select>` behavior.\n */\nfunction itemAligned(\n selectedOption: () => HTMLElement | null,\n paddingFn: () => number,\n): Middleware {\n return {\n name: 'item-aligned',\n fn(state) {\n const reference = state.elements.reference;\n const floating = state.elements.floating;\n const triggerRect = reference.getBoundingClientRect();\n const listboxRect = floating.getBoundingClientRect();\n const target = selectedOption() ?? findFirstEnabledOption(floating);\n const padding = paddingFn();\n // Read the viewport height through the floating element's own\n // window so the middleware works in iframes / multiple-document\n // contexts and stays SSR-safe (the middleware itself only runs\n // inside a `computePosition` callback, which is browser-only).\n const viewportHeight = floating.ownerDocument.defaultView?.innerHeight ?? 0;\n\n let y: number;\n if (target) {\n const optRect = target.getBoundingClientRect();\n const targetCenterRelToListbox = optRect.top - listboxRect.top + optRect.height / 2;\n const desiredY = triggerRect.top + triggerRect.height / 2 - targetCenterRelToListbox;\n const minY = padding;\n const maxY = viewportHeight - listboxRect.height - padding;\n y = maxY > minY ? Math.max(minY, Math.min(desiredY, maxY)) : minY;\n } else {\n y = Math.max(\n padding,\n Math.min(triggerRect.top, viewportHeight - listboxRect.height - padding),\n );\n }\n\n return { x: triggerRect.left, y };\n },\n };\n}\n\n/**\n * Item-aligned positioner for `[forSelectContent]` (the `position=\"item-aligned\"`\n * mode). The listbox overlays the trigger so the *selected option*'s center\n * lines up with the trigger's center on the cross axis — visually the menu\n * \"snaps over\" the trigger when opened, mirroring macOS native `<select>`\n * dropdowns.\n *\n * Owns:\n * 1. Optional portal — `appendChild` to `document.body` on first render,\n * `remove()` on destroy.\n * 2. A reactive effect that runs `autoUpdate(reference, listbox, …)` while\n * `open` is true. Inside, calls `computePosition` with the custom\n * `itemAligned` middleware and writes the resolved position via the\n * `translate` property (leaving `transform` free for the consumer),\n * `data-position=\"item-aligned\"`, anchor-width / anchor-height /\n * available-height CSS vars. On the first resolved position it drops the\n * `clip-path` hide baseline so the listbox is only painted once anchored.\n * 3. After the first position resolves, scrolls the target option into view\n * via `scrollIntoView({ block: 'nearest' })` so the visual anchor stays\n * correct when the listbox is taller than the viewport.\n *\n * `side`, `align`, `sideOffset`, `alignOffset`, `placement`, `flip`, `shift`,\n * and `arrow` are intentionally **not** part of this API — item-aligned mode\n * treats them as no-ops.\n */\nexport function injectItemAlignedPositioner(config: ItemAlignedConfig): void {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const el = host.nativeElement;\n\n if (config.portal !== false) {\n injectPortal();\n }\n\n afterNextRender(() => {\n // `clip-path: inset(50%)` keeps the listbox unpainted until the first\n // position resolves, so a CSS enter animation never flashes a frame at\n // the `left:0 / top:0` origin before the async `computePosition().then()`\n // writes the real `transform`. `clip-path` (not `visibility: hidden`)\n // keeps the element focusable so the overlay shell's initial-focus move\n // (selected option) still lands. Dropped on the first resolved position.\n Object.assign(el.style, {\n position: 'fixed',\n left: '0',\n top: '0',\n clipPath: 'inset(50%)',\n });\n });\n\n effect((onCleanup) => {\n const isOpen = config.open();\n const reference = config.reference();\n\n if (!isOpen || !reference) {\n return;\n }\n\n const collisionPadding = paddingTop(config.collisionPadding?.(), 8);\n\n // Re-arm the `clip-path: inset(50%)` baseline on every open effect run.\n // `onCleanup` now calls `resetItemAlignedStyles` which clears it, so\n // without re-arming a reopen / selection change would paint at the\n // previous frame's stale `translate` until `computePosition` re-resolves.\n el.style.clipPath = 'inset(50%)';\n\n let initialScrollDone = false;\n\n const cleanup = autoUpdate(reference, el, () => {\n computePosition(reference, el, {\n strategy: 'fixed',\n // Placement is irrelevant — `itemAligned` overrides x/y outright —\n // but `computePosition` requires *some* placement. Pick a stable one\n // so middleware data stays predictable.\n placement: 'bottom-start',\n middleware: [\n itemAligned(\n () => config.selectedOption(),\n () => collisionPadding,\n ),\n ],\n }).then(({ x, y }) => {\n if (!config.open()) {\n return;\n }\n\n // Position via the `translate` property (not `transform`) so a\n // consumer's enter animation on `scale` / `transform` pivots in place\n // instead of scaling the position offset — see the note in\n // `injectFloating`. Leaves `transform` free for the consumer.\n el.style.translate = `${Math.round(x)}px ${Math.round(y)}px`;\n el.dataset['position'] = 'item-aligned';\n // First valid position resolved — reveal the listbox by dropping the\n // `clip-path: inset(50%)` baseline.\n el.style.clipPath = '';\n\n const triggerRect = reference.getBoundingClientRect();\n el.style.setProperty('--for-anchor-width', `${Math.round(triggerRect.width)}px`);\n el.style.setProperty('--for-anchor-height', `${Math.round(triggerRect.height)}px`);\n\n const innerHeight = el.ownerDocument.defaultView?.innerHeight ?? 0;\n const availableHeight = Math.max(0, innerHeight - 2 * collisionPadding);\n el.style.setProperty(\n '--for-select-content-available-height',\n `${Math.round(availableHeight)}px`,\n );\n\n if (!initialScrollDone) {\n initialScrollDone = true;\n const target = config.selectedOption() ?? findFirstEnabledOption(el);\n // jsdom (test env) doesn't implement scrollIntoView — guard the\n // call so the helper stays usable in non-browser environments.\n target?.scrollIntoView?.({ block: 'nearest' });\n }\n });\n });\n\n // Clean up symmetrically with what computePosition wrote — mirrors\n // `injectFloating` — so a same-instance reopen doesn't inherit stale\n // `translate` / `--for-*` / `data-position` or a dropped anti-flash\n // baseline.\n onCleanup(() => {\n cleanup();\n resetItemAlignedStyles(el);\n });\n });\n}\n\n/**\n * Strip every inline style, CSS custom property, and `data-*` attribute\n * `injectItemAlignedPositioner` writes to the listbox (including the\n * `clip-path` hide baseline). Mirrors `resetFloatingStyles` in `floating.ts`\n * so a closed-then-reopened listbox starts from a clean slate — no leftover\n * `translate` jumping the next open, no stale `--for-*` poisoning size\n * styles, no orphaned `data-position`.\n */\nfunction resetItemAlignedStyles(el: HTMLElement): void {\n el.style.removeProperty('translate');\n el.style.removeProperty('clip-path');\n el.style.removeProperty('--for-anchor-width');\n el.style.removeProperty('--for-anchor-height');\n el.style.removeProperty('--for-select-content-available-height');\n el.removeAttribute('data-position');\n}\n","import { DestroyRef, ElementRef, inject, isDevMode, type Signal } from '@angular/core';\n\nimport { afterNextRenderCancellable } from '../after-next-render-cancellable/after-next-render-cancellable';\nimport {\n injectDismissableLayer,\n type DismissableLayerActivateOptions,\n} from '../dismissable-layer/dismissable-layer';\nimport { findFirstFocusable } from '../focus-trap/focus-trap';\nimport { injectFloating, type FloatingConfig } from '../floating/floating';\nimport { InertSiblingsStack, MODAL_PEER_ATTRIBUTE } from '../inert-siblings/inert-siblings';\nimport { injectItemAlignedPositioner, type ItemAlignedConfig } from '../floating/item-aligned';\nimport {\n createVetoableNativeEvent,\n type VetoableNativeEvent,\n} from '../vetoable-event/vetoable-event';\n\n/**\n * Tagged-union positioner config. The shell delegates to either\n * `injectFloating` (the standard anchored placement) or\n * `injectItemAlignedPositioner` (the macOS-style overlay used by Select's\n * `position=\"item-aligned\"` mode). Both helpers portal by default, so the\n * shell never calls `injectPortal` itself — that responsibility stays with\n * the positioner.\n */\nexport type OverlayShellPositionerConfig =\n | ({ readonly kind: 'floating' } & FloatingConfig)\n | ({ readonly kind: 'item-aligned' } & ItemAlignedConfig);\n\n/**\n * Dismissable-layer wiring. The shell owns the pointer/focus/interact veto\n * reuse that every trigger-anchored overlay (Popover, Menu / MenuSub /\n * ContextMenu / DropdownMenu, Combobox, Select, date-picker) used to\n * duplicate verbatim as a per-primitive `#pendingOutsideVeto` field:\n *\n * - The specific outside channels (pointer-down-outside / focus-outside) fire\n * on the same physical interaction as the composite `interactOutside`, and\n * the dismissable layer always invokes the specific listener first. The\n * shell builds a single `VetoableNativeEvent` on the specific call, hands it\n * to the consumer's emitter, and reuses it for the immediately-following\n * composite call so a `preventDefault()` from either handler vetoes the\n * close.\n * - When the consumer doesn't veto AND `dismissible()` is `true`, the shell\n * calls `requestClose(reason)` with the channel's reason\n * (`'pointerDownOutside' | 'focusOutside'`) from the composite handler.\n * `dismissible` / `requestClose` are required whenever any outside channel\n * is wired and unused otherwise.\n * - `exemptElements` is recomputed on every event so DOM mutations (newly\n * portaled siblings, swapped triggers) are picked up live.\n *\n * Escape stays a one-shot, consumer-owned channel (`emitEscapeKeyDown`\n * receives the raw `KeyboardEvent` and forwards verbatim to the layer): it\n * never participates in the shared `#pendingOutsideVeto` reuse, and its close\n * behaviour differs per primitive (hover-card schedules a close, the input-\n * focused combobox owns Escape on its input directive and omits it here). The\n * shell therefore leaves Escape's emit + close decision entirely to the\n * consumer.\n *\n * Each callback is individually optional so a primitive can opt out of a\n * single channel; the shell registers a layer listener only for the channels\n * the consumer actually forwards.\n */\nexport interface OverlayShellDismissConfig {\n /**\n * Whether an un-vetoed outside interaction fires the implicit\n * `requestClose`. Required when any outside channel\n * (`emitPointerDownOutside` / `emitFocusOutside` / `emitInteractOutside`)\n * is wired.\n */\n readonly dismissible?: Signal<boolean>;\n /**\n * Called with the matching reason when the consumer doesn't veto an outside\n * interaction. The consumer owns the close (and any bookkeeping such as\n * marking the control touched); the shell never touches the directive's\n * close output directly. Required alongside `dismissible`. The implicit close\n * fires from the composite `emitInteractOutside` channel only, so a wiring\n * that provides `requestClose` MUST also wire `emitInteractOutside` — the\n * shell throws a dev-mode error otherwise.\n */\n readonly requestClose?: (reason: 'pointerDownOutside' | 'focusOutside') => void;\n /** Forwards the raw Escape `KeyboardEvent` to the consumer; close is consumer-owned. */\n readonly emitEscapeKeyDown?: (event: KeyboardEvent) => void;\n /** Forwards the pointer-down-outside veto to the directive's `(pointerDownOutside)` output. */\n readonly emitPointerDownOutside?: (veto: VetoableNativeEvent<PointerEvent>) => void;\n /** Forwards the focus-outside veto to the directive's `(focusOutside)` output. */\n readonly emitFocusOutside?: (veto: VetoableNativeEvent<FocusEvent>) => void;\n /** Forwards the composite veto to the directive's `(interactOutside)` output. */\n readonly emitInteractOutside?: (veto: VetoableNativeEvent<PointerEvent | FocusEvent>) => void;\n /**\n * Extra elements whose subtrees count as \"inside\" for outside-pointer /\n * outside-focus checks (e.g. an anchored trigger that lives outside the\n * portaled content). Recomputed on every event so DOM mutations are\n * picked up.\n */\n readonly exemptElements?: () => readonly Element[];\n}\n\n/**\n * Where initial focus should land when the surface mounts.\n *\n * - `'first'` — first focusable descendant of the host (uses the shared\n * `findFirstFocusable` selector). Falls back to the host element itself.\n * - `'container'` — host element (gets `tabindex=\"-1\"` semantics from the\n * primitive's host bindings).\n * - `move()` — primitive-owned focus algorithm (e.g. Menu's\n * `focusFirstEnabledItem`, Select's `focusSelectedOption`). Should return\n * `true` on success and `false` if no candidate was found, so the shell can\n * fall back to focusing the host element.\n */\nexport type OverlayShellInitialFocusMove = 'first' | 'container' | (() => boolean);\n\n/**\n * Optional initial-focus wiring. Absent when the consumer wants focus to\n * stay where it is (Combobox keeps focus in the input; Tooltip / HoverCard\n * have no focus moves).\n *\n * `veto` corresponds to the `(autoFocusOnOpen)` output: returning `true`\n * skips the imperative focus move.\n */\nexport interface OverlayShellInitialFocusConfig {\n readonly move: OverlayShellInitialFocusMove;\n readonly veto?: () => boolean;\n}\n\n/**\n * Optional return-focus wiring. Absent when the consumer never wants to\n * return focus on destroy (Combobox closes back into the input via its own\n * keydown / blur paths; Tooltip / HoverCard are non-focusing).\n *\n * - `enabled` — the primitive's `[returnFocus]` input. When `false`, the\n * shell skips the return-focus call entirely.\n * - `target` — the element to focus on destroy (typically the trigger).\n * Returning `null` is a safe no-op (the trigger may have unmounted).\n * - `veto` — `(autoFocusOnClose)` veto. Returning `true` skips the focus\n * call.\n * - `skip` — additional opt-out. Used by Select to skip return-focus when\n * `lastCloseReason() === 'tab'` (Tab already moved focus to the trigger\n * and let the browser advance from there).\n */\nexport interface OverlayShellReturnFocusConfig {\n readonly enabled: Signal<boolean>;\n readonly target: () => HTMLElement | null;\n readonly veto?: () => boolean;\n readonly skip?: () => boolean;\n}\n\n/**\n * Single config for the overlay-content lifecycle. Each sub-bundle is\n * individually optional so the nine concrete primitives (Popover, Menu,\n * MenuSub, ContextMenu, DropdownMenu, Combobox, Select, Tooltip, HoverCard)\n * can opt in to only the pieces they need.\n *\n * The shell never reads any of the primitive's own context tokens — the\n * caller forwards each piece as plain signals / callbacks so the shell stays\n * orthogonal to the primitive surface and trivially mockable in tests.\n */\nexport interface OverlayShellConfig {\n readonly positioner: OverlayShellPositionerConfig;\n readonly dismiss?: OverlayShellDismissConfig;\n readonly initialFocus?: OverlayShellInitialFocusConfig;\n readonly returnFocus?: OverlayShellReturnFocusConfig;\n}\n\n/**\n * Single source of truth for the floating-overlay content lifecycle. Drives\n * every `*-content.ts` directive in the library that mounts a portaled\n * surface (`Popover`, `Menu` / `MenuSub` / `ContextMenu` via the shared\n * `[forMenuContent]`, `Combobox`, `Select`, `Tooltip`, `HoverCard`). The\n * shell owns:\n *\n * 1. Positioning. Delegates to `injectFloating` (default) or\n * `injectItemAlignedPositioner` (Select's `position=\"item-aligned\"`).\n * Both positioners portal by default, so the shell never calls\n * `injectPortal` itself — the consumer must NOT either, on pain of\n * double-portaling (see #106).\n * 2. Dismissable layer. When `dismiss` is configured, creates a layer for\n * the host element and activates it inside `afterNextRender`. The shell\n * owns the triple-veto + composite `interactOutside` bookkeeping: it\n * builds one `VetoableNativeEvent` per physical interaction and reuses it\n * across the specific (`pointerDownOutside` / `focusOutside`) and composite\n * (`interactOutside`) channels, so a `preventDefault()` from either\n * suppresses the implicit close. When the consumer doesn't veto and\n * `dismissible()` is `true`, the shell calls `requestClose(reason)`.\n * Deactivation runs from the shell's `DestroyRef.onDestroy` hook.\n * 3. Initial focus. When `initialFocus` is configured, runs `veto()` first;\n * if it returns truthy the imperative focus move is skipped (this is the\n * `(autoFocusOnOpen)` veto). Otherwise the shell either calls the\n * primitive-owned `move()` callback (Menu / Select), focuses the first\n * focusable descendant via the shared `findFirstFocusable` from\n * `focus-trap.ts` (Popover's `'first'` mode), or focuses the host\n * container directly (Popover's `'container'` mode). When the chosen\n * move returns `false` (no candidate), focus falls back to the host so\n * keyboard users always land somewhere predictable.\n * 4. Return focus. When `returnFocus` is configured and `enabled()` is true,\n * on destroy the shell consults `skip()` and `veto()` (`(autoFocusOnClose)`)\n * and, if neither vetoes, calls `target()?.focus()`.\n *\n * Destroy ordering matches the per-primitive code that this helper replaced.\n * Hooks fire in registration order: `injectDismissableLayer` runs first\n * (deactivate + remove from stack), then the positioner's portal helper\n * (`el.remove()`), and the return-focus hook is registered last so it runs\n * after the portaled DOM node is detached — the trigger receives the focus\n * event in a stable layout.\n *\n * Must be called from an injection context (typically the directive\n * constructor). Forwards the host's `ElementRef` to the dismissable layer\n * and the positioner; the consumer never has to touch them.\n *\n * @example\n * // Popover-content\n * injectOverlayShell({\n * positioner: { kind: 'floating', reference: ctx.reference, open: ctx.open, ... },\n * dismiss: {\n * dismissible: ctx.dismissible,\n * requestClose: () => ctx.open.set(false),\n * emitEscapeKeyDown: (event) => ctx.emitEscapeKeyDown(event),\n * emitPointerDownOutside: (veto) => ctx.pointerDownOutside.emit(veto),\n * emitFocusOutside: (veto) => ctx.focusOutside.emit(veto),\n * emitInteractOutside: (veto) => ctx.interactOutside.emit(veto),\n * exemptElements: () => (ctx.trigger() ? [ctx.trigger()!] : []),\n * },\n * initialFocus: {\n * move: ctx.initialFocus() === 'container' ? 'container' : 'first',\n * veto: () => ctx.emitAutoFocusOnOpen(),\n * },\n * returnFocus: {\n * enabled: ctx.returnFocus,\n * target: () => ctx.trigger(),\n * veto: () => ctx.emitAutoFocusOnClose(),\n * },\n * });\n */\nexport function injectOverlayShell(config: OverlayShellConfig): void {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const el = host.nativeElement;\n const inertStack = inject(InertSiblingsStack);\n\n // 1. Dismissable layer. Created BEFORE the positioner so its\n // `DestroyRef.onDestroy` (dismissable.deactivate) registers first and\n // therefore runs first on teardown — i.e. the layer is removed from\n // the stack before the positioner's portal removes the node from the\n // DOM. That ordering matches every pre-shell *-content directive and\n // avoids a window where a focusin fired during DOM removal could\n // route through `handleFocusIn` and trigger a spurious onFocusOutside.\n const dismissCfg = config.dismiss;\n const layer = dismissCfg !== undefined ? injectDismissableLayer() : null;\n\n // 2. Positioner. The kind is read once at construction; switching modes\n // at runtime would require unmounting + remounting the directive,\n // which is the expected pattern for primitives whose positioning\n // algorithm is structurally different (Select's two modes).\n if (config.positioner.kind === 'item-aligned') {\n const { kind: _ignored, ...rest } = config.positioner;\n injectItemAlignedPositioner(rest);\n } else {\n const { kind: _ignored, ...rest } = config.positioner;\n injectFloating(rest);\n }\n\n // 3. afterNextRender — activate the layer and run initial focus once\n // input bindings have settled. Both pieces depend on having a\n // fully-rendered host element (exempt-element queries, focus targets).\n // `afterNextRenderCancellable` makes the destroy-before-render path safe.\n // On the true-async path (queued render after destroy) the callback is\n // cancelled, so the dismissable layer is never pushed onto the stack. On\n // the synchronous-teardown path the callback flushes just before the\n // layer's own `DestroyRef.onDestroy` (registered above via\n // `injectDismissableLayer`, so it runs first among the destroy hooks),\n // which pops the just-pushed layer. Either way the stack is left without\n // a dead topmost entry that would swallow every later Escape /\n // pointer-down-outside.\n afterNextRenderCancellable(() => {\n // Modal-peer marking (#676). When this overlay is anchored to an element\n // inside an active modal's protected root — i.e. it was opened from inside\n // a Dialog / Drawer (a Select in a form, a context menu on dialog content)\n // — stamp the freshly portaled host so the inert-siblings pass / observer\n // skips it. Without this the body-level inert sweep swallows forty's own\n // overlay, leaving it painted (z-index) but `inert` + `aria-hidden`: clicks\n // fall through to the controls behind it and the surface reads as hidden to\n // assistive tech (#676). `ownsAnchor` returns false when no modal is active,\n // so an overlay with no surrounding modal is never pre-marked (a modal\n // opened later inerts it like any background sibling), and false when the\n // anchor sits in an inerted background subtree, so a toast / background\n // overlay stays isolated (#388 semantics). The positioner's portal ran in\n // an earlier hook of this same render batch, so the host is already in\n // `body`; the attribute is set before the observer's microtask runs, so the\n // host is flagged by the time the observer inspects it.\n const anchor = resolveModalAnchor(config);\n if (anchor && inertStack.ownsAnchor(anchor)) {\n el.setAttribute(MODAL_PEER_ATTRIBUTE, '');\n }\n\n if (layer && dismissCfg) {\n // Pointer-down-outside and focus-outside both fire on the same physical\n // interaction as the composite `interactOutside`, and the dismissable\n // layer always invokes the specific listener before the composite one.\n // We build a single veto wrapper on the specific call and reuse it for\n // the composite call, so a `preventDefault()` in either handler vetoes\n // the close. Escape never enters this reuse — it is a one-shot,\n // consumer-owned channel forwarded verbatim below.\n let pendingOutsideVeto: VetoableNativeEvent<PointerEvent | FocusEvent> | null = null;\n const requestClose = dismissCfg.requestClose;\n const dismissible = dismissCfg.dismissible;\n const options: DismissableLayerActivateOptions = {};\n\n // The implicit outside-close fires from the composite `onInteractOutside`\n // handler only (the specific pointer/focus handlers just emit). A wiring\n // that provides `requestClose` but omits `emitInteractOutside` would emit\n // its outside outputs yet never close — fail loudly in dev rather than\n // ship that silent gap.\n if (isDevMode() && requestClose && !dismissCfg.emitInteractOutside) {\n throw new Error(\n '[forty-cdk/overlay-shell] dismiss.requestClose requires dismiss.emitInteractOutside to be wired; the implicit outside-close fires from the composite interactOutside channel.',\n );\n }\n\n if (dismissCfg.exemptElements) {\n options.exemptElements = dismissCfg.exemptElements;\n }\n // Escape: forwarded verbatim. The consumer owns the emit + close\n // decision (combobox routes it through its input directive instead and\n // omits this channel; hover-card schedules a timed close).\n if (dismissCfg.emitEscapeKeyDown) {\n options.onEscapeKeyDown = dismissCfg.emitEscapeKeyDown;\n }\n if (dismissCfg.emitPointerDownOutside) {\n const emit = dismissCfg.emitPointerDownOutside;\n options.onPointerDownOutside = (event) => {\n pendingOutsideVeto = createVetoableNativeEvent<PointerEvent | FocusEvent>(event);\n emit(pendingOutsideVeto as VetoableNativeEvent<PointerEvent>);\n };\n }\n if (dismissCfg.emitFocusOutside) {\n const emit = dismissCfg.emitFocusOutside;\n options.onFocusOutside = (event) => {\n pendingOutsideVeto = createVetoableNativeEvent<PointerEvent | FocusEvent>(event);\n emit(pendingOutsideVeto as VetoableNativeEvent<FocusEvent>);\n };\n }\n if (dismissCfg.emitInteractOutside) {\n const emit = dismissCfg.emitInteractOutside;\n options.onInteractOutside = (event) => {\n const veto =\n pendingOutsideVeto ?? createVetoableNativeEvent<PointerEvent | FocusEvent>(event);\n pendingOutsideVeto = null;\n emit(veto);\n if (!veto.defaultPrevented && dismissible?.() && requestClose) {\n requestClose(event.type === 'pointerdown' ? 'pointerDownOutside' : 'focusOutside');\n }\n };\n }\n\n layer.activate(options);\n }\n\n const focusCfg = config.initialFocus;\n if (focusCfg) {\n // Veto first — the `(autoFocusOnOpen)` output's `preventDefault`\n // returns true here, mirroring what the per-primitive code did.\n if (focusCfg.veto?.()) {\n return;\n }\n const move = focusCfg.move;\n if (move === 'first') {\n (findFirstFocusable(el) ?? el).focus();\n } else if (move === 'container') {\n el.focus();\n } else {\n // Primitive-owned focus algorithm (Menu's first/last item, Select's\n // selected option, etc.). Returns true on success; on miss we fall\n // back to the host so keyboard users land somewhere predictable.\n const moved = move();\n if (!moved) {\n el.focus();\n }\n }\n }\n });\n\n // 4. Return focus on destroy. The hook is registered AFTER the layer's\n // destroy hook (created above) and AFTER the positioner's portal hook\n // (created inside injectFloating / injectItemAlignedPositioner) so it\n // runs last — same ordering as the pre-shell hand-rolled code.\n const rfCfg = config.returnFocus;\n if (rfCfg) {\n inject(DestroyRef).onDestroy(() => {\n if (rfCfg.skip?.()) {\n return;\n }\n if (rfCfg.veto?.()) {\n return;\n }\n if (!rfCfg.enabled()) {\n return;\n }\n rfCfg.target()?.focus();\n });\n }\n}\n\n/**\n * Resolve the real DOM element an overlay is anchored to, for the modal-peer\n * ownership check (#676). Most overlays anchor to a real element (the trigger\n * button / input), exposed directly via the positioner `reference`.\n * Pointer-positioned overlays (ContextMenu) anchor to a floating-ui\n * `VirtualElement`: we read its `contextElement` when present, then fall back\n * to the return-focus target — the logical trigger the overlay was opened\n * from, which for ContextMenu is the registered right-click region. Returns\n * `null` when no backing element can be found (the overlay is then never\n * marked, falling back to the pre-#676 behaviour for that surface).\n */\nfunction resolveModalAnchor(config: OverlayShellConfig): Element | null {\n const ref = config.positioner.reference();\n if (ref instanceof Element) {\n return ref;\n }\n const contextElement = ref?.contextElement;\n if (contextElement instanceof Element) {\n return contextElement;\n }\n return config.returnFocus?.target() ?? null;\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/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 must include it.\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 — not re-exported from `public-api.ts`.\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 */\nexport function injectPauseController<R extends string>(\n options: PauseControllerOptions = {},\n): PauseController<R> {\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","import type { FloatingSide } from '../floating/floating';\n\n/**\n * Pointer-grace (\"safe triangle\") helper.\n *\n * When a mouse leaves a submenu trigger heading toward the submenu content,\n * a naive \"close on pointer-leave\" would dismiss the submenu the moment the\n * cursor crosses the gap between the trigger and the content. The fix native\n * desktop menus use is a *safe triangle*: a polygon drawn\n * from the cursor's exit point to the near edge of the submenu content. While\n * the pointer stays inside that polygon it is assumed to be travelling toward\n * the submenu, so the close is held off.\n *\n * This module keeps no Angular DI surface — the geometry is pure functions\n * (unit-tested in `pointer-grace.spec.ts`) and {@link attachPointerGrace} is a\n * plain `addEventListener` wrapper returning a cleanup, wired by the directive\n * through its `DestroyRef`. The DOM-measured inputs (cursor position, content\n * rect, resolved side) are supplied by the caller, so the geometry stays\n * testable without faking layout.\n */\n\n/** A point in client (viewport) coordinates. */\nexport interface Point {\n readonly x: number;\n readonly y: number;\n}\n\n/** The subset of `DOMRect` the grace polygon needs. */\nexport interface GraceRect {\n readonly top: number;\n readonly right: number;\n readonly bottom: number;\n readonly left: number;\n}\n\n/**\n * Resolves which side a submenu actually rendered on by comparing the\n * geometry of the trigger and content rects, independent of any requested\n * placement. Picks the axis (horizontal vs vertical) with the larger\n * centre-to-centre separation, then the direction along it.\n *\n * This is the load-bearing fix for the safe-triangle: `injectFloating` only\n * writes the resolved `data-side` inside the async `computePosition().then()`,\n * so on the first hover-open it is still `undefined` and a `flip` near a\n * viewport edge would have armed the grace polygon toward the *requested*\n * side. Deriving the side from the live rects at arm time reflects the real\n * placement even before positioning settles.\n *\n * @param trigger Sub-trigger rect (client coords), from `getBoundingClientRect`.\n * @param content Submenu content rect (client coords), from `getBoundingClientRect`.\n */\nexport function resolveGraceSide(trigger: GraceRect, content: GraceRect): FloatingSide {\n const triggerCenterX = (trigger.left + trigger.right) / 2;\n const triggerCenterY = (trigger.top + trigger.bottom) / 2;\n const contentCenterX = (content.left + content.right) / 2;\n const contentCenterY = (content.top + content.bottom) / 2;\n const dx = contentCenterX - triggerCenterX;\n const dy = contentCenterY - triggerCenterY;\n if (Math.abs(dx) >= Math.abs(dy)) {\n return dx >= 0 ? 'right' : 'left';\n }\n return dy >= 0 ? 'bottom' : 'top';\n}\n\n/** An ordered list of vertices describing a simple (non-self-intersecting) polygon. */\nexport type Polygon = readonly Point[];\n\n/**\n * Pixels the cursor apex is pulled *back* (away from the content) when the\n * polygon is built, so the exit point sits reliably inside the polygon even\n * after sub-pixel rounding of the pointer-leave coordinates.\n */\nconst GRACE_BLEED_PX = 5;\n\n/**\n * Standard even-odd ray-casting point-in-polygon test. Returns `true` when\n * {@link point} lies inside {@link polygon}. Points exactly on an edge are\n * reported inconsistently (as with any ray-cast) — that is acceptable here\n * because the bleed keeps the cursor apex strictly inside and the close path\n * is delay-guarded, so a single ambiguous edge sample never decides the\n * outcome.\n */\nexport function isPointInPolygon(point: Point, polygon: Polygon): boolean {\n let inside = false;\n for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {\n const vi = polygon[i];\n const vj = polygon[j];\n const intersects =\n vi.y > point.y !== vj.y > point.y &&\n point.x < ((vj.x - vi.x) * (point.y - vi.y)) / (vj.y - vi.y) + vi.x;\n if (intersects) {\n inside = !inside;\n }\n }\n return inside;\n}\n\n/**\n * Builds the safe-triangle polygon for a submenu opening on {@link side}.\n *\n * The polygon is a pentagon: the (bleeded) cursor apex plus the four corners\n * of the content rect, ordered so the cursor is adjacent to the two corners of\n * the content edge *nearest* the trigger. That shape covers both the triangle\n * the pointer travels through and the content itself, so the pointer is \"in\n * the grace area\" right up until it reaches the content.\n *\n * @param cursor Pointer position (client coords) captured at pointer-leave.\n * @param rect Submenu content rect (client coords), from `getBoundingClientRect`.\n * @param side Resolved side the content actually rendered on, from {@link resolveGraceSide}.\n */\nexport function buildSubmenuGracePolygon(\n cursor: Point,\n rect: GraceRect,\n side: FloatingSide,\n): Polygon {\n const { top, right, bottom, left } = rect;\n switch (side) {\n // Content to the right; near edge = content's left edge.\n case 'right':\n return [\n { x: cursor.x - GRACE_BLEED_PX, y: cursor.y },\n { x: left, y: top },\n { x: right, y: top },\n { x: right, y: bottom },\n { x: left, y: bottom },\n ];\n // Content to the left; near edge = content's right edge.\n case 'left':\n return [\n { x: cursor.x + GRACE_BLEED_PX, y: cursor.y },\n { x: right, y: top },\n { x: left, y: top },\n { x: left, y: bottom },\n { x: right, y: bottom },\n ];\n // Content below; near edge = content's top edge.\n case 'bottom':\n return [\n { x: cursor.x, y: cursor.y - GRACE_BLEED_PX },\n { x: left, y: top },\n { x: left, y: bottom },\n { x: right, y: bottom },\n { x: right, y: top },\n ];\n // Content above; near edge = content's bottom edge.\n case 'top':\n return [\n { x: cursor.x, y: cursor.y + GRACE_BLEED_PX },\n { x: left, y: bottom },\n { x: left, y: top },\n { x: right, y: top },\n { x: right, y: bottom },\n ];\n }\n}\n\n/**\n * Attaches a document-level `pointermove` listener that calls {@link onExit}\n * the first time the mouse leaves {@link polygon}. The caller arms this on a\n * trigger pointer-leave and disarms it (via the returned cleanup) once the\n * pointer reaches the content, the grace window elapses, or the submenu is\n * otherwise resolved.\n *\n * Touch / pen moves are ignored — the safe triangle models a hovering mouse;\n * touch interaction opens submenus by tap, never by hover.\n *\n * Static-polygon assumption: {@link polygon} is captured once at arm time and\n * never re-measured for the lifetime of this listener. If the submenu content\n * repositions (a flip, a scroll, a resize) while the grace window is open, the\n * polygon goes stale and no longer matches the content's live rect. This is an\n * accepted trade-off: the grace window is short (a single pointer traversal\n * from trigger to content) and is itself delay-guarded downstream, so a\n * mid-window reposition is out of scope. Callers that need re-measurement\n * should re-arm (call the cleanup, then re-attach with a fresh polygon) rather\n * than expecting this handler to track layout.\n *\n * @returns A cleanup that removes the listener. Idempotent-safe to store and\n * call once from a `DestroyRef` hook.\n */\nexport function attachPointerGrace(\n doc: Document,\n polygon: Polygon,\n onExit: () => void,\n): () => void {\n const onMove = (event: PointerEvent): void => {\n if (event.pointerType !== '' && event.pointerType !== 'mouse') {\n return;\n }\n if (!isPointInPolygon({ x: event.clientX, y: event.clientY }, polygon)) {\n onExit();\n }\n };\n doc.addEventListener('pointermove', onMove);\n return () => doc.removeEventListener('pointermove', onMove);\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 { clamp } from '../numeric-step/numeric-step';\n\nexport { roundToStepPrecision } from '../numeric-step/numeric-step';\n\n/** Pointer travel (px) required before a resize drag starts mutating the value. */\nexport const DRAG_DEAD_ZONE_PX = 3;\n\n/** Clamps `value` into the inclusive `[min, max]` range. */\nexport function clampToRange(value: number, min: number, max: number): number {\n return clamp(value, min, max);\n}\n\n/** Configuration for {@link startPointerResize}. */\nexport interface PointerResizeConfig {\n /** Element that captures the pointer and receives the move / up / cancel listeners. */\n readonly host: HTMLElement;\n /** Axis the drag reads: `'x'` uses `clientX`, `'y'` uses `clientY`. */\n readonly axis: 'x' | 'y';\n /** Value at gesture start; raw pixel deltas are added to this. */\n readonly startValue: number;\n /** When `true`, the pixel delta sign is inverted (RTL on the `x` axis). */\n readonly invert: boolean;\n /** Maps a raw candidate value to its constrained value (clamp / round). */\n readonly constrain: (next: number) => number;\n /** Called with the new constrained value on every armed move that changes it. */\n readonly onResize: (value: number) => void;\n /**\n * Called once at gesture end (pointer-up / cancel) with the final value, but only\n * if the drag armed (crossed the dead-zone). A plain click never commits.\n */\n readonly onCommit: (value: number) => void;\n}\n\n/**\n * Starts a pointer-capture resize drag from a `pointerdown` event. Owns the\n * pointer-capture lifecycle, the dead-zone arming (a sub-threshold move never\n * mutates the value, so a jittery click is a no-op), the axis delta math with\n * optional RTL inversion, and the commit-once-on-release contract.\n *\n * Returns a teardown that detaches all listeners and releases the capture — call\n * it from the host's `DestroyRef` to clean up a drag interrupted by destruction.\n */\nexport function startPointerResize(event: PointerEvent, config: PointerResizeConfig): () => void {\n const { host, axis } = config;\n const startCoord = axis === 'x' ? event.clientX : event.clientY;\n let current = config.startValue;\n let armed = false;\n let active = true;\n\n function onMove(move: PointerEvent): void {\n if (!active) {\n return;\n }\n const raw = axis === 'x' ? move.clientX : move.clientY;\n let delta = raw - startCoord;\n if (!armed) {\n if (Math.abs(delta) < DRAG_DEAD_ZONE_PX) {\n return;\n }\n armed = true;\n }\n if (config.invert) {\n delta = -delta;\n }\n const next = config.constrain(config.startValue + delta);\n if (next === current) {\n return;\n }\n current = next;\n config.onResize(next);\n }\n\n function onUp(up: PointerEvent): void {\n if (!active) {\n return;\n }\n active = false;\n host.removeEventListener('pointermove', onMove);\n host.removeEventListener('pointerup', onUp);\n host.removeEventListener('pointercancel', onUp);\n if (host.hasPointerCapture(up.pointerId)) {\n host.releasePointerCapture(up.pointerId);\n }\n if (armed) {\n config.onCommit(current);\n }\n }\n\n host.setPointerCapture(event.pointerId);\n host.addEventListener('pointermove', onMove);\n host.addEventListener('pointerup', onUp);\n host.addEventListener('pointercancel', onUp);\n\n return () => {\n if (!active) {\n return;\n }\n active = false;\n host.removeEventListener('pointermove', onMove);\n host.removeEventListener('pointerup', onUp);\n host.removeEventListener('pointercancel', onUp);\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 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 { effect, type Signal } from '@angular/core';\n\nimport type { HostRovingItemHandle } from './host-roving-context';\nimport type { RovingTabindex } from './roving-tabindex';\n\n/**\n * Reactively reset a {@link RovingTabindex} active pointer when the active\n * host leaves the group's usable set — it unregisters, becomes disabled, or\n * detaches from the document. Nulling the pointer lets each item's\n * first-enabled fallback re-engage so the group keeps exactly one tab stop\n * after a routine UI op (remove the focused item, disable it, filter a\n * dynamic list).\n *\n * Pairs with {@link RovingTabindex.unregister} (the deterministic teardown\n * path): this effect covers the runtime-disable case, where the host stays\n * registered but should no longer own the tab stop.\n *\n * Must be called in an injection context (a container directive's field\n * initializer or constructor) — internally calls `effect`.\n *\n * @param roving The tracker to reconcile.\n * @param items Reactive list of the group's registered handles (typically\n * `Collection.items()`); each must expose `host` and a `disabled` signal.\n */\nexport function reconcileRovingActive(\n roving: RovingTabindex,\n items: Signal<readonly HostRovingItemHandle[]>,\n): void {\n effect(() => {\n const active = roving.active();\n if (active === null) {\n return;\n }\n const handle = items().find((item) => item.host === active);\n if (!handle || handle.disabled() || !active.isConnected) {\n roving.setActive(null);\n }\n });\n}\n","import { computed, type Signal, signal } from '@angular/core';\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 deliberately 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**: a stale active element — one that\n * has detached from the document, or carries `disabled` / `aria-disabled`\n * (every primitive reflects its disabled state to one of those attributes) —\n * is treated as \"no active\", so the consumer's first-enabled fallback\n * re-engages and the group keeps exactly one tab stop. This guards the\n * single-frame window before the container's reconciliation nulls the\n * pointer; containers should still call {@link unregister} on teardown and\n * reconcile against their visible set for a clean, reactive reset.\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 #active = signal<HTMLElement | null>(null);\n\n /**\n * The raw active element, or `null`. Reflects the last {@link setActive}\n * call verbatim, including a now-stale element — use it for \"is this the\n * focused candidate\" styling (`data-highlighted`). For the tab-stop gate,\n * prefer {@link hasActive}, which discounts a stale active.\n */\n readonly active: Signal<HTMLElement | null> = this.#active.asReadonly();\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> = computed(() => {\n const el = this.#active();\n return el !== null && !isStale(el);\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.#active.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.#active.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.#active.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 type { SwipeDirection } from '../swipe-dismiss/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","import { isSignal, type Signal, signal, type WritableSignal } from '@angular/core';\n\n/** Options for {@link SelectionModel}. */\nexport interface SelectionModelOptions<T> {\n /**\n * Allow more than one selected value. `false` (default) is single-select:\n * `select` / `setSelection` replace the prior value. Accepts a `Signal` so a\n * consumer whose mode is reactive (e.g. a table's `selectionMode`) can drive\n * it without reconstructing the model.\n */\n readonly multiple?: boolean | Signal<boolean>;\n /**\n * Equality comparator used for membership and de-duplication. Defaults to\n * `===` (correct for primitive values); supply an id-based comparator for\n * object values: `(a, b) => a.id === b.id`.\n */\n readonly compareWith?: (a: T, b: T) => boolean;\n}\n\n/**\n * Signal-first selection state shared across primitives (table rows today;\n * listbox / tree can converge later). Single- or multi-select, equality-aware\n * membership, and `added` / `removed` deltas from the last mutation. Every\n * mutating method returns whether the selection actually changed.\n *\n * The model does **not** own its backing store: callers pass a\n * `WritableSignal<readonly T[]>` (typically their own `model()`), so there is a\n * single source of truth and no `effect()`-based sync. `selected` is a readonly\n * view of that source; mutators write through it.\n */\nexport class SelectionModel<T> {\n readonly #source: WritableSignal<readonly T[]>;\n readonly #multiple: Signal<boolean>;\n readonly #compareWith: (a: T, b: T) => boolean;\n\n readonly #added = signal<readonly T[]>([]);\n readonly #removed = signal<readonly T[]>([]);\n\n /** The current selection, in insertion order. Readonly view of the backing source. */\n readonly selected: Signal<readonly T[]>;\n /** Values added by the most recent mutation through this model. */\n readonly added: Signal<readonly T[]> = this.#added.asReadonly();\n /** Values removed by the most recent mutation through this model. */\n readonly removed: Signal<readonly T[]> = this.#removed.asReadonly();\n\n constructor(source: WritableSignal<readonly T[]>, options?: SelectionModelOptions<T>) {\n this.#source = source;\n this.selected = source.asReadonly();\n const multiple = options?.multiple ?? false;\n this.#multiple = isSignal(multiple) ? multiple : signal(multiple);\n this.#compareWith = options?.compareWith ?? ((a, b) => a === b);\n }\n\n /** Whether `value` is currently selected (under the comparator). */\n isSelected(value: T): boolean {\n return this.#has(this.#source(), value);\n }\n\n /**\n * Select `values`. In single mode keeps only the last given value; in multi\n * mode appends those not already present. Returns whether anything changed.\n */\n select(...values: T[]): boolean {\n if (values.length === 0) {\n return false;\n }\n if (!this.#multiple()) {\n return this.#commit([values[values.length - 1]!]);\n }\n const next = [...this.#source()];\n for (const v of values) {\n if (!this.#has(next, v)) {\n next.push(v);\n }\n }\n return this.#commit(next);\n }\n\n /** Deselect `values`. Returns whether anything changed. */\n deselect(...values: T[]): boolean {\n if (values.length === 0) {\n return false;\n }\n const next = this.#source().filter((v) => !values.some((d) => this.#compareWith(v, d)));\n return this.#commit(next);\n }\n\n /** Toggle a single value. Returns whether anything changed (always `true`). */\n toggle(value: T): boolean {\n return this.isSelected(value) ? this.deselect(value) : this.select(value);\n }\n\n /**\n * Replace the entire selection with `values` (de-duplicated). In single mode\n * keeps only the last. Returns whether anything changed.\n */\n setSelection(...values: T[]): boolean {\n if (!this.#multiple() && values.length > 1) {\n return this.#commit([values[values.length - 1]!]);\n }\n const next: T[] = [];\n for (const v of values) {\n if (!this.#has(next, v)) {\n next.push(v);\n }\n }\n return this.#commit(next);\n }\n\n /** Clear the selection. Returns whether anything changed. */\n clear(): boolean {\n return this.#commit([]);\n }\n\n #has(arr: readonly T[], value: T): boolean {\n return arr.some((x) => this.#compareWith(x, value));\n }\n\n #commit(next: readonly T[]): boolean {\n const current = this.#source();\n const added = next.filter((v) => !this.#has(current, v));\n const removed = current.filter((v) => !this.#has(next, v));\n if (added.length === 0 && removed.length === 0) {\n return false;\n }\n this.#added.set(added);\n this.#removed.set(removed);\n this.#source.set(next);\n return true;\n }\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. Other\n * array-backed primitives keep their own selection/expansion logic — `ForTree`\n * (string-keyed select / expand / extend-by-arrow), `Accordion`, and\n * `ToggleGroup` all manage their arrays directly rather than routing through\n * here, because their value semantics (string keys, no equality comparator, no\n * single-mode `T | null` view) differ. Treat this module as \"the\n * Select/Listbox/Combobox helper set\", not \"the library's one true selection\n * source\".\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","/**\n * Whether `error` is the NG0950 `RuntimeError(-950)` Angular throws when an\n * `input.required` is read before its binding is written. Detected via the\n * stable numeric `code` rather than the message text (stripped in production\n * builds). Returns `false` for any other throw, including non-`Error` values.\n */\nexport function isRequiredInputUnset(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n const code = (error as Error & { code?: unknown }).code;\n return typeof code === 'number' && Math.abs(code) === 950;\n}\n\n/**\n * Read a handle's inputs inside a snapshot fold, tolerating the NG0950 thrown\n * while a statically-rendered option is in the gap between registering (its\n * constructor, during the content view's *creation* pass) and having its\n * `input.required` binding written (that view's *update* pass). A fold-priming\n * effect flush runs in that gap, so a static option above a `@for` list would\n * otherwise hard-crash on open.\n *\n * Returns `null` in that window; the caller skips the handle for this fold. The\n * required-input signal's producer is accessed *before* the read throws, so the\n * dependency is still tracked: writing the binding marks the fold's\n * `linkedSignal` dirty and it re-runs, folding the handle in once its value is\n * set. Any non-NG0950 error propagates unchanged.\n */\nexport function tryReadHandle<R>(read: () => R): R | null {\n try {\n return read();\n } catch (error) {\n if (isRequiredInputUnset(error)) {\n return null;\n }\n throw error;\n }\n}\n","/**\n * Resolved snap target. The caller decides what to do with it: either close\n * the drawer (`willClose: true`) or transition to `nextSnapPoint` and update\n * the consumer's `[(activeSnapPoint)]`.\n */\nexport interface SnapResolution<S> {\n readonly willClose: boolean;\n /** The snap point to transition to. `null` when `willClose` is `true`. */\n readonly nextSnapPoint: S | null;\n}\n\nexport interface ResolveSnapTargetOptions<S> {\n /**\n * The snap points provided by the consumer, in the order they appear in\n * the input array (low → high — i.e. closest-to-anchor → furthest-from-anchor).\n * Each entry corresponds 1:1 with an entry in {@link snapPositions}.\n */\n readonly snapPoints: ReadonlyArray<S>;\n /**\n * The pixel position (along the dismissal axis, measured from the anchored\n * edge) of each snap point. Same length and ordering as {@link snapPoints}.\n * Computed from the live drawer dimension and the snap-point semantics by\n * the caller.\n */\n readonly snapPositions: ReadonlyArray<number>;\n /** The currently-active snap point. Match the elements of `snapPoints` by reference. */\n readonly activeSnapPoint: S | null;\n /**\n * Final pointer position along the dismissal axis, measured from the\n * anchored edge in CSS pixels. Larger means further from the edge.\n */\n readonly position: number;\n /**\n * Pointer velocity at release in CSS pixels per millisecond, signed so\n * positive == moving away from the anchored edge (i.e. toward larger\n * `position`). The threshold for \"fast flick\" is hard-coded to\n * `0.4` px/ms inside the helper.\n */\n readonly velocity: number;\n /**\n * Fraction of the **lowest snap point's** extent past which a\n * release from that snap dismisses the drawer. Default `0.25` — a release\n * that has dragged more than 25% of the lowest snap's size past it (toward\n * the edge) closes. Measuring against the lowest snap rather than the full\n * drawer dimension keeps dismissal reachable when the lowest snap is a\n * small \"peek\" relative to the full surface.\n */\n readonly closeThreshold: number;\n}\n\nconst VELOCITY_THRESHOLD_PX_PER_MS = 0.4;\n\n/**\n * Pure function that picks the snap target for a release gesture, combining\n * the final pointer position with the gesture velocity. Pulled into\n * `_internal/` so the Drawer directive doesn't have to embed the algorithm\n * (which is mildly involved and well-tested in isolation).\n *\n * Algorithm:\n *\n * 1. Pick the snap point with `snapPositions[i]` closest to `position`.\n * 2. If the velocity is fast enough (`|velocity| >= 0.4 px/ms`), bias one\n * step in the velocity direction. Negative velocity = toward edge,\n * positive = away from edge. Clamped at the array bounds.\n * 3. If the chosen target is the closest-to-edge snap point AND the gesture\n * ended *past* (closer to the edge than) that snap by more than\n * `closeThreshold` of the lowest snap's own extent, return\n * `willClose: true`. Scaling by the lowest snap rather than the full\n * drawer dimension keeps a small \"peek\" snap dismissable without having\n * to drag it entirely off-screen.\n *\n * Snap points are passed by the caller already converted to pixel positions\n * (`snapPositions`); the algorithm does not know whether they came from a\n * fraction, percentage string, or pixel string.\n *\n * Contract: callers must guard `snapPoints.length > 0` before calling this —\n * the no-snap-points dismissal is owned entirely by the caller (the Drawer\n * computes it directly from its drag offset and `closeThreshold`), so the\n * helper does not duplicate that branch with a second, inconsistent threshold\n * formula. Passing an empty `snapPoints` throws.\n */\nexport function resolveSnapTarget<S>(opts: ResolveSnapTargetOptions<S>): SnapResolution<S> {\n const { snapPoints, snapPositions, activeSnapPoint, position, velocity } = opts;\n if (snapPositions.length !== snapPoints.length) {\n throw new Error(\n '[forty-cdk/snap-points] resolveSnapTarget: snapPoints and snapPositions must have the same length.',\n );\n }\n if (snapPoints.length === 0) {\n throw new Error(\n '[forty-cdk/snap-points] resolveSnapTarget: requires at least one snap point; callers must guard snapPoints.length > 0 (the no-snap-points dismissal is the caller’s responsibility).',\n );\n }\n\n // 1) Closest snap by position.\n let closestIdx = 0;\n let closestDist = Math.abs(snapPositions[0]! - position);\n for (let i = 1; i < snapPositions.length; i++) {\n const dist = Math.abs(snapPositions[i]! - position);\n if (dist < closestDist) {\n closestDist = dist;\n closestIdx = i;\n }\n }\n\n // 2) Velocity bias. The active snap point is the anchor for the velocity\n // step — bias relative to where the user *was* before the gesture,\n // not relative to the geometric closest. Falls back to closestIdx if the\n // active is unknown.\n const activeIdx = activeSnapPoint != null ? snapPoints.indexOf(activeSnapPoint) : -1;\n const anchorIdx = activeIdx >= 0 ? activeIdx : closestIdx;\n\n let targetIdx = closestIdx;\n if (Math.abs(velocity) >= VELOCITY_THRESHOLD_PX_PER_MS) {\n if (velocity < 0) {\n // Fast move toward edge — bias one snap closer.\n targetIdx = Math.max(0, anchorIdx - 1);\n } else {\n // Fast move away from edge — bias one snap further.\n targetIdx = Math.min(snapPoints.length - 1, anchorIdx + 1);\n }\n }\n\n // 3) Dismiss check: only the closest-to-edge snap (index 0) gates dismissal.\n // Position past the threshold (i.e. closer to the edge) means the user\n // has dragged the drawer far enough off-screen to count as a dismiss.\n if (targetIdx === 0) {\n const lowestPos = snapPositions[0]!;\n const dismissThreshold = lowestPos * (1 - opts.closeThreshold);\n if (position < dismissThreshold) {\n return { willClose: true, nextSnapPoint: null };\n }\n }\n\n return { willClose: false, nextSnapPoint: snapPoints[targetIdx] ?? null };\n}\n","/**\n * Pointer-based swipe-to-dismiss helper.\n *\n * Used by `ForToast` (and any future primitive that wants swipe-to-dismiss\n * semantics: a horizontal/vertical drag that, when released past\n * the configured threshold, triggers a dismissal).\n *\n * The helper keeps no Angular DI surface — it's a plain function that\n * attaches pointer listeners to an `HTMLElement` and returns a cleanup\n * function. Callers wire it through the directive's `DestroyRef`.\n *\n * Behavior summary:\n * - On `pointerdown` the start position is recorded but no swipe is\n * announced yet. This avoids fake start/cancel pairs on plain clicks.\n * A second `pointerdown` while a pointer is already tracked is ignored,\n * so the first pointer keeps its capture and its `pointerup` still ends\n * the gesture (no orphaned capture on multi-touch).\n * - On `pointermove` the helper waits until the drag exceeds an internal\n * \"arm\" distance (a few pixels), picks the dominant axis, and decides\n * the candidate direction. If that direction is not in the allowed\n * set the gesture is dropped silently.\n * - Once armed, `onSwipeStart` fires (with the constrained delta) and\n * `onSwipeMove` fires for every subsequent move including the arming\n * one. Pointer capture is requested so events keep flowing if the\n * pointer leaves the element. `getDirections()` is re-read on every\n * armed move: if the active direction is toggled out of the allowed\n * set mid-gesture, the swipe is aborted (`onSwipeCancel` fires and the\n * captured pointer is released).\n * - On `pointerup`, if the projection along the active direction\n * reaches `getThreshold()`, `onSwipeEnd` fires; otherwise\n * `onSwipeCancel` fires.\n * - On `pointercancel`, `onSwipeCancel` always fires.\n * - `pointerup`, `pointercancel`, mid-gesture abort, and cleanup all\n * release the requested pointer capture symmetrically.\n *\n * Movement perpendicular to the active direction is clamped to `0`,\n * and movement opposite to the direction is clamped to `0` as well —\n * the consumer's CSS only ever sees a non-negative push along the\n * dismissal axis, so animations stay simple.\n */\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 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 * Attach swipe-dismiss listeners to `opts.element`. Returns a cleanup\n * function that removes every listener and releases pointer capture.\n *\n * @throws never. Capture / release calls are wrapped in try/catch so\n * environments without `PointerCapture` (jsdom) don't break.\n */\nexport function attachSwipeDismiss(opts: SwipeDismissOptions): () => void {\n const el = opts.element;\n let active = false;\n let direction: SwipeDirection | null = null;\n let pointerId: number | null = null;\n let startX = 0;\n let startY = 0;\n\n const reset = (): void => {\n active = false;\n direction = null;\n pointerId = null;\n };\n\n const releaseCapture = (id: number): void => {\n try {\n if (el.hasPointerCapture?.(id)) {\n el.releasePointerCapture?.(id);\n }\n } catch {\n // Some environments (jsdom) reject release on detached nodes.\n }\n };\n\n const onPointerDown = (event: PointerEvent): void => {\n // Mouse: only the primary button arms a potential swipe.\n if (event.pointerType === 'mouse' && event.button !== 0) {\n return;\n }\n // A pointer is already being tracked (the gesture is armed, or pending\n // arm): ignore the second pointerdown so its id/start don't overwrite the\n // first pointer's state and orphan its capture. The first pointer's\n // pointerup is then still honored.\n if (pointerId !== null) {\n return;\n }\n if (opts.getDirections().length === 0) {\n return;\n }\n pointerId = event.pointerId;\n startX = event.clientX;\n startY = event.clientY;\n active = false;\n direction = null;\n };\n\n const onPointerMove = (event: PointerEvent): void => {\n if (pointerId === null || event.pointerId !== pointerId) {\n return;\n }\n const dx = event.clientX - startX;\n const dy = event.clientY - startY;\n\n if (!active) {\n const detected = detectDirection(dx, dy, opts.getDirections());\n if (!detected) {\n return;\n }\n active = true;\n direction = detected;\n try {\n el.setPointerCapture?.(event.pointerId);\n } catch {\n // Some environments (jsdom) reject capture on detached nodes.\n }\n const detail: SwipeEventDetail = {\n direction: detected,\n delta: constrainedDelta(dx, dy, detected),\n originalEvent: event,\n };\n opts.onSwipeStart?.(detail);\n opts.onSwipeMove?.(detail);\n return;\n }\n\n if (!direction) {\n return;\n }\n // The allowed set can toggle mid-gesture (the \"off switch\"). If the active\n // direction is no longer allowed, abort the armed swipe: release capture\n // and fire onSwipeCancel so the consumer can settle back.\n if (!opts.getDirections().includes(direction)) {\n const detail: SwipeEventDetail = {\n direction,\n delta: constrainedDelta(dx, dy, direction),\n originalEvent: event,\n };\n releaseCapture(event.pointerId);\n reset();\n opts.onSwipeCancel?.(detail);\n return;\n }\n opts.onSwipeMove?.({\n direction,\n delta: constrainedDelta(dx, dy, direction),\n originalEvent: event,\n });\n };\n\n const onPointerUp = (event: PointerEvent): void => {\n if (pointerId === null || event.pointerId !== pointerId) {\n return;\n }\n if (active && direction) {\n const dx = event.clientX - startX;\n const dy = event.clientY - startY;\n const detail: SwipeEventDetail = {\n direction,\n delta: constrainedDelta(dx, dy, direction),\n originalEvent: event,\n };\n const proj = projection(dx, dy, direction);\n if (proj >= opts.getThreshold()) {\n opts.onSwipeEnd?.(detail);\n } else {\n opts.onSwipeCancel?.(detail);\n }\n releaseCapture(event.pointerId);\n }\n reset();\n };\n\n const onPointerCancel = (event: PointerEvent): void => {\n if (pointerId === null || event.pointerId !== pointerId) {\n return;\n }\n if (active && direction) {\n const dx = event.clientX - startX;\n const dy = event.clientY - startY;\n opts.onSwipeCancel?.({\n direction,\n delta: constrainedDelta(dx, dy, direction),\n originalEvent: event,\n });\n releaseCapture(event.pointerId);\n }\n reset();\n };\n\n el.addEventListener('pointerdown', onPointerDown);\n el.addEventListener('pointermove', onPointerMove);\n el.addEventListener('pointerup', onPointerUp);\n el.addEventListener('pointercancel', onPointerCancel);\n\n return () => {\n el.removeEventListener('pointerdown', onPointerDown);\n el.removeEventListener('pointermove', onPointerMove);\n el.removeEventListener('pointerup', onPointerUp);\n el.removeEventListener('pointercancel', onPointerCancel);\n if (pointerId !== null) {\n releaseCapture(pointerId);\n }\n };\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` that watches `dir`\n * attribute changes across the whole document, and exposes them as a\n * monotonically increasing `revision` tick.\n *\n * One observer covers every primitive: `injectTextDirection` derives each\n * host's ambient direction from a `computed` keyed on `revision`, so N\n * primitives reflecting `[attr.dir]` on first render coalesce into a single\n * observer callback (microtask-batched) → one `revision` bump → N ambient\n * recomputes — O(N), not the O(N²) cascade of N per-instance observers each\n * retriggering on every other's reflection.\n *\n * SSR-safe: on the server no observer is created, the DOM is never touched,\n * and `revision` stays `0`.\n *\n * The observer callback writing `#revision` is the single, intentional\n * \"external imperative source → signal\" exception, isolated here.\n *\n * Recompute granularity (intentional trade-off): a single `dir` mutation\n * anywhere in the document bumps the one shared `revision`, which invalidates\n * the ambient `computed` of **every** mounted dir-aware primitive — each then\n * re-walks its own ancestor chain. This is deliberately coarse: it keeps the\n * library at one document observer instead of one per primitive, and the\n * recompute is a cheap synchronous `closest('[dir]')` walk per host. With the\n * modest number of dir-aware primitives a typical page mounts, the\n * recompute-all cost is well below the cost of N per-instance observers each\n * retriggering on every other's reflection. If profiling ever flags it, cache\n * the ambient per *ancestor* (siblings under the same `[dir]` share a result)\n * or push the resolved ambient from this callback so a recompute becomes a\n * signal read rather than a DOM walk.\n *\n * Internal — not re-exported from `public-api.ts`.\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 * Returns a `Signal<WritingDirection>` equal to `explicitDir() ?? <ambient>`:\n * an explicit `[dir]` always wins, and when it is `null` the value falls back\n * to the **nearest ancestor carrying a `dir` attribute** (the host itself is\n * skipped — it reflects its own resolved `dir`), then to `<html dir>`,\n * defaulting to `'ltr'`.\n * Direction is read from the semantic `dir` attribute, not from CSS\n * `direction`; consumers who need a specific direction should set the `dir`\n * attribute on an ancestor (the standard `<html dir=\"rtl\">` setup) rather than\n * relying on `direction` in a stylesheet.\n *\n * SSR-safe: with no browser platform the ambient value is `'ltr'` and the DOM\n * is never touched. Reactive: a single application-wide `MutationObserver`\n * (owned by the root `AmbientDirection` service) watches `dir` attribute\n * changes across the whole document and publishes them as a shared `revision`\n * tick; the ambient is a `computed` keyed on that tick that reads the host's\n * ancestor chain synchronously. A runtime flip (e.g. a locale switch toggling\n * `<html dir>`, or an ancestor wrapper toggling its `dir`) bumps the tick and\n * recomputes the returned signal — regardless of how many primitives are\n * mounted, there is exactly one observer.\n *\n * Limitation: the shared observer watches `dir` attribute mutations only\n * (`attributeFilter: ['dir']`), not `childList`. The ambient therefore does\n * **not** recompute when the host is moved into a different-`dir` subtree\n * without any `dir` attribute itself changing (e.g. a parent re-parents the\n * element under an existing `[dir=\"rtl\"]` ancestor). Detecting that would need\n * a `childList`/`subtree` observer over the whole document — far costlier than\n * this case warrants. Reparenting between subtrees with different ambient\n * directions is rare; consumers who hit it should set an explicit `[dir]` on\n * the moved element or trigger any `dir` mutation to force a recompute.\n *\n * Must be called from an injection context (it injects `ElementRef`,\n * `DOCUMENT`, `PLATFORM_ID`, and `AmbientDirection`).\n *\n * Internal — not re-exported from `public-api.ts`.\n */\nexport function injectTextDirection(\n explicitDir: Signal<WritingDirection | null>,\n): Signal<WritingDirection> {\n const isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\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 if (!isBrowser) {\n return 'ltr';\n }\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-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 * 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 and case-insensitively. Returns the\n * matching option, or `null` when none matches (or the buffer is 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 = query.buffer.toLowerCase();\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 (getText(option).trim().toLowerCase().startsWith(needle)) {\n return option;\n }\n }\n return null;\n}\n","import { linkedSignal, signal, type Signal } from '@angular/core';\n\nimport { type ListNavigationAction, moveIndex } from '../keyboard-navigation/keyboard-navigation';\n\n/**\n * Re-export of the shared NG0950 read guard under the navigator's historical\n * name. The single source lives in `_internal/signal-graph/read-handle.ts`;\n * adapters wiring `readEntry` keep importing it from here.\n */\nexport { tryReadHandle as readEntryGuarded } from '../signal-graph/read-handle';\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 * Build the position-snapshot entry for a live handle, or `null` to skip it\n * this fold. The single NG0950 read guard (`readEntryGuarded`) is injected\n * here: a statically-rendered option that registers before its\n * `input.required` binding is written returns `null` and is folded in on the\n * 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\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 thin adapter — only once the consumer\n * sets `totalCount()` — so a non-virtualized collection never pulls this\n * position-map machinery into its hot path. Encapsulates two pieces of state\n * that make keyboard navigation work across a virtualized window where the\n * 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.\n * - **Pending active position** — when navigation lands outside the visible\n * window, the engine emits `(scrollToIndex)` and remembers the target. The\n * adapter's bridge effect calls `tryResolvePending` once the freshly-mounted\n * item carries that position.\n *\n * Internal — lives in `_internal/`, never re-exported from `public-api.ts`.\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 readonly #pendingActivePos = signal<number | 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 deferFold = options.deferFoldOnTotalTransition === true;\n\n this.#snapshotByPos = linkedSignal<\n { total: number | undefined; items: readonly H[] },\n Map<number, E>\n >({\n source: () => ({ total: deps.totalCount(), items: deps.items() }),\n computation: (src, prev) => {\n const totalChanged = prev !== undefined && prev.source.total !== src.total;\n if (deferFold && totalChanged) {\n return new Map<number, E>();\n }\n const next =\n totalChanged || prev === undefined ? new Map<number, E>() : new Map(prev.value);\n for (const item of src.items) {\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 }\n\n /**\n * Pull the position-map so its `linkedSignal` `prev` slot gets seeded while\n * the items are tracked. Called from the adapter'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 * 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. Returns `true` if a pending request was resolved, `false`\n * otherwise.\n */\n tryResolvePending(): boolean {\n const pendingPos = this.#pendingActivePos();\n if (pendingPos === null) {\n return false;\n }\n const match = this.#deps.items().find((it) => this.#accessors.posOf(it) === pendingPos);\n if (!match) {\n return false;\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. Walks `moveIndex` against the\n * absolute total, using the indexed snapshot to learn about disabled items\n * outside the rendered window. When the target is in the visible range and a\n * live item is present, seeds activedescendant directly; otherwise stashes the\n * target in the pending slot and emits `(scrollToIndex)`.\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 }\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 const isDisabled = (i: number) => indexed.get(i)?.disabled === true;\n\n const next = moveIndex(currentPos, total, action, {\n loop: this.#deps.loop(),\n isDisabled,\n });\n if (next === null) {\n return;\n }\n\n if (this.#seedIfRendered(next)) {\n return;\n }\n this.#pendingActivePos.set(next);\n this.#deps.emitScrollToIndex(next);\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.\n */\n seedActive(index: number): void {\n if (this.#seedIfRendered(index)) {\n return;\n }\n this.#pendingActivePos.set(index);\n this.#deps.emitScrollToIndex(index);\n }\n\n /** Clear any pending navigation (called by the adapter on close). */\n resetPending(): void {\n this.#pendingActivePos.set(null);\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","/** 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\n * one place rather than being re-derived per branch (the off-by-one shape behind\n * the #808 `gapIndex` overflow).\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 * Internal shared surface of forty-cdk — the `forty-cdk/core` entry point.\n *\n * This entry point holds everything formerly under `src/lib/_internal/`: the\n * cross-primitive DI singletons (`LiveAnnouncer`, focus-trap / dismissable-layer\n * / inert-siblings / drawer stacks, the id-generator salt, the defaults\n * registry), the framework-free geometry / interaction / overlay helpers, and\n * the cross-cutting public 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 * Stability: the symbols re-exported here carry NO semver guarantees. They are\n * an internal composition surface shared between forty-cdk's own entry points,\n * not a supported public API. Consume primitives from their own\n * `forty-cdk/<primitive>` entry points (or the main `forty-cdk` barrel), not\n * from here.\n */\n\nexport * from './body-scroll-lock/body-scroll-lock';\nexport * from './class-list/resolve-config-class';\nexport * from './collection/collection';\nexport * from './collection/first-enabled-host';\nexport * from './collection/fold-snapshot';\nexport * from './collection/register-handle';\nexport * from './date-adapter/date-adapter';\nexport * from './datetime/hour-cycle';\nexport * from './datetime/literal-directive';\nexport * from './datetime/segment-directive';\nexport * from './datetime/segment-editor';\nexport * from './datetime/segment-types';\nexport * from './datetime/serialize';\nexport * from './datetime/time-value-source';\nexport * from './defaults/defaults';\nexport * from './disabled-reflection/disabled-reflection';\nexport * from './dismissable-layer/dismissable-layer';\nexport * from './drag-session/auto-scroll';\nexport * from './drag-session/clamp-preview';\nexport * from './drag-session/drag-geometry';\nexport * from './drag-session/drag-positions';\nexport * from './drag-session/drag-preview';\nexport * from './drag-session/flip';\nexport * from './drag-session/handle-guard';\nexport * from './drag-session/keyboard-drag-keys';\nexport * from './drag-session/keyboard-drag-mediator';\nexport * from './drag-session/placeholder-position';\nexport * from './drag-session/pointer-session';\nexport * from './drag-session/preview-controller';\nexport * from './drag-session/tree-drop-resolver';\nexport * from './drawer-scale/drawer-scale-coordinator';\nexport * from './drawer-stack/drawer-side';\nexport * from './drawer-stack/drawer-stack';\nexport * from './element-size/element-size';\nexport * from './field/field-wiring';\nexport * from './fieldset/fieldset-context';\nexport * from './flat-hierarchy/flat-hierarchy';\nexport * from './floating/anchored-positioning-inputs';\nexport * from './floating/floating';\nexport * from './focusable-content/focusable-content';\nexport * from './form-ui-control/form-ui-control-base';\nexport * from './form-ui-control/unfocused-value-mirror';\nexport * from './form-ui-control/text-value-control-base';\nexport * from './hidden-input/hidden-input';\nexport * from './host-id/host-id';\nexport * from './hover-intent/debounced-action';\nexport * from './hover-intent/force-close-when-disabled';\nexport * from './hover-intent/hover-intent';\nexport * from './hover-intent/skip-delay-coordinator';\nexport * from './id-generator/id-generator';\nexport * from './inert-siblings/inert-siblings';\nexport * from './interactions/focus-visible';\nexport * from './interactions/hovered';\nexport * from './interactions/pressed';\nexport * from './keyboard-navigation/keyboard-navigation';\nexport * from './keyboard-navigation/move-in-collection';\nexport * from './listbox-overlay/listbox-overlay-controller';\nexport * from './live-announcer/live-announcer';\nexport * from './locale-number/locale-number';\nexport * from './media-query/media-query';\nexport * from './menu-overlay/menu-context';\nexport * from './menu-overlay/menu-focus-state';\nexport * from './menu-overlay/menu-item-list';\nexport * from './menu-overlay/menu-overlay';\nexport * from './menu-overlay/menu-overlay-host';\nexport * from './menu-overlay/menu-positioning-inputs';\nexport * from './modal-shell/modal-shell';\nexport * from './numeric-step/numeric-step';\nexport * from './overlay-manager/overlay-context-injector';\nexport * from './overlay-manager/overlay-manager';\nexport * from './overlay-manager/overlay-ref';\nexport * from './overlay-shell/overlay-shell';\nexport * from './pausable/pause-controller';\nexport * from './pointer-grace/pointer-grace';\nexport * from './pointer-suppression/pointer-suppression';\nexport * from './portal/portal';\nexport * from './resize-geometry/resize-geometry';\nexport * from './roving-tabindex/host-roving-context';\nexport * from './roving-tabindex/reconcile-roving-active';\nexport * from './roving-tabindex/roving-tabindex';\nexport * from './scroll-boundary/scroll-boundary';\nexport * from './selection-model/selection-model';\nexport * from './selection/selection';\nexport * from './signal-graph/read-handle';\nexport * from './snap-points/snap-points';\nexport * from './swipe-dismiss/swipe-dismiss';\nexport * from './text-direction/text-direction';\nexport * from './typeahead/match-options';\nexport * from './typeahead/typeahead';\nexport * from './vetoable-event/vetoable-event';\nexport * from './virtualized-navigator/virtualized-navigator';\nexport * from './visually-hidden/visually-hidden';\nexport * from './window-index-map/window-index-map';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":["clamp","hasInertAncestor"],"mappings":";;;;;AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCG;MAEU,cAAc,CAAA;AAChB,IAAA,SAAS,GAAG,MAAM,CAAC,QAAQ,CAAC;AAC5B,IAAA,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,WAAW;IACpC,UAAU,GAAG,iBAAiB,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;AAEnD,IAAA,QAAQ,GAAG,IAAI,GAAG,EAA8D;AAEzF;;;;AAIG;AACH,IAAA,IAAI,CAAC,MAAA,GAAsB,IAAI,CAAC,SAAS,CAAC,IAAI,EAAA;AAC5C,QAAA,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE;YACpB;QACF;QACA,IAAI,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC;QACtC,IAAI,CAAC,MAAM,EAAE;YACX,MAAM,GAAG,EAAE,KAAK,EAAE,CAAC,EAAE,iBAAiB,EAAE,KAAK,EAAE;YAC/C,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC;QACnC;AACA,QAAA,IAAI,MAAM,CAAC,KAAK,KAAK,CAAC,EAAE;AACtB,YAAA,MAAM,CAAC,KAAK,CAAC,QAAQ,GAAG,QAAQ;YAChC,MAAM,MAAM,GAAG,MAAM,KAAK,IAAI,CAAC,SAAS,CAAC,IAAI;AAC7C,YAAA,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO;AACxB,YAAA,IAAI,cAAsB;YAC1B,IAAI,MAAM,EAAE;AACV,gBAAA,MAAM,KAAK,GAAG,IAAI,C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