forty-cdk 0.44.0 → 0.45.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/accordion/README.md +16 -3
- package/combobox/README.md +15 -4
- package/disclosure/README.md +15 -3
- package/fesm2022/forty-cdk-accordion.mjs +64 -17
- package/fesm2022/forty-cdk-accordion.mjs.map +1 -1
- package/fesm2022/forty-cdk-avatar.mjs +6 -7
- package/fesm2022/forty-cdk-avatar.mjs.map +1 -1
- package/fesm2022/forty-cdk-combobox.mjs +8 -9
- package/fesm2022/forty-cdk-combobox.mjs.map +1 -1
- package/fesm2022/forty-cdk-core-anchored.mjs +9 -7
- package/fesm2022/forty-cdk-core-anchored.mjs.map +1 -1
- package/fesm2022/forty-cdk-core.mjs +72 -15
- package/fesm2022/forty-cdk-core.mjs.map +1 -1
- package/fesm2022/forty-cdk-defaults.mjs.map +1 -1
- package/fesm2022/forty-cdk-disclosure.mjs +69 -15
- package/fesm2022/forty-cdk-disclosure.mjs.map +1 -1
- package/fesm2022/forty-cdk-select.mjs +6 -7
- package/fesm2022/forty-cdk-select.mjs.map +1 -1
- package/fesm2022/forty-cdk-table.mjs +45 -1
- package/fesm2022/forty-cdk-table.mjs.map +1 -1
- package/package.json +1 -1
- package/radio-group/README.md +2 -2
- package/table/README.md +2 -0
- package/toggle/README.md +2 -2
- package/types/forty-cdk-accordion.d.ts +27 -4
- package/types/forty-cdk-combobox.d.ts +6 -6
- package/types/forty-cdk-core-anchored.d.ts +21 -4
- package/types/forty-cdk-core.d.ts +22 -26
- package/types/forty-cdk-defaults.d.ts +4 -3
- package/types/forty-cdk-disclosure.d.ts +37 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"forty-cdk-core-anchored.mjs","names":[],"sources":["../../../projects/forty-cdk/core-anchored/src/floating/floating-custom-properties.ts","../../../projects/forty-cdk/core-anchored/src/floating/floating-direction.ts","../../../projects/forty-cdk/core-anchored/src/floating/run-positioning.ts","../../../projects/forty-cdk/core-anchored/src/floating/floating.ts","../../../projects/forty-cdk/core-anchored/src/floating/anchored-positioning-inputs.ts","../../../projects/forty-cdk/core-anchored/src/floating/anchored-form-value-control-base.ts","../../../projects/forty-cdk/core-anchored/src/floating/anchored-overlay-positioning-base.ts","../../../projects/forty-cdk/core-anchored/src/floating/item-aligned.ts","../../../projects/forty-cdk/core-anchored/src/hover-intent/hover-intent.ts","../../../projects/forty-cdk/core-anchored/src/pointer-grace/pointer-grace.ts","../../../projects/forty-cdk/core-anchored/src/hover-intent/hover-surface-state.ts","../../../projects/forty-cdk/core-anchored/src/overlay-controller/element-registry.ts","../../../projects/forty-cdk/core-anchored/src/overlay-controller/close-reason-state.ts","../../../projects/forty-cdk/core-anchored/src/overlay-controller/initial-focus-state.ts","../../../projects/forty-cdk/core-anchored/src/overlay-controller/overlay-controller.ts","../../../projects/forty-cdk/core-anchored/src/overlay-controller/overlay-shell.ts","../../../projects/forty-cdk/core-anchored/src/listbox-overlay/listbox-overlay-controller.ts","../../../projects/forty-cdk/core-anchored/src/menu-overlay/menu-context.ts","../../../projects/forty-cdk/core-anchored/src/menu-overlay/menu-item-list.ts","../../../projects/forty-cdk/core-anchored/src/menu-overlay/menubar-axis.ts","../../../projects/forty-cdk/core-anchored/src/menu-overlay/menu-open-chain.ts","../../../projects/forty-cdk/core-anchored/src/menu-overlay/menu-opener-registry.ts","../../../projects/forty-cdk/core-anchored/src/menu-overlay/menu-overlay.ts","../../../projects/forty-cdk/core-anchored/src/menu-overlay/menu-overlay-host.ts","../../../projects/forty-cdk/core-anchored/src/scroll-dismiss/scroll-dismiss-dispatcher.ts"],"sourcesContent":["import { inject } from '@angular/core';\nimport { CssVarNamespacer } from '@angular/platform-browser';\n\nexport interface FloatingCustomProperties {\n readonly anchorWidth: string;\n readonly anchorHeight: string;\n readonly availableWidth: string;\n readonly availableHeight: string;\n readonly contentTransformOrigin: string;\n readonly arrowOffset: string;\n}\n\nexport function injectFloatingCustomProperties(): FloatingCustomProperties {\n const namespacer = inject(CssVarNamespacer);\n return {\n anchorWidth: namespacer.namespace('--for-floating-anchor-width'),\n anchorHeight: namespacer.namespace('--for-floating-anchor-height'),\n availableWidth: namespacer.namespace('--for-floating-available-width'),\n availableHeight: namespacer.namespace('--for-floating-available-height'),\n contentTransformOrigin: namespacer.namespace('--for-floating-content-transform-origin'),\n arrowOffset: namespacer.namespace('--for-floating-arrow-offset'),\n };\n}\n","export function isFloatingRtl(el: Element): boolean {\n return el.ownerDocument.defaultView?.getComputedStyle(el).direction === 'rtl';\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n afterNextRender,\n effect,\n ElementRef,\n inject,\n PLATFORM_ID,\n type Signal,\n} from '@angular/core';\nimport {\n autoUpdate,\n computePosition,\n type ComputePositionReturn,\n type Middleware,\n type Placement,\n type ReferenceElement,\n} from '@floating-ui/dom';\n\nimport { injectPortal } from 'forty-cdk/core';\n\n/**\n * The positioner-specific work for a single open run, returned by\n * {@link PositioningConfig.computeAndApply}. The shared scaffold owns the\n * platform gate, portal, anti-flash baseline, `autoUpdate` loop, the\n * `!open()` / cancelled-run bail, the `translate` write, the `clip-path` drop,\n * the per-open {@link PositioningConfig.onFirstPosition} dispatch, and the\n * `.catch(() => {})`; a run supplies only the parts that genuinely differ\n * between positioners.\n */\nexport interface PositioningRun {\n /**\n * The requested placement handed to `@floating-ui/dom`'s `computePosition`.\n * (The strategy is always `'fixed'`, owned by the scaffold.)\n */\n readonly placement: Placement;\n\n /** The middleware stack handed to `computePosition` for this run. */\n readonly middleware: Middleware[];\n\n /**\n * Applies a resolved position. Runs on every `autoUpdate` frame, after the\n * scaffold has bailed on a mid-frame close, written the resolved `translate`,\n * and dropped the `clip-path` anti-flash baseline. Writes the positioner's\n * own `data-*` attributes and CSS variables (and, for the anchored\n * positioner, the arrow).\n */\n apply(result: ComputePositionReturn): void;\n\n /**\n * Resets everything the run wrote, invoked from the effect's `onCleanup`\n * when `open` flips back to `false`, the config changes while open, or the\n * host is destroyed. What is reset (and what is intentionally retained for\n * `animate.leave`) is the positioner's decision.\n */\n reset(): void;\n}\n\n/**\n * Configuration for {@link runPositioning}. Mirrors the shared shape of the\n * two positioners (`injectFloating`, `injectItemAlignedPositioner`) — the\n * reactive `reference` / `open`, the optional `portal` and anti-flash toggle —\n * and defers the positioner-specific compute + apply + reset to\n * {@link computeAndApply}.\n */\nexport interface PositioningConfig {\n /**\n * The anchor. Reactive — should emit `null` until the anchor is available;\n * positioning is skipped while `null` or `open` is `false`.\n */\n readonly reference: Signal<ReferenceElement | null>;\n\n /**\n * Whether the floating element is currently visible. `autoUpdate` is started\n * when this becomes `true` and torn down when it goes back to `false`.\n */\n readonly open: Signal<boolean>;\n\n /**\n * When `true` (default), the floating element is moved to `document.body` on\n * first render and removed on destroy. Set to `false` to keep it in its\n * declared parent (or when the caller already invokes `injectPortal()`).\n */\n readonly portal?: boolean;\n\n /**\n * When the signal returns anything other than `false` (the default when the\n * signal is omitted), the surface is clipped with `clip-path: inset(50%)`\n * until the first position resolves, so a CSS enter animation never flashes\n * at the viewport corner before the async `computePosition` lands.\n */\n readonly clipUntilPositioned?: Signal<boolean>;\n\n /**\n * Invoked once per **open cycle**, immediately after the first\n * `computePosition` of that cycle resolves and its `run.apply` has run —\n * i.e. after the portal move, after the `clip-path` anti-flash baseline is\n * dropped, and after the positioner has written its `data-*` / CSS vars.\n *\n * The semantics are **per-open, not per-run**: a positioner\n * config change while the surface stays open re-runs the effect (a new\n * positioning run), but this hook does **not** fire again — it fires only on\n * the run that first resolves after `open` transitions to `true`. A run that\n * is superseded (config change while open) or torn down (close / destroy)\n * before its `computePosition` resolves is cancelled: its resolution writes\n * nothing and never fires this hook. This matters because consumers use it to\n * seed one-shot state that a re-fire would corrupt — e.g. scrolling an active\n * option into view inside a freshly portaled listbox, which a per-run re-fire\n * would yank back mid-interaction on every side flip.\n */\n readonly onFirstPosition?: () => void;\n\n /**\n * Builds the per-run controller. Called once per open run, synchronously\n * inside the positioning effect, so its reactive reads (side, align,\n * offsets, selected option, …) register as effect dependencies and a change\n * while open re-runs the effect. Receives the floating element and the\n * resolved (non-null) reference.\n */\n readonly computeAndApply: (el: HTMLElement, reference: ReferenceElement) => PositioningRun;\n}\n\n/**\n * Shared scaffold behind the library's two `@floating-ui/dom` positioners —\n * `injectFloating` (the general anchored positioner) and\n * `injectItemAlignedPositioner` (the macOS-style over-trigger positioner for\n * `[forSelectContent]`). Must be called from an injection context, and takes the `ElementRef` it\n * lives on as the floating element.\n *\n * It owns the portal, the positioning effect and `autoUpdate`, and tears all three down\n * symmetrically so a re-open never inherits stale geometry. While closed the effect tracks only\n * `open` and `reference`, so an offset or side change on a closed overlay re-runs nothing. A\n * `computePosition` that loses its reference mid-frame is swallowed, since `autoUpdate` reschedules\n * on the next live frame.\n *\n * Until the first position resolves the surface wears a `clip-path` anti-flash baseline, re-armed\n * whenever a config change restarts an open run so it stays hidden at the retained stale position.\n * `clip-path` rather than `visibility: hidden` keeps the element focusable, so the overlay shell's\n * initial-focus move still lands while the surface is unpainted.\n *\n * Position is written to `translate`, never `transform`. CSS composes `translate` outside\n * `transform`, so a consumer's `scale` enter animation pivots in place instead of scaling the\n * position offset and dragging the surface in from the viewport corner — leaving `transform` free\n * for the consumer is the point.\n *\n * SSR-safe: `effect()` runs server-side, so the browser gate here is explicit.\n */\nexport function runPositioning(config: PositioningConfig): void {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const el = host.nativeElement;\n\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n return;\n }\n\n if (config.portal !== false) {\n injectPortal();\n }\n\n const shouldClip = (): boolean => config.clipUntilPositioned?.() !== false;\n\n afterNextRender(() => {\n Object.assign(el.style, {\n position: 'fixed',\n left: '0',\n top: '0',\n });\n if (shouldClip()) {\n el.style.clipPath = 'inset(50%)';\n }\n });\n\n let openCycleActive = false;\n let firstPositionFired = false;\n\n effect((onCleanup) => {\n const isOpen = config.open();\n const reference = config.reference();\n\n if (!isOpen || !reference) {\n openCycleActive = false;\n return;\n }\n\n if (!openCycleActive) {\n openCycleActive = true;\n firstPositionFired = false;\n }\n\n if (shouldClip()) {\n el.style.clipPath = 'inset(50%)';\n }\n\n const run = config.computeAndApply(el, reference);\n let cancelled = false;\n\n const cleanup = autoUpdate(reference, el, () => {\n computePosition(reference, el, {\n strategy: 'fixed',\n placement: run.placement,\n middleware: run.middleware,\n })\n .then((result) => {\n if (cancelled || !config.open()) {\n return;\n }\n el.style.translate = `${Math.round(result.x)}px ${Math.round(result.y)}px`;\n el.style.clipPath = '';\n run.apply(result);\n if (!firstPositionFired) {\n firstPositionFired = true;\n config.onFirstPosition?.();\n }\n })\n .catch(() => {});\n });\n\n onCleanup(() => {\n cancelled = true;\n cleanup();\n run.reset();\n });\n });\n}\n","import { type Signal } from '@angular/core';\nimport {\n arrow,\n type ComputePositionReturn,\n flip,\n type FlipOptions,\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 type { OverlayShellPositioner } from '../overlay-controller/overlay-shell';\nimport {\n type FloatingCustomProperties,\n injectFloatingCustomProperties,\n} from './floating-custom-properties';\nimport { isFloatingRtl } from './floating-direction';\nimport { runPositioning } from './run-positioning';\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\n/**\n * Direction floating-ui's `flip` middleware falls back to on the *perpendicular*\n * axis when no placement on the preferred axis fits. `'none'` (the default)\n * keeps floating-ui's historical behavior — only the opposite same-axis\n * placement is tried; `'start'` / `'end'` let the surface drop to a\n * perpendicular side (e.g. a right-anchored submenu dropping to `top` / `bottom`)\n * when both sides of the preferred axis overflow.\n */\nexport type FloatingFallbackAxisSideDirection = 'none' | 'start' | '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-floating-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-floating-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 /**\n * Direction floating-ui's `flip` falls back to on the *perpendicular* axis\n * when no placement on the preferred axis fits. `'none'` (default) keeps the\n * historical behavior — only the opposite same-axis placement is tried; set\n * `'start'` / `'end'` to let a side-anchored surface (e.g. a submenu) drop to\n * a perpendicular side when both sides of the preferred axis overflow. Only\n * consulted when `avoidCollisions` is on.\n */\n readonly fallbackAxisSideDirection?: Signal<FloatingFallbackAxisSideDirection>;\n\n /**\n * Explicit ordered list of fallback placements handed to `flip`. Advanced\n * control; overrides floating-ui's axis-side heuristic when provided. Only\n * consulted when `avoidCollisions` is on.\n */\n readonly fallbackPlacements?: Signal<readonly Placement[] | undefined>;\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 * Invoked once per **open cycle**, on the first resolved position after\n * `open` transitions to `true` — after `@floating-ui/dom`'s async\n * `computePosition` lands, the helper drops the `clip-path` anti-flash\n * baseline, and the positioner has written its `data-*` / CSS vars.\n *\n * The semantics are **per-open, not per-run**: a positioner-config change\n * while the surface stays open re-runs the positioning effect, but this\n * callback does **not** re-fire — it fires only on the run that first\n * resolves after opening, and never while the surface stays closed. A run\n * superseded by a config change (or torn down by a close / destroy) before\n * its `computePosition` resolves is cancelled: its resolution writes nothing\n * and never fires this hook.\n *\n * This per-open guarantee is load-bearing for the seed-once consumers.\n * Because the hook runs strictly after the optional portal's `appendChild`\n * and after `computePosition` (so the `size` middleware's `max-height` is\n * already applied), it is the only moment a consumer can touch the\n * now-portaled, now-sized surface. Combobox uses it to scroll the active\n * descendant into view inside a `max-height`-constrained listbox whose\n * `scrollTop` the portal move reset to 0 — see `[forComboboxContent]`; a\n * per-run re-fire would yank that scroll back on every side flip.\n */\n readonly onFirstPosition?: () => void;\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. Under `rtl` the inline axis mirrors, so the same placement pivots\n * from `right top`.\n */\nfunction transformOriginFor(side: FloatingSide, align: FloatingAlign, rtl: boolean): 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 const start = rtl ? 'right' : 'left';\n const end = rtl ? 'left' : 'right';\n x = align === 'start' ? start : align === 'end' ? end : '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 * Assemble the options handed to floating-ui's `flip` middleware. Kept as a\n * pure function so the collision-fallback wiring (`fallbackAxisSideDirection`,\n * `fallbackPlacements`) is unit-testable without a live DOM — jsdom returns\n * zero rects, so `flip` never actually relocates there.\n *\n * `fallbackAxisSideDirection` is omitted (rather than passed as `'none'`) so the\n * emitted options match floating-ui's own default exactly, and\n * `fallbackPlacements` is omitted when empty / unset.\n */\nexport function buildFlipOptions(options: {\n readonly padding: number | Padding;\n readonly boundary: Element | Element[] | null;\n readonly fallbackAxisSideDirection: FloatingFallbackAxisSideDirection;\n readonly fallbackPlacements: readonly Placement[] | undefined;\n}): FlipOptions {\n const flipOptions: FlipOptions = { padding: options.padding };\n if (options.boundary) {\n flipOptions.boundary = options.boundary;\n }\n if (options.fallbackAxisSideDirection !== 'none') {\n flipOptions.fallbackAxisSideDirection = options.fallbackAxisSideDirection;\n }\n if (options.fallbackPlacements?.length) {\n flipOptions.fallbackPlacements = [...options.fallbackPlacements];\n }\n return flipOptions;\n}\n\n/**\n * The `injectOverlayShell` positioner that places the surface beside its anchor through\n * {@link injectFloating}.\n */\nexport function floatingPositioner(config: FloatingConfig): OverlayShellPositioner {\n return {\n reference: config.reference,\n open: config.open,\n attach: () => injectFloating(config),\n };\n}\n\n/**\n * Wires a floating UI element (tooltip, popover, menu...) to its anchor.\n * Must be called from an injection context. Delegates the platform gate,\n * portal, anti-flash baseline, `autoUpdate` loop, and symmetric cleanup to\n * the shared {@link runPositioning} scaffold, and supplies the anchored\n * positioner's own per-run body: the `offset` / `flip` / `shift` / `size` /\n * `hide` / `arrow` middleware stack, plus the writes that follow each resolved\n * position — `data-placement`, `data-side`, `data-align`, `data-occluded`\n * (when the `hide` middleware reports the reference is off-screen),\n * `data-detached` (when `hideWhenDetached` is on and the reference escaped its\n * clipping ancestors), the `--for-floating-anchor-width/-height`,\n * `--for-floating-available-width/-height`, and `--for-floating-content-transform-origin` CSS\n * variables, and the optional arrow's position + `--for-floating-arrow-offset`.\n *\n * Once per open cycle, on the first resolved position after opening, it invokes\n * `onFirstPosition` — after the portal move and after `size` applied its\n * `max-height`, so a consumer can touch the now-portaled, now-sized surface. A\n * config change while open does not re-fire it; see\n * {@link FloatingConfig.onFirstPosition}.\n *\n * Cleanup is asymmetric on purpose: {@link resetFloatingStyles} strips the\n * transient sizing vars and occlusion attributes but retains the resolved\n * `translate` and placement outputs, and the arrow keeps its inline position,\n * `data-side` and `data-placement`, so a closing surface and its arrow stay\n * anchored to the trigger through `animate.leave`; the next mount re-arms the\n * baseline and recomputes everything before painting.\n *\n * Stylistic concerns (which side gets the arrow offset via\n * `--for-floating-arrow-offset`, pointer events, background, animations) stay with the\n * consumer.\n */\nexport function injectFloating(config: FloatingConfig): void {\n const fallbackShiftPadding = config.shiftPadding ?? 8;\n const vars = injectFloatingCustomProperties();\n\n runPositioning({\n reference: config.reference,\n open: config.open,\n portal: config.portal,\n clipUntilPositioned: config.clipUntilPositioned,\n onFirstPosition: config.onFirstPosition,\n computeAndApply: (el, reference) => {\n const arrowEl = config.arrow?.() ?? null;\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 middleware.push(\n flip(\n buildFlipOptions({\n padding: flipPaddingValue,\n boundary: collisionBoundary,\n fallbackAxisSideDirection: config.fallbackAxisSideDirection?.() ?? 'none',\n fallbackPlacements: config.fallbackPlacements?.(),\n }),\n ),\n );\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-floating-available-height)` etc.\n const sizeOptions: Parameters<typeof size>[0] = {\n padding: sizePaddingValue,\n apply({ availableWidth, availableHeight }) {\n el.style.setProperty(vars.availableWidth, `${Math.max(0, Math.round(availableWidth))}px`);\n el.style.setProperty(\n vars.availableHeight,\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 return {\n placement: requestedPlacement,\n middleware,\n apply({ placement: resolvedPlacement, middlewareData }: ComputePositionReturn) {\n const { side: resolvedSide, align: resolvedAlign } = splitPlacement(\n resolvedPlacement as Placement,\n );\n\n el.dataset['placement'] = resolvedPlacement;\n el.dataset['side'] = resolvedSide;\n el.dataset['align'] = resolvedAlign;\n\n // Anchor box → CSS vars so the consumer can size the floating\n // element relative to the anchor (`width: var(--for-floating-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(vars.anchorWidth, `${Math.round(rect.width)}px`);\n el.style.setProperty(vars.anchorHeight, `${Math.round(rect.height)}px`);\n el.style.setProperty(\n vars.contentTransformOrigin,\n transformOriginFor(resolvedSide, resolvedAlign, isFloatingRtl(el)),\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(${vars.arrowOffset}, 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 reset() {\n resetFloatingStyles(el, vars);\n },\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-floating-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. The arrow element is not reset\n * at all: everything a run writes to it is resolved placement, rewritten in\n * full by the next run, so it keeps pointing at the trigger through the exit.\n */\nfunction resetFloatingStyles(el: HTMLElement, vars: FloatingCustomProperties): 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(vars.anchorWidth);\n el.style.removeProperty(vars.anchorHeight);\n el.style.removeProperty(vars.availableWidth);\n el.style.removeProperty(vars.availableHeight);\n el.removeAttribute('data-occluded');\n el.removeAttribute('data-detached');\n}\n","import type { Signal } from '@angular/core';\nimport type { ReferenceElement } from '@floating-ui/dom';\n\nimport type { OverlayShellPositioner } from '../overlay-controller/overlay-shell';\nimport { type FloatingAlign, floatingPositioner, type FloatingSide } from './floating';\n\n/**\n * Single source of truth for the floating-ui positioning defaults shared by\n * every trigger-anchored overlay root. It is read once, by the two bases the\n * roots inherit their positioning block from\n * (`AnchoredOverlayPositioningBase` / `AnchoredFormValueControlBase`), so no\n * root spells a non-seed default itself.\n *\n * Only `side` / `align` / `sideOffset` / `collisionPadding` are seeded from\n * each root's own defaults provider (`provideForPopoverDefaults`,\n * `provideForSelectDefaults`, …) so a scope override flows through — those are\n * the placement values a design system tunes, and they legitimately vary per\n * root. Everything below is identical for every anchored overlay in the\n * library, which is why `arrowPadding` is not among them: only the three roots\n * shipping an arrow piece declare it, each seeded from its own defaults\n * provider.\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 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): OverlayShellPositioner {\n return floatingPositioner({\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 { booleanAttribute, computed, Directive, input, numberAttribute } from '@angular/core';\n\nimport { FormUiControlBase } from 'forty-cdk/core';\nimport { ANCHORED_POSITIONING_DEFAULTS } from './anchored-positioning-inputs';\nimport type {\n AnchoredPositioningOverride,\n AnchoredPositioningSeedDefaults,\n} from './anchored-overlay-positioning-base';\nimport type { FloatingAlign, FloatingSide } from './floating';\n\n/**\n * `AnchoredOverlayPositioningBase` for the anchored roots that are also form\n * values — `[forSelect]`, `[forCombobox]`, `[forTimePicker]`, and both\n * date-picker roots through `DatePickerBase`. They must extend\n * `FormUiControlBase` for the Signal Forms contract, and TypeScript has single\n * inheritance, so the positioning block cannot reach them by extending the\n * other base as the remaining eight roots do.\n *\n * This class is therefore the **second and last** declaration site of that\n * block, and it is a verbatim copy on purpose:\n * `anchored-positioning-inputs.spec.ts` reads both files and fails when the two\n * regions stop matching character-for-character, so a change to one is a change\n * to both. Everything the block means is documented on\n * {@link AnchoredOverlayPositioningBase}; do not restate it here, and do not add\n * a member to one base without adding it to the other.\n */\n@Directive()\nexport abstract class AnchoredFormValueControlBase extends FormUiControlBase {\n /**\n * The four positioning seeds this root resolves from its own scoped defaults\n * provider. Concrete roots implement it with\n * `protected readonly positioningDefaults = inject(FOR_X_DEFAULTS)`, or with\n * a getter over a `computed` when one seed is derived (writing direction).\n */\n protected abstract readonly positioningDefaults: AnchoredPositioningSeedDefaults;\n\n /**\n * Placement override for the current open, resolved ahead of this root's own\n * inputs. `null` (the default) leaves the inputs in charge; the menu roots\n * override it with the active opener's `[menuPositioning]`.\n */\n protected positioningOverride(): AnchoredPositioningOverride | null {\n return null;\n }\n\n /**\n * Per-instance override for the side the overlay is anchored to. Pair with\n * `align` for the full positioning API. When `undefined` (default), falls\n * back to the scope default. Aliased to `side`; consumers bind `[side]=\"...\"`\n * and read the effective value via the public {@link side} computed.\n */\n readonly _sideInput = input<FloatingSide | undefined>(undefined, { alias: 'side' });\n\n /** Effective anchor side: the per-open override, else the `side` input, else the scope default. */\n readonly side = computed<FloatingSide>(\n () => this.positioningOverride()?.side ?? this._sideInput() ?? this.positioningDefaults.side,\n );\n\n /**\n * Per-instance override for the alignment along the chosen `side`. When\n * `undefined` (default), falls back to the scope default. Aliased to `align`;\n * consumers bind `[align]=\"...\"` and read the effective value via the public\n * {@link align} computed.\n */\n readonly _alignInput = input<FloatingAlign | undefined>(undefined, { alias: 'align' });\n\n /** Effective alignment: the per-open override, else the `align` input, else the scope default. */\n readonly align = computed<FloatingAlign>(\n () => this.positioningOverride()?.align ?? this._alignInput() ?? this.positioningDefaults.align,\n );\n\n /**\n * Per-instance override for the gap (px) between trigger and content along\n * the main axis. When `undefined` (default), falls back to the scope default.\n * Aliased to `sideOffset`; consumers bind `[sideOffset]=\"...\"` and read the\n * effective value via the public {@link sideOffset} computed.\n */\n readonly _sideOffsetInput = input(undefined, {\n alias: 'sideOffset',\n transform: (v: unknown): number | undefined => (v == null ? undefined : numberAttribute(v)),\n });\n\n /** Effective main-axis gap (px): the per-open override, else the input, else the scope default. */\n readonly sideOffset = computed<number>(\n () =>\n this.positioningOverride()?.sideOffset ??\n this._sideOffsetInput() ??\n this.positioningDefaults.sideOffset,\n );\n\n /**\n * Per-instance gap (px) along the cross axis (parallel to `side`). Default\n * `0`. Aliased to `alignOffset`; consumers bind `[alignOffset]=\"...\"` and read\n * the effective value via the public {@link alignOffset} computed.\n */\n readonly _alignOffsetInput = input(ANCHORED_POSITIONING_DEFAULTS.alignOffset, {\n alias: 'alignOffset',\n transform: numberAttribute,\n });\n\n /** Effective cross-axis gap (px): the per-open override, else the `alignOffset` input. */\n readonly alignOffset = computed<number>(\n () => this.positioningOverride()?.alignOffset ?? this._alignOffsetInput(),\n );\n\n /**\n * When `true` (default), `flip` and `shift` keep the overlay inside the\n * viewport. Disable for strict positioning where overflow is acceptable.\n */\n readonly avoidCollisions = input(ANCHORED_POSITIONING_DEFAULTS.avoidCollisions, {\n transform: booleanAttribute,\n });\n\n /**\n * Per-instance override for the padding (px) applied uniformly to the `flip`,\n * `shift`, and `size` middlewares. When `undefined` (default), falls back to\n * the scope default. Aliased to `collisionPadding`; consumers bind\n * `[collisionPadding]=\"...\"` and read the effective value via the public\n * {@link collisionPadding} computed.\n */\n readonly _collisionPaddingInput = input(undefined, {\n alias: 'collisionPadding',\n transform: (v: unknown): number | undefined => (v == null ? undefined : numberAttribute(v)),\n });\n\n /** Effective collision padding (px): the `collisionPadding` input when set, else the scope default. */\n readonly collisionPadding = computed<number>(\n () => this._collisionPaddingInput() ?? this.positioningDefaults.collisionPadding,\n );\n\n /**\n * Stickiness behaviour for `shift`. `'partial'` (default) lets the overlay\n * shift to stay visible. `'always'` keeps the requested placement even\n * off-screen.\n */\n readonly sticky = input<'partial' | 'always' | false>(ANCHORED_POSITIONING_DEFAULTS.sticky);\n\n /**\n * When `true`, sets `data-detached=\"\"` while the trigger has scrolled off all\n * clipping ancestors.\n */\n readonly hideWhenDetached = input(ANCHORED_POSITIONING_DEFAULTS.hideWhenDetached, {\n transform: booleanAttribute,\n });\n\n /**\n * When `true` (default), the content is clipped until floating-ui resolves\n * its first position, preventing a flash at the viewport corner. Set to\n * `false` so a dramatic `animate.enter` plays from its first frame (the\n * surface may flash briefly at the unresolved position while positioning\n * computes).\n */\n readonly clipUntilPositioned = input(ANCHORED_POSITIONING_DEFAULTS.clipUntilPositioned, {\n transform: booleanAttribute,\n });\n}\n","import { booleanAttribute, computed, Directive, input, numberAttribute } from '@angular/core';\n\nimport { ANCHORED_POSITIONING_DEFAULTS } from './anchored-positioning-inputs';\nimport type { FloatingAlign, FloatingSide } from './floating';\n\n/**\n * The four positioning seeds a trigger-anchored overlay root resolves from its\n * own scoped defaults provider (`provideForPopoverDefaults`,\n * `provideForSelectDefaults`, …), rather than from the shared\n * {@link ANCHORED_POSITIONING_DEFAULTS} constant. A root's `ForXDefaults`\n * interface `extends` this whenever all four keys are plain values, so the\n * shared seed contract stays typed identically across roots, and every concrete\n * {@link AnchoredOverlayPositioningBase} subclass supplies an instance of it\n * through its `positioningDefaults` accessor.\n *\n * A root whose library fallback for one seed is *derived* rather than fixed —\n * MenuSub's writing-direction `side` — declares that key nullable on its own\n * defaults interface and resolves it inside `positioningDefaults`, so what the\n * base reads is always a settled value.\n */\nexport interface AnchoredPositioningSeedDefaults {\n /** Side the overlay is anchored to when the `side` input is unset. */\n side: FloatingSide;\n /** Alignment along the chosen `side` when the `align` input is unset. */\n align: FloatingAlign;\n /** Gap (px) between trigger and content along the main axis when the `sideOffset` input is unset. */\n sideOffset: number;\n /** Padding (px) applied uniformly to `flip` / `shift` / `size` when the `collisionPadding` input is unset. */\n collisionPadding: number;\n}\n\n/**\n * Per-open override of the four **placement** values, resolved ahead of the\n * root's own inputs. It exists for the menu roots, where one surface is shared\n * by heterogeneous openers and the opener that fired legitimately decides the\n * placement (`MenuOpenerPositioning` is the shape flowing through\n * `[menuPositioning]`); every other root inherits the base's `null` and\n * resolves its inputs directly.\n *\n * Only the four placement values are overridable. The rest of the surface\n * (`avoidCollisions`, `collisionPadding`, `sticky`, …) is collision / viewport\n * policy for the overlay rather than a property of what opened it.\n */\nexport interface AnchoredPositioningOverride {\n /** Side the overlay is anchored to for this open. */\n readonly side?: FloatingSide;\n /** Alignment along the chosen `side` for this open. */\n readonly align?: FloatingAlign;\n /** Gap (px) along the main axis for this open. */\n readonly sideOffset?: number;\n /** Gap (px) along the cross axis for this open. */\n readonly alignOffset?: number;\n}\n\n/**\n * Abstract base for the trigger-anchored overlay roots. It single-sources the\n * nine shared floating-ui positioning inputs and the five effective computeds\n * over them, so the declarations live in one place instead of being copied per\n * root.\n *\n * Each of the four placement values resolves in the same three steps — the\n * per-open {@link positioningOverride}, then the root's own input, then the\n * scope default read through {@link positioningDefaults}. The five non-placement\n * inputs (`avoidCollisions` / `sticky` / `hideWhenDetached` /\n * `clipUntilPositioned`, plus `alignOffset`'s own library fallback) default from\n * the shared {@link ANCHORED_POSITIONING_DEFAULTS} constant.\n *\n * `arrowPadding` is **not** here: floating-ui installs the `arrow` middleware\n * only when an arrow element is supplied, so it belongs to the three roots that\n * ship one — `[forPopover]`, `[forTooltip]`, `[forHoverCard]` — each declaring\n * the input itself, seeded from its own defaults provider.\n *\n * Roots that must also extend `FormUiControlBase` reach the identical block\n * through `AnchoredFormValueControlBase` instead.\n */\n@Directive()\nexport abstract class AnchoredOverlayPositioningBase {\n /**\n * The four positioning seeds this root resolves from its own scoped defaults\n * provider. Concrete roots implement it with\n * `protected readonly positioningDefaults = inject(FOR_X_DEFAULTS)`, or with\n * a getter over a `computed` when one seed is derived (writing direction).\n */\n protected abstract readonly positioningDefaults: AnchoredPositioningSeedDefaults;\n\n /**\n * Placement override for the current open, resolved ahead of this root's own\n * inputs. `null` (the default) leaves the inputs in charge; the menu roots\n * override it with the active opener's `[menuPositioning]`.\n */\n protected positioningOverride(): AnchoredPositioningOverride | null {\n return null;\n }\n\n /**\n * Per-instance override for the side the overlay is anchored to. Pair with\n * `align` for the full positioning API. When `undefined` (default), falls\n * back to the scope default. Aliased to `side`; consumers bind `[side]=\"...\"`\n * and read the effective value via the public {@link side} computed.\n */\n readonly _sideInput = input<FloatingSide | undefined>(undefined, { alias: 'side' });\n\n /** Effective anchor side: the per-open override, else the `side` input, else the scope default. */\n readonly side = computed<FloatingSide>(\n () => this.positioningOverride()?.side ?? this._sideInput() ?? this.positioningDefaults.side,\n );\n\n /**\n * Per-instance override for the alignment along the chosen `side`. When\n * `undefined` (default), falls back to the scope default. Aliased to `align`;\n * consumers bind `[align]=\"...\"` and read the effective value via the public\n * {@link align} computed.\n */\n readonly _alignInput = input<FloatingAlign | undefined>(undefined, { alias: 'align' });\n\n /** Effective alignment: the per-open override, else the `align` input, else the scope default. */\n readonly align = computed<FloatingAlign>(\n () => this.positioningOverride()?.align ?? this._alignInput() ?? this.positioningDefaults.align,\n );\n\n /**\n * Per-instance override for the gap (px) between trigger and content along\n * the main axis. When `undefined` (default), falls back to the scope default.\n * Aliased to `sideOffset`; consumers bind `[sideOffset]=\"...\"` and read the\n * effective value via the public {@link sideOffset} computed.\n */\n readonly _sideOffsetInput = input(undefined, {\n alias: 'sideOffset',\n transform: (v: unknown): number | undefined => (v == null ? undefined : numberAttribute(v)),\n });\n\n /** Effective main-axis gap (px): the per-open override, else the input, else the scope default. */\n readonly sideOffset = computed<number>(\n () =>\n this.positioningOverride()?.sideOffset ??\n this._sideOffsetInput() ??\n this.positioningDefaults.sideOffset,\n );\n\n /**\n * Per-instance gap (px) along the cross axis (parallel to `side`). Default\n * `0`. Aliased to `alignOffset`; consumers bind `[alignOffset]=\"...\"` and read\n * the effective value via the public {@link alignOffset} computed.\n */\n readonly _alignOffsetInput = input(ANCHORED_POSITIONING_DEFAULTS.alignOffset, {\n alias: 'alignOffset',\n transform: numberAttribute,\n });\n\n /** Effective cross-axis gap (px): the per-open override, else the `alignOffset` input. */\n readonly alignOffset = computed<number>(\n () => this.positioningOverride()?.alignOffset ?? this._alignOffsetInput(),\n );\n\n /**\n * When `true` (default), `flip` and `shift` keep the overlay inside the\n * viewport. Disable for strict positioning where overflow is acceptable.\n */\n readonly avoidCollisions = input(ANCHORED_POSITIONING_DEFAULTS.avoidCollisions, {\n transform: booleanAttribute,\n });\n\n /**\n * Per-instance override for the padding (px) applied uniformly to the `flip`,\n * `shift`, and `size` middlewares. When `undefined` (default), falls back to\n * the scope default. Aliased to `collisionPadding`; consumers bind\n * `[collisionPadding]=\"...\"` and read the effective value via the public\n * {@link collisionPadding} computed.\n */\n readonly _collisionPaddingInput = input(undefined, {\n alias: 'collisionPadding',\n transform: (v: unknown): number | undefined => (v == null ? undefined : numberAttribute(v)),\n });\n\n /** Effective collision padding (px): the `collisionPadding` input when set, else the scope default. */\n readonly collisionPadding = computed<number>(\n () => this._collisionPaddingInput() ?? this.positioningDefaults.collisionPadding,\n );\n\n /**\n * Stickiness behaviour for `shift`. `'partial'` (default) lets the overlay\n * shift to stay visible. `'always'` keeps the requested placement even\n * off-screen.\n */\n readonly sticky = input<'partial' | 'always' | false>(ANCHORED_POSITIONING_DEFAULTS.sticky);\n\n /**\n * When `true`, sets `data-detached=\"\"` while the trigger has scrolled off all\n * clipping ancestors.\n */\n readonly hideWhenDetached = input(ANCHORED_POSITIONING_DEFAULTS.hideWhenDetached, {\n transform: booleanAttribute,\n });\n\n /**\n * When `true` (default), the content is clipped until floating-ui resolves\n * its first position, preventing a flash at the viewport corner. Set to\n * `false` so a dramatic `animate.enter` plays from its first frame (the\n * surface may flash briefly at the unresolved position while positioning\n * computes).\n */\n readonly clipUntilPositioned = input(ANCHORED_POSITIONING_DEFAULTS.clipUntilPositioned, {\n transform: booleanAttribute,\n });\n}\n","import { type Signal } from '@angular/core';\nimport {\n type Middleware,\n type Padding,\n type Placement,\n type ReferenceElement,\n} from '@floating-ui/dom';\n\nimport type { OverlayShellPositioner } from '../overlay-controller/overlay-shell';\nimport {\n type FloatingCustomProperties,\n injectFloatingCustomProperties,\n} from './floating-custom-properties';\nimport { isFloatingRtl } from './floating-direction';\nimport { runPositioning } from './run-positioning';\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. Read on each position run, so a selection change while open\n * does not reposition the listbox; it is anchored on the next open or the\n * next `autoUpdate` run.\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 every edge of the listbox and the\n * `--for-floating-available-height` CSS variable.\n */\n readonly collisionPadding?: Signal<number | Padding>;\n\n /**\n * Called once per open cycle, on the first resolved position, after the listbox has been\n * portaled and its CSS vars written. When set it replaces the positioner's own first-position\n * scroll of the anchored option, so the caller decides which option to reveal.\n */\n readonly onFirstPosition?: () => void;\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\ninterface ItemAlignedPadding {\n readonly top: number;\n readonly left: number;\n readonly right: number;\n}\n\nfunction paddingSide(\n padding: number | Padding | undefined,\n side: keyof ItemAlignedPadding,\n fallback: number,\n): number {\n if (padding == null) {\n return fallback;\n }\n if (typeof padding === 'number') {\n return padding;\n }\n return padding[side] ?? 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\nexport interface ItemAlignedGeometry {\n /** Viewport-relative top edge of the anchor. */\n readonly triggerTop: number;\n\n readonly triggerHeight: number;\n\n /** Border-box height of the listbox, excluding any CSS transform. */\n readonly listboxHeight: number;\n\n /**\n * Distance from the listbox's top border edge to the vertical center of the\n * option to anchor over the trigger, or `null` when the listbox holds no\n * anchorable option — the listbox then aligns to the trigger's top edge.\n */\n readonly targetCenter: number | null;\n\n readonly viewportHeight: number;\n\n /** Distance the listbox keeps from the viewport's top and bottom edges. */\n readonly padding: number;\n}\n\n/**\n * Resolves the listbox's vertical offset so the target option's center lines up\n * with the trigger's center, clamped inside the viewport. A listbox taller than\n * the band the padding leaves cannot satisfy both edges and pins to the top.\n */\nexport function resolveItemAlignedY(geometry: ItemAlignedGeometry): number {\n const { triggerTop, triggerHeight, listboxHeight, targetCenter, viewportHeight, padding } =\n geometry;\n const minY = padding;\n const maxY = viewportHeight - listboxHeight - padding;\n\n if (targetCenter == null) {\n return Math.max(minY, Math.min(triggerTop, maxY));\n }\n\n const desiredY = triggerTop + triggerHeight / 2 - targetCenter;\n return maxY > minY ? Math.max(minY, Math.min(desiredY, maxY)) : minY;\n}\n\nexport interface ItemAlignedInlineGeometry {\n readonly triggerLeft: number;\n readonly triggerWidth: number;\n readonly listboxWidth: number;\n readonly viewportWidth: number;\n readonly paddingLeft: number;\n readonly paddingRight: number;\n readonly rtl: boolean;\n}\n\nexport function resolveItemAlignedX(geometry: ItemAlignedInlineGeometry): number {\n const { triggerLeft, triggerWidth, listboxWidth, viewportWidth, paddingLeft, paddingRight, rtl } =\n geometry;\n const minX = paddingLeft;\n const maxX = viewportWidth - listboxWidth - paddingRight;\n\n if (maxX < minX) {\n return rtl ? maxX : minX;\n }\n\n const desiredX = rtl ? triggerLeft + triggerWidth - listboxWidth : triggerLeft;\n return Math.max(minX, Math.min(desiredX, maxX));\n}\n\nfunction offsetTopWithinChain(el: HTMLElement): number {\n const view = el.ownerDocument.defaultView;\n let top = 0;\n let node: HTMLElement | null = el;\n while (node) {\n top += node.offsetTop;\n const parent: Element | null = node.offsetParent;\n node = view && parent instanceof view.HTMLElement ? parent : null;\n }\n return top;\n}\n\n/**\n * Distance from `listbox`'s top border edge to `target`'s vertical center, read\n * from offset geometry so a CSS transform on either element cannot skew it.\n * Offset geometry is integer-rounded, so the result is accurate to about a\n * pixel.\n */\nexport function offsetCenterWithinListbox(target: HTMLElement, listbox: HTMLElement): number {\n return offsetTopWithinChain(target) + target.offsetHeight / 2 - offsetTopWithinChain(listbox);\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*, and the\n * listbox's inline-start edge lines up with the trigger's, mirrored under RTL.\n * Both axes are clamped inside the viewport with `padding`.\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 padding: ItemAlignedPadding,\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 target = selectedOption() ?? findFirstEnabledOption(floating);\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 const y = resolveItemAlignedY({\n triggerTop: triggerRect.top,\n triggerHeight: triggerRect.height,\n listboxHeight: floating.offsetHeight,\n targetCenter: target ? offsetCenterWithinListbox(target, floating) : null,\n viewportHeight,\n padding: padding.top,\n });\n\n const x = resolveItemAlignedX({\n triggerLeft: triggerRect.left,\n triggerWidth: triggerRect.width,\n listboxWidth: floating.offsetWidth,\n viewportWidth: floating.ownerDocument.documentElement.clientWidth,\n paddingLeft: padding.left,\n paddingRight: padding.right,\n rtl: isFloatingRtl(floating),\n });\n\n return { x, y };\n },\n };\n}\n\n/**\n * The `injectOverlayShell` positioner that overlays the surface on its anchor through\n * {@link injectItemAlignedPositioner}.\n */\nexport function itemAlignedPositioner(config: ItemAlignedConfig): OverlayShellPositioner {\n return {\n reference: config.reference,\n open: config.open,\n attach: () => injectItemAlignedPositioner(config),\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 * Delegates the platform gate, portal, anti-flash baseline, `autoUpdate` loop,\n * `translate` write, `clip-path` drop, and symmetric cleanup to the shared\n * {@link runPositioning} scaffold, and supplies its own per-run body: the\n * custom `itemAligned` middleware plus the writes that follow each resolved\n * position — `data-position=\"item-aligned\"`, the `--for-floating-anchor-width/-height`\n * and `--for-floating-available-height` CSS vars — and, on the first resolved position,\n * `scrollIntoView({ block: 'nearest' })` on the target option so the visual\n * anchor stays correct when the listbox is taller than the viewport, unless\n * `onFirstPosition` is supplied, which then owns that reveal.\n *\n * `--for-floating-available-height` is the same *concept* the anchored positioner\n * publishes (the maximum block-size the surface may occupy before it\n * collides), computed for this algorithm: the surface overlays the trigger\n * rather than sitting beside it, so the band is the full viewport minus\n * `collisionPadding` on both edges (`innerHeight - 2 * collisionPadding`)\n * rather than the anchor-relative space floating-ui's `size` middleware\n * reports. A consumer's `max-height: var(--for-floating-available-height)` therefore\n * works unchanged across `position=\"popper\"` and `position=\"item-aligned\"`.\n * `--for-floating-available-width` is **not** published here: item-aligned\n * aligns the listbox's inline-start edge with the trigger's and computes no\n * width budget.\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 vars = injectFloatingCustomProperties();\n runPositioning({\n reference: config.reference,\n open: config.open,\n portal: config.portal,\n onFirstPosition: config.onFirstPosition,\n computeAndApply: (el, reference) => {\n const paddingInput = config.collisionPadding?.();\n const padding: ItemAlignedPadding = {\n top: paddingSide(paddingInput, 'top', 8),\n left: paddingSide(paddingInput, 'left', 8),\n right: paddingSide(paddingInput, 'right', 8),\n };\n const collisionPadding = padding.top;\n\n let initialScrollDone = config.onFirstPosition !== undefined;\n\n return {\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' satisfies Placement,\n middleware: [itemAligned(() => config.selectedOption(), padding)],\n apply() {\n el.dataset['position'] = 'item-aligned';\n\n const triggerRect = reference.getBoundingClientRect();\n el.style.setProperty(vars.anchorWidth, `${Math.round(triggerRect.width)}px`);\n el.style.setProperty(vars.anchorHeight, `${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(vars.availableHeight, `${Math.round(availableHeight)}px`);\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 reset() {\n resetItemAlignedStyles(el, vars);\n },\n };\n },\n });\n}\n\n/**\n * Strip the transient sizing CSS custom properties\n * `injectItemAlignedPositioner` writes to the listbox — including the\n * `clip-path` hide baseline — while **retaining** the resolved `translate` and\n * `data-position=\"item-aligned\"`, so a leave animation scoped to that selector\n * keeps matching through the exit.\n * Mirrors `resetFloatingStyles` in `floating.ts`: the surface is portaled\n * until `getAnimations().finished`, so during an `animate.leave` exit the host\n * keeps `position: fixed; left: 0; top: 0` and the retained `translate` stays\n * anchored over the trigger instead of flashing at the viewport origin. The\n * next mount re-arms the `clip-path` baseline in `afterNextRender` and\n * recomputes the position before painting, so the retained `translate` never\n * produces a stale-position flash.\n */\nfunction resetItemAlignedStyles(el: HTMLElement, vars: FloatingCustomProperties): void {\n el.style.removeProperty('clip-path');\n el.style.removeProperty(vars.anchorWidth);\n el.style.removeProperty(vars.anchorHeight);\n el.style.removeProperty(vars.availableHeight);\n}\n","import { effect, type Signal, untracked, type WritableSignal } from '@angular/core';\n\nimport { isImeComposing } from 'forty-cdk/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 /** Document whose Escape cancels a pending open. */\n document: Document;\n}\n\n/**\n * Hover-intent scheduler handle returned by {@link createHoverIntent}.\n */\nexport interface HoverIntentScheduler {\n /**\n * Schedule the open after the resolved open delay (instant when delay is 0 or skipped);\n * `immediate` bypasses the delay.\n */\n scheduleOpen(immediate?: boolean): void;\n /** Schedule the close after the resolved close delay; `immediate` bypasses the delay. */\n scheduleClose(immediate: boolean): void;\n /**\n * Cancel any pending open / close timer without changing state. An Escape\n * pressed anywhere in the document while an open is pending does the same,\n * unless it belongs to an IME composition.\n */\n cancelPending(): void;\n /** Whether an open or close timer is pending. */\n isPending(): boolean;\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.\n *\n * Internal core tier — exported from `forty-cdk/core-anchored` for the\n * library's own entry points, with no semver guarantee.\n */\nexport function createHoverIntent(options: HoverIntentOptions): HoverIntentScheduler {\n let pendingTimer: ReturnType<typeof setTimeout> | null = null;\n let disarmEscape: (() => void) | null = null;\n\n function releaseEscape(): void {\n if (disarmEscape) {\n disarmEscape();\n disarmEscape = null;\n }\n }\n\n function cancelPending(): void {\n releaseEscape();\n if (pendingTimer !== null) {\n clearTimeout(pendingTimer);\n pendingTimer = null;\n }\n }\n\n function armEscape(): void {\n const doc = options.document;\n const onKeyDown = (event: KeyboardEvent): void => {\n if (event.key === 'Escape' && !isImeComposing(event)) {\n cancelPending();\n }\n };\n doc.addEventListener('keydown', onKeyDown, true);\n disarmEscape = () => doc.removeEventListener('keydown', onKeyDown, true);\n }\n\n function close(): void {\n options.open.set(false);\n options.coordinator.startSkipDelay();\n }\n\n function scheduleOpen(immediate = false): void {\n cancelPending();\n if (options.isDisabled()) {\n return;\n }\n if (options.open()) {\n return;\n }\n const base = immediate || 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 releaseEscape();\n if (options.isDisabled()) {\n return;\n }\n options.open.set(true);\n }, delay);\n armEscape();\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, isPending: () => pendingTimer !== null };\n}\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 * core tier — no semver guarantee.\n */\nexport function forceCloseWhenDisabled(options: ForceCloseWhenDisabledOptions): void {\n // @sanctioned-effect(untracked-read): the `open` read is untracked, so the\n // effect reacts to `disabled` alone and never cycles on the signal it writes.\n effect(() => {\n if (options.disabled() && untracked(options.open)) {\n options.onForceClose();\n options.open.set(false);\n }\n });\n}\n","import { isHoverCapablePointer } from 'forty-cdk/core';\nimport 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/** Options for {@link attachPointerGrace}. */\nexport interface PointerGraceOptions {\n /**\n * Which pointer moves the polygon tracks; a move it rejects is ignored.\n * Defaults to `isHoverCapablePointer` (mouse only), the menu family's hover\n * vocabulary. A caller whose trigger also opens on pen hover passes\n * `isNonTouchPointer`, so the pen that opened the surface can close it.\n */\n readonly tracksPointer?: (event: Pick<PointerEvent, 'pointerType'>) => boolean;\n readonly exitsOutOfRange?: boolean;\n}\n\n/**\n * Attaches a document-level `pointermove` listener that calls {@link onExit}\n * on every tracked move outside {@link polygon}, until the returned cleanup\n * disarms it. With {@link PointerGraceOptions.exitsOutOfRange}, a tracked\n * `pointerout` with no `relatedTarget` (the pointer left the document, or a pen\n * left the digitizer's hover range) is an exit too. The caller arms this on a\n * trigger pointer-leave and disarms it once the pointer reaches the content,\n * the grace window elapses, or the surface is otherwise resolved.\n *\n * Moves {@link PointerGraceOptions.tracksPointer} rejects are ignored: touch\n * opens by tap, never by hover, so a touch move has no safe triangle to leave.\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 aborts the listener's `AbortSignal`. Idempotent —\n * safe to store and call from a `DestroyRef` hook after an earlier disarm.\n */\nexport function attachPointerGrace(\n doc: Document,\n polygon: Polygon,\n onExit: () => void,\n options: PointerGraceOptions = {},\n): () => void {\n const tracksPointer = options.tracksPointer ?? isHoverCapablePointer;\n const onMove = (event: PointerEvent): void => {\n if (!tracksPointer(event)) {\n return;\n }\n if (!isPointInPolygon({ x: event.clientX, y: event.clientY }, polygon)) {\n onExit();\n }\n };\n const controller = new AbortController();\n doc.addEventListener('pointermove', onMove, { signal: controller.signal });\n if (options.exitsOutOfRange) {\n const onOut = (event: PointerEvent): void => {\n if (tracksPointer(event) && event.relatedTarget === null) {\n onExit();\n }\n };\n doc.addEventListener('pointerout', onOut, { signal: controller.signal });\n }\n return () => controller.abort();\n}\n","import { isNonTouchPointer } from 'forty-cdk/core';\n\nimport type { FloatingSide } from '../floating/floating';\nimport {\n attachPointerGrace,\n buildSubmenuGracePolygon,\n type Point,\n resolveGraceSide,\n} from '../pointer-grace/pointer-grace';\n\n/**\n * Inputs for {@link createHoverSurfaceState}.\n */\nexport interface HoverSurfaceOptions {\n /**\n * The registered trigger: measured to orient the grace polygon, and the only\n * element whose hover and focus keep the surface alive.\n */\n readonly trigger: () => HTMLElement | null;\n /** The registered content the grace polygon bridges toward. */\n readonly content: () => HTMLElement | null;\n /** Side the grace polygon assumes when no trigger is registered to measure. */\n readonly side: () => FloatingSide;\n /**\n * Whether a surface opened from inside the content is still open above it,\n * which keeps the surface alive like hover and focus do.\n */\n readonly nested: () => boolean;\n /** Closes the surface once no keep-alive source is active. */\n readonly close: () => void;\n}\n\n/**\n * Keep-alive bookkeeping of a hover-scheduled overlay, returned by\n * {@link createHoverSurfaceState}.\n */\nexport interface HoverSurfaceState {\n /** Whether the trigger holds focus. */\n triggerFocused(): boolean;\n /** Whether the trigger or the content holds focus. */\n focused(): boolean;\n /** The pointer entered the trigger: marks it hovered and disarms the grace. */\n enterTrigger(): void;\n /** The pointer left the trigger: clears its hover, leaving the close to the caller. */\n leaveTrigger(): void;\n /** The trigger received focus. */\n focusTrigger(): void;\n /** The trigger lost focus: closes when nothing else keeps the surface alive. */\n blurTrigger(): void;\n /** The pointer entered the content: marks it hovered and disarms the grace. */\n enterContent(): void;\n /** The pointer left the content: closes when nothing else keeps the surface alive. */\n leaveContent(): void;\n /** Focus entered the content. */\n focusContent(): void;\n /** Focus left the content: closes when nothing else keeps the surface alive. */\n blurContent(): void;\n /** The content unmounted: clears its hover and focus and disarms the grace. */\n resetContent(): void;\n /**\n * The trigger on `el` unmounted: forgets its hover and focus, so the state\n * keeps no reference to the element.\n */\n releaseTrigger(el: HTMLElement): void;\n /**\n * A surface opened from inside the content closed: once the current task\n * settles (a return of focus into the content included), closes when nothing\n * else keeps the surface alive.\n */\n nestedSurfaceClosed(): void;\n /**\n * Closes unless the trigger or the content is hovered or focused, or a\n * surface opened from inside the content is still open.\n */\n closeIfInactive(): void;\n /**\n * Arms a pointer-grace polygon from `cursor` toward the content, so the\n * pointer can cross the gap without closing. Leaving it disarms the grace and\n * closes when nothing else keeps the surface alive. Without registered\n * content it closes the same way at once.\n */\n armGrace(cursor: Point): void;\n /** Detaches an armed grace polygon. Safe when none is armed. */\n disarmGrace(): void;\n}\n\n/**\n * Shared keep-alive state for Tooltip and Hover-card: which side of the\n * overlay is hovered or focused, and the pointer-grace bridge between them.\n * An element removed under the pointer never reports `pointerleave` or `blur`,\n * so the trigger's hover and focus count only while the element they were\n * observed on is still the registered trigger, `releaseTrigger` forgets that\n * element when it unmounts, and `resetContent` clears the content side when\n * its element unmounts.\n *\n * Internal core tier — exported from `forty-cdk/core-anchored` for the\n * library's own entry points, with no semver guarantee.\n */\nexport function createHoverSurfaceState(options: HoverSurfaceOptions): HoverSurfaceState {\n let hoveredTrigger: HTMLElement | null = null;\n let focusedTrigger: HTMLElement | null = null;\n let contentHovered = false;\n let contentFocused = false;\n let detachGrace: (() => void) | null = null;\n\n const isTrigger = (el: HTMLElement | null): boolean => el !== null && el === options.trigger();\n const triggerHovered = (): boolean => isTrigger(hoveredTrigger);\n const triggerFocused = (): boolean => isTrigger(focusedTrigger);\n\n function disarmGrace(): void {\n if (detachGrace) {\n detachGrace();\n detachGrace = null;\n }\n }\n\n function closeIfInactive(): void {\n if (\n triggerHovered() ||\n triggerFocused() ||\n contentHovered ||\n contentFocused ||\n options.nested()\n ) {\n return;\n }\n options.close();\n }\n\n function armGrace(cursor: Point): void {\n const content = options.content();\n if (!content) {\n closeIfInactive();\n return;\n }\n const rect = content.getBoundingClientRect();\n const trigger = options.trigger();\n const side = trigger ? resolveGraceSide(trigger.getBoundingClientRect(), rect) : options.side();\n const polygon = buildSubmenuGracePolygon(cursor, rect, side);\n disarmGrace();\n detachGrace = attachPointerGrace(\n content.ownerDocument,\n polygon,\n () => {\n disarmGrace();\n closeIfInactive();\n },\n { tracksPointer: isNonTouchPointer, exitsOutOfRange: true },\n );\n }\n\n return {\n triggerFocused,\n focused: () => triggerFocused() || contentFocused,\n enterTrigger: () => {\n hoveredTrigger = options.trigger();\n disarmGrace();\n },\n leaveTrigger: () => {\n hoveredTrigger = null;\n },\n focusTrigger: () => {\n focusedTrigger = options.trigger();\n },\n blurTrigger: () => {\n focusedTrigger = null;\n closeIfInactive();\n },\n enterContent: () => {\n contentHovered = true;\n disarmGrace();\n },\n leaveContent: () => {\n contentHovered = false;\n closeIfInactive();\n },\n focusContent: () => {\n contentFocused = true;\n },\n blurContent: () => {\n contentFocused = false;\n closeIfInactive();\n },\n resetContent: () => {\n contentHovered = false;\n contentFocused = false;\n disarmGrace();\n },\n releaseTrigger: (el) => {\n if (hoveredTrigger === el) {\n hoveredTrigger = null;\n }\n if (focusedTrigger === el) {\n focusedTrigger = null;\n }\n },\n nestedSurfaceClosed: () => {\n queueMicrotask(closeIfInactive);\n },\n closeIfInactive,\n armGrace,\n disarmGrace,\n };\n}\n","import {\n computed,\n inject,\n linkedSignal,\n type Signal,\n signal,\n type WritableSignal,\n} from '@angular/core';\nimport type { ReferenceElement } from '@floating-ui/dom';\n\nimport {\n adoptHostId,\n createSingleSlot,\n IdGenerator,\n type RootedHandle,\n type SingleSlot,\n type SingleSlotConfig,\n} from 'forty-cdk/core';\n\n/**\n * A registered overlay element whose aria-wiring id the surface exposes. Backs\n * the content / list / input slots the overlay controllers used to each\n * hand-copy: the register step adopts a consumer-set static `id` into the\n * seeded id signal (so external `aria-labelledby` / label `for` references keep\n * resolving), the unregister step clears the element only when the same node\n * deregisters.\n *\n * Construct through {@link injectIdentifiedSlot} so the id signal is seeded from\n * the shared {@link IdGenerator} at the controller's construction.\n *\n * @typeParam E Concrete element type registered here (e.g. `HTMLInputElement`\n * for the combobox input). Defaults to `HTMLElement`.\n */\nexport class IdentifiedElementSlot<E extends HTMLElement = HTMLElement> {\n readonly #el = signal<E | null>(null);\n readonly #id: WritableSignal<string>;\n\n /** The registered element, or `null` while nothing is mounted. */\n readonly element: Signal<E | null> = this.#el.asReadonly();\n\n /** The element's aria-wiring id — the generated fallback until a static id is adopted. */\n readonly id: WritableSignal<string>;\n\n constructor(id: WritableSignal<string>) {\n this.#id = id;\n this.id = id;\n }\n\n /** Register the element, adopting a consumer-set static `id` into the id signal. */\n register(el: E): void {\n adoptHostId(el, this.#id);\n this.#el.set(el);\n }\n\n /** Deregister the element (no-op unless the same node registered). */\n unregister(el: E): void {\n if (this.#el() === el) {\n this.#el.set(null);\n }\n }\n}\n\n/**\n * A trigger registered with its root. `id` is the id the trigger carries on its own host, minted\n * per trigger; a trigger the surface never names in its ARIA wiring (a hover card's) has none.\n */\nexport interface RootedTriggerHandle<R extends object = object> extends RootedHandle<R> {\n readonly host: HTMLElement;\n readonly id?: Signal<string>;\n}\n\n/**\n * The triggers registered with one root, and which of them the surface belongs to.\n *\n * Every registered trigger toggles the surface, so {@link hosts} lists them all for the\n * surface's outside-press and outside-focus exemption. One of them is **active**: the\n * surface is positioned against it, labelled by it and returns focus to it. A trigger\n * claims that role through {@link activate} from the interaction that opens or toggles the\n * surface; with no claim, or once the claiming trigger unmounts, the newest registered\n * trigger is active.\n */\nexport class RootedTriggerSlot {\n readonly #claimed: WritableSignal<HTMLElement | null>;\n readonly #active: Signal<RootedTriggerHandle | null>;\n\n /** Every registered trigger's host, in registration order. */\n readonly hosts: Signal<readonly HTMLElement[]>;\n\n /** The active trigger's host, or `null` while no trigger is registered. */\n readonly element: Signal<HTMLElement | null>;\n\n /** The active trigger's id, or `''` while no trigger carrying one is registered. */\n readonly id: Signal<string>;\n\n constructor(triggers: Signal<readonly RootedTriggerHandle[]>) {\n // Holds the claiming host until it leaves the registered set, then drops it.\n this.#claimed = linkedSignal<readonly RootedTriggerHandle[], HTMLElement | null>({\n source: triggers,\n computation: (list, previous) => {\n const claimed = previous?.value ?? null;\n return claimed !== null && list.some((handle) => handle.host === claimed) ? claimed : null;\n },\n });\n this.#active = computed(() => {\n const list = triggers();\n const claimed = this.#claimed();\n return list.find((handle) => handle.host === claimed) ?? list.at(-1) ?? null;\n });\n this.hosts = computed(() => triggers().map((handle) => handle.host));\n this.element = computed(() => this.#active()?.host ?? null);\n this.id = computed(() => this.#active()?.id?.() ?? '');\n }\n\n /** Make the trigger on `host` the active one. Called by a trigger as it opens or toggles. */\n activate(host: HTMLElement): void {\n this.#claimed.set(host);\n }\n}\n\n/**\n * The floating-ui anchor slot shared by the listbox overlays, combobox and the\n * date pickers. An explicit `[for…Anchor]` registers here; the resolved\n * anchor prefers it and otherwise walks the fallback chain (field anchor,\n * trigger, input) so a primitive without an explicit anchor keeps its\n * behaviour.\n *\n * Registrations are stacked like a core `createSingleSlot`: the newest\n * anchor is the one used, unregistering it restores the previous survivor,\n * and a second anchor still registered once the change-detection pass\n * settles warns in dev mode. A structural swap that mounts the replacement\n * anchor before destroying the outgoing one is therefore not reported.\n */\nexport class AnchorSlot {\n readonly #slot: SingleSlot<HTMLElement>;\n\n /** The explicitly-registered anchor element, or `null`. */\n readonly element: Signal<HTMLElement | null>;\n\n constructor(config: SingleSlotConfig) {\n this.#slot = createSingleSlot<HTMLElement>(config);\n this.element = this.#slot.value;\n }\n\n /**\n * Register the explicit anchor, making it the one the overlay positions\n * against. Registering the current anchor again is a no-op.\n */\n register(el: HTMLElement): void {\n if (this.element() === el) {\n return;\n }\n this.#slot.register(el);\n }\n\n /** Deregister the anchor (no-op unless the same node registered). */\n unregister(el: HTMLElement): void {\n this.#slot.unregister(el);\n }\n\n /**\n * Build the resolved-anchor signal: the explicit anchor, otherwise the first\n * non-null fallback in order (field anchor → trigger → input). Decoupled from\n * those elements so they keep driving their own aria-wiring / keyboard\n * interaction regardless of where the surface paints.\n */\n resolve(...fallbacks: Signal<HTMLElement | null>[]): Signal<ReferenceElement | null> {\n return computed<ReferenceElement | null>(() => {\n const explicit = this.element();\n if (explicit !== null) {\n return explicit;\n }\n for (const fallback of fallbacks) {\n const el = fallback();\n if (el !== null) {\n return el;\n }\n }\n return null;\n });\n }\n}\n\n/**\n * A writable `<idPrefix>-<suffix>` id signal off the shared {@link IdGenerator},\n * for a controller that owns the element side itself — the menu overlay's opener\n * registry keeps one seed id across many openers, so it needs the id without a\n * slot's single-element storage.\n *\n * Call it from an injection context — a directive's field initializer, or a\n * controller constructed from one — so the generator resolves and slot id\n * sequences stay deterministic across renders (hydration relies on it).\n */\nexport function injectSlotId(idPrefix: string, suffix: string): WritableSignal<string> {\n return signal(inject(IdGenerator).next(`${idPrefix}-${suffix}`));\n}\n\n/**\n * A slot whose element registration adopts a consumer-set static `id`. Seeds the\n * id signal with `<idPrefix>-<suffix>` off the shared {@link IdGenerator}, so it\n * carries the same injection-context requirement as {@link injectSlotId}.\n *\n * @typeParam E Concrete element type the slot registers. Defaults to\n * `HTMLElement`.\n */\nexport function injectIdentifiedSlot<E extends HTMLElement = HTMLElement>(\n idPrefix: string,\n suffix: string,\n): IdentifiedElementSlot<E> {\n return new IdentifiedElementSlot<E>(injectSlotId(idPrefix, suffix));\n}\n\n/**\n * The floating-ui anchor slot with the settled single-anchor warning + fallback\n * chain. Must be called in an injection context, which a directive field\n * initializer is, because the dev-mode duplicate warning runs on an `effect`.\n *\n * @param config Names the root and its anchor piece in the duplicate warning.\n */\nexport function anchorSlot(config: SingleSlotConfig): AnchorSlot {\n return new AnchorSlot(config);\n}\n","import { linkedSignal, type Signal, untracked, type WritableSignal } from '@angular/core';\n\n/**\n * Records the reason of an overlay's most recent close, and clears it whenever the overlay's open\n * source turns `true`, whoever wrote it: an owner's own open path, an APG key, or a consumer's\n * `[(open)]` binding. The shared content pieces read it to skip their return-focus on a `'tab'`\n * close (so Tab advances focus out of the surface instead of snapping back to the trigger).\n *\n * `close` records the reason before running the close, so a synchronous `openChange` handler\n * already reads it, and settles it against the closed state before returning. A later read that\n * finds the source changed but closed again therefore knows an open happened in between, even one\n * nothing read during.\n *\n * Generic over the reason union so every overlay controller shares one implementation —\n * `OverlayController` (and through it `MenuOverlay`, the listbox overlays, combobox and\n * `[forMenubar]`'s multiplexed menu context) and `[forPopover]` compose it, and\n * `injectOverlayShell` records the closes it requests itself in one, so its return-focus skip\n * lasts one open. Plain class (no `inject()`) so each composes it instead of hand-copying the\n * signal.\n *\n * @typeParam Reason Close-reason union owned by the controller.\n */\nexport class CloseReasonState<Reason> {\n readonly #reason: WritableSignal<Reason | null>;\n\n /**\n * Reason of the most recent close, or `null` while the overlay is open / has never closed.\n */\n readonly reason: Signal<Reason | null>;\n\n constructor(isOpen: () => boolean) {\n this.#reason = linkedSignal<boolean, Reason | null>({\n source: isOpen,\n computation: (open, previous) => (open || !previous?.source ? null : previous.value),\n });\n this.reason = this.#reason.asReadonly();\n }\n\n close(reason: Reason, apply: () => void): void {\n this.#reason.set(reason);\n apply();\n untracked(this.#reason);\n }\n}\n","import { type Signal, signal } from '@angular/core';\n\n/**\n * Tracks where an overlay's initial focus should land on the next open and\n * whether that one programmatic move should reflect `data-highlighted` on the\n * focused item.\n *\n * `target` is set by triggers before they flip the overlay open (ArrowDown →\n * `'first'`, ArrowUp → `'last'`, or a primitive-specific `'selected'`).\n * `highlightOnNextFocus` is armed per open via {@link prepareOpen}: a keyboard\n * activation highlights the focused item per the APG menu-button pattern; a\n * pointer activation (click, hover-after-open) suppresses the highlight so a\n * mouse-opened surface doesn't read as \"preselected\". {@link consumeHighlight}\n * reads the flag once and re-arms it to `true`, so the suppression applies only\n * to the single initial-focus move that follows an open.\n *\n * Generic over the focus-target union so every overlay controller reuses the\n * same one-shot protocol: `MenuOverlay` / `[forMenubar]`'s multiplexed menu\n * context keep `'first' | 'last'` (the default), while the listbox overlays and\n * combobox widen it with `'selected'`. Plain class (no `inject()`) so each\n * controller composes the same implementation instead of hand-copying it.\n *\n * @typeParam Focus Initial-focus target union. Defaults to `'first' | 'last'`.\n */\nexport class InitialFocusState<Focus = 'first' | 'last'> {\n readonly #target: ReturnType<typeof signal<Focus>>;\n #highlightOnNextFocus = true;\n\n /** Where focus should land when the overlay mounts. */\n readonly target: Signal<Focus>;\n\n /**\n * @param defaultTarget Initial focus target before any open. Defaults to\n * `'first'`, valid for the default `'first' | 'last'` union.\n */\n constructor(defaultTarget: Focus = 'first' as Focus) {\n this.#target = signal<Focus>(defaultTarget);\n this.target = this.#target.asReadonly();\n }\n\n setTarget(target: Focus): 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: Focus, 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","import {\n effect,\n type OutputEmitterRef,\n type Signal,\n untracked,\n type WritableSignal,\n} from '@angular/core';\n\nimport {\n emitVetoableNativeEvent,\n injectVetoableEmitter,\n type VetoableEvent,\n type VetoableNativeEvent,\n type TouchDismissal,\n} from 'forty-cdk/core';\nimport { CloseReasonState } from './close-reason-state';\nimport { IdentifiedElementSlot, injectSlotId } from './element-registry';\nimport { InitialFocusState } from './initial-focus-state';\n\n/**\n * The dismiss / auto-focus outputs an overlay controller forwards to. Each\n * primitive 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 OverlayEmitTargets {\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 * One of the two element sides a surface has — the trigger focus returns to, and\n * the content that mounts. Both are supplied by the composing controller,\n * because neither is the same object twice in the library: a listbox overlay's\n * trigger is the active one of those registered with its root, a menu overlay's is a\n * registry of openers resolving one active element and its id, and\n * `[forMenubar]`'s multiplexed context resolves both sides off whichever bar\n * trigger is — or was last — active.\n */\nexport interface OverlaySide {\n /**\n * The element's aria-wiring id. Non-empty for a slot minting its own; the\n * menubar's multiplexed sources resolve `''` until a trigger has been active,\n * which `[forMenuContent]` emits as no attribute rather than as `id=\"\"`.\n */\n readonly id: Signal<string>;\n /** The registered element, or `null` while none is registered. */\n readonly element: Signal<HTMLElement | null>;\n}\n\nexport interface OverlaySlot extends OverlaySide {\n /** Register the element. */\n register(el: HTMLElement): void;\n /** Deregister the element. */\n unregister(el: HTMLElement): void;\n}\n\n/**\n * Per-transition options forwarded verbatim to the `onOpen` / `onClose` hooks so\n * a host directive can react to *how* a transition was driven without\n * re-deriving it from outside the pipeline.\n */\nexport interface OverlayTransitionOptions {\n /**\n * When `true`, the transition is pointer-driven (hover) and the surface's\n * imperative focus move must be suppressed — an open must not pull focus into\n * the surface, and a close must not return focus to the trigger. Defaults to\n * `false`, so keyboard / click / programmatic transitions move focus as usual.\n */\n readonly suppressFocusMoves?: boolean;\n}\n\n/** Per-call options for {@link OverlayController.open}. */\nexport interface OverlayOpenOptions {\n /**\n * Arms the initial-focus state's one-shot highlight flag for this open —\n * `true` for a keyboard activation, `false` for a pointer one. Omit it\n * entirely on a surface that does not reflect `data-highlighted` on its\n * initial focus, so the flag is left untouched.\n */\n readonly highlight?: boolean;\n /** Transition options handed verbatim to the `onOpen` hook. */\n readonly transition?: OverlayTransitionOptions;\n}\n\n/**\n * What {@link OverlayController.open} did, so a composing controller can run its\n * own tail without re-reading the open model (which the call may just have\n * written).\n *\n * - `'blocked'` — the control is disabled; nothing happened.\n * - `'opened'` — the surface transitioned from closed to open.\n * - `'already-open'` — the surface was already mounted, so no state transition\n * (and therefore no `openChange` emit) happened. The initial-focus target and\n * the close reason were still re-armed.\n */\nexport type OverlayOpenOutcome = 'blocked' | 'opened' | 'already-open';\n\n/**\n * Construction-time wiring for {@link OverlayController}. Plain signals and\n * callbacks only — the controller never imports a primitive's context token,\n * mirroring `injectOverlayShell`, so it stays orthogonal to each root's surface.\n *\n * @typeParam Focus Initial-focus union owned by the composing controller.\n * @typeParam CloseReason Close-reason union owned by the composing controller.\n */\nexport interface OverlayControllerDeps<Focus, CloseReason> {\n /** Id-generator prefix base, e.g. `'for-select'` (suffixed with `-trigger` / `-content`). */\n readonly idPrefix: string;\n /**\n * Builds the trigger side, from a factory minting the seeded\n * `<idPrefix>-trigger` id. Call the factory exactly once for a trigger that\n * owns an id, and **not at all** for one whose id lives elsewhere — the\n * combobox's lives on its input, the menubar's on each bar trigger — because\n * the `IdGenerator` counter is per application, so an id nothing ever emits\n * still shifts every id minted after it.\n *\n * Runs during construction, ahead of {@link createContent}, so the\n * trigger-then-content minting order is fixed here rather than per caller —\n * hydration's id adoption depends on both renders repeating it. It may\n * `inject()`, and so may the factory.\n */\n readonly createTrigger: (mintId: () => WritableSignal<string>) => OverlaySide;\n /**\n * Builds the content side, same contract as {@link createTrigger} and called\n * immediately after it. Optional: omitted, the controller registers its own\n * {@link IdentifiedElementSlot} over the minted `<idPrefix>-content` id, which\n * is what every surface owning its content id wants. Supply it when the id\n * comes from somewhere else, or when registration does more than adopt a\n * static id — `[forMenubar]` resolves the id off the active trigger and\n * records whether the surface is shared across the bar's triggers.\n */\n readonly createContent?: (mintId: () => WritableSignal<string>) => OverlaySlot;\n /** Default initial-focus target before any open. */\n readonly defaultInitialFocus: Focus;\n /** The control's effective disabled — gates `open` and `toggle`. */\n readonly disabled: Signal<boolean>;\n /** Whether Escape / outside interactions dismiss the surface. */\n readonly dismissible: Signal<boolean>;\n /** Read the control's current open state. */\n readonly isOpen: () => boolean;\n /** Write the control's open state — the open / close machine's only channel. */\n readonly setOpen: (open: boolean) => void;\n /** Dismiss / auto-focus outputs to forward to. */\n readonly emit: OverlayEmitTargets;\n /** Close reason recorded when Escape dismisses the surface. */\n readonly escapeReason: CloseReason;\n /** Close reason recorded when {@link OverlayController.toggle} closes the surface. */\n readonly programmaticReason: CloseReason;\n /**\n * Side effect run after {@link OverlayController.open} resolves an un-blocked\n * open, receiving the resolved initial-focus target and the transition\n * options. Runs on the `'already-open'` outcome too, so a pending hover-close\n * is still cancelled by an open key pressed on a mounted surface.\n */\n readonly onOpen?: (initialFocus: Focus, options: OverlayTransitionOptions) => void;\n /**\n * Side effect run after {@link OverlayController.close} flips the open state\n * to `false`, receiving the close reason and the transition options. Also\n * runs, with the programmatic reason, when the open state turns `false`\n * through any other channel, such as a consumer's `[(open)]` write.\n */\n readonly onClose?: (reason: CloseReason, options: OverlayTransitionOptions) => void;\n /**\n * Side effect run on a user-driven dismissal — an un-vetoed Escape, or the\n * shell's implicit close after an un-vetoed outside interaction — just before\n * the close, receiving the channel that requested it. Optional: only a form\n * control has touched state to mark, so the menu overlays pass nothing.\n */\n readonly onDismiss?: (dismissal: TouchDismissal) => void;\n}\n\n/**\n * The open / close / dismiss machine every trigger-anchored overlay surface\n * runs, composed by `MenuOverlay` (the four menu roots), by\n * `ListboxOverlayController` (`[forSelect]` / `[forTimePicker]`), and by\n * `[forCombobox]` and `[forMenubar]`. It owns the initial-focus and close-reason\n * state, the `disabled`-gated open / close / toggle transitions, the four\n * outside / Escape emit forwarders, the shell's implicit `requestClose`, and the\n * two auto-focus veto pass-throughs — plus the order in which the two supplied\n * element sides mint their ids.\n *\n * It does not own the item **collection**: the menu side composes `MenuItemList`\n * separately, and the two navigate tails differ — the menu suppresses the item\n * highlight and scrolls the surface's own overflow, the listbox runs a\n * per-primitive `onNavigateFocus` and gates the move on `disabled`.\n *\n * Construct it from a directive's field initializer, or from a controller\n * constructed there: it reads that directive's `DestroyRef` for the auto-focus\n * vetoes, and the slot factories' `inject()` calls resolve through the same\n * injector.\n *\n * @typeParam Focus Initial-focus union owned by the composing controller.\n * @typeParam CloseReason Close-reason union owned by the composing controller.\n */\nexport class OverlayController<Focus, CloseReason> {\n readonly #deps: OverlayControllerDeps<Focus, CloseReason>;\n\n readonly #triggerSlot: OverlaySide;\n readonly #contentSlot: OverlaySlot;\n\n readonly #initialFocusState: InitialFocusState<Focus>;\n readonly #closeReasonState: CloseReasonState<CloseReason>;\n\n readonly #autoFocusOnOpen: () => boolean;\n readonly #autoFocusOnClose: () => boolean;\n\n /** Set by {@link close} so the open-state observer skips the edge it already handled. */\n #closedHere = false;\n\n /** The trigger's stable id, adopted from a consumer-set static id when present. */\n readonly triggerId: Signal<string>;\n\n /** The content surface's stable id, adopted from a consumer-set static id when present. */\n readonly contentId: Signal<string>;\n\n /** The focusable element the surface returns focus to on close. */\n readonly trigger: Signal<HTMLElement | null>;\n\n /** The mounted content element, or `null` while the surface is closed. */\n readonly content: Signal<HTMLElement | null>;\n\n /** Where focus should land when the surface mounts. Set by triggers before flipping open. */\n readonly initialFocus: Signal<Focus>;\n\n /**\n * Reason of the most recent close, or `null` while the surface is open / has\n * never closed. Reset to `null` on every open — the content pieces read it to\n * skip their return-focus on a `'tab'` close.\n */\n readonly lastCloseReason: Signal<CloseReason | null>;\n\n constructor(deps: OverlayControllerDeps<Focus, CloseReason>) {\n this.#deps = deps;\n const mintContentId = () => injectSlotId(deps.idPrefix, 'content');\n this.#triggerSlot = deps.createTrigger(() => injectSlotId(deps.idPrefix, 'trigger'));\n this.#contentSlot = deps.createContent\n ? deps.createContent(mintContentId)\n : new IdentifiedElementSlot(mintContentId());\n this.#initialFocusState = new InitialFocusState<Focus>(deps.defaultInitialFocus);\n this.#closeReasonState = new CloseReasonState<CloseReason>(deps.isOpen);\n this.#autoFocusOnOpen = injectVetoableEmitter(deps.emit.autoFocusOnOpen);\n this.#autoFocusOnClose = injectVetoableEmitter(deps.emit.autoFocusOnClose);\n this.triggerId = this.#triggerSlot.id;\n this.contentId = this.#contentSlot.id;\n this.trigger = this.#triggerSlot.element;\n this.content = this.#contentSlot.element;\n this.initialFocus = this.#initialFocusState.target;\n this.lastCloseReason = this.#closeReasonState.reason;\n\n let wasOpen = untracked(deps.isOpen);\n // @sanctioned-effect(untracked-read): only `isOpen` is tracked, and the close\n // it runs leaves that state where the other channel already put it.\n effect(() => {\n const open = deps.isOpen();\n untracked(() => {\n const closedElsewhere = wasOpen && !open && !this.#closedHere;\n wasOpen = open;\n this.#closedHere = false;\n if (closedElsewhere) {\n this.close(deps.programmaticReason);\n }\n });\n });\n }\n\n /** Set the initial-focus target ahead of the next open. */\n setInitialFocus(target: Focus): void {\n this.#initialFocusState.setTarget(target);\n }\n\n /**\n * Reads the initial-focus state's one-shot highlight flag and re-arms it, so\n * the composing controller's initial-focus move can suppress the focused\n * item's `data-highlighted` for a pointer-driven open only.\n */\n consumeInitialHighlight(): boolean {\n return this.#initialFocusState.consumeHighlight();\n }\n\n /** Register the mounted content element. */\n registerContent(el: HTMLElement): void {\n this.#contentSlot.register(el);\n }\n\n /** Deregister the content element (no-op unless the same node registered). */\n unregisterContent(el: HTMLElement): void {\n this.#contentSlot.unregister(el);\n }\n\n /**\n * Opens the surface when closed, closes it with the deps' programmatic reason\n * when open. Honours `disabled` on both branches — there is no distinct\n * `'trigger'` close reason for the user-initiated toggle-close path.\n */\n toggle(initialFocus: Focus, options: OverlayOpenOptions = {}): void {\n if (this.#deps.disabled()) {\n return;\n }\n if (this.#deps.isOpen()) {\n this.close(this.#deps.programmaticReason);\n } else {\n this.open(initialFocus, options);\n }\n }\n\n /**\n * Records where the initial focus should land and flips the open state,\n * which clears the close reason. Returns the {@link OverlayOpenOutcome} so a composing\n * controller can branch on an already-open surface — no state transition\n * happened there, so nothing emitted `openChange`, and a re-focus is the only\n * way an APG open key stays live on a mounted surface.\n */\n open(initialFocus: Focus, options: OverlayOpenOptions = {}): OverlayOpenOutcome {\n if (this.#deps.disabled()) {\n return 'blocked';\n }\n const alreadyOpen = this.#deps.isOpen();\n if (options.highlight === undefined) {\n this.#initialFocusState.setTarget(initialFocus);\n } else {\n this.#initialFocusState.prepareOpen(initialFocus, options.highlight);\n }\n if (!alreadyOpen) {\n this.#deps.setOpen(true);\n }\n this.#deps.onOpen?.(initialFocus, options.transition ?? {});\n return alreadyOpen ? 'already-open' : 'opened';\n }\n\n /**\n * Closes the surface, recording `reason` as the {@link lastCloseReason} the\n * content pieces read. Never gated on `disabled`: a control disabled while its\n * surface is open must still be closable.\n */\n close(reason: CloseReason, transition: OverlayTransitionOptions = {}): void {\n this.#closedHere = true;\n this.#closeReasonState.close(reason, () => this.#deps.setOpen(false));\n this.#deps.onClose?.(reason, transition);\n }\n\n /**\n * Escape on the anchored path: emit `(escapeKeyDown)`, then close when\n * un-vetoed and dismissible.\n */\n emitEscapeKeyDown(event: KeyboardEvent): void {\n const vetoed = emitVetoableNativeEvent(this.#deps.emit.escapeKeyDown, event);\n if (!vetoed && this.#deps.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 `core-overlay/dismissible-layer/dismissible-layer.ts`).\n event.stopPropagation();\n this.#deps.onDismiss?.('escape');\n this.close(this.#deps.escapeReason);\n }\n }\n\n /** Modal-path Escape forwarder: emit only; the modal shell owns the close. */\n forwardEscapeKeyDown(veto: VetoableNativeEvent<KeyboardEvent>): void {\n this.#deps.emit.escapeKeyDown.emit(veto);\n }\n\n /**\n * Outside-interaction emit forwarders. The shared `#pendingOutsideVeto` reuse\n * between the specific outside channels and the composite `interactOutside`\n * lives in `injectOverlayShell`; these only fire the matching output with the\n * veto the shell built.\n */\n emitPointerDownOutside(veto: VetoableNativeEvent<PointerEvent>): void {\n this.#deps.emit.pointerDownOutside.emit(veto);\n }\n\n /** Focus-outside emit forwarder — see {@link emitPointerDownOutside}. */\n emitFocusOutside(veto: VetoableNativeEvent<FocusEvent>): void {\n this.#deps.emit.focusOutside.emit(veto);\n }\n\n /** Composite outside-interaction emit forwarder — see {@link emitPointerDownOutside}. */\n emitInteractOutside(veto: VetoableNativeEvent<PointerEvent | FocusEvent>): void {\n this.#deps.emit.interactOutside.emit(veto);\n }\n\n /**\n * Implicit close requested by `injectOverlayShell` after an un-vetoed outside\n * interaction. The shell owns the shared `#pendingOutsideVeto` reuse between\n * the specific outside channels and the composite `interactOutside`; this\n * controller only owns the close. The open guard keeps a stale event from\n * re-closing an already-closed surface and clobbering its\n * {@link lastCloseReason} (e.g. a `'tab'` close must survive so the content\n * skips its return-focus).\n */\n requestClose(reason: CloseReason & Exclude<TouchDismissal, 'escape'>): void {\n if (!this.#deps.isOpen()) {\n return;\n }\n this.#deps.onDismiss?.(reason);\n this.close(reason);\n }\n\n /**\n * Emits `(autoFocusOnOpen)`, returning whether the mount's focus move is\n * vetoed — by a consumer, or by the root's own destruction.\n */\n emitAutoFocusOnOpen(): boolean {\n return this.#autoFocusOnOpen();\n }\n\n /**\n * Emits `(autoFocusOnClose)`, returning whether the return-focus move is\n * vetoed — by a consumer, or by the root's own destruction.\n */\n emitAutoFocusOnClose(): boolean {\n return this.#autoFocusOnClose();\n }\n}\n","import { DestroyRef, effect, ElementRef, inject, type Signal } from '@angular/core';\nimport type { ReferenceElement } from '@floating-ui/dom';\n\nimport {\n afterNextRenderCancellable,\n findFirstFocusable,\n findTabbableEdges,\n isInitialFocusTarget,\n leavesTabSequence,\n resolveActiveElement,\n resolveEventTarget,\n type VetoableNativeEvent,\n} from 'forty-cdk/core';\nimport {\n buildOutsideVetoOptions,\n injectDismissibleLayer,\n InertSiblingsStack,\n ModalActivationOrder,\n outsideVetoChannels,\n type DismissibleLayerActivateOptions,\n type DismissibleLayerNesting,\n} from 'forty-cdk/core-overlay';\n\nimport { CloseReasonState } from './close-reason-state';\n\n/**\n * The positioning strategy a trigger-anchored surface hands the shell, built by\n * `floatingPositioner` or `itemAlignedPositioner`. The shell installs it once at construction, so\n * switching strategies means remounting the surface. The installed positioner portals the host\n * by default, so the shell never calls `injectPortal` itself.\n */\nexport interface OverlayShellPositioner {\n /** The element the surface anchors to, also read to resolve the modal that owns the surface. */\n readonly reference: Signal<ReferenceElement | null>;\n /** Whether the surface is open. The shell scopes the closes it requests itself to one open. */\n readonly open: Signal<boolean>;\n /** Installs the positioner on the host. Called once, from the shell's injection context. */\n readonly attach: () => void;\n}\n\n/**\n * Outside-interaction wiring for a trigger-anchored overlay.\n *\n * Each wired channel builds one `VetoableNativeEvent` and hands it to both the specific emitter and\n * the composite `interactOutside` one, so a `preventDefault()` from either vetoes the close. When\n * nothing vetoes and `dismissible()` is `true`, the shell calls `requestClose` with the channel's\n * reason. `dismissible` and `requestClose` are required whenever any outside channel is wired.\n *\n * `exemptElements` is re-read on every event, so newly portaled siblings and swapped triggers are\n * honoured.\n *\n * Escape is forwarded verbatim and never participates in the outside-close: its close behaviour\n * differs per primitive, so emitting and closing stay the consumer's decision.\n *\n * Every callback is optional; the shell registers a listener only for the channels supplied.\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`. Each wired outside\n * channel fires its own close, so a specific channel (`emitPointerDownOutside`\n * / `emitFocusOutside`) closes even without `emitInteractOutside` wired. A\n * close requested here does not return focus on destroy, unless the surface\n * reopens before it unmounts and then closes some other way.\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, and handed the node being tested.\n */\n readonly exemptElements?: (target: Node) => readonly Element[];\n /**\n * Declared nesting position of this surface inside a chain of structurally\n * nested overlays (a menu and its submenus). Forwarded verbatim to the\n * dismissible layer so the stack orders the chain by depth instead of by the\n * order the levels happened to render in. Omit for a standalone overlay.\n */\n readonly nesting?: DismissibleLayerNesting;\n /**\n * Whether the surface also closes on an outside press the overlay stacked directly above it\n * closed on, instead of leaving that press to the topmost overlay alone. Read on every press.\n */\n readonly cascadeOutsidePress?: () => boolean;\n /**\n * Called after a surface opened from inside this one closes, that is an\n * overlay whose anchor lies inside this surface or inside an overlay opened\n * from it.\n */\n readonly onNestedLayerRemoved?: () => void;\n}\n\n/**\n * Handle returned by {@link injectOverlayShell}.\n */\nexport interface OverlayShell {\n /**\n * Whether a surface opened from inside this one is still open above it: an\n * overlay anchored inside this surface, or inside an overlay opened from it.\n * Always `false` for a shell without `dismiss` wiring.\n */\n hasNestedLayer(): boolean;\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 * `focusInitialEnabledItem`, 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 * Element the consumer marked as the initial focus target, read once at mount. When it resolves\n * to an element that passes `isInitialFocusTarget`, focus lands there instead of running `move`.\n */\n readonly target?: () => HTMLElement | null;\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, read before `veto`. The shell already skips\n * the return after a close it requested itself, through an outside channel\n * or a Tab out, since focus is then where the user moved it. `skip` covers\n * the closes that reach the root another way, such as a Tab the root handles\n * or a close propagated from a nested surface. The shell's own skip lasts one\n * open: a surface reopened while still mounted returns focus on its next\n * close like any other.\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 * Optional Tab-out wiring for a non-modal surface portaled away from its trigger. A Tab past the\n * surface's last tabbable lands on the element after `target` in the page's tab order, and a\n * Shift+Tab before its first lands on `target` itself, as if the surface sat right after it.\n *\n * - `target` — the element the surface follows in the tab order (typically the trigger).\n * Returning `null` leaves Tab to the browser.\n * - `close` — closes the surface after the focus move, unless `dismiss.dismissible()` is\n * `false`. Return focus is skipped for that close.\n */\nexport interface OverlayShellTabOutConfig {\n readonly target: () => HTMLElement | null;\n readonly close: () => void;\n}\n\n/**\n * Single config for the overlay-content lifecycle. Each sub-bundle is\n * individually optional so each trigger-anchored primitive (Popover, the menu\n * roots, Combobox, Select, DatePicker, TimePicker, Tooltip, HoverCard) can opt\n * in to only the pieces it needs.\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: OverlayShellPositioner;\n readonly dismiss?: OverlayShellDismissConfig;\n readonly initialFocus?: OverlayShellInitialFocusConfig;\n readonly returnFocus?: OverlayShellReturnFocusConfig;\n readonly tabOut?: OverlayShellTabOutConfig;\n}\n\n/**\n * Owns the lifecycle of a portaled, trigger-anchored overlay surface — the `*-content` directives\n * of Popover, the menu family, Combobox, Select, Tooltip and HoverCard.\n *\n * Positioning is delegated to the configured positioner, which portals the host itself: the caller\n * must not also call `injectPortal`.\n *\n * When configured, the shell activates a dismissible layer after the first render, performs the\n * initial focus move — falling back to the host when the move finds no candidate — and restores\n * focus to the return target on destroy. Both focus moves are skipped when their `veto()` returns\n * truthy, which is how `autoFocusOnOpen` / `autoFocusOnClose` are honoured. The return is also\n * skipped when the surface closed through one of its own outside channels or a Tab out, without\n * consulting `veto`: focus already moved where the user put it. That skip belongs to the open the\n * close ended, so a surface reopened before it unmounts returns focus on its next close, and one\n * reopened after a Tab out gets its dismissible layer back.\n *\n * Return focus runs after the portaled node has been detached, so the trigger receives the focus\n * event in a settled layout.\n *\n * Must be called from an injection context. The host's `ElementRef` is forwarded to the dismissible\n * layer and the positioner.\n */\nexport function injectOverlayShell(config: OverlayShellConfig): OverlayShell {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const el = host.nativeElement;\n const inertStack = inject(InertSiblingsStack);\n const order = inject(ModalActivationOrder);\n\n // 1. Dismissible layer. Created BEFORE the positioner so its\n // `DestroyRef.onDestroy` (dismissible.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 ? injectDismissibleLayer() : null;\n let layerOptions: DismissibleLayerActivateOptions | null = null;\n const ownClose = new CloseReasonState<'outside' | 'tab'>(config.positioner.open);\n\n // 2. Positioner.\n config.positioner.attach();\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 dismissible 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 // `injectDismissibleLayer`, 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 let destroyed = false;\n let releasePeer: (() => void) | null = null;\n inject(DestroyRef).onDestroy(() => {\n destroyed = true;\n releasePeer?.();\n releasePeer = null;\n });\n afterNextRenderCancellable(() => {\n const anchor = resolveModalAnchor(config);\n order.after(order.enclosingHeld(anchor), () => {\n if (!destroyed) {\n activate(anchor);\n }\n });\n });\n\n const activate = (anchor: Element | null): void => {\n // Modal-peer registration (#676). The positioner's portal ran in an\n // earlier hook of this same render batch, so the host is already in\n // `body`. Registering it with the anchor lets `InertSiblingsStack` leave it\n // live while the anchor belongs to the topmost modal — opened from inside a\n // Dialog / Drawer (a Select in a form, a context menu on dialog content) —\n // and inert it under any other owner, so a toast / background overlay stays\n // isolated (#388) and a background modal's overlay is inerted under a\n // nested modal. The registration lands before the inert observer's\n // microtask inspects the portaled host.\n if (anchor !== null) {\n releasePeer = inertStack.registerPeer(el, [anchor]);\n }\n\n if (layer && dismissCfg) {\n const requestClose = dismissCfg.requestClose;\n const options: DismissibleLayerActivateOptions = {\n channels: outsideVetoChannels(dismissCfg),\n ...buildOutsideVetoOptions(\n requestClose\n ? {\n ...dismissCfg,\n requestClose: (reason) => ownClose.close('outside', () => requestClose(reason)),\n }\n : dismissCfg,\n ),\n };\n\n if (dismissCfg.exemptElements) {\n options.exemptElements = dismissCfg.exemptElements;\n }\n if (dismissCfg.nesting) {\n options.nesting = dismissCfg.nesting;\n }\n if (dismissCfg.cascadeOutsidePress) {\n options.cascadeOutsidePress = dismissCfg.cascadeOutsidePress;\n }\n if (dismissCfg.onNestedLayerRemoved) {\n options.onNestedLayerRemoved = dismissCfg.onNestedLayerRemoved;\n }\n if (anchor !== null) {\n options.anchor = anchor;\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\n layerOptions = options;\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 marked = focusCfg.target?.() ?? null;\n const move = focusCfg.move;\n if (marked !== null && isInitialFocusTarget(marked, el)) {\n marked.focus();\n } else 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 const tabOutCfg = config.tabOut;\n if (tabOutCfg) {\n const closeOnTab = (): void => ownClose.close('tab', tabOutCfg.close);\n let layerParked = false;\n const onKeyDown = (event: KeyboardEvent): void => {\n const closes = dismissCfg?.dismissible?.() ?? true;\n if (handleTabOut(event, el, tabOutCfg.target, closes ? closeOnTab : null) && layer) {\n layerParked = true;\n layer.deactivate();\n }\n };\n el.addEventListener('keydown', onKeyDown);\n inject(DestroyRef).onDestroy(() => el.removeEventListener('keydown', onKeyDown));\n\n if (layer) {\n effect(() => {\n if (ownClose.reason() === null && layerParked && layerOptions !== null) {\n layerParked = false;\n layer.activate(layerOptions);\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 the positioner's `attach`) 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 (ownClose.reason() !== null || 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 return { hasNestedLayer: () => layer?.hasNestedLayer() ?? false };\n}\n\n/**\n * Moves focus to the tab-out target when a Tab press would leave the surface's Tab cycle, then\n * runs `close` when one is given. A forward Tab keeps its default action so the browser advances\n * from the target, with the surface inert until that action has run so the advance never lands\n * back inside it; a backward one is prevented so focus stays on it. Returns whether it closed.\n */\nfunction handleTabOut(\n event: KeyboardEvent,\n host: HTMLElement,\n resolveTarget: () => HTMLElement | null,\n close: (() => void) | null,\n): boolean {\n if (\n event.key !== 'Tab' ||\n event.defaultPrevented ||\n event.altKey ||\n event.ctrlKey ||\n event.metaKey\n ) {\n return false;\n }\n const target = resolveTarget();\n if (target === null) {\n return false;\n }\n const from = resolveEventTarget(event);\n const backward = event.shiftKey;\n if (\n !leavesTabSequence(findTabbableEdges(host), from instanceof Element ? from : null, backward)\n ) {\n return false;\n }\n target.focus();\n if (resolveActiveElement(target.ownerDocument) !== target) {\n return false;\n }\n if (backward) {\n event.preventDefault();\n } else {\n skipTabDefaultAction(host);\n }\n if (close === null) {\n return false;\n }\n close();\n return true;\n}\n\n/**\n * Keeps a surface out of a forward Tab's default action. Call it after moving focus out of the\n * surface from that Tab's `keydown`, without preventing the event: the browser then advances from\n * the element that took focus, and the surface is inert until that advance has run, so a surface\n * that is still mounted and tabbable is never the element focus advances into. The overlay shell's\n * Tab-out and `ListboxOverlayController.commitTabToTrigger` are its callers.\n */\nexport function skipTabDefaultAction(host: HTMLElement): void {\n if (host.hasAttribute('inert')) {\n return;\n }\n host.setAttribute('inert', '');\n setTimeout(() => host.removeAttribute('inert'), 0);\n}\n\n/**\n * Resolves the real DOM element an overlay is anchored to, for the modal-peer ownership check.\n *\n * Falls back to the `VirtualElement`'s `contextElement` and then to the return-focus target for\n * pointer-positioned overlays. Returns `null` when no backing element exists, leaving the overlay\n * unmarked.\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 { type Signal } from '@angular/core';\nimport type { ReferenceElement } from '@floating-ui/dom';\n\nimport {\n accessibleTextContent,\n Collection,\n firstEnabledHost,\n injectFieldAnchor,\n injectTypeahead,\n lastEnabledHost,\n type ListNavigationAction,\n nextEnabledHandle,\n resolveActiveElement,\n resolveListTypeahead,\n type SingleSlotConfig,\n type VetoableNativeEvent,\n dismissMarksTouched,\n type TouchDismissal,\n} from 'forty-cdk/core';\nimport {\n anchorSlot,\n type AnchorSlot,\n type RootedTriggerHandle,\n RootedTriggerSlot,\n} from '../overlay-controller/element-registry';\nimport {\n OverlayController,\n type OverlayEmitTargets,\n} from '../overlay-controller/overlay-controller';\nimport {\n type OverlayShellTabOutConfig,\n skipTabDefaultAction,\n} from '../overlay-controller/overlay-shell';\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 * 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 readonly triggers: Signal<readonly RootedTriggerHandle[]>;\n /** Names the root and its anchor piece in the dev-mode duplicate-anchor warning. */\n readonly anchorSlot: SingleSlotConfig;\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: OverlayEmitTargets;\n /** Whether keyboard navigation wraps at the ends of the option list. */\n readonly loop: Signal<boolean>;\n /** Whether Escape / outside interactions dismiss the overlay. */\n readonly dismissible: Signal<boolean>;\n /** Close reason set when Escape dismisses the overlay (both primitives use `'escape'`). */\n readonly escapeReason: CloseReason;\n /** Close reason set when {@link ListboxOverlayController.toggle} closes the overlay (both primitives use `'programmatic'`). */\n readonly programmaticReason: CloseReason;\n /** Mark the control touched on a dismissal that {@link dismissMarksTouched} counts. */\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` or a typeahead match 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 * The texts open-state typeahead matches an option against, any of which may match. Defaults to\n * the option's accessible text (TimePicker adds its label without the hour's leading zero).\n */\n readonly typeaheadText?: (handle: H) => string | readonly string[];\n}\n\n/**\n * The narrow, typed facade a primitive surfaces on its coordination context\n * (`ctx.overlay`) so child directives read the shared overlay-listbox state and\n * behavior here instead of the root re-forwarding every member. Implemented by\n * {@link ListboxOverlayController}; each primitive's context exposes it as a\n * sub-object, keeping the child-facing surface a single, self-documenting seam.\n *\n * @typeParam H Primitive option-handle type.\n * @typeParam Focus Initial-focus union.\n * @typeParam CloseReason Close-reason union owned by the primitive.\n */\nexport interface ListboxOverlayContext<H extends ListboxOverlayOptionHandle, Focus, CloseReason> {\n /**\n * The active trigger's id, which the content names in `aria-labelledby`, or `''` while no\n * trigger is registered.\n */\n readonly triggerId: Signal<string>;\n /** The content surface's stable id, adopted from a consumer-set static id when present. */\n readonly contentId: Signal<string>;\n /** Where focus should land after the content mounts. Triggers set this before flipping `open`. */\n readonly initialFocus: Signal<Focus>;\n /** Reason of the most recent close, or `null` while open (or before any close). */\n readonly lastCloseReason: Signal<CloseReason | null>;\n /**\n * The active trigger: the one that last opened or toggled the listbox, else the newest\n * registered. The listbox anchors to it and returns focus to it.\n */\n readonly trigger: Signal<HTMLElement | null>;\n /**\n * Element floating-ui anchors the content against. Prefers a registered\n * anchor, otherwise falls back to the trigger.\n */\n readonly anchor: Signal<ReferenceElement | null>;\n /** The mounted content element. */\n readonly content: Signal<HTMLElement | null>;\n /** All registered options in DOM order. */\n readonly options: Signal<readonly H[]>;\n\n /** Set the initial-focus target ahead of the next open. */\n setInitialFocus(target: Focus): void;\n\n registerAnchor(el: HTMLElement): void;\n unregisterAnchor(el: HTMLElement): void;\n registerContent(el: HTMLElement): void;\n unregisterContent(el: HTMLElement): void;\n registerOption(handle: H): void;\n unregisterOption(handle: H): void;\n\n /** Move focus inside the open content in response to an arrow / Home / End key. */\n navigate(currentOption: HTMLElement, action: ListNavigationAction): void;\n focusFirstEnabledOption(): boolean;\n focusLastEnabledOption(): boolean;\n\n toggle(initialFocus: Focus): void;\n openOverlay(initialFocus: Focus): void;\n closeOverlay(reason: CloseReason): void;\n\n /** Escape on the anchored path: emit `(escapeKeyDown)`, then close when un-vetoed and dismissible. */\n emitEscapeKeyDown(event: KeyboardEvent): void;\n emitPointerDownOutside(veto: VetoableNativeEvent<PointerEvent>): void;\n emitFocusOutside(veto: VetoableNativeEvent<FocusEvent>): void;\n emitInteractOutside(veto: VetoableNativeEvent<PointerEvent | FocusEvent>): void;\n /** Modal-path Escape forwarder: emit only; the modal shell owns the close. */\n forwardEscapeKeyDown(veto: VetoableNativeEvent<KeyboardEvent>): void;\n /** Implicit close requested by the shell after an un-vetoed outside interaction. */\n requestClose(reason: CloseReason & Exclude<TouchDismissal, 'escape'>): void;\n emitAutoFocusOnOpen(): boolean;\n emitAutoFocusOnClose(): boolean;\n}\n\n/**\n * {@link ListboxOverlayContext} plus the calls only a primitive's option pieces make, so the\n * blessed surface a root publishes on `ctx.overlay` never carries them. Each primitive reads\n * its `ctx.overlay` at this type through its own internal context.\n *\n * Internal core tier — exported from `forty-cdk/core-anchored` for the library's\n * own entry points, with no semver guarantee.\n *\n * @typeParam H Primitive option-handle type.\n * @typeParam Focus Initial-focus union.\n * @typeParam CloseReason Close-reason union.\n */\nexport interface ListboxOverlayPieceContext<\n H extends ListboxOverlayOptionHandle,\n Focus,\n CloseReason,\n> extends ListboxOverlayContext<H, Focus, CloseReason> {\n /**\n * Open-state typeahead: focus the first enabled option after the event target whose\n * accessible text matches the buffered prefix. Returns `true` when the key was consumed,\n * so a Space the buffer took must not also activate.\n */\n handleTypeahead(event: KeyboardEvent): boolean;\n /** Every registered trigger's host, each exempt from the outside-press and outside-focus checks. */\n readonly triggerHosts: Signal<readonly HTMLElement[]>;\n /** Make the trigger on `host` the active one. A trigger calls it as it opens or toggles. */\n activateTrigger(host: HTMLElement): 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). It owns\n * the option collection, the anchor slot, the DOM-focus navigation algorithm and\n * the trigger focus move; everything the menu overlays run identically — the\n * trigger / content slots and their ids, the initial-focus and close-reason\n * state, the open / close machine, the dismiss / auto-focus forwarders — is the\n * shared {@link OverlayController}'s, composed here rather than re-declared.\n *\n * Value-specific behaviour (selection equality, `activate`, `focusSelectedOption`,\n * closed-state 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 core tier — exported from `forty-cdk/core-anchored` for the library's\n * own entry points, with no semver guarantee.\n *\n * Construct it from a directive's field initializer, so the slot factories'\n * `inject()` calls resolve through the directive's injector.\n *\n * @typeParam H Primitive option-handle type.\n * @typeParam Focus Initial-focus union.\n * @typeParam CloseReason Close-reason union.\n */\nexport class ListboxOverlayController<\n H extends ListboxOverlayOptionHandle,\n Focus,\n CloseReason,\n> implements ListboxOverlayPieceContext<H, Focus, CloseReason> {\n readonly #deps: ListboxOverlayControllerDeps<H, Focus, CloseReason>;\n readonly #items = new Collection<H>();\n readonly #typeahead = injectTypeahead();\n\n readonly #anchorSlot: AnchorSlot;\n readonly #triggerSlot: RootedTriggerSlot;\n readonly #controller: OverlayController<Focus, CloseReason>;\n\n /**\n * The active trigger's id, which the content names in `aria-labelledby`, or `''` while no\n * trigger is registered.\n */\n readonly triggerId: Signal<string>;\n\n /** The content surface's stable id, adopted from a consumer-set static id when present. */\n readonly contentId: Signal<string>;\n\n /** Where focus should land after the content mounts. Triggers set this before flipping `open`. */\n readonly initialFocus: Signal<Focus>;\n\n /** Reason of the most recent close, or `null` while open (or before any close). */\n readonly lastCloseReason: Signal<CloseReason | null>;\n\n /**\n * The active trigger: the one that last opened or toggled the listbox, else the newest\n * registered. The listbox anchors to it and returns focus to it.\n */\n readonly trigger: Signal<HTMLElement | null>;\n\n /**\n * Element floating-ui anchors the listbox against. Prefers an optional\n * registered anchor, then the surrounding field's `[forFieldAnchor]`,\n * otherwise falls back to the trigger so primitives without an anchor keep\n * their behavior.\n */\n readonly anchor: Signal<ReferenceElement | null>;\n\n /** The mounted content element. */\n readonly content: Signal<HTMLElement | null>;\n\n /** All registered options in DOM order. */\n readonly options: Signal<readonly H[]>;\n\n /** Every registered trigger's host, each exempt from the outside-press and outside-focus checks. */\n readonly triggerHosts: Signal<readonly HTMLElement[]>;\n\n constructor(deps: ListboxOverlayControllerDeps<H, Focus, CloseReason>) {\n this.#deps = deps;\n let triggerSlot!: RootedTriggerSlot;\n this.#controller = new OverlayController<Focus, CloseReason>({\n idPrefix: deps.idPrefix,\n createTrigger: () => {\n triggerSlot = new RootedTriggerSlot(deps.triggers);\n return triggerSlot;\n },\n defaultInitialFocus: deps.defaultInitialFocus,\n disabled: deps.effectiveDisabled,\n dismissible: deps.dismissible,\n isOpen: deps.isOpen,\n setOpen: deps.setOpen,\n emit: deps.emit,\n escapeReason: deps.escapeReason,\n programmaticReason: deps.programmaticReason,\n onClose: deps.onClose,\n onDismiss: (dismissal) => {\n if (dismissMarksTouched(dismissal)) {\n deps.markTouched();\n }\n },\n });\n this.#triggerSlot = triggerSlot;\n this.#anchorSlot = anchorSlot(deps.anchorSlot);\n this.triggerId = this.#controller.triggerId;\n this.contentId = this.#controller.contentId;\n this.initialFocus = this.#controller.initialFocus;\n this.lastCloseReason = this.#controller.lastCloseReason;\n this.trigger = this.#controller.trigger;\n this.triggerHosts = triggerSlot.hosts;\n this.content = this.#controller.content;\n this.anchor = this.#anchorSlot.resolve(injectFieldAnchor(), this.#controller.trigger);\n this.options = this.#items.items;\n }\n\n setInitialFocus(target: Focus): void {\n this.#controller.setInitialFocus(target);\n }\n\n activateTrigger(host: HTMLElement): void {\n this.#triggerSlot.activate(host);\n }\n\n registerAnchor(el: HTMLElement): void {\n this.#anchorSlot.register(el);\n }\n unregisterAnchor(el: HTMLElement): void {\n this.#anchorSlot.unregister(el);\n }\n\n registerContent(el: HTMLElement): void {\n this.#controller.registerContent(el);\n }\n unregisterContent(el: HTMLElement): void {\n this.#controller.unregisterContent(el);\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): void {\n if (this.#deps.effectiveDisabled()) {\n return;\n }\n const target = nextEnabledHandle(this.#items.items(), currentOption, action, {\n loop: this.#deps.loop(),\n });\n if (target === null) {\n return;\n }\n target.host.focus();\n this.#deps.onNavigateFocus?.(target);\n }\n\n handleTypeahead(event: KeyboardEvent): boolean {\n const items = this.#items.items();\n const { handled, match } = resolveListTypeahead(this.#typeahead, event, {\n items,\n anchorIndex: items.findIndex((o) => o.host === event.target),\n getText: this.#deps.typeaheadText ?? ((o) => accessibleTextContent(o.host)),\n isDisabled: (o) => o.disabled(),\n });\n if (match) {\n match.host.focus();\n this.#deps.onNavigateFocus?.(match);\n }\n return handled;\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 host = lastEnabledHost(this.#items.items());\n if (!host) {\n return false;\n }\n host.focus();\n return true;\n }\n\n /**\n * The option an open surface still has to scroll into view: the registered option holding DOM\n * focus, else `fallback()` when focus is on none of them. `null` when that option is the first\n * enabled one, which the surface already shows at its top, or when there is none.\n */\n revealTarget(fallback: () => HTMLElement | null = () => null): HTMLElement | null {\n const content = this.content();\n if (content === null) {\n return null;\n }\n const items = this.#items.items();\n const active = resolveActiveElement(content.ownerDocument);\n const target = items.find((o) => o.host === active)?.host ?? fallback();\n return target === firstEnabledHost(items) ? null : target;\n }\n\n /**\n * The overlay shell's Tab-out wiring: a Tab that leaves the open surface's tab cycle moves focus\n * to the trigger, so the browser advances from there rather than from the body-appended portal,\n * and closes with `reason`. The target resolves only while the overlay is open and `enabled()`\n * holds, so an option that already committed and closed on the same Tab keeps the browser's own\n * advance from the trigger.\n */\n tabOut(reason: CloseReason, enabled: () => boolean = () => true): OverlayShellTabOutConfig {\n return {\n target: () => (this.#deps.isOpen() && enabled() ? this.trigger() : null),\n close: () => this.closeOverlay(reason),\n };\n }\n\n toggle(initialFocus: Focus): void {\n this.#controller.toggle(initialFocus);\n }\n\n openOverlay(initialFocus: Focus): void {\n this.#controller.open(initialFocus);\n }\n\n closeOverlay(reason: CloseReason): void {\n this.#controller.close(reason);\n }\n\n emitEscapeKeyDown(event: KeyboardEvent): void {\n this.#controller.emitEscapeKeyDown(event);\n }\n\n emitPointerDownOutside(veto: VetoableNativeEvent<PointerEvent>): void {\n this.#controller.emitPointerDownOutside(veto);\n }\n emitFocusOutside(veto: VetoableNativeEvent<FocusEvent>): void {\n this.#controller.emitFocusOutside(veto);\n }\n emitInteractOutside(veto: VetoableNativeEvent<PointerEvent | FocusEvent>): void {\n this.#controller.emitInteractOutside(veto);\n }\n\n forwardEscapeKeyDown(veto: VetoableNativeEvent<KeyboardEvent>): void {\n this.#controller.forwardEscapeKeyDown(veto);\n }\n\n /**\n * Implicit close requested by the shell after an un-vetoed outside\n * interaction. The `isOpen` guard keeps a stale event from re-closing an\n * already-closed overlay and clobbering its `lastCloseReason` (e.g. a `'tab'`\n * close must survive so the content skips its return-focus).\n */\n requestClose(reason: CloseReason & Exclude<TouchDismissal, 'escape'>): void {\n this.#controller.requestClose(reason);\n }\n\n emitAutoFocusOnOpen(): boolean {\n return this.#controller.emitAutoFocusOnOpen();\n }\n\n emitAutoFocusOnClose(): boolean {\n return this.#controller.emitAutoFocusOnClose();\n }\n\n /**\n * Hands a Tab press that commits and closes the listbox to the trigger: focuses it, so the\n * browser's Tab default advances from there, and on a forward Tab keeps the content out of that\n * advance until it has run, so focus never re-enters the closing surface. Call it from the Tab\n * `keydown` before the close, without preventing the event.\n */\n commitTabToTrigger(event: KeyboardEvent): void {\n const trigger = this.#controller.trigger();\n if (trigger === null) {\n return;\n }\n trigger.focus();\n const content = this.content();\n if (\n event.shiftKey ||\n content === null ||\n resolveActiveElement(trigger.ownerDocument) !== trigger\n ) {\n return;\n }\n skipTabDefaultAction(content);\n }\n}\n","import { inject, InjectionToken, type Signal } from '@angular/core';\nimport type { ReferenceElement } from '@floating-ui/dom';\n\nimport {\n type CollectionHandle,\n type ListNavigationAction,\n orphanContextError,\n type VetoableNativeEvent,\n type WritingDirection,\n} from 'forty-cdk/core';\nimport type { DismissibleLayerNesting } from 'forty-cdk/core-overlay';\nimport type {\n FloatingAlign,\n FloatingFallbackAxisSideDirection,\n FloatingSide,\n} from '../floating/floating';\nimport type { MenuActivationModality } from './menu-overlay';\nimport type { Point } from '../pointer-grace/pointer-grace';\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 /**\n * Axis the bar lays its triggers out on. It decides what the horizontal\n * arrows do inside a menu opened from the bar: switch sibling menus on a\n * horizontal bar, return to the bar on a vertical one.\n */\n readonly orientation: Signal<'horizontal' | 'vertical'>;\n /**\n * Move focus/open to the previous or next sibling menu, returning whether the\n * bar actually moved. `false` means there was nowhere to go — the bar is\n * disabled, it has no registered triggers, or no enabled sibling exists in\n * that direction with `loop` off — so a caller must not tear down state (an\n * open submenu chain) it would then be unable to leave.\n */\n switchToSibling(direction: 'next' | 'prev'): boolean;\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. `'hover'` is a pointer-driven\n * (hover-leave) close and, like `'escape'` / `'programmatic'`, affects only\n * the level that scheduled it — it never propagates up the menu chain.\n */\nexport type ForMenuCloseReason =\n 'escape' | 'pointerDownOutside' | 'focusOutside' | 'select' | 'tab' | 'hover' | '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 the item's accessible\n * text for typeahead matching — useful when announced content such as a kbd\n * shortcut, a badge, or an SVG title would otherwise bleed into the match\n * string. Empty / unset means \"fall back to the host's accessible text\", which\n * already excludes any `aria-hidden` subtree.\n */\nexport interface ForMenuItemHandle extends CollectionHandle {\n /**\n * Narrowed from {@link CollectionHandle}'s `Node`: the menu focuses its items\n * and scrolls them into view.\n */\n readonly host: HTMLElement;\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 * 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, and\n * the menu calls it on every other item before a keyboard focus move.\n * Optional — items that don't reflect a highlight 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 /**\n * Direction `flip` falls back to on the perpendicular axis when both sides of\n * the preferred axis overflow. `'none'` (default) keeps only the opposite\n * same-axis placement; `'start'` / `'end'` let a submenu drop to a vertical\n * side on a narrow viewport. Threaded through to `injectOverlayShell`'s\n * floating positioner.\n */\n readonly fallbackAxisSideDirection: Signal<FloatingFallbackAxisSideDirection>;\n readonly collisionPadding: 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 /**\n * Id of the trigger, used as the surface's `aria-labelledby` fallback. An\n * empty string means the context has no trigger to name the surface with, and\n * `[forMenuContent]` emits no attribute at all — never `aria-labelledby=\"\"`.\n */\n readonly triggerId: Signal<string>;\n /**\n * Id the surface exposes, and the trigger's `aria-controls` target. An empty\n * string means the context has not associated a trigger with the surface yet\n * (only reachable under `[forMenubar]`, whose single context multiplexes over\n * the triggers), and `[forMenuContent]` emits no `id` at all — never `id=\"\"`.\n */\n readonly contentId: Signal<string>;\n readonly ariaLabel: Signal<string | null>;\n\n /**\n * Whether the trigger's own accessible name is a valid name for the menu\n * surface. `true` — the default when a root omits the member entirely — lets\n * `[forMenuContent]` fall back to `aria-labelledby=\"<triggerId>\"` when no\n * `ariaLabel` is set, which is correct for a discrete labelling control (a\n * `[forDropdownMenuTrigger]` button, a `[forMenubarTrigger]` or\n * `[forMenuSubTrigger]` menuitem). `[forContextMenu]` reports `false`: its\n * trigger is the whole right-click region, so an `aria-labelledby` pointing at\n * it would make screen readers announce the entire row / card text as the\n * menu's name. A root that reports `false` must expose `ariaLabel` as the way\n * to name the menu.\n *\n * A `Signal` rather than a plain `boolean` because a multi-opener root\n * (`[forMenu]`) has heterogeneous openers: a button opener *is* a labelling\n * control while a right-click region is not, so the answer is a property of\n * the **active** opener and changes as the menu is opened from a different one. Roots with a\n * single fixed trigger flavour report a constant signal.\n */\n readonly triggerLabelsMenu?: Signal<boolean>;\n\n /** Anchor passed to floating-ui — `HTMLElement` (Dropdown) or `VirtualElement` (Context). */\n readonly anchor: Signal<ReferenceElement | null>;\n\n /**\n * The element the menu was opened from (the trigger button or right-click\n * region). Focus returns here on close, except after a keyboard activation\n * from a focused element inside a right-click region, which returns focus to\n * that element while it is still in the document.\n */\n readonly trigger: Signal<HTMLElement | null>;\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 dismissible 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 dismissibleExemptions: 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 /**\n * Prefix-match against item text content and focus the first match. Returns\n * `true` when the key was consumed as a typeahead character (a printable\n * char, or Space while the buffer is already non-empty). Items applied on a\n * native `<button>` use this to `preventDefault()` a mid-typeahead Space so\n * it extends the buffer instead of activating the focused item.\n */\n handleTypeahead(event: KeyboardEvent): boolean;\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 /**\n * Focuses the first or last enabled item per `target` — the contract-level\n * resolution of {@link initialFocus}, so a piece that reads that signal hands\n * the value straight back instead of re-deriving which of the two granular\n * calls it maps to. `[forMenuContent]` uses it for the mount-time initial\n * focus; the mapping itself is owned once by core's `MenuItemList`. This is\n * the contract's only initial-focus entry point — the granular\n * `focusFirstEnabledItem` / `focusLastEnabledItem` pair stays on the concrete\n * controllers as an imperative escape hatch and is not part of what an\n * implementor owes. Returns `true` if focus moved; `false` when no enabled\n * items exist.\n */\n focusInitialEnabledItem(target: 'first' | 'last'): 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. The specific and composite channels\n * observe the same veto, so `preventDefault()` from either one suppresses the\n * close that otherwise follows.\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\n/**\n * Nesting descriptor for a menu level's dismissible layer, derived from the\n * `parentMenu` chain: the chain identity is the outermost menu context and the\n * depth is the number of hops needed to reach it (`0` for a top-level\n * `[forDropdownMenu]` / `[forContextMenu]` / `[forMenubar]` menu, `1` for its\n * first `[forMenuSub]`, and so on).\n *\n * Menu levels are ordered on the layer stack by this depth rather than by the\n * order their `afterNextRender` callbacks ran, because a menu and its submenu\n * mounted in the same render pass activate child-before-parent — which would\n * put the parent above its own submenu and make the submenu's first focus close\n * the whole chain with reason `'focusOutside'`.\n */\nexport function menuLayerNesting(ctx: ForMenuContext): DismissibleLayerNesting {\n let chain: ForMenuContext = ctx;\n let depth = 0;\n while (chain.parentMenu) {\n chain = chain.parentMenu;\n depth++;\n }\n return { chain, depth };\n}\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 orphanContextError({\n code: 'FORCDK-MENU-001',\n piece,\n root: '[forMenu], [forDropdownMenu], [forContextMenu], [forMenubar], or [forMenuSub]',\n token: 'FOR_MENU_CONTEXT',\n });\n }\n return ctx;\n}\n","import { type Signal } from '@angular/core';\n\nimport {\n accessibleTextContent,\n Collection,\n type CollectionHandle,\n firstEnabledHandle,\n injectTypeahead,\n lastEnabledHandle,\n type ListNavigationAction,\n nextEnabledHandle,\n resolveListTypeahead,\n type Typeahead,\n} from 'forty-cdk/core';\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 `./menu-context` (no cycle into a primitive).\n *\n * Stays exported from `forty-cdk/core-anchored` — internal tier, not blessed —\n * because it is the default type argument of `MenuOverlay`, which the emitted\n * `.d.ts` names as `MenuOverlay<MenuItemHandle>` for the `protected readonly\n * _overlay` field on `[forDropdownMenu]` / `[forContextMenu]` / `[forMenu]` /\n * `[forMenuSub]`.\n */\nexport interface MenuItemHandle extends CollectionHandle {\n /**\n * Narrowed from {@link CollectionHandle}'s `Node`: the list focuses its items\n * and scrolls them into view.\n */\n readonly host: HTMLElement;\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 * 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, and\n * before every keyboard focus move so a hover highlight held without focus\n * never outlives it. 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 their\n * navigate / typeahead / focus behaviour to this unit.\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 /**\n * Moves focus to the next enabled item for an Arrow / Home / End action,\n * honouring the owner's `loop`. The focus move passes `preventScroll` and\n * then scrolls the target into view with `block: 'nearest'`, so a menu with\n * its own overflow scrolls minimally while the page underneath the portaled\n * surface never jumps.\n */\n navigate(currentItem: HTMLElement, action: ListNavigationAction): void {\n const target = nextEnabledHandle(this.#items.items(), currentItem, action, {\n loop: this.#loop(),\n });\n if (!target) {\n return;\n }\n this.#focus(target);\n }\n\n /**\n * Feeds `event` to the typeahead buffer and focuses the first matching item.\n * An item matches on its `textValue` when set, else on its accessible text:\n * an `aria-hidden` subtree (a `[forMenuItemIndicator]` glyph, an icon, a\n * badge) contributes nothing, while visually-hidden but announced content\n * still does. Text and buffer are compared trimmed, case-insensitively and\n * diacritics-insensitively, so `e` reaches `Éditer`.\n * Returns `true` when the key was consumed as a typeahead character (a\n * printable char, or Space while the buffer is already non-empty), `false`\n * otherwise. A consumed Space is `preventDefault()`-ed, so it extends the\n * buffer instead of triggering a native `<button>` item's activation. The\n * focus move passes `preventScroll` and reveals the match with\n * `scrollIntoView({ block: 'nearest' })`.\n */\n handleTypeahead(event: KeyboardEvent): boolean {\n const items = this.#items.items();\n const { handled, match } = resolveListTypeahead(this.#typeahead, event, {\n items,\n anchorIndex: items.findIndex((item) => item.host === event.target),\n getText: (item) => {\n const override = item.textValue?.() ?? '';\n return override !== '' ? override : accessibleTextContent(item.host);\n },\n isDisabled: (item) => item.disabled(),\n });\n if (match) {\n this.#focus(match);\n }\n return handled;\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`. The move passes\n * `preventScroll`: the menu surface is portaled and `position: fixed`, and\n * floating-ui has not resolved its placement yet when the initial focus\n * runs, so letting the browser scroll for it would move the page (and the\n * anchor) under a pointer-driven open.\n */\n focusFirstEnabledItem(highlight = true): boolean {\n const target = firstEnabledHandle(this.#items.items());\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`. Like\n * {@link focusFirstEnabledItem} the move passes `preventScroll` and reveals\n * the item with `scrollIntoView({ block: 'nearest' })`, so a scrollable menu\n * still scrolls its own overflow to the last item.\n */\n focusLastEnabledItem(highlight = true): boolean {\n const target = lastEnabledHandle(this.#items.items());\n if (!target) {\n return false;\n }\n this.#focusItem(target, highlight);\n return true;\n }\n\n /**\n * Focuses the first or last enabled item per `target`. The single owner of the\n * `'first' | 'last'` → focus-call mapping every menu surface resolves its\n * initial focus through — the mount path, the already-open re-focus branch of\n * a `MenuOverlay`, and `[forMenubar]`'s equivalent — so the fallback ordering\n * and any future widening of the target union live in one place instead of one\n * copy per surface. `highlight` behaves exactly as on\n * {@link focusFirstEnabledItem} / {@link focusLastEnabledItem}.\n */\n focusInitialEnabledItem(target: 'first' | 'last', highlight = true): boolean {\n return target === 'last'\n ? this.focusLastEnabledItem(highlight)\n : this.focusFirstEnabledItem(highlight);\n }\n\n #focusItem(item: H, highlight: boolean): void {\n if (!highlight) {\n item.suppressHighlightOnNextFocus?.();\n }\n this.#focus(item);\n }\n\n #focus(target: H): void {\n for (const item of this.#items.items()) {\n if (item !== target) {\n item.clearHighlight?.();\n }\n }\n focusMenuItemHost(target.host);\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\nfunction focusMenuItemHost(host: HTMLElement): void {\n host.focus({ preventScroll: true });\n host.scrollIntoView?.({ block: 'nearest' });\n}\n","import type { WritingDirection } from 'forty-cdk/core';\nimport type { FloatingSide } from '../floating/floating';\n\n/** Axis a menubar lays its triggers out on. */\nexport type MenubarOrientation = 'horizontal' | 'vertical';\n\n/**\n * What a horizontal arrow key does on an item of a menu opened from a menubar:\n * switch to the previous or next sibling menu, close the menu and return focus\n * to its trigger on the bar, or nothing (`null`).\n */\nexport type MenubarInMenuArrow = 'prev' | 'next' | 'close' | null;\n\n/**\n * Every decision that depends on which way a menubar lays out, resolved from\n * its orientation and writing direction by {@link resolveMenubarAxis}.\n */\nexport interface MenubarAxis {\n /** Side a trigger's menu opens on when neither the trigger nor the scope sets one. */\n readonly side: FloatingSide;\n /** Key on a trigger that opens its menu with the first item focused. */\n readonly openFirstKey: 'ArrowDown' | 'ArrowLeft' | 'ArrowRight';\n /** Key on a trigger that opens its menu with the last item focused, `null` when none does. */\n readonly openLastKey: 'ArrowUp' | null;\n /** What `ArrowLeft` / `ArrowRight` do on an item of the open menu. */\n readonly inMenu: {\n readonly ArrowLeft: MenubarInMenuArrow;\n readonly ArrowRight: MenubarInMenuArrow;\n };\n}\n\nconst HORIZONTAL_LTR: MenubarAxis = {\n side: 'bottom',\n openFirstKey: 'ArrowDown',\n openLastKey: 'ArrowUp',\n inMenu: { ArrowLeft: 'prev', ArrowRight: 'next' },\n};\n\nconst HORIZONTAL_RTL: MenubarAxis = {\n side: 'bottom',\n openFirstKey: 'ArrowDown',\n openLastKey: 'ArrowUp',\n inMenu: { ArrowLeft: 'next', ArrowRight: 'prev' },\n};\n\nconst VERTICAL_LTR: MenubarAxis = {\n side: 'right',\n openFirstKey: 'ArrowRight',\n openLastKey: null,\n inMenu: { ArrowLeft: 'close', ArrowRight: null },\n};\n\nconst VERTICAL_RTL: MenubarAxis = {\n side: 'left',\n openFirstKey: 'ArrowLeft',\n openLastKey: null,\n inMenu: { ArrowLeft: null, ArrowRight: 'close' },\n};\n\n/**\n * Resolves a menubar's {@link MenubarAxis}. A horizontal bar opens each menu\n * below its trigger, opens with `ArrowDown` / `ArrowUp`, and switches between\n * sibling menus with the horizontal arrows inside a menu. A vertical bar opens\n * each menu beside it, on the inline-end side, opens with the inline-end arrow,\n * and inside a menu the inline-start arrow closes the menu back to the bar,\n * while the inline-end arrow has no sibling menu to reach.\n */\nexport function resolveMenubarAxis(\n orientation: MenubarOrientation,\n dir: WritingDirection,\n): MenubarAxis {\n if (orientation === 'vertical') {\n return dir === 'rtl' ? VERTICAL_RTL : VERTICAL_LTR;\n }\n return dir === 'rtl' ? HORIZONTAL_RTL : HORIZONTAL_LTR;\n}\n","import { InjectionToken } from '@angular/core';\n\nimport type { ForMenuContext } from './menu-context';\n\n/**\n * A submenu as its parent menu sees it while it holds the parent's open-child\n * slot.\n */\nexport interface MenuOpenChild {\n /** The submenu's own menu context, which keys the slot of its own open child. */\n readonly context: ForMenuContext;\n /**\n * Closes the submenu because a menu above it is closing: its `open` model is\n * written `false` and its `(openChange)` emits, no focus moves, and the close\n * does not propagate up the chain.\n */\n closeWithParent(): void;\n /**\n * Closes the submenu because a sibling took its parent's slot. Focus returns\n * to its trigger only when it was inside the submenu's open chain.\n */\n closeForSibling(): void;\n /**\n * Whether the pointer is travelling from the submenu's trigger toward its\n * content inside the armed pointer-grace corridor.\n */\n pointerGraceArmed(): boolean;\n}\n\n/**\n * Which submenu each menu holds open. A menu holds at most one open submenu, so\n * the registry is the chain of open levels below every menu context: a root\n * closes that chain before it closes, and a sub-trigger reads a sibling's\n * pointer-grace state through it before it schedules a hover-open.\n */\nexport class MenuOpenChain {\n readonly #openChildren = new WeakMap<ForMenuContext, MenuOpenChild>();\n readonly #graceWaiters = new WeakMap<ForMenuContext, () => void>();\n\n /** The submenu `parent` holds open, or `null`. */\n openChild(parent: ForMenuContext): MenuOpenChild | null {\n return this.#openChildren.get(parent) ?? null;\n }\n\n /**\n * Makes `child` the open submenu of `parent`, closing the previous holder\n * through {@link MenuOpenChild.closeForSibling} when it is a different submenu.\n */\n claim(parent: ForMenuContext, child: MenuOpenChild): void {\n const previous = this.#openChildren.get(parent);\n this.#openChildren.set(parent, child);\n if (previous && previous !== child) {\n previous.closeForSibling();\n }\n }\n\n /** Clears `parent`'s open-child slot when `child` holds it. */\n release(parent: ForMenuContext, child: MenuOpenChild): void {\n if (this.#openChildren.get(parent) === child) {\n this.#openChildren.delete(parent);\n }\n }\n\n /**\n * Closes every submenu open below `parent`, deepest first, through\n * {@link MenuOpenChild.closeWithParent}. Every menu context calls it from the\n * close transition all of its close paths pass through.\n */\n closeOpenChildChain(parent: ForMenuContext): void {\n const chain: MenuOpenChild[] = [];\n let child = this.#openChildren.get(parent);\n while (child && !chain.includes(child)) {\n chain.push(child);\n child = this.#openChildren.get(child.context);\n }\n for (const level of chain.reverse()) {\n level.closeWithParent();\n }\n }\n\n /**\n * Holds a hover-open of a submenu of `parent` until the pointer-grace corridor\n * of the open sibling ends. A later call replaces the waiting one.\n */\n deferUntilGraceEnds(parent: ForMenuContext, resume: () => void): void {\n this.#graceWaiters.set(parent, resume);\n }\n\n /**\n * The pointer-grace corridor of `parent`'s open submenu ended without the\n * pointer reaching its content: runs the hover-open waiting on it, if any.\n */\n graceEnded(parent: ForMenuContext): void {\n const resume = this.#graceWaiters.get(parent);\n if (resume) {\n this.#graceWaiters.delete(parent);\n resume();\n }\n }\n}\n\n/** The application's {@link MenuOpenChain}. */\nexport const MENU_OPEN_CHAIN = new InjectionToken<MenuOpenChain>('MENU_OPEN_CHAIN', {\n providedIn: 'root',\n factory: () => new MenuOpenChain(),\n});\n","import { computed, InjectionToken, signal, type Signal, type WritableSignal } from '@angular/core';\nimport type { ReferenceElement, VirtualElement } from '@floating-ui/dom';\n\nimport type { FloatingAlign, FloatingSide } from '../floating/floating';\nimport { type RootedHandle, RootedRegistry } from 'forty-cdk/core';\nimport type { ForMenuContext } from './menu-context';\n\n/**\n * Builds a floating-ui `VirtualElement` pinned to a by-value rect snapshot, so\n * later layout changes never shift the anchor. A 0×0 box models a pointer\n * position; a real box models the focused element a keyboard activation\n * anchored at.\n */\nfunction menuVirtualAnchor(x: number, y: number, width: number, height: number): VirtualElement {\n return {\n getBoundingClientRect: () => ({\n x,\n y,\n width,\n height,\n top: y,\n left: x,\n right: x + width,\n bottom: y + height,\n toJSON() {\n return this;\n },\n }),\n };\n}\n\n/**\n * Per-opener override of a menu root's **placement** inputs, applied only while\n * that opener is the active one. Every key is optional and an omitted one\n * resolves the root's own input, so an opener that overrides nothing positions\n * exactly as the root does.\n *\n * It carries the four values an opener's own geometry can legitimately decide.\n * The root keeps the rest of the positioning surface (`avoidCollisions`,\n * `collisionPadding`, `sticky`, …), which is collision / viewport policy for the\n * surface rather than a property of the opener that fired.\n *\n * The canonical case is a `[forMenu]` shared by heterogeneous openers: a button\n * opener wants the few pixels of clearance `[forDropdownMenu]` seeds, while a\n * pointer-anchored right-click region wants to sit flush at the cursor.\n */\nexport interface MenuOpenerPositioning {\n /** Side the menu is anchored to for this opener's opens. */\n readonly side?: FloatingSide;\n /** Alignment along the chosen side for this opener's opens. */\n readonly align?: FloatingAlign;\n /** Gap (px) between this opener's anchor and the menu along the main axis. */\n readonly sideOffset?: number;\n /** Gap (px) along the cross axis for this opener's opens. */\n readonly alignOffset?: number;\n}\n\n/** What an opener declares about itself when it registers with a menu root. */\nexport interface MenuOpenerOptions {\n /** The opener's own aria-wiring id, so two openers on one root never emit the same `id`. */\n readonly id: Signal<string>;\n /**\n * Whether a pointer-down on this opener counts as \"inside\" the menu. A\n * toggle-style opener (a `[forDropdownMenuTrigger]` button) must be exempt,\n * or its own click would also fire pointer-down-outside and double-close. A\n * right-click region must not be, so a left-click on it closes the menu like\n * any other outside click. Defaults to `false`.\n */\n readonly dismissibleExempt?: boolean;\n /**\n * Whether this opener's own accessible name is a valid name for the menu\n * surface. A discrete labelling control (a `[forDropdownMenuTrigger]` button)\n * passes `true`, so the surface can fall back to\n * `aria-labelledby=\"<openerId>\"`; a right-click region\n * (`[forContextMenuTrigger]`) passes `false`, because pointing the menu's name\n * at a whole row would announce the row's entire text. Defaults to `false` —\n * the conservative answer, which is also what a root with no resolvable active\n * opener reports.\n */\n readonly labelsMenu?: boolean;\n /**\n * This opener's placement override, read while it is the active one. Passed as\n * a signal so a bound `[menuPositioning]` flows through without\n * re-registering the element. Omitting it (and emitting `null`) resolves the\n * root's own positioning inputs.\n */\n readonly positioning?: Signal<MenuOpenerPositioning | null>;\n}\n\nexport interface MenuOpenerHandle extends RootedHandle<object> {\n readonly host: HTMLElement;\n readonly id: Signal<string>;\n readonly dismissibleExempt: boolean;\n readonly labelsMenu: boolean;\n readonly positioning: Signal<MenuOpenerPositioning | null> | null;\n readonly virtualAnchor: WritableSignal<ReferenceElement | null>;\n}\n\nexport const MENU_OPENERS = new InjectionToken<RootedRegistry<object, MenuOpenerHandle>>(\n 'MENU_OPENERS',\n { providedIn: 'root', factory: () => new RootedRegistry() },\n);\n\nexport function createMenuOpenerHandle(\n host: HTMLElement,\n root: Signal<object | null>,\n options: MenuOpenerOptions,\n): MenuOpenerHandle {\n return {\n host,\n root,\n id: options.id,\n dismissibleExempt: options.dismissibleExempt ?? false,\n labelsMenu: options.labelsMenu ?? false,\n positioning: options.positioning ?? null,\n virtualAnchor: signal<ReferenceElement | null>(null),\n };\n}\n\n/**\n * The opener protocol a multi-opener menu root exposes. Deliberately **not**\n * part of `ForMenuContext`: how openers drive a root is the piece protocol the\n * library refactors freely, whereas `ForMenuContext` is the blessed consumer\n * read surface. It stays out of every stable entry point's barrel and out of\n * every public signature — the trigger directives resolve it by narrowing their\n * already-resolved root with {@link asMenuOpenerRegistration}.\n */\nexport interface MenuOpenerRegistration {\n /**\n * Marks `opener` as the opener driving the current open. Return-focus, the\n * surface's `aria-labelledby` fallback, and the anchor all resolve against it.\n * `returnFocusTarget` records where focus returns for this open instead of\n * the opener's host — the focused descendant a keyboard activation started\n * from.\n */\n activateOpener(opener: MenuOpenerHandle, returnFocusTarget?: HTMLElement | null): void;\n releaseOpener(opener: MenuOpenerHandle): void;\n /**\n * The element focus returns to when the menu closes: the target the active\n * opener recorded for this open while it is still in the document, else the\n * active opener itself.\n */\n returnFocusTarget(): HTMLElement | null;\n /** Anchors the active opener's next open at a 0×0 point in viewport coordinates. */\n setVirtualAnchor(x: number, y: number): void;\n /** Anchors the active opener's next open at a by-value snapshot of `rect`. */\n setVirtualAnchorFromRect(rect: DOMRect): void;\n}\n\n/**\n * Narrows a resolved menu root to its opener protocol, or `null` when the root\n * does not implement one. Every root built on `MenuOverlayHost` does;\n * `[forMenubar]`'s multiplexed context does not, because the bar owns its own\n * trigger multiplexing.\n */\nexport function asMenuOpenerRegistration(root: object): MenuOpenerRegistration | null {\n const candidate = root as Partial<MenuOpenerRegistration>;\n return typeof candidate.activateOpener === 'function'\n ? (candidate as MenuOpenerRegistration)\n : null;\n}\n\n/**\n * The element a menu returns focus to on close: the opener registry's per-open\n * target on a root that has one, the context's `trigger` otherwise.\n */\nexport function menuReturnFocusTarget(ctx: Pick<ForMenuContext, 'trigger'>): HTMLElement | null {\n const openers = asMenuOpenerRegistration(ctx);\n return openers ? openers.returnFocusTarget() : ctx.trigger();\n}\n\nexport function releaseMenuOpener(opener: MenuOpenerHandle): void {\n const root = opener.root();\n if (root !== null) {\n asMenuOpenerRegistration(root)?.releaseOpener(opener);\n }\n}\n\n/**\n * The registry of openers behind a menu root. Several triggers may drive one\n * menu definition, which is what lets `[forMenu]` be declared once and opened\n * from many places.\n *\n * Everything the mounted surface reads resolves against the **active** opener:\n * the element return-focus lands on, the id the surface names itself after,\n * whether that id is a valid name at all, the floating-ui anchor, and the\n * placement override that anchor is measured with. \"Active\" is whichever opener\n * last called {@link activate}, falling back to the newest opener when every\n * registered one sits on the same element — so a single-opener root and a\n * programmatic open resolve unambiguously.\n *\n * Each opener carries its own optional virtual anchor, so switching openers\n * switches the anchor with no clearing step: a pointer-anchored right-click\n * opener keeps its `VirtualElement` while a button opener keeps resolving to its\n * own element.\n */\nexport class MenuOpenerRegistry {\n readonly #seedId: Signal<string>;\n readonly #openers: Signal<readonly MenuOpenerHandle[]>;\n readonly #activeOpener = signal<MenuOpenerHandle | null>(null);\n #returnFocusTarget: HTMLElement | null = null;\n #activatedSinceMount = false;\n\n readonly #active = computed<MenuOpenerHandle | null>(() => {\n const openers = this.#openers();\n const active = this.#activeOpener();\n if (active !== null && openers.includes(active)) {\n return active;\n }\n const newest = openers.at(-1);\n return newest !== undefined && openers.every((opener) => opener.host === newest.host)\n ? newest\n : null;\n });\n\n /**\n * Id of the opener driving the current open, falling back to the root's seeded\n * trigger id while no single opener is resolvable. Never the empty string, so\n * the surface's `aria-labelledby` fallback keeps the shape it had when the id\n * lived on the root.\n */\n readonly id: Signal<string>;\n\n /**\n * The active opener's element — the return-focus target, unless the open\n * recorded one of its own (see {@link returnFocusTarget}).\n */\n readonly element = computed<HTMLElement | null>(() => this.#active()?.host ?? null);\n\n /**\n * The active opener's floating-ui anchor: its virtual anchor when it set one\n * (a pointer / rect activation), otherwise its own element.\n */\n readonly anchor = computed<ReferenceElement | null>(() => {\n const active = this.#active();\n if (active === null) {\n return null;\n }\n return active.virtualAnchor() ?? active.host;\n });\n\n /**\n * The active opener's virtual anchor only — `null` until an opener sets one.\n * `[forContextMenu]` resolves its anchor through this so a right-click menu\n * with no recorded pointer position stays unanchored rather than falling back\n * to its whole right-click region.\n */\n readonly virtualAnchor = computed<ReferenceElement | null>(\n () => this.#active()?.virtualAnchor() ?? null,\n );\n\n /** Every registered opener that asked to count as \"inside\" the menu. */\n readonly dismissibleExemptions = computed<readonly HTMLElement[]>(() =>\n this.#openers()\n .filter((opener) => opener.dismissibleExempt)\n .map((opener) => opener.host),\n );\n\n /**\n * Whether the **active** opener's accessible name is a valid name for the menu\n * surface, so `[forMenuContent]` may fall back to\n * `aria-labelledby=\"<openerId>\"`. Per-opener rather than per-root because a\n * shared menu's openers are heterogeneous — a button opener is a labelling\n * control, a right-click region is not — and the answer therefore flips as the\n * menu is opened from a different one.\n *\n * `false` while no single opener is resolvable: the surface would otherwise\n * name itself after the root's seeded trigger id, which no element carries\n * once every opener owns an id of its own.\n */\n readonly labelsMenu = computed<boolean>(() => this.#active()?.labelsMenu ?? false);\n\n /**\n * The **active** opener's placement override, or `null` when it declared none\n * (and while no single opener is resolvable). Per-opener for the same reason\n * the anchor is: a shared menu's openers are heterogeneous, so the offsets a\n * button opener wants are not the ones a pointer-anchored region wants. A\n * root resolves each key against its own input — `positioning()?.x ??\n * xInput()` — so an opener that overrides nothing changes nothing.\n */\n readonly positioning = computed<MenuOpenerPositioning | null>(\n () => this.#active()?.positioning?.() ?? null,\n );\n\n constructor(seedId: Signal<string>, openers: Signal<readonly MenuOpenerHandle[]>) {\n this.#seedId = seedId;\n this.#openers = openers;\n this.id = computed(() => this.#active()?.id() ?? this.#seedId());\n }\n\n activate(opener: MenuOpenerHandle, returnFocusTarget: HTMLElement | null = null): void {\n this.#activeOpener.set(opener);\n this.#returnFocusTarget = returnFocusTarget;\n this.#activatedSinceMount = true;\n }\n\n release(opener: MenuOpenerHandle): void {\n if (this.#activeOpener() === opener) {\n this.#activeOpener.set(null);\n this.#returnFocusTarget = null;\n }\n }\n\n mountSurface(): void {\n if (!this.#activatedSinceMount) {\n this.#returnFocusTarget = null;\n }\n this.#activatedSinceMount = false;\n }\n\n /**\n * The return-focus target of the current open: the one {@link activate}\n * recorded for it while it is still in the document and its opener is still\n * the active one, else the active opener. Read at close time rather than\n * derived, because a menu action may remove the recorded element from the\n * document.\n */\n returnFocusTarget(): HTMLElement | null {\n const element = this.element();\n const target = this.#returnFocusTarget;\n const opener = this.#activeOpener();\n return target !== null && target.isConnected && opener !== null && this.#active() === opener\n ? target\n : element;\n }\n\n setVirtualAnchor(x: number, y: number): void {\n this.#active()?.virtualAnchor.set(menuVirtualAnchor(x, y, 0, 0));\n }\n\n setVirtualAnchorFromRect(rect: DOMRect): void {\n this.#active()?.virtualAnchor.set(menuVirtualAnchor(rect.x, rect.y, rect.width, rect.height));\n }\n}\n","import { inject, type ModelSignal, type Signal } from '@angular/core';\nimport type { ReferenceElement } from '@floating-ui/dom';\n\nimport { type ListNavigationAction, type VetoableNativeEvent } from 'forty-cdk/core';\nimport {\n OverlayController,\n type OverlayEmitTargets,\n type OverlayTransitionOptions,\n} from '../overlay-controller/overlay-controller';\nimport {\n type MenuOpenerHandle,\n type MenuOpenerPositioning,\n MenuOpenerRegistry,\n} from './menu-opener-registry';\nimport type { ForMenuCloseReason, ForMenuContext } from './menu-context';\nimport { createMenuItemList, type MenuItemHandle, type MenuItemList } from './menu-item-list';\nimport { MENU_OPEN_CHAIN } from './menu-open-chain';\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 extends OverlayEmitTargets {\n /**\n * The menu context the overlay backs. Every close of it first closes the\n * submenus open below it, through the {@link MENU_OPEN_CHAIN} slot keyed by\n * this context.\n */\n readonly context: ForMenuContext;\n readonly open: ModelSignal<boolean>;\n readonly disabled: Signal<boolean>;\n readonly dismissible: Signal<boolean>;\n readonly loop: Signal<boolean>;\n readonly openers: Signal<readonly MenuOpenerHandle[]>;\n\n /**\n * Optional side effect run after `openMenu` resolves the open, receiving the\n * resolved initial-focus target. `[forMenuSub]` uses it to cancel in-flight\n * hover scheduling and set its focus-suppression flags from\n * `options.suppressFocusMoves` (a keyboard / click open supersedes hover).\n * Top-level roots (`[forDropdownMenu]` / `[forContextMenu]`) pass neither\n * hook.\n *\n * It also runs when `openMenu` re-targets an **already-open** menu (no model\n * write, focus moved instead), so a pending hover-close is still cancelled by\n * an open key pressed on a mounted submenu.\n */\n readonly onOpen?: (initialFocus: 'first' | 'last', options: OverlayTransitionOptions) => void;\n\n /**\n * Optional side effect run after `closeMenu` flips `open` to `false`,\n * receiving the close reason and the transition options. `[forMenuSub]` uses\n * it to cancel in-flight hover scheduling, set its focus-suppression flags\n * from `options.suppressFocusMoves`, and propagate the close upward through\n * the menu chain for every reason except `'escape'` / `'hover'` /\n * `'programmatic'`. Top-level roots pass neither hook. It runs after the\n * submenus open below the menu have been closed.\n */\n readonly onClose?: (reason: ForMenuCloseReason, options: OverlayTransitionOptions) => void;\n}\n\n/**\n * Shared coordination behaviour of the menu overlay roots — `ForDropdownMenu`,\n * `ForContextMenu`, `ForMenu` and `ForMenuSub` — which share the same\n * item-collection / typeahead / navigate / dismissible shape. Menubar's per-bar\n * menu is not one of them: it composes `MenuItemList` and\n * {@link OverlayController} directly.\n *\n * The helper owns:\n *\n * - the item list (`MenuItemList`: the item `Collection`, typeahead and the navigate / focus\n * moves), shared with `[forMenubar]`'s multiplexed menu context,\n * - the opener registry: every trigger that can open this menu, which one is driving the current\n * open, and the per-opener id / anchor / labelling policy resolved against it,\n * - the menu vocabulary over the shared {@link OverlayController} — `'first' | 'last'` initial\n * focus, `ForMenuCloseReason`, the `'pointer' | 'keyboard'` activation modality, and\n * `openMenu`'s already-open re-focus branch.\n *\n * Everything below that vocabulary — the trigger / content slots and their ids, the\n * initial-focus and close-reason state, the `disabled`-gated open / close / toggle transitions,\n * the outside / Escape forwarders, `requestClose`, and the auto-focus vetoes — is the shared\n * controller's, declared once and composed here.\n *\n * It does not own:\n *\n * - the resolved `anchor` signal, which each root derives differently — from the trigger element,\n * from a virtual anchor, or from the active opener,\n * - `dismissibleExemptions`, since only some roots exempt their trigger to stop a click toggle\n * double-firing as a pointer-down-outside,\n * - the `input()` / `output()` / `model()` declarations, which must stay on the directive class for\n * Angular's template binding to see them.\n *\n * Construct via `createMenuOverlay` from a directive's field initializer, so the helper's `inject()`\n * calls resolve through the directive's injector.\n */\nexport class MenuOverlay<H extends MenuItemHandle = MenuItemHandle> {\n readonly #itemList: MenuItemList<H>;\n\n readonly #openers: MenuOpenerRegistry;\n readonly #controller: OverlayController<'first' | 'last', ForMenuCloseReason>;\n\n /**\n * Id of the opener driving the current open — the active opener's own id when\n * it owns one, else the seeded `<idPrefix>-trigger-*` fallback. Non-empty from\n * construction, so `[forMenuContent]`'s `aria-labelledby` fallback keeps the\n * shape it had when a single id lived on the root.\n */\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 /** Where focus should land when the menu mounts. Set by triggers before flipping `open`. */\n readonly initialFocus: Signal<'first' | 'last'>;\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: Signal<ForMenuCloseReason | null>;\n\n /**\n * The focusable element the menu should return focus to on close — the opener\n * that actually opened this instance, so a menu shared by several openers\n * hands focus back to the one the user used.\n */\n readonly trigger: Signal<HTMLElement | null>;\n\n /** The mounted `[forMenuContent]` element, or `null` while the menu is closed. */\n readonly content: Signal<HTMLElement | null>;\n\n /**\n * The active opener's floating-ui anchor: its virtual anchor when it recorded\n * one, else its own element. `[forMenu]` resolves its `anchor` through this so\n * the surface follows whichever opener fired.\n */\n readonly openerAnchor: Signal<ReferenceElement | null>;\n\n /**\n * The active opener's virtual anchor only, `null` until one is recorded.\n * `[forContextMenu]` resolves its `anchor` through this so a menu with no\n * recorded pointer position stays unanchored rather than falling back to its\n * whole right-click region.\n */\n readonly openerVirtualAnchor: Signal<ReferenceElement | null>;\n\n /** Registered openers that count as \"inside\" for outside-dismissal. */\n readonly openerExemptions: Signal<readonly HTMLElement[]>;\n\n /**\n * Whether the active opener is a discrete labelling control, so\n * `[forMenuContent]` may name itself `aria-labelledby=\"<triggerId>\"`.\n * `[forMenu]` exposes this as its `ForMenuContext.triggerLabelsMenu` so a\n * shared menu's name follows whichever opener fired.\n */\n readonly openerLabelsMenu: Signal<boolean>;\n\n /**\n * The active opener's placement override, `null` when it declared none. Each\n * root resolves its `side` / `align` / `sideOffset` / `alignOffset` against\n * its own input through this, so a shared menu positions per the opener that\n * fired while an opener with no override keeps the root's values.\n */\n readonly openerPositioning: Signal<MenuOpenerPositioning | null>;\n\n constructor(idPrefix: string, hooks: MenuOverlayHooks) {\n const openChain = inject(MENU_OPEN_CHAIN);\n this.#itemList = createMenuItemList<H>(() => hooks.loop());\n let openers!: MenuOpenerRegistry;\n this.#controller = new OverlayController<'first' | 'last', ForMenuCloseReason>({\n idPrefix,\n createTrigger: (mintId) => {\n openers = new MenuOpenerRegistry(mintId(), hooks.openers);\n return openers;\n },\n defaultInitialFocus: 'first',\n disabled: hooks.disabled,\n dismissible: hooks.dismissible,\n isOpen: () => hooks.open(),\n setOpen: (open) => hooks.open.set(open),\n emit: hooks,\n escapeReason: 'escape',\n programmaticReason: 'programmatic',\n onOpen: hooks.onOpen,\n onClose: (reason, options) => {\n openChain.closeOpenChildChain(hooks.context);\n hooks.onClose?.(reason, options);\n },\n });\n this.#openers = openers;\n this.triggerId = this.#controller.triggerId;\n this.contentId = this.#controller.contentId;\n this.initialFocus = this.#controller.initialFocus;\n this.lastCloseReason = this.#controller.lastCloseReason;\n this.trigger = this.#controller.trigger;\n this.content = this.#controller.content;\n this.openerAnchor = this.#openers.anchor;\n this.openerVirtualAnchor = this.#openers.virtualAnchor;\n this.openerExemptions = this.#openers.dismissibleExemptions;\n this.openerLabelsMenu = this.#openers.labelsMenu;\n this.openerPositioning = this.#openers.positioning;\n }\n\n setInitialFocus(target: 'first' | 'last'): void {\n this.#controller.setInitialFocus(target);\n }\n\n activateOpener(opener: MenuOpenerHandle, returnFocusTarget: HTMLElement | null = null): void {\n this.#openers.activate(opener, returnFocusTarget);\n }\n\n releaseOpener(opener: MenuOpenerHandle): void {\n this.#openers.release(opener);\n }\n\n /**\n * The element focus returns to on close: the target the active opener\n * recorded for this open while it is still in the document, else\n * {@link trigger}.\n */\n returnFocusTarget(): HTMLElement | null {\n return this.#openers.returnFocusTarget();\n }\n\n setVirtualAnchor(x: number, y: number): void {\n this.#openers.setVirtualAnchor(x, y);\n }\n\n setVirtualAnchorFromRect(rect: DOMRect): void {\n this.#openers.setVirtualAnchorFromRect(rect);\n }\n\n registerContent(el: HTMLElement): void {\n this.#openers.mountSurface();\n this.#controller.registerContent(el);\n }\n\n unregisterContent(el: HTMLElement): void {\n this.#controller.unregisterContent(el);\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): boolean {\n return 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 * An imperative escape hatch for an explicit first / last move, independent of the resolved\n * {@link initialFocus} target. No piece of the library routes through it — they all go through\n * {@link focusInitialEnabledItem} — and `ForMenuContext` does not declare it.\n */\n focusFirstEnabledItem(): boolean {\n return this.#itemList.focusFirstEnabledItem(this.#controller.consumeInitialHighlight());\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). The\n * granular counterpart of {@link focusFirstEnabledItem}, and like it an\n * imperative escape hatch rather than a `ForMenuContext` member.\n */\n focusLastEnabledItem(): boolean {\n return this.#itemList.focusLastEnabledItem(this.#controller.consumeInitialHighlight());\n }\n\n /**\n * Focuses the first or last enabled item per `target`, resolving the mapping\n * through the shared `MenuItemList` rather than re-deriving it here. Used by\n * the mount path (through the `ForMenuContext` contract) and by `openMenu`'s\n * already-open re-focus branch. 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 focusInitialEnabledItem(target: 'first' | 'last'): boolean {\n return this.#itemList.focusInitialEnabledItem(\n target,\n this.#controller.consumeInitialHighlight(),\n );\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 this.#controller.toggle(initialFocus, { highlight: modality === 'keyboard' });\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 * `options` is forwarded verbatim to the `onOpen` hook — `[forMenuSub]`'s\n * hover-open passes `{ suppressFocusMoves: true }` so the mount does not\n * pull focus off whatever the user was on.\n *\n * When the menu is **already open** there is no state transition (and\n * therefore no `(openChange)` emit): focus moves straight to the requested\n * first / last enabled item instead, so an APG open key pressed on a trigger\n * whose menu is already mounted is never a dead key. The menu is never\n * toggled closed — the open keys have no close semantics in the APG patterns\n * — and a menu with no enabled item moves nothing rather than pulling focus\n * onto an item-less surface. The re-focus is not gated on the\n * `(autoFocusOnOpen)` veto: that veto covers the mount's automatic focus\n * move, and honouring it here would silently restore the dead key for\n * consumers who opted out of auto-focus-on-open. It *is* skipped for a\n * `{ suppressFocusMoves: true }` transition, whose whole contract is that no\n * imperative focus move may happen (`[forMenuSub]`'s hover-open).\n *\n * This branch is the menu's own: it stays out of the shared controller, which\n * reports the already-open case as an outcome rather than acting on it.\n */\n openMenu(\n initialFocus: 'first' | 'last' = 'first',\n modality: MenuActivationModality = 'keyboard',\n options: OverlayTransitionOptions = {},\n ): void {\n const outcome = this.#controller.open(initialFocus, {\n highlight: modality === 'keyboard',\n transition: options,\n });\n if (outcome === 'already-open' && !options.suppressFocusMoves) {\n this.focusInitialEnabledItem(initialFocus);\n }\n }\n\n /**\n * Closes the menu, recording `reason` as the `lastCloseReason` the content\n * pieces read. `options` is forwarded verbatim to the `onClose` hook —\n * `[forMenuSub]`'s hover-close passes `{ suppressFocusMoves: true }` so the\n * unmount does not yank focus back to the sub-trigger.\n */\n closeMenu(reason: ForMenuCloseReason, options: OverlayTransitionOptions = {}): void {\n this.#controller.close(reason, options);\n }\n\n emitEscapeKeyDown(event: KeyboardEvent): void {\n this.#controller.emitEscapeKeyDown(event);\n }\n\n emitPointerDownOutside(veto: VetoableNativeEvent<PointerEvent>): void {\n this.#controller.emitPointerDownOutside(veto);\n }\n\n emitFocusOutside(veto: VetoableNativeEvent<FocusEvent>): void {\n this.#controller.emitFocusOutside(veto);\n }\n\n emitInteractOutside(veto: VetoableNativeEvent<PointerEvent | FocusEvent>): void {\n this.#controller.emitInteractOutside(veto);\n }\n\n requestClose(reason: 'pointerDownOutside' | 'focusOutside'): void {\n this.#controller.requestClose(reason);\n }\n\n emitAutoFocusOnOpen(): boolean {\n return this.#controller.emitAutoFocusOnOpen();\n }\n\n emitAutoFocusOnClose(): boolean {\n return this.#controller.emitAutoFocusOnClose();\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 MenuItemHandle = MenuItemHandle>(\n idPrefix: string,\n hooks: MenuOverlayHooks,\n): MenuOverlay<H> {\n return new MenuOverlay<H>(idPrefix, hooks);\n}\n","import { Directive, type Signal } from '@angular/core';\n\nimport { AnchoredOverlayPositioningBase } from '../floating/anchored-overlay-positioning-base';\nimport { type ListNavigationAction, type VetoableNativeEvent } from 'forty-cdk/core';\nimport type { ForMenuCloseReason } from './menu-context';\nimport type { MenuItemHandle } from './menu-item-list';\nimport type { MenuOpenerHandle } from './menu-opener-registry';\nimport type { MenuActivationModality, MenuOverlay } from './menu-overlay';\n\n/**\n * Abstract base that forwards the `MenuOverlay` coordination slice every menu\n * root re-exposes — `[forDropdownMenu]`, `[forContextMenu]`, `[forMenu]` and\n * `[forMenuSub]` all extend it. Each subclass owns its own `MenuOverlay`\n * instance (created with its own id prefix and lifecycle hooks) and exposes it\n * through the abstract `_overlay` accessor; the base implements the 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 four 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 flags).\n *\n * Kept generic over the item handle so the subclass's `MenuOverlay<H>` flows\n * through `registerItem` / `unregisterItem` without a cast.\n *\n * It also carries `AnchoredOverlayPositioningBase` for its subclasses: every\n * menu root is a trigger-anchored overlay, so inheriting the shared positioning\n * block here is what keeps the four of them from redeclaring it. The\n * `@Directive()` decorator is required for that inheritance — Angular only\n * collects signal inputs through a decorated chain.\n */\n@Directive()\nexport abstract class MenuOverlayHost<\n H extends MenuItemHandle = MenuItemHandle,\n> extends AnchoredOverlayPositioningBase {\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<ForMenuCloseReason | 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 /**\n * The `MenuOpenerRegistration` protocol, forwarded once for every root. Kept\n * `private` on purpose: it is the piece protocol, so it must stay out of the\n * roots' emitted `.d.ts` while remaining callable at runtime — which is what\n * the trigger directives' `asMenuOpenerRegistration` narrowing relies on.\n */\n private activateOpener(opener: MenuOpenerHandle, returnFocusTarget?: HTMLElement | null): void {\n this._overlay.activateOpener(opener, returnFocusTarget);\n }\n\n private releaseOpener(opener: MenuOpenerHandle): void {\n this._overlay.releaseOpener(opener);\n }\n\n private returnFocusTarget(): HTMLElement | null {\n return this._overlay.returnFocusTarget();\n }\n\n protected setVirtualAnchor(x: number, y: number): void {\n this._overlay.setVirtualAnchor(x, y);\n }\n\n protected setVirtualAnchorFromRect(rect: DOMRect): void {\n this._overlay.setVirtualAnchorFromRect(rect);\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): boolean {\n return 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 focusInitialEnabledItem(target: 'first' | 'last'): boolean {\n return this._overlay.focusInitialEnabledItem(target);\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: ForMenuCloseReason): 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 { DestroyRef, DOCUMENT, inject, Injectable, PLATFORM_ID } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\nimport { composedContains } from 'forty-cdk/core';\n\n/** Window (ms) hover opens stay suppressed after the last scroll that concerns an overlay. */\nexport const DEFAULT_SCROLL_DISMISS_SUPPRESSION_MS = 200;\n\n/**\n * Which scrolls concern one registered overlay. Both accessors are read when a\n * scroll is dispatched or a suppression is queried, so a trigger or surface\n * registered after the overlay is picked up.\n */\nexport interface ScrollDismissScope {\n /**\n * The element the overlay is anchored to. A scroll of an element that does\n * not contain it moves nothing the overlay is positioned against, so it\n * neither dismisses nor suppresses. `null`, or an anchor no longer in the\n * document, leaves every scroll in scope.\n */\n readonly anchor: () => Element | null;\n /**\n * The overlay's own surface. A scroll inside it (an `overflow: auto` region\n * in the content) neither dismisses nor suppresses.\n */\n readonly surface: () => Element | null;\n}\n\n/** Inputs for {@link ScrollDismissDispatcher.register}. */\nexport interface ScrollDismissOptions {\n /**\n * Closes the overlay and cancels its pending timers. Called synchronously on\n * every scroll in scope while {@link active} holds.\n */\n readonly dismiss: () => void;\n /** Narrows which scrolls dismiss and suppress. Omitted, every scroll does. */\n readonly scope?: ScrollDismissScope;\n /**\n * Whether a scroll has anything to dismiss: the overlay is open, or an open /\n * close timer is pending. Read before the scope, so an idle overlay costs one\n * call per scroll. Omitted, the registration is always active.\n */\n readonly active?: () => boolean;\n}\n\n/** Handle returned by {@link ScrollDismissDispatcher.register}. */\nexport interface ScrollDismissRegistration {\n /**\n * Whether a scroll in this registration's scope happened within the\n * suppression window. Hover opens bail while this returns `true`, so content\n * sliding under a stationary pointer cannot flicker the overlay open.\n * Always `false` on the server and after {@link unregister}.\n */\n isSuppressed(): boolean;\n /** Removes this registration. Idempotent; call it from a `DestroyRef` hook. */\n unregister(): void;\n}\n\ninterface Registration {\n readonly dismiss: () => void;\n readonly scope: ScrollDismissScope | undefined;\n readonly active: () => boolean;\n}\n\nconst ALWAYS_ACTIVE = (): boolean => true;\n\nconst SERVER_REGISTRATION: ScrollDismissRegistration = {\n isSuppressed: () => false,\n unregister: () => {},\n};\n\n/**\n * Application-scoped owner of the single capture-phase document `scroll`\n * listener shared by every hover-driven anchored overlay (Tooltip, HoverCard).\n *\n * When an ancestor scroll container moves its content under a stationary\n * cursor, the browser does not reliably dispatch `pointerleave` /\n * `pointerenter` on the triggers sliding past the pointer. On each scroll the\n * dispatcher therefore dismisses every active registration whose scope the\n * scroll concerns, and records the scrolled element with a timestamp. A\n * registration is suppressed while a recorded scroll within\n * {@link DEFAULT_SCROLL_DISMISS_SUPPRESSION_MS} concerns its own scope, so a\n * scroll elsewhere on the page, or inside the overlay's own surface, never\n * blocks its hover opens.\n *\n * One listener is installed with the first registration and removed with the\n * last. Per scroll the work is one map write plus one `active()` call per\n * registration; the containment walk runs only for active registrations, and\n * for idle ones only when their own hover asks whether it is suppressed.\n *\n * `providedIn: 'root'`, so it is one instance per application injector and is\n * garbage-collected with it. Internal core tier, exported for the tooltip /\n * hover-card entry points, never for consumers.\n */\n@Injectable({ providedIn: 'root' })\nexport class ScrollDismissDispatcher {\n readonly #doc = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n\n readonly #registrations = new Set<Registration>();\n readonly #recentScrolls = new Map<EventTarget | null, number>();\n #listener: AbortController | null = null;\n\n constructor() {\n inject(DestroyRef).onDestroy(() => {\n this.#listener?.abort();\n this.#listener = null;\n this.#registrations.clear();\n this.#recentScrolls.clear();\n });\n }\n\n /**\n * Registers an overlay for scroll dismissal and per-overlay suppression. Each\n * call is an independent registration, so registering the same callback\n * twice yields two handles that must both be unregistered. A no-op handle on\n * the server.\n */\n register(options: ScrollDismissOptions): ScrollDismissRegistration {\n if (!this.#isBrowser) {\n return SERVER_REGISTRATION;\n }\n const registration: Registration = {\n dismiss: options.dismiss,\n scope: options.scope,\n active: options.active ?? ALWAYS_ACTIVE,\n };\n this.#registrations.add(registration);\n this.#listen();\n return {\n isSuppressed: () =>\n this.#registrations.has(registration) && this.#suppresses(registration.scope),\n unregister: () => this.#unregister(registration),\n };\n }\n\n #listen(): void {\n if (this.#listener) {\n return;\n }\n this.#listener = new AbortController();\n this.#doc.addEventListener('scroll', (event) => this.#onScroll(event), {\n capture: true,\n passive: true,\n signal: this.#listener.signal,\n });\n }\n\n #unregister(registration: Registration): void {\n if (!this.#registrations.delete(registration) || this.#registrations.size > 0) {\n return;\n }\n this.#listener?.abort();\n this.#listener = null;\n this.#recentScrolls.clear();\n }\n\n #onScroll(event: Event): void {\n const now = Date.now();\n this.#recentScrolls.delete(event.target);\n this.#recentScrolls.set(event.target, now + DEFAULT_SCROLL_DISMISS_SUPPRESSION_MS);\n this.#pruneExpired(now);\n for (const registration of this.#registrations) {\n if (\n registration.active() &&\n (!registration.scope || scrollConcerns(event.target, registration.scope))\n ) {\n registration.dismiss();\n }\n }\n }\n\n #pruneExpired(now: number): void {\n for (const [target, until] of this.#recentScrolls) {\n if (until > now) {\n return;\n }\n this.#recentScrolls.delete(target);\n }\n }\n\n #suppresses(scope: ScrollDismissScope | undefined): boolean {\n const now = Date.now();\n this.#pruneExpired(now);\n for (const target of this.#recentScrolls.keys()) {\n if (!scope || scrollConcerns(target, scope)) {\n return true;\n }\n }\n return false;\n }\n}\n\nfunction scrollConcerns(target: EventTarget | null, scope: ScrollDismissScope): boolean {\n if (!(target instanceof Node)) {\n return true;\n }\n const surface = scope.surface();\n if (surface && composedContains(surface, target)) {\n return false;\n }\n const anchor = scope.anchor();\n if (!anchor || !anchor.isConnected) {\n return true;\n }\n return composedContains(target, anchor);\n}\n"],"mappings":";;;;;;;AAYA,SAAgB,iCAA8B;CAC5C,MAAM,aAAa,OAAO,gBAAgB;CAC1C,OAAO;EACL,aAAa,WAAW,UAAU,6BAA6B;EAC/D,cAAc,WAAW,UAAU,8BAA8B;EACjE,gBAAgB,WAAW,UAAU,gCAAgC;EACrE,iBAAiB,WAAW,UAAU,iCAAiC;EACvE,wBAAwB,WAAW,UAAU,yCAAyC;EACtF,aAAa,WAAW,UAAU,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,mBAAA;EAAA,YAAA;EAAA,SAAA;EAAA,UAAA;EAAA,MAAA;EAAuB,MAAA,CAAA;EAAA,QAAA,GAAA,gBAAA;CAAA,CAAA;CAAvB,OAAA,QAAA,GAAA,sBAAA;EAAA,YAAA;EAAA,SAAA;EAAA,UAAA;EAAA,MAAA;EAAuB,YADV;CAAM,CAAA;;AACnB,GAAA,yBAAA;CAAA,YAAA;CAAA,SAAA;CAAA,UAAA;CAAA,MAAA;CAAuB,YAAA,CAAA;EADnC,MAAA;EAAW,MAAA,CAAA,EAAE,YAAY,OAAM,CAAE;;;;AAmGlC,SAAS,eAAe,QAA4B,OAAyB;CAC3E,IAAI,EAAE,kBAAkB,OACtB,OAAO;CAET,MAAM,UAAU,MAAM,QAAO;CAC7B,IAAI,WAAW,iBAAiB,SAAS,MAAM,GAC7C,OAAO;CAET,MAAM,SAAS,MAAM,OAAM;CAC3B,IAAI,CAAC,UAAU,CAAC,OAAO,aACrB,OAAO;CAET,OAAO,iBAAiB,QAAQ,MAAM;AACxC"}
|
|
1
|
+
{"version":3,"file":"forty-cdk-core-anchored.mjs","names":[],"sources":["../../../projects/forty-cdk/core-anchored/src/floating/floating-custom-properties.ts","../../../projects/forty-cdk/core-anchored/src/floating/floating-direction.ts","../../../projects/forty-cdk/core-anchored/src/floating/run-positioning.ts","../../../projects/forty-cdk/core-anchored/src/floating/floating.ts","../../../projects/forty-cdk/core-anchored/src/floating/floating-arrow.ts","../../../projects/forty-cdk/core-anchored/src/floating/anchored-positioning-inputs.ts","../../../projects/forty-cdk/core-anchored/src/floating/anchored-form-value-control-base.ts","../../../projects/forty-cdk/core-anchored/src/floating/anchored-overlay-positioning-base.ts","../../../projects/forty-cdk/core-anchored/src/floating/item-aligned.ts","../../../projects/forty-cdk/core-anchored/src/hover-intent/hover-intent.ts","../../../projects/forty-cdk/core-anchored/src/pointer-grace/pointer-grace.ts","../../../projects/forty-cdk/core-anchored/src/hover-intent/hover-surface-state.ts","../../../projects/forty-cdk/core-anchored/src/overlay-controller/element-registry.ts","../../../projects/forty-cdk/core-anchored/src/overlay-controller/close-reason-state.ts","../../../projects/forty-cdk/core-anchored/src/overlay-controller/initial-focus-state.ts","../../../projects/forty-cdk/core-anchored/src/overlay-controller/overlay-controller.ts","../../../projects/forty-cdk/core-anchored/src/overlay-controller/overlay-shell.ts","../../../projects/forty-cdk/core-anchored/src/listbox-overlay/listbox-overlay-controller.ts","../../../projects/forty-cdk/core-anchored/src/menu-overlay/menu-context.ts","../../../projects/forty-cdk/core-anchored/src/menu-overlay/menu-item-list.ts","../../../projects/forty-cdk/core-anchored/src/menu-overlay/menubar-axis.ts","../../../projects/forty-cdk/core-anchored/src/menu-overlay/menu-open-chain.ts","../../../projects/forty-cdk/core-anchored/src/menu-overlay/menu-opener-registry.ts","../../../projects/forty-cdk/core-anchored/src/menu-overlay/menu-overlay.ts","../../../projects/forty-cdk/core-anchored/src/menu-overlay/menu-overlay-host.ts","../../../projects/forty-cdk/core-anchored/src/scroll-dismiss/scroll-dismiss-dispatcher.ts"],"sourcesContent":["import { inject } from '@angular/core';\nimport { CssVarNamespacer } from '@angular/platform-browser';\n\nexport interface FloatingCustomProperties {\n readonly anchorWidth: string;\n readonly anchorHeight: string;\n readonly availableWidth: string;\n readonly availableHeight: string;\n readonly contentTransformOrigin: string;\n readonly arrowOffset: string;\n}\n\nexport function injectFloatingCustomProperties(): FloatingCustomProperties {\n const namespacer = inject(CssVarNamespacer);\n return {\n anchorWidth: namespacer.namespace('--for-floating-anchor-width'),\n anchorHeight: namespacer.namespace('--for-floating-anchor-height'),\n availableWidth: namespacer.namespace('--for-floating-available-width'),\n availableHeight: namespacer.namespace('--for-floating-available-height'),\n contentTransformOrigin: namespacer.namespace('--for-floating-content-transform-origin'),\n arrowOffset: namespacer.namespace('--for-floating-arrow-offset'),\n };\n}\n","export function isFloatingRtl(el: Element): boolean {\n return el.ownerDocument.defaultView?.getComputedStyle(el).direction === 'rtl';\n}\n","import { isPlatformBrowser } from '@angular/common';\nimport {\n afterNextRender,\n effect,\n ElementRef,\n inject,\n PLATFORM_ID,\n type Signal,\n} from '@angular/core';\nimport {\n autoUpdate,\n computePosition,\n type ComputePositionReturn,\n type Middleware,\n type Placement,\n type ReferenceElement,\n} from '@floating-ui/dom';\n\nimport { injectPortal } from 'forty-cdk/core';\n\n/**\n * The positioner-specific work for a single open run, returned by\n * {@link PositioningConfig.computeAndApply}. The shared scaffold owns the\n * platform gate, portal, anti-flash baseline, `autoUpdate` loop, the\n * `!open()` / cancelled-run bail, the `translate` write, the `clip-path` drop,\n * the per-open {@link PositioningConfig.onFirstPosition} dispatch, and the\n * `.catch(() => {})`; a run supplies only the parts that genuinely differ\n * between positioners.\n */\nexport interface PositioningRun {\n /**\n * The requested placement handed to `@floating-ui/dom`'s `computePosition`.\n * (The strategy is always `'fixed'`, owned by the scaffold.)\n */\n readonly placement: Placement;\n\n /** The middleware stack handed to `computePosition` for this run. */\n readonly middleware: Middleware[];\n\n /**\n * Applies a resolved position. Runs on every `autoUpdate` frame, after the\n * scaffold has bailed on a mid-frame close, written the resolved `translate`,\n * and dropped the `clip-path` anti-flash baseline. Writes the positioner's\n * own `data-*` attributes and CSS variables (and, for the anchored\n * positioner, the arrow).\n */\n apply(result: ComputePositionReturn): void;\n\n /**\n * Resets everything the run wrote, invoked from the effect's `onCleanup`\n * when `open` flips back to `false`, the config changes while open, or the\n * host is destroyed. What is reset (and what is intentionally retained for\n * `animate.leave`) is the positioner's decision.\n */\n reset(): void;\n}\n\n/**\n * Configuration for {@link runPositioning}. Mirrors the shared shape of the\n * two positioners (`injectFloating`, `injectItemAlignedPositioner`) — the\n * reactive `reference` / `open`, the optional `portal` and anti-flash toggle —\n * and defers the positioner-specific compute + apply + reset to\n * {@link computeAndApply}.\n */\nexport interface PositioningConfig {\n /**\n * The anchor. Reactive — should emit `null` until the anchor is available;\n * positioning is skipped while `null` or `open` is `false`.\n */\n readonly reference: Signal<ReferenceElement | null>;\n\n /**\n * Whether the floating element is currently visible. `autoUpdate` is started\n * when this becomes `true` and torn down when it goes back to `false`.\n */\n readonly open: Signal<boolean>;\n\n /**\n * When `true` (default), the floating element is moved to `document.body` on\n * first render and removed on destroy. Set to `false` to keep it in its\n * declared parent (or when the caller already invokes `injectPortal()`).\n */\n readonly portal?: boolean;\n\n /**\n * When the signal returns anything other than `false` (the default when the\n * signal is omitted), the surface is clipped with `clip-path: inset(50%)`\n * until the first position resolves, so a CSS enter animation never flashes\n * at the viewport corner before the async `computePosition` lands.\n */\n readonly clipUntilPositioned?: Signal<boolean>;\n\n /**\n * Invoked once per **open cycle**, immediately after the first\n * `computePosition` of that cycle resolves and its `run.apply` has run —\n * i.e. after the portal move, after the `clip-path` anti-flash baseline is\n * dropped, and after the positioner has written its `data-*` / CSS vars.\n *\n * The semantics are **per-open, not per-run**: a positioner\n * config change while the surface stays open re-runs the effect (a new\n * positioning run), but this hook does **not** fire again — it fires only on\n * the run that first resolves after `open` transitions to `true`. A run that\n * is superseded (config change while open) or torn down (close / destroy)\n * before its `computePosition` resolves is cancelled: its resolution writes\n * nothing and never fires this hook. This matters because consumers use it to\n * seed one-shot state that a re-fire would corrupt — e.g. scrolling an active\n * option into view inside a freshly portaled listbox, which a per-run re-fire\n * would yank back mid-interaction on every side flip.\n */\n readonly onFirstPosition?: () => void;\n\n /**\n * Builds the per-run controller. Called once per open run, synchronously\n * inside the positioning effect, so its reactive reads (side, align,\n * offsets, selected option, …) register as effect dependencies and a change\n * while open re-runs the effect. Receives the floating element and the\n * resolved (non-null) reference.\n */\n readonly computeAndApply: (el: HTMLElement, reference: ReferenceElement) => PositioningRun;\n}\n\n/**\n * Shared scaffold behind the library's two `@floating-ui/dom` positioners —\n * `injectFloating` (the general anchored positioner) and\n * `injectItemAlignedPositioner` (the macOS-style over-trigger positioner for\n * `[forSelectContent]`). Must be called from an injection context, and takes the `ElementRef` it\n * lives on as the floating element.\n *\n * It owns the portal, the positioning effect and `autoUpdate`, and tears all three down\n * symmetrically so a re-open never inherits stale geometry. While closed the effect tracks only\n * `open` and `reference`, so an offset or side change on a closed overlay re-runs nothing. A\n * `computePosition` that loses its reference mid-frame is swallowed, since `autoUpdate` reschedules\n * on the next live frame.\n *\n * Until the first position resolves the surface wears a `clip-path` anti-flash baseline, re-armed\n * whenever a config change restarts an open run so it stays hidden at the retained stale position.\n * `clip-path` rather than `visibility: hidden` keeps the element focusable, so the overlay shell's\n * initial-focus move still lands while the surface is unpainted.\n *\n * Position is written to `translate`, never `transform`. CSS composes `translate` outside\n * `transform`, so a consumer's `scale` enter animation pivots in place instead of scaling the\n * position offset and dragging the surface in from the viewport corner — leaving `transform` free\n * for the consumer is the point.\n *\n * SSR-safe: `effect()` runs server-side, so the browser gate here is explicit.\n */\nexport function runPositioning(config: PositioningConfig): void {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const el = host.nativeElement;\n\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n return;\n }\n\n if (config.portal !== false) {\n injectPortal();\n }\n\n const shouldClip = (): boolean => config.clipUntilPositioned?.() !== false;\n\n afterNextRender(() => {\n Object.assign(el.style, {\n position: 'fixed',\n left: '0',\n top: '0',\n });\n if (shouldClip()) {\n el.style.clipPath = 'inset(50%)';\n }\n });\n\n let openCycleActive = false;\n let firstPositionFired = false;\n\n effect((onCleanup) => {\n const isOpen = config.open();\n const reference = config.reference();\n\n if (!isOpen || !reference) {\n openCycleActive = false;\n return;\n }\n\n if (!openCycleActive) {\n openCycleActive = true;\n firstPositionFired = false;\n }\n\n if (shouldClip()) {\n el.style.clipPath = 'inset(50%)';\n }\n\n const run = config.computeAndApply(el, reference);\n let cancelled = false;\n\n const cleanup = autoUpdate(reference, el, () => {\n computePosition(reference, el, {\n strategy: 'fixed',\n placement: run.placement,\n middleware: run.middleware,\n })\n .then((result) => {\n if (cancelled || !config.open()) {\n return;\n }\n el.style.translate = `${Math.round(result.x)}px ${Math.round(result.y)}px`;\n el.style.clipPath = '';\n run.apply(result);\n if (!firstPositionFired) {\n firstPositionFired = true;\n config.onFirstPosition?.();\n }\n })\n .catch(() => {});\n });\n\n onCleanup(() => {\n cancelled = true;\n cleanup();\n run.reset();\n });\n });\n}\n","import { type Signal } from '@angular/core';\nimport {\n type ComputePositionReturn,\n flip,\n type FlipOptions,\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 type { OverlayShellPositioner } from '../overlay-controller/overlay-shell';\nimport type { FloatingArrowMiddleware } from './floating-arrow';\nimport {\n type FloatingCustomProperties,\n injectFloatingCustomProperties,\n} from './floating-custom-properties';\nimport { isFloatingRtl } from './floating-direction';\nimport { runPositioning } from './run-positioning';\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\n/**\n * Direction floating-ui's `flip` middleware falls back to on the *perpendicular*\n * axis when no placement on the preferred axis fits. `'none'` (the default)\n * keeps floating-ui's historical behavior — only the opposite same-axis\n * placement is tried; `'start'` / `'end'` let the surface drop to a\n * perpendicular side (e.g. a right-anchored submenu dropping to `top` / `bottom`)\n * when both sides of the preferred axis overflow.\n */\nexport type FloatingFallbackAxisSideDirection = 'none' | 'start' | '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 and `arrowMiddleware` is set, the\n * middleware it builds is registered and the helper writes `position: absolute`, the resolved\n * `left` / `top` from floating-ui, and a side-aware\n * `var(--for-floating-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-floating-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 * Builds the middleware that positions `arrow`; pass `floatingArrowMiddleware`.\n * Without it an arrow element is never positioned.\n */\n readonly arrowMiddleware?: FloatingArrowMiddleware;\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 /**\n * Direction floating-ui's `flip` falls back to on the *perpendicular* axis\n * when no placement on the preferred axis fits. `'none'` (default) keeps the\n * historical behavior — only the opposite same-axis placement is tried; set\n * `'start'` / `'end'` to let a side-anchored surface (e.g. a submenu) drop to\n * a perpendicular side when both sides of the preferred axis overflow. Only\n * consulted when `avoidCollisions` is on.\n */\n readonly fallbackAxisSideDirection?: Signal<FloatingFallbackAxisSideDirection>;\n\n /**\n * Explicit ordered list of fallback placements handed to `flip`. Advanced\n * control; overrides floating-ui's axis-side heuristic when provided. Only\n * consulted when `avoidCollisions` is on.\n */\n readonly fallbackPlacements?: Signal<readonly Placement[] | undefined>;\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 * Invoked once per **open cycle**, on the first resolved position after\n * `open` transitions to `true` — after `@floating-ui/dom`'s async\n * `computePosition` lands, the helper drops the `clip-path` anti-flash\n * baseline, and the positioner has written its `data-*` / CSS vars.\n *\n * The semantics are **per-open, not per-run**: a positioner-config change\n * while the surface stays open re-runs the positioning effect, but this\n * callback does **not** re-fire — it fires only on the run that first\n * resolves after opening, and never while the surface stays closed. A run\n * superseded by a config change (or torn down by a close / destroy) before\n * its `computePosition` resolves is cancelled: its resolution writes nothing\n * and never fires this hook.\n *\n * This per-open guarantee is load-bearing for the seed-once consumers.\n * Because the hook runs strictly after the optional portal's `appendChild`\n * and after `computePosition` (so the `size` middleware's `max-height` is\n * already applied), it is the only moment a consumer can touch the\n * now-portaled, now-sized surface. Combobox uses it to scroll the active\n * descendant into view inside a `max-height`-constrained listbox whose\n * `scrollTop` the portal move reset to 0 — see `[forComboboxContent]`; a\n * per-run re-fire would yank that scroll back on every side flip.\n */\n readonly onFirstPosition?: () => void;\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. Under `rtl` the inline axis mirrors, so the same placement pivots\n * from `right top`.\n */\nfunction transformOriginFor(side: FloatingSide, align: FloatingAlign, rtl: boolean): 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 const start = rtl ? 'right' : 'left';\n const end = rtl ? 'left' : 'right';\n x = align === 'start' ? start : align === 'end' ? end : '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 * Assemble the options handed to floating-ui's `flip` middleware. Kept as a\n * pure function so the collision-fallback wiring (`fallbackAxisSideDirection`,\n * `fallbackPlacements`) is unit-testable without a live DOM — jsdom returns\n * zero rects, so `flip` never actually relocates there.\n *\n * `fallbackAxisSideDirection` is omitted (rather than passed as `'none'`) so the\n * emitted options match floating-ui's own default exactly, and\n * `fallbackPlacements` is omitted when empty / unset.\n */\nexport function buildFlipOptions(options: {\n readonly padding: number | Padding;\n readonly boundary: Element | Element[] | null;\n readonly fallbackAxisSideDirection: FloatingFallbackAxisSideDirection;\n readonly fallbackPlacements: readonly Placement[] | undefined;\n}): FlipOptions {\n const flipOptions: FlipOptions = { padding: options.padding };\n if (options.boundary) {\n flipOptions.boundary = options.boundary;\n }\n if (options.fallbackAxisSideDirection !== 'none') {\n flipOptions.fallbackAxisSideDirection = options.fallbackAxisSideDirection;\n }\n if (options.fallbackPlacements?.length) {\n flipOptions.fallbackPlacements = [...options.fallbackPlacements];\n }\n return flipOptions;\n}\n\n/**\n * The `injectOverlayShell` positioner that places the surface beside its anchor through\n * {@link injectFloating}.\n */\nexport function floatingPositioner(config: FloatingConfig): OverlayShellPositioner {\n return {\n reference: config.reference,\n open: config.open,\n attach: () => injectFloating(config),\n };\n}\n\n/**\n * Wires a floating UI element (tooltip, popover, menu...) to its anchor.\n * Must be called from an injection context. Delegates the platform gate,\n * portal, anti-flash baseline, `autoUpdate` loop, and symmetric cleanup to\n * the shared {@link runPositioning} scaffold, and supplies the anchored\n * positioner's own per-run body: the `offset` / `flip` / `shift` / `size` /\n * `hide` middleware stack and the `arrowMiddleware` the config supplies, plus the writes that follow each resolved\n * position — `data-placement`, `data-side`, `data-align`, `data-occluded`\n * (when the `hide` middleware reports the reference is off-screen),\n * `data-detached` (when `hideWhenDetached` is on and the reference escaped its\n * clipping ancestors), the `--for-floating-anchor-width/-height`,\n * `--for-floating-available-width/-height`, and `--for-floating-content-transform-origin` CSS\n * variables, and the optional arrow's position + `--for-floating-arrow-offset`.\n *\n * Once per open cycle, on the first resolved position after opening, it invokes\n * `onFirstPosition` — after the portal move and after `size` applied its\n * `max-height`, so a consumer can touch the now-portaled, now-sized surface. A\n * config change while open does not re-fire it; see\n * {@link FloatingConfig.onFirstPosition}.\n *\n * Cleanup is asymmetric on purpose: {@link resetFloatingStyles} strips the\n * transient sizing vars and occlusion attributes but retains the resolved\n * `translate` and placement outputs, and the arrow keeps its inline position,\n * `data-side` and `data-placement`, so a closing surface and its arrow stay\n * anchored to the trigger through `animate.leave`; the next mount re-arms the\n * baseline and recomputes everything before painting.\n *\n * Stylistic concerns (which side gets the arrow offset via\n * `--for-floating-arrow-offset`, pointer events, background, animations) stay with the\n * consumer.\n */\nexport function injectFloating(config: FloatingConfig): void {\n const fallbackShiftPadding = config.shiftPadding ?? 8;\n const vars = injectFloatingCustomProperties();\n\n runPositioning({\n reference: config.reference,\n open: config.open,\n portal: config.portal,\n clipUntilPositioned: config.clipUntilPositioned,\n onFirstPosition: config.onFirstPosition,\n computeAndApply: (el, reference) => {\n const arrowEl = config.arrowMiddleware ? (config.arrow?.() ?? null) : null;\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 middleware.push(\n flip(\n buildFlipOptions({\n padding: flipPaddingValue,\n boundary: collisionBoundary,\n fallbackAxisSideDirection: config.fallbackAxisSideDirection?.() ?? 'none',\n fallbackPlacements: config.fallbackPlacements?.(),\n }),\n ),\n );\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-floating-available-height)` etc.\n const sizeOptions: Parameters<typeof size>[0] = {\n padding: sizePaddingValue,\n apply({ availableWidth, availableHeight }) {\n el.style.setProperty(vars.availableWidth, `${Math.max(0, Math.round(availableWidth))}px`);\n el.style.setProperty(\n vars.availableHeight,\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 && config.arrowMiddleware) {\n middleware.push(config.arrowMiddleware(arrowEl, arrowPaddingVal));\n }\n\n return {\n placement: requestedPlacement,\n middleware,\n apply({ placement: resolvedPlacement, middlewareData }: ComputePositionReturn) {\n const { side: resolvedSide, align: resolvedAlign } = splitPlacement(\n resolvedPlacement as Placement,\n );\n\n el.dataset['placement'] = resolvedPlacement;\n el.dataset['side'] = resolvedSide;\n el.dataset['align'] = resolvedAlign;\n\n // Anchor box → CSS vars so the consumer can size the floating\n // element relative to the anchor (`width: var(--for-floating-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(vars.anchorWidth, `${Math.round(rect.width)}px`);\n el.style.setProperty(vars.anchorHeight, `${Math.round(rect.height)}px`);\n el.style.setProperty(\n vars.contentTransformOrigin,\n transformOriginFor(resolvedSide, resolvedAlign, isFloatingRtl(el)),\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(${vars.arrowOffset}, 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 reset() {\n resetFloatingStyles(el, vars);\n },\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-floating-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. The arrow element is not reset\n * at all: everything a run writes to it is resolved placement, rewritten in\n * full by the next run, so it keeps pointing at the trigger through the exit.\n */\nfunction resetFloatingStyles(el: HTMLElement, vars: FloatingCustomProperties): 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(vars.anchorWidth);\n el.style.removeProperty(vars.anchorHeight);\n el.style.removeProperty(vars.availableWidth);\n el.style.removeProperty(vars.availableHeight);\n el.removeAttribute('data-occluded');\n el.removeAttribute('data-detached');\n}\n","import { arrow, type Middleware } from '@floating-ui/dom';\n\n/**\n * Builds the middleware that positions an arrow element against its floating\n * surface, given the element and the padding (px) keeping it clear of the\n * surface's edges.\n */\nexport type FloatingArrowMiddleware = (element: HTMLElement, padding: number) => Middleware;\n\n/**\n * The {@link FloatingArrowMiddleware} wrapping floating-ui's `arrow`. Passed as\n * `FloatingConfig.arrowMiddleware` by the positioners whose surface can render an\n * arrow, so a positioner that never does carries no reference to `arrow`.\n */\nexport const floatingArrowMiddleware: FloatingArrowMiddleware = (element, padding) =>\n arrow({ element, padding });\n","import type { Signal } from '@angular/core';\nimport type { ReferenceElement } from '@floating-ui/dom';\n\nimport type { OverlayShellPositioner } from '../overlay-controller/overlay-shell';\nimport { type FloatingAlign, floatingPositioner, type FloatingSide } from './floating';\nimport { floatingArrowMiddleware } from './floating-arrow';\n\n/**\n * Single source of truth for the floating-ui positioning defaults shared by\n * every trigger-anchored overlay root. It is read once, by the two bases the\n * roots inherit their positioning block from\n * (`AnchoredOverlayPositioningBase` / `AnchoredFormValueControlBase`), so no\n * root spells a non-seed default itself.\n *\n * Only `side` / `align` / `sideOffset` / `collisionPadding` are seeded from\n * each root's own defaults provider (`provideForPopoverDefaults`,\n * `provideForSelectDefaults`, …) so a scope override flows through — those are\n * the placement values a design system tunes, and they legitimately vary per\n * root. Everything below is identical for every anchored overlay in the\n * library, which is why `arrowPadding` is not among them: only the three roots\n * shipping an arrow piece declare it, each seeded from its own defaults\n * provider.\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 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): OverlayShellPositioner {\n return floatingPositioner({\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 arrowMiddleware: floatingArrowMiddleware,\n });\n}\n","import { booleanAttribute, computed, Directive, input, numberAttribute } from '@angular/core';\n\nimport { FormUiControlBase } from 'forty-cdk/core';\nimport { ANCHORED_POSITIONING_DEFAULTS } from './anchored-positioning-inputs';\nimport type {\n AnchoredPositioningOverride,\n AnchoredPositioningSeedDefaults,\n} from './anchored-overlay-positioning-base';\nimport type { FloatingAlign, FloatingSide } from './floating';\n\n/**\n * `AnchoredOverlayPositioningBase` for the anchored roots that are also form\n * values — `[forSelect]`, `[forCombobox]`, `[forTimePicker]`, and both\n * date-picker roots through `DatePickerBase`. They must extend\n * `FormUiControlBase` for the Signal Forms contract, and TypeScript has single\n * inheritance, so the positioning block cannot reach them by extending the\n * other base as the remaining eight roots do.\n *\n * This class is therefore the **second and last** declaration site of that\n * block, and it is a verbatim copy on purpose:\n * `anchored-positioning-inputs.spec.ts` reads both files and fails when the two\n * regions stop matching character-for-character, so a change to one is a change\n * to both. Everything the block means is documented on\n * {@link AnchoredOverlayPositioningBase}; do not restate it here, and do not add\n * a member to one base without adding it to the other.\n */\n@Directive()\nexport abstract class AnchoredFormValueControlBase extends FormUiControlBase {\n /**\n * The four positioning seeds this root resolves from its own scoped defaults\n * provider. Concrete roots implement it with\n * `protected readonly positioningDefaults = inject(FOR_X_DEFAULTS)`, or with\n * a getter over a `computed` when one seed is derived (writing direction).\n */\n protected abstract readonly positioningDefaults: AnchoredPositioningSeedDefaults;\n\n /**\n * Placement override for the current open, resolved ahead of this root's own\n * inputs. `null` (the default) leaves the inputs in charge; the menu roots\n * override it with the active opener's `[menuPositioning]`.\n */\n protected positioningOverride(): AnchoredPositioningOverride | null {\n return null;\n }\n\n /**\n * Per-instance override for the side the overlay is anchored to. Pair with\n * `align` for the full positioning API. When `undefined` (default), falls\n * back to the scope default. Aliased to `side`; consumers bind `[side]=\"...\"`\n * and read the effective value via the public {@link side} computed.\n */\n readonly _sideInput = input<FloatingSide | undefined>(undefined, { alias: 'side' });\n\n /** Effective anchor side: the per-open override, else the `side` input, else the scope default. */\n readonly side = computed<FloatingSide>(\n () => this.positioningOverride()?.side ?? this._sideInput() ?? this.positioningDefaults.side,\n );\n\n /**\n * Per-instance override for the alignment along the chosen `side`. When\n * `undefined` (default), falls back to the scope default. Aliased to `align`;\n * consumers bind `[align]=\"...\"` and read the effective value via the public\n * {@link align} computed.\n */\n readonly _alignInput = input<FloatingAlign | undefined>(undefined, { alias: 'align' });\n\n /** Effective alignment: the per-open override, else the `align` input, else the scope default. */\n readonly align = computed<FloatingAlign>(\n () => this.positioningOverride()?.align ?? this._alignInput() ?? this.positioningDefaults.align,\n );\n\n /**\n * Per-instance override for the gap (px) between trigger and content along\n * the main axis. When `undefined` (default), falls back to the scope default.\n * Aliased to `sideOffset`; consumers bind `[sideOffset]=\"...\"` and read the\n * effective value via the public {@link sideOffset} computed.\n */\n readonly _sideOffsetInput = input(undefined, {\n alias: 'sideOffset',\n transform: (v: unknown): number | undefined => (v == null ? undefined : numberAttribute(v)),\n });\n\n /** Effective main-axis gap (px): the per-open override, else the input, else the scope default. */\n readonly sideOffset = computed<number>(\n () =>\n this.positioningOverride()?.sideOffset ??\n this._sideOffsetInput() ??\n this.positioningDefaults.sideOffset,\n );\n\n /**\n * Per-instance gap (px) along the cross axis (parallel to `side`). Default\n * `0`. Aliased to `alignOffset`; consumers bind `[alignOffset]=\"...\"` and read\n * the effective value via the public {@link alignOffset} computed.\n */\n readonly _alignOffsetInput = input(ANCHORED_POSITIONING_DEFAULTS.alignOffset, {\n alias: 'alignOffset',\n transform: numberAttribute,\n });\n\n /** Effective cross-axis gap (px): the per-open override, else the `alignOffset` input. */\n readonly alignOffset = computed<number>(\n () => this.positioningOverride()?.alignOffset ?? this._alignOffsetInput(),\n );\n\n /**\n * When `true` (default), `flip` and `shift` keep the overlay inside the\n * viewport. Disable for strict positioning where overflow is acceptable.\n */\n readonly avoidCollisions = input(ANCHORED_POSITIONING_DEFAULTS.avoidCollisions, {\n transform: booleanAttribute,\n });\n\n /**\n * Per-instance override for the padding (px) applied uniformly to the `flip`,\n * `shift`, and `size` middlewares. When `undefined` (default), falls back to\n * the scope default. Aliased to `collisionPadding`; consumers bind\n * `[collisionPadding]=\"...\"` and read the effective value via the public\n * {@link collisionPadding} computed.\n */\n readonly _collisionPaddingInput = input(undefined, {\n alias: 'collisionPadding',\n transform: (v: unknown): number | undefined => (v == null ? undefined : numberAttribute(v)),\n });\n\n /** Effective collision padding (px): the `collisionPadding` input when set, else the scope default. */\n readonly collisionPadding = computed<number>(\n () => this._collisionPaddingInput() ?? this.positioningDefaults.collisionPadding,\n );\n\n /**\n * Stickiness behaviour for `shift`. `'partial'` (default) lets the overlay\n * shift to stay visible. `'always'` keeps the requested placement even\n * off-screen.\n */\n readonly sticky = input<'partial' | 'always' | false>(ANCHORED_POSITIONING_DEFAULTS.sticky);\n\n /**\n * When `true`, sets `data-detached=\"\"` while the trigger has scrolled off all\n * clipping ancestors.\n */\n readonly hideWhenDetached = input(ANCHORED_POSITIONING_DEFAULTS.hideWhenDetached, {\n transform: booleanAttribute,\n });\n\n /**\n * When `true` (default), the content is clipped until floating-ui resolves\n * its first position, preventing a flash at the viewport corner. Set to\n * `false` so a dramatic `animate.enter` plays from its first frame (the\n * surface may flash briefly at the unresolved position while positioning\n * computes).\n */\n readonly clipUntilPositioned = input(ANCHORED_POSITIONING_DEFAULTS.clipUntilPositioned, {\n transform: booleanAttribute,\n });\n}\n","import { booleanAttribute, computed, Directive, input, numberAttribute } from '@angular/core';\n\nimport { ANCHORED_POSITIONING_DEFAULTS } from './anchored-positioning-inputs';\nimport type { FloatingAlign, FloatingSide } from './floating';\n\n/**\n * The four positioning seeds a trigger-anchored overlay root resolves from its\n * own scoped defaults provider (`provideForPopoverDefaults`,\n * `provideForSelectDefaults`, …), rather than from the shared\n * {@link ANCHORED_POSITIONING_DEFAULTS} constant. A root's `ForXDefaults`\n * interface `extends` this whenever all four keys are plain values, so the\n * shared seed contract stays typed identically across roots, and every concrete\n * {@link AnchoredOverlayPositioningBase} subclass supplies an instance of it\n * through its `positioningDefaults` accessor.\n *\n * A root whose library fallback for one seed is *derived* rather than fixed —\n * MenuSub's writing-direction `side` — declares that key nullable on its own\n * defaults interface and resolves it inside `positioningDefaults`, so what the\n * base reads is always a settled value.\n */\nexport interface AnchoredPositioningSeedDefaults {\n /** Side the overlay is anchored to when the `side` input is unset. */\n side: FloatingSide;\n /** Alignment along the chosen `side` when the `align` input is unset. */\n align: FloatingAlign;\n /** Gap (px) between trigger and content along the main axis when the `sideOffset` input is unset. */\n sideOffset: number;\n /** Padding (px) applied uniformly to `flip` / `shift` / `size` when the `collisionPadding` input is unset. */\n collisionPadding: number;\n}\n\n/**\n * Per-open override of the four **placement** values, resolved ahead of the\n * root's own inputs. It exists for the menu roots, where one surface is shared\n * by heterogeneous openers and the opener that fired legitimately decides the\n * placement (`MenuOpenerPositioning` is the shape flowing through\n * `[menuPositioning]`); every other root inherits the base's `null` and\n * resolves its inputs directly.\n *\n * Only the four placement values are overridable. The rest of the surface\n * (`avoidCollisions`, `collisionPadding`, `sticky`, …) is collision / viewport\n * policy for the overlay rather than a property of what opened it.\n */\nexport interface AnchoredPositioningOverride {\n /** Side the overlay is anchored to for this open. */\n readonly side?: FloatingSide;\n /** Alignment along the chosen `side` for this open. */\n readonly align?: FloatingAlign;\n /** Gap (px) along the main axis for this open. */\n readonly sideOffset?: number;\n /** Gap (px) along the cross axis for this open. */\n readonly alignOffset?: number;\n}\n\n/**\n * Abstract base for the trigger-anchored overlay roots. It single-sources the\n * nine shared floating-ui positioning inputs and the five effective computeds\n * over them, so the declarations live in one place instead of being copied per\n * root.\n *\n * Each of the four placement values resolves in the same three steps — the\n * per-open {@link positioningOverride}, then the root's own input, then the\n * scope default read through {@link positioningDefaults}. The five non-placement\n * inputs (`avoidCollisions` / `sticky` / `hideWhenDetached` /\n * `clipUntilPositioned`, plus `alignOffset`'s own library fallback) default from\n * the shared {@link ANCHORED_POSITIONING_DEFAULTS} constant.\n *\n * `arrowPadding` is **not** here: floating-ui installs the `arrow` middleware\n * only when an arrow element is supplied, so it belongs to the three roots that\n * ship one — `[forPopover]`, `[forTooltip]`, `[forHoverCard]` — each declaring\n * the input itself, seeded from its own defaults provider.\n *\n * Roots that must also extend `FormUiControlBase` reach the identical block\n * through `AnchoredFormValueControlBase` instead.\n */\n@Directive()\nexport abstract class AnchoredOverlayPositioningBase {\n /**\n * The four positioning seeds this root resolves from its own scoped defaults\n * provider. Concrete roots implement it with\n * `protected readonly positioningDefaults = inject(FOR_X_DEFAULTS)`, or with\n * a getter over a `computed` when one seed is derived (writing direction).\n */\n protected abstract readonly positioningDefaults: AnchoredPositioningSeedDefaults;\n\n /**\n * Placement override for the current open, resolved ahead of this root's own\n * inputs. `null` (the default) leaves the inputs in charge; the menu roots\n * override it with the active opener's `[menuPositioning]`.\n */\n protected positioningOverride(): AnchoredPositioningOverride | null {\n return null;\n }\n\n /**\n * Per-instance override for the side the overlay is anchored to. Pair with\n * `align` for the full positioning API. When `undefined` (default), falls\n * back to the scope default. Aliased to `side`; consumers bind `[side]=\"...\"`\n * and read the effective value via the public {@link side} computed.\n */\n readonly _sideInput = input<FloatingSide | undefined>(undefined, { alias: 'side' });\n\n /** Effective anchor side: the per-open override, else the `side` input, else the scope default. */\n readonly side = computed<FloatingSide>(\n () => this.positioningOverride()?.side ?? this._sideInput() ?? this.positioningDefaults.side,\n );\n\n /**\n * Per-instance override for the alignment along the chosen `side`. When\n * `undefined` (default), falls back to the scope default. Aliased to `align`;\n * consumers bind `[align]=\"...\"` and read the effective value via the public\n * {@link align} computed.\n */\n readonly _alignInput = input<FloatingAlign | undefined>(undefined, { alias: 'align' });\n\n /** Effective alignment: the per-open override, else the `align` input, else the scope default. */\n readonly align = computed<FloatingAlign>(\n () => this.positioningOverride()?.align ?? this._alignInput() ?? this.positioningDefaults.align,\n );\n\n /**\n * Per-instance override for the gap (px) between trigger and content along\n * the main axis. When `undefined` (default), falls back to the scope default.\n * Aliased to `sideOffset`; consumers bind `[sideOffset]=\"...\"` and read the\n * effective value via the public {@link sideOffset} computed.\n */\n readonly _sideOffsetInput = input(undefined, {\n alias: 'sideOffset',\n transform: (v: unknown): number | undefined => (v == null ? undefined : numberAttribute(v)),\n });\n\n /** Effective main-axis gap (px): the per-open override, else the input, else the scope default. */\n readonly sideOffset = computed<number>(\n () =>\n this.positioningOverride()?.sideOffset ??\n this._sideOffsetInput() ??\n this.positioningDefaults.sideOffset,\n );\n\n /**\n * Per-instance gap (px) along the cross axis (parallel to `side`). Default\n * `0`. Aliased to `alignOffset`; consumers bind `[alignOffset]=\"...\"` and read\n * the effective value via the public {@link alignOffset} computed.\n */\n readonly _alignOffsetInput = input(ANCHORED_POSITIONING_DEFAULTS.alignOffset, {\n alias: 'alignOffset',\n transform: numberAttribute,\n });\n\n /** Effective cross-axis gap (px): the per-open override, else the `alignOffset` input. */\n readonly alignOffset = computed<number>(\n () => this.positioningOverride()?.alignOffset ?? this._alignOffsetInput(),\n );\n\n /**\n * When `true` (default), `flip` and `shift` keep the overlay inside the\n * viewport. Disable for strict positioning where overflow is acceptable.\n */\n readonly avoidCollisions = input(ANCHORED_POSITIONING_DEFAULTS.avoidCollisions, {\n transform: booleanAttribute,\n });\n\n /**\n * Per-instance override for the padding (px) applied uniformly to the `flip`,\n * `shift`, and `size` middlewares. When `undefined` (default), falls back to\n * the scope default. Aliased to `collisionPadding`; consumers bind\n * `[collisionPadding]=\"...\"` and read the effective value via the public\n * {@link collisionPadding} computed.\n */\n readonly _collisionPaddingInput = input(undefined, {\n alias: 'collisionPadding',\n transform: (v: unknown): number | undefined => (v == null ? undefined : numberAttribute(v)),\n });\n\n /** Effective collision padding (px): the `collisionPadding` input when set, else the scope default. */\n readonly collisionPadding = computed<number>(\n () => this._collisionPaddingInput() ?? this.positioningDefaults.collisionPadding,\n );\n\n /**\n * Stickiness behaviour for `shift`. `'partial'` (default) lets the overlay\n * shift to stay visible. `'always'` keeps the requested placement even\n * off-screen.\n */\n readonly sticky = input<'partial' | 'always' | false>(ANCHORED_POSITIONING_DEFAULTS.sticky);\n\n /**\n * When `true`, sets `data-detached=\"\"` while the trigger has scrolled off all\n * clipping ancestors.\n */\n readonly hideWhenDetached = input(ANCHORED_POSITIONING_DEFAULTS.hideWhenDetached, {\n transform: booleanAttribute,\n });\n\n /**\n * When `true` (default), the content is clipped until floating-ui resolves\n * its first position, preventing a flash at the viewport corner. Set to\n * `false` so a dramatic `animate.enter` plays from its first frame (the\n * surface may flash briefly at the unresolved position while positioning\n * computes).\n */\n readonly clipUntilPositioned = input(ANCHORED_POSITIONING_DEFAULTS.clipUntilPositioned, {\n transform: booleanAttribute,\n });\n}\n","import { type Signal } from '@angular/core';\nimport {\n type Middleware,\n type Padding,\n type Placement,\n type ReferenceElement,\n} from '@floating-ui/dom';\n\nimport type { OverlayShellPositioner } from '../overlay-controller/overlay-shell';\nimport {\n type FloatingCustomProperties,\n injectFloatingCustomProperties,\n} from './floating-custom-properties';\nimport { isFloatingRtl } from './floating-direction';\nimport { runPositioning } from './run-positioning';\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. Read on each position run, so a selection change while open\n * does not reposition the listbox; it is anchored on the next open or the\n * next `autoUpdate` run.\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 every edge of the listbox and the\n * `--for-floating-available-height` CSS variable.\n */\n readonly collisionPadding?: Signal<number | Padding>;\n\n /**\n * Called once per open cycle, on the first resolved position, after the listbox has been\n * portaled and its CSS vars written. When set it replaces the positioner's own first-position\n * scroll of the anchored option, so the caller decides which option to reveal.\n */\n readonly onFirstPosition?: () => void;\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\ninterface ItemAlignedPadding {\n readonly top: number;\n readonly left: number;\n readonly right: number;\n}\n\nfunction paddingSide(\n padding: number | Padding | undefined,\n side: keyof ItemAlignedPadding,\n fallback: number,\n): number {\n if (padding == null) {\n return fallback;\n }\n if (typeof padding === 'number') {\n return padding;\n }\n return padding[side] ?? 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\nexport interface ItemAlignedGeometry {\n /** Viewport-relative top edge of the anchor. */\n readonly triggerTop: number;\n\n readonly triggerHeight: number;\n\n /** Border-box height of the listbox, excluding any CSS transform. */\n readonly listboxHeight: number;\n\n /**\n * Distance from the listbox's top border edge to the vertical center of the\n * option to anchor over the trigger, or `null` when the listbox holds no\n * anchorable option — the listbox then aligns to the trigger's top edge.\n */\n readonly targetCenter: number | null;\n\n readonly viewportHeight: number;\n\n /** Distance the listbox keeps from the viewport's top and bottom edges. */\n readonly padding: number;\n}\n\n/**\n * Resolves the listbox's vertical offset so the target option's center lines up\n * with the trigger's center, clamped inside the viewport. A listbox taller than\n * the band the padding leaves cannot satisfy both edges and pins to the top.\n */\nexport function resolveItemAlignedY(geometry: ItemAlignedGeometry): number {\n const { triggerTop, triggerHeight, listboxHeight, targetCenter, viewportHeight, padding } =\n geometry;\n const minY = padding;\n const maxY = viewportHeight - listboxHeight - padding;\n\n if (targetCenter == null) {\n return Math.max(minY, Math.min(triggerTop, maxY));\n }\n\n const desiredY = triggerTop + triggerHeight / 2 - targetCenter;\n return maxY > minY ? Math.max(minY, Math.min(desiredY, maxY)) : minY;\n}\n\nexport interface ItemAlignedInlineGeometry {\n readonly triggerLeft: number;\n readonly triggerWidth: number;\n readonly listboxWidth: number;\n readonly viewportWidth: number;\n readonly paddingLeft: number;\n readonly paddingRight: number;\n readonly rtl: boolean;\n}\n\nexport function resolveItemAlignedX(geometry: ItemAlignedInlineGeometry): number {\n const { triggerLeft, triggerWidth, listboxWidth, viewportWidth, paddingLeft, paddingRight, rtl } =\n geometry;\n const minX = paddingLeft;\n const maxX = viewportWidth - listboxWidth - paddingRight;\n\n if (maxX < minX) {\n return rtl ? maxX : minX;\n }\n\n const desiredX = rtl ? triggerLeft + triggerWidth - listboxWidth : triggerLeft;\n return Math.max(minX, Math.min(desiredX, maxX));\n}\n\nfunction offsetTopWithinChain(el: HTMLElement): number {\n const view = el.ownerDocument.defaultView;\n let top = 0;\n let node: HTMLElement | null = el;\n while (node) {\n top += node.offsetTop;\n const parent: Element | null = node.offsetParent;\n node = view && parent instanceof view.HTMLElement ? parent : null;\n }\n return top;\n}\n\n/**\n * Distance from `listbox`'s top border edge to `target`'s vertical center, read\n * from offset geometry so a CSS transform on either element cannot skew it.\n * Offset geometry is integer-rounded, so the result is accurate to about a\n * pixel.\n */\nexport function offsetCenterWithinListbox(target: HTMLElement, listbox: HTMLElement): number {\n return offsetTopWithinChain(target) + target.offsetHeight / 2 - offsetTopWithinChain(listbox);\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*, and the\n * listbox's inline-start edge lines up with the trigger's, mirrored under RTL.\n * Both axes are clamped inside the viewport with `padding`.\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 padding: ItemAlignedPadding,\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 target = selectedOption() ?? findFirstEnabledOption(floating);\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 const y = resolveItemAlignedY({\n triggerTop: triggerRect.top,\n triggerHeight: triggerRect.height,\n listboxHeight: floating.offsetHeight,\n targetCenter: target ? offsetCenterWithinListbox(target, floating) : null,\n viewportHeight,\n padding: padding.top,\n });\n\n const x = resolveItemAlignedX({\n triggerLeft: triggerRect.left,\n triggerWidth: triggerRect.width,\n listboxWidth: floating.offsetWidth,\n viewportWidth: floating.ownerDocument.documentElement.clientWidth,\n paddingLeft: padding.left,\n paddingRight: padding.right,\n rtl: isFloatingRtl(floating),\n });\n\n return { x, y };\n },\n };\n}\n\n/**\n * The `injectOverlayShell` positioner that overlays the surface on its anchor through\n * {@link injectItemAlignedPositioner}.\n */\nexport function itemAlignedPositioner(config: ItemAlignedConfig): OverlayShellPositioner {\n return {\n reference: config.reference,\n open: config.open,\n attach: () => injectItemAlignedPositioner(config),\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 * Delegates the platform gate, portal, anti-flash baseline, `autoUpdate` loop,\n * `translate` write, `clip-path` drop, and symmetric cleanup to the shared\n * {@link runPositioning} scaffold, and supplies its own per-run body: the\n * custom `itemAligned` middleware plus the writes that follow each resolved\n * position — `data-position=\"item-aligned\"`, the `--for-floating-anchor-width/-height`\n * and `--for-floating-available-height` CSS vars — and, on the first resolved position,\n * `scrollIntoView({ block: 'nearest' })` on the target option so the visual\n * anchor stays correct when the listbox is taller than the viewport, unless\n * `onFirstPosition` is supplied, which then owns that reveal.\n *\n * `--for-floating-available-height` is the same *concept* the anchored positioner\n * publishes (the maximum block-size the surface may occupy before it\n * collides), computed for this algorithm: the surface overlays the trigger\n * rather than sitting beside it, so the band is the full viewport minus\n * `collisionPadding` on both edges (`innerHeight - 2 * collisionPadding`)\n * rather than the anchor-relative space floating-ui's `size` middleware\n * reports. A consumer's `max-height: var(--for-floating-available-height)` therefore\n * works unchanged across `position=\"popper\"` and `position=\"item-aligned\"`.\n * `--for-floating-available-width` is **not** published here: item-aligned\n * aligns the listbox's inline-start edge with the trigger's and computes no\n * width budget.\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 vars = injectFloatingCustomProperties();\n runPositioning({\n reference: config.reference,\n open: config.open,\n portal: config.portal,\n onFirstPosition: config.onFirstPosition,\n computeAndApply: (el, reference) => {\n const paddingInput = config.collisionPadding?.();\n const padding: ItemAlignedPadding = {\n top: paddingSide(paddingInput, 'top', 8),\n left: paddingSide(paddingInput, 'left', 8),\n right: paddingSide(paddingInput, 'right', 8),\n };\n const collisionPadding = padding.top;\n\n let initialScrollDone = config.onFirstPosition !== undefined;\n\n return {\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' satisfies Placement,\n middleware: [itemAligned(() => config.selectedOption(), padding)],\n apply() {\n el.dataset['position'] = 'item-aligned';\n\n const triggerRect = reference.getBoundingClientRect();\n el.style.setProperty(vars.anchorWidth, `${Math.round(triggerRect.width)}px`);\n el.style.setProperty(vars.anchorHeight, `${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(vars.availableHeight, `${Math.round(availableHeight)}px`);\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 reset() {\n resetItemAlignedStyles(el, vars);\n },\n };\n },\n });\n}\n\n/**\n * Strip the transient sizing CSS custom properties\n * `injectItemAlignedPositioner` writes to the listbox — including the\n * `clip-path` hide baseline — while **retaining** the resolved `translate` and\n * `data-position=\"item-aligned\"`, so a leave animation scoped to that selector\n * keeps matching through the exit.\n * Mirrors `resetFloatingStyles` in `floating.ts`: the surface is portaled\n * until `getAnimations().finished`, so during an `animate.leave` exit the host\n * keeps `position: fixed; left: 0; top: 0` and the retained `translate` stays\n * anchored over the trigger instead of flashing at the viewport origin. The\n * next mount re-arms the `clip-path` baseline in `afterNextRender` and\n * recomputes the position before painting, so the retained `translate` never\n * produces a stale-position flash.\n */\nfunction resetItemAlignedStyles(el: HTMLElement, vars: FloatingCustomProperties): void {\n el.style.removeProperty('clip-path');\n el.style.removeProperty(vars.anchorWidth);\n el.style.removeProperty(vars.anchorHeight);\n el.style.removeProperty(vars.availableHeight);\n}\n","import { effect, type Signal, untracked, type WritableSignal } from '@angular/core';\n\nimport { isImeComposing } from 'forty-cdk/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 /** Document whose Escape cancels a pending open. */\n document: Document;\n}\n\n/**\n * Hover-intent scheduler handle returned by {@link createHoverIntent}.\n */\nexport interface HoverIntentScheduler {\n /**\n * Schedule the open after the resolved open delay (instant when delay is 0 or skipped);\n * `immediate` bypasses the delay.\n */\n scheduleOpen(immediate?: boolean): void;\n /** Schedule the close after the resolved close delay; `immediate` bypasses the delay. */\n scheduleClose(immediate: boolean): void;\n /**\n * Cancel any pending open / close timer without changing state. An Escape\n * pressed anywhere in the document while an open is pending does the same,\n * unless it belongs to an IME composition.\n */\n cancelPending(): void;\n /** Whether an open or close timer is pending. */\n isPending(): boolean;\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.\n *\n * Internal core tier — exported from `forty-cdk/core-anchored` for the\n * library's own entry points, with no semver guarantee.\n */\nexport function createHoverIntent(options: HoverIntentOptions): HoverIntentScheduler {\n let pendingTimer: ReturnType<typeof setTimeout> | null = null;\n let disarmEscape: (() => void) | null = null;\n\n function releaseEscape(): void {\n if (disarmEscape) {\n disarmEscape();\n disarmEscape = null;\n }\n }\n\n function cancelPending(): void {\n releaseEscape();\n if (pendingTimer !== null) {\n clearTimeout(pendingTimer);\n pendingTimer = null;\n }\n }\n\n function armEscape(): void {\n const doc = options.document;\n const onKeyDown = (event: KeyboardEvent): void => {\n if (event.key === 'Escape' && !isImeComposing(event)) {\n cancelPending();\n }\n };\n doc.addEventListener('keydown', onKeyDown, true);\n disarmEscape = () => doc.removeEventListener('keydown', onKeyDown, true);\n }\n\n function close(): void {\n options.open.set(false);\n options.coordinator.startSkipDelay();\n }\n\n function scheduleOpen(immediate = false): void {\n cancelPending();\n if (options.isDisabled()) {\n return;\n }\n if (options.open()) {\n return;\n }\n const base = immediate || 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 releaseEscape();\n if (options.isDisabled()) {\n return;\n }\n options.open.set(true);\n }, delay);\n armEscape();\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, isPending: () => pendingTimer !== null };\n}\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 * core tier — no semver guarantee.\n */\nexport function forceCloseWhenDisabled(options: ForceCloseWhenDisabledOptions): void {\n // @sanctioned-effect(untracked-read): the `open` read is untracked, so the\n // effect reacts to `disabled` alone and never cycles on the signal it writes.\n effect(() => {\n if (options.disabled() && untracked(options.open)) {\n options.onForceClose();\n options.open.set(false);\n }\n });\n}\n","import { isHoverCapablePointer } from 'forty-cdk/core';\nimport 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/** Options for {@link attachPointerGrace}. */\nexport interface PointerGraceOptions {\n /**\n * Which pointer moves the polygon tracks; a move it rejects is ignored.\n * Defaults to `isHoverCapablePointer` (mouse only), the menu family's hover\n * vocabulary. A caller whose trigger also opens on pen hover passes\n * `isNonTouchPointer`, so the pen that opened the surface can close it.\n */\n readonly tracksPointer?: (event: Pick<PointerEvent, 'pointerType'>) => boolean;\n readonly exitsOutOfRange?: boolean;\n}\n\n/**\n * Attaches a document-level `pointermove` listener that calls {@link onExit}\n * on every tracked move outside {@link polygon}, until the returned cleanup\n * disarms it. With {@link PointerGraceOptions.exitsOutOfRange}, a tracked\n * `pointerout` with no `relatedTarget` (the pointer left the document, or a pen\n * left the digitizer's hover range) is an exit too. The caller arms this on a\n * trigger pointer-leave and disarms it once the pointer reaches the content,\n * the grace window elapses, or the surface is otherwise resolved.\n *\n * Moves {@link PointerGraceOptions.tracksPointer} rejects are ignored: touch\n * opens by tap, never by hover, so a touch move has no safe triangle to leave.\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 aborts the listener's `AbortSignal`. Idempotent —\n * safe to store and call from a `DestroyRef` hook after an earlier disarm.\n */\nexport function attachPointerGrace(\n doc: Document,\n polygon: Polygon,\n onExit: () => void,\n options: PointerGraceOptions = {},\n): () => void {\n const tracksPointer = options.tracksPointer ?? isHoverCapablePointer;\n const onMove = (event: PointerEvent): void => {\n if (!tracksPointer(event)) {\n return;\n }\n if (!isPointInPolygon({ x: event.clientX, y: event.clientY }, polygon)) {\n onExit();\n }\n };\n const controller = new AbortController();\n doc.addEventListener('pointermove', onMove, { signal: controller.signal });\n if (options.exitsOutOfRange) {\n const onOut = (event: PointerEvent): void => {\n if (tracksPointer(event) && event.relatedTarget === null) {\n onExit();\n }\n };\n doc.addEventListener('pointerout', onOut, { signal: controller.signal });\n }\n return () => controller.abort();\n}\n","import { isNonTouchPointer } from 'forty-cdk/core';\n\nimport type { FloatingSide } from '../floating/floating';\nimport {\n attachPointerGrace,\n buildSubmenuGracePolygon,\n type Point,\n resolveGraceSide,\n} from '../pointer-grace/pointer-grace';\n\n/**\n * Inputs for {@link createHoverSurfaceState}.\n */\nexport interface HoverSurfaceOptions {\n /**\n * The registered trigger: measured to orient the grace polygon, and the only\n * element whose hover and focus keep the surface alive.\n */\n readonly trigger: () => HTMLElement | null;\n /** The registered content the grace polygon bridges toward. */\n readonly content: () => HTMLElement | null;\n /** Side the grace polygon assumes when no trigger is registered to measure. */\n readonly side: () => FloatingSide;\n /**\n * Whether a surface opened from inside the content is still open above it,\n * which keeps the surface alive like hover and focus do.\n */\n readonly nested: () => boolean;\n /** Closes the surface once no keep-alive source is active. */\n readonly close: () => void;\n}\n\n/**\n * Keep-alive bookkeeping of a hover-scheduled overlay, returned by\n * {@link createHoverSurfaceState}.\n */\nexport interface HoverSurfaceState {\n /** Whether the trigger holds focus. */\n triggerFocused(): boolean;\n /** Whether the trigger or the content holds focus. */\n focused(): boolean;\n /** The pointer entered the trigger: marks it hovered and disarms the grace. */\n enterTrigger(): void;\n /** The pointer left the trigger: clears its hover, leaving the close to the caller. */\n leaveTrigger(): void;\n /** The trigger received focus. */\n focusTrigger(): void;\n /** The trigger lost focus: closes when nothing else keeps the surface alive. */\n blurTrigger(): void;\n /** The pointer entered the content: marks it hovered and disarms the grace. */\n enterContent(): void;\n /** The pointer left the content: closes when nothing else keeps the surface alive. */\n leaveContent(): void;\n /** Focus entered the content. */\n focusContent(): void;\n /** Focus left the content: closes when nothing else keeps the surface alive. */\n blurContent(): void;\n /** The content unmounted: clears its hover and focus and disarms the grace. */\n resetContent(): void;\n /**\n * The trigger on `el` unmounted: forgets its hover and focus, so the state\n * keeps no reference to the element.\n */\n releaseTrigger(el: HTMLElement): void;\n /**\n * A surface opened from inside the content closed: once the current task\n * settles (a return of focus into the content included), closes when nothing\n * else keeps the surface alive.\n */\n nestedSurfaceClosed(): void;\n /**\n * Closes unless the trigger or the content is hovered or focused, or a\n * surface opened from inside the content is still open.\n */\n closeIfInactive(): void;\n /**\n * Arms a pointer-grace polygon from `cursor` toward the content, so the\n * pointer can cross the gap without closing. Leaving it disarms the grace and\n * closes when nothing else keeps the surface alive. Without registered\n * content it closes the same way at once.\n */\n armGrace(cursor: Point): void;\n /** Detaches an armed grace polygon. Safe when none is armed. */\n disarmGrace(): void;\n}\n\n/**\n * Shared keep-alive state for Tooltip and Hover-card: which side of the\n * overlay is hovered or focused, and the pointer-grace bridge between them.\n * An element removed under the pointer never reports `pointerleave` or `blur`,\n * so the trigger's hover and focus count only while the element they were\n * observed on is still the registered trigger, `releaseTrigger` forgets that\n * element when it unmounts, and `resetContent` clears the content side when\n * its element unmounts.\n *\n * Internal core tier — exported from `forty-cdk/core-anchored` for the\n * library's own entry points, with no semver guarantee.\n */\nexport function createHoverSurfaceState(options: HoverSurfaceOptions): HoverSurfaceState {\n let hoveredTrigger: HTMLElement | null = null;\n let focusedTrigger: HTMLElement | null = null;\n let contentHovered = false;\n let contentFocused = false;\n let detachGrace: (() => void) | null = null;\n\n const isTrigger = (el: HTMLElement | null): boolean => el !== null && el === options.trigger();\n const triggerHovered = (): boolean => isTrigger(hoveredTrigger);\n const triggerFocused = (): boolean => isTrigger(focusedTrigger);\n\n function disarmGrace(): void {\n if (detachGrace) {\n detachGrace();\n detachGrace = null;\n }\n }\n\n function closeIfInactive(): void {\n if (\n triggerHovered() ||\n triggerFocused() ||\n contentHovered ||\n contentFocused ||\n options.nested()\n ) {\n return;\n }\n options.close();\n }\n\n function armGrace(cursor: Point): void {\n const content = options.content();\n if (!content) {\n closeIfInactive();\n return;\n }\n const rect = content.getBoundingClientRect();\n const trigger = options.trigger();\n const side = trigger ? resolveGraceSide(trigger.getBoundingClientRect(), rect) : options.side();\n const polygon = buildSubmenuGracePolygon(cursor, rect, side);\n disarmGrace();\n detachGrace = attachPointerGrace(\n content.ownerDocument,\n polygon,\n () => {\n disarmGrace();\n closeIfInactive();\n },\n { tracksPointer: isNonTouchPointer, exitsOutOfRange: true },\n );\n }\n\n return {\n triggerFocused,\n focused: () => triggerFocused() || contentFocused,\n enterTrigger: () => {\n hoveredTrigger = options.trigger();\n disarmGrace();\n },\n leaveTrigger: () => {\n hoveredTrigger = null;\n },\n focusTrigger: () => {\n focusedTrigger = options.trigger();\n },\n blurTrigger: () => {\n focusedTrigger = null;\n closeIfInactive();\n },\n enterContent: () => {\n contentHovered = true;\n disarmGrace();\n },\n leaveContent: () => {\n contentHovered = false;\n closeIfInactive();\n },\n focusContent: () => {\n contentFocused = true;\n },\n blurContent: () => {\n contentFocused = false;\n closeIfInactive();\n },\n resetContent: () => {\n contentHovered = false;\n contentFocused = false;\n disarmGrace();\n },\n releaseTrigger: (el) => {\n if (hoveredTrigger === el) {\n hoveredTrigger = null;\n }\n if (focusedTrigger === el) {\n focusedTrigger = null;\n }\n },\n nestedSurfaceClosed: () => {\n queueMicrotask(closeIfInactive);\n },\n closeIfInactive,\n armGrace,\n disarmGrace,\n };\n}\n","import {\n computed,\n inject,\n linkedSignal,\n type Signal,\n signal,\n type WritableSignal,\n} from '@angular/core';\nimport type { ReferenceElement } from '@floating-ui/dom';\n\nimport {\n adoptHostId,\n createSingleSlot,\n IdGenerator,\n type RootedHandle,\n type SingleSlot,\n type SingleSlotConfig,\n} from 'forty-cdk/core';\n\n/**\n * A registered overlay element whose aria-wiring id the surface exposes. Backs\n * the content / list / input slots the overlay controllers used to each\n * hand-copy: the register step adopts a consumer-set static `id` into the\n * seeded id signal (so external `aria-labelledby` / label `for` references keep\n * resolving), the unregister step clears the element only when the same node\n * deregisters.\n *\n * Construct through {@link injectIdentifiedSlot} so the id signal is seeded from\n * the shared {@link IdGenerator} at the controller's construction.\n *\n * @typeParam E Concrete element type registered here (e.g. `HTMLInputElement`\n * for the combobox input). Defaults to `HTMLElement`.\n */\nexport class IdentifiedElementSlot<E extends HTMLElement = HTMLElement> {\n readonly #el = signal<E | null>(null);\n readonly #id: WritableSignal<string>;\n\n /** The registered element, or `null` while nothing is mounted. */\n readonly element: Signal<E | null> = this.#el.asReadonly();\n\n /** The element's aria-wiring id — the generated fallback until a static id is adopted. */\n readonly id: WritableSignal<string>;\n\n constructor(id: WritableSignal<string>) {\n this.#id = id;\n this.id = id;\n }\n\n /** Register the element, adopting a consumer-set static `id` into the id signal. */\n register(el: E): void {\n adoptHostId(el, this.#id);\n this.#el.set(el);\n }\n\n /** Deregister the element (no-op unless the same node registered). */\n unregister(el: E): void {\n if (this.#el() === el) {\n this.#el.set(null);\n }\n }\n}\n\n/**\n * A trigger registered with its root. `id` is the id the trigger carries on its own host, minted\n * per trigger; a trigger the surface never names in its ARIA wiring (a hover card's) has none.\n */\nexport interface RootedTriggerHandle<R extends object = object> extends RootedHandle<R> {\n readonly host: HTMLElement;\n readonly id?: Signal<string>;\n}\n\n/**\n * The triggers registered with one root, and which of them the surface belongs to.\n *\n * Every registered trigger toggles the surface, so {@link hosts} lists them all for the\n * surface's outside-press and outside-focus exemption. One of them is **active**: the\n * surface is positioned against it, labelled by it and returns focus to it. A trigger\n * claims that role through {@link activate} from the interaction that opens or toggles the\n * surface; with no claim, or once the claiming trigger unmounts, the newest registered\n * trigger is active.\n */\nexport class RootedTriggerSlot {\n readonly #claimed: WritableSignal<HTMLElement | null>;\n readonly #active: Signal<RootedTriggerHandle | null>;\n\n /** Every registered trigger's host, in registration order. */\n readonly hosts: Signal<readonly HTMLElement[]>;\n\n /** The active trigger's host, or `null` while no trigger is registered. */\n readonly element: Signal<HTMLElement | null>;\n\n /** The active trigger's id, or `''` while no trigger carrying one is registered. */\n readonly id: Signal<string>;\n\n constructor(triggers: Signal<readonly RootedTriggerHandle[]>) {\n // Holds the claiming host until it leaves the registered set, then drops it.\n this.#claimed = linkedSignal<readonly RootedTriggerHandle[], HTMLElement | null>({\n source: triggers,\n computation: (list, previous) => {\n const claimed = previous?.value ?? null;\n return claimed !== null && list.some((handle) => handle.host === claimed) ? claimed : null;\n },\n });\n this.#active = computed(() => {\n const list = triggers();\n const claimed = this.#claimed();\n return list.find((handle) => handle.host === claimed) ?? list.at(-1) ?? null;\n });\n this.hosts = computed(() => triggers().map((handle) => handle.host));\n this.element = computed(() => this.#active()?.host ?? null);\n this.id = computed(() => this.#active()?.id?.() ?? '');\n }\n\n /** Make the trigger on `host` the active one. Called by a trigger as it opens or toggles. */\n activate(host: HTMLElement): void {\n this.#claimed.set(host);\n }\n}\n\n/**\n * The floating-ui anchor slot shared by the listbox overlays, combobox and the\n * date pickers. An explicit `[for…Anchor]` registers here; the resolved\n * anchor prefers it and otherwise walks the fallback chain (field anchor,\n * trigger, input) so a primitive without an explicit anchor keeps its\n * behaviour.\n *\n * Registrations are stacked like a core `createSingleSlot`: the newest\n * anchor is the one used, unregistering it restores the previous survivor,\n * and a second anchor still registered once the change-detection pass\n * settles warns in dev mode. A structural swap that mounts the replacement\n * anchor before destroying the outgoing one is therefore not reported.\n */\nexport class AnchorSlot {\n readonly #slot: SingleSlot<HTMLElement>;\n\n /** The explicitly-registered anchor element, or `null`. */\n readonly element: Signal<HTMLElement | null>;\n\n constructor(config: SingleSlotConfig) {\n this.#slot = createSingleSlot<HTMLElement>(config);\n this.element = this.#slot.value;\n }\n\n /**\n * Register the explicit anchor, making it the one the overlay positions\n * against. Registering the current anchor again is a no-op.\n */\n register(el: HTMLElement): void {\n if (this.element() === el) {\n return;\n }\n this.#slot.register(el);\n }\n\n /** Deregister the anchor (no-op unless the same node registered). */\n unregister(el: HTMLElement): void {\n this.#slot.unregister(el);\n }\n\n /**\n * Build the resolved-anchor signal: the explicit anchor, otherwise the first\n * non-null fallback in order (field anchor → trigger → input). Decoupled from\n * those elements so they keep driving their own aria-wiring / keyboard\n * interaction regardless of where the surface paints.\n */\n resolve(...fallbacks: Signal<HTMLElement | null>[]): Signal<ReferenceElement | null> {\n return computed<ReferenceElement | null>(() => {\n const explicit = this.element();\n if (explicit !== null) {\n return explicit;\n }\n for (const fallback of fallbacks) {\n const el = fallback();\n if (el !== null) {\n return el;\n }\n }\n return null;\n });\n }\n}\n\n/**\n * A writable `<idPrefix>-<suffix>` id signal off the shared {@link IdGenerator},\n * for a controller that owns the element side itself — the menu overlay's opener\n * registry keeps one seed id across many openers, so it needs the id without a\n * slot's single-element storage.\n *\n * Call it from an injection context — a directive's field initializer, or a\n * controller constructed from one — so the generator resolves and slot id\n * sequences stay deterministic across renders (hydration relies on it).\n */\nexport function injectSlotId(idPrefix: string, suffix: string): WritableSignal<string> {\n return signal(inject(IdGenerator).next(`${idPrefix}-${suffix}`));\n}\n\n/**\n * A slot whose element registration adopts a consumer-set static `id`. Seeds the\n * id signal with `<idPrefix>-<suffix>` off the shared {@link IdGenerator}, so it\n * carries the same injection-context requirement as {@link injectSlotId}.\n *\n * @typeParam E Concrete element type the slot registers. Defaults to\n * `HTMLElement`.\n */\nexport function injectIdentifiedSlot<E extends HTMLElement = HTMLElement>(\n idPrefix: string,\n suffix: string,\n): IdentifiedElementSlot<E> {\n return new IdentifiedElementSlot<E>(injectSlotId(idPrefix, suffix));\n}\n\n/**\n * The floating-ui anchor slot with the settled single-anchor warning + fallback\n * chain. Must be called in an injection context, which a directive field\n * initializer is, because the dev-mode duplicate warning runs on an `effect`.\n *\n * @param config Names the root and its anchor piece in the duplicate warning.\n */\nexport function anchorSlot(config: SingleSlotConfig): AnchorSlot {\n return new AnchorSlot(config);\n}\n","import { linkedSignal, type Signal, untracked, type WritableSignal } from '@angular/core';\n\n/**\n * Records the reason of an overlay's most recent close, and clears it whenever the overlay's open\n * source turns `true`, whoever wrote it: an owner's own open path, an APG key, or a consumer's\n * `[(open)]` binding. The shared content pieces read it to skip their return-focus on a `'tab'`\n * close (so Tab advances focus out of the surface instead of snapping back to the trigger).\n *\n * `close` records the reason before running the close, so a synchronous `openChange` handler\n * already reads it, and settles it against the closed state before returning. A later read that\n * finds the source changed but closed again therefore knows an open happened in between, even one\n * nothing read during.\n *\n * Generic over the reason union so every overlay controller shares one implementation —\n * `OverlayController` (and through it `MenuOverlay`, the listbox overlays, combobox and\n * `[forMenubar]`'s multiplexed menu context) and `[forPopover]` compose it, and\n * `injectOverlayShell` records the closes it requests itself in one, so its return-focus skip\n * lasts one open. Plain class (no `inject()`) so each composes it instead of hand-copying the\n * signal.\n *\n * @typeParam Reason Close-reason union owned by the controller.\n */\nexport class CloseReasonState<Reason> {\n readonly #reason: WritableSignal<Reason | null>;\n\n /**\n * Reason of the most recent close, or `null` while the overlay is open / has never closed.\n */\n readonly reason: Signal<Reason | null>;\n\n constructor(isOpen: () => boolean) {\n this.#reason = linkedSignal<boolean, Reason | null>({\n source: isOpen,\n computation: (open, previous) => (open || !previous?.source ? null : previous.value),\n });\n this.reason = this.#reason.asReadonly();\n }\n\n close(reason: Reason, apply: () => void): void {\n this.#reason.set(reason);\n apply();\n untracked(this.#reason);\n }\n}\n","import { type Signal, signal } from '@angular/core';\n\n/**\n * Tracks where an overlay's initial focus should land on the next open and\n * whether that one programmatic move should reflect `data-highlighted` on the\n * focused item.\n *\n * `target` is set by triggers before they flip the overlay open (ArrowDown →\n * `'first'`, ArrowUp → `'last'`, or a primitive-specific `'selected'`).\n * `highlightOnNextFocus` is armed per open via {@link prepareOpen}: a keyboard\n * activation highlights the focused item per the APG menu-button pattern; a\n * pointer activation (click, hover-after-open) suppresses the highlight so a\n * mouse-opened surface doesn't read as \"preselected\". {@link consumeHighlight}\n * reads the flag once and re-arms it to `true`, so the suppression applies only\n * to the single initial-focus move that follows an open.\n *\n * Generic over the focus-target union so every overlay controller reuses the\n * same one-shot protocol: `MenuOverlay` / `[forMenubar]`'s multiplexed menu\n * context keep `'first' | 'last'` (the default), while the listbox overlays and\n * combobox widen it with `'selected'`. Plain class (no `inject()`) so each\n * controller composes the same implementation instead of hand-copying it.\n *\n * @typeParam Focus Initial-focus target union. Defaults to `'first' | 'last'`.\n */\nexport class InitialFocusState<Focus = 'first' | 'last'> {\n readonly #target: ReturnType<typeof signal<Focus>>;\n #highlightOnNextFocus = true;\n\n /** Where focus should land when the overlay mounts. */\n readonly target: Signal<Focus>;\n\n /**\n * @param defaultTarget Initial focus target before any open. Defaults to\n * `'first'`, valid for the default `'first' | 'last'` union.\n */\n constructor(defaultTarget: Focus = 'first' as Focus) {\n this.#target = signal<Focus>(defaultTarget);\n this.target = this.#target.asReadonly();\n }\n\n setTarget(target: Focus): 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: Focus, 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","import {\n effect,\n type OutputEmitterRef,\n type Signal,\n untracked,\n type WritableSignal,\n} from '@angular/core';\n\nimport {\n emitVetoableNativeEvent,\n injectVetoableEmitter,\n type VetoableEvent,\n type VetoableNativeEvent,\n type TouchDismissal,\n} from 'forty-cdk/core';\nimport { CloseReasonState } from './close-reason-state';\nimport { IdentifiedElementSlot, injectSlotId } from './element-registry';\nimport { InitialFocusState } from './initial-focus-state';\n\n/**\n * The dismiss / auto-focus outputs an overlay controller forwards to. Each\n * primitive 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 OverlayEmitTargets {\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 * One of the two element sides a surface has — the trigger focus returns to, and\n * the content that mounts. Both are supplied by the composing controller,\n * because neither is the same object twice in the library: a listbox overlay's\n * trigger is the active one of those registered with its root, a menu overlay's is a\n * registry of openers resolving one active element and its id, and\n * `[forMenubar]`'s multiplexed context resolves both sides off whichever bar\n * trigger is — or was last — active.\n */\nexport interface OverlaySide {\n /**\n * The element's aria-wiring id. Non-empty for a slot minting its own; the\n * menubar's multiplexed sources resolve `''` until a trigger has been active,\n * which `[forMenuContent]` emits as no attribute rather than as `id=\"\"`.\n */\n readonly id: Signal<string>;\n /** The registered element, or `null` while none is registered. */\n readonly element: Signal<HTMLElement | null>;\n}\n\nexport interface OverlaySlot extends OverlaySide {\n /** Register the element. */\n register(el: HTMLElement): void;\n /** Deregister the element. */\n unregister(el: HTMLElement): void;\n}\n\n/**\n * Per-transition options forwarded verbatim to the `onOpen` / `onClose` hooks so\n * a host directive can react to *how* a transition was driven without\n * re-deriving it from outside the pipeline.\n */\nexport interface OverlayTransitionOptions {\n /**\n * When `true`, the transition is pointer-driven (hover) and the surface's\n * imperative focus move must be suppressed — an open must not pull focus into\n * the surface, and a close must not return focus to the trigger. Defaults to\n * `false`, so keyboard / click / programmatic transitions move focus as usual.\n */\n readonly suppressFocusMoves?: boolean;\n}\n\n/** Per-call options for {@link OverlayController.open}. */\nexport interface OverlayOpenOptions {\n /**\n * Arms the initial-focus state's one-shot highlight flag for this open —\n * `true` for a keyboard activation, `false` for a pointer one. Omit it\n * entirely on a surface that does not reflect `data-highlighted` on its\n * initial focus, so the flag is left untouched.\n */\n readonly highlight?: boolean;\n /** Transition options handed verbatim to the `onOpen` hook. */\n readonly transition?: OverlayTransitionOptions;\n}\n\n/**\n * What {@link OverlayController.open} did, so a composing controller can run its\n * own tail without re-reading the open model (which the call may just have\n * written).\n *\n * - `'blocked'` — the control is disabled; nothing happened.\n * - `'opened'` — the surface transitioned from closed to open.\n * - `'already-open'` — the surface was already mounted, so no state transition\n * (and therefore no `openChange` emit) happened. The initial-focus target and\n * the close reason were still re-armed.\n */\nexport type OverlayOpenOutcome = 'blocked' | 'opened' | 'already-open';\n\n/**\n * Construction-time wiring for {@link OverlayController}. Plain signals and\n * callbacks only — the controller never imports a primitive's context token,\n * mirroring `injectOverlayShell`, so it stays orthogonal to each root's surface.\n *\n * @typeParam Focus Initial-focus union owned by the composing controller.\n * @typeParam CloseReason Close-reason union owned by the composing controller.\n */\nexport interface OverlayControllerDeps<Focus, CloseReason> {\n /** Id-generator prefix base, e.g. `'for-select'` (suffixed with `-trigger` / `-content`). */\n readonly idPrefix: string;\n /**\n * Builds the trigger side, from a factory minting the seeded\n * `<idPrefix>-trigger` id. Call the factory exactly once for a trigger that\n * owns an id, and **not at all** for one whose id lives elsewhere — the\n * combobox's lives on its input, the menubar's on each bar trigger — because\n * the `IdGenerator` counter is per application, so an id nothing ever emits\n * still shifts every id minted after it.\n *\n * Runs during construction, ahead of {@link createContent}, so the\n * trigger-then-content minting order is fixed here rather than per caller —\n * hydration's id adoption depends on both renders repeating it. It may\n * `inject()`, and so may the factory.\n */\n readonly createTrigger: (mintId: () => WritableSignal<string>) => OverlaySide;\n /**\n * Builds the content side, same contract as {@link createTrigger} and called\n * immediately after it. Optional: omitted, the controller registers its own\n * {@link IdentifiedElementSlot} over the minted `<idPrefix>-content` id, which\n * is what every surface owning its content id wants. Supply it when the id\n * comes from somewhere else, or when registration does more than adopt a\n * static id — `[forMenubar]` resolves the id off the active trigger and\n * records whether the surface is shared across the bar's triggers.\n */\n readonly createContent?: (mintId: () => WritableSignal<string>) => OverlaySlot;\n /** Default initial-focus target before any open. */\n readonly defaultInitialFocus: Focus;\n /** The control's effective disabled — gates `open` and `toggle`. */\n readonly disabled: Signal<boolean>;\n /** Whether Escape / outside interactions dismiss the surface. */\n readonly dismissible: Signal<boolean>;\n /** Read the control's current open state. */\n readonly isOpen: () => boolean;\n /** Write the control's open state — the open / close machine's only channel. */\n readonly setOpen: (open: boolean) => void;\n /** Dismiss / auto-focus outputs to forward to. */\n readonly emit: OverlayEmitTargets;\n /** Close reason recorded when Escape dismisses the surface. */\n readonly escapeReason: CloseReason;\n /** Close reason recorded when {@link OverlayController.toggle} closes the surface. */\n readonly programmaticReason: CloseReason;\n /**\n * Side effect run after {@link OverlayController.open} resolves an un-blocked\n * open, receiving the resolved initial-focus target and the transition\n * options. Runs on the `'already-open'` outcome too, so a pending hover-close\n * is still cancelled by an open key pressed on a mounted surface.\n */\n readonly onOpen?: (initialFocus: Focus, options: OverlayTransitionOptions) => void;\n /**\n * Side effect run after {@link OverlayController.close} flips the open state\n * to `false`, receiving the close reason and the transition options. Also\n * runs, with the programmatic reason, when the open state turns `false`\n * through any other channel, such as a consumer's `[(open)]` write.\n */\n readonly onClose?: (reason: CloseReason, options: OverlayTransitionOptions) => void;\n /**\n * Side effect run on a user-driven dismissal — an un-vetoed Escape, or the\n * shell's implicit close after an un-vetoed outside interaction — just before\n * the close, receiving the channel that requested it. Optional: only a form\n * control has touched state to mark, so the menu overlays pass nothing.\n */\n readonly onDismiss?: (dismissal: TouchDismissal) => void;\n}\n\n/**\n * The open / close / dismiss machine every trigger-anchored overlay surface\n * runs, composed by `MenuOverlay` (the four menu roots), by\n * `ListboxOverlayController` (`[forSelect]` / `[forTimePicker]`), and by\n * `[forCombobox]` and `[forMenubar]`. It owns the initial-focus and close-reason\n * state, the `disabled`-gated open / close / toggle transitions, the four\n * outside / Escape emit forwarders, the shell's implicit `requestClose`, and the\n * two auto-focus veto pass-throughs — plus the order in which the two supplied\n * element sides mint their ids.\n *\n * It does not own the item **collection**: the menu side composes `MenuItemList`\n * separately, and the two navigate tails differ — the menu suppresses the item\n * highlight and scrolls the surface's own overflow, the listbox runs a\n * per-primitive `onNavigateFocus` and gates the move on `disabled`.\n *\n * Construct it from a directive's field initializer, or from a controller\n * constructed there: it reads that directive's `DestroyRef` for the auto-focus\n * vetoes, and the slot factories' `inject()` calls resolve through the same\n * injector.\n *\n * @typeParam Focus Initial-focus union owned by the composing controller.\n * @typeParam CloseReason Close-reason union owned by the composing controller.\n */\nexport class OverlayController<Focus, CloseReason> {\n readonly #deps: OverlayControllerDeps<Focus, CloseReason>;\n\n readonly #triggerSlot: OverlaySide;\n readonly #contentSlot: OverlaySlot;\n\n readonly #initialFocusState: InitialFocusState<Focus>;\n readonly #closeReasonState: CloseReasonState<CloseReason>;\n\n readonly #autoFocusOnOpen: () => boolean;\n readonly #autoFocusOnClose: () => boolean;\n\n /** Set by {@link close} so the open-state observer skips the edge it already handled. */\n #closedHere = false;\n\n /** The trigger's stable id, adopted from a consumer-set static id when present. */\n readonly triggerId: Signal<string>;\n\n /** The content surface's stable id, adopted from a consumer-set static id when present. */\n readonly contentId: Signal<string>;\n\n /** The focusable element the surface returns focus to on close. */\n readonly trigger: Signal<HTMLElement | null>;\n\n /** The mounted content element, or `null` while the surface is closed. */\n readonly content: Signal<HTMLElement | null>;\n\n /** Where focus should land when the surface mounts. Set by triggers before flipping open. */\n readonly initialFocus: Signal<Focus>;\n\n /**\n * Reason of the most recent close, or `null` while the surface is open / has\n * never closed. Reset to `null` on every open — the content pieces read it to\n * skip their return-focus on a `'tab'` close.\n */\n readonly lastCloseReason: Signal<CloseReason | null>;\n\n constructor(deps: OverlayControllerDeps<Focus, CloseReason>) {\n this.#deps = deps;\n const mintContentId = () => injectSlotId(deps.idPrefix, 'content');\n this.#triggerSlot = deps.createTrigger(() => injectSlotId(deps.idPrefix, 'trigger'));\n this.#contentSlot = deps.createContent\n ? deps.createContent(mintContentId)\n : new IdentifiedElementSlot(mintContentId());\n this.#initialFocusState = new InitialFocusState<Focus>(deps.defaultInitialFocus);\n this.#closeReasonState = new CloseReasonState<CloseReason>(deps.isOpen);\n this.#autoFocusOnOpen = injectVetoableEmitter(deps.emit.autoFocusOnOpen);\n this.#autoFocusOnClose = injectVetoableEmitter(deps.emit.autoFocusOnClose);\n this.triggerId = this.#triggerSlot.id;\n this.contentId = this.#contentSlot.id;\n this.trigger = this.#triggerSlot.element;\n this.content = this.#contentSlot.element;\n this.initialFocus = this.#initialFocusState.target;\n this.lastCloseReason = this.#closeReasonState.reason;\n\n let wasOpen = untracked(deps.isOpen);\n // @sanctioned-effect(untracked-read): only `isOpen` is tracked, and the close\n // it runs leaves that state where the other channel already put it.\n effect(() => {\n const open = deps.isOpen();\n untracked(() => {\n const closedElsewhere = wasOpen && !open && !this.#closedHere;\n wasOpen = open;\n this.#closedHere = false;\n if (closedElsewhere) {\n this.close(deps.programmaticReason);\n }\n });\n });\n }\n\n /** Set the initial-focus target ahead of the next open. */\n setInitialFocus(target: Focus): void {\n this.#initialFocusState.setTarget(target);\n }\n\n /**\n * Reads the initial-focus state's one-shot highlight flag and re-arms it, so\n * the composing controller's initial-focus move can suppress the focused\n * item's `data-highlighted` for a pointer-driven open only.\n */\n consumeInitialHighlight(): boolean {\n return this.#initialFocusState.consumeHighlight();\n }\n\n /** Register the mounted content element. */\n registerContent(el: HTMLElement): void {\n this.#contentSlot.register(el);\n }\n\n /** Deregister the content element (no-op unless the same node registered). */\n unregisterContent(el: HTMLElement): void {\n this.#contentSlot.unregister(el);\n }\n\n /**\n * Opens the surface when closed, closes it with the deps' programmatic reason\n * when open. Honours `disabled` on both branches — there is no distinct\n * `'trigger'` close reason for the user-initiated toggle-close path.\n */\n toggle(initialFocus: Focus, options: OverlayOpenOptions = {}): void {\n if (this.#deps.disabled()) {\n return;\n }\n if (this.#deps.isOpen()) {\n this.close(this.#deps.programmaticReason);\n } else {\n this.open(initialFocus, options);\n }\n }\n\n /**\n * Records where the initial focus should land and flips the open state,\n * which clears the close reason. Returns the {@link OverlayOpenOutcome} so a composing\n * controller can branch on an already-open surface — no state transition\n * happened there, so nothing emitted `openChange`, and a re-focus is the only\n * way an APG open key stays live on a mounted surface.\n */\n open(initialFocus: Focus, options: OverlayOpenOptions = {}): OverlayOpenOutcome {\n if (this.#deps.disabled()) {\n return 'blocked';\n }\n const alreadyOpen = this.#deps.isOpen();\n if (options.highlight === undefined) {\n this.#initialFocusState.setTarget(initialFocus);\n } else {\n this.#initialFocusState.prepareOpen(initialFocus, options.highlight);\n }\n if (!alreadyOpen) {\n this.#deps.setOpen(true);\n }\n this.#deps.onOpen?.(initialFocus, options.transition ?? {});\n return alreadyOpen ? 'already-open' : 'opened';\n }\n\n /**\n * Closes the surface, recording `reason` as the {@link lastCloseReason} the\n * content pieces read. Never gated on `disabled`: a control disabled while its\n * surface is open must still be closable.\n */\n close(reason: CloseReason, transition: OverlayTransitionOptions = {}): void {\n this.#closedHere = true;\n this.#closeReasonState.close(reason, () => this.#deps.setOpen(false));\n this.#deps.onClose?.(reason, transition);\n }\n\n /**\n * Escape on the anchored path: emit `(escapeKeyDown)`, then close when\n * un-vetoed and dismissible.\n */\n emitEscapeKeyDown(event: KeyboardEvent): void {\n const vetoed = emitVetoableNativeEvent(this.#deps.emit.escapeKeyDown, event);\n if (!vetoed && this.#deps.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 `core-overlay/dismissible-layer/dismissible-layer.ts`).\n event.stopPropagation();\n this.#deps.onDismiss?.('escape');\n this.close(this.#deps.escapeReason);\n }\n }\n\n /** Modal-path Escape forwarder: emit only; the modal shell owns the close. */\n forwardEscapeKeyDown(veto: VetoableNativeEvent<KeyboardEvent>): void {\n this.#deps.emit.escapeKeyDown.emit(veto);\n }\n\n /**\n * Outside-interaction emit forwarders. The shared `#pendingOutsideVeto` reuse\n * between the specific outside channels and the composite `interactOutside`\n * lives in `injectOverlayShell`; these only fire the matching output with the\n * veto the shell built.\n */\n emitPointerDownOutside(veto: VetoableNativeEvent<PointerEvent>): void {\n this.#deps.emit.pointerDownOutside.emit(veto);\n }\n\n /** Focus-outside emit forwarder — see {@link emitPointerDownOutside}. */\n emitFocusOutside(veto: VetoableNativeEvent<FocusEvent>): void {\n this.#deps.emit.focusOutside.emit(veto);\n }\n\n /** Composite outside-interaction emit forwarder — see {@link emitPointerDownOutside}. */\n emitInteractOutside(veto: VetoableNativeEvent<PointerEvent | FocusEvent>): void {\n this.#deps.emit.interactOutside.emit(veto);\n }\n\n /**\n * Implicit close requested by `injectOverlayShell` after an un-vetoed outside\n * interaction. The shell owns the shared `#pendingOutsideVeto` reuse between\n * the specific outside channels and the composite `interactOutside`; this\n * controller only owns the close. The open guard keeps a stale event from\n * re-closing an already-closed surface and clobbering its\n * {@link lastCloseReason} (e.g. a `'tab'` close must survive so the content\n * skips its return-focus).\n */\n requestClose(reason: CloseReason & Exclude<TouchDismissal, 'escape'>): void {\n if (!this.#deps.isOpen()) {\n return;\n }\n this.#deps.onDismiss?.(reason);\n this.close(reason);\n }\n\n /**\n * Emits `(autoFocusOnOpen)`, returning whether the mount's focus move is\n * vetoed — by a consumer, or by the root's own destruction.\n */\n emitAutoFocusOnOpen(): boolean {\n return this.#autoFocusOnOpen();\n }\n\n /**\n * Emits `(autoFocusOnClose)`, returning whether the return-focus move is\n * vetoed — by a consumer, or by the root's own destruction.\n */\n emitAutoFocusOnClose(): boolean {\n return this.#autoFocusOnClose();\n }\n}\n","import { DestroyRef, effect, ElementRef, inject, type Signal } from '@angular/core';\nimport type { ReferenceElement } from '@floating-ui/dom';\n\nimport {\n afterNextRenderCancellable,\n findFirstFocusable,\n findTabbableEdges,\n isInitialFocusTarget,\n leavesTabSequence,\n resolveActiveElement,\n resolveEventTarget,\n type VetoableNativeEvent,\n} from 'forty-cdk/core';\nimport {\n buildOutsideVetoOptions,\n injectDismissibleLayer,\n InertSiblingsStack,\n ModalActivationOrder,\n outsideVetoChannels,\n type DismissibleLayerActivateOptions,\n type DismissibleLayerNesting,\n} from 'forty-cdk/core-overlay';\n\nimport { CloseReasonState } from './close-reason-state';\n\n/**\n * The positioning strategy a trigger-anchored surface hands the shell, built by\n * `floatingPositioner` or `itemAlignedPositioner`. The shell installs it once at construction, so\n * switching strategies means remounting the surface. The installed positioner portals the host\n * by default, so the shell never calls `injectPortal` itself.\n */\nexport interface OverlayShellPositioner {\n /** The element the surface anchors to, also read to resolve the modal that owns the surface. */\n readonly reference: Signal<ReferenceElement | null>;\n /** Whether the surface is open. The shell scopes the closes it requests itself to one open. */\n readonly open: Signal<boolean>;\n /** Installs the positioner on the host. Called once, from the shell's injection context. */\n readonly attach: () => void;\n}\n\n/**\n * Outside-interaction wiring for a trigger-anchored overlay.\n *\n * Each wired channel builds one `VetoableNativeEvent` and hands it to both the specific emitter and\n * the composite `interactOutside` one, so a `preventDefault()` from either vetoes the close. When\n * nothing vetoes and `dismissible()` is `true`, the shell calls `requestClose` with the channel's\n * reason. `dismissible` and `requestClose` are required whenever any outside channel is wired.\n *\n * `exemptElements` is re-read on every event, so newly portaled siblings and swapped triggers are\n * honoured.\n *\n * Escape is forwarded verbatim and never participates in the outside-close: its close behaviour\n * differs per primitive, so emitting and closing stay the consumer's decision.\n *\n * Every callback is optional; the shell registers a listener only for the channels supplied.\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`. Each wired outside\n * channel fires its own close, so a specific channel (`emitPointerDownOutside`\n * / `emitFocusOutside`) closes even without `emitInteractOutside` wired. A\n * close requested here does not return focus on destroy, unless the surface\n * reopens before it unmounts and then closes some other way.\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, and handed the node being tested.\n */\n readonly exemptElements?: (target: Node) => readonly Element[];\n /**\n * Declared nesting position of this surface inside a chain of structurally\n * nested overlays (a menu and its submenus). Forwarded verbatim to the\n * dismissible layer so the stack orders the chain by depth instead of by the\n * order the levels happened to render in. Omit for a standalone overlay.\n */\n readonly nesting?: DismissibleLayerNesting;\n /**\n * Whether the surface also closes on an outside press the overlay stacked directly above it\n * closed on, instead of leaving that press to the topmost overlay alone. Read on every press.\n */\n readonly cascadeOutsidePress?: () => boolean;\n /**\n * Called after a surface opened from inside this one closes, that is an\n * overlay whose anchor lies inside this surface or inside an overlay opened\n * from it.\n */\n readonly onNestedLayerRemoved?: () => void;\n}\n\n/**\n * Handle returned by {@link injectOverlayShell}.\n */\nexport interface OverlayShell {\n /**\n * Whether a surface opened from inside this one is still open above it: an\n * overlay anchored inside this surface, or inside an overlay opened from it.\n * Always `false` for a shell without `dismiss` wiring.\n */\n hasNestedLayer(): boolean;\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 * `focusInitialEnabledItem`, 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 * Element the consumer marked as the initial focus target, read once at mount. When it resolves\n * to an element that passes `isInitialFocusTarget`, focus lands there instead of running `move`.\n */\n readonly target?: () => HTMLElement | null;\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, read before `veto`. The shell already skips\n * the return after a close it requested itself, through an outside channel\n * or a Tab out, since focus is then where the user moved it. `skip` covers\n * the closes that reach the root another way, such as a Tab the root handles\n * or a close propagated from a nested surface. The shell's own skip lasts one\n * open: a surface reopened while still mounted returns focus on its next\n * close like any other.\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 * Optional Tab-out wiring for a non-modal surface portaled away from its trigger. A Tab past the\n * surface's last tabbable lands on the element after `target` in the page's tab order, and a\n * Shift+Tab before its first lands on `target` itself, as if the surface sat right after it.\n *\n * - `target` — the element the surface follows in the tab order (typically the trigger).\n * Returning `null` leaves Tab to the browser.\n * - `close` — closes the surface after the focus move, unless `dismiss.dismissible()` is\n * `false`. Return focus is skipped for that close.\n */\nexport interface OverlayShellTabOutConfig {\n readonly target: () => HTMLElement | null;\n readonly close: () => void;\n}\n\n/**\n * Single config for the overlay-content lifecycle. Each sub-bundle is\n * individually optional so each trigger-anchored primitive (Popover, the menu\n * roots, Combobox, Select, DatePicker, TimePicker, Tooltip, HoverCard) can opt\n * in to only the pieces it needs.\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: OverlayShellPositioner;\n readonly dismiss?: OverlayShellDismissConfig;\n readonly initialFocus?: OverlayShellInitialFocusConfig;\n readonly returnFocus?: OverlayShellReturnFocusConfig;\n readonly tabOut?: OverlayShellTabOutConfig;\n}\n\n/**\n * Owns the lifecycle of a portaled, trigger-anchored overlay surface — the `*-content` directives\n * of Popover, the menu family, Combobox, Select, Tooltip and HoverCard.\n *\n * Positioning is delegated to the configured positioner, which portals the host itself: the caller\n * must not also call `injectPortal`.\n *\n * When configured, the shell activates a dismissible layer after the first render, performs the\n * initial focus move — falling back to the host when the move finds no candidate — and restores\n * focus to the return target on destroy. Both focus moves are skipped when their `veto()` returns\n * truthy, which is how `autoFocusOnOpen` / `autoFocusOnClose` are honoured. The return is also\n * skipped when the surface closed through one of its own outside channels or a Tab out, without\n * consulting `veto`: focus already moved where the user put it. That skip belongs to the open the\n * close ended, so a surface reopened before it unmounts returns focus on its next close, and one\n * reopened after a Tab out gets its dismissible layer back.\n *\n * Return focus runs after the portaled node has been detached, so the trigger receives the focus\n * event in a settled layout.\n *\n * Must be called from an injection context. The host's `ElementRef` is forwarded to the dismissible\n * layer and the positioner.\n */\nexport function injectOverlayShell(config: OverlayShellConfig): OverlayShell {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const el = host.nativeElement;\n const inertStack = inject(InertSiblingsStack);\n const order = inject(ModalActivationOrder);\n\n // 1. Dismissible layer. Created BEFORE the positioner so its\n // `DestroyRef.onDestroy` (dismissible.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 ? injectDismissibleLayer() : null;\n let layerOptions: DismissibleLayerActivateOptions | null = null;\n const ownClose = new CloseReasonState<'outside' | 'tab'>(config.positioner.open);\n\n // 2. Positioner.\n config.positioner.attach();\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 dismissible 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 // `injectDismissibleLayer`, 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 let destroyed = false;\n let releasePeer: (() => void) | null = null;\n inject(DestroyRef).onDestroy(() => {\n destroyed = true;\n releasePeer?.();\n releasePeer = null;\n });\n afterNextRenderCancellable(() => {\n const anchor = resolveModalAnchor(config);\n order.after(order.enclosingHeld(anchor), () => {\n if (!destroyed) {\n activate(anchor);\n }\n });\n });\n\n const activate = (anchor: Element | null): void => {\n // Modal-peer registration (#676). The positioner's portal ran in an\n // earlier hook of this same render batch, so the host is already in\n // `body`. Registering it with the anchor lets `InertSiblingsStack` leave it\n // live while the anchor belongs to the topmost modal — opened from inside a\n // Dialog / Drawer (a Select in a form, a context menu on dialog content) —\n // and inert it under any other owner, so a toast / background overlay stays\n // isolated (#388) and a background modal's overlay is inerted under a\n // nested modal. The registration lands before the inert observer's\n // microtask inspects the portaled host.\n if (anchor !== null) {\n releasePeer = inertStack.registerPeer(el, [anchor]);\n }\n\n if (layer && dismissCfg) {\n const requestClose = dismissCfg.requestClose;\n const options: DismissibleLayerActivateOptions = {\n channels: outsideVetoChannels(dismissCfg),\n ...buildOutsideVetoOptions(\n requestClose\n ? {\n ...dismissCfg,\n requestClose: (reason) => ownClose.close('outside', () => requestClose(reason)),\n }\n : dismissCfg,\n ),\n };\n\n if (dismissCfg.exemptElements) {\n options.exemptElements = dismissCfg.exemptElements;\n }\n if (dismissCfg.nesting) {\n options.nesting = dismissCfg.nesting;\n }\n if (dismissCfg.cascadeOutsidePress) {\n options.cascadeOutsidePress = dismissCfg.cascadeOutsidePress;\n }\n if (dismissCfg.onNestedLayerRemoved) {\n options.onNestedLayerRemoved = dismissCfg.onNestedLayerRemoved;\n }\n if (anchor !== null) {\n options.anchor = anchor;\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\n layerOptions = options;\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 marked = focusCfg.target?.() ?? null;\n const move = focusCfg.move;\n if (marked !== null && isInitialFocusTarget(marked, el)) {\n marked.focus();\n } else 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 const tabOutCfg = config.tabOut;\n if (tabOutCfg) {\n const closeOnTab = (): void => ownClose.close('tab', tabOutCfg.close);\n let layerParked = false;\n const onKeyDown = (event: KeyboardEvent): void => {\n const closes = dismissCfg?.dismissible?.() ?? true;\n if (handleTabOut(event, el, tabOutCfg.target, closes ? closeOnTab : null) && layer) {\n layerParked = true;\n layer.deactivate();\n }\n };\n el.addEventListener('keydown', onKeyDown);\n inject(DestroyRef).onDestroy(() => el.removeEventListener('keydown', onKeyDown));\n\n if (layer) {\n effect(() => {\n if (ownClose.reason() === null && layerParked && layerOptions !== null) {\n layerParked = false;\n layer.activate(layerOptions);\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 the positioner's `attach`) 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 (ownClose.reason() !== null || 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 return { hasNestedLayer: () => layer?.hasNestedLayer() ?? false };\n}\n\n/**\n * Moves focus to the tab-out target when a Tab press would leave the surface's Tab cycle, then\n * runs `close` when one is given. A forward Tab keeps its default action so the browser advances\n * from the target, with the surface inert until that action has run so the advance never lands\n * back inside it; a backward one is prevented so focus stays on it. Returns whether it closed.\n */\nfunction handleTabOut(\n event: KeyboardEvent,\n host: HTMLElement,\n resolveTarget: () => HTMLElement | null,\n close: (() => void) | null,\n): boolean {\n if (\n event.key !== 'Tab' ||\n event.defaultPrevented ||\n event.altKey ||\n event.ctrlKey ||\n event.metaKey\n ) {\n return false;\n }\n const target = resolveTarget();\n if (target === null) {\n return false;\n }\n const from = resolveEventTarget(event);\n const backward = event.shiftKey;\n if (\n !leavesTabSequence(findTabbableEdges(host), from instanceof Element ? from : null, backward)\n ) {\n return false;\n }\n target.focus();\n if (resolveActiveElement(target.ownerDocument) !== target) {\n return false;\n }\n if (backward) {\n event.preventDefault();\n } else {\n skipTabDefaultAction(host);\n }\n if (close === null) {\n return false;\n }\n close();\n return true;\n}\n\n/**\n * Keeps a surface out of a forward Tab's default action. Call it after moving focus out of the\n * surface from that Tab's `keydown`, without preventing the event: the browser then advances from\n * the element that took focus, and the surface is inert until that advance has run, so a surface\n * that is still mounted and tabbable is never the element focus advances into. The overlay shell's\n * Tab-out and `ListboxOverlayController.commitTabToTrigger` are its callers.\n */\nexport function skipTabDefaultAction(host: HTMLElement): void {\n if (host.hasAttribute('inert')) {\n return;\n }\n host.setAttribute('inert', '');\n setTimeout(() => host.removeAttribute('inert'), 0);\n}\n\n/**\n * Resolves the real DOM element an overlay is anchored to, for the modal-peer ownership check.\n *\n * Falls back to the `VirtualElement`'s `contextElement` and then to the return-focus target for\n * pointer-positioned overlays. Returns `null` when no backing element exists, leaving the overlay\n * unmarked.\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 { type Signal } from '@angular/core';\nimport type { ReferenceElement } from '@floating-ui/dom';\n\nimport {\n accessibleTextContent,\n Collection,\n firstEnabledHost,\n injectFieldAnchor,\n injectTypeahead,\n lastEnabledHost,\n type ListNavigationAction,\n nextEnabledHandle,\n resolveActiveElement,\n resolveListTypeahead,\n type SingleSlotConfig,\n type VetoableNativeEvent,\n dismissMarksTouched,\n type TouchDismissal,\n} from 'forty-cdk/core';\nimport {\n anchorSlot,\n type AnchorSlot,\n type RootedTriggerHandle,\n RootedTriggerSlot,\n} from '../overlay-controller/element-registry';\nimport {\n OverlayController,\n type OverlayEmitTargets,\n} from '../overlay-controller/overlay-controller';\nimport {\n type OverlayShellTabOutConfig,\n skipTabDefaultAction,\n} from '../overlay-controller/overlay-shell';\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 * 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 readonly triggers: Signal<readonly RootedTriggerHandle[]>;\n /** Names the root and its anchor piece in the dev-mode duplicate-anchor warning. */\n readonly anchorSlot: SingleSlotConfig;\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: OverlayEmitTargets;\n /** Whether keyboard navigation wraps at the ends of the option list. */\n readonly loop: Signal<boolean>;\n /** Whether Escape / outside interactions dismiss the overlay. */\n readonly dismissible: Signal<boolean>;\n /** Close reason set when Escape dismisses the overlay (both primitives use `'escape'`). */\n readonly escapeReason: CloseReason;\n /** Close reason set when {@link ListboxOverlayController.toggle} closes the overlay (both primitives use `'programmatic'`). */\n readonly programmaticReason: CloseReason;\n /** Mark the control touched on a dismissal that {@link dismissMarksTouched} counts. */\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` or a typeahead match 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 * The texts open-state typeahead matches an option against, any of which may match. Defaults to\n * the option's accessible text (TimePicker adds its label without the hour's leading zero).\n */\n readonly typeaheadText?: (handle: H) => string | readonly string[];\n}\n\n/**\n * The narrow, typed facade a primitive surfaces on its coordination context\n * (`ctx.overlay`) so child directives read the shared overlay-listbox state and\n * behavior here instead of the root re-forwarding every member. Implemented by\n * {@link ListboxOverlayController}; each primitive's context exposes it as a\n * sub-object, keeping the child-facing surface a single, self-documenting seam.\n *\n * @typeParam H Primitive option-handle type.\n * @typeParam Focus Initial-focus union.\n * @typeParam CloseReason Close-reason union owned by the primitive.\n */\nexport interface ListboxOverlayContext<H extends ListboxOverlayOptionHandle, Focus, CloseReason> {\n /**\n * The active trigger's id, which the content names in `aria-labelledby`, or `''` while no\n * trigger is registered.\n */\n readonly triggerId: Signal<string>;\n /** The content surface's stable id, adopted from a consumer-set static id when present. */\n readonly contentId: Signal<string>;\n /** Where focus should land after the content mounts. Triggers set this before flipping `open`. */\n readonly initialFocus: Signal<Focus>;\n /** Reason of the most recent close, or `null` while open (or before any close). */\n readonly lastCloseReason: Signal<CloseReason | null>;\n /**\n * The active trigger: the one that last opened or toggled the listbox, else the newest\n * registered. The listbox anchors to it and returns focus to it.\n */\n readonly trigger: Signal<HTMLElement | null>;\n /**\n * Element floating-ui anchors the content against. Prefers a registered\n * anchor, otherwise falls back to the trigger.\n */\n readonly anchor: Signal<ReferenceElement | null>;\n /** The mounted content element. */\n readonly content: Signal<HTMLElement | null>;\n /** All registered options in DOM order. */\n readonly options: Signal<readonly H[]>;\n\n /** Set the initial-focus target ahead of the next open. */\n setInitialFocus(target: Focus): void;\n\n registerAnchor(el: HTMLElement): void;\n unregisterAnchor(el: HTMLElement): void;\n registerContent(el: HTMLElement): void;\n unregisterContent(el: HTMLElement): void;\n registerOption(handle: H): void;\n unregisterOption(handle: H): void;\n\n /** Move focus inside the open content in response to an arrow / Home / End key. */\n navigate(currentOption: HTMLElement, action: ListNavigationAction): void;\n focusFirstEnabledOption(): boolean;\n focusLastEnabledOption(): boolean;\n\n toggle(initialFocus: Focus): void;\n openOverlay(initialFocus: Focus): void;\n closeOverlay(reason: CloseReason): void;\n\n /** Escape on the anchored path: emit `(escapeKeyDown)`, then close when un-vetoed and dismissible. */\n emitEscapeKeyDown(event: KeyboardEvent): void;\n emitPointerDownOutside(veto: VetoableNativeEvent<PointerEvent>): void;\n emitFocusOutside(veto: VetoableNativeEvent<FocusEvent>): void;\n emitInteractOutside(veto: VetoableNativeEvent<PointerEvent | FocusEvent>): void;\n /** Modal-path Escape forwarder: emit only; the modal shell owns the close. */\n forwardEscapeKeyDown(veto: VetoableNativeEvent<KeyboardEvent>): void;\n /** Implicit close requested by the shell after an un-vetoed outside interaction. */\n requestClose(reason: CloseReason & Exclude<TouchDismissal, 'escape'>): void;\n emitAutoFocusOnOpen(): boolean;\n emitAutoFocusOnClose(): boolean;\n}\n\n/**\n * {@link ListboxOverlayContext} plus the calls only a primitive's option pieces make, so the\n * blessed surface a root publishes on `ctx.overlay` never carries them. Each primitive reads\n * its `ctx.overlay` at this type through its own internal context.\n *\n * Internal core tier — exported from `forty-cdk/core-anchored` for the library's\n * own entry points, with no semver guarantee.\n *\n * @typeParam H Primitive option-handle type.\n * @typeParam Focus Initial-focus union.\n * @typeParam CloseReason Close-reason union.\n */\nexport interface ListboxOverlayPieceContext<\n H extends ListboxOverlayOptionHandle,\n Focus,\n CloseReason,\n> extends ListboxOverlayContext<H, Focus, CloseReason> {\n /**\n * Open-state typeahead: focus the first enabled option after the event target whose\n * accessible text matches the buffered prefix. Returns `true` when the key was consumed,\n * so a Space the buffer took must not also activate.\n */\n handleTypeahead(event: KeyboardEvent): boolean;\n /** Every registered trigger's host, each exempt from the outside-press and outside-focus checks. */\n readonly triggerHosts: Signal<readonly HTMLElement[]>;\n /** Make the trigger on `host` the active one. A trigger calls it as it opens or toggles. */\n activateTrigger(host: HTMLElement): 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). It owns\n * the option collection, the anchor slot, the DOM-focus navigation algorithm and\n * the trigger focus move; everything the menu overlays run identically — the\n * trigger / content slots and their ids, the initial-focus and close-reason\n * state, the open / close machine, the dismiss / auto-focus forwarders — is the\n * shared {@link OverlayController}'s, composed here rather than re-declared.\n *\n * Value-specific behaviour (selection equality, `activate`, `focusSelectedOption`,\n * closed-state 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 core tier — exported from `forty-cdk/core-anchored` for the library's\n * own entry points, with no semver guarantee.\n *\n * Construct it from a directive's field initializer, so the slot factories'\n * `inject()` calls resolve through the directive's injector.\n *\n * @typeParam H Primitive option-handle type.\n * @typeParam Focus Initial-focus union.\n * @typeParam CloseReason Close-reason union.\n */\nexport class ListboxOverlayController<\n H extends ListboxOverlayOptionHandle,\n Focus,\n CloseReason,\n> implements ListboxOverlayPieceContext<H, Focus, CloseReason> {\n readonly #deps: ListboxOverlayControllerDeps<H, Focus, CloseReason>;\n readonly #items = new Collection<H>();\n readonly #typeahead = injectTypeahead();\n\n readonly #anchorSlot: AnchorSlot;\n readonly #triggerSlot: RootedTriggerSlot;\n readonly #controller: OverlayController<Focus, CloseReason>;\n\n /**\n * The active trigger's id, which the content names in `aria-labelledby`, or `''` while no\n * trigger is registered.\n */\n readonly triggerId: Signal<string>;\n\n /** The content surface's stable id, adopted from a consumer-set static id when present. */\n readonly contentId: Signal<string>;\n\n /** Where focus should land after the content mounts. Triggers set this before flipping `open`. */\n readonly initialFocus: Signal<Focus>;\n\n /** Reason of the most recent close, or `null` while open (or before any close). */\n readonly lastCloseReason: Signal<CloseReason | null>;\n\n /**\n * The active trigger: the one that last opened or toggled the listbox, else the newest\n * registered. The listbox anchors to it and returns focus to it.\n */\n readonly trigger: Signal<HTMLElement | null>;\n\n /**\n * Element floating-ui anchors the listbox against. Prefers an optional\n * registered anchor, then the surrounding field's `[forFieldAnchor]`,\n * otherwise falls back to the trigger so primitives without an anchor keep\n * their behavior.\n */\n readonly anchor: Signal<ReferenceElement | null>;\n\n /** The mounted content element. */\n readonly content: Signal<HTMLElement | null>;\n\n /** All registered options in DOM order. */\n readonly options: Signal<readonly H[]>;\n\n /** Every registered trigger's host, each exempt from the outside-press and outside-focus checks. */\n readonly triggerHosts: Signal<readonly HTMLElement[]>;\n\n constructor(deps: ListboxOverlayControllerDeps<H, Focus, CloseReason>) {\n this.#deps = deps;\n let triggerSlot!: RootedTriggerSlot;\n this.#controller = new OverlayController<Focus, CloseReason>({\n idPrefix: deps.idPrefix,\n createTrigger: () => {\n triggerSlot = new RootedTriggerSlot(deps.triggers);\n return triggerSlot;\n },\n defaultInitialFocus: deps.defaultInitialFocus,\n disabled: deps.effectiveDisabled,\n dismissible: deps.dismissible,\n isOpen: deps.isOpen,\n setOpen: deps.setOpen,\n emit: deps.emit,\n escapeReason: deps.escapeReason,\n programmaticReason: deps.programmaticReason,\n onClose: deps.onClose,\n onDismiss: (dismissal) => {\n if (dismissMarksTouched(dismissal)) {\n deps.markTouched();\n }\n },\n });\n this.#triggerSlot = triggerSlot;\n this.#anchorSlot = anchorSlot(deps.anchorSlot);\n this.triggerId = this.#controller.triggerId;\n this.contentId = this.#controller.contentId;\n this.initialFocus = this.#controller.initialFocus;\n this.lastCloseReason = this.#controller.lastCloseReason;\n this.trigger = this.#controller.trigger;\n this.triggerHosts = triggerSlot.hosts;\n this.content = this.#controller.content;\n this.anchor = this.#anchorSlot.resolve(injectFieldAnchor(), this.#controller.trigger);\n this.options = this.#items.items;\n }\n\n setInitialFocus(target: Focus): void {\n this.#controller.setInitialFocus(target);\n }\n\n activateTrigger(host: HTMLElement): void {\n this.#triggerSlot.activate(host);\n }\n\n registerAnchor(el: HTMLElement): void {\n this.#anchorSlot.register(el);\n }\n unregisterAnchor(el: HTMLElement): void {\n this.#anchorSlot.unregister(el);\n }\n\n registerContent(el: HTMLElement): void {\n this.#controller.registerContent(el);\n }\n unregisterContent(el: HTMLElement): void {\n this.#controller.unregisterContent(el);\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): void {\n if (this.#deps.effectiveDisabled()) {\n return;\n }\n const target = nextEnabledHandle(this.#items.items(), currentOption, action, {\n loop: this.#deps.loop(),\n });\n if (target === null) {\n return;\n }\n target.host.focus();\n this.#deps.onNavigateFocus?.(target);\n }\n\n handleTypeahead(event: KeyboardEvent): boolean {\n const items = this.#items.items();\n const { handled, match } = resolveListTypeahead(this.#typeahead, event, {\n items,\n anchorIndex: items.findIndex((o) => o.host === event.target),\n getText: this.#deps.typeaheadText ?? ((o) => accessibleTextContent(o.host)),\n isDisabled: (o) => o.disabled(),\n });\n if (match) {\n match.host.focus();\n this.#deps.onNavigateFocus?.(match);\n }\n return handled;\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 host = lastEnabledHost(this.#items.items());\n if (!host) {\n return false;\n }\n host.focus();\n return true;\n }\n\n /**\n * The option an open surface still has to scroll into view: the registered option holding DOM\n * focus, else `fallback()` when focus is on none of them. `null` when that option is the first\n * enabled one, which the surface already shows at its top, or when there is none.\n */\n revealTarget(fallback: () => HTMLElement | null = () => null): HTMLElement | null {\n const content = this.content();\n if (content === null) {\n return null;\n }\n const items = this.#items.items();\n const active = resolveActiveElement(content.ownerDocument);\n const target = items.find((o) => o.host === active)?.host ?? fallback();\n return target === firstEnabledHost(items) ? null : target;\n }\n\n /**\n * The overlay shell's Tab-out wiring: a Tab that leaves the open surface's tab cycle moves focus\n * to the trigger, so the browser advances from there rather than from the body-appended portal,\n * and closes with `reason`. The target resolves only while the overlay is open and `enabled()`\n * holds, so an option that already committed and closed on the same Tab keeps the browser's own\n * advance from the trigger.\n */\n tabOut(reason: CloseReason, enabled: () => boolean = () => true): OverlayShellTabOutConfig {\n return {\n target: () => (this.#deps.isOpen() && enabled() ? this.trigger() : null),\n close: () => this.closeOverlay(reason),\n };\n }\n\n toggle(initialFocus: Focus): void {\n this.#controller.toggle(initialFocus);\n }\n\n openOverlay(initialFocus: Focus): void {\n this.#controller.open(initialFocus);\n }\n\n closeOverlay(reason: CloseReason): void {\n this.#controller.close(reason);\n }\n\n emitEscapeKeyDown(event: KeyboardEvent): void {\n this.#controller.emitEscapeKeyDown(event);\n }\n\n emitPointerDownOutside(veto: VetoableNativeEvent<PointerEvent>): void {\n this.#controller.emitPointerDownOutside(veto);\n }\n emitFocusOutside(veto: VetoableNativeEvent<FocusEvent>): void {\n this.#controller.emitFocusOutside(veto);\n }\n emitInteractOutside(veto: VetoableNativeEvent<PointerEvent | FocusEvent>): void {\n this.#controller.emitInteractOutside(veto);\n }\n\n forwardEscapeKeyDown(veto: VetoableNativeEvent<KeyboardEvent>): void {\n this.#controller.forwardEscapeKeyDown(veto);\n }\n\n /**\n * Implicit close requested by the shell after an un-vetoed outside\n * interaction. The `isOpen` guard keeps a stale event from re-closing an\n * already-closed overlay and clobbering its `lastCloseReason` (e.g. a `'tab'`\n * close must survive so the content skips its return-focus).\n */\n requestClose(reason: CloseReason & Exclude<TouchDismissal, 'escape'>): void {\n this.#controller.requestClose(reason);\n }\n\n emitAutoFocusOnOpen(): boolean {\n return this.#controller.emitAutoFocusOnOpen();\n }\n\n emitAutoFocusOnClose(): boolean {\n return this.#controller.emitAutoFocusOnClose();\n }\n\n /**\n * Hands a Tab press that commits and closes the listbox to the trigger: focuses it, so the\n * browser's Tab default advances from there, and on a forward Tab keeps the content out of that\n * advance until it has run, so focus never re-enters the closing surface. Call it from the Tab\n * `keydown` before the close, without preventing the event.\n */\n commitTabToTrigger(event: KeyboardEvent): void {\n const trigger = this.#controller.trigger();\n if (trigger === null) {\n return;\n }\n trigger.focus();\n const content = this.content();\n if (\n event.shiftKey ||\n content === null ||\n resolveActiveElement(trigger.ownerDocument) !== trigger\n ) {\n return;\n }\n skipTabDefaultAction(content);\n }\n}\n","import { inject, InjectionToken, type Signal } from '@angular/core';\nimport type { ReferenceElement } from '@floating-ui/dom';\n\nimport {\n type CollectionHandle,\n type ListNavigationAction,\n orphanContextError,\n type VetoableNativeEvent,\n type WritingDirection,\n} from 'forty-cdk/core';\nimport type { DismissibleLayerNesting } from 'forty-cdk/core-overlay';\nimport type {\n FloatingAlign,\n FloatingFallbackAxisSideDirection,\n FloatingSide,\n} from '../floating/floating';\nimport type { MenuActivationModality } from './menu-overlay';\nimport type { Point } from '../pointer-grace/pointer-grace';\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 /**\n * Axis the bar lays its triggers out on. It decides what the horizontal\n * arrows do inside a menu opened from the bar: switch sibling menus on a\n * horizontal bar, return to the bar on a vertical one.\n */\n readonly orientation: Signal<'horizontal' | 'vertical'>;\n /**\n * Move focus/open to the previous or next sibling menu, returning whether the\n * bar actually moved. `false` means there was nowhere to go — the bar is\n * disabled, it has no registered triggers, or no enabled sibling exists in\n * that direction with `loop` off — so a caller must not tear down state (an\n * open submenu chain) it would then be unable to leave.\n */\n switchToSibling(direction: 'next' | 'prev'): boolean;\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. `'hover'` is a pointer-driven\n * (hover-leave) close and, like `'escape'` / `'programmatic'`, affects only\n * the level that scheduled it — it never propagates up the menu chain.\n */\nexport type ForMenuCloseReason =\n 'escape' | 'pointerDownOutside' | 'focusOutside' | 'select' | 'tab' | 'hover' | '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 the item's accessible\n * text for typeahead matching — useful when announced content such as a kbd\n * shortcut, a badge, or an SVG title would otherwise bleed into the match\n * string. Empty / unset means \"fall back to the host's accessible text\", which\n * already excludes any `aria-hidden` subtree.\n */\nexport interface ForMenuItemHandle extends CollectionHandle {\n /**\n * Narrowed from {@link CollectionHandle}'s `Node`: the menu focuses its items\n * and scrolls them into view.\n */\n readonly host: HTMLElement;\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 * 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, and\n * the menu calls it on every other item before a keyboard focus move.\n * Optional — items that don't reflect a highlight 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 /**\n * Direction `flip` falls back to on the perpendicular axis when both sides of\n * the preferred axis overflow. `'none'` (default) keeps only the opposite\n * same-axis placement; `'start'` / `'end'` let a submenu drop to a vertical\n * side on a narrow viewport. Threaded through to `injectOverlayShell`'s\n * floating positioner.\n */\n readonly fallbackAxisSideDirection: Signal<FloatingFallbackAxisSideDirection>;\n readonly collisionPadding: 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 /**\n * Id of the trigger, used as the surface's `aria-labelledby` fallback. An\n * empty string means the context has no trigger to name the surface with, and\n * `[forMenuContent]` emits no attribute at all — never `aria-labelledby=\"\"`.\n */\n readonly triggerId: Signal<string>;\n /**\n * Id the surface exposes, and the trigger's `aria-controls` target. An empty\n * string means the context has not associated a trigger with the surface yet\n * (only reachable under `[forMenubar]`, whose single context multiplexes over\n * the triggers), and `[forMenuContent]` emits no `id` at all — never `id=\"\"`.\n */\n readonly contentId: Signal<string>;\n readonly ariaLabel: Signal<string | null>;\n\n /**\n * Whether the trigger's own accessible name is a valid name for the menu\n * surface. `true` — the default when a root omits the member entirely — lets\n * `[forMenuContent]` fall back to `aria-labelledby=\"<triggerId>\"` when no\n * `ariaLabel` is set, which is correct for a discrete labelling control (a\n * `[forDropdownMenuTrigger]` button, a `[forMenubarTrigger]` or\n * `[forMenuSubTrigger]` menuitem). `[forContextMenu]` reports `false`: its\n * trigger is the whole right-click region, so an `aria-labelledby` pointing at\n * it would make screen readers announce the entire row / card text as the\n * menu's name. A root that reports `false` must expose `ariaLabel` as the way\n * to name the menu.\n *\n * A `Signal` rather than a plain `boolean` because a multi-opener root\n * (`[forMenu]`) has heterogeneous openers: a button opener *is* a labelling\n * control while a right-click region is not, so the answer is a property of\n * the **active** opener and changes as the menu is opened from a different one. Roots with a\n * single fixed trigger flavour report a constant signal.\n */\n readonly triggerLabelsMenu?: Signal<boolean>;\n\n /** Anchor passed to floating-ui — `HTMLElement` (Dropdown) or `VirtualElement` (Context). */\n readonly anchor: Signal<ReferenceElement | null>;\n\n /**\n * The element the menu was opened from (the trigger button or right-click\n * region). Focus returns here on close, except after a keyboard activation\n * from a focused element inside a right-click region, which returns focus to\n * that element while it is still in the document.\n */\n readonly trigger: Signal<HTMLElement | null>;\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 dismissible 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 dismissibleExemptions: 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 /**\n * Prefix-match against item text content and focus the first match. Returns\n * `true` when the key was consumed as a typeahead character (a printable\n * char, or Space while the buffer is already non-empty). Items applied on a\n * native `<button>` use this to `preventDefault()` a mid-typeahead Space so\n * it extends the buffer instead of activating the focused item.\n */\n handleTypeahead(event: KeyboardEvent): boolean;\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 /**\n * Focuses the first or last enabled item per `target` — the contract-level\n * resolution of {@link initialFocus}, so a piece that reads that signal hands\n * the value straight back instead of re-deriving which of the two granular\n * calls it maps to. `[forMenuContent]` uses it for the mount-time initial\n * focus; the mapping itself is owned once by core's `MenuItemList`. This is\n * the contract's only initial-focus entry point — the granular\n * `focusFirstEnabledItem` / `focusLastEnabledItem` pair stays on the concrete\n * controllers as an imperative escape hatch and is not part of what an\n * implementor owes. Returns `true` if focus moved; `false` when no enabled\n * items exist.\n */\n focusInitialEnabledItem(target: 'first' | 'last'): 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. The specific and composite channels\n * observe the same veto, so `preventDefault()` from either one suppresses the\n * close that otherwise follows.\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\n/**\n * Nesting descriptor for a menu level's dismissible layer, derived from the\n * `parentMenu` chain: the chain identity is the outermost menu context and the\n * depth is the number of hops needed to reach it (`0` for a top-level\n * `[forDropdownMenu]` / `[forContextMenu]` / `[forMenubar]` menu, `1` for its\n * first `[forMenuSub]`, and so on).\n *\n * Menu levels are ordered on the layer stack by this depth rather than by the\n * order their `afterNextRender` callbacks ran, because a menu and its submenu\n * mounted in the same render pass activate child-before-parent — which would\n * put the parent above its own submenu and make the submenu's first focus close\n * the whole chain with reason `'focusOutside'`.\n */\nexport function menuLayerNesting(ctx: ForMenuContext): DismissibleLayerNesting {\n let chain: ForMenuContext = ctx;\n let depth = 0;\n while (chain.parentMenu) {\n chain = chain.parentMenu;\n depth++;\n }\n return { chain, depth };\n}\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 orphanContextError({\n code: 'FORCDK-MENU-001',\n piece,\n root: '[forMenu], [forDropdownMenu], [forContextMenu], [forMenubar], or [forMenuSub]',\n token: 'FOR_MENU_CONTEXT',\n });\n }\n return ctx;\n}\n","import { type Signal } from '@angular/core';\n\nimport {\n accessibleTextContent,\n Collection,\n type CollectionHandle,\n firstEnabledHandle,\n injectTypeahead,\n lastEnabledHandle,\n type ListNavigationAction,\n nextEnabledHandle,\n resolveListTypeahead,\n type Typeahead,\n} from 'forty-cdk/core';\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 `./menu-context` (no cycle into a primitive).\n *\n * Stays exported from `forty-cdk/core-anchored` — internal tier, not blessed —\n * because it is the default type argument of `MenuOverlay`, which the emitted\n * `.d.ts` names as `MenuOverlay<MenuItemHandle>` for the `protected readonly\n * _overlay` field on `[forDropdownMenu]` / `[forContextMenu]` / `[forMenu]` /\n * `[forMenuSub]`.\n */\nexport interface MenuItemHandle extends CollectionHandle {\n /**\n * Narrowed from {@link CollectionHandle}'s `Node`: the list focuses its items\n * and scrolls them into view.\n */\n readonly host: HTMLElement;\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 * 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, and\n * before every keyboard focus move so a hover highlight held without focus\n * never outlives it. 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 their\n * navigate / typeahead / focus behaviour to this unit.\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 /**\n * Moves focus to the next enabled item for an Arrow / Home / End action,\n * honouring the owner's `loop`. The focus move passes `preventScroll` and\n * then scrolls the target into view with `block: 'nearest'`, so a menu with\n * its own overflow scrolls minimally while the page underneath the portaled\n * surface never jumps.\n */\n navigate(currentItem: HTMLElement, action: ListNavigationAction): void {\n const target = nextEnabledHandle(this.#items.items(), currentItem, action, {\n loop: this.#loop(),\n });\n if (!target) {\n return;\n }\n this.#focus(target);\n }\n\n /**\n * Feeds `event` to the typeahead buffer and focuses the first matching item.\n * An item matches on its `textValue` when set, else on its accessible text:\n * an `aria-hidden` subtree (a `[forMenuItemIndicator]` glyph, an icon, a\n * badge) contributes nothing, while visually-hidden but announced content\n * still does. Text and buffer are compared trimmed, case-insensitively and\n * diacritics-insensitively, so `e` reaches `Éditer`.\n * Returns `true` when the key was consumed as a typeahead character (a\n * printable char, or Space while the buffer is already non-empty), `false`\n * otherwise. A consumed Space is `preventDefault()`-ed, so it extends the\n * buffer instead of triggering a native `<button>` item's activation. The\n * focus move passes `preventScroll` and reveals the match with\n * `scrollIntoView({ block: 'nearest' })`.\n */\n handleTypeahead(event: KeyboardEvent): boolean {\n const items = this.#items.items();\n const { handled, match } = resolveListTypeahead(this.#typeahead, event, {\n items,\n anchorIndex: items.findIndex((item) => item.host === event.target),\n getText: (item) => {\n const override = item.textValue?.() ?? '';\n return override !== '' ? override : accessibleTextContent(item.host);\n },\n isDisabled: (item) => item.disabled(),\n });\n if (match) {\n this.#focus(match);\n }\n return handled;\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`. The move passes\n * `preventScroll`: the menu surface is portaled and `position: fixed`, and\n * floating-ui has not resolved its placement yet when the initial focus\n * runs, so letting the browser scroll for it would move the page (and the\n * anchor) under a pointer-driven open.\n */\n focusFirstEnabledItem(highlight = true): boolean {\n const target = firstEnabledHandle(this.#items.items());\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`. Like\n * {@link focusFirstEnabledItem} the move passes `preventScroll` and reveals\n * the item with `scrollIntoView({ block: 'nearest' })`, so a scrollable menu\n * still scrolls its own overflow to the last item.\n */\n focusLastEnabledItem(highlight = true): boolean {\n const target = lastEnabledHandle(this.#items.items());\n if (!target) {\n return false;\n }\n this.#focusItem(target, highlight);\n return true;\n }\n\n /**\n * Focuses the first or last enabled item per `target`. The single owner of the\n * `'first' | 'last'` → focus-call mapping every menu surface resolves its\n * initial focus through — the mount path, the already-open re-focus branch of\n * a `MenuOverlay`, and `[forMenubar]`'s equivalent — so the fallback ordering\n * and any future widening of the target union live in one place instead of one\n * copy per surface. `highlight` behaves exactly as on\n * {@link focusFirstEnabledItem} / {@link focusLastEnabledItem}.\n */\n focusInitialEnabledItem(target: 'first' | 'last', highlight = true): boolean {\n return target === 'last'\n ? this.focusLastEnabledItem(highlight)\n : this.focusFirstEnabledItem(highlight);\n }\n\n #focusItem(item: H, highlight: boolean): void {\n if (!highlight) {\n item.suppressHighlightOnNextFocus?.();\n }\n this.#focus(item);\n }\n\n #focus(target: H): void {\n for (const item of this.#items.items()) {\n if (item !== target) {\n item.clearHighlight?.();\n }\n }\n focusMenuItemHost(target.host);\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\nfunction focusMenuItemHost(host: HTMLElement): void {\n host.focus({ preventScroll: true });\n host.scrollIntoView?.({ block: 'nearest' });\n}\n","import type { WritingDirection } from 'forty-cdk/core';\nimport type { FloatingSide } from '../floating/floating';\n\n/** Axis a menubar lays its triggers out on. */\nexport type MenubarOrientation = 'horizontal' | 'vertical';\n\n/**\n * What a horizontal arrow key does on an item of a menu opened from a menubar:\n * switch to the previous or next sibling menu, close the menu and return focus\n * to its trigger on the bar, or nothing (`null`).\n */\nexport type MenubarInMenuArrow = 'prev' | 'next' | 'close' | null;\n\n/**\n * Every decision that depends on which way a menubar lays out, resolved from\n * its orientation and writing direction by {@link resolveMenubarAxis}.\n */\nexport interface MenubarAxis {\n /** Side a trigger's menu opens on when neither the trigger nor the scope sets one. */\n readonly side: FloatingSide;\n /** Key on a trigger that opens its menu with the first item focused. */\n readonly openFirstKey: 'ArrowDown' | 'ArrowLeft' | 'ArrowRight';\n /** Key on a trigger that opens its menu with the last item focused, `null` when none does. */\n readonly openLastKey: 'ArrowUp' | null;\n /** What `ArrowLeft` / `ArrowRight` do on an item of the open menu. */\n readonly inMenu: {\n readonly ArrowLeft: MenubarInMenuArrow;\n readonly ArrowRight: MenubarInMenuArrow;\n };\n}\n\nconst HORIZONTAL_LTR: MenubarAxis = {\n side: 'bottom',\n openFirstKey: 'ArrowDown',\n openLastKey: 'ArrowUp',\n inMenu: { ArrowLeft: 'prev', ArrowRight: 'next' },\n};\n\nconst HORIZONTAL_RTL: MenubarAxis = {\n side: 'bottom',\n openFirstKey: 'ArrowDown',\n openLastKey: 'ArrowUp',\n inMenu: { ArrowLeft: 'next', ArrowRight: 'prev' },\n};\n\nconst VERTICAL_LTR: MenubarAxis = {\n side: 'right',\n openFirstKey: 'ArrowRight',\n openLastKey: null,\n inMenu: { ArrowLeft: 'close', ArrowRight: null },\n};\n\nconst VERTICAL_RTL: MenubarAxis = {\n side: 'left',\n openFirstKey: 'ArrowLeft',\n openLastKey: null,\n inMenu: { ArrowLeft: null, ArrowRight: 'close' },\n};\n\n/**\n * Resolves a menubar's {@link MenubarAxis}. A horizontal bar opens each menu\n * below its trigger, opens with `ArrowDown` / `ArrowUp`, and switches between\n * sibling menus with the horizontal arrows inside a menu. A vertical bar opens\n * each menu beside it, on the inline-end side, opens with the inline-end arrow,\n * and inside a menu the inline-start arrow closes the menu back to the bar,\n * while the inline-end arrow has no sibling menu to reach.\n */\nexport function resolveMenubarAxis(\n orientation: MenubarOrientation,\n dir: WritingDirection,\n): MenubarAxis {\n if (orientation === 'vertical') {\n return dir === 'rtl' ? VERTICAL_RTL : VERTICAL_LTR;\n }\n return dir === 'rtl' ? HORIZONTAL_RTL : HORIZONTAL_LTR;\n}\n","import { InjectionToken } from '@angular/core';\n\nimport type { ForMenuContext } from './menu-context';\n\n/**\n * A submenu as its parent menu sees it while it holds the parent's open-child\n * slot.\n */\nexport interface MenuOpenChild {\n /** The submenu's own menu context, which keys the slot of its own open child. */\n readonly context: ForMenuContext;\n /**\n * Closes the submenu because a menu above it is closing: its `open` model is\n * written `false` and its `(openChange)` emits, no focus moves, and the close\n * does not propagate up the chain.\n */\n closeWithParent(): void;\n /**\n * Closes the submenu because a sibling took its parent's slot. Focus returns\n * to its trigger only when it was inside the submenu's open chain.\n */\n closeForSibling(): void;\n /**\n * Whether the pointer is travelling from the submenu's trigger toward its\n * content inside the armed pointer-grace corridor.\n */\n pointerGraceArmed(): boolean;\n}\n\n/**\n * Which submenu each menu holds open. A menu holds at most one open submenu, so\n * the registry is the chain of open levels below every menu context: a root\n * closes that chain before it closes, and a sub-trigger reads a sibling's\n * pointer-grace state through it before it schedules a hover-open.\n */\nexport class MenuOpenChain {\n readonly #openChildren = new WeakMap<ForMenuContext, MenuOpenChild>();\n readonly #graceWaiters = new WeakMap<ForMenuContext, () => void>();\n\n /** The submenu `parent` holds open, or `null`. */\n openChild(parent: ForMenuContext): MenuOpenChild | null {\n return this.#openChildren.get(parent) ?? null;\n }\n\n /**\n * Makes `child` the open submenu of `parent`, closing the previous holder\n * through {@link MenuOpenChild.closeForSibling} when it is a different submenu.\n */\n claim(parent: ForMenuContext, child: MenuOpenChild): void {\n const previous = this.#openChildren.get(parent);\n this.#openChildren.set(parent, child);\n if (previous && previous !== child) {\n previous.closeForSibling();\n }\n }\n\n /** Clears `parent`'s open-child slot when `child` holds it. */\n release(parent: ForMenuContext, child: MenuOpenChild): void {\n if (this.#openChildren.get(parent) === child) {\n this.#openChildren.delete(parent);\n }\n }\n\n /**\n * Closes every submenu open below `parent`, deepest first, through\n * {@link MenuOpenChild.closeWithParent}. Every menu context calls it from the\n * close transition all of its close paths pass through.\n */\n closeOpenChildChain(parent: ForMenuContext): void {\n const chain: MenuOpenChild[] = [];\n let child = this.#openChildren.get(parent);\n while (child && !chain.includes(child)) {\n chain.push(child);\n child = this.#openChildren.get(child.context);\n }\n for (const level of chain.reverse()) {\n level.closeWithParent();\n }\n }\n\n /**\n * Holds a hover-open of a submenu of `parent` until the pointer-grace corridor\n * of the open sibling ends. A later call replaces the waiting one.\n */\n deferUntilGraceEnds(parent: ForMenuContext, resume: () => void): void {\n this.#graceWaiters.set(parent, resume);\n }\n\n /**\n * The pointer-grace corridor of `parent`'s open submenu ended without the\n * pointer reaching its content: runs the hover-open waiting on it, if any.\n */\n graceEnded(parent: ForMenuContext): void {\n const resume = this.#graceWaiters.get(parent);\n if (resume) {\n this.#graceWaiters.delete(parent);\n resume();\n }\n }\n}\n\n/** The application's {@link MenuOpenChain}. */\nexport const MENU_OPEN_CHAIN = new InjectionToken<MenuOpenChain>('MENU_OPEN_CHAIN', {\n providedIn: 'root',\n factory: () => new MenuOpenChain(),\n});\n","import { computed, InjectionToken, signal, type Signal, type WritableSignal } from '@angular/core';\nimport type { ReferenceElement, VirtualElement } from '@floating-ui/dom';\n\nimport type { FloatingAlign, FloatingSide } from '../floating/floating';\nimport { type RootedHandle, RootedRegistry } from 'forty-cdk/core';\nimport type { ForMenuContext } from './menu-context';\n\n/**\n * Builds a floating-ui `VirtualElement` pinned to a by-value rect snapshot, so\n * later layout changes never shift the anchor. A 0×0 box models a pointer\n * position; a real box models the focused element a keyboard activation\n * anchored at.\n */\nfunction menuVirtualAnchor(x: number, y: number, width: number, height: number): VirtualElement {\n return {\n getBoundingClientRect: () => ({\n x,\n y,\n width,\n height,\n top: y,\n left: x,\n right: x + width,\n bottom: y + height,\n toJSON() {\n return this;\n },\n }),\n };\n}\n\n/**\n * Per-opener override of a menu root's **placement** inputs, applied only while\n * that opener is the active one. Every key is optional and an omitted one\n * resolves the root's own input, so an opener that overrides nothing positions\n * exactly as the root does.\n *\n * It carries the four values an opener's own geometry can legitimately decide.\n * The root keeps the rest of the positioning surface (`avoidCollisions`,\n * `collisionPadding`, `sticky`, …), which is collision / viewport policy for the\n * surface rather than a property of the opener that fired.\n *\n * The canonical case is a `[forMenu]` shared by heterogeneous openers: a button\n * opener wants the few pixels of clearance `[forDropdownMenu]` seeds, while a\n * pointer-anchored right-click region wants to sit flush at the cursor.\n */\nexport interface MenuOpenerPositioning {\n /** Side the menu is anchored to for this opener's opens. */\n readonly side?: FloatingSide;\n /** Alignment along the chosen side for this opener's opens. */\n readonly align?: FloatingAlign;\n /** Gap (px) between this opener's anchor and the menu along the main axis. */\n readonly sideOffset?: number;\n /** Gap (px) along the cross axis for this opener's opens. */\n readonly alignOffset?: number;\n}\n\n/** What an opener declares about itself when it registers with a menu root. */\nexport interface MenuOpenerOptions {\n /** The opener's own aria-wiring id, so two openers on one root never emit the same `id`. */\n readonly id: Signal<string>;\n /**\n * Whether a pointer-down on this opener counts as \"inside\" the menu. A\n * toggle-style opener (a `[forDropdownMenuTrigger]` button) must be exempt,\n * or its own click would also fire pointer-down-outside and double-close. A\n * right-click region must not be, so a left-click on it closes the menu like\n * any other outside click. Defaults to `false`.\n */\n readonly dismissibleExempt?: boolean;\n /**\n * Whether this opener's own accessible name is a valid name for the menu\n * surface. A discrete labelling control (a `[forDropdownMenuTrigger]` button)\n * passes `true`, so the surface can fall back to\n * `aria-labelledby=\"<openerId>\"`; a right-click region\n * (`[forContextMenuTrigger]`) passes `false`, because pointing the menu's name\n * at a whole row would announce the row's entire text. Defaults to `false` —\n * the conservative answer, which is also what a root with no resolvable active\n * opener reports.\n */\n readonly labelsMenu?: boolean;\n /**\n * This opener's placement override, read while it is the active one. Passed as\n * a signal so a bound `[menuPositioning]` flows through without\n * re-registering the element. Omitting it (and emitting `null`) resolves the\n * root's own positioning inputs.\n */\n readonly positioning?: Signal<MenuOpenerPositioning | null>;\n}\n\nexport interface MenuOpenerHandle extends RootedHandle<object> {\n readonly host: HTMLElement;\n readonly id: Signal<string>;\n readonly dismissibleExempt: boolean;\n readonly labelsMenu: boolean;\n readonly positioning: Signal<MenuOpenerPositioning | null> | null;\n readonly virtualAnchor: WritableSignal<ReferenceElement | null>;\n}\n\nexport const MENU_OPENERS = new InjectionToken<RootedRegistry<object, MenuOpenerHandle>>(\n 'MENU_OPENERS',\n { providedIn: 'root', factory: () => new RootedRegistry() },\n);\n\nexport function createMenuOpenerHandle(\n host: HTMLElement,\n root: Signal<object | null>,\n options: MenuOpenerOptions,\n): MenuOpenerHandle {\n return {\n host,\n root,\n id: options.id,\n dismissibleExempt: options.dismissibleExempt ?? false,\n labelsMenu: options.labelsMenu ?? false,\n positioning: options.positioning ?? null,\n virtualAnchor: signal<ReferenceElement | null>(null),\n };\n}\n\n/**\n * The opener protocol a multi-opener menu root exposes. Deliberately **not**\n * part of `ForMenuContext`: how openers drive a root is the piece protocol the\n * library refactors freely, whereas `ForMenuContext` is the blessed consumer\n * read surface. It stays out of every stable entry point's barrel and out of\n * every public signature — the trigger directives resolve it by narrowing their\n * already-resolved root with {@link asMenuOpenerRegistration}.\n */\nexport interface MenuOpenerRegistration {\n /**\n * Marks `opener` as the opener driving the current open. Return-focus, the\n * surface's `aria-labelledby` fallback, and the anchor all resolve against it.\n * `returnFocusTarget` records where focus returns for this open instead of\n * the opener's host — the focused descendant a keyboard activation started\n * from.\n */\n activateOpener(opener: MenuOpenerHandle, returnFocusTarget?: HTMLElement | null): void;\n releaseOpener(opener: MenuOpenerHandle): void;\n /**\n * The element focus returns to when the menu closes: the target the active\n * opener recorded for this open while it is still in the document, else the\n * active opener itself.\n */\n returnFocusTarget(): HTMLElement | null;\n /** Anchors the active opener's next open at a 0×0 point in viewport coordinates. */\n setVirtualAnchor(x: number, y: number): void;\n /** Anchors the active opener's next open at a by-value snapshot of `rect`. */\n setVirtualAnchorFromRect(rect: DOMRect): void;\n}\n\n/**\n * Narrows a resolved menu root to its opener protocol, or `null` when the root\n * does not implement one. Every root built on `MenuOverlayHost` does;\n * `[forMenubar]`'s multiplexed context does not, because the bar owns its own\n * trigger multiplexing.\n */\nexport function asMenuOpenerRegistration(root: object): MenuOpenerRegistration | null {\n const candidate = root as Partial<MenuOpenerRegistration>;\n return typeof candidate.activateOpener === 'function'\n ? (candidate as MenuOpenerRegistration)\n : null;\n}\n\n/**\n * The element a menu returns focus to on close: the opener registry's per-open\n * target on a root that has one, the context's `trigger` otherwise.\n */\nexport function menuReturnFocusTarget(ctx: Pick<ForMenuContext, 'trigger'>): HTMLElement | null {\n const openers = asMenuOpenerRegistration(ctx);\n return openers ? openers.returnFocusTarget() : ctx.trigger();\n}\n\nexport function releaseMenuOpener(opener: MenuOpenerHandle): void {\n const root = opener.root();\n if (root !== null) {\n asMenuOpenerRegistration(root)?.releaseOpener(opener);\n }\n}\n\n/**\n * The registry of openers behind a menu root. Several triggers may drive one\n * menu definition, which is what lets `[forMenu]` be declared once and opened\n * from many places.\n *\n * Everything the mounted surface reads resolves against the **active** opener:\n * the element return-focus lands on, the id the surface names itself after,\n * whether that id is a valid name at all, the floating-ui anchor, and the\n * placement override that anchor is measured with. \"Active\" is whichever opener\n * last called {@link activate}, falling back to the newest opener when every\n * registered one sits on the same element — so a single-opener root and a\n * programmatic open resolve unambiguously.\n *\n * Each opener carries its own optional virtual anchor, so switching openers\n * switches the anchor with no clearing step: a pointer-anchored right-click\n * opener keeps its `VirtualElement` while a button opener keeps resolving to its\n * own element.\n */\nexport class MenuOpenerRegistry {\n readonly #seedId: Signal<string>;\n readonly #openers: Signal<readonly MenuOpenerHandle[]>;\n readonly #activeOpener = signal<MenuOpenerHandle | null>(null);\n #returnFocusTarget: HTMLElement | null = null;\n #activatedSinceMount = false;\n\n readonly #active = computed<MenuOpenerHandle | null>(() => {\n const openers = this.#openers();\n const active = this.#activeOpener();\n if (active !== null && openers.includes(active)) {\n return active;\n }\n const newest = openers.at(-1);\n return newest !== undefined && openers.every((opener) => opener.host === newest.host)\n ? newest\n : null;\n });\n\n /**\n * Id of the opener driving the current open, falling back to the root's seeded\n * trigger id while no single opener is resolvable. Never the empty string, so\n * the surface's `aria-labelledby` fallback keeps the shape it had when the id\n * lived on the root.\n */\n readonly id: Signal<string>;\n\n /**\n * The active opener's element — the return-focus target, unless the open\n * recorded one of its own (see {@link returnFocusTarget}).\n */\n readonly element = computed<HTMLElement | null>(() => this.#active()?.host ?? null);\n\n /**\n * The active opener's floating-ui anchor: its virtual anchor when it set one\n * (a pointer / rect activation), otherwise its own element.\n */\n readonly anchor = computed<ReferenceElement | null>(() => {\n const active = this.#active();\n if (active === null) {\n return null;\n }\n return active.virtualAnchor() ?? active.host;\n });\n\n /**\n * The active opener's virtual anchor only — `null` until an opener sets one.\n * `[forContextMenu]` resolves its anchor through this so a right-click menu\n * with no recorded pointer position stays unanchored rather than falling back\n * to its whole right-click region.\n */\n readonly virtualAnchor = computed<ReferenceElement | null>(\n () => this.#active()?.virtualAnchor() ?? null,\n );\n\n /** Every registered opener that asked to count as \"inside\" the menu. */\n readonly dismissibleExemptions = computed<readonly HTMLElement[]>(() =>\n this.#openers()\n .filter((opener) => opener.dismissibleExempt)\n .map((opener) => opener.host),\n );\n\n /**\n * Whether the **active** opener's accessible name is a valid name for the menu\n * surface, so `[forMenuContent]` may fall back to\n * `aria-labelledby=\"<openerId>\"`. Per-opener rather than per-root because a\n * shared menu's openers are heterogeneous — a button opener is a labelling\n * control, a right-click region is not — and the answer therefore flips as the\n * menu is opened from a different one.\n *\n * `false` while no single opener is resolvable: the surface would otherwise\n * name itself after the root's seeded trigger id, which no element carries\n * once every opener owns an id of its own.\n */\n readonly labelsMenu = computed<boolean>(() => this.#active()?.labelsMenu ?? false);\n\n /**\n * The **active** opener's placement override, or `null` when it declared none\n * (and while no single opener is resolvable). Per-opener for the same reason\n * the anchor is: a shared menu's openers are heterogeneous, so the offsets a\n * button opener wants are not the ones a pointer-anchored region wants. A\n * root resolves each key against its own input — `positioning()?.x ??\n * xInput()` — so an opener that overrides nothing changes nothing.\n */\n readonly positioning = computed<MenuOpenerPositioning | null>(\n () => this.#active()?.positioning?.() ?? null,\n );\n\n constructor(seedId: Signal<string>, openers: Signal<readonly MenuOpenerHandle[]>) {\n this.#seedId = seedId;\n this.#openers = openers;\n this.id = computed(() => this.#active()?.id() ?? this.#seedId());\n }\n\n activate(opener: MenuOpenerHandle, returnFocusTarget: HTMLElement | null = null): void {\n this.#activeOpener.set(opener);\n this.#returnFocusTarget = returnFocusTarget;\n this.#activatedSinceMount = true;\n }\n\n release(opener: MenuOpenerHandle): void {\n if (this.#activeOpener() === opener) {\n this.#activeOpener.set(null);\n this.#returnFocusTarget = null;\n }\n }\n\n mountSurface(): void {\n if (!this.#activatedSinceMount) {\n this.#returnFocusTarget = null;\n }\n this.#activatedSinceMount = false;\n }\n\n /**\n * The return-focus target of the current open: the one {@link activate}\n * recorded for it while it is still in the document and its opener is still\n * the active one, else the active opener. Read at close time rather than\n * derived, because a menu action may remove the recorded element from the\n * document.\n */\n returnFocusTarget(): HTMLElement | null {\n const element = this.element();\n const target = this.#returnFocusTarget;\n const opener = this.#activeOpener();\n return target !== null && target.isConnected && opener !== null && this.#active() === opener\n ? target\n : element;\n }\n\n setVirtualAnchor(x: number, y: number): void {\n this.#active()?.virtualAnchor.set(menuVirtualAnchor(x, y, 0, 0));\n }\n\n setVirtualAnchorFromRect(rect: DOMRect): void {\n this.#active()?.virtualAnchor.set(menuVirtualAnchor(rect.x, rect.y, rect.width, rect.height));\n }\n}\n","import { inject, type ModelSignal, type Signal } from '@angular/core';\nimport type { ReferenceElement } from '@floating-ui/dom';\n\nimport { type ListNavigationAction, type VetoableNativeEvent } from 'forty-cdk/core';\nimport {\n OverlayController,\n type OverlayEmitTargets,\n type OverlayTransitionOptions,\n} from '../overlay-controller/overlay-controller';\nimport {\n type MenuOpenerHandle,\n type MenuOpenerPositioning,\n MenuOpenerRegistry,\n} from './menu-opener-registry';\nimport type { ForMenuCloseReason, ForMenuContext } from './menu-context';\nimport { createMenuItemList, type MenuItemHandle, type MenuItemList } from './menu-item-list';\nimport { MENU_OPEN_CHAIN } from './menu-open-chain';\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 extends OverlayEmitTargets {\n /**\n * The menu context the overlay backs. Every close of it first closes the\n * submenus open below it, through the {@link MENU_OPEN_CHAIN} slot keyed by\n * this context.\n */\n readonly context: ForMenuContext;\n readonly open: ModelSignal<boolean>;\n readonly disabled: Signal<boolean>;\n readonly dismissible: Signal<boolean>;\n readonly loop: Signal<boolean>;\n readonly openers: Signal<readonly MenuOpenerHandle[]>;\n\n /**\n * Optional side effect run after `openMenu` resolves the open, receiving the\n * resolved initial-focus target. `[forMenuSub]` uses it to cancel in-flight\n * hover scheduling and set its focus-suppression flags from\n * `options.suppressFocusMoves` (a keyboard / click open supersedes hover).\n * Top-level roots (`[forDropdownMenu]` / `[forContextMenu]`) pass neither\n * hook.\n *\n * It also runs when `openMenu` re-targets an **already-open** menu (no model\n * write, focus moved instead), so a pending hover-close is still cancelled by\n * an open key pressed on a mounted submenu.\n */\n readonly onOpen?: (initialFocus: 'first' | 'last', options: OverlayTransitionOptions) => void;\n\n /**\n * Optional side effect run after `closeMenu` flips `open` to `false`,\n * receiving the close reason and the transition options. `[forMenuSub]` uses\n * it to cancel in-flight hover scheduling, set its focus-suppression flags\n * from `options.suppressFocusMoves`, and propagate the close upward through\n * the menu chain for every reason except `'escape'` / `'hover'` /\n * `'programmatic'`. Top-level roots pass neither hook. It runs after the\n * submenus open below the menu have been closed.\n */\n readonly onClose?: (reason: ForMenuCloseReason, options: OverlayTransitionOptions) => void;\n}\n\n/**\n * Shared coordination behaviour of the menu overlay roots — `ForDropdownMenu`,\n * `ForContextMenu`, `ForMenu` and `ForMenuSub` — which share the same\n * item-collection / typeahead / navigate / dismissible shape. Menubar's per-bar\n * menu is not one of them: it composes `MenuItemList` and\n * {@link OverlayController} directly.\n *\n * The helper owns:\n *\n * - the item list (`MenuItemList`: the item `Collection`, typeahead and the navigate / focus\n * moves), shared with `[forMenubar]`'s multiplexed menu context,\n * - the opener registry: every trigger that can open this menu, which one is driving the current\n * open, and the per-opener id / anchor / labelling policy resolved against it,\n * - the menu vocabulary over the shared {@link OverlayController} — `'first' | 'last'` initial\n * focus, `ForMenuCloseReason`, the `'pointer' | 'keyboard'` activation modality, and\n * `openMenu`'s already-open re-focus branch.\n *\n * Everything below that vocabulary — the trigger / content slots and their ids, the\n * initial-focus and close-reason state, the `disabled`-gated open / close / toggle transitions,\n * the outside / Escape forwarders, `requestClose`, and the auto-focus vetoes — is the shared\n * controller's, declared once and composed here.\n *\n * It does not own:\n *\n * - the resolved `anchor` signal, which each root derives differently — from the trigger element,\n * from a virtual anchor, or from the active opener,\n * - `dismissibleExemptions`, since only some roots exempt their trigger to stop a click toggle\n * double-firing as a pointer-down-outside,\n * - the `input()` / `output()` / `model()` declarations, which must stay on the directive class for\n * Angular's template binding to see them.\n *\n * Construct via `createMenuOverlay` from a directive's field initializer, so the helper's `inject()`\n * calls resolve through the directive's injector.\n */\nexport class MenuOverlay<H extends MenuItemHandle = MenuItemHandle> {\n readonly #itemList: MenuItemList<H>;\n\n readonly #openers: MenuOpenerRegistry;\n readonly #controller: OverlayController<'first' | 'last', ForMenuCloseReason>;\n\n /**\n * Id of the opener driving the current open — the active opener's own id when\n * it owns one, else the seeded `<idPrefix>-trigger-*` fallback. Non-empty from\n * construction, so `[forMenuContent]`'s `aria-labelledby` fallback keeps the\n * shape it had when a single id lived on the root.\n */\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 /** Where focus should land when the menu mounts. Set by triggers before flipping `open`. */\n readonly initialFocus: Signal<'first' | 'last'>;\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: Signal<ForMenuCloseReason | null>;\n\n /**\n * The focusable element the menu should return focus to on close — the opener\n * that actually opened this instance, so a menu shared by several openers\n * hands focus back to the one the user used.\n */\n readonly trigger: Signal<HTMLElement | null>;\n\n /** The mounted `[forMenuContent]` element, or `null` while the menu is closed. */\n readonly content: Signal<HTMLElement | null>;\n\n /**\n * The active opener's floating-ui anchor: its virtual anchor when it recorded\n * one, else its own element. `[forMenu]` resolves its `anchor` through this so\n * the surface follows whichever opener fired.\n */\n readonly openerAnchor: Signal<ReferenceElement | null>;\n\n /**\n * The active opener's virtual anchor only, `null` until one is recorded.\n * `[forContextMenu]` resolves its `anchor` through this so a menu with no\n * recorded pointer position stays unanchored rather than falling back to its\n * whole right-click region.\n */\n readonly openerVirtualAnchor: Signal<ReferenceElement | null>;\n\n /** Registered openers that count as \"inside\" for outside-dismissal. */\n readonly openerExemptions: Signal<readonly HTMLElement[]>;\n\n /**\n * Whether the active opener is a discrete labelling control, so\n * `[forMenuContent]` may name itself `aria-labelledby=\"<triggerId>\"`.\n * `[forMenu]` exposes this as its `ForMenuContext.triggerLabelsMenu` so a\n * shared menu's name follows whichever opener fired.\n */\n readonly openerLabelsMenu: Signal<boolean>;\n\n /**\n * The active opener's placement override, `null` when it declared none. Each\n * root resolves its `side` / `align` / `sideOffset` / `alignOffset` against\n * its own input through this, so a shared menu positions per the opener that\n * fired while an opener with no override keeps the root's values.\n */\n readonly openerPositioning: Signal<MenuOpenerPositioning | null>;\n\n constructor(idPrefix: string, hooks: MenuOverlayHooks) {\n const openChain = inject(MENU_OPEN_CHAIN);\n this.#itemList = createMenuItemList<H>(() => hooks.loop());\n let openers!: MenuOpenerRegistry;\n this.#controller = new OverlayController<'first' | 'last', ForMenuCloseReason>({\n idPrefix,\n createTrigger: (mintId) => {\n openers = new MenuOpenerRegistry(mintId(), hooks.openers);\n return openers;\n },\n defaultInitialFocus: 'first',\n disabled: hooks.disabled,\n dismissible: hooks.dismissible,\n isOpen: () => hooks.open(),\n setOpen: (open) => hooks.open.set(open),\n emit: hooks,\n escapeReason: 'escape',\n programmaticReason: 'programmatic',\n onOpen: hooks.onOpen,\n onClose: (reason, options) => {\n openChain.closeOpenChildChain(hooks.context);\n hooks.onClose?.(reason, options);\n },\n });\n this.#openers = openers;\n this.triggerId = this.#controller.triggerId;\n this.contentId = this.#controller.contentId;\n this.initialFocus = this.#controller.initialFocus;\n this.lastCloseReason = this.#controller.lastCloseReason;\n this.trigger = this.#controller.trigger;\n this.content = this.#controller.content;\n this.openerAnchor = this.#openers.anchor;\n this.openerVirtualAnchor = this.#openers.virtualAnchor;\n this.openerExemptions = this.#openers.dismissibleExemptions;\n this.openerLabelsMenu = this.#openers.labelsMenu;\n this.openerPositioning = this.#openers.positioning;\n }\n\n setInitialFocus(target: 'first' | 'last'): void {\n this.#controller.setInitialFocus(target);\n }\n\n activateOpener(opener: MenuOpenerHandle, returnFocusTarget: HTMLElement | null = null): void {\n this.#openers.activate(opener, returnFocusTarget);\n }\n\n releaseOpener(opener: MenuOpenerHandle): void {\n this.#openers.release(opener);\n }\n\n /**\n * The element focus returns to on close: the target the active opener\n * recorded for this open while it is still in the document, else\n * {@link trigger}.\n */\n returnFocusTarget(): HTMLElement | null {\n return this.#openers.returnFocusTarget();\n }\n\n setVirtualAnchor(x: number, y: number): void {\n this.#openers.setVirtualAnchor(x, y);\n }\n\n setVirtualAnchorFromRect(rect: DOMRect): void {\n this.#openers.setVirtualAnchorFromRect(rect);\n }\n\n registerContent(el: HTMLElement): void {\n this.#openers.mountSurface();\n this.#controller.registerContent(el);\n }\n\n unregisterContent(el: HTMLElement): void {\n this.#controller.unregisterContent(el);\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): boolean {\n return 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 * An imperative escape hatch for an explicit first / last move, independent of the resolved\n * {@link initialFocus} target. No piece of the library routes through it — they all go through\n * {@link focusInitialEnabledItem} — and `ForMenuContext` does not declare it.\n */\n focusFirstEnabledItem(): boolean {\n return this.#itemList.focusFirstEnabledItem(this.#controller.consumeInitialHighlight());\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). The\n * granular counterpart of {@link focusFirstEnabledItem}, and like it an\n * imperative escape hatch rather than a `ForMenuContext` member.\n */\n focusLastEnabledItem(): boolean {\n return this.#itemList.focusLastEnabledItem(this.#controller.consumeInitialHighlight());\n }\n\n /**\n * Focuses the first or last enabled item per `target`, resolving the mapping\n * through the shared `MenuItemList` rather than re-deriving it here. Used by\n * the mount path (through the `ForMenuContext` contract) and by `openMenu`'s\n * already-open re-focus branch. 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 focusInitialEnabledItem(target: 'first' | 'last'): boolean {\n return this.#itemList.focusInitialEnabledItem(\n target,\n this.#controller.consumeInitialHighlight(),\n );\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 this.#controller.toggle(initialFocus, { highlight: modality === 'keyboard' });\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 * `options` is forwarded verbatim to the `onOpen` hook — `[forMenuSub]`'s\n * hover-open passes `{ suppressFocusMoves: true }` so the mount does not\n * pull focus off whatever the user was on.\n *\n * When the menu is **already open** there is no state transition (and\n * therefore no `(openChange)` emit): focus moves straight to the requested\n * first / last enabled item instead, so an APG open key pressed on a trigger\n * whose menu is already mounted is never a dead key. The menu is never\n * toggled closed — the open keys have no close semantics in the APG patterns\n * — and a menu with no enabled item moves nothing rather than pulling focus\n * onto an item-less surface. The re-focus is not gated on the\n * `(autoFocusOnOpen)` veto: that veto covers the mount's automatic focus\n * move, and honouring it here would silently restore the dead key for\n * consumers who opted out of auto-focus-on-open. It *is* skipped for a\n * `{ suppressFocusMoves: true }` transition, whose whole contract is that no\n * imperative focus move may happen (`[forMenuSub]`'s hover-open).\n *\n * This branch is the menu's own: it stays out of the shared controller, which\n * reports the already-open case as an outcome rather than acting on it.\n */\n openMenu(\n initialFocus: 'first' | 'last' = 'first',\n modality: MenuActivationModality = 'keyboard',\n options: OverlayTransitionOptions = {},\n ): void {\n const outcome = this.#controller.open(initialFocus, {\n highlight: modality === 'keyboard',\n transition: options,\n });\n if (outcome === 'already-open' && !options.suppressFocusMoves) {\n this.focusInitialEnabledItem(initialFocus);\n }\n }\n\n /**\n * Closes the menu, recording `reason` as the `lastCloseReason` the content\n * pieces read. `options` is forwarded verbatim to the `onClose` hook —\n * `[forMenuSub]`'s hover-close passes `{ suppressFocusMoves: true }` so the\n * unmount does not yank focus back to the sub-trigger.\n */\n closeMenu(reason: ForMenuCloseReason, options: OverlayTransitionOptions = {}): void {\n this.#controller.close(reason, options);\n }\n\n emitEscapeKeyDown(event: KeyboardEvent): void {\n this.#controller.emitEscapeKeyDown(event);\n }\n\n emitPointerDownOutside(veto: VetoableNativeEvent<PointerEvent>): void {\n this.#controller.emitPointerDownOutside(veto);\n }\n\n emitFocusOutside(veto: VetoableNativeEvent<FocusEvent>): void {\n this.#controller.emitFocusOutside(veto);\n }\n\n emitInteractOutside(veto: VetoableNativeEvent<PointerEvent | FocusEvent>): void {\n this.#controller.emitInteractOutside(veto);\n }\n\n requestClose(reason: 'pointerDownOutside' | 'focusOutside'): void {\n this.#controller.requestClose(reason);\n }\n\n emitAutoFocusOnOpen(): boolean {\n return this.#controller.emitAutoFocusOnOpen();\n }\n\n emitAutoFocusOnClose(): boolean {\n return this.#controller.emitAutoFocusOnClose();\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 MenuItemHandle = MenuItemHandle>(\n idPrefix: string,\n hooks: MenuOverlayHooks,\n): MenuOverlay<H> {\n return new MenuOverlay<H>(idPrefix, hooks);\n}\n","import { Directive, type Signal } from '@angular/core';\n\nimport { AnchoredOverlayPositioningBase } from '../floating/anchored-overlay-positioning-base';\nimport { type ListNavigationAction, type VetoableNativeEvent } from 'forty-cdk/core';\nimport type { ForMenuCloseReason } from './menu-context';\nimport type { MenuItemHandle } from './menu-item-list';\nimport type { MenuOpenerHandle } from './menu-opener-registry';\nimport type { MenuActivationModality, MenuOverlay } from './menu-overlay';\n\n/**\n * Abstract base that forwards the `MenuOverlay` coordination slice every menu\n * root re-exposes — `[forDropdownMenu]`, `[forContextMenu]`, `[forMenu]` and\n * `[forMenuSub]` all extend it. Each subclass owns its own `MenuOverlay`\n * instance (created with its own id prefix and lifecycle hooks) and exposes it\n * through the abstract `_overlay` accessor; the base implements the 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 four 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 flags).\n *\n * Kept generic over the item handle so the subclass's `MenuOverlay<H>` flows\n * through `registerItem` / `unregisterItem` without a cast.\n *\n * It also carries `AnchoredOverlayPositioningBase` for its subclasses: every\n * menu root is a trigger-anchored overlay, so inheriting the shared positioning\n * block here is what keeps the four of them from redeclaring it. The\n * `@Directive()` decorator is required for that inheritance — Angular only\n * collects signal inputs through a decorated chain.\n */\n@Directive()\nexport abstract class MenuOverlayHost<\n H extends MenuItemHandle = MenuItemHandle,\n> extends AnchoredOverlayPositioningBase {\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<ForMenuCloseReason | 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 /**\n * The `MenuOpenerRegistration` protocol, forwarded once for every root. Kept\n * `private` on purpose: it is the piece protocol, so it must stay out of the\n * roots' emitted `.d.ts` while remaining callable at runtime — which is what\n * the trigger directives' `asMenuOpenerRegistration` narrowing relies on.\n */\n private activateOpener(opener: MenuOpenerHandle, returnFocusTarget?: HTMLElement | null): void {\n this._overlay.activateOpener(opener, returnFocusTarget);\n }\n\n private releaseOpener(opener: MenuOpenerHandle): void {\n this._overlay.releaseOpener(opener);\n }\n\n private returnFocusTarget(): HTMLElement | null {\n return this._overlay.returnFocusTarget();\n }\n\n protected setVirtualAnchor(x: number, y: number): void {\n this._overlay.setVirtualAnchor(x, y);\n }\n\n protected setVirtualAnchorFromRect(rect: DOMRect): void {\n this._overlay.setVirtualAnchorFromRect(rect);\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): boolean {\n return 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 focusInitialEnabledItem(target: 'first' | 'last'): boolean {\n return this._overlay.focusInitialEnabledItem(target);\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: ForMenuCloseReason): 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 { DestroyRef, DOCUMENT, inject, Injectable, PLATFORM_ID } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\nimport { composedContains } from 'forty-cdk/core';\n\n/** Window (ms) hover opens stay suppressed after the last scroll that concerns an overlay. */\nexport const DEFAULT_SCROLL_DISMISS_SUPPRESSION_MS = 200;\n\n/**\n * Which scrolls concern one registered overlay. Both accessors are read when a\n * scroll is dispatched or a suppression is queried, so a trigger or surface\n * registered after the overlay is picked up.\n */\nexport interface ScrollDismissScope {\n /**\n * The element the overlay is anchored to. A scroll of an element that does\n * not contain it moves nothing the overlay is positioned against, so it\n * neither dismisses nor suppresses. `null`, or an anchor no longer in the\n * document, leaves every scroll in scope.\n */\n readonly anchor: () => Element | null;\n /**\n * The overlay's own surface. A scroll inside it (an `overflow: auto` region\n * in the content) neither dismisses nor suppresses.\n */\n readonly surface: () => Element | null;\n}\n\n/** Inputs for {@link ScrollDismissDispatcher.register}. */\nexport interface ScrollDismissOptions {\n /**\n * Closes the overlay and cancels its pending timers. Called synchronously on\n * every scroll in scope while {@link active} holds.\n */\n readonly dismiss: () => void;\n /** Narrows which scrolls dismiss and suppress. Omitted, every scroll does. */\n readonly scope?: ScrollDismissScope;\n /**\n * Whether a scroll has anything to dismiss: the overlay is open, or an open /\n * close timer is pending. Read before the scope, so an idle overlay costs one\n * call per scroll. Omitted, the registration is always active.\n */\n readonly active?: () => boolean;\n}\n\n/** Handle returned by {@link ScrollDismissDispatcher.register}. */\nexport interface ScrollDismissRegistration {\n /**\n * Whether a scroll in this registration's scope happened within the\n * suppression window. Hover opens bail while this returns `true`, so content\n * sliding under a stationary pointer cannot flicker the overlay open.\n * Always `false` on the server and after {@link unregister}.\n */\n isSuppressed(): boolean;\n /** Removes this registration. Idempotent; call it from a `DestroyRef` hook. */\n unregister(): void;\n}\n\ninterface Registration {\n readonly dismiss: () => void;\n readonly scope: ScrollDismissScope | undefined;\n readonly active: () => boolean;\n}\n\nconst ALWAYS_ACTIVE = (): boolean => true;\n\nconst SERVER_REGISTRATION: ScrollDismissRegistration = {\n isSuppressed: () => false,\n unregister: () => {},\n};\n\n/**\n * Application-scoped owner of the single capture-phase document `scroll`\n * listener shared by every hover-driven anchored overlay (Tooltip, HoverCard).\n *\n * When an ancestor scroll container moves its content under a stationary\n * cursor, the browser does not reliably dispatch `pointerleave` /\n * `pointerenter` on the triggers sliding past the pointer. On each scroll the\n * dispatcher therefore dismisses every active registration whose scope the\n * scroll concerns, and records the scrolled element with a timestamp. A\n * registration is suppressed while a recorded scroll within\n * {@link DEFAULT_SCROLL_DISMISS_SUPPRESSION_MS} concerns its own scope, so a\n * scroll elsewhere on the page, or inside the overlay's own surface, never\n * blocks its hover opens.\n *\n * One listener is installed with the first registration and removed with the\n * last. Per scroll the work is one map write plus one `active()` call per\n * registration; the containment walk runs only for active registrations, and\n * for idle ones only when their own hover asks whether it is suppressed.\n *\n * `providedIn: 'root'`, so it is one instance per application injector and is\n * garbage-collected with it. Internal core tier, exported for the tooltip /\n * hover-card entry points, never for consumers.\n */\n@Injectable({ providedIn: 'root' })\nexport class ScrollDismissDispatcher {\n readonly #doc = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n\n readonly #registrations = new Set<Registration>();\n readonly #recentScrolls = new Map<EventTarget | null, number>();\n #listener: AbortController | null = null;\n\n constructor() {\n inject(DestroyRef).onDestroy(() => {\n this.#listener?.abort();\n this.#listener = null;\n this.#registrations.clear();\n this.#recentScrolls.clear();\n });\n }\n\n /**\n * Registers an overlay for scroll dismissal and per-overlay suppression. Each\n * call is an independent registration, so registering the same callback\n * twice yields two handles that must both be unregistered. A no-op handle on\n * the server.\n */\n register(options: ScrollDismissOptions): ScrollDismissRegistration {\n if (!this.#isBrowser) {\n return SERVER_REGISTRATION;\n }\n const registration: Registration = {\n dismiss: options.dismiss,\n scope: options.scope,\n active: options.active ?? ALWAYS_ACTIVE,\n };\n this.#registrations.add(registration);\n this.#listen();\n return {\n isSuppressed: () =>\n this.#registrations.has(registration) && this.#suppresses(registration.scope),\n unregister: () => this.#unregister(registration),\n };\n }\n\n #listen(): void {\n if (this.#listener) {\n return;\n }\n this.#listener = new AbortController();\n this.#doc.addEventListener('scroll', (event) => this.#onScroll(event), {\n capture: true,\n passive: true,\n signal: this.#listener.signal,\n });\n }\n\n #unregister(registration: Registration): void {\n if (!this.#registrations.delete(registration) || this.#registrations.size > 0) {\n return;\n }\n this.#listener?.abort();\n this.#listener = null;\n this.#recentScrolls.clear();\n }\n\n #onScroll(event: Event): void {\n const now = Date.now();\n this.#recentScrolls.delete(event.target);\n this.#recentScrolls.set(event.target, now + DEFAULT_SCROLL_DISMISS_SUPPRESSION_MS);\n this.#pruneExpired(now);\n for (const registration of this.#registrations) {\n if (\n registration.active() &&\n (!registration.scope || scrollConcerns(event.target, registration.scope))\n ) {\n registration.dismiss();\n }\n }\n }\n\n #pruneExpired(now: number): void {\n for (const [target, until] of this.#recentScrolls) {\n if (until > now) {\n return;\n }\n this.#recentScrolls.delete(target);\n }\n }\n\n #suppresses(scope: ScrollDismissScope | undefined): boolean {\n const now = Date.now();\n this.#pruneExpired(now);\n for (const target of this.#recentScrolls.keys()) {\n if (!scope || scrollConcerns(target, scope)) {\n return true;\n }\n }\n return false;\n }\n}\n\nfunction scrollConcerns(target: EventTarget | null, scope: ScrollDismissScope): boolean {\n if (!(target instanceof Node)) {\n return true;\n }\n const surface = scope.surface();\n if (surface && composedContains(surface, target)) {\n return false;\n }\n const anchor = scope.anchor();\n if (!anchor || !anchor.isConnected) {\n return true;\n }\n return composedContains(target, anchor);\n}\n"],"mappings":";;;;;;;AAYA,SAAgB,iCAA8B;CAC5C,MAAM,aA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