forty-cdk 0.45.1 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/fesm2022/forty-cdk-core-anchored.mjs +3 -3
  2. package/fesm2022/forty-cdk-core-anchored.mjs.map +1 -1
  3. package/fesm2022/forty-cdk-core-overlay.mjs +60 -17
  4. package/fesm2022/forty-cdk-core-overlay.mjs.map +1 -1
  5. package/fesm2022/forty-cdk-core.mjs +66 -4
  6. package/fesm2022/forty-cdk-core.mjs.map +1 -1
  7. package/fesm2022/forty-cdk-drag-drop.mjs +5 -4
  8. package/fesm2022/forty-cdk-drag-drop.mjs.map +1 -1
  9. package/fesm2022/forty-cdk-listbox.mjs +73 -22
  10. package/fesm2022/forty-cdk-listbox.mjs.map +1 -1
  11. package/fesm2022/forty-cdk-menubar.mjs +8 -6
  12. package/fesm2022/forty-cdk-menubar.mjs.map +1 -1
  13. package/fesm2022/forty-cdk-navigation-menu.mjs +18 -28
  14. package/fesm2022/forty-cdk-navigation-menu.mjs.map +1 -1
  15. package/fesm2022/forty-cdk-radio-group.mjs +7 -9
  16. package/fesm2022/forty-cdk-radio-group.mjs.map +1 -1
  17. package/fesm2022/forty-cdk-slider.mjs +3 -3
  18. package/fesm2022/forty-cdk-slider.mjs.map +1 -1
  19. package/fesm2022/forty-cdk-table.mjs +19 -15
  20. package/fesm2022/forty-cdk-table.mjs.map +1 -1
  21. package/fesm2022/forty-cdk-tabs.mjs +15 -20
  22. package/fesm2022/forty-cdk-tabs.mjs.map +1 -1
  23. package/fesm2022/forty-cdk-toggle.mjs +6 -10
  24. package/fesm2022/forty-cdk-toggle.mjs.map +1 -1
  25. package/fesm2022/forty-cdk-tree.mjs +35 -11
  26. package/fesm2022/forty-cdk-tree.mjs.map +1 -1
  27. package/listbox/README.md +22 -0
  28. package/package.json +1 -1
  29. package/types/forty-cdk-core-overlay.d.ts +33 -4
  30. package/types/forty-cdk-core.d.ts +42 -0
  31. package/types/forty-cdk-listbox.d.ts +19 -1
  32. package/types/forty-cdk-tabs.d.ts +4 -3
@@ -1 +1 @@
1
- {"version":3,"file":"forty-cdk-core-overlay.mjs","names":[],"sources":["../../../projects/forty-cdk/core-overlay/src/body-scroll-lock/body-scroll-lock.ts","../../../projects/forty-cdk/core-overlay/src/dismissible-layer/dismissible-layer.ts","../../../projects/forty-cdk/core-overlay/src/dismissible-layer/outside-veto.ts","../../../projects/forty-cdk/core-overlay/src/drawer-stack/drawer-stack.ts","../../../projects/forty-cdk/core-overlay/src/debounced-action/debounced-action.ts","../../../projects/forty-cdk/core-overlay/src/inert-siblings/inert-siblings.ts","../../../projects/forty-cdk/core-overlay/src/modal-shell/modal-activation-order.ts","../../../projects/forty-cdk/core-overlay/src/modal-shell/modal-backdrop.ts","../../../projects/forty-cdk/core-overlay/src/modal-shell/modal-shell.ts","../../../projects/forty-cdk/core-overlay/src/modal-shell/modal-trigger.ts","../../../projects/forty-cdk/core-overlay/src/modal-shell/modal-surface-base.ts","../../../projects/forty-cdk/core-overlay/src/overlay-warnings/mounted-while-closed.ts","../../../projects/forty-cdk/core-overlay/src/overlay-warnings/open-without-content.ts","../../../projects/forty-cdk/core-overlay/src/overlay-warnings/uncontrolled-trigger.ts","../../../projects/forty-cdk/core-overlay/src/overlay-warnings/unnamed-dialog.ts","../../../projects/forty-cdk/core-overlay/src/overlay-manager/overlay-manager.ts","../../../projects/forty-cdk/core-overlay/src/overlay-manager/overlay-ref.ts"],"sourcesContent":["import { DOCUMENT, Injectable, PLATFORM_ID, inject } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\n/**\n * Refcounted scroll lock, keyed per target element (default `<body>`).\n * Multiple modal surfaces acquire and release locks independently — only the\n * first acquire for a given target mutates that target, only the last release\n * un-mutates it. Different targets (body vs a container element) are fully\n * independent: locking a container does not affect body scroll and vice versa.\n *\n * **Semantic: clear, do not restore.** On the first lock for a target the\n * service writes `overflow: hidden` and an optional scrollbar-compensating\n * `padding-right` inline on that target. On the final unlock it _clears_ the\n * inline styles it set (`target.style.overflow = ''`, and\n * `target.style.paddingRight = ''` only when this lock actually wrote it) and\n * lets the CSS cascade take over again. It does NOT snapshot the values at\n * lock time and rewrite them at unlock time.\n *\n * Why: any code (route transition, theme toggle, the consumer themselves)\n * that mutates `target.style.overflow` between `lock()` and the final\n * `unlock()` would otherwise be silently clobbered when we restored the\n * stale snapshot. Clearing on unlock means the lock owns the inline style\n * only while it exists; intervening mutations win, and the resting state\n * is whatever stylesheet rules apply.\n *\n * **The page lock reaches the viewport.** Body overflow scrolls the viewport\n * only while `<html>` declares none of its own, so when `<html>` computes a\n * scrollable overflow (`html { overflow-y: scroll }`) the body lock also\n * writes `overflow: hidden` on `<html>`, and clears it on the final unlock\n * under the same contract.\n *\n * **Compensation is measured, not assumed.** The lock reads the width of the\n * scrolling box (`documentElement.clientWidth` for the body path, the\n * target's own `clientWidth` for an element) before and after writing\n * `overflow: hidden`, and pads the target by exactly the width the hidden\n * scrollbar gave back. Borders never count. When nothing is given back (an\n * overlay-scrollbar platform, a page that does not overflow), or when\n * `scrollbar-gutter: stable` keeps the space reserved, no `padding-right` is\n * written, so a consumer's unrelated inline `padding-right` survives the\n * lock. A container whose width is fixed under `box-sizing: content-box`\n * grows by the compensation rather than absorbing it.\n *\n * SSR: the service is `providedIn: 'root'` so its counter map is scoped to a\n * single Angular bootstrap (one per SSR request). Server-side calls are\n * no-ops.\n */\n@Injectable({ providedIn: 'root' })\nexport class BodyScrollLock {\n readonly #document = inject(DOCUMENT);\n readonly #window = this.#document.defaultView;\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n\n readonly #targets = new Map<\n HTMLElement,\n { count: number; wrotePaddingRight: boolean; wroteRootOverflow: boolean }\n >();\n\n /**\n * Acquire the scroll lock on `target` (default `document.body`). The first\n * call for a given target sets `overflow: hidden` and compensates for the\n * scrollbar width; subsequent calls increment the refcount only.\n */\n lock(target: HTMLElement = this.#document.body): void {\n if (!this.#isBrowser) {\n return;\n }\n let record = this.#targets.get(target);\n if (!record) {\n record = { count: 0, wrotePaddingRight: false, wroteRootOverflow: false };\n this.#targets.set(target, record);\n }\n if (record.count === 0) {\n const root = this.#document.documentElement;\n const isBody = target === this.#document.body;\n const scroller = isBody ? root : target;\n const win = this.#window;\n const widthBefore = scroller.clientWidth;\n const paddingRight = win ? parseFloat(win.getComputedStyle(target).paddingRight) || 0 : 0;\n const lockRoot = isBody && win !== null && this.#scrollsViewport(win, root);\n const gutterIsStable =\n win !== null && this.#gutterIsStable(win, isBody ? [root, target] : [target]);\n\n target.style.overflow = 'hidden';\n if (lockRoot) {\n root.style.overflow = 'hidden';\n record.wroteRootOverflow = true;\n }\n\n const scrollbarWidth = scroller.clientWidth - widthBefore;\n if (scrollbarWidth > 0 && !gutterIsStable) {\n target.style.paddingRight = `${paddingRight + scrollbarWidth}px`;\n record.wrotePaddingRight = true;\n }\n }\n record.count++;\n }\n\n /**\n * Release the scroll lock on `target` (default `document.body`). The last\n * release clears the inline `overflow` (and `padding-right` if written) and\n * lets the CSS cascade take over.\n */\n unlock(target: HTMLElement = this.#document.body): void {\n if (!this.#isBrowser) {\n return;\n }\n const record = this.#targets.get(target);\n if (!record || record.count === 0) {\n return;\n }\n record.count--;\n if (record.count === 0) {\n target.style.overflow = '';\n if (record.wroteRootOverflow) {\n this.#document.documentElement.style.overflow = '';\n }\n if (record.wrotePaddingRight) {\n target.style.paddingRight = '';\n }\n this.#targets.delete(target);\n }\n }\n\n /**\n * True when any of the given elements reserves the scrollbar gutter via\n * `scrollbar-gutter: stable` (or `stable both-edges`). The gutter then\n * survives the `overflow: hidden` toggle, so no padding compensation is\n * needed, even though `clientWidth` reports the reserved space as freed.\n */\n #gutterIsStable(win: Window, els: readonly HTMLElement[]): boolean {\n for (const el of els) {\n const gutter = win.getComputedStyle(el).getPropertyValue('scrollbar-gutter');\n if (gutter.trim().split(/\\s+/).includes('stable')) {\n return true;\n }\n }\n return false;\n }\n\n #scrollsViewport(win: Window, root: HTMLElement): boolean {\n const style = win.getComputedStyle(root);\n return [style.overflowX, style.overflowY].some(\n (value) => value === 'auto' || value === 'scroll',\n );\n }\n}\n","import { DOCUMENT, DestroyRef, ElementRef, Injectable, PLATFORM_ID, inject } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\nimport {\n composedContains,\n EscapeArbiter,\n isImeComposing,\n resolveActiveElement,\n resolveEventTarget,\n} from 'forty-cdk/core';\n\n/**\n * The outside-interaction channels a {@link DismissibleLayer} can own. A layer\n * declares the channels it wants routed to it at {@link DismissibleLayer.activate};\n * {@link DismissibleLayerStack} dispatches an outside `pointerdown` / `focusin`\n * to the topmost layer that declared the matching channel. Escape is not a\n * channel — it is dispatched to the topmost active layer, and to a layer below\n * only while every layer above it declines the key (see\n * {@link DismissibleLayerActivateOptions.onEscapeKeyDown}).\n */\nexport type DismissibleLayerChannel = 'pointer' | 'focus';\n\n/**\n * Declared nesting position of a layer inside a chain of layers that are\n * structurally nested (a menubar menu and its submenus, a submenu and its own\n * submenu). {@link DismissibleLayerStack} orders such a chain by `depth` rather\n * than by activation order, so a deeper level is always dispatched to before\n * its ancestors even when both levels mount in the same render pass and the\n * `afterNextRender` callbacks fire child-before-parent.\n *\n * A layer that declares no nesting keeps the plain LIFO behaviour: it is pushed\n * on top of everything, and never reorders relative to a chain it does not\n * belong to (a Dialog opened from inside a submenu still lands topmost).\n */\nexport interface DismissibleLayerNesting {\n /**\n * Identity of the chain this layer belongs to — typically the coordination\n * context of the outermost level. Only layers sharing a chain are ordered\n * against each other by `depth`.\n */\n readonly chain: object;\n /** `0` for the outermost level, `+1` per nesting level below it. */\n readonly depth: number;\n}\n\n/**\n * Options passed to `DismissibleLayer.activate`. Each handler receives the\n * native event; the consumer owns the close decision inside its own handler\n * (there is no separate default-dismiss callback).\n */\nexport interface DismissibleLayerActivateOptions {\n /**\n * The outside-interaction channels this layer owns. The stack routes an\n * outside `pointerdown` to the topmost layer declaring `'pointer'` and an\n * outside `focusin` to the topmost layer declaring `'focus'`, so an\n * Escape-only surface (Tooltip, HoverCard) declares `[]` and stays\n * transparent to the real dismissible layers beneath it. Escape is dispatched\n * from the topmost layer down regardless of this declaration.\n */\n channels: readonly DismissibleLayerChannel[];\n\n /**\n * Declared position of this layer inside a chain of structurally nested\n * layers. When present, {@link DismissibleLayerStack} inserts the layer by\n * depth within its chain instead of pushing it on top, so the stack order\n * reflects the nesting rather than the order the levels happened to activate\n * in. Omit for a standalone overlay.\n */\n nesting?: DismissibleLayerNesting;\n\n /**\n * The element the surface was opened from. A layer whose anchor lies inside\n * another layer, or inside a layer stacked above that one, counts as nested\n * in it (see {@link DismissibleLayer.hasNestedLayer}).\n */\n anchor?: Element;\n\n /**\n * Fired when a layer nested in this one is removed from the stack, after the\n * removal.\n */\n onNestedLayerRemoved?: () => void;\n\n /**\n * Fired when the user presses `Escape` while this is the topmost layer, or while every layer\n * stacked above it declined the key. Return `false` to decline it too: the key is then offered\n * to the layer below, unless this layer is\n * {@link DismissibleLayerActivateOptions.modal | modal}. Any other return value keeps it.\n */\n onEscapeKeyDown?: (event: KeyboardEvent) => unknown;\n\n /**\n * Fired when the user pointer-downs outside this layer's host. Return `true` when the handler\n * closed the layer: only then is the press offered to the pointer layer below, and only when that\n * layer opted in through {@link DismissibleLayerActivateOptions.cascadeOutsidePress}.\n */\n onPointerDownOutside?: (event: PointerEvent) => unknown;\n\n /**\n * Fired when the user pointer-downs **inside** this layer's host or one of its `exemptElements`\n * — the mirror of `onPointerDownOutside`.\n *\n * It answers \"was that press mine?\" with the same containment rule the dismissal path uses,\n * instead of the owner re-deriving the surface set from its own host listeners.\n */\n onPointerDownInside?: (event: PointerEvent) => void;\n\n /**\n * Fired when focus moves outside this layer's host. That includes focus moving into an\n * `<iframe>` outside it, which the host document observes only as its window losing focus:\n * `event` is then the window's `blur`.\n */\n onFocusOutside?: (event: FocusEvent) => void;\n\n /**\n * Fired in addition to `onPointerDownOutside` / `onFocusOutside` for\n * consumers that don't care which one occurred.\n */\n onInteractOutside?: (event: PointerEvent | FocusEvent) => void;\n\n /**\n * Extra elements whose subtrees count as \"inside\" for outside-pointer /\n * outside-focus checks (e.g. a portaled popover content owned by this\n * layer). Recomputed on every event so that DOM mutations are picked up,\n * and handed the node being tested so an owner can leave part of an exempt\n * subtree outside.\n */\n exemptElements?: (target: Node) => readonly Element[];\n\n /**\n * Whether this layer also closes on an outside press that the pointer layer directly above it\n * closed on. Read on every press. Without it, an outside press reaches only the topmost pointer\n * layer.\n *\n * The cascade walks down one pointer layer at a time and stops at the first layer that contains\n * the press, keeps itself open, did not opt in, or is\n * {@link DismissibleLayerActivateOptions.modal | modal}.\n */\n cascadeOutsidePress?: () => boolean;\n\n /**\n * Whether this layer is a modal surface. A modal layer ends an outside-press cascade: a press it\n * receives is never offered to the layers beneath it.\n */\n modal?: boolean;\n}\n\nconst EMPTY_ACTIVATE_OPTIONS: DismissibleLayerActivateOptions = { channels: [] };\n\n/**\n * Application-scoped registry that owns the document listeners used by\n * dismissible layers. Created once per Angular bootstrap (one per SSR\n * request), tied to the root injector lifetime.\n *\n * Listeners are installed on the first layer activation and removed with the last, and a\n * `DestroyRef` hook clears both the listeners and the stack, so no bootstrap leaves listeners\n * behind. Installation is a no-op off-browser.\n *\n * **Stack order** is activation order for standalone layers, but a layer declaring a\n * {@link DismissibleLayerNesting} is inserted by nesting depth within its chain. Activation order\n * is a render-timing artifact — a menu and its submenu mounted in one pass run their\n * `afterNextRender` callbacks child-before-parent — so ordering by timing would place an ancestor\n * above its own descendant, making the descendant's first focus read as `focusOutside` and collapse\n * the chain.\n *\n * **Listener phases are asymmetric.** `pointerdown` and `focusin` register on the\n * capture phase, so an outside interaction is detected even when overlay content stops\n * propagation. `keydown` registers on the bubble phase instead, because the per-overlay Escape\n * handlers call `stopPropagation()` after closing — which is what keeps one Escape from closing an\n * ancestor layer too. The accepted trade-off is that overlay content with its own bubble-phase\n * `keydown` handler calling `stopPropagation()` can swallow Escape before it arrives.\n *\n * An Escape that belongs to an IME composition (see `isImeComposing`) is never dispatched: it\n * cancels the conversion, not the topmost layer.\n *\n * **A press inside an `<iframe>` reaches no document listener**: it is dispatched in the frame's\n * own document, and engines do not consistently fire `focusin` on the `<iframe>` element either.\n * What the host document does observe is its window's `blur` with the frame as the active element,\n * resolved through open shadow roots, so the stack also listens for that and dispatches it on the\n * `'focus'` channel as focus moving to the frame — once, even in an engine that also reports the\n * frame's `focusin`.\n */\n@Injectable({ providedIn: 'root' })\nexport class DismissibleLayerStack {\n readonly #document = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n\n readonly #stack: DismissibleLayer[] = [];\n #suppressDepth = 0;\n #listening = false;\n #lastFocusInTarget: EventTarget | null = null;\n\n readonly #onKeyDown = (event: KeyboardEvent): void => {\n if (event.key !== 'Escape' || isImeComposing(event)) {\n return;\n }\n if (event.defaultPrevented) {\n return;\n }\n if (this.#suppressDepth > 0) {\n return;\n }\n for (const layer of [...this.#stack].reverse()) {\n if (layer.isActive && (layer.handleEscape(event) || layer.isModal)) {\n return;\n }\n }\n };\n readonly #onPointerDown = (event: Event): void => {\n if (this.#suppressDepth > 0) {\n return;\n }\n const [topmost, ...below] = this.#layersForChannel('pointer');\n if (!topmost?.handlePointerDown(event as PointerEvent) || topmost.isModal) {\n return;\n }\n for (const layer of below) {\n if (!layer.isActive || !layer.cascadesOutsidePress()) {\n return;\n }\n if (!layer.handlePointerDown(event as PointerEvent) || layer.isModal) {\n return;\n }\n }\n };\n readonly #onFocusIn = (event: Event): void => {\n this.#lastFocusInTarget = resolveEventTarget(event);\n if (this.#suppressDepth > 0) {\n return;\n }\n this.#topmostForChannel('focus')?.handleFocusIn(event as FocusEvent);\n };\n readonly #onWindowBlur = (event: FocusEvent): void => {\n if (this.#suppressDepth > 0) {\n return;\n }\n const frame = resolveActiveElement(this.#document);\n if (!(frame instanceof HTMLIFrameElement) || frame === this.#lastFocusInTarget) {\n return;\n }\n this.#lastFocusInTarget = frame;\n this.#topmostForChannel('focus')?.handleFocusIn(event, frame);\n };\n\n constructor() {\n const unregisterEscapeQuery = inject(EscapeArbiter).register((node) =>\n this.#hasEscapeLayerAbove(node),\n );\n inject(DestroyRef).onDestroy(() => {\n unregisterEscapeQuery();\n this.#removeListeners();\n this.#stack.length = 0;\n this.#suppressDepth = 0;\n });\n }\n\n /** @internal */\n push(layer: DismissibleLayer): void {\n this.#stack.splice(this.#insertionIndex(layer), 0, layer);\n if (this.#stack.length === 1) {\n this.#installListeners();\n }\n }\n\n /** @internal */\n remove(layer: DismissibleLayer): void {\n const idx = this.#stack.indexOf(layer);\n if (idx < 0) {\n return;\n }\n const anchor = layer.anchor;\n const hosts = anchor\n ? this.#stack.slice(0, idx).filter((below) => this.containsFromLayer(below, anchor))\n : [];\n this.#stack.splice(idx, 1);\n if (this.#stack.length === 0) {\n this.#removeListeners();\n }\n for (const host of hosts) {\n host.nestedLayerRemoved();\n }\n }\n\n /**\n * @internal Whether `target` is inside `layer` or inside any layer stacked\n * above it. A layer stacked above the chosen channel handler (e.g. an\n * interactive Escape-only HoverCard over a Popover) counts as \"inside\", so an\n * interaction within it never leaks an \"outside\" dismissal to the layer below.\n */\n containsFromLayer(layer: DismissibleLayer, target: Node): boolean {\n const idx = this.#stack.indexOf(layer);\n if (idx < 0) {\n return layer.contains(target);\n }\n for (let i = idx; i < this.#stack.length; i++) {\n const above = this.#stack[i];\n if (above && above.contains(target)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * @internal Whether a layer stacked above `layer` was opened from inside it:\n * its anchor is inside `layer` or inside another layer stacked above it.\n */\n hasNestedLayer(layer: DismissibleLayer): boolean {\n const idx = this.#stack.indexOf(layer);\n if (idx < 0) {\n return false;\n }\n for (let i = idx + 1; i < this.#stack.length; i++) {\n const anchor = this.#stack[i]?.anchor;\n if (anchor && this.containsFromLayer(layer, anchor)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * @internal Whether `layer` is the topmost layer declaring `channel`, i.e. the\n * one an outside interaction on that channel is dispatched to.\n */\n isTopmostForChannel(layer: DismissibleLayer, channel: DismissibleLayerChannel): boolean {\n return this.#topmostForChannel(channel) === layer;\n }\n\n /**\n * Runs `fn` with the dispatcher suppressed. While suppressed, neither\n * Escape, pointer-down outside, nor focus-outside events are forwarded\n * to the topmost layer. Refcounted so nested teardowns nest correctly.\n */\n suppress<T>(fn: () => T): T {\n this.#suppressDepth++;\n try {\n return fn();\n } finally {\n this.#suppressDepth--;\n }\n }\n\n /**\n * Whether an `Escape` pressed inside `node` reaches an active layer before any layer containing\n * `node`: walking down from the top, an active layer comes first. Answers `false` while the\n * dispatcher is suppressed, since it would then dispatch to no layer.\n */\n #hasEscapeLayerAbove(node: Node): boolean {\n if (this.#suppressDepth > 0) {\n return false;\n }\n for (let i = this.#stack.length - 1; i >= 0; i--) {\n const layer = this.#stack[i];\n if (!layer) {\n continue;\n }\n if (layer.contains(node)) {\n return false;\n }\n if (layer.isActive) {\n return true;\n }\n }\n return false;\n }\n\n #installListeners(): void {\n if (!this.#isBrowser || this.#listening) {\n return;\n }\n this.#listening = true;\n this.#document.addEventListener('keydown', this.#onKeyDown);\n this.#document.addEventListener('pointerdown', this.#onPointerDown, true);\n this.#document.addEventListener('focusin', this.#onFocusIn, true);\n this.#document.defaultView?.addEventListener('blur', this.#onWindowBlur);\n }\n\n #removeListeners(): void {\n if (!this.#listening) {\n return;\n }\n this.#listening = false;\n this.#document.removeEventListener('keydown', this.#onKeyDown);\n this.#document.removeEventListener('pointerdown', this.#onPointerDown, true);\n this.#document.removeEventListener('focusin', this.#onFocusIn, true);\n this.#document.defaultView?.removeEventListener('blur', this.#onWindowBlur);\n this.#lastFocusInTarget = null;\n }\n\n /**\n * Where a newly activated layer belongs. Plain LIFO (the top of the stack)\n * unless the layer declared a {@link DismissibleLayerNesting}: then it slides\n * down past the trailing run of layers from the same chain that sit deeper\n * than it, so an ancestor activating after its own descendant still lands\n * below it. The scan stops at the first layer that is not a deeper\n * level of the same chain, so an unrelated overlay (a Dialog opened from\n * inside a submenu) is never jumped over.\n */\n #insertionIndex(layer: DismissibleLayer): number {\n const nesting = layer.nesting;\n let idx = this.#stack.length;\n if (!nesting) {\n return idx;\n }\n while (idx > 0) {\n const below = this.#stack[idx - 1]?.nesting;\n if (!below || below.chain !== nesting.chain || below.depth <= nesting.depth) {\n break;\n }\n idx--;\n }\n return idx;\n }\n\n #layersForChannel(channel: DismissibleLayerChannel): DismissibleLayer[] {\n const layers: DismissibleLayer[] = [];\n for (let i = this.#stack.length - 1; i >= 0; i--) {\n const layer = this.#stack[i];\n if (layer && layer.ownsChannel(channel)) {\n layers.push(layer);\n }\n }\n return layers;\n }\n\n #topmostForChannel(channel: DismissibleLayerChannel): DismissibleLayer | undefined {\n for (let i = this.#stack.length - 1; i >= 0; i--) {\n const layer = this.#stack[i];\n if (layer && layer.ownsChannel(channel)) {\n return layer;\n }\n }\n return undefined;\n }\n}\n\n/**\n * Coordinates the standard \"dismissible surface\" interactions used by modal\n * dialogs, popovers, dropdown menus, drawers, and any other transient\n * overlay: Escape, pointer-down outside, focus-outside.\n *\n * Dispatch is per channel. Escape goes to the topmost active layer, and reaches\n * a layer below only when every layer above it declined the key, so one Escape\n * still closes at most one layer and never crosses a modal layer.\n * Pointer-down-outside and focus-outside instead go to the topmost\n * layer that declared the matching channel: a layer that owns only Escape (e.g.\n * a Tooltip, declaring `channels: []`) is transparent to outside-pointer /\n * focus for the real dismissible layers beneath it, so a tooltip visible over\n * an open menu never shadows the menu's outside-click dismissal. Nested\n * real layers (a popover inside a dialog) still resolve to a single topmost\n * handler per channel, so single-dismiss semantics hold — unless a lower layer\n * opts into `cascadeOutsidePress`, in which case an outside press the layer\n * above it closed on reaches it too.\n *\n * Containment is stack-aware: an interaction inside a layer stacked *above* the\n * chosen handler counts as \"inside\", so an interactive Escape-only surface (a\n * HoverCard over a Popover) never leaks an outside dismissal to the layer below.\n *\n * Dispatch goes through a single shared document listener, so synchronous\n * changes to the stack from a handler don't leak into sibling listeners.\n */\nexport class DismissibleLayer {\n readonly #host: HTMLElement;\n readonly #stack: DismissibleLayerStack;\n #options: DismissibleLayerActivateOptions = EMPTY_ACTIVATE_OPTIONS;\n #channels: ReadonlySet<DismissibleLayerChannel> = new Set();\n #active = false;\n\n constructor(host: HTMLElement, stack: DismissibleLayerStack) {\n this.#host = host;\n this.#stack = stack;\n }\n\n get host(): HTMLElement {\n return this.#host;\n }\n\n get isActive(): boolean {\n return this.#active;\n }\n\n /**\n * @internal The nesting position declared at `activate`, or `undefined` for a\n * standalone layer. Read by {@link DismissibleLayerStack} to place the layer\n * by nesting depth instead of activation order. Public only so the stack can\n * read it, not part of the supported API.\n */\n get nesting(): DismissibleLayerNesting | undefined {\n return this.#options.nesting;\n }\n\n /**\n * @internal The anchor declared at `activate`. Read by\n * {@link DismissibleLayerStack} to tell which layers are nested in which.\n */\n get anchor(): Element | undefined {\n return this.#options.anchor;\n }\n\n /**\n * Whether this layer is active and a layer opened from inside it is still\n * stacked above it: one whose anchor lies inside this layer, or inside a\n * layer stacked above this one.\n */\n hasNestedLayer(): boolean {\n return this.#active && this.#stack.hasNestedLayer(this);\n }\n\n /**\n * @internal Called by {@link DismissibleLayerStack} after a layer nested in\n * this one was removed.\n */\n nestedLayerRemoved(): void {\n this.#options.onNestedLayerRemoved?.();\n }\n\n /**\n * Pushes this layer onto the dispatch stack. Calling `activate` twice\n * without an intervening `deactivate` is a no-op.\n */\n activate(options: DismissibleLayerActivateOptions): void {\n if (this.#active) {\n return;\n }\n this.#active = true;\n this.#options = options;\n this.#channels = new Set(options.channels);\n this.#stack.push(this);\n }\n\n /** Removes this layer from the stack. */\n deactivate(): void {\n if (!this.#active) {\n return;\n }\n this.#active = false;\n this.#stack.remove(this);\n this.#options = EMPTY_ACTIVATE_OPTIONS;\n this.#channels = new Set();\n }\n\n /**\n * Convenience wrapper around the stack's `suppress`. Lets owners\n * suppress the dispatcher without needing a fresh injection context\n * (e.g. inside `DestroyRef.onDestroy` or imperative teardown closures).\n */\n suppress<T>(fn: () => T): T {\n return this.#stack.suppress(fn);\n }\n\n /**\n * @internal Whether this layer declared ownership of `channel`. Read by\n * {@link DismissibleLayerStack} to route an outside pointer-down / focus to\n * the topmost owning layer. Public only so the stack can read it, not part of\n * the supported API.\n */\n ownsChannel(channel: DismissibleLayerChannel): boolean {\n return this.#channels.has(channel);\n }\n\n /**\n * Whether this layer is active and is the topmost layer declaring `channel`, so no other layer\n * stacked above it would receive an outside interaction on that channel first.\n */\n isTopmostFor(channel: DismissibleLayerChannel): boolean {\n return this.#active && this.#stack.isTopmostForChannel(this, channel);\n }\n\n /**\n * @internal Whether `target` is inside this layer's host or its exempt\n * elements. Read by {@link DismissibleLayerStack} when walking the stack for\n * stack-aware containment. Public only so the stack can read it.\n *\n * Containment is composed-tree containment, the counterpart of the deep\n * target {@link resolveEventTarget} resolves: plain `Node.contains` answers\n * within one node tree, so a press on a control inside a web component's\n * shadow root — a target the composed path resolves precisely — would read as\n * a press outside the surface that renders it.\n */\n contains(target: Node): boolean {\n if (composedContains(this.#host, target)) {\n return true;\n }\n const exempt = this.#options.exemptElements?.(target);\n if (!exempt) {\n return false;\n }\n for (const el of exempt) {\n if (composedContains(el, target)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * @internal Dispatched by {@link DismissibleLayerStack} to the topmost layer\n * on `Escape`, and to each layer below it while the layers above decline the\n * key. Returns whether this layer kept it. Public only so the stack can call it\n * without exploiting a TS visibility loophole; not part of the supported API\n * (stripped from `.d.ts`).\n */\n handleEscape(event: KeyboardEvent): boolean {\n return this.#options.onEscapeKeyDown?.(event) !== false;\n }\n\n /**\n * @internal Dispatched by {@link DismissibleLayerStack} to the topmost layer\n * declaring the `'pointer'` channel on an outside `pointerdown`, and to each\n * layer below it an outside-press cascade reaches. Returns whether the press\n * was outside and the layer closed on it. See {@link handleEscape}.\n */\n handlePointerDown(event: PointerEvent): boolean {\n const target = resolveEventTarget(event);\n if (!target) {\n return false;\n }\n if (this.#stack.containsFromLayer(this, target)) {\n this.#options.onPointerDownInside?.(event);\n return false;\n }\n const closed = this.#options.onPointerDownOutside?.(event) === true;\n this.#options.onInteractOutside?.(event);\n return closed;\n }\n\n /**\n * @internal Whether this layer declared itself modal at `activate`. Read by\n * {@link DismissibleLayerStack} to end an outside-press cascade.\n */\n get isModal(): boolean {\n return this.#options.modal === true;\n }\n\n /**\n * @internal Whether this layer currently opts into an outside-press cascade.\n * Read by {@link DismissibleLayerStack} on every press.\n */\n cascadesOutsidePress(): boolean {\n return this.#options.cascadeOutsidePress?.() === true;\n }\n\n /**\n * @internal Dispatched by {@link DismissibleLayerStack} to the topmost layer\n * declaring the `'focus'` channel on an outside `focusin`, and on the\n * window `blur` that moves focus into an `<iframe>`, with that frame as\n * `target`. See {@link handleEscape}.\n */\n handleFocusIn(event: FocusEvent, target: Node | null = resolveEventTarget(event)): void {\n if (!target || this.#stack.containsFromLayer(this, target)) {\n return;\n }\n this.#options.onFocusOutside?.(event);\n this.#options.onInteractOutside?.(event);\n }\n}\n\n/**\n * Creates a `DismissibleLayer` for the directive's host element and wires\n * deactivation into `DestroyRef`. The host primitive owns activation\n * (typically via an `effect()` watching the open state).\n *\n * Use `layer.suppress(fn)` to run a callback with the dispatcher\n * suppressed (e.g. across a focus-return that would otherwise\n * cascade-dismiss the next topmost layer).\n */\nexport function injectDismissibleLayer(): DismissibleLayer {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const stack = inject(DismissibleLayerStack);\n const layer = new DismissibleLayer(host.nativeElement, stack);\n inject(DestroyRef).onDestroy(() => layer.deactivate());\n return layer;\n}\n","import type { Signal } from '@angular/core';\n\nimport type { DismissibleLayerActivateOptions, DismissibleLayerChannel } from './dismissible-layer';\nimport { createVetoableNativeEvent, type VetoableNativeEvent } from 'forty-cdk/core';\n\n/**\n * Emit forwarders + implicit-close wiring for the outside-interaction channels\n * that {@link buildOutsideVetoOptions} folds into self-closing layer handlers.\n * Each wired outside channel builds one veto, emits it through the specific\n * output (if wired) and the composite `interactOutside` output (if wired), then\n * closes itself when un-vetoed and `dismissible()` is `true`. Escape is\n * intentionally absent: it never participates in the outside-close (it is a\n * one-shot channel whose close behaviour differs per shell), so each shell\n * wires its own `onEscapeKeyDown` alongside the object this returns.\n *\n * Every field is optional so a shell can register a layer listener only for the\n * channels its consumer actually forwards — the trigger-anchored overlays opt\n * out of individual channels (an input-focused combobox owns Escape on its\n * input and omits it here), while the modal shell forwards all three.\n */\nexport interface OutsideVetoConfig {\n /**\n * Whether an un-vetoed outside interaction fires the implicit\n * `requestClose`. Read fresh on every outside interaction.\n */\n readonly dismissible?: Signal<boolean>;\n /**\n * Called with the matching reason (`'pointerDownOutside'` / `'focusOutside'`)\n * when the consumer doesn't veto the outside interaction and `dismissible()`\n * is `true`. Each wired outside channel fires its own close.\n */\n readonly requestClose?: (reason: 'pointerDownOutside' | 'focusOutside') => 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\n/**\n * Builds the pointer-down-outside / focus-outside entries of a\n * {@link DismissibleLayerActivateOptions}, folding the composite\n * `interactOutside` emit and the implicit close into each specific channel so\n * every wired outside channel closes itself.\n *\n * The protocol: each handler builds a single {@link VetoableNativeEvent} for\n * its physical interaction, hands it to the specific emitter (if wired) and\n * then to the composite `interactOutside` emitter (if wired), and — when\n * neither subscriber vetoed and `dismissible()` is `true` — calls\n * `requestClose(reason)` with the channel's reason (`'pointerDownOutside'` /\n * `'focusOutside'`). A `preventDefault()` from either the specific or the\n * composite subscriber suppresses the close, since both observe the same veto.\n * The pointer handler returns whether it closed, which is what lets an outside\n * press cascade to a lower layer that opted in.\n *\n * `onPointerDownOutside` is registered when either the specific\n * `emitPointerDownOutside` or the composite `emitInteractOutside` is wired, and\n * `onFocusOutside` likewise — matching what {@link outsideVetoChannels}\n * declares — so an interact-only wiring still gets both self-closing handlers.\n * Returns only the channels whose emitter is present, so the caller can spread\n * the result into its `dismissible.activate({...})` call alongside the pieces\n * that stay shell-specific (`exemptElements`, `onEscapeKeyDown`).\n */\nexport function buildOutsideVetoOptions(\n config: OutsideVetoConfig,\n): Pick<DismissibleLayerActivateOptions, 'onPointerDownOutside' | 'onFocusOutside'> {\n const options: Pick<DismissibleLayerActivateOptions, 'onPointerDownOutside' | 'onFocusOutside'> =\n {};\n const {\n dismissible,\n requestClose,\n emitPointerDownOutside,\n emitFocusOutside,\n emitInteractOutside,\n } = config;\n\n if (emitPointerDownOutside || emitInteractOutside) {\n options.onPointerDownOutside = (event) => {\n const veto = createVetoableNativeEvent<PointerEvent | FocusEvent>(event);\n emitPointerDownOutside?.(veto as VetoableNativeEvent<PointerEvent>);\n emitInteractOutside?.(veto);\n if (!veto.defaultPrevented && dismissible?.() && requestClose) {\n requestClose('pointerDownOutside');\n return true;\n }\n return false;\n };\n }\n\n if (emitFocusOutside || emitInteractOutside) {\n options.onFocusOutside = (event) => {\n const veto = createVetoableNativeEvent<PointerEvent | FocusEvent>(event);\n emitFocusOutside?.(veto as VetoableNativeEvent<FocusEvent>);\n emitInteractOutside?.(veto);\n if (!veto.defaultPrevented && dismissible?.() && requestClose) {\n requestClose('focusOutside');\n }\n };\n }\n\n return options;\n}\n\n/**\n * Derives the outside-interaction channels a shell must declare at\n * `dismissible.activate({ channels })` from the same {@link OutsideVetoConfig}\n * passed to {@link buildOutsideVetoOptions}. A layer owns `'pointer'` when it\n * forwards either the specific pointer-down-outside channel or the composite\n * interact-outside channel (which fires for pointer-downs too), and likewise\n * `'focus'` for focus-outside / interact-outside. A shell that forwards no\n * outside channel (an Escape-only surface) gets `[]` and stays transparent to\n * the real dismissible layers beneath it.\n */\nexport function outsideVetoChannels(config: OutsideVetoConfig): DismissibleLayerChannel[] {\n const channels: DismissibleLayerChannel[] = [];\n if (config.emitPointerDownOutside || config.emitInteractOutside) {\n channels.push('pointer');\n }\n if (config.emitFocusOutside || config.emitInteractOutside) {\n channels.push('focus');\n }\n return channels;\n}\n","import { computed, Injectable, type Signal, signal } from '@angular/core';\n\nimport { type ForDrawerSide } from './drawer-side';\nimport { fortyError } from 'forty-cdk/core';\n\n/**\n * Snapshot of a single drawer registered with {@link ForDrawerStack}. The\n * stack is LIFO ordered (root → topmost) and exposes only what other\n * coordinators need — `host` for ancestry checks, `side` (a `Signal`, so a\n * runtime side flip recomputes dependent transforms) for layout heuristics,\n * `parent` for topology, and the resolved nested-transform tunables so\n * `ForDrawerScaleCoordinator`'s nested-transform pass never needs to re-read\n * scope-dependent defaults.\n */\nexport interface DrawerStackNode {\n readonly host: HTMLElement;\n /**\n * Reactive edge the drawer is anchored to. Read inside the coordinator's\n * nested-transform effect so a runtime `[side]` rebind recomputes the\n * parent surface's transform axis.\n */\n readonly side: Signal<ForDrawerSide>;\n readonly parent: HTMLElement | null;\n /**\n * Scale factor applied to *this* drawer's host while it owns one or\n * more direct child drawers (the nested-drawer visual). Resolved from\n * the drawer's own injector scope at push time so per-scope\n * `provideForDrawerDefaults` overrides flow through.\n */\n readonly nestedScaleAmount: number;\n /**\n * Pixels of translation applied to *this* drawer's host while it owns\n * one or more direct child drawers, in the direction *away* from its\n * anchored edge.\n */\n readonly nestedTranslateYpx: number;\n}\n\n/**\n * Returned by {@link ForDrawerStack.push}. `depth` is the number of\n * ancestor drawers in the node's `parent` chain (0 for a root drawer, 1 for a\n * single-nested child, …), recomputed whenever the stack changes. `cleanup`\n * pops the node; calling it while descendants are still registered throws so\n * consumers surface their own destroy-order bugs instead of silently leaking.\n */\nexport interface DrawerStackHandle {\n readonly depth: Signal<number>;\n cleanup(): void;\n}\n\n/**\n * App-scoped LIFO registry of every active `[forDrawer]`. Mounted drawers\n * push themselves on first render and pop on destroy; the stack's signal\n * is the single source of truth for nesting topology consumed by:\n *\n * - `[forDrawer]` itself, to derive `data-depth` and `data-state-nested`\n * on its host (the latter when the stack contains a node whose\n * `parent` is this drawer's host).\n * - `ForDrawerScaleCoordinator`, when `scaleBackground` is opted in by\n * multiple levels of nesting and the visual effect must compose along\n * the LIFO topmost.\n *\n * The companion to {@link DismissibleLayerStack} and `InertSiblingsStack`:\n * those keep the focus / dismiss / inert behaviour LIFO-correct, this one\n * keeps the *visual* / *topology* layer LIFO-correct. Both are read-only\n * to consumers — there is no public API for explicit ordering. A drawer is\n * pushed on top unless one of its descendants is already registered, as\n * when parent and child mount in one render pass, in which case it is\n * inserted below its first descendant.\n *\n * SSR: `providedIn: 'root'` so state is per Angular bootstrap. The\n * directives that call `push` only do so from `afterNextRender`, which\n * doesn't run on the server, so there is nothing to guard here.\n *\n * Internal core tier — exported from `forty-cdk/core-overlay` for the\n * library's own entry points, with no semver guarantee.\n */\n@Injectable({ providedIn: 'root' })\nexport class ForDrawerStack {\n readonly #stack = signal<readonly DrawerStackNode[]>([]);\n\n /**\n * Reactive view of the current drawer stack (root → topmost). Reading\n * this from a `computed`/`effect` lets primitives react to nesting\n * changes synchronously when a child drawer mounts or unmounts.\n */\n readonly stack: Signal<readonly DrawerStackNode[]> = this.#stack.asReadonly();\n\n /**\n * Push a drawer onto the stack. Returns a {@link DrawerStackHandle}\n * carrying the computed `depth` and a `cleanup` that pops the same\n * node. `depth` is derived from the node's `parent` chain through the\n * registered drawers: a root drawer (no `parent`) is depth 0; a child of\n * a depth-N drawer is depth N+1.\n *\n * `cleanup` is idempotent on a node that's already gone, but throws if\n * the node still has descendants in the stack — the canonical signal\n * that the consumer's template tore down a parent before its child\n * (typically because the parent's `@if` flipped to `false` while the\n * child sits in a separate template branch). Nest the child's\n * `@if (childOpen())` *inside* the parent's `@if (parentOpen())` to\n * inherit Angular's bottom-up destroy order automatically.\n */\n push(node: DrawerStackNode): DrawerStackHandle {\n this.#stack.update((s) => {\n const descendant = s.findIndex((other) => this.#isDescendant(other, node, s));\n const next = s.slice();\n next.splice(descendant === -1 ? next.length : descendant, 0, node);\n return next;\n });\n return {\n depth: computed(() => this.#computeDepth(node, this.#stack())),\n cleanup: () => this.#cleanup(node),\n };\n }\n\n #cleanup(node: DrawerStackNode): void {\n const current = this.#stack();\n const idx = current.indexOf(node);\n if (idx === -1) {\n return;\n }\n const hasDescendant = current.some(\n (other) => other !== node && this.#isDescendant(other, node, current),\n );\n if (hasDescendant) {\n throw fortyError({\n code: 'FORCDK-DRAWER-001',\n message: 'A parent drawer was destroyed while a nested child drawer was still registered.',\n cause:\n 'The drawer stack unwinds last-in-first-out, so a child must unmount before its parent. ' +\n 'Sibling @if blocks unmount in template order instead.',\n fix: \"Wrap the child drawer's @if inside the parent's, so the child unmounts first.\",\n });\n }\n const next = current.slice();\n next.splice(idx, 1);\n this.#stack.set(next);\n }\n\n #computeDepth(node: DrawerStackNode, stack: readonly DrawerStackNode[]): number {\n if (node.parent === null) {\n return 0;\n }\n let depth = 0;\n let cursor: HTMLElement | null = node.parent;\n while (cursor) {\n depth += 1;\n const ancestor = stack.find((n) => n.host === cursor);\n if (!ancestor) {\n break;\n }\n cursor = ancestor.parent;\n }\n return depth;\n }\n\n #isDescendant(\n candidate: DrawerStackNode,\n ancestor: DrawerStackNode,\n stack: readonly DrawerStackNode[],\n ): boolean {\n let cursor: HTMLElement | null = candidate.parent;\n while (cursor) {\n if (cursor === ancestor.host) {\n return true;\n }\n const next = stack.find((n) => n.host === cursor);\n if (!next) {\n return false;\n }\n cursor = next.parent;\n }\n return false;\n }\n}\n","/**\n * A single self-clearing debounce timer: the `Math.max(0, delay)` clamp, the\n * `delay === 0` synchronous fast-path, and the lone pending\n * `setTimeout` / `clearTimeout` pair.\n *\n * The hover-driven menus (`[forMenuSub]`, `[forMenubar]`, `[forNavigationMenu]`)\n * each hand-rolled this exact timer arming/clearing under their own divergent\n * open/close policy (chain keep-alive, hover-after-open, per-value cancel\n * guards, skip-delay). This factory owns only the timing mechanics so those\n * policies stay at the call site — the caller arms with `schedule(delay)`,\n * which clears any in-flight timer first, runs `run` immediately when the\n * clamped delay is `0`, else fires it once after the delay.\n *\n * Internal core tier — exported from `forty-cdk/core-overlay` for the\n * library's own entry points, with no semver guarantee.\n */\nexport interface DebouncedAction {\n /**\n * Arm the action after `delay` ms (clamped to `>= 0`). Clears any pending\n * timer first; a clamped delay of `0` runs `run` synchronously.\n */\n schedule(delay: number): void;\n /** Cancel a pending action without running it. Safe with no pending timer. */\n cancel(): void;\n /** `true` while an action is armed but not yet fired. */\n isPending(): boolean;\n}\n\n/**\n * Builds a {@link DebouncedAction} around `run`. Framework-free.\n */\nexport function createDebouncedAction(run: () => void): DebouncedAction {\n let timer: ReturnType<typeof setTimeout> | null = null;\n\n function cancel(): void {\n if (timer !== null) {\n clearTimeout(timer);\n timer = null;\n }\n }\n\n function schedule(delay: number): void {\n cancel();\n const clamped = Math.max(0, delay);\n if (clamped === 0) {\n run();\n return;\n }\n timer = setTimeout(() => {\n timer = null;\n run();\n }, clamped);\n }\n\n return {\n schedule,\n cancel,\n isPending: () => timer !== null,\n };\n}\n","import { DOCUMENT, Injectable, PLATFORM_ID, inject } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\nimport {\n composedContains,\n composedParentElement,\n MODAL_EXEMPT_ATTRIBUTE,\n MODAL_PEER_ATTRIBUTE,\n} from 'forty-cdk/core';\n\ninterface SnapshotEntry {\n readonly el: HTMLElement;\n readonly hadInert: boolean;\n readonly prevAriaHidden: string | null;\n}\n\nexport interface InertSiblingsHandle {\n /** Pop this owner off the stack and recompute. */\n deactivate(): void;\n /** Whether this handle is still on the stack. */\n readonly isActive: boolean;\n}\n\ninterface RootState {\n readonly root: HTMLElement;\n readonly stack: HTMLElement[];\n appliedSnapshot: SnapshotEntry[];\n observer: MutationObserver | null;\n}\n\ntype PeerAnchors = readonly Element[] | 'always';\n\n/**\n * Marks every direct child of a **root element** (default `document.body`,\n * or a positioned container when a region-scoped modal passes one)\n * other than the topmost active owner (and any peer of that owner) as `inert` and\n * `aria-hidden=\"true\"` while at least one owner is active on that root.\n * Restores each touched element to its exact prior state once the last\n * owner deactivates.\n *\n * `aria-modal=\"true\"` alone is insufficient: Safari with VoiceOver, among other combinations, still\n * announces siblings of an aria-modal node unless the rest of the document is explicitly hidden.\n *\n * **Stacking.** Each root keeps its own owner stack, snapshot and `MutationObserver`, so a\n * `document.body` root and a container root are fully independent. The element-level outcome is\n * recomputed from the current topmost owner whenever the stack changes: the previous outcome is\n * reverted to its snapshot first, then a fresh one is applied. Closing owners out of LIFO order\n * therefore still leaves a coherent document, and full restoration runs when the stack empties.\n *\n * **Portals.** The owner need not be a direct child of the root — the root-level child that is an\n * ancestor of the owner is resolved and its subtree excluded, so an in-place dialog keeps its\n * enclosing app shell interactive. That walk climbs the composed tree, so an owner rendered inside\n * a shadow root still resolves to the root-level child hosting it.\n *\n * **Peers.** An overlay registered through {@link InertSiblingsStack.registerPeer} is excluded from\n * the snapshot only while it belongs to the topmost owner of the root it sits in, so the peer of a\n * background modal is inerted again under a nested one. The stack reflects that state as\n * `data-for-modal-peer` on the registered host. An element carrying the attribute without being\n * registered (a backdrop) is excluded under every owner, as is one carrying\n * {@link MODAL_EXEMPT_ATTRIBUTE}, which additionally opts out of the dismissible layer.\n *\n * **Late siblings.** While any owner is active, a `MutationObserver` inerts each newly added\n * sibling under the same rules, so an element portaled to the root after activation is isolated and\n * restored too.\n *\n * SSR: every operation is a no-op on the server, since `activate()` is only ever called from\n * `afterNextRender`.\n */\n@Injectable({ providedIn: 'root' })\nexport class InertSiblingsStack {\n readonly #document = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n\n readonly #roots = new Map<HTMLElement, RootState>();\n readonly #peers = new Map<HTMLElement, PeerAnchors>();\n\n /**\n * Push `owner` onto the inert-siblings stack for `root` (default\n * `document.body`) and (re)apply the isolation outcome for the new topmost\n * owner. Returns a handle whose `deactivate()` pops this specific owner —\n * order-safe, so closing out of LIFO order works.\n *\n * When `root` is a positioned container (e.g. a region-scoped modal), only\n * that container's other children are inerted; body siblings outside the\n * container stay fully interactive.\n */\n activate(owner: HTMLElement, root: HTMLElement = this.#document.body): InertSiblingsHandle {\n if (!this.#isBrowser) {\n return {\n deactivate: () => {},\n get isActive(): boolean {\n return false;\n },\n };\n }\n const state = this.#stateFor(root);\n this.#revertAppliedSnapshot(state);\n if (state.stack.length === 0) {\n this.#startObserving(state);\n }\n state.stack.push(owner);\n this.#applyForCurrentTopmost(state);\n this.#syncPeerAttributes();\n\n let active = true;\n return {\n get isActive(): boolean {\n return active;\n },\n deactivate: (): void => {\n if (!active) {\n return;\n }\n active = false;\n const idx = state.stack.indexOf(owner);\n if (idx === -1) {\n return;\n }\n this.#revertAppliedSnapshot(state);\n state.stack.splice(idx, 1);\n if (state.stack.length > 0) {\n this.#applyForCurrentTopmost(state);\n } else {\n this.#stopObserving(state);\n this.#roots.delete(root);\n }\n this.#syncPeerAttributes();\n },\n };\n }\n\n /**\n * Whether an overlay anchored to `anchor` should be left interactive over\n * the active modal — i.e. treated as a peer of the topmost owner instead of\n * inerted. Returns `true` only while at least one owner is active AND\n * `anchor` lives inside the current protected root for any active root, or\n * inside a registered peer that does, which means the overlay was opened\n * from within a modal (e.g. a Select / DropdownMenu opened from a form inside\n * a Dialog, or a submenu opened from that DropdownMenu).\n *\n * Returns `false` when no owner is active — so an overlay opened with no\n * modal present is never pre-marked, and a modal opened later inerts it like\n * any other background sibling — and when `anchor` sits in an already-inerted\n * background subtree (a toast or a tooltip anchored to a backdrop element).\n * SSR-safe: on the server the roots map is always empty (no owner\n * activates), so this returns `false`.\n */\n ownsAnchor(anchor: Element): boolean {\n for (const state of this.#roots.values()) {\n const protectedRoot = this.#currentProtectedRoot(state);\n if (protectedRoot !== null && this.#owns(protectedRoot, [anchor], new Set())) {\n return true;\n }\n }\n return false;\n }\n\n registerPeer(host: HTMLElement, anchors: PeerAnchors): () => void {\n if (!this.#isBrowser) {\n return () => {};\n }\n this.#peers.set(host, anchors);\n this.#reapplyAll();\n return () => {\n if (this.#peers.get(host) !== anchors) {\n return;\n }\n this.#peers.delete(host);\n host.removeAttribute(MODAL_PEER_ATTRIBUTE);\n this.#reapplyAll();\n };\n }\n\n #stateFor(root: HTMLElement): RootState {\n let state = this.#roots.get(root);\n if (!state) {\n state = { root, stack: [], appliedSnapshot: [], observer: null };\n this.#roots.set(root, state);\n }\n return state;\n }\n\n #applyForCurrentTopmost(state: RootState): void {\n const protectedRoot = this.#currentProtectedRoot(state);\n if (!protectedRoot) {\n return;\n }\n\n for (const child of Array.from(state.root.children)) {\n this.#inertChild(child, protectedRoot, state);\n }\n }\n\n #inertChild(child: Element, protectedRoot: HTMLElement, state: RootState): void {\n if (!(child instanceof HTMLElement)) {\n return;\n }\n if (child === protectedRoot || child.hasAttribute(MODAL_EXEMPT_ATTRIBUTE)) {\n return;\n }\n const anchors = this.#peers.get(child);\n const exempt =\n anchors === undefined\n ? child.hasAttribute(MODAL_PEER_ATTRIBUTE)\n : anchors === 'always' || this.#owns(protectedRoot, anchors, new Set());\n if (exempt) {\n return;\n }\n if (state.appliedSnapshot.some((entry) => entry.el === child)) {\n return;\n }\n\n state.appliedSnapshot.push({\n el: child,\n hadInert: child.hasAttribute('inert'),\n prevAriaHidden: child.getAttribute('aria-hidden'),\n });\n\n child.setAttribute('inert', '');\n child.setAttribute('aria-hidden', 'true');\n }\n\n #owns(\n protectedRoot: HTMLElement,\n anchors: readonly Element[],\n visited: Set<HTMLElement>,\n ): boolean {\n return anchors.some((anchor) => {\n if (composedContains(protectedRoot, anchor)) {\n return true;\n }\n for (const [peer, peerAnchors] of this.#peers) {\n if (peerAnchors === 'always' || visited.has(peer) || !composedContains(peer, anchor)) {\n continue;\n }\n visited.add(peer);\n if (this.#owns(protectedRoot, peerAnchors, visited)) {\n return true;\n }\n }\n return false;\n });\n }\n\n #reapplyAll(): void {\n for (const state of this.#roots.values()) {\n this.#revertAppliedSnapshot(state);\n this.#applyForCurrentTopmost(state);\n }\n this.#syncPeerAttributes();\n }\n\n #syncPeerAttributes(): void {\n for (const [peer, anchors] of this.#peers) {\n peer.toggleAttribute(MODAL_PEER_ATTRIBUTE, this.#isLivePeer(peer, anchors));\n }\n }\n\n #isLivePeer(peer: HTMLElement, anchors: PeerAnchors): boolean {\n if (anchors === 'always') {\n return true;\n }\n for (const state of this.#roots.values()) {\n const protectedRoot = this.#currentProtectedRoot(state);\n if (protectedRoot !== null && this.#owns(protectedRoot, anchors, new Set())) {\n return true;\n }\n }\n return false;\n }\n\n #currentProtectedRoot(state: RootState): HTMLElement | null {\n const top = state.stack[state.stack.length - 1];\n if (!top) {\n return null;\n }\n return this.#rootLevelChild(top, state.root) ?? top;\n }\n\n #startObserving(state: RootState): void {\n const win = this.#document.defaultView;\n if (state.observer || !win || typeof win.MutationObserver !== 'function') {\n return;\n }\n state.observer = new win.MutationObserver((records) => {\n const protectedRoot = this.#currentProtectedRoot(state);\n if (!protectedRoot) {\n return;\n }\n let addedPeer = false;\n for (const record of records) {\n for (const node of Array.from(record.addedNodes)) {\n if (node instanceof HTMLElement && node.parentElement === state.root) {\n addedPeer ||= this.#peers.has(node);\n this.#inertChild(node, protectedRoot, state);\n }\n }\n }\n if (addedPeer) {\n this.#syncPeerAttributes();\n }\n });\n state.observer.observe(state.root, { childList: true });\n }\n\n #stopObserving(state: RootState): void {\n state.observer?.disconnect();\n state.observer = null;\n }\n\n #revertAppliedSnapshot(state: RootState): void {\n for (const entry of state.appliedSnapshot) {\n if (!entry.hadInert) {\n entry.el.removeAttribute('inert');\n }\n if (entry.prevAriaHidden === null) {\n entry.el.removeAttribute('aria-hidden');\n } else {\n entry.el.setAttribute('aria-hidden', entry.prevAriaHidden);\n }\n }\n state.appliedSnapshot = [];\n }\n\n #rootLevelChild(el: HTMLElement, root: HTMLElement): HTMLElement | null {\n let cur: HTMLElement = el;\n let parent = composedParentElement(cur);\n while (parent && parent !== root) {\n cur = parent;\n parent = composedParentElement(cur);\n }\n return parent === root ? cur : null;\n }\n}\n","import { Injectable } from '@angular/core';\n\nimport { composedParentElement } from 'forty-cdk/core';\n\n@Injectable({ providedIn: 'root' })\nexport class ModalActivationOrder {\n readonly #held = new Map<HTMLElement, (() => void)[]>();\n\n hold(host: HTMLElement): void {\n this.#held.set(host, []);\n }\n\n enclosingHeld(node: Element | null): HTMLElement | null {\n let cursor: Element | null = node;\n while (cursor !== null) {\n if (cursor instanceof HTMLElement && this.#held.has(cursor)) {\n return cursor;\n }\n cursor = composedParentElement(cursor);\n }\n return null;\n }\n\n after(enclosing: HTMLElement | null, activate: () => void): void {\n const queue = enclosing === null ? undefined : this.#held.get(enclosing);\n if (queue === undefined) {\n activate();\n } else {\n queue.push(activate);\n }\n }\n\n release(host: HTMLElement): void {\n const queue = this.#held.get(host);\n if (queue === undefined) {\n return;\n }\n this.#held.delete(host);\n for (const activate of queue) {\n activate();\n }\n }\n}\n","import { DestroyRef, ElementRef, inject, type Signal } from '@angular/core';\n\nimport { injectPortal } from 'forty-cdk/core';\n\n/**\n * The members a modal surface's internal context adds for its backdrop piece. `ForDialog` and\n * `ForDrawer` implement them through `ModalSurfaceBase`.\n */\nexport interface ModalSurfaceBackdropContext {\n /**\n * The surface's host element, which the backdrop is portaled immediately before. `null` when no\n * surface host is rendered, and the backdrop is then appended to the container.\n */\n surfaceElement(): HTMLElement | null;\n /**\n * Whether the surface is the topmost layer owning the pointer channel, so a press on its\n * backdrop is not an outside press of a layer stacked above it.\n */\n isTopmostPointerLayer(): boolean;\n /**\n * Registers the backdrop as part of the surface, so the dismissible layer treats a press on it\n * as inside. The newest registration is the surface's backdrop, and a second one still mounted\n * once the render settles warns in dev mode.\n */\n registerBackdrop(el: HTMLElement): void;\n /** Removes a registered backdrop, leaving any newer registration in place. */\n unregisterBackdrop(el: HTMLElement): void;\n}\n\n/** What a backdrop piece reads off the modal surface that owns it. */\nexport interface ModalBackdropSurface extends ModalSurfaceBackdropContext {\n /** Portal target shared with the surface. `null` ⇒ `document.body`. */\n readonly container: Signal<HTMLElement | null>;\n /** Asks the surface to close with reason `'backdrop'`, gated on its `dismissible()`. */\n requestClose(reason: 'backdrop'): void;\n}\n\n/** Host listeners {@link injectModalBackdrop} hands back to the backdrop piece. */\nexport interface ModalBackdropHandle {\n /** Bind to the backdrop host's `(pointerdown)`. */\n readonly pointerDown: () => void;\n /** Bind to the backdrop host's `(click)`. */\n readonly click: (event: MouseEvent) => void;\n}\n\n/**\n * Wires a modal surface's backdrop piece: portals the host to the surface's container, registers\n * it on the surface for the piece's lifetime, and closes the surface with reason `'backdrop'` on a\n * click that lands on the backdrop itself.\n *\n * The backdrop lands immediately before its surface in the container, so two positioned elements\n * with no `z-index` paint the surface on top, and each backdrop of a stacked pair sits directly\n * below its own surface.\n *\n * The click closes the surface only when the surface was the topmost pointer layer as the press\n * began. A press that goes down while another layer is stacked above it (a nested drawer without a\n * backdrop of its own, a popover open inside the dialog) is that layer's outside press, so the\n * click ending it leaves the surface beneath open. A click with no preceding `pointerdown` is\n * judged on the stack as it stands.\n *\n * Must be called from the backdrop directive's injection context.\n */\nexport function injectModalBackdrop(surface: ModalBackdropSurface): ModalBackdropHandle {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n injectPortal({ target: surface.container, before: () => surface.surfaceElement() });\n surface.registerBackdrop(host);\n inject(DestroyRef).onDestroy(() => surface.unregisterBackdrop(host));\n\n let pressOwned: boolean | null = null;\n return {\n pointerDown: () => {\n pressOwned = surface.isTopmostPointerLayer();\n },\n click: (event) => {\n const owned = pressOwned ?? surface.isTopmostPointerLayer();\n pressOwned = null;\n if (event.target === host && owned) {\n surface.requestClose('backdrop');\n }\n },\n };\n}\n","import {\n computed,\n DestroyRef,\n DOCUMENT,\n ElementRef,\n inject,\n type Signal,\n signal,\n} from '@angular/core';\n\nimport {\n afterNextRenderCancellable,\n composedContains,\n composedParentElement,\n createVetoableEvent,\n createVetoableNativeEvent,\n findFirstFocusable,\n injectFocusTrap,\n injectPortal,\n isInitialFocusTarget,\n MODAL_EXEMPT_ATTRIBUTE,\n ModalOwnedRegions,\n resolveActiveElement,\n ReturnFocusResolver,\n type VetoableEvent,\n type VetoableNativeEvent,\n} from 'forty-cdk/core';\nimport { BodyScrollLock } from '../body-scroll-lock/body-scroll-lock';\nimport { injectDismissibleLayer } from '../dismissible-layer/dismissible-layer';\nimport { type InertSiblingsHandle, InertSiblingsStack } from '../inert-siblings/inert-siblings';\nimport { buildOutsideVetoOptions, outsideVetoChannels } from '../dismissible-layer/outside-veto';\nimport { ModalActivationOrder } from './modal-activation-order';\n\n/**\n * Dismissal wiring for a modal surface.\n *\n * Each channel builds one `VetoableNativeEvent` and hands it to both the specific emitter and the\n * composite `interactOutside` one, so a `preventDefault()` from either suppresses the close. When\n * nothing vetoes and `dismissible()` is `true`, the shell calls `requestClose` with the reason\n * matching the channel.\n *\n * `exemptElements` is re-read on every event, so elements portaled after activation are honoured.\n */\nexport interface ModalShellDismissConfig {\n /** Whether dismissals via the layer fire the implicit `requestClose`. */\n readonly dismissible: Signal<boolean>;\n /** Called with the matching reason when the consumer doesn't veto. */\n readonly requestClose: (reason: 'escape' | 'pointerDownOutside' | 'focusOutside') => void;\n /** Forwards the Escape `VetoableNativeEvent` to the directive's `(escapeKeyDown)` output. */\n readonly emitEscapeKeyDown: (veto: VetoableNativeEvent<KeyboardEvent>) => void;\n /** Forwards the pointer-down-outside veto to the directive's `(pointerDownOutside)` output. */\n readonly emitPointerDownOutside: (veto: VetoableNativeEvent<PointerEvent>) => void;\n /** Forwards the focus-outside veto to the directive's `(focusOutside)` output. */\n readonly emitFocusOutside: (veto: VetoableNativeEvent<FocusEvent>) => void;\n /** Forwards the composite veto to the directive's `(interactOutside)` output. */\n readonly emitInteractOutside: (veto: VetoableNativeEvent<PointerEvent | FocusEvent>) => void;\n /**\n * Live \"elements that count as inside\" set — Drawer uses this to exempt\n * its portaled backdrop so a backdrop click routes through the backdrop's\n * own `requestClose('backdrop')` path instead of `pointerDownOutside`.\n *\n * The shell always merges every `MODAL_EXEMPT_ATTRIBUTE` overlay (e.g. toast\n * viewports) on top of whatever this returns, so a primitive only lists its\n * *own* extra exemptions here. It is handed the node being tested.\n */\n readonly exemptElements?: (target: Node) => readonly Element[];\n}\n\n/**\n * Primitive-owned initial-focus algorithm for the surface. The richer\n * alternative to the `'first' | 'container'` literal: the shell sets up the\n * focus trap (Tab cycling + return capture) WITHOUT its own imperative focus\n * move, runs the optional `veto`, and — unless vetoed — calls `move()`. When\n * `move()` returns `false` (no candidate found) focus falls back to the trap\n * container (modal) or the first focusable descendant (non-modal).\n *\n * Mirrors `OverlayShellInitialFocusConfig` so a content directive can hand the\n * same focus algorithm to either shell. Used by Select (selected → first →\n * last option) and available for a future date-picker calendar-cell move.\n */\nexport interface ModalShellInitialFocusConfig {\n /** Primitive focus algorithm. Returns `true` on success, `false` to fall back. */\n readonly move: () => boolean;\n /** `(autoFocusOnOpen)` veto. Returning `true` skips the imperative focus move. */\n readonly veto?: () => boolean;\n}\n\n/**\n * Single config for the free-floating modal-overlay lifecycle. Mirrors the\n * `injectOverlayShell` shape on the trigger-anchored side. Each sub-bundle\n * is individually optional so a primitive can opt out of the channels it\n * doesn't need (e.g. a dismiss-less confirm dialog, though none ship today).\n */\nexport interface ModalShellConfig {\n /** Whether the surface activates focus-trap + scroll-lock + inert siblings. */\n readonly modal: Signal<boolean>;\n /**\n * Whether focus returns to the previously-focused element on destroy. No effect in non-modal\n * mode, where the shell never moves focus on close.\n */\n readonly returnFocus: Signal<boolean>;\n /**\n * Overrides the return-focus target, read at close time instead of captured in the constructor.\n * A `null` value falls back to the construction-time capture.\n *\n * Supply it when the surface may be constructed while focus lives inside another surface that is\n * about to be destroyed — a close→open modal swap in one change-detection pass — where the\n * captured element would be disconnected by close time and focus would fall back to `<body>`.\n *\n * Read only in modal mode, and only under the same gate as the construction-time capture:\n * {@link returnFocus} is `true` and `autoFocusOnClose` did not veto.\n */\n readonly returnFocusTarget?: Signal<HTMLElement | null>;\n /**\n * Where to send focus on mount. Two shapes:\n * - `Signal<'first' | 'container'>` — `'first'` = first focusable descendant\n * (falls back to host); `'container'` = host element. Same vocabulary as\n * `FocusTrap.activate({ initialFocus })`. Used by Dialog / Drawer /\n * date-picker.\n * - {@link ModalShellInitialFocusConfig} — a primitive-owned `move()`\n * algorithm (e.g. Select's selected → first → last option) with its own\n * open-veto, falling back to the container / first focusable on a miss.\n */\n readonly initialFocus: Signal<'first' | 'container'> | ModalShellInitialFocusConfig;\n /**\n * Element the consumer marked as the initial focus target, read once at mount. Honoured with the\n * literal `initialFocus` form only: when it resolves to an element that passes\n * `isInitialFocusTarget`, focus lands there, and otherwise the literal applies.\n */\n readonly initialFocusTarget?: () => HTMLElement | null;\n /**\n * `(autoFocusOnOpen)` veto. Bound as a function reference (not as an\n * Angular `output()`) so the shell can invoke it during the destroy hook\n * without depending on `OutputEmitterRef` lifecycle. Read at every mount;\n * a `preventDefault()` on the emitted event skips the imperative initial\n * focus move while still leaving the focus-trap (Tab cycling, return\n * capture) wired in modal mode.\n */\n readonly autoFocusOnOpen?: () => ((event: VetoableEvent) => void) | undefined;\n /**\n * `(autoFocusOnClose)` veto. Same shape as `autoFocusOnOpen`. Fired\n * synchronously from the shell's release (at close intent, or from the\n * destroy hook), BEFORE the modal / non-modal teardown so it runs reliably\n * on every close path — including a direct `open.set(false)` from the\n * consumer that bypasses any close-output emission.\n */\n readonly autoFocusOnClose?: () => ((event: VetoableEvent) => void) | undefined;\n /**\n * Portal target for the surface. A signal so it is read once at the first\n * render (the portal moves the host once), after the consumer's input is\n * bound. `undefined` / a signal yielding `null` ⇒ `document.body`.\n */\n readonly container?: Signal<HTMLElement | null>;\n /** Optional dismiss bundle. Absent for primitives that don't dismiss via the layer. */\n readonly dismiss?: ModalShellDismissConfig;\n}\n\n/** Imperative handle returned by `injectModalShell`. */\nexport interface ModalShellHandle {\n /** True while the shell activated focus-trap + scroll-lock + inert (modal mode). */\n readonly isModal: () => boolean;\n /**\n * The mode the surface is in: {@link ModalShellConfig.modal} until the shell activates, then the\n * mode it activated with, for the rest of the mount. Bind modality attributes to this so they\n * never disagree with the trap, the inert siblings and the scroll lock.\n */\n readonly modal: Signal<boolean>;\n /**\n * Whether the surface's dismissible layer is active and no layer owning the pointer channel is\n * stacked above it, so an outside press is the surface's to handle.\n */\n readonly isTopmostPointerLayer: () => boolean;\n readonly release: (returnFocusTarget?: HTMLElement | null) => void;\n}\n\n/**\n * Resolves the live set of independent overlay surfaces that opt out of every\n * modal's dismissible layer via {@link MODAL_EXEMPT_ATTRIBUTE} — today\n * `ForToastViewport`. Queried fresh on each interaction (no snapshot) so a\n * surface mounted *after* the modal opened still counts as \"inside\", which is\n * exactly the toast-over-open-dialog case. An interaction inside any returned\n * element therefore never dismisses the modal.\n */\nexport function resolveModalExemptOverlays(doc: Document): readonly Element[] {\n return Array.from(doc.querySelectorAll(`[${MODAL_EXEMPT_ATTRIBUTE}]`));\n}\n\n/**\n * Owns the lifecycle of a free-floating modal surface — the overlay primitives that mount as their\n * own root, `[forDialog]` and `[forDrawer]` today.\n *\n * The shell captures the return-focus target, portals the host to `document.body` (or to\n * `config.container`), and activates the dismissible layer. In modal mode it additionally inerts\n * the siblings, activates the focus trap and locks scroll, all scoped to `config.container` when\n * one is supplied; in non-modal mode it only performs the initial focus move. A modal host carrying\n * `aria-modal=\"true\"` also claims `ModalOwnedRegions` until it releases, so the live regions and\n * exempt toast viewports outside it stay in its accessibility subtree.\n *\n * Teardown reverses that order on destroy, deactivating inert siblings before focus returns so the\n * target is not blocked by an inert ancestor.\n *\n * Must be called from an injection context. The host's `ElementRef` is forwarded to every\n * collaborator, so the caller never wires them up directly.\n */\nexport function injectModalShell(config: ModalShellConfig): ModalShellHandle {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const document = inject(DOCUMENT);\n const focusTrap = injectFocusTrap();\n const dismissible = injectDismissibleLayer();\n const inertStack = inject(InertSiblingsStack);\n const scrollLock = inject(BodyScrollLock);\n const returnFocus = inject(ReturnFocusResolver);\n const modalOwnedRegions = inject(ModalOwnedRegions);\n\n // 1. Capture the return-focus target SYNCHRONOUSLY, before any side effect\n // runs. WebKit (#136) blurs the previously-focused element as soon as\n // `inert` is applied to an ancestor, so by the time `afterNextRender`\n // fires the focus trap could no longer read the trigger from\n // `document.activeElement`. Reading it now locks the trigger in.\n //\n // Resolved through open shadow roots (#1586): a raw `document.activeElement`\n // reports the shadow *host* when the trigger lives inside one — a consumer\n // component using `ViewEncapsulation.ShadowDom`, or a design-system web\n // component — and that host is typically not focusable, so return-focus\n // would silently drop to `<body>` on close. Because this target is always\n // passed to `trap.activate()`, the trap's own shadow-aware capture never\n // runs for a modal surface; this is the one that has to resolve.\n const active = resolveActiveElement(document);\n let returnFocusTarget: HTMLElement | null = active instanceof HTMLElement ? active : null;\n\n const order = inject(ModalActivationOrder);\n order.hold(host.nativeElement);\n let origin: Element | null = null;\n let enclosing: HTMLElement | null = null;\n afterNextRenderCancellable(() => {\n origin = composedParentElement(host.nativeElement);\n enclosing = order.enclosingHeld(origin);\n });\n\n // 2. Portal — moves the host to `document.body` after first render and\n // cleans up on destroy. `DestroyRef.onDestroy` callbacks fire in\n // registration order (FIFO), and the portal registers its hook here,\n // before the shell's own destroy hook below. That hook does not remove\n // the host synchronously in a browser: it waits for the next frame and\n // for any finite exit animation, so the shell runs return-focus while the\n // host is still attached. The ordering is harmless either way:\n // return-focus targets the previously-focused element (the trigger,\n // captured synchronously above), which lives OUTSIDE the portaled host.\n injectPortal(config.container ? { target: config.container } : {});\n\n // Captured at mount time so the destroy path can mirror the same mode the\n // shell activated, regardless of any `modal()` toggle on a doomed\n // instance.\n let activatedAsModal = false;\n const activatedMode = signal<boolean | null>(null);\n let inertHandle: InertSiblingsHandle | null = null;\n let activatedContainer: HTMLElement | null = null;\n let releaseOwnedRegions: (() => void) | null = null;\n\n const resolveMarkedTarget = (): HTMLElement | null => {\n const target = config.initialFocusTarget?.() ?? null;\n return target !== null && isInitialFocusTarget(target, host.nativeElement) ? target : null;\n };\n\n // 3. Side-effect setup runs after Angular has applied input bindings.\n // Reading `config.modal()` etc. in the constructor would always see the\n // default value because the input writes haven't flowed through yet.\n // `afterNextRenderCancellable` makes the destroy-before-render path safe.\n // On the true-async path (queued render after destroy) the callback is\n // cancelled, so inert siblings / focus trap / scroll lock / dismissible\n // layer are never activated (`activatedAsModal` stays false). On the\n // synchronous-teardown path the callback flushes just before the destroy\n // hook, so it sets `activatedAsModal = true` and the destroy hook below\n // tears the side-effect stack back down. Either way nothing leaks.\n let released = false;\n let releasePeer: (() => void) | null = null;\n const activate = (deferred: boolean): void => {\n if (deferred) {\n const current = resolveActiveElement(document);\n if (\n current instanceof HTMLElement &&\n enclosing !== null &&\n composedContains(enclosing, current)\n ) {\n returnFocusTarget = current;\n }\n }\n const isModal = config.modal();\n activatedAsModal = isModal;\n activatedMode.set(isModal);\n\n // 3a. Dismissible layer. Pushed onto the stack BEFORE moving focus so\n // focusin events triggered by our own focus management land on this\n // layer, not on whatever lower layer was previously topmost.\n //\n // Outside channels are self-closing: `buildOutsideVetoOptions` builds\n // one veto per physical interaction and hands it to both the specific\n // (pointer-down-outside / focus-outside) and the composite\n // `interactOutside` emitter, so a `preventDefault()` in either handler\n // vetoes the close.\n const dismissCfg = config.dismiss;\n if (dismissCfg !== undefined) {\n dismissible.activate({\n channels: outsideVetoChannels(dismissCfg),\n modal: isModal,\n exemptElements: (target) => [\n ...(dismissCfg.exemptElements?.(target) ?? []),\n ...resolveModalExemptOverlays(document),\n ],\n onEscapeKeyDown: (event) => {\n const veto = createVetoableNativeEvent(event);\n dismissCfg.emitEscapeKeyDown(veto);\n if (!veto.defaultPrevented && dismissCfg.dismissible()) {\n event.stopPropagation();\n dismissCfg.requestClose('escape');\n }\n },\n ...buildOutsideVetoOptions(dismissCfg),\n });\n }\n\n // 3b. Resolve the initial-focus config. The simple form is a\n // `Signal<'first' | 'container'>` (Dialog / Drawer / date-picker); the\n // richer form carries a primitive-owned `move()` algorithm (Select's\n // selected → first → last option) plus its own veto. A `Signal` is\n // callable, so `typeof === 'function'` distinguishes the two shapes;\n // the literal mode is read eagerly only in the simple form.\n const initialFocusCfg = config.initialFocus;\n const moveCfg: ModalShellInitialFocusConfig | null =\n typeof initialFocusCfg === 'function' ? null : initialFocusCfg;\n const literalFocus: 'first' | 'container' | null =\n typeof initialFocusCfg === 'function' ? initialFocusCfg() : null;\n const markedTarget = literalFocus === null ? null : resolveMarkedTarget();\n\n // 3c. `(autoFocusOnOpen)` veto — read once for this mount. The move-config\n // carries its own boolean veto (mirroring `injectOverlayShell`); the\n // simple form routes through the top-level `autoFocusOnOpen` callback.\n let skipInitialFocus: boolean;\n if (moveCfg) {\n skipInitialFocus = moveCfg.veto?.() ?? false;\n } else {\n const autoFocusOpenEvent = createVetoableEvent();\n config.autoFocusOnOpen?.()?.(autoFocusOpenEvent);\n skipInitialFocus = autoFocusOpenEvent.defaultPrevented;\n }\n\n if (isModal) {\n // 3d. Modal mode. Inert + aria-hide siblings BEFORE the focus trap\n // activates so the trap's `focus()` call lands on an\n // already-isolated tree. The return-focus target was captured\n // synchronously above (#136).\n const containerEl = config.container?.() ?? null;\n inertHandle = inertStack.activate(host.nativeElement, containerEl ?? undefined);\n activatedContainer = containerEl;\n if (host.nativeElement.getAttribute('aria-modal') === 'true') {\n releaseOwnedRegions = modalOwnedRegions.claim(host.nativeElement);\n }\n if (moveCfg) {\n // The primitive owns the focus move. Set up Tab cycling + return\n // capture WITHOUT the trap's own imperative focus, then run the\n // algorithm; fall back to the container when it finds no candidate.\n focusTrap.activate({\n preventInitialFocus: true,\n returnFocus: returnFocusTarget,\n });\n if (!skipInitialFocus && !moveCfg.move()) {\n focusTrap.container.focus();\n }\n } else {\n focusTrap.activate({\n initialFocus: markedTarget ?? literalFocus ?? 'first',\n preventInitialFocus: skipInitialFocus,\n returnFocus: returnFocusTarget,\n });\n }\n scrollLock.lock(containerEl ?? undefined);\n } else {\n // 3e. Non-modal mode. No trap, no scroll lock, no inert. Still respect\n // the configured initial focus: the primitive's `move()` algorithm\n // (falling back to the first focusable on a miss), the first\n // focusable descendant ('first'), or the host ('container').\n releasePeer = inertStack.registerPeer(\n host.nativeElement,\n [origin, returnFocusTarget].filter((anchor): anchor is Element => anchor !== null),\n );\n if (!skipInitialFocus) {\n const el = focusTrap.container;\n if (moveCfg) {\n if (!moveCfg.move()) {\n (findFirstFocusable(el) ?? el).focus();\n }\n } else if (markedTarget) {\n markedTarget.focus();\n } else if (literalFocus === 'container') {\n el.focus();\n } else {\n (findFirstFocusable(el) ?? el).focus();\n }\n }\n }\n };\n afterNextRenderCancellable(() => {\n let synchronous = true;\n order.after(enclosing, () => {\n if (!released) {\n activate(!synchronous);\n }\n order.release(host.nativeElement);\n });\n synchronous = false;\n });\n\n // 4. Release. Tears the side-effect stack down in the inverse order it was\n // activated, once: from `release()` at close intent when a manager drives\n // the exit animation, else from the destroy hook. Destroy hooks fire in\n // registration order; the portal's was registered inside `injectPortal()`\n // (above) so it runs BEFORE ours, scheduling the element's removal for\n // after the next frame and any finite exit animation.\n const release = (target?: HTMLElement | null): void => {\n if (released) {\n return;\n }\n released = true;\n order.release(host.nativeElement);\n releasePeer?.();\n releasePeer = null;\n dismissible.deactivate();\n // Invoke `(autoFocusOnClose)` synchronously, BEFORE either the modal or\n // non-modal teardown runs. Fires on every close path regardless of mode\n // (the consumer's `(dismiss)` flow AND a direct `open.set(false)` that\n // bypasses any close-output emission). The callback is a plain function\n // reference — input signals stay readable during destroy and there is no\n // dependency on `OutputEmitterRef` lifecycle. Non-modal mode never moves\n // focus on close, so `skipReturnFocus` is only consulted in the modal\n // branch — but the hook still fires for symmetry with the manager and so\n // consumers can wire their own focus moves on close in non-modal mode.\n const autoFocusCloseEvent = createVetoableEvent();\n config.autoFocusOnClose?.()?.(autoFocusCloseEvent);\n const skipReturnFocus = autoFocusCloseEvent.defaultPrevented;\n if (activatedAsModal) {\n // Lift inert + aria-hide BEFORE moving focus back: an `inert` ancestor\n // blocks `.focus()` on its descendants, so the return-focus target\n // needs to be live again first.\n inertHandle?.deactivate();\n inertHandle = null;\n releaseOwnedRegions?.();\n releaseOwnedRegions = null;\n const shouldReturnFocus = config.returnFocus() && !skipReturnFocus;\n const overrideTarget = target === undefined ? (config.returnFocusTarget?.() ?? null) : target;\n // Suppress the dismissible-layer dispatcher across focus-return so the\n // synthetic `focusin` triggered by `.focus()`-ing the previous element\n // does not cascade-dismiss whatever modal is now topmost (a stacked\n // dialog opened above this one).\n dismissible.suppress(() => {\n focusTrap.deactivate({ returnFocus: false });\n if (shouldReturnFocus) {\n returnFocus.resolve(overrideTarget, returnFocusTarget)?.focus();\n }\n });\n scrollLock.unlock(activatedContainer ?? undefined);\n }\n };\n inject(DestroyRef).onDestroy(() => release());\n\n return {\n isModal: () => activatedAsModal,\n modal: computed(() => activatedMode() ?? config.modal()),\n isTopmostPointerLayer: () => dismissible.isTopmostFor('pointer'),\n release,\n };\n}\n","import { DestroyRef, ElementRef, inject, Injectable, type Signal } from '@angular/core';\n\n/** The trigger state a modal-shell surface reads to recognise its own trigger. */\nexport interface ModalTriggerConfig {\n /** The trigger's open state. */\n readonly open: Signal<boolean>;\n /** The id of the surface the trigger controls, or `null` when unset. */\n readonly controls: Signal<string | null>;\n}\n\ninterface ModalTriggerEntry extends ModalTriggerConfig {\n readonly element: HTMLElement;\n}\n\n/**\n * The mounted triggers that toggle a modal-shell surface. A surface counts its own controlling\n * triggers as inside itself for outside-press and outside-focus dismissal, so the press that\n * precedes a trigger's toggling click never closes the surface the click is about to close.\n */\n@Injectable({ providedIn: 'root' })\nexport class ModalTriggerRegistry {\n readonly #entries = new Set<ModalTriggerEntry>();\n\n /** Adds a trigger and returns the function that removes it. */\n register(entry: ModalTriggerEntry): () => void {\n this.#entries.add(entry);\n return () => this.#entries.delete(entry);\n }\n\n /**\n * The open triggers controlling `surface`: those whose `controls` names the surface's id, and\n * those with no `controls`, which name no surface and so count as controlling any open one.\n */\n controlling(surface: HTMLElement): HTMLElement[] {\n const out: HTMLElement[] = [];\n for (const entry of this.#entries) {\n if (!entry.open()) {\n continue;\n }\n const controls = entry.controls();\n if (controls === null || (controls !== '' && controls === surface.id)) {\n out.push(entry.element);\n }\n }\n return out;\n }\n}\n\n/**\n * Registers the host as a trigger toggling a modal-shell surface, for as long as the host lives.\n * Must be called from an injection context.\n */\nexport function injectModalTrigger(config: ModalTriggerConfig): void {\n const element = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const release = inject(ModalTriggerRegistry).register({ ...config, element });\n inject(DestroyRef).onDestroy(release);\n}\n","import {\n booleanAttribute,\n computed,\n Directive,\n ElementRef,\n inject,\n input,\n output,\n signal,\n type Signal,\n} from '@angular/core';\n\nimport {\n hostAriaLabel,\n hostDescribedBy,\n hostLabelledBy,\n type SingleSlot,\n type VetoableEvent,\n type VetoableNativeEvent,\n} from 'forty-cdk/core';\nimport { type ModalShellConfig, type ModalShellHandle } from './modal-shell';\nimport { ModalTriggerRegistry } from './modal-trigger';\n\n/**\n * Abstract base for free-floating modal-surface primitives — a directive that\n * mounts a modal surface as its own root, coordinates label / description\n * registration, and drives its lifecycle through {@link injectModalShell}.\n * `ForDialog` and `ForDrawer` extend it; a future modal Toast / full-screen\n * sheet / command palette can too.\n *\n * The base owns everything the two surfaces used to duplicate verbatim: the\n * `aria-labelledby` / `aria-describedby` registry, the backdrop registration,\n * the exemption of the backdrop and of the controlling triggers\n * (`injectModalTrigger`) from outside dismissal,\n * the `requestClose` dismissible gating, the `lastCloseValue` bridge read by\n * the programmatic managers, the seven shared ARIA / state host bindings (`role`, `aria-modal`, `aria-label`,\n * `aria-labelledby`, `aria-describedby`, `data-state=\"open\"`, `tabindex=\"-1\"`),\n * the non-defaults inputs and dismiss outputs, and the {@link modalShellConfig}\n * factory. Anything primitive-specific (Drawer's drag / snap / scale / stack,\n * the four defaults-backed inputs each subclass seeds from its own\n * `FOR_<PRIMITIVE>_DEFAULTS`) stays on the subclass.\n *\n * The base does **not** call {@link injectModalShell} itself —\n * each subclass calls `injectModalShell(this.modalShellConfig())` from its own\n * constructor. A base-owned call would register its `afterNextRender` during\n * `super()`, before a subclass (Drawer) could register its own pre-shell\n * `afterNextRender` (stack push + snap validation), breaking the documented\n * ordering.\n *\n * Implemented as an `@Directive()`-decorated abstract class because Angular\n * recognises signal inputs / outputs and host bindings only when the\n * `input()` / `output()` calls and the `host` block appear on a decorated\n * class; inheritance is the supported mechanism for sharing them across\n * directives.\n *\n * Internal core tier — exported from `forty-cdk/core-overlay` for the\n * library's own entry points, with no semver guarantee. Subclassing a library\n * base is not a supported contract, so it is absent from `CORE_PUBLISHERS` and\n * from every primitive's own barrel; the public-types gate ignores\n * `extends`-only heritage, which is why the base may appear in the shipped\n * `.d.ts` as the parent of `[forDialog]` / `[forDrawer]` without being blessed.\n */\n@Directive({\n host: {\n '[attr.role]': 'alert() ? \"alertdialog\" : \"dialog\"',\n '[attr.aria-modal]': 'modalInEffect() ? \"true\" : null',\n '[attr.aria-label]': 'resolvedAriaLabel()',\n 'data-state': 'open',\n tabindex: '-1',\n },\n})\nexport abstract class ModalSurfaceBase<Reason extends string> {\n /** When true, role becomes `alertdialog` (interrupts assistive tech). */\n readonly alert = input(false, { transform: booleanAttribute });\n\n /**\n * Explicit element focus returns to on close, read at close time. Overrides\n * the element the shell captures at construction — supply it when this\n * surface can be constructed while focus lives inside a *different, doomed*\n * surface, the canonical case being a close→open swap in one change-detection\n * pass. The programmatic managers thread the true origin through this input\n * automatically; declarative consumers driving such a swap by hand can bind\n * it too. `null` (default) keeps the construction-time capture, so ordinary\n * usage is unaffected. Has no effect in non-modal mode (the shell never moves\n * focus on close then).\n */\n readonly returnFocusTarget = input<HTMLElement | null>(null);\n\n /** Manual `aria-label`. Use this when no visible title element exists. */\n readonly ariaLabel = input<string | null>(null);\n\n /**\n * Resolved `aria-label`: a consumer-set static value on the surface when\n * present, else the {@link ariaLabel} input.\n */\n private readonly resolvedAriaLabel = hostAriaLabel(() => this.ariaLabel() || null);\n\n /**\n * Portal target for the surface. Defaults to `document.body`. Pair with\n * `[modal]=\"false\"` for a surface scoped to a positioned region instead of\n * the viewport. Read once at mount. The backdrop portals to the same\n * container.\n */\n readonly container = input<HTMLElement | null>(null);\n\n /**\n * Callback invoked just before the surface moves focus into itself on mount.\n * Receives a `VetoableEvent`; call `event.preventDefault()` to skip the\n * imperative focus move — useful when opening from an input you want to keep\n * focused. The focus trap (modal mode) still cycles Tab inside the surface\n * once focus enters it.\n *\n * Bound as a function reference (`[autoFocusOnOpen]=\"onOpen\"`), not as an\n * event binding. The callback shape (rather than an `output()`) lets the\n * shell invoke it during the destroy hook without depending on Angular's\n * `OutputEmitterRef` lifecycle.\n */\n readonly autoFocusOnOpen = input<((event: VetoableEvent) => void) | undefined>(undefined);\n\n /**\n * Callback invoked just before focus returns to the previously focused\n * element on unmount. Receives a `VetoableEvent`; call\n * `event.preventDefault()` to skip the return-focus — useful when the\n * consumer wants to send focus elsewhere imperatively. Fires reliably on\n * both close paths: the `(dismiss)` output flow AND a direct\n * `open.set(false)` from the consumer.\n */\n readonly autoFocusOnClose = input<((event: VetoableEvent) => void) | undefined>(undefined);\n\n /**\n * Whether dismiss interactions (Escape, backdrop, outside interaction, and\n * any primitive-specific gesture) close the surface. Implemented by the\n * subclass so its default can be seeded from the primitive's scope defaults.\n */\n abstract readonly dismissible: Signal<boolean>;\n\n /**\n * Whether the surface activates modal semantics (`aria-modal`, focus trap,\n * body scroll lock, inert siblings). Read once at mount: a later change takes\n * effect on the next mount. Implemented by the subclass so its default can be\n * seeded from the primitive's scope defaults.\n */\n abstract readonly modal: Signal<boolean>;\n\n /**\n * Whether focus returns to the previously focused element on close.\n * Implemented by the subclass so its default can be seeded from the\n * primitive's scope defaults.\n */\n abstract readonly returnFocus: Signal<boolean>;\n\n /**\n * Where to send focus on mount — `'first'` (first focusable descendant) or\n * `'container'` (the surface host). Implemented by the subclass so its\n * default can be seeded from the primitive's scope defaults.\n */\n abstract readonly initialFocus: Signal<'first' | 'container'>;\n\n /**\n * Entry-point name the shared surface errors report under, e.g. `'dialog'`.\n * The subclass supplies it because the shell's checks are shared while the\n * `[forty-cdk/<scope>]` prefix a consumer reads must name the primitive they\n * actually wrote.\n */\n protected abstract readonly entryPoint: string;\n\n /**\n * The element the primitive's initial-focus marker registered inside the surface, or `null`.\n * Implemented by the subclass, which owns the marker's registration slot. The shell focuses it on\n * mount when it is a usable target, and falls back to {@link initialFocus} otherwise.\n */\n protected abstract readonly initialFocusTarget: Signal<HTMLElement | null>;\n\n /**\n * The slot the primitive's backdrop piece registers into. Implemented by the subclass, so the\n * dev-mode duplicate warning names the primitive's own surface and backdrop selectors.\n */\n protected abstract readonly backdropSlot: SingleSlot<HTMLElement>;\n\n /**\n * Emitted when the surface wants to close. Consumers wire this to flip the\n * signal that gates the surrounding `@if`. The reason union is\n * primitive-specific.\n */\n readonly dismiss = output<Reason>();\n\n /**\n * Fires when the user presses Escape while this surface is the topmost\n * dismissible layer. Call `preventDefault()` on the emitted veto to suppress\n * the subsequent `(dismiss)` emission. The original `KeyboardEvent` is on\n * `.event`.\n */\n readonly escapeKeyDown = output<VetoableNativeEvent<KeyboardEvent>>();\n\n /**\n * Fires when a pointer goes down outside the surface. Call `preventDefault()`\n * on the emitted veto to suppress the auto `(dismiss)`. The native\n * `PointerEvent` is on `.event`.\n */\n readonly pointerDownOutside = output<VetoableNativeEvent<PointerEvent>>();\n\n /**\n * Fires when focus moves outside the surface. `preventDefault()` on the veto\n * suppresses the auto `(dismiss)`. The native `FocusEvent` is on `.event`.\n */\n readonly focusOutside = output<VetoableNativeEvent<FocusEvent>>();\n\n /**\n * Composite event: fires alongside `pointerDownOutside` and `focusOutside`\n * and shares their veto state — `preventDefault()` on either one suppresses\n * the auto `(dismiss)`.\n */\n readonly interactOutside = output<VetoableNativeEvent<PointerEvent | FocusEvent>>();\n\n readonly #labelIds = signal<readonly string[]>([]);\n readonly #describedByIds = signal<readonly string[]>([]);\n readonly #lastCloseValue = signal<unknown>(undefined);\n readonly #host = inject<ElementRef<HTMLElement>>(ElementRef);\n readonly #triggers = inject(ModalTriggerRegistry);\n #shell: ModalShellHandle | null = null;\n\n private readonly modalInEffect = computed(() => this.#shell?.modal() ?? this.modal());\n\n /**\n * Resolved `aria-labelledby`: a consumer-set static value when present, else\n * the space-joined ids of the registered titles, or `null` when none.\n */\n readonly labelledBy = hostLabelledBy(() => {\n const ids = this.#labelIds();\n return ids.length === 0 ? null : ids.join(' ');\n });\n\n /**\n * Resolved `aria-describedby`: a consumer-set static value composed with the\n * space-joined ids of the registered descriptions, or `null` when neither is\n * present.\n */\n readonly describedBy = hostDescribedBy(() => {\n const ids = this.#describedByIds();\n return ids.length === 0 ? null : ids.join(' ');\n });\n\n /** Register a title element's id into `aria-labelledby`. */\n registerLabel(id: string): void {\n this.#labelIds.update((arr) => (arr.includes(id) ? arr : [...arr, id]));\n }\n\n /** Remove a title element's id from `aria-labelledby`. */\n unregisterLabel(id: string): void {\n this.#labelIds.update((arr) => arr.filter((x) => x !== id));\n }\n\n /** Register a description element's id into `aria-describedby`. */\n registerDescription(id: string): void {\n this.#describedByIds.update((arr) => (arr.includes(id) ? arr : [...arr, id]));\n }\n\n /** Remove a description element's id from `aria-describedby`. */\n unregisterDescription(id: string): void {\n this.#describedByIds.update((arr) => arr.filter((x) => x !== id));\n }\n\n private surfaceElement(): HTMLElement {\n return this.#host.nativeElement;\n }\n\n private registerBackdrop(el: HTMLElement): void {\n this.backdropSlot.register(el);\n }\n\n private unregisterBackdrop(el: HTMLElement): void {\n this.backdropSlot.unregister(el);\n }\n\n /**\n * Request that the surface close. `'closeButton'` and `'programmatic'` always\n * emit `(dismiss)`; every other reason is gated on `dismissible()`. `value`\n * is the close result, captured for the programmatic managers' close bridge.\n */\n requestClose(reason: Reason, value?: unknown): void {\n if (reason !== 'closeButton' && reason !== 'programmatic' && !this.dismissible()) {\n return;\n }\n this.#lastCloseValue.set(value);\n this.dismiss.emit(reason);\n }\n\n /**\n * The `value` argument from the most recent `requestClose(reason, value)`\n * call. Read by the programmatic managers to bridge `[for…Close] [closeWith]`\n * into `For…Ref.close(value)`. Part of the internal composition surface with\n * no semver guarantee; declarative consumers never need this.\n */\n readonly lastCloseValue = this.#lastCloseValue.asReadonly();\n\n /**\n * The registered backdrop element, or `null` when none is rendered. Read by\n * the programmatic managers' surface registrar so `beginLeave` drives the\n * backdrop's exit animation by direct reference instead of a document query.\n * Part of the internal composition surface with no semver guarantee;\n * declarative consumers never need this.\n */\n readonly backdropElement = computed(() => this.backdropSlot.value());\n\n /**\n * Keeps the handle the subclass's `injectModalShell(this.modalShellConfig())` call returned, which\n * the backdrop piece reads through {@link isTopmostPointerLayer}. Called once from the subclass\n * constructor.\n */\n protected attachModalShell(shell: ModalShellHandle): void {\n this.#shell = shell;\n }\n\n /**\n * Ends the surface's modal side effects ahead of its destroy and returns focus, to\n * `returnFocusTarget` when one is passed. Called by the programmatic managers at close intent, so\n * only the DOM removal waits for the exit animation. Part of the internal composition surface\n * with no semver guarantee; declarative consumers never need this.\n */\n releaseModalShell(returnFocusTarget?: HTMLElement | null): void {\n this.#shell?.release(returnFocusTarget);\n }\n\n /**\n * Whether this surface is the topmost layer owning the pointer channel. Read by the backdrop\n * piece through the internal context to decide whether a press on it is this surface's.\n */\n private isTopmostPointerLayer(): boolean {\n return this.#shell?.isTopmostPointerLayer() ?? true;\n }\n\n protected modalShellConfig(): ModalShellConfig {\n return {\n modal: this.modal,\n returnFocus: this.returnFocus,\n returnFocusTarget: this.returnFocusTarget,\n initialFocus: this.initialFocus,\n initialFocusTarget: () => this.initialFocusTarget(),\n container: this.container,\n autoFocusOnOpen: () => this.autoFocusOnOpen(),\n autoFocusOnClose: () => this.autoFocusOnClose(),\n dismiss: {\n dismissible: this.dismissible,\n requestClose: (reason) => this.requestClose(reason as Reason),\n emitEscapeKeyDown: (veto) => this.escapeKeyDown.emit(veto),\n emitPointerDownOutside: (veto) => this.pointerDownOutside.emit(veto),\n emitFocusOutside: (veto) => this.focusOutside.emit(veto),\n emitInteractOutside: (veto) => this.interactOutside.emit(veto),\n exemptElements: () => {\n const backdrop = this.backdropSlot.value();\n const triggers = this.#triggers.controlling(this.#host.nativeElement);\n return backdrop ? [backdrop, ...triggers] : triggers;\n },\n },\n };\n }\n}\n","import { afterNextRender } from '@angular/core';\nimport { fortyWarn } from 'forty-cdk/core';\n\n/**\n * Identifies the piece in the dev-mode mounted-while-closed warning and tells\n * the helper how to read its surface's open state.\n */\nexport interface MountedWhileClosedConfig {\n /** Entry-point name used in the `[forty-cdk/<primitive>]` prefix (e.g. `'select'`). */\n readonly primitive: string;\n /**\n * Selector of the mounted piece (e.g. `'[forSelectContent]'`). A directive\n * with more than one selector resolves the one the consumer actually wrote,\n * so the report names a piece they can find in their template —\n * `[forMenuContent]` serves `[forMenuSubContent]` too.\n */\n readonly piece: string;\n /**\n * The `@if` condition the primitive's README uses, quoted back as the fix\n * (e.g. `'select.open()'`). Keep the two in sync — a consumer following the\n * link should read the same expression there.\n *\n * A thunk is resolved inside the render hook, which is what lets a condition\n * interpolate a bound input: `[forNavigationMenuContent]` quotes its owning\n * item's value, unreadable at construction (see below).\n */\n readonly condition: string | (() => string);\n /** The surface's open state, read once after the first render. */\n readonly open: () => boolean;\n}\n\n/**\n * Warns — dev mode only, once per instance — when an overlay surface is still mounted after its\n * first render while its own open state reports closed, which is the consumer forgetting the `@if`.\n *\n * It is the library's quietest first-use mistake: the surface renders permanently,\n * `data-state=\"closed\"` lands on a visible element, the ARIA stays internally consistent and the\n * primitive keeps working, so it reads as a CSS bug rather than a wiring one.\n *\n * Mount equals open is structural for these surfaces, so the `@if` is the whole contract and no\n * input suppresses the warning. Only pieces whose closed state has no supported mounted shape adopt\n * it, so the always-mounted panel families do not.\n *\n * **The check is mount-time**, reading the open state inside `afterNextRender` and never again,\n * which buys three things:\n *\n * - The exit-animation window stays silent. A closed surface is legitimately mounted for as long as\n * `animate.leave` keeps it, so re-checking on close would report every correct overlay.\n * - Bindings have settled. A piece deriving its open state from an `input.required` its parent has\n * not written yet would throw NG0950 on a construction-time read. `condition` takes a thunk for\n * the same reason, so the quoted fix is built where the input is readable.\n * - It is inert on the server, where `afterNextRender` never fires.\n *\n * The cost is a deliberate false negative: a surface that mounts open and is then left mounted\n * forever goes unreported, since catching it would mean re-checking on close.\n *\n * Must be called from an injection context. A production build registers no render hook at all.\n */\nexport function warnIfMountedWhileClosed(config: MountedWhileClosedConfig): void {\n if (typeof ngDevMode !== 'undefined' && !ngDevMode) {\n return;\n }\n\n afterNextRender(() => {\n if (config.open()) {\n return;\n }\n const condition =\n typeof config.condition === 'function' ? config.condition() : config.condition;\n fortyWarn({\n code: 'FORCDK-CORE-006',\n scope: config.primitive,\n message: `${config.piece} is mounted while the surface is closed.`,\n cause:\n \"Presence in the DOM is the consumer's job, and there is no forceMount input — a surface \" +\n 'kept mounted while closed never runs `animate.enter` / `animate.leave`, and the lifecycle ' +\n 'it sets up on mount stays live while closed.',\n fix: `Wrap it with \\`@if (${condition})\\` so it unmounts on close. See the ${config.primitive} README.`,\n });\n });\n}\n","import { afterNextRender, effect, inject, Injector, untracked } from '@angular/core';\nimport { fortyWarn } from 'forty-cdk/core';\n\n/**\n * Identifies the surface in the dev-mode open-without-content warning and tells\n * the helper how to read the root's open state and its registered content.\n */\nexport interface OpenWithoutContentConfig {\n /** Entry-point name used in the `[forty-cdk/<primitive>]` prefix (e.g. `'select'`). */\n readonly primitive: string;\n /** Selector of the content piece the open surface is missing (e.g. `'[forSelectContent]'`). */\n readonly piece: string;\n /**\n * The `@if` condition the primitive's README uses, quoted back as the fix\n * (e.g. `'select.open()'`). A thunk is resolved when the warning is built, so\n * a root whose open state is a value can quote the one that opened.\n */\n readonly condition: string | (() => string);\n /** The surface's open state. */\n readonly open: () => boolean;\n /** The registered content element, or `null` while none is mounted. */\n readonly content: () => HTMLElement | null;\n}\n\n/**\n * Warns — dev mode only, once per entry into the state — when a surface is still open after a\n * settled render with no content piece registered, which is the consumer leaving out the content\n * block or gating it on a condition that stays false.\n *\n * The state fails silently: the trigger reflects `aria-expanded=\"true\"` and references a content id\n * no element carries, and Escape and outside presses are handled by the mounted surface, so nothing\n * but the trigger can close it again.\n *\n * The check runs in the `read` phase of the render that follows the open, after every content piece\n * that render mounted has registered from its constructor, so a correctly wired `@if` never reports.\n * Closing, or a content piece registering, re-arms it. A surface mounted only after that render, from\n * a `@defer` block inside the `@if`, reports once before it arrives.\n *\n * It is inert on the server, where `afterNextRender` never fires. Must be called from an injection\n * context. A production build creates no effect at all.\n */\nexport function warnIfOpenWithoutContent(config: OpenWithoutContentConfig): void {\n if (typeof ngDevMode !== 'undefined' && !ngDevMode) {\n return;\n }\n\n const injector = inject(Injector);\n let reported = false;\n effect(() => {\n if (!config.open() || config.content() !== null) {\n reported = false;\n return;\n }\n if (reported) {\n return;\n }\n untracked(() => {\n afterNextRender(\n {\n read: () => {\n if (reported || !config.open() || config.content() !== null) {\n return;\n }\n reported = true;\n const condition =\n typeof config.condition === 'function' ? config.condition() : config.condition;\n fortyWarn({\n code: 'FORCDK-CORE-014',\n scope: config.primitive,\n message: `The surface is open, but no ${config.piece} is mounted.`,\n cause:\n 'The trigger already reflects the open state and references a content id no ' +\n 'element carries, and Escape and outside presses are handled by the mounted ' +\n 'surface, so only the trigger can close it again.',\n fix: `Render ${config.piece} inside \\`@if (${condition})\\`, with nothing else gating it. See the ${config.primitive} README.`,\n });\n },\n },\n { injector },\n );\n });\n });\n}\n","import { effect, type Signal } from '@angular/core';\n\n/** The trigger state the dev-mode missing-`[controls]` warning watches, and the warning itself. */\nexport interface UncontrolledTriggerConfig {\n /** The trigger's open state. */\n readonly open: Signal<boolean>;\n /** The id the trigger mirrors to `aria-controls`, or `null` when unset. */\n readonly controls: Signal<string | null>;\n /** Emits the primitive's own `fortyWarn`, so each primitive keeps its own code. */\n readonly warn: () => void;\n}\n\n/**\n * Warns — dev mode only — when a trigger that mirrors `[controls]` to `aria-controls` opens while\n * `controls` is unset, so the missing relationship is visible during development.\n *\n * It warns once per entry into that state: reopening without `controls` stays silent, and setting\n * then clearing it warns again. Must be called from an injection context. A production build\n * creates no effect at all.\n */\nexport function warnIfOpenWithoutControls(config: UncontrolledTriggerConfig): void {\n if (typeof ngDevMode !== 'undefined' && !ngDevMode) {\n return;\n }\n let warned = false;\n effect(() => {\n if (config.controls() !== null) {\n warned = false;\n } else if (config.open() && !warned) {\n warned = true;\n config.warn();\n }\n });\n}\n","import { afterNextRender, ElementRef, inject } from '@angular/core';\nimport { fortyWarn } from 'forty-cdk/core';\n\n/** Identifies the surface and its two naming channels in the dev-mode missing-name warning. */\nexport interface UnnamedDialogConfig {\n /** Entry-point name used in the `[forty-cdk/<primitive>]` prefix (e.g. `'dialog'`). */\n readonly primitive: string;\n /** Selector of the piece carrying the dialog role (e.g. `'[forDialog]'`). */\n readonly piece: string;\n /** Selector of the title piece that names the surface (e.g. `'[forDialogTitle]'`). */\n readonly title: string;\n /**\n * Where the consumer binds `ariaLabel` for this surface, quoted into the fix (e.g.\n * `'[forPopover]'`, whose content reads the root's input).\n */\n readonly ariaLabelOn: string;\n}\n\n/**\n * Warns — dev mode only, once per instance — when a surface carrying the dialog role has no\n * accessible name after its first render: neither an `aria-labelledby` nor a non-empty\n * `aria-label` resolved on its host.\n *\n * The attributes are read from the host inside `afterNextRender`, so a title registered during the\n * first render, a bound `ariaLabel` and a static `aria-label` attribute all count. Must be called\n * from an injection context on the surface's own host. A production build registers no render hook\n * at all, and the check is inert on the server.\n */\nexport function warnIfDialogUnnamed(config: UnnamedDialogConfig): void {\n if (typeof ngDevMode !== 'undefined' && !ngDevMode) {\n return;\n }\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n\n afterNextRender(() => {\n const label = host.getAttribute('aria-label')?.trim() ?? '';\n if (label !== '' || host.hasAttribute('aria-labelledby')) {\n return;\n }\n fortyWarn({\n code: 'FORCDK-CORE-011',\n scope: config.primitive,\n message: `${config.piece} has no accessible name.`,\n cause:\n 'Neither `aria-labelledby` nor a non-empty `aria-label` resolved on its host, so assistive ' +\n 'technology announces the surface as a bare \"dialog\". Automated audits tagged for WCAG ' +\n 'A / AA do not report it.',\n fix: `Render a ${config.title} inside it, or bind \\`ariaLabel\\` on ${config.ariaLabelOn}.`,\n });\n });\n}\n","import {\n ApplicationRef,\n type ComponentRef,\n computed,\n type DestroyableInjector,\n DestroyRef,\n DOCUMENT,\n EnvironmentInjector,\n inject,\n Injector,\n PLATFORM_ID,\n type Provider,\n type ProviderToken,\n type Signal,\n signal,\n untracked,\n} from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\nimport {\n composedClosest,\n composedContains,\n FOR_FIELD_ANCHOR_CONTEXT,\n FOR_FIELD_CONTEXT,\n IdGenerator,\n resolveActiveElement,\n} from 'forty-cdk/core';\nimport { InertSiblingsStack } from '../inert-siblings/inert-siblings';\nimport type { OverlayRef } from './overlay-ref';\n\n/**\n * Minimal shape every overlay entry must satisfy so the shared core can index,\n * render, and tear it down. Per-primitive entries (`ForDialogEntry`,\n * `ForDrawerEntry`) extend this with their own directive-input fields and\n * narrow `ref` to their concrete `For<Primitive>Ref`. The core closes an\n * entry's ref and reads its `isClosed` flag (to tell a still-open parent apart\n * from one being swapped out during return-focus origin resolution), so the\n * base requires just those two members — both reason-agnostic, so the base\n * stays independent of each ref's close-reason union. `returnFocusTarget` is\n * the target threaded to the directive, which the core rewrites when the\n * overlay it points into closes first.\n *\n * Internal core tier — exported from `forty-cdk/core-overlay` for the\n * library's own entry points, with no semver guarantee.\n */\nexport interface OverlayManagerEntry {\n readonly id: string;\n readonly ref: Pick<OverlayRef, 'close' | 'isClosed'>;\n readonly returnFocusTarget?: HTMLElement | null;\n}\n\n/**\n * A rendered overlay's exit-animation surface, registered with the core at\n * attach time so `beginLeave` targets the exact host (and its backdrop) by\n * direct reference instead of re-querying the whole document on every close.\n *\n * `host` is the overlay root — the `[forDialog]` / `[forDrawer]` element the\n * outlet stamps. `backdrop()` reads the currently-registered\n * `[for<Primitive>Backdrop]` element **live at close time** (`null` when none\n * is rendered), preserving the \"read the backdrop when it closes\" semantics a\n * registration-time snapshot would lose.\n *\n * Part of the shared core composition surface; carries no semver guarantees.\n */\nexport interface OverlaySurface {\n readonly host: HTMLElement;\n backdrop(): HTMLElement | null;\n release(returnFocusTarget: HTMLElement | null): void;\n}\n\n/**\n * The reactive surface a manager's outlet component is wired with on first\n * `open()`. Mirrors `ForDialogOutletHost` / `ForDrawerOutletHost`.\n *\n * Internal core tier — exported from `forty-cdk/core-overlay` for the\n * library's own entry points, with no semver guarantee.\n */\nexport interface OverlayManagerOutletHost<TEntry extends OverlayManagerEntry> {\n readonly entries: Signal<readonly TEntry[]>;\n closeAllForDestroy(): void;\n /**\n * Registers a rendered entry's exit-animation surface under its id so\n * `beginLeave` can drive the leave classes by direct reference. Called from\n * the per-row surface-registrar directive's `afterNextRender` (so it also\n * runs for an entry whose mount was deferred to a later render). The core\n * drops the surface when the entry is removed.\n */\n registerSurface(id: string, surface: OverlaySurface): void;\n}\n\n/**\n * The minimal surface a manager's outlet component exposes so the core can\n * wire it on first `open()`. Mirrors `ForDialogOutlet` / `ForDrawerOutlet`.\n *\n * Internal core tier — exported from `forty-cdk/core-overlay` for the\n * library's own entry points, with no semver guarantee.\n */\nexport interface OverlayManagerOutlet<TEntry extends OverlayManagerEntry> {\n init(host: OverlayManagerOutletHost<TEntry>): void;\n}\n\n/**\n * Per-primitive bindings the shared core needs: how to name ids and the\n * exit-animation host / backdrop attributes, and how to create the outlet\n * component that renders the entries.\n *\n * Internal core tier — exported from `forty-cdk/core-overlay` for the\n * library's own entry points, with no semver guarantee.\n */\nexport interface OverlayManagerConfig<TEntry extends OverlayManagerEntry> {\n /**\n * Per-instance id prefix passed to `IdGenerator.next` (e.g.\n * `'for-dialog-instance'`).\n */\n readonly idPrefix: string;\n /**\n * Attribute the overlay root + backdrop reflect their per-instance id on\n * (e.g. `'data-for-dialog-id'`), read during return-focus origin resolution.\n */\n readonly idAttribute: string;\n /**\n * Attribute marking the portaled backdrop element (e.g.\n * `'data-for-dialog-backdrop'`), used to exclude the backdrop during\n * return-focus origin resolution.\n */\n readonly backdropAttribute: string;\n /** Creates the manager-owned outlet component (e.g. `ForDialogOutlet`). */\n createOutlet(\n environmentInjector: EnvironmentInjector,\n ): ComponentRef<OverlayManagerOutlet<TEntry>>;\n}\n\n/**\n * Shared imperative-overlay engine behind `ForDialogManager` and\n * `ForDrawerManager`. Owns the entries signal, the reactive `openCount`, the\n * lazily-created outlet, the public `closeAll()` and the destroy-time close-all\n * sweep, the exit-animation `beginLeave` driver, and the parent-cached\n * per-component `Injector` factory.\n *\n * In the browser the outlet host is appended to `document.body` before its\n * first render, as a `display: contents` modal peer, so opened content is\n * connected (and never under an `inert` ancestor) from its first render on\n * rather than only once its row is portaled.\n * The two managers differ only in their entry shape and directive-input\n * mapping; everything structural lives here once.\n *\n * Internal core tier — no semver guarantee; the public surface is\n * `ForDialogManager` / `ForDrawerManager`.\n */\nexport class OverlayManagerCore<TEntry extends OverlayManagerEntry> {\n readonly #appRef = inject(ApplicationRef);\n readonly #envInjector = inject(EnvironmentInjector);\n readonly #document = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n readonly #inertStack = inject(InertSiblingsStack);\n private readonly idGen = inject(IdGenerator);\n\n readonly #entries = signal<readonly TEntry[]>([]);\n readonly #surfaces = new Map<string, OverlaySurface>();\n readonly #config: OverlayManagerConfig<TEntry>;\n\n /**\n * Reactive count of the overlays this manager has open. A closed overlay stops counting once its\n * exit animation finishes.\n */\n readonly openCount = computed(() => this.#entries().length);\n\n #outletRef: ComponentRef<OverlayManagerOutlet<TEntry>> | null = null;\n #destroying = false;\n #lastReturnFocusOrigin: HTMLElement | null = null;\n #pendingRemovals = 0;\n\n constructor(config: OverlayManagerConfig<TEntry>) {\n this.#config = config;\n }\n\n /**\n * Resolves the element focus should return to when the overlay this `open()`\n * is about to register later closes — the \"true origin\". Threaded to the\n * directive's `returnFocusTarget` so `injectModalShell` restores focus there\n * instead of to whatever it happened to capture at construction (which breaks\n * on a close→open swap, where the incoming surface is built while focus still\n * lives inside the outgoing, doomed one).\n *\n * Read the currently-focused element **synchronously at `open()` time**,\n * before the render tick mounts the new overlay and swaps the DOM, and\n * classify it:\n *\n * - **Genuine outside element** (focus is on the trigger, not inside any\n * managed overlay host) → that element is the origin.\n * - **Inside a still-live managed overlay** (a stacked open on top of an open\n * overlay, or an open→close swap) → the focused element itself. Should that\n * overlay close first, `beginLeave` hands its own origin to this entry.\n * - **Inside an overlay that is closing / already gone** (a close→open swap:\n * its ref is closed, or it has left the entries list but its DOM host is\n * still mounted for this tick) → inherit the chain's origin.\n * - **No usable focus** (`<body>` / `documentElement` / none) → inherit the\n * chain's origin too.\n *\n * The chain's origin is inherited only while the chain is alive (some\n * overlay is still registered, or one was removed in the current task) and\n * only while it is still in the document; otherwise the result is `null`.\n *\n * `explicit` is the caller's `returnFocusTarget`, returned as is when it is\n * not `undefined`. An explicit element still becomes the chain's origin, so\n * a swap out of that overlay inherits it.\n *\n * Both halves of the resolution read the composed tree: the capture\n * descends through open shadow roots, so a trigger inside one is the origin\n * rather than its (usually unfocusable) host, and the \"am I inside a managed\n * overlay?\" walk climbs back out of them. The two go together — resolving the\n * deep element while classifying it with a plain `closest` would report every\n * shadow-nested trigger as an outside element.\n */\n protected resolveReturnFocusTarget(explicit?: HTMLElement | null): HTMLElement | null {\n const active = resolveActiveElement(this.#document);\n const captured = active instanceof HTMLElement ? active : null;\n const resolved = untracked(() => this.#computeReturnFocusOrigin(captured));\n this.#lastReturnFocusOrigin = explicit ?? resolved;\n return explicit === undefined ? resolved : explicit;\n }\n\n #computeReturnFocusOrigin(captured: HTMLElement | null): HTMLElement | null {\n const { body, documentElement } = this.#document;\n if (captured === null || captured === body || captured === documentElement) {\n return this.#chainOrigin();\n }\n const { idAttribute, backdropAttribute } = this.#config;\n const host = composedClosest(captured, `[${idAttribute}]:not([${backdropAttribute}])`);\n if (host === null) {\n return captured;\n }\n const hostId = host.getAttribute(idAttribute);\n const parentStillOpen = this.#entries().some(\n (entry) => entry.id === hostId && !entry.ref.isClosed(),\n );\n return parentStillOpen ? captured : this.#chainOrigin();\n }\n\n #chainOrigin(): HTMLElement | null {\n const origin = this.#lastReturnFocusOrigin;\n if (origin !== null && !origin.isConnected) {\n this.#lastReturnFocusOrigin = null;\n return null;\n }\n return this.#entries().length > 0 || this.#pendingRemovals > 0 ? origin : null;\n }\n\n #handOffReturnFocus(id: string): void {\n const entries = this.#entries();\n const closing = entries.find((entry) => entry.id === id);\n if (closing === undefined) {\n return;\n }\n const origin = closing.returnFocusTarget ?? null;\n const host = this.#surfaces.get(id)?.host ?? null;\n const inside = (target: HTMLElement | null | undefined): boolean =>\n host !== null && target != null && composedContains(host, target);\n if (origin !== null || inside(this.#lastReturnFocusOrigin)) {\n this.#lastReturnFocusOrigin = origin;\n }\n if (host === null) {\n return;\n }\n let handedOff = false;\n const next = entries.map((entry) => {\n if (entry.id === id || !inside(entry.returnFocusTarget)) {\n return entry;\n }\n handedOff = true;\n return { ...entry, returnFocusTarget: origin };\n });\n if (handedOff) {\n this.#entries.set(next);\n }\n }\n\n #releaseChainAfterTask(): void {\n if (this.#destroying || !this.#isBrowser) {\n if (this.#entries().length === 0) {\n this.#lastReturnFocusOrigin = null;\n }\n return;\n }\n this.#pendingRemovals += 1;\n setTimeout(() => {\n this.#pendingRemovals -= 1;\n if (this.#pendingRemovals === 0 && this.#entries().length === 0) {\n this.#lastReturnFocusOrigin = null;\n }\n }, 0);\n }\n\n /**\n * Generates the next per-instance id and a paired idempotent\n * `remove` that drops the entry. The caller builds the `ref` with a teardown\n * that drives the exit animation before invoking `remove`.\n */\n protected nextId(): { id: string; remove: () => void } {\n const id = this.idGen.next(this.#config.idPrefix);\n let removed = false;\n const remove = (): void => {\n if (removed) {\n return;\n }\n removed = true;\n this.#surfaces.delete(id);\n this.#entries.update((arr) => arr.filter((e) => e.id !== id));\n untracked(() => this.#releaseChainAfterTask());\n };\n return { id, remove };\n }\n\n #releaseSurface(id: string): void {\n const entry = this.#entries().find((candidate) => candidate.id === id);\n this.#surfaces.get(id)?.release(entry?.returnFocusTarget ?? null);\n }\n\n /**\n * Hands the closing entry's return-focus origin on (see\n * `resolveReturnFocusTarget`) and releases its surface, so the overlay stops\n * being modal and returns focus at close intent. Then drives the exit\n * animation on the overlay root and, in lockstep,\n * on the portaled backdrop (both resolved from the `OverlaySurface` stored at\n * attach time — the backdrop's template `animate.leave` never fires under the\n * manager's `ngComponentOutlet` mount), then calls `remove`. Runs `remove`\n * immediately when destroying, when `requestAnimationFrame` is unavailable,\n * when no surface was registered (nothing rendered), or when there is nothing\n * to animate.\n */\n protected beginLeave(\n id: string,\n leaveClass: string | undefined,\n backdropLeaveClass: string | undefined,\n remove: () => void,\n ): void {\n if (!this.#destroying) {\n untracked(() => {\n this.#handOffReturnFocus(id);\n this.#releaseSurface(id);\n });\n }\n if (this.#destroying || typeof requestAnimationFrame === 'undefined') {\n remove();\n return;\n }\n const surface = this.#surfaces.get(id);\n const targets: HTMLElement[] = [];\n if (surface && leaveClass && typeof surface.host.getAnimations === 'function') {\n surface.host.classList.add(leaveClass);\n targets.push(surface.host);\n }\n if (surface && backdropLeaveClass) {\n const backdrop = surface.backdrop();\n if (backdrop && typeof backdrop.getAnimations === 'function') {\n backdrop.classList.add(backdropLeaveClass);\n targets.push(backdrop);\n }\n }\n if (targets.length === 0) {\n remove();\n return;\n }\n requestAnimationFrame(() => {\n const finite = targets\n .flatMap((el) => el.getAnimations({ subtree: true }))\n .filter(isFiniteAnimation);\n if (finite.length === 0) {\n remove();\n return;\n }\n Promise.all(finite.map((animation) => animation.finished.catch(() => undefined))).then(() =>\n remove(),\n );\n });\n }\n\n /**\n * Builds a parent-cached per-component `Injector`. The returned\n * factory recreates the injector only when its parent changes, so re-renders\n * with the same enclosing `[forDialog]` / `[forDrawer]` host reuse it.\n *\n * With no `scope`, the opened component's injector is parented on the\n * declarative host's element injector (`parent`), matching the declarative\n * path. When the caller passed an `injector` on the `open()` config, `scope`\n * re-parents the opened component on that caller scope instead — so DI inside\n * the opened component resolves the scope's providers (a lazy route, a\n * component `providers`). The host's `contextToken` and the field-boundary\n * tokens are copied across as value providers so the primitive's own pieces\n * still resolve `FOR_<PRIMITIVE>_CONTEXT`, and a control in the opened\n * component stays cut off from the caller's `[forField]`, exactly as on the\n * declarative path.\n *\n * Each injector it creates is destroyed when the view owning `parent` is\n * destroyed, after the opened component it served, or when a new parent\n * replaces it, so the services passed in `providers` run their teardown.\n */\n protected createInjectorFactory(\n providers: readonly Provider[],\n scope?: { readonly injector: Injector; readonly contextToken: ProviderToken<unknown> },\n ): (parent: Injector) => Injector {\n let cached: {\n readonly parent: Injector;\n readonly injector: Injector;\n readonly release: () => void;\n } | null = null;\n return (parent: Injector): Injector => {\n if (cached?.parent === parent) {\n return cached.injector;\n }\n cached?.release();\n const injector = scope\n ? Injector.create({\n parent: scope.injector,\n providers: [\n ...[scope.contextToken, ...FIELD_BOUNDARY_TOKENS].map((token) => ({\n provide: token,\n useValue: parent.get(token),\n })),\n ...providers,\n ],\n })\n : Injector.create({ parent, providers: [...providers] });\n cached = { parent, injector, release: bindInjectorLifetime(injector, parent) };\n return injector;\n };\n }\n\n /**\n * Registers a fully-built entry, ensures the outlet exists, and requests a\n * render so the `@for` mounts it.\n *\n * The render is attempted synchronously via `ApplicationRef.tick()` so the\n * overlay DOM is available the moment `open()` returns — the common case.\n * When `open()` is itself called from within change detection (an `effect`,\n * `ngOnInit`, or an `afterNextRender` callback) a tick is already in flight\n * and a nested `tick()` is illegal (NG0101); the synchronous attempt is then\n * skipped and the `#entries` signal write drives the mount on the next\n * scheduled render instead. The entry is registered immediately either way,\n * so the returned overlay ref is usable straight away.\n */\n protected register(entry: TEntry): void {\n this.#ensureOutlet();\n this.#entries.update((arr) => [...arr, entry]);\n this.#renderNow();\n }\n\n #renderNow(): void {\n try {\n this.#appRef.tick();\n } catch (error: unknown) {\n if (isRecursiveTickError(error)) {\n return;\n }\n throw error;\n }\n }\n\n /**\n * Closes every overlay this manager has open, topmost first, with reason `'programmatic'` and\n * `result` as each close result. Each ref's `closed` resolves as it does for `ref.close()`, exit\n * animations still play, and focus ends where the bottom overlay's return focus sends it. A no-op\n * when nothing is open.\n */\n closeAll(result?: unknown): void {\n for (const entry of [...this.#entries()].reverse()) {\n entry.ref.close(result);\n }\n }\n\n #closeAllForDestroy(): void {\n this.#destroying = true;\n for (const entry of this.#entries()) {\n entry.ref.close();\n }\n }\n\n #ensureOutlet(): void {\n if (this.#outletRef) {\n return;\n }\n const outletRef = this.#config.createOutlet(this.#envInjector);\n this.#appRef.attachView(outletRef.hostView);\n if (this.#isBrowser) {\n const outletHost = outletRef.location.nativeElement as HTMLElement;\n outletHost.style.display = 'contents';\n const releasePeer = this.#inertStack.registerPeer(outletHost, 'always');\n this.#document.body.appendChild(outletHost);\n outletRef.onDestroy(() => {\n releasePeer();\n outletHost.remove();\n });\n }\n outletRef.instance.init({\n entries: this.#entries.asReadonly(),\n closeAllForDestroy: () => this.#closeAllForDestroy(),\n registerSurface: (id, surface) => {\n this.#surfaces.set(id, surface);\n },\n });\n this.#outletRef = outletRef;\n }\n}\n\nconst FIELD_BOUNDARY_TOKENS: readonly ProviderToken<unknown>[] = [\n FOR_FIELD_CONTEXT,\n FOR_FIELD_ANCHOR_CONTEXT,\n];\n\n/**\n * Destroys `injector` when the scope `parent` belongs to is destroyed, and\n * returns a release that destroys it early and drops that hook. Either path\n * destroys it once.\n */\nfunction bindInjectorLifetime(injector: DestroyableInjector, parent: Injector): () => void {\n let destroyed = false;\n const destroy = (): void => {\n if (!destroyed) {\n destroyed = true;\n injector.destroy();\n }\n };\n const unregister = parent.get(DestroyRef).onDestroy(destroy);\n return () => {\n unregister();\n destroy();\n };\n}\n\n/**\n * True when `error` is Angular's recursive-`ApplicationRef.tick()` runtime\n * error (`NG0101`), thrown when a change-detection tick is already in flight.\n * Matched by the stable numeric `RuntimeError.code` with a message-prefix\n * fallback so it survives production builds where the message text is stripped.\n */\nfunction isRecursiveTickError(error: unknown): boolean {\n if (error === null || typeof error !== 'object') {\n return false;\n }\n const { code, message } = error as { code?: unknown; message?: unknown };\n return code === 101 || (typeof message === 'string' && message.startsWith('NG0101'));\n}\n\n/**\n * True when `animation` will actually finish — i.e. it does not run forever.\n * An infinite exit animation (a shimmer / pulse with `animation-iteration-count:\n * infinite`) reports `Infinity` iterations, and its `finished` promise never\n * resolves; awaiting it would strand `beginLeave` and leak the overlay entry.\n * Filtering these out before awaiting `finished` lets teardown proceed once the\n * finite animations settle (or immediately, when none remain). Guards for a\n * possibly-null effect and for environments lacking `getComputedTiming`.\n */\nfunction isFiniteAnimation(animation: Animation): boolean {\n const effect = animation.effect;\n if (!effect || typeof effect.getComputedTiming !== 'function') {\n return true;\n }\n return effect.getComputedTiming().iterations !== Infinity;\n}\n","import { signal } from '@angular/core';\n\n/**\n * The awaitable close payload resolved by `OverlayRef.closed` — the reason the\n * overlay closed plus the optional close result. Homogeneous with\n * `ForToastRef.closed` so all three programmatic overlay handles expose the\n * same `{ reason, result }` shape.\n *\n * Internal core tier — exported from `forty-cdk/core-overlay` for the\n * library's own entry points, with no semver guarantee.\n */\nexport interface OverlayCloseEvent<R, Reason> {\n /** Why the overlay closed (e.g. `'escape'`, `'closeButton'`, `'programmatic'`). */\n readonly reason: Reason;\n /** The close result passed to `close(result)`, or `undefined`. */\n readonly result: R | undefined;\n}\n\n/**\n * Shared handle returned by an imperative overlay manager's `open()`.\n * `ForDialogRef` / `ForDrawerRef` extend this verbatim to keep their public\n * class identity (and DI token) while the close engine lives here once.\n *\n * Both reactive (`isClosed`, `result`) and awaitable (`closed`) APIs are\n * exposed — pick what fits the call site. `R` is the close-result type and\n * `Reason` the close-reason union (`ForDialogCloseReason` /\n * `ForDrawerCloseReason`).\n *\n * Internal core tier — no semver guarantee; the public surface is\n * `ForDialogRef` / `ForDrawerRef`.\n */\nexport class OverlayRef<R = unknown, Reason = string> {\n readonly #result = signal<R | undefined>(undefined);\n readonly #closed = signal(false);\n\n /** Reactive: `true` once `close()` has been called. */\n readonly isClosed = this.#closed.asReadonly();\n\n /** Reactive: the close result. `undefined` while open. */\n readonly result = this.#result.asReadonly();\n\n /**\n * Awaitable: resolves with `{ reason, result }` the first time `close()`\n * runs. The reason distinguishes an explicit `close(result)` (the manager's\n * default reason, `'programmatic'`) from a dismiss channel (Escape, backdrop,\n * outside-pointer, close button), which a bare result cannot.\n */\n readonly closed: Promise<OverlayCloseEvent<R, Reason>>;\n\n #resolveClosed!: (event: OverlayCloseEvent<R, Reason>) => void;\n readonly #teardown: () => void;\n readonly #defaultReason: Reason;\n\n /** Internal composition surface (no semver guarantees). */\n constructor(teardown: () => void, defaultReason: Reason) {\n this.#teardown = teardown;\n this.#defaultReason = defaultReason;\n this.closed = new Promise((resolve) => {\n this.#resolveClosed = resolve;\n });\n }\n\n /**\n * Close the overlay, optionally returning a result. Idempotent — calling\n * twice is a no-op. `reason` defaults to the manager's default (`'programmatic'`\n * for a direct imperative close); the dismiss channels pass their own reason.\n */\n close(result?: R, reason: Reason = this.#defaultReason): void {\n if (this.#closed()) {\n return;\n }\n this.#result.set(result);\n this.#closed.set(true);\n this.#resolveClosed({ reason, result });\n this.#teardown();\n }\n}\n"],"mappings":";;;;AA+CA,IAAa,iBAAb,MAAa,eAAc;CAChB,YAAY,OAAO,QAAQ;CAC3B,UAAU,KAAK,UAAU;CACzB,aAAa,kBAAkB,OAAO,WAAW,CAAC;CAElD,2BAAW,IAAI,IAAG;CAU3B,KAAK,SAAsB,KAAK,UAAU,MAAI;EAC5C,IAAI,CAAC,KAAK,YACR;EAEF,IAAI,SAAS,KAAK,SAAS,IAAI,MAAM;EACrC,IAAI,CAAC,QAAQ;GACX,SAAS;IAAE,OAAO;IAAG,mBAAmB;IAAO,mBAAmB;GAAK;GACvE,KAAK,SAAS,IAAI,QAAQ,MAAM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A;CAGT,YAAY,UAAsB,eAAqB;EACrD,KAAK,YAAY;EACjB,KAAK,iBAAiB;EACtB,KAAK,SAAS,IAAI,SAAS,YAAW;GACpC,KAAK,iBAAiB;EACxB,CAAC;CACH;CAOA,MAAM,QAAY,SAAiB,KAAK,gBAAc;EACpD,IAAI,KAAK,QAAO,GACd;EAEF,KAAK,QAAQ,IAAI,MAAM;EACvB,KAAK,QAAQ,IAAI,IAAI;EACrB,KAAK,eAAe;GAAE;GAAQ;EAAM,CAAE;EACtC,KAAK,UAAS;CAChB;AACD"}
1
+ {"version":3,"file":"forty-cdk-core-overlay.mjs","names":[],"sources":["../../../projects/forty-cdk/core-overlay/src/body-scroll-lock/body-scroll-lock.ts","../../../projects/forty-cdk/core-overlay/src/dismissible-layer/dismissible-layer.ts","../../../projects/forty-cdk/core-overlay/src/dismissible-layer/outside-veto.ts","../../../projects/forty-cdk/core-overlay/src/drawer-stack/drawer-stack.ts","../../../projects/forty-cdk/core-overlay/src/debounced-action/debounced-action.ts","../../../projects/forty-cdk/core-overlay/src/inert-siblings/modal-peer-registry.ts","../../../projects/forty-cdk/core-overlay/src/inert-siblings/inert-siblings.ts","../../../projects/forty-cdk/core-overlay/src/modal-shell/modal-activation-order.ts","../../../projects/forty-cdk/core-overlay/src/modal-shell/modal-backdrop.ts","../../../projects/forty-cdk/core-overlay/src/modal-shell/modal-shell.ts","../../../projects/forty-cdk/core-overlay/src/modal-shell/modal-trigger.ts","../../../projects/forty-cdk/core-overlay/src/modal-shell/modal-surface-base.ts","../../../projects/forty-cdk/core-overlay/src/overlay-warnings/mounted-while-closed.ts","../../../projects/forty-cdk/core-overlay/src/overlay-warnings/open-without-content.ts","../../../projects/forty-cdk/core-overlay/src/overlay-warnings/uncontrolled-trigger.ts","../../../projects/forty-cdk/core-overlay/src/overlay-warnings/unnamed-dialog.ts","../../../projects/forty-cdk/core-overlay/src/overlay-manager/overlay-manager.ts","../../../projects/forty-cdk/core-overlay/src/overlay-manager/overlay-ref.ts"],"sourcesContent":["import { DOCUMENT, Injectable, PLATFORM_ID, inject } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\n/**\n * Refcounted scroll lock, keyed per target element (default `<body>`).\n * Multiple modal surfaces acquire and release locks independently — only the\n * first acquire for a given target mutates that target, only the last release\n * un-mutates it. Different targets (body vs a container element) are fully\n * independent: locking a container does not affect body scroll and vice versa.\n *\n * **Semantic: clear, do not restore.** On the first lock for a target the\n * service writes `overflow: hidden` and an optional scrollbar-compensating\n * `padding-right` inline on that target. On the final unlock it _clears_ the\n * inline styles it set (`target.style.overflow = ''`, and\n * `target.style.paddingRight = ''` only when this lock actually wrote it) and\n * lets the CSS cascade take over again. It does NOT snapshot the values at\n * lock time and rewrite them at unlock time.\n *\n * Why: any code (route transition, theme toggle, the consumer themselves)\n * that mutates `target.style.overflow` between `lock()` and the final\n * `unlock()` would otherwise be silently clobbered when we restored the\n * stale snapshot. Clearing on unlock means the lock owns the inline style\n * only while it exists; intervening mutations win, and the resting state\n * is whatever stylesheet rules apply.\n *\n * **The page lock reaches the viewport.** Body overflow scrolls the viewport\n * only while `<html>` declares none of its own, so when `<html>` computes a\n * scrollable overflow (`html { overflow-y: scroll }`) the body lock also\n * writes `overflow: hidden` on `<html>`, and clears it on the final unlock\n * under the same contract.\n *\n * **Compensation is measured, not assumed.** The lock reads the width of the\n * scrolling box (`documentElement.clientWidth` for the body path, the\n * target's own `clientWidth` for an element) before and after writing\n * `overflow: hidden`, and pads the target by exactly the width the hidden\n * scrollbar gave back. Borders never count. When nothing is given back (an\n * overlay-scrollbar platform, a page that does not overflow), or when\n * `scrollbar-gutter: stable` keeps the space reserved, no `padding-right` is\n * written, so a consumer's unrelated inline `padding-right` survives the\n * lock. A container whose width is fixed under `box-sizing: content-box`\n * grows by the compensation rather than absorbing it.\n *\n * SSR: the service is `providedIn: 'root'` so its counter map is scoped to a\n * single Angular bootstrap (one per SSR request). Server-side calls are\n * no-ops.\n */\n@Injectable({ providedIn: 'root' })\nexport class BodyScrollLock {\n readonly #document = inject(DOCUMENT);\n readonly #window = this.#document.defaultView;\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n\n readonly #targets = new Map<\n HTMLElement,\n { count: number; wrotePaddingRight: boolean; wroteRootOverflow: boolean }\n >();\n\n /**\n * Acquire the scroll lock on `target` (default `document.body`). The first\n * call for a given target sets `overflow: hidden` and compensates for the\n * scrollbar width; subsequent calls increment the refcount only.\n */\n lock(target: HTMLElement = this.#document.body): void {\n if (!this.#isBrowser) {\n return;\n }\n let record = this.#targets.get(target);\n if (!record) {\n record = { count: 0, wrotePaddingRight: false, wroteRootOverflow: false };\n this.#targets.set(target, record);\n }\n if (record.count === 0) {\n const root = this.#document.documentElement;\n const isBody = target === this.#document.body;\n const scroller = isBody ? root : target;\n const win = this.#window;\n const widthBefore = scroller.clientWidth;\n const paddingRight = win ? parseFloat(win.getComputedStyle(target).paddingRight) || 0 : 0;\n const lockRoot = isBody && win !== null && this.#scrollsViewport(win, root);\n const gutterIsStable =\n win !== null && this.#gutterIsStable(win, isBody ? [root, target] : [target]);\n\n target.style.overflow = 'hidden';\n if (lockRoot) {\n root.style.overflow = 'hidden';\n record.wroteRootOverflow = true;\n }\n\n const scrollbarWidth = scroller.clientWidth - widthBefore;\n if (scrollbarWidth > 0 && !gutterIsStable) {\n target.style.paddingRight = `${paddingRight + scrollbarWidth}px`;\n record.wrotePaddingRight = true;\n }\n }\n record.count++;\n }\n\n /**\n * Release the scroll lock on `target` (default `document.body`). The last\n * release clears the inline `overflow` (and `padding-right` if written) and\n * lets the CSS cascade take over.\n */\n unlock(target: HTMLElement = this.#document.body): void {\n if (!this.#isBrowser) {\n return;\n }\n const record = this.#targets.get(target);\n if (!record || record.count === 0) {\n return;\n }\n record.count--;\n if (record.count === 0) {\n target.style.overflow = '';\n if (record.wroteRootOverflow) {\n this.#document.documentElement.style.overflow = '';\n }\n if (record.wrotePaddingRight) {\n target.style.paddingRight = '';\n }\n this.#targets.delete(target);\n }\n }\n\n /**\n * True when any of the given elements reserves the scrollbar gutter via\n * `scrollbar-gutter: stable` (or `stable both-edges`). The gutter then\n * survives the `overflow: hidden` toggle, so no padding compensation is\n * needed, even though `clientWidth` reports the reserved space as freed.\n */\n #gutterIsStable(win: Window, els: readonly HTMLElement[]): boolean {\n for (const el of els) {\n const gutter = win.getComputedStyle(el).getPropertyValue('scrollbar-gutter');\n if (gutter.trim().split(/\\s+/).includes('stable')) {\n return true;\n }\n }\n return false;\n }\n\n #scrollsViewport(win: Window, root: HTMLElement): boolean {\n const style = win.getComputedStyle(root);\n return [style.overflowX, style.overflowY].some(\n (value) => value === 'auto' || value === 'scroll',\n );\n }\n}\n","import { DOCUMENT, DestroyRef, ElementRef, Injectable, PLATFORM_ID, inject } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\nimport {\n composedContains,\n EscapeArbiter,\n isImeComposing,\n resolveActiveElement,\n resolveEventTarget,\n} from 'forty-cdk/core';\n\n/**\n * The outside-interaction channels a {@link DismissibleLayer} can own. A layer\n * declares the channels it wants routed to it at {@link DismissibleLayer.activate};\n * {@link DismissibleLayerStack} dispatches an outside `pointerdown` / `focusin`\n * to the topmost layer that declared the matching channel. Escape is not a\n * channel — it is dispatched to the topmost active layer, and to a layer below\n * only while every layer above it declines the key (see\n * {@link DismissibleLayerActivateOptions.onEscapeKeyDown}).\n */\nexport type DismissibleLayerChannel = 'pointer' | 'focus';\n\n/**\n * Declared nesting position of a layer inside a chain of layers that are\n * structurally nested (a menubar menu and its submenus, a submenu and its own\n * submenu). {@link DismissibleLayerStack} orders such a chain by `depth` rather\n * than by activation order, so a deeper level is always dispatched to before\n * its ancestors even when both levels mount in the same render pass and the\n * `afterNextRender` callbacks fire child-before-parent.\n *\n * A layer that declares no nesting keeps the plain LIFO behaviour: it is pushed\n * on top of everything, and never reorders relative to a chain it does not\n * belong to (a Dialog opened from inside a submenu still lands topmost).\n */\nexport interface DismissibleLayerNesting {\n /**\n * Identity of the chain this layer belongs to — typically the coordination\n * context of the outermost level. Only layers sharing a chain are ordered\n * against each other by `depth`.\n */\n readonly chain: object;\n /** `0` for the outermost level, `+1` per nesting level below it. */\n readonly depth: number;\n}\n\n/**\n * Options passed to `DismissibleLayer.activate`. Each handler receives the\n * native event; the consumer owns the close decision inside its own handler\n * (there is no separate default-dismiss callback).\n */\nexport interface DismissibleLayerActivateOptions {\n /**\n * The outside-interaction channels this layer owns. The stack routes an\n * outside `pointerdown` to the topmost layer declaring `'pointer'` and an\n * outside `focusin` to the topmost layer declaring `'focus'`, so an\n * Escape-only surface (Tooltip, HoverCard) declares `[]` and stays\n * transparent to the real dismissible layers beneath it. Escape is dispatched\n * from the topmost layer down regardless of this declaration.\n */\n channels: readonly DismissibleLayerChannel[];\n\n /**\n * Declared position of this layer inside a chain of structurally nested\n * layers. When present, {@link DismissibleLayerStack} inserts the layer by\n * depth within its chain instead of pushing it on top, so the stack order\n * reflects the nesting rather than the order the levels happened to activate\n * in. Omit for a standalone overlay.\n */\n nesting?: DismissibleLayerNesting;\n\n /**\n * The element the surface was opened from. A layer whose anchor lies inside\n * another layer, or inside a layer stacked above that one, counts as nested\n * in it (see {@link DismissibleLayer.hasNestedLayer}).\n */\n anchor?: Element;\n\n /**\n * Fired when a layer nested in this one is removed from the stack, after the\n * removal.\n */\n onNestedLayerRemoved?: () => void;\n\n /**\n * Fired when the user presses `Escape` while this is the topmost layer, or while every layer\n * stacked above it declined the key. Return `false` to decline it too: the key is then offered\n * to the layer below, unless this layer is\n * {@link DismissibleLayerActivateOptions.modal | modal}. Any other return value keeps it.\n */\n onEscapeKeyDown?: (event: KeyboardEvent) => unknown;\n\n /**\n * Fired when the user pointer-downs outside this layer's host. Return `true` when the handler\n * closed the layer: only then is the press offered to the pointer layer below, and only when that\n * layer opted in through {@link DismissibleLayerActivateOptions.cascadeOutsidePress}.\n */\n onPointerDownOutside?: (event: PointerEvent) => unknown;\n\n /**\n * Fired when the user pointer-downs **inside** this layer's host or one of its `exemptElements`\n * — the mirror of `onPointerDownOutside`.\n *\n * It answers \"was that press mine?\" with the same containment rule the dismissal path uses,\n * instead of the owner re-deriving the surface set from its own host listeners.\n */\n onPointerDownInside?: (event: PointerEvent) => void;\n\n /**\n * Fired when focus moves outside this layer's host. That includes focus moving into an\n * `<iframe>` outside it, which the host document observes only as its window losing focus:\n * `event` is then the window's `blur`.\n */\n onFocusOutside?: (event: FocusEvent) => void;\n\n /**\n * Fired in addition to `onPointerDownOutside` / `onFocusOutside` for\n * consumers that don't care which one occurred.\n */\n onInteractOutside?: (event: PointerEvent | FocusEvent) => void;\n\n /**\n * Extra elements whose subtrees count as \"inside\" for outside-pointer /\n * outside-focus checks (e.g. a portaled popover content owned by this\n * layer). Recomputed on every event so that DOM mutations are picked up,\n * and handed the node being tested so an owner can leave part of an exempt\n * subtree outside.\n */\n exemptElements?: (target: Node) => readonly Element[];\n\n /**\n * Whether this layer also closes on an outside press that the pointer layer directly above it\n * closed on. Read on every press. Without it, an outside press reaches only the topmost pointer\n * layer.\n *\n * The cascade walks down one pointer layer at a time and stops at the first layer that contains\n * the press, keeps itself open, did not opt in, or is\n * {@link DismissibleLayerActivateOptions.modal | modal}.\n */\n cascadeOutsidePress?: () => boolean;\n\n /**\n * Whether this layer is a modal surface. A modal layer ends an outside-press cascade: a press it\n * receives is never offered to the layers beneath it.\n */\n modal?: boolean;\n}\n\nconst EMPTY_ACTIVATE_OPTIONS: DismissibleLayerActivateOptions = { channels: [] };\n\n/**\n * Application-scoped registry that owns the document listeners used by\n * dismissible layers. Created once per Angular bootstrap (one per SSR\n * request), tied to the root injector lifetime.\n *\n * Listeners are installed on the first layer activation and removed with the last, and a\n * `DestroyRef` hook clears both the listeners and the stack, so no bootstrap leaves listeners\n * behind. Installation is a no-op off-browser.\n *\n * **Stack order** is activation order for standalone layers, but a layer declaring a\n * {@link DismissibleLayerNesting} is inserted by nesting depth within its chain. Activation order\n * is a render-timing artifact — a menu and its submenu mounted in one pass run their\n * `afterNextRender` callbacks child-before-parent — so ordering by timing would place an ancestor\n * above its own descendant, making the descendant's first focus read as `focusOutside` and collapse\n * the chain.\n *\n * **Listener phases are asymmetric.** `pointerdown` and `focusin` register on the\n * capture phase, so an outside interaction is detected even when overlay content stops\n * propagation. `keydown` registers on the bubble phase instead, because the per-overlay Escape\n * handlers call `stopPropagation()` after closing — which is what keeps one Escape from closing an\n * ancestor layer too. The accepted trade-off is that overlay content with its own bubble-phase\n * `keydown` handler calling `stopPropagation()` can swallow Escape before it arrives.\n *\n * An Escape that belongs to an IME composition (see `isImeComposing`) is never dispatched: it\n * cancels the conversion, not the topmost layer.\n *\n * **A press inside an `<iframe>` reaches no document listener**: it is dispatched in the frame's\n * own document, and engines do not consistently fire `focusin` on the `<iframe>` element either.\n * What the host document does observe is its window's `blur` with the frame as the active element,\n * resolved through open shadow roots, so the stack also listens for that and dispatches it on the\n * `'focus'` channel as focus moving to the frame — once, even in an engine that also reports the\n * frame's `focusin`.\n */\n@Injectable({ providedIn: 'root' })\nexport class DismissibleLayerStack {\n readonly #document = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n\n readonly #stack: DismissibleLayer[] = [];\n #suppressDepth = 0;\n #listening = false;\n #lastFocusInTarget: EventTarget | null = null;\n\n readonly #onKeyDown = (event: KeyboardEvent): void => {\n if (event.key !== 'Escape' || isImeComposing(event)) {\n return;\n }\n if (event.defaultPrevented) {\n return;\n }\n if (this.#suppressDepth > 0) {\n return;\n }\n for (const layer of [...this.#stack].reverse()) {\n if (layer.isActive && (layer.handleEscape(event) || layer.isModal)) {\n return;\n }\n }\n };\n readonly #onPointerDown = (event: Event): void => {\n if (this.#suppressDepth > 0) {\n return;\n }\n const [topmost, ...below] = this.#layersForChannel('pointer');\n if (!topmost?.handlePointerDown(event as PointerEvent) || topmost.isModal) {\n return;\n }\n for (const layer of below) {\n if (!layer.isActive || !layer.cascadesOutsidePress()) {\n return;\n }\n if (!layer.handlePointerDown(event as PointerEvent) || layer.isModal) {\n return;\n }\n }\n };\n readonly #onFocusIn = (event: Event): void => {\n this.#lastFocusInTarget = resolveEventTarget(event);\n if (this.#suppressDepth > 0) {\n return;\n }\n this.#topmostForChannel('focus')?.handleFocusIn(event as FocusEvent);\n };\n readonly #onWindowBlur = (event: FocusEvent): void => {\n if (this.#suppressDepth > 0) {\n return;\n }\n const frame = resolveActiveElement(this.#document);\n if (!(frame instanceof HTMLIFrameElement) || frame === this.#lastFocusInTarget) {\n return;\n }\n this.#lastFocusInTarget = frame;\n this.#topmostForChannel('focus')?.handleFocusIn(event, frame);\n };\n\n constructor() {\n const unregisterEscapeQuery = inject(EscapeArbiter).register((node) =>\n this.#hasEscapeLayerAbove(node),\n );\n inject(DestroyRef).onDestroy(() => {\n unregisterEscapeQuery();\n this.#removeListeners();\n this.#stack.length = 0;\n this.#suppressDepth = 0;\n });\n }\n\n /** @internal */\n push(layer: DismissibleLayer): void {\n this.#stack.splice(this.#insertionIndex(layer), 0, layer);\n if (this.#stack.length === 1) {\n this.#installListeners();\n }\n }\n\n /** @internal */\n remove(layer: DismissibleLayer): void {\n const idx = this.#stack.indexOf(layer);\n if (idx < 0) {\n return;\n }\n const anchor = layer.anchor;\n const hosts = anchor\n ? this.#stack.slice(0, idx).filter((below) => this.containsFromLayer(below, anchor))\n : [];\n this.#stack.splice(idx, 1);\n if (this.#stack.length === 0) {\n this.#removeListeners();\n }\n for (const host of hosts) {\n host.nestedLayerRemoved();\n }\n }\n\n /**\n * @internal Whether `target` is inside `layer` or inside any layer stacked\n * above it. A layer stacked above the chosen channel handler (e.g. an\n * interactive Escape-only HoverCard over a Popover) counts as \"inside\", so an\n * interaction within it never leaks an \"outside\" dismissal to the layer below.\n */\n containsFromLayer(layer: DismissibleLayer, target: Node): boolean {\n const idx = this.#stack.indexOf(layer);\n if (idx < 0) {\n return layer.contains(target);\n }\n for (let i = idx; i < this.#stack.length; i++) {\n const above = this.#stack[i];\n if (above && above.contains(target)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * @internal Whether a layer stacked above `layer` was opened from inside it:\n * its anchor is inside `layer` or inside another layer stacked above it.\n */\n hasNestedLayer(layer: DismissibleLayer): boolean {\n const idx = this.#stack.indexOf(layer);\n if (idx < 0) {\n return false;\n }\n for (let i = idx + 1; i < this.#stack.length; i++) {\n const anchor = this.#stack[i]?.anchor;\n if (anchor && this.containsFromLayer(layer, anchor)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * @internal Whether `layer` is the topmost layer declaring `channel`, i.e. the\n * one an outside interaction on that channel is dispatched to.\n */\n isTopmostForChannel(layer: DismissibleLayer, channel: DismissibleLayerChannel): boolean {\n return this.#topmostForChannel(channel) === layer;\n }\n\n /**\n * Runs `fn` with the dispatcher suppressed. While suppressed, neither\n * Escape, pointer-down outside, nor focus-outside events are forwarded\n * to the topmost layer. Refcounted so nested teardowns nest correctly.\n */\n suppress<T>(fn: () => T): T {\n this.#suppressDepth++;\n try {\n return fn();\n } finally {\n this.#suppressDepth--;\n }\n }\n\n /**\n * Whether an `Escape` pressed inside `node` reaches an active layer before any layer containing\n * `node`: walking down from the top, an active layer comes first. Answers `false` while the\n * dispatcher is suppressed, since it would then dispatch to no layer.\n */\n #hasEscapeLayerAbove(node: Node): boolean {\n if (this.#suppressDepth > 0) {\n return false;\n }\n for (let i = this.#stack.length - 1; i >= 0; i--) {\n const layer = this.#stack[i];\n if (!layer) {\n continue;\n }\n if (layer.contains(node)) {\n return false;\n }\n if (layer.isActive) {\n return true;\n }\n }\n return false;\n }\n\n #installListeners(): void {\n if (!this.#isBrowser || this.#listening) {\n return;\n }\n this.#listening = true;\n this.#document.addEventListener('keydown', this.#onKeyDown);\n this.#document.addEventListener('pointerdown', this.#onPointerDown, true);\n this.#document.addEventListener('focusin', this.#onFocusIn, true);\n this.#document.defaultView?.addEventListener('blur', this.#onWindowBlur);\n }\n\n #removeListeners(): void {\n if (!this.#listening) {\n return;\n }\n this.#listening = false;\n this.#document.removeEventListener('keydown', this.#onKeyDown);\n this.#document.removeEventListener('pointerdown', this.#onPointerDown, true);\n this.#document.removeEventListener('focusin', this.#onFocusIn, true);\n this.#document.defaultView?.removeEventListener('blur', this.#onWindowBlur);\n this.#lastFocusInTarget = null;\n }\n\n /**\n * Where a newly activated layer belongs. Plain LIFO (the top of the stack)\n * unless the layer declared a {@link DismissibleLayerNesting}: then it slides\n * down past the trailing run of layers from the same chain that sit deeper\n * than it, so an ancestor activating after its own descendant still lands\n * below it. The scan stops at the first layer that is not a deeper\n * level of the same chain, so an unrelated overlay (a Dialog opened from\n * inside a submenu) is never jumped over.\n */\n #insertionIndex(layer: DismissibleLayer): number {\n const nesting = layer.nesting;\n let idx = this.#stack.length;\n if (!nesting) {\n return idx;\n }\n while (idx > 0) {\n const below = this.#stack[idx - 1]?.nesting;\n if (!below || below.chain !== nesting.chain || below.depth <= nesting.depth) {\n break;\n }\n idx--;\n }\n return idx;\n }\n\n #layersForChannel(channel: DismissibleLayerChannel): DismissibleLayer[] {\n const layers: DismissibleLayer[] = [];\n for (let i = this.#stack.length - 1; i >= 0; i--) {\n const layer = this.#stack[i];\n if (layer && layer.ownsChannel(channel)) {\n layers.push(layer);\n }\n }\n return layers;\n }\n\n #topmostForChannel(channel: DismissibleLayerChannel): DismissibleLayer | undefined {\n for (let i = this.#stack.length - 1; i >= 0; i--) {\n const layer = this.#stack[i];\n if (layer && layer.ownsChannel(channel)) {\n return layer;\n }\n }\n return undefined;\n }\n}\n\n/**\n * Coordinates the standard \"dismissible surface\" interactions used by modal\n * dialogs, popovers, dropdown menus, drawers, and any other transient\n * overlay: Escape, pointer-down outside, focus-outside.\n *\n * Dispatch is per channel. Escape goes to the topmost active layer, and reaches\n * a layer below only when every layer above it declined the key, so one Escape\n * still closes at most one layer and never crosses a modal layer.\n * Pointer-down-outside and focus-outside instead go to the topmost\n * layer that declared the matching channel: a layer that owns only Escape (e.g.\n * a Tooltip, declaring `channels: []`) is transparent to outside-pointer /\n * focus for the real dismissible layers beneath it, so a tooltip visible over\n * an open menu never shadows the menu's outside-click dismissal. Nested\n * real layers (a popover inside a dialog) still resolve to a single topmost\n * handler per channel, so single-dismiss semantics hold — unless a lower layer\n * opts into `cascadeOutsidePress`, in which case an outside press the layer\n * above it closed on reaches it too.\n *\n * Containment is stack-aware: an interaction inside a layer stacked *above* the\n * chosen handler counts as \"inside\", so an interactive Escape-only surface (a\n * HoverCard over a Popover) never leaks an outside dismissal to the layer below.\n *\n * Dispatch goes through a single shared document listener, so synchronous\n * changes to the stack from a handler don't leak into sibling listeners.\n */\nexport class DismissibleLayer {\n readonly #host: HTMLElement;\n readonly #stack: DismissibleLayerStack;\n #options: DismissibleLayerActivateOptions = EMPTY_ACTIVATE_OPTIONS;\n #channels: ReadonlySet<DismissibleLayerChannel> = new Set();\n #active = false;\n\n constructor(host: HTMLElement, stack: DismissibleLayerStack) {\n this.#host = host;\n this.#stack = stack;\n }\n\n get host(): HTMLElement {\n return this.#host;\n }\n\n get isActive(): boolean {\n return this.#active;\n }\n\n /**\n * @internal The nesting position declared at `activate`, or `undefined` for a\n * standalone layer. Read by {@link DismissibleLayerStack} to place the layer\n * by nesting depth instead of activation order. Public only so the stack can\n * read it, not part of the supported API.\n */\n get nesting(): DismissibleLayerNesting | undefined {\n return this.#options.nesting;\n }\n\n /**\n * @internal The anchor declared at `activate`. Read by\n * {@link DismissibleLayerStack} to tell which layers are nested in which.\n */\n get anchor(): Element | undefined {\n return this.#options.anchor;\n }\n\n /**\n * Whether this layer is active and a layer opened from inside it is still\n * stacked above it: one whose anchor lies inside this layer, or inside a\n * layer stacked above this one.\n */\n hasNestedLayer(): boolean {\n return this.#active && this.#stack.hasNestedLayer(this);\n }\n\n /**\n * @internal Called by {@link DismissibleLayerStack} after a layer nested in\n * this one was removed.\n */\n nestedLayerRemoved(): void {\n this.#options.onNestedLayerRemoved?.();\n }\n\n /**\n * Pushes this layer onto the dispatch stack. Calling `activate` twice\n * without an intervening `deactivate` is a no-op.\n */\n activate(options: DismissibleLayerActivateOptions): void {\n if (this.#active) {\n return;\n }\n this.#active = true;\n this.#options = options;\n this.#channels = new Set(options.channels);\n this.#stack.push(this);\n }\n\n /** Removes this layer from the stack. */\n deactivate(): void {\n if (!this.#active) {\n return;\n }\n this.#active = false;\n this.#stack.remove(this);\n this.#options = EMPTY_ACTIVATE_OPTIONS;\n this.#channels = new Set();\n }\n\n /**\n * Convenience wrapper around the stack's `suppress`. Lets owners\n * suppress the dispatcher without needing a fresh injection context\n * (e.g. inside `DestroyRef.onDestroy` or imperative teardown closures).\n */\n suppress<T>(fn: () => T): T {\n return this.#stack.suppress(fn);\n }\n\n /**\n * @internal Whether this layer declared ownership of `channel`. Read by\n * {@link DismissibleLayerStack} to route an outside pointer-down / focus to\n * the topmost owning layer. Public only so the stack can read it, not part of\n * the supported API.\n */\n ownsChannel(channel: DismissibleLayerChannel): boolean {\n return this.#channels.has(channel);\n }\n\n /**\n * Whether this layer is active and is the topmost layer declaring `channel`, so no other layer\n * stacked above it would receive an outside interaction on that channel first.\n */\n isTopmostFor(channel: DismissibleLayerChannel): boolean {\n return this.#active && this.#stack.isTopmostForChannel(this, channel);\n }\n\n /**\n * @internal Whether `target` is inside this layer's host or its exempt\n * elements. Read by {@link DismissibleLayerStack} when walking the stack for\n * stack-aware containment. Public only so the stack can read it.\n *\n * Containment is composed-tree containment, the counterpart of the deep\n * target {@link resolveEventTarget} resolves: plain `Node.contains` answers\n * within one node tree, so a press on a control inside a web component's\n * shadow root — a target the composed path resolves precisely — would read as\n * a press outside the surface that renders it.\n */\n contains(target: Node): boolean {\n if (composedContains(this.#host, target)) {\n return true;\n }\n const exempt = this.#options.exemptElements?.(target);\n if (!exempt) {\n return false;\n }\n for (const el of exempt) {\n if (composedContains(el, target)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * @internal Dispatched by {@link DismissibleLayerStack} to the topmost layer\n * on `Escape`, and to each layer below it while the layers above decline the\n * key. Returns whether this layer kept it. Public only so the stack can call it\n * without exploiting a TS visibility loophole; not part of the supported API\n * (stripped from `.d.ts`).\n */\n handleEscape(event: KeyboardEvent): boolean {\n return this.#options.onEscapeKeyDown?.(event) !== false;\n }\n\n /**\n * @internal Dispatched by {@link DismissibleLayerStack} to the topmost layer\n * declaring the `'pointer'` channel on an outside `pointerdown`, and to each\n * layer below it an outside-press cascade reaches. Returns whether the press\n * was outside and the layer closed on it. See {@link handleEscape}.\n */\n handlePointerDown(event: PointerEvent): boolean {\n const target = resolveEventTarget(event);\n if (!target) {\n return false;\n }\n if (this.#stack.containsFromLayer(this, target)) {\n this.#options.onPointerDownInside?.(event);\n return false;\n }\n const closed = this.#options.onPointerDownOutside?.(event) === true;\n this.#options.onInteractOutside?.(event);\n return closed;\n }\n\n /**\n * @internal Whether this layer declared itself modal at `activate`. Read by\n * {@link DismissibleLayerStack} to end an outside-press cascade.\n */\n get isModal(): boolean {\n return this.#options.modal === true;\n }\n\n /**\n * @internal Whether this layer currently opts into an outside-press cascade.\n * Read by {@link DismissibleLayerStack} on every press.\n */\n cascadesOutsidePress(): boolean {\n return this.#options.cascadeOutsidePress?.() === true;\n }\n\n /**\n * @internal Dispatched by {@link DismissibleLayerStack} to the topmost layer\n * declaring the `'focus'` channel on an outside `focusin`, and on the\n * window `blur` that moves focus into an `<iframe>`, with that frame as\n * `target`. See {@link handleEscape}.\n */\n handleFocusIn(event: FocusEvent, target: Node | null = resolveEventTarget(event)): void {\n if (!target || this.#stack.containsFromLayer(this, target)) {\n return;\n }\n this.#options.onFocusOutside?.(event);\n this.#options.onInteractOutside?.(event);\n }\n}\n\n/**\n * Creates a `DismissibleLayer` for the directive's host element and wires\n * deactivation into `DestroyRef`. The host primitive owns activation\n * (typically via an `effect()` watching the open state).\n *\n * Use `layer.suppress(fn)` to run a callback with the dispatcher\n * suppressed (e.g. across a focus-return that would otherwise\n * cascade-dismiss the next topmost layer).\n */\nexport function injectDismissibleLayer(): DismissibleLayer {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const stack = inject(DismissibleLayerStack);\n const layer = new DismissibleLayer(host.nativeElement, stack);\n inject(DestroyRef).onDestroy(() => layer.deactivate());\n return layer;\n}\n","import type { Signal } from '@angular/core';\n\nimport type { DismissibleLayerActivateOptions, DismissibleLayerChannel } from './dismissible-layer';\nimport { createVetoableNativeEvent, type VetoableNativeEvent } from 'forty-cdk/core';\n\n/**\n * Emit forwarders + implicit-close wiring for the outside-interaction channels\n * that {@link buildOutsideVetoOptions} folds into self-closing layer handlers.\n * Each wired outside channel builds one veto, emits it through the specific\n * output (if wired) and the composite `interactOutside` output (if wired), then\n * closes itself when un-vetoed and `dismissible()` is `true`. Escape is\n * intentionally absent: it never participates in the outside-close (it is a\n * one-shot channel whose close behaviour differs per shell), so each shell\n * wires its own `onEscapeKeyDown` alongside the object this returns.\n *\n * Every field is optional so a shell can register a layer listener only for the\n * channels its consumer actually forwards — the trigger-anchored overlays opt\n * out of individual channels (an input-focused combobox owns Escape on its\n * input and omits it here), while the modal shell forwards all three.\n */\nexport interface OutsideVetoConfig {\n /**\n * Whether an un-vetoed outside interaction fires the implicit\n * `requestClose`. Read fresh on every outside interaction.\n */\n readonly dismissible?: Signal<boolean>;\n /**\n * Called with the matching reason (`'pointerDownOutside'` / `'focusOutside'`)\n * when the consumer doesn't veto the outside interaction and `dismissible()`\n * is `true`. Each wired outside channel fires its own close.\n */\n readonly requestClose?: (reason: 'pointerDownOutside' | 'focusOutside') => 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\n/**\n * Builds the pointer-down-outside / focus-outside entries of a\n * {@link DismissibleLayerActivateOptions}, folding the composite\n * `interactOutside` emit and the implicit close into each specific channel so\n * every wired outside channel closes itself.\n *\n * The protocol: each handler builds a single {@link VetoableNativeEvent} for\n * its physical interaction, hands it to the specific emitter (if wired) and\n * then to the composite `interactOutside` emitter (if wired), and — when\n * neither subscriber vetoed and `dismissible()` is `true` — calls\n * `requestClose(reason)` with the channel's reason (`'pointerDownOutside'` /\n * `'focusOutside'`). A `preventDefault()` from either the specific or the\n * composite subscriber suppresses the close, since both observe the same veto.\n * The pointer handler returns whether it closed, which is what lets an outside\n * press cascade to a lower layer that opted in.\n *\n * `onPointerDownOutside` is registered when either the specific\n * `emitPointerDownOutside` or the composite `emitInteractOutside` is wired, and\n * `onFocusOutside` likewise — matching what {@link outsideVetoChannels}\n * declares — so an interact-only wiring still gets both self-closing handlers.\n * Returns only the channels whose emitter is present, so the caller can spread\n * the result into its `dismissible.activate({...})` call alongside the pieces\n * that stay shell-specific (`exemptElements`, `onEscapeKeyDown`).\n */\nexport function buildOutsideVetoOptions(\n config: OutsideVetoConfig,\n): Pick<DismissibleLayerActivateOptions, 'onPointerDownOutside' | 'onFocusOutside'> {\n const options: Pick<DismissibleLayerActivateOptions, 'onPointerDownOutside' | 'onFocusOutside'> =\n {};\n const {\n dismissible,\n requestClose,\n emitPointerDownOutside,\n emitFocusOutside,\n emitInteractOutside,\n } = config;\n\n if (emitPointerDownOutside || emitInteractOutside) {\n options.onPointerDownOutside = (event) => {\n const veto = createVetoableNativeEvent<PointerEvent | FocusEvent>(event);\n emitPointerDownOutside?.(veto as VetoableNativeEvent<PointerEvent>);\n emitInteractOutside?.(veto);\n if (!veto.defaultPrevented && dismissible?.() && requestClose) {\n requestClose('pointerDownOutside');\n return true;\n }\n return false;\n };\n }\n\n if (emitFocusOutside || emitInteractOutside) {\n options.onFocusOutside = (event) => {\n const veto = createVetoableNativeEvent<PointerEvent | FocusEvent>(event);\n emitFocusOutside?.(veto as VetoableNativeEvent<FocusEvent>);\n emitInteractOutside?.(veto);\n if (!veto.defaultPrevented && dismissible?.() && requestClose) {\n requestClose('focusOutside');\n }\n };\n }\n\n return options;\n}\n\n/**\n * Derives the outside-interaction channels a shell must declare at\n * `dismissible.activate({ channels })` from the same {@link OutsideVetoConfig}\n * passed to {@link buildOutsideVetoOptions}. A layer owns `'pointer'` when it\n * forwards either the specific pointer-down-outside channel or the composite\n * interact-outside channel (which fires for pointer-downs too), and likewise\n * `'focus'` for focus-outside / interact-outside. A shell that forwards no\n * outside channel (an Escape-only surface) gets `[]` and stays transparent to\n * the real dismissible layers beneath it.\n */\nexport function outsideVetoChannels(config: OutsideVetoConfig): DismissibleLayerChannel[] {\n const channels: DismissibleLayerChannel[] = [];\n if (config.emitPointerDownOutside || config.emitInteractOutside) {\n channels.push('pointer');\n }\n if (config.emitFocusOutside || config.emitInteractOutside) {\n channels.push('focus');\n }\n return channels;\n}\n","import { computed, Injectable, type Signal, signal } from '@angular/core';\n\nimport { type ForDrawerSide } from './drawer-side';\nimport { fortyError } from 'forty-cdk/core';\n\n/**\n * Snapshot of a single drawer registered with {@link ForDrawerStack}. The\n * stack is LIFO ordered (root → topmost) and exposes only what other\n * coordinators need — `host` for ancestry checks, `side` (a `Signal`, so a\n * runtime side flip recomputes dependent transforms) for layout heuristics,\n * `parent` for topology, and the resolved nested-transform tunables so\n * `ForDrawerScaleCoordinator`'s nested-transform pass never needs to re-read\n * scope-dependent defaults.\n */\nexport interface DrawerStackNode {\n readonly host: HTMLElement;\n /**\n * Reactive edge the drawer is anchored to. Read inside the coordinator's\n * nested-transform effect so a runtime `[side]` rebind recomputes the\n * parent surface's transform axis.\n */\n readonly side: Signal<ForDrawerSide>;\n readonly parent: HTMLElement | null;\n /**\n * Scale factor applied to *this* drawer's host while it owns one or\n * more direct child drawers (the nested-drawer visual). Resolved from\n * the drawer's own injector scope at push time so per-scope\n * `provideForDrawerDefaults` overrides flow through.\n */\n readonly nestedScaleAmount: number;\n /**\n * Pixels of translation applied to *this* drawer's host while it owns\n * one or more direct child drawers, in the direction *away* from its\n * anchored edge.\n */\n readonly nestedTranslateYpx: number;\n}\n\n/**\n * Returned by {@link ForDrawerStack.push}. `depth` is the number of\n * ancestor drawers in the node's `parent` chain (0 for a root drawer, 1 for a\n * single-nested child, …), recomputed whenever the stack changes. `cleanup`\n * pops the node; calling it while descendants are still registered throws so\n * consumers surface their own destroy-order bugs instead of silently leaking.\n */\nexport interface DrawerStackHandle {\n readonly depth: Signal<number>;\n cleanup(): void;\n}\n\n/**\n * App-scoped LIFO registry of every active `[forDrawer]`. Mounted drawers\n * push themselves on first render and pop on destroy; the stack's signal\n * is the single source of truth for nesting topology consumed by:\n *\n * - `[forDrawer]` itself, to derive `data-depth` and `data-state-nested`\n * on its host (the latter when the stack contains a node whose\n * `parent` is this drawer's host).\n * - `ForDrawerScaleCoordinator`, when `scaleBackground` is opted in by\n * multiple levels of nesting and the visual effect must compose along\n * the LIFO topmost.\n *\n * The companion to {@link DismissibleLayerStack} and `InertSiblingsStack`:\n * those keep the focus / dismiss / inert behaviour LIFO-correct, this one\n * keeps the *visual* / *topology* layer LIFO-correct. Both are read-only\n * to consumers — there is no public API for explicit ordering. A drawer is\n * pushed on top unless one of its descendants is already registered, as\n * when parent and child mount in one render pass, in which case it is\n * inserted below its first descendant.\n *\n * SSR: `providedIn: 'root'` so state is per Angular bootstrap. The\n * directives that call `push` only do so from `afterNextRender`, which\n * doesn't run on the server, so there is nothing to guard here.\n *\n * Internal core tier — exported from `forty-cdk/core-overlay` for the\n * library's own entry points, with no semver guarantee.\n */\n@Injectable({ providedIn: 'root' })\nexport class ForDrawerStack {\n readonly #stack = signal<readonly DrawerStackNode[]>([]);\n\n /**\n * Reactive view of the current drawer stack (root → topmost). Reading\n * this from a `computed`/`effect` lets primitives react to nesting\n * changes synchronously when a child drawer mounts or unmounts.\n */\n readonly stack: Signal<readonly DrawerStackNode[]> = this.#stack.asReadonly();\n\n /**\n * Push a drawer onto the stack. Returns a {@link DrawerStackHandle}\n * carrying the computed `depth` and a `cleanup` that pops the same\n * node. `depth` is derived from the node's `parent` chain through the\n * registered drawers: a root drawer (no `parent`) is depth 0; a child of\n * a depth-N drawer is depth N+1.\n *\n * `cleanup` is idempotent on a node that's already gone, but throws if\n * the node still has descendants in the stack — the canonical signal\n * that the consumer's template tore down a parent before its child\n * (typically because the parent's `@if` flipped to `false` while the\n * child sits in a separate template branch). Nest the child's\n * `@if (childOpen())` *inside* the parent's `@if (parentOpen())` to\n * inherit Angular's bottom-up destroy order automatically.\n */\n push(node: DrawerStackNode): DrawerStackHandle {\n this.#stack.update((s) => {\n const descendant = s.findIndex((other) => this.#isDescendant(other, node, s));\n const next = s.slice();\n next.splice(descendant === -1 ? next.length : descendant, 0, node);\n return next;\n });\n return {\n depth: computed(() => this.#computeDepth(node, this.#stack())),\n cleanup: () => this.#cleanup(node),\n };\n }\n\n #cleanup(node: DrawerStackNode): void {\n const current = this.#stack();\n const idx = current.indexOf(node);\n if (idx === -1) {\n return;\n }\n const hasDescendant = current.some(\n (other) => other !== node && this.#isDescendant(other, node, current),\n );\n if (hasDescendant) {\n throw fortyError({\n code: 'FORCDK-DRAWER-001',\n message: 'A parent drawer was destroyed while a nested child drawer was still registered.',\n cause:\n 'The drawer stack unwinds last-in-first-out, so a child must unmount before its parent. ' +\n 'Sibling @if blocks unmount in template order instead.',\n fix: \"Wrap the child drawer's @if inside the parent's, so the child unmounts first.\",\n });\n }\n const next = current.slice();\n next.splice(idx, 1);\n this.#stack.set(next);\n }\n\n #computeDepth(node: DrawerStackNode, stack: readonly DrawerStackNode[]): number {\n if (node.parent === null) {\n return 0;\n }\n let depth = 0;\n let cursor: HTMLElement | null = node.parent;\n while (cursor) {\n depth += 1;\n const ancestor = stack.find((n) => n.host === cursor);\n if (!ancestor) {\n break;\n }\n cursor = ancestor.parent;\n }\n return depth;\n }\n\n #isDescendant(\n candidate: DrawerStackNode,\n ancestor: DrawerStackNode,\n stack: readonly DrawerStackNode[],\n ): boolean {\n let cursor: HTMLElement | null = candidate.parent;\n while (cursor) {\n if (cursor === ancestor.host) {\n return true;\n }\n const next = stack.find((n) => n.host === cursor);\n if (!next) {\n return false;\n }\n cursor = next.parent;\n }\n return false;\n }\n}\n","/**\n * A single self-clearing debounce timer: the `Math.max(0, delay)` clamp, the\n * `delay === 0` synchronous fast-path, and the lone pending\n * `setTimeout` / `clearTimeout` pair.\n *\n * The hover-driven menus (`[forMenuSub]`, `[forMenubar]`, `[forNavigationMenu]`)\n * each hand-rolled this exact timer arming/clearing under their own divergent\n * open/close policy (chain keep-alive, hover-after-open, per-value cancel\n * guards, skip-delay). This factory owns only the timing mechanics so those\n * policies stay at the call site — the caller arms with `schedule(delay)`,\n * which clears any in-flight timer first, runs `run` immediately when the\n * clamped delay is `0`, else fires it once after the delay.\n *\n * Internal core tier — exported from `forty-cdk/core-overlay` for the\n * library's own entry points, with no semver guarantee.\n */\nexport interface DebouncedAction {\n /**\n * Arm the action after `delay` ms (clamped to `>= 0`). Clears any pending\n * timer first; a clamped delay of `0` runs `run` synchronously.\n */\n schedule(delay: number): void;\n /** Cancel a pending action without running it. Safe with no pending timer. */\n cancel(): void;\n /** `true` while an action is armed but not yet fired. */\n isPending(): boolean;\n}\n\n/**\n * Builds a {@link DebouncedAction} around `run`. Framework-free.\n */\nexport function createDebouncedAction(run: () => void): DebouncedAction {\n let timer: ReturnType<typeof setTimeout> | null = null;\n\n function cancel(): void {\n if (timer !== null) {\n clearTimeout(timer);\n timer = null;\n }\n }\n\n function schedule(delay: number): void {\n cancel();\n const clamped = Math.max(0, delay);\n if (clamped === 0) {\n run();\n return;\n }\n timer = setTimeout(() => {\n timer = null;\n run();\n }, clamped);\n }\n\n return {\n schedule,\n cancel,\n isPending: () => timer !== null,\n };\n}\n","import { Injectable, PLATFORM_ID, inject } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\n/**\n * What keeps a registered peer interactive over a modal: the elements it was opened from, which\n * must belong to the topmost owner, or `'always'` for a host exempt under every owner.\n */\nexport type PeerAnchors = readonly Element[] | 'always';\n\n/**\n * The overlays that may stay interactive over a modal, kept apart from `InertSiblingsStack` so\n * that registering one does not construct the modal isolation engine. Until a modal activates, a\n * registration is a map write; the stack reads {@link ModalPeerRegistry.peers} when it first\n * applies, so a peer registered before then is honoured.\n *\n * SSR: registration is a no-op on the server.\n */\n@Injectable({ providedIn: 'root' })\nexport class ModalPeerRegistry {\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n readonly #peers = new Map<HTMLElement, PeerAnchors>();\n #listener: ((released: HTMLElement | null) => void) | null = null;\n\n /** Every registered peer host, with the anchors it was registered with. */\n get peers(): ReadonlyMap<HTMLElement, PeerAnchors> {\n return this.#peers;\n }\n\n /**\n * Register `host` as a peer of the modal owning `anchors`. Returns a release function, which is\n * a no-op once `host` has been registered again with other anchors.\n */\n registerPeer(host: HTMLElement, anchors: PeerAnchors): () => void {\n if (!this.#isBrowser) {\n return () => {};\n }\n this.#peers.set(host, anchors);\n this.#listener?.(null);\n return () => {\n if (this.#peers.get(host) !== anchors) {\n return;\n }\n this.#peers.delete(host);\n this.#listener?.(host);\n };\n }\n\n /**\n * Install the single callback run after every registration change, with the released host, or\n * `null` for a new registration.\n */\n connect(listener: (released: HTMLElement | null) => void): void {\n this.#listener = listener;\n }\n}\n","import { DOCUMENT, Injectable, PLATFORM_ID, inject } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\nimport {\n composedContains,\n composedParentElement,\n MODAL_EXEMPT_ATTRIBUTE,\n MODAL_PEER_ATTRIBUTE,\n} from 'forty-cdk/core';\n\nimport { ModalPeerRegistry, type PeerAnchors } from './modal-peer-registry';\n\ninterface SnapshotEntry {\n readonly el: HTMLElement;\n readonly hadInert: boolean;\n readonly prevAriaHidden: string | null;\n}\n\nexport interface InertSiblingsHandle {\n /** Pop this owner off the stack and recompute. */\n deactivate(): void;\n /** Whether this handle is still on the stack. */\n readonly isActive: boolean;\n}\n\ninterface RootState {\n readonly root: HTMLElement;\n readonly stack: HTMLElement[];\n appliedSnapshot: SnapshotEntry[];\n observer: MutationObserver | null;\n}\n\n/**\n * Marks every direct child of a **root element** (default `document.body`,\n * or a positioned container when a region-scoped modal passes one)\n * other than the topmost active owner (and any peer of that owner) as `inert` and\n * `aria-hidden=\"true\"` while at least one owner is active on that root.\n * Restores each touched element to its exact prior state once the last\n * owner deactivates.\n *\n * `aria-modal=\"true\"` alone is insufficient: Safari with VoiceOver, among other combinations, still\n * announces siblings of an aria-modal node unless the rest of the document is explicitly hidden.\n *\n * **Stacking.** Each root keeps its own owner stack, snapshot and `MutationObserver`, so a\n * `document.body` root and a container root are fully independent. The element-level outcome is\n * recomputed from the current topmost owner whenever the stack changes: the previous outcome is\n * reverted to its snapshot first, then a fresh one is applied. Closing owners out of LIFO order\n * therefore still leaves a coherent document, and full restoration runs when the stack empties.\n *\n * **Portals.** The owner need not be a direct child of the root — the root-level child that is an\n * ancestor of the owner is resolved and its subtree excluded, so an in-place dialog keeps its\n * enclosing app shell interactive. That walk climbs the composed tree, so an owner rendered inside\n * a shadow root still resolves to the root-level child hosting it.\n *\n * **Peers.** An overlay registered through `ModalPeerRegistry.registerPeer` is excluded from\n * the snapshot only while it belongs to the topmost owner of the root it sits in, so the peer of a\n * background modal is inerted again under a nested one. The stack reflects that state as\n * `data-for-modal-peer` on the registered host. An element carrying the attribute without being\n * registered (a backdrop) is excluded under every owner, as is one carrying\n * {@link MODAL_EXEMPT_ATTRIBUTE}, which additionally opts out of the dismissible layer.\n *\n * **Late siblings.** While any owner is active, a `MutationObserver` inerts each newly added\n * sibling under the same rules, so an element portaled to the root after activation is isolated and\n * restored too.\n *\n * SSR: every operation is a no-op on the server, since `activate()` is only ever called from\n * `afterNextRender`.\n */\n@Injectable({ providedIn: 'root' })\nexport class InertSiblingsStack {\n readonly #document = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n\n readonly #roots = new Map<HTMLElement, RootState>();\n readonly #peers = inject(ModalPeerRegistry).peers;\n\n constructor() {\n inject(ModalPeerRegistry).connect((released) => {\n released?.removeAttribute(MODAL_PEER_ATTRIBUTE);\n this.#reapplyAll();\n });\n }\n\n /**\n * Push `owner` onto the inert-siblings stack for `root` (default\n * `document.body`) and (re)apply the isolation outcome for the new topmost\n * owner. Returns a handle whose `deactivate()` pops this specific owner —\n * order-safe, so closing out of LIFO order works.\n *\n * When `root` is a positioned container (e.g. a region-scoped modal), only\n * that container's other children are inerted; body siblings outside the\n * container stay fully interactive.\n */\n activate(owner: HTMLElement, root: HTMLElement = this.#document.body): InertSiblingsHandle {\n if (!this.#isBrowser) {\n return {\n deactivate: () => {},\n get isActive(): boolean {\n return false;\n },\n };\n }\n const state = this.#stateFor(root);\n this.#revertAppliedSnapshot(state);\n if (state.stack.length === 0) {\n this.#startObserving(state);\n }\n state.stack.push(owner);\n this.#applyForCurrentTopmost(state);\n this.#syncPeerAttributes();\n\n let active = true;\n return {\n get isActive(): boolean {\n return active;\n },\n deactivate: (): void => {\n if (!active) {\n return;\n }\n active = false;\n const idx = state.stack.indexOf(owner);\n if (idx === -1) {\n return;\n }\n this.#revertAppliedSnapshot(state);\n state.stack.splice(idx, 1);\n if (state.stack.length > 0) {\n this.#applyForCurrentTopmost(state);\n } else {\n this.#stopObserving(state);\n this.#roots.delete(root);\n }\n this.#syncPeerAttributes();\n },\n };\n }\n\n /**\n * Whether an overlay anchored to `anchor` should be left interactive over\n * the active modal — i.e. treated as a peer of the topmost owner instead of\n * inerted. Returns `true` only while at least one owner is active AND\n * `anchor` lives inside the current protected root for any active root, or\n * inside a registered peer that does, which means the overlay was opened\n * from within a modal (e.g. a Select / DropdownMenu opened from a form inside\n * a Dialog, or a submenu opened from that DropdownMenu).\n *\n * Returns `false` when no owner is active — so an overlay opened with no\n * modal present is never pre-marked, and a modal opened later inerts it like\n * any other background sibling — and when `anchor` sits in an already-inerted\n * background subtree (a toast or a tooltip anchored to a backdrop element).\n * SSR-safe: on the server the roots map is always empty (no owner\n * activates), so this returns `false`.\n */\n ownsAnchor(anchor: Element): boolean {\n for (const state of this.#roots.values()) {\n const protectedRoot = this.#currentProtectedRoot(state);\n if (protectedRoot !== null && this.#owns(protectedRoot, [anchor], new Set())) {\n return true;\n }\n }\n return false;\n }\n\n #stateFor(root: HTMLElement): RootState {\n let state = this.#roots.get(root);\n if (!state) {\n state = { root, stack: [], appliedSnapshot: [], observer: null };\n this.#roots.set(root, state);\n }\n return state;\n }\n\n #applyForCurrentTopmost(state: RootState): void {\n const protectedRoot = this.#currentProtectedRoot(state);\n if (!protectedRoot) {\n return;\n }\n\n for (const child of Array.from(state.root.children)) {\n this.#inertChild(child, protectedRoot, state);\n }\n }\n\n #inertChild(child: Element, protectedRoot: HTMLElement, state: RootState): void {\n if (!(child instanceof HTMLElement)) {\n return;\n }\n if (child === protectedRoot || child.hasAttribute(MODAL_EXEMPT_ATTRIBUTE)) {\n return;\n }\n const anchors = this.#peers.get(child);\n const exempt =\n anchors === undefined\n ? child.hasAttribute(MODAL_PEER_ATTRIBUTE)\n : anchors === 'always' || this.#owns(protectedRoot, anchors, new Set());\n if (exempt) {\n return;\n }\n if (state.appliedSnapshot.some((entry) => entry.el === child)) {\n return;\n }\n\n state.appliedSnapshot.push({\n el: child,\n hadInert: child.hasAttribute('inert'),\n prevAriaHidden: child.getAttribute('aria-hidden'),\n });\n\n child.setAttribute('inert', '');\n child.setAttribute('aria-hidden', 'true');\n }\n\n #owns(\n protectedRoot: HTMLElement,\n anchors: readonly Element[],\n visited: Set<HTMLElement>,\n ): boolean {\n return anchors.some((anchor) => {\n if (composedContains(protectedRoot, anchor)) {\n return true;\n }\n for (const [peer, peerAnchors] of this.#peers) {\n if (peerAnchors === 'always' || visited.has(peer) || !composedContains(peer, anchor)) {\n continue;\n }\n visited.add(peer);\n if (this.#owns(protectedRoot, peerAnchors, visited)) {\n return true;\n }\n }\n return false;\n });\n }\n\n #reapplyAll(): void {\n for (const state of this.#roots.values()) {\n this.#revertAppliedSnapshot(state);\n this.#applyForCurrentTopmost(state);\n }\n this.#syncPeerAttributes();\n }\n\n #syncPeerAttributes(): void {\n for (const [peer, anchors] of this.#peers) {\n peer.toggleAttribute(MODAL_PEER_ATTRIBUTE, this.#isLivePeer(peer, anchors));\n }\n }\n\n #isLivePeer(peer: HTMLElement, anchors: PeerAnchors): boolean {\n if (anchors === 'always') {\n return true;\n }\n for (const state of this.#roots.values()) {\n const protectedRoot = this.#currentProtectedRoot(state);\n if (protectedRoot !== null && this.#owns(protectedRoot, anchors, new Set())) {\n return true;\n }\n }\n return false;\n }\n\n #currentProtectedRoot(state: RootState): HTMLElement | null {\n const top = state.stack[state.stack.length - 1];\n if (!top) {\n return null;\n }\n return this.#rootLevelChild(top, state.root) ?? top;\n }\n\n #startObserving(state: RootState): void {\n const win = this.#document.defaultView;\n if (state.observer || !win || typeof win.MutationObserver !== 'function') {\n return;\n }\n state.observer = new win.MutationObserver((records) => {\n const protectedRoot = this.#currentProtectedRoot(state);\n if (!protectedRoot) {\n return;\n }\n let addedPeer = false;\n for (const record of records) {\n for (const node of Array.from(record.addedNodes)) {\n if (node instanceof HTMLElement && node.parentElement === state.root) {\n addedPeer ||= this.#peers.has(node);\n this.#inertChild(node, protectedRoot, state);\n }\n }\n }\n if (addedPeer) {\n this.#syncPeerAttributes();\n }\n });\n state.observer.observe(state.root, { childList: true });\n }\n\n #stopObserving(state: RootState): void {\n state.observer?.disconnect();\n state.observer = null;\n }\n\n #revertAppliedSnapshot(state: RootState): void {\n for (const entry of state.appliedSnapshot) {\n if (!entry.hadInert) {\n entry.el.removeAttribute('inert');\n }\n if (entry.prevAriaHidden === null) {\n entry.el.removeAttribute('aria-hidden');\n } else {\n entry.el.setAttribute('aria-hidden', entry.prevAriaHidden);\n }\n }\n state.appliedSnapshot = [];\n }\n\n #rootLevelChild(el: HTMLElement, root: HTMLElement): HTMLElement | null {\n let cur: HTMLElement = el;\n let parent = composedParentElement(cur);\n while (parent && parent !== root) {\n cur = parent;\n parent = composedParentElement(cur);\n }\n return parent === root ? cur : null;\n }\n}\n","import { Injectable } from '@angular/core';\n\nimport { composedParentElement } from 'forty-cdk/core';\n\n@Injectable({ providedIn: 'root' })\nexport class ModalActivationOrder {\n readonly #held = new Map<HTMLElement, (() => void)[]>();\n\n hold(host: HTMLElement): void {\n this.#held.set(host, []);\n }\n\n enclosingHeld(node: Element | null): HTMLElement | null {\n let cursor: Element | null = node;\n while (cursor !== null) {\n if (cursor instanceof HTMLElement && this.#held.has(cursor)) {\n return cursor;\n }\n cursor = composedParentElement(cursor);\n }\n return null;\n }\n\n after(enclosing: HTMLElement | null, activate: () => void): void {\n const queue = enclosing === null ? undefined : this.#held.get(enclosing);\n if (queue === undefined) {\n activate();\n } else {\n queue.push(activate);\n }\n }\n\n release(host: HTMLElement): void {\n const queue = this.#held.get(host);\n if (queue === undefined) {\n return;\n }\n this.#held.delete(host);\n for (const activate of queue) {\n activate();\n }\n }\n}\n","import { DestroyRef, ElementRef, inject, type Signal } from '@angular/core';\n\nimport { injectPortal } from 'forty-cdk/core';\n\n/**\n * The members a modal surface's internal context adds for its backdrop piece. `ForDialog` and\n * `ForDrawer` implement them through `ModalSurfaceBase`.\n */\nexport interface ModalSurfaceBackdropContext {\n /**\n * The surface's host element, which the backdrop is portaled immediately before. `null` when no\n * surface host is rendered, and the backdrop is then appended to the container.\n */\n surfaceElement(): HTMLElement | null;\n /**\n * Whether the surface is the topmost layer owning the pointer channel, so a press on its\n * backdrop is not an outside press of a layer stacked above it.\n */\n isTopmostPointerLayer(): boolean;\n /**\n * Registers the backdrop as part of the surface, so the dismissible layer treats a press on it\n * as inside. The newest registration is the surface's backdrop, and a second one still mounted\n * once the render settles warns in dev mode.\n */\n registerBackdrop(el: HTMLElement): void;\n /** Removes a registered backdrop, leaving any newer registration in place. */\n unregisterBackdrop(el: HTMLElement): void;\n}\n\n/** What a backdrop piece reads off the modal surface that owns it. */\nexport interface ModalBackdropSurface extends ModalSurfaceBackdropContext {\n /** Portal target shared with the surface. `null` ⇒ `document.body`. */\n readonly container: Signal<HTMLElement | null>;\n /** Asks the surface to close with reason `'backdrop'`, gated on its `dismissible()`. */\n requestClose(reason: 'backdrop'): void;\n}\n\n/** Host listeners {@link injectModalBackdrop} hands back to the backdrop piece. */\nexport interface ModalBackdropHandle {\n /** Bind to the backdrop host's `(pointerdown)`. */\n readonly pointerDown: () => void;\n /** Bind to the backdrop host's `(click)`. */\n readonly click: (event: MouseEvent) => void;\n}\n\n/**\n * Wires a modal surface's backdrop piece: portals the host to the surface's container, registers\n * it on the surface for the piece's lifetime, and closes the surface with reason `'backdrop'` on a\n * click that lands on the backdrop itself.\n *\n * The backdrop lands immediately before its surface in the container, so two positioned elements\n * with no `z-index` paint the surface on top, and each backdrop of a stacked pair sits directly\n * below its own surface.\n *\n * The click closes the surface only when the surface was the topmost pointer layer as the press\n * began. A press that goes down while another layer is stacked above it (a nested drawer without a\n * backdrop of its own, a popover open inside the dialog) is that layer's outside press, so the\n * click ending it leaves the surface beneath open. A click with no preceding `pointerdown` is\n * judged on the stack as it stands.\n *\n * Must be called from the backdrop directive's injection context.\n */\nexport function injectModalBackdrop(surface: ModalBackdropSurface): ModalBackdropHandle {\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n injectPortal({ target: surface.container, before: () => surface.surfaceElement() });\n surface.registerBackdrop(host);\n inject(DestroyRef).onDestroy(() => surface.unregisterBackdrop(host));\n\n let pressOwned: boolean | null = null;\n return {\n pointerDown: () => {\n pressOwned = surface.isTopmostPointerLayer();\n },\n click: (event) => {\n const owned = pressOwned ?? surface.isTopmostPointerLayer();\n pressOwned = null;\n if (event.target === host && owned) {\n surface.requestClose('backdrop');\n }\n },\n };\n}\n","import {\n computed,\n DestroyRef,\n DOCUMENT,\n ElementRef,\n inject,\n type Signal,\n signal,\n} from '@angular/core';\n\nimport {\n afterNextRenderCancellable,\n composedContains,\n composedParentElement,\n createVetoableEvent,\n createVetoableNativeEvent,\n findFirstFocusable,\n injectFocusTrap,\n injectPortal,\n isInitialFocusTarget,\n MODAL_EXEMPT_ATTRIBUTE,\n ModalOwnedRegions,\n resolveActiveElement,\n ReturnFocusResolver,\n type VetoableEvent,\n type VetoableNativeEvent,\n} from 'forty-cdk/core';\nimport { BodyScrollLock } from '../body-scroll-lock/body-scroll-lock';\nimport { injectDismissibleLayer } from '../dismissible-layer/dismissible-layer';\nimport { type InertSiblingsHandle, InertSiblingsStack } from '../inert-siblings/inert-siblings';\nimport { ModalPeerRegistry } from '../inert-siblings/modal-peer-registry';\nimport { buildOutsideVetoOptions, outsideVetoChannels } from '../dismissible-layer/outside-veto';\nimport { ModalActivationOrder } from './modal-activation-order';\n\n/**\n * Dismissal wiring for a modal surface.\n *\n * Each channel builds one `VetoableNativeEvent` and hands it to both the specific emitter and the\n * composite `interactOutside` one, so a `preventDefault()` from either suppresses the close. When\n * nothing vetoes and `dismissible()` is `true`, the shell calls `requestClose` with the reason\n * matching the channel.\n *\n * `exemptElements` is re-read on every event, so elements portaled after activation are honoured.\n */\nexport interface ModalShellDismissConfig {\n /** Whether dismissals via the layer fire the implicit `requestClose`. */\n readonly dismissible: Signal<boolean>;\n /** Called with the matching reason when the consumer doesn't veto. */\n readonly requestClose: (reason: 'escape' | 'pointerDownOutside' | 'focusOutside') => void;\n /** Forwards the Escape `VetoableNativeEvent` to the directive's `(escapeKeyDown)` output. */\n readonly emitEscapeKeyDown: (veto: VetoableNativeEvent<KeyboardEvent>) => void;\n /** Forwards the pointer-down-outside veto to the directive's `(pointerDownOutside)` output. */\n readonly emitPointerDownOutside: (veto: VetoableNativeEvent<PointerEvent>) => void;\n /** Forwards the focus-outside veto to the directive's `(focusOutside)` output. */\n readonly emitFocusOutside: (veto: VetoableNativeEvent<FocusEvent>) => void;\n /** Forwards the composite veto to the directive's `(interactOutside)` output. */\n readonly emitInteractOutside: (veto: VetoableNativeEvent<PointerEvent | FocusEvent>) => void;\n /**\n * Live \"elements that count as inside\" set — Drawer uses this to exempt\n * its portaled backdrop so a backdrop click routes through the backdrop's\n * own `requestClose('backdrop')` path instead of `pointerDownOutside`.\n *\n * The shell always merges every `MODAL_EXEMPT_ATTRIBUTE` overlay (e.g. toast\n * viewports) on top of whatever this returns, so a primitive only lists its\n * *own* extra exemptions here. It is handed the node being tested.\n */\n readonly exemptElements?: (target: Node) => readonly Element[];\n}\n\n/**\n * Primitive-owned initial-focus algorithm for the surface. The richer\n * alternative to the `'first' | 'container'` literal: the shell sets up the\n * focus trap (Tab cycling + return capture) WITHOUT its own imperative focus\n * move, runs the optional `veto`, and — unless vetoed — calls `move()`. When\n * `move()` returns `false` (no candidate found) focus falls back to the trap\n * container (modal) or the first focusable descendant (non-modal).\n *\n * Mirrors `OverlayShellInitialFocusConfig` so a content directive can hand the\n * same focus algorithm to either shell. Used by Select (selected → first →\n * last option) and available for a future date-picker calendar-cell move.\n */\nexport interface ModalShellInitialFocusConfig {\n /** Primitive focus algorithm. Returns `true` on success, `false` to fall back. */\n readonly move: () => boolean;\n /** `(autoFocusOnOpen)` veto. Returning `true` skips the imperative focus move. */\n readonly veto?: () => boolean;\n}\n\n/**\n * Single config for the free-floating modal-overlay lifecycle. Mirrors the\n * `injectOverlayShell` shape on the trigger-anchored side. Each sub-bundle\n * is individually optional so a primitive can opt out of the channels it\n * doesn't need (e.g. a dismiss-less confirm dialog, though none ship today).\n */\nexport interface ModalShellConfig {\n /** Whether the surface activates focus-trap + scroll-lock + inert siblings. */\n readonly modal: Signal<boolean>;\n /**\n * Whether focus returns to the previously-focused element on destroy. No effect in non-modal\n * mode, where the shell never moves focus on close.\n */\n readonly returnFocus: Signal<boolean>;\n /**\n * Overrides the return-focus target, read at close time instead of captured in the constructor.\n * A `null` value falls back to the construction-time capture.\n *\n * Supply it when the surface may be constructed while focus lives inside another surface that is\n * about to be destroyed — a close→open modal swap in one change-detection pass — where the\n * captured element would be disconnected by close time and focus would fall back to `<body>`.\n *\n * Read only in modal mode, and only under the same gate as the construction-time capture:\n * {@link returnFocus} is `true` and `autoFocusOnClose` did not veto.\n */\n readonly returnFocusTarget?: Signal<HTMLElement | null>;\n /**\n * Where to send focus on mount. Two shapes:\n * - `Signal<'first' | 'container'>` — `'first'` = first focusable descendant\n * (falls back to host); `'container'` = host element. Same vocabulary as\n * `FocusTrap.activate({ initialFocus })`. Used by Dialog / Drawer /\n * date-picker.\n * - {@link ModalShellInitialFocusConfig} — a primitive-owned `move()`\n * algorithm (e.g. Select's selected → first → last option) with its own\n * open-veto, falling back to the container / first focusable on a miss.\n */\n readonly initialFocus: Signal<'first' | 'container'> | ModalShellInitialFocusConfig;\n /**\n * Element the consumer marked as the initial focus target, read once at mount. Honoured with the\n * literal `initialFocus` form only: when it resolves to an element that passes\n * `isInitialFocusTarget`, focus lands there, and otherwise the literal applies.\n */\n readonly initialFocusTarget?: () => HTMLElement | null;\n /**\n * `(autoFocusOnOpen)` veto. Bound as a function reference (not as an\n * Angular `output()`) so the shell can invoke it during the destroy hook\n * without depending on `OutputEmitterRef` lifecycle. Read at every mount;\n * a `preventDefault()` on the emitted event skips the imperative initial\n * focus move while still leaving the focus-trap (Tab cycling, return\n * capture) wired in modal mode.\n */\n readonly autoFocusOnOpen?: () => ((event: VetoableEvent) => void) | undefined;\n /**\n * `(autoFocusOnClose)` veto. Same shape as `autoFocusOnOpen`. Fired\n * synchronously from the shell's release (at close intent, or from the\n * destroy hook), BEFORE the modal / non-modal teardown so it runs reliably\n * on every close path — including a direct `open.set(false)` from the\n * consumer that bypasses any close-output emission.\n */\n readonly autoFocusOnClose?: () => ((event: VetoableEvent) => void) | undefined;\n /**\n * Portal target for the surface. A signal so it is read once at the first\n * render (the portal moves the host once), after the consumer's input is\n * bound. `undefined` / a signal yielding `null` ⇒ `document.body`.\n */\n readonly container?: Signal<HTMLElement | null>;\n /** Optional dismiss bundle. Absent for primitives that don't dismiss via the layer. */\n readonly dismiss?: ModalShellDismissConfig;\n}\n\n/** Imperative handle returned by `injectModalShell`. */\nexport interface ModalShellHandle {\n /** True while the shell activated focus-trap + scroll-lock + inert (modal mode). */\n readonly isModal: () => boolean;\n /**\n * The mode the surface is in: {@link ModalShellConfig.modal} until the shell activates, then the\n * mode it activated with, for the rest of the mount. Bind modality attributes to this so they\n * never disagree with the trap, the inert siblings and the scroll lock.\n */\n readonly modal: Signal<boolean>;\n /**\n * Whether the surface's dismissible layer is active and no layer owning the pointer channel is\n * stacked above it, so an outside press is the surface's to handle.\n */\n readonly isTopmostPointerLayer: () => boolean;\n readonly release: (returnFocusTarget?: HTMLElement | null) => void;\n}\n\n/**\n * Resolves the live set of independent overlay surfaces that opt out of every\n * modal's dismissible layer via {@link MODAL_EXEMPT_ATTRIBUTE} — today\n * `ForToastViewport`. Queried fresh on each interaction (no snapshot) so a\n * surface mounted *after* the modal opened still counts as \"inside\", which is\n * exactly the toast-over-open-dialog case. An interaction inside any returned\n * element therefore never dismisses the modal.\n */\nexport function resolveModalExemptOverlays(doc: Document): readonly Element[] {\n return Array.from(doc.querySelectorAll(`[${MODAL_EXEMPT_ATTRIBUTE}]`));\n}\n\n/**\n * Owns the lifecycle of a free-floating modal surface — the overlay primitives that mount as their\n * own root, `[forDialog]` and `[forDrawer]` today.\n *\n * The shell captures the return-focus target, portals the host to `document.body` (or to\n * `config.container`), and activates the dismissible layer. In modal mode it additionally inerts\n * the siblings, activates the focus trap and locks scroll, all scoped to `config.container` when\n * one is supplied; in non-modal mode it only performs the initial focus move. A modal host carrying\n * `aria-modal=\"true\"` also claims `ModalOwnedRegions` until it releases, so the live regions and\n * exempt toast viewports outside it stay in its accessibility subtree.\n *\n * Teardown reverses that order on destroy, deactivating inert siblings before focus returns so the\n * target is not blocked by an inert ancestor.\n *\n * Must be called from an injection context. The host's `ElementRef` is forwarded to every\n * collaborator, so the caller never wires them up directly.\n */\nexport function injectModalShell(config: ModalShellConfig): ModalShellHandle {\n const host = inject<ElementRef<HTMLElement>>(ElementRef);\n const document = inject(DOCUMENT);\n const focusTrap = injectFocusTrap();\n const dismissible = injectDismissibleLayer();\n const inertStack = inject(InertSiblingsStack);\n const peerRegistry = inject(ModalPeerRegistry);\n const scrollLock = inject(BodyScrollLock);\n const returnFocus = inject(ReturnFocusResolver);\n const modalOwnedRegions = inject(ModalOwnedRegions);\n\n // 1. Capture the return-focus target SYNCHRONOUSLY, before any side effect\n // runs. WebKit (#136) blurs the previously-focused element as soon as\n // `inert` is applied to an ancestor, so by the time `afterNextRender`\n // fires the focus trap could no longer read the trigger from\n // `document.activeElement`. Reading it now locks the trigger in.\n //\n // Resolved through open shadow roots (#1586): a raw `document.activeElement`\n // reports the shadow *host* when the trigger lives inside one — a consumer\n // component using `ViewEncapsulation.ShadowDom`, or a design-system web\n // component — and that host is typically not focusable, so return-focus\n // would silently drop to `<body>` on close. Because this target is always\n // passed to `trap.activate()`, the trap's own shadow-aware capture never\n // runs for a modal surface; this is the one that has to resolve.\n const active = resolveActiveElement(document);\n let returnFocusTarget: HTMLElement | null = active instanceof HTMLElement ? active : null;\n\n const order = inject(ModalActivationOrder);\n order.hold(host.nativeElement);\n let origin: Element | null = null;\n let enclosing: HTMLElement | null = null;\n afterNextRenderCancellable(() => {\n origin = composedParentElement(host.nativeElement);\n enclosing = order.enclosingHeld(origin);\n });\n\n // 2. Portal — moves the host to `document.body` after first render and\n // cleans up on destroy. `DestroyRef.onDestroy` callbacks fire in\n // registration order (FIFO), and the portal registers its hook here,\n // before the shell's own destroy hook below. That hook does not remove\n // the host synchronously in a browser: it waits for the next frame and\n // for any finite exit animation, so the shell runs return-focus while the\n // host is still attached. The ordering is harmless either way:\n // return-focus targets the previously-focused element (the trigger,\n // captured synchronously above), which lives OUTSIDE the portaled host.\n injectPortal(config.container ? { target: config.container } : {});\n\n // Captured at mount time so the destroy path can mirror the same mode the\n // shell activated, regardless of any `modal()` toggle on a doomed\n // instance.\n let activatedAsModal = false;\n const activatedMode = signal<boolean | null>(null);\n let inertHandle: InertSiblingsHandle | null = null;\n let activatedContainer: HTMLElement | null = null;\n let releaseOwnedRegions: (() => void) | null = null;\n\n const resolveMarkedTarget = (): HTMLElement | null => {\n const target = config.initialFocusTarget?.() ?? null;\n return target !== null && isInitialFocusTarget(target, host.nativeElement) ? target : null;\n };\n\n // 3. Side-effect setup runs after Angular has applied input bindings.\n // Reading `config.modal()` etc. in the constructor would always see the\n // default value because the input writes haven't flowed through yet.\n // `afterNextRenderCancellable` makes the destroy-before-render path safe.\n // On the true-async path (queued render after destroy) the callback is\n // cancelled, so inert siblings / focus trap / scroll lock / dismissible\n // layer are never activated (`activatedAsModal` stays false). On the\n // synchronous-teardown path the callback flushes just before the destroy\n // hook, so it sets `activatedAsModal = true` and the destroy hook below\n // tears the side-effect stack back down. Either way nothing leaks.\n let released = false;\n let releasePeer: (() => void) | null = null;\n const activate = (deferred: boolean): void => {\n if (deferred) {\n const current = resolveActiveElement(document);\n if (\n current instanceof HTMLElement &&\n enclosing !== null &&\n composedContains(enclosing, current)\n ) {\n returnFocusTarget = current;\n }\n }\n const isModal = config.modal();\n activatedAsModal = isModal;\n activatedMode.set(isModal);\n\n // 3a. Dismissible layer. Pushed onto the stack BEFORE moving focus so\n // focusin events triggered by our own focus management land on this\n // layer, not on whatever lower layer was previously topmost.\n //\n // Outside channels are self-closing: `buildOutsideVetoOptions` builds\n // one veto per physical interaction and hands it to both the specific\n // (pointer-down-outside / focus-outside) and the composite\n // `interactOutside` emitter, so a `preventDefault()` in either handler\n // vetoes the close.\n const dismissCfg = config.dismiss;\n if (dismissCfg !== undefined) {\n dismissible.activate({\n channels: outsideVetoChannels(dismissCfg),\n modal: isModal,\n exemptElements: (target) => [\n ...(dismissCfg.exemptElements?.(target) ?? []),\n ...resolveModalExemptOverlays(document),\n ],\n onEscapeKeyDown: (event) => {\n const veto = createVetoableNativeEvent(event);\n dismissCfg.emitEscapeKeyDown(veto);\n if (!veto.defaultPrevented && dismissCfg.dismissible()) {\n event.stopPropagation();\n dismissCfg.requestClose('escape');\n }\n },\n ...buildOutsideVetoOptions(dismissCfg),\n });\n }\n\n // 3b. Resolve the initial-focus config. The simple form is a\n // `Signal<'first' | 'container'>` (Dialog / Drawer / date-picker); the\n // richer form carries a primitive-owned `move()` algorithm (Select's\n // selected → first → last option) plus its own veto. A `Signal` is\n // callable, so `typeof === 'function'` distinguishes the two shapes;\n // the literal mode is read eagerly only in the simple form.\n const initialFocusCfg = config.initialFocus;\n const moveCfg: ModalShellInitialFocusConfig | null =\n typeof initialFocusCfg === 'function' ? null : initialFocusCfg;\n const literalFocus: 'first' | 'container' | null =\n typeof initialFocusCfg === 'function' ? initialFocusCfg() : null;\n const markedTarget = literalFocus === null ? null : resolveMarkedTarget();\n\n // 3c. `(autoFocusOnOpen)` veto — read once for this mount. The move-config\n // carries its own boolean veto (mirroring `injectOverlayShell`); the\n // simple form routes through the top-level `autoFocusOnOpen` callback.\n let skipInitialFocus: boolean;\n if (moveCfg) {\n skipInitialFocus = moveCfg.veto?.() ?? false;\n } else {\n const autoFocusOpenEvent = createVetoableEvent();\n config.autoFocusOnOpen?.()?.(autoFocusOpenEvent);\n skipInitialFocus = autoFocusOpenEvent.defaultPrevented;\n }\n\n if (isModal) {\n // 3d. Modal mode. Inert + aria-hide siblings BEFORE the focus trap\n // activates so the trap's `focus()` call lands on an\n // already-isolated tree. The return-focus target was captured\n // synchronously above (#136).\n const containerEl = config.container?.() ?? null;\n inertHandle = inertStack.activate(host.nativeElement, containerEl ?? undefined);\n activatedContainer = containerEl;\n if (host.nativeElement.getAttribute('aria-modal') === 'true') {\n releaseOwnedRegions = modalOwnedRegions.claim(host.nativeElement);\n }\n if (moveCfg) {\n // The primitive owns the focus move. Set up Tab cycling + return\n // capture WITHOUT the trap's own imperative focus, then run the\n // algorithm; fall back to the container when it finds no candidate.\n focusTrap.activate({\n preventInitialFocus: true,\n returnFocus: returnFocusTarget,\n });\n if (!skipInitialFocus && !moveCfg.move()) {\n focusTrap.container.focus();\n }\n } else {\n focusTrap.activate({\n initialFocus: markedTarget ?? literalFocus ?? 'first',\n preventInitialFocus: skipInitialFocus,\n returnFocus: returnFocusTarget,\n });\n }\n scrollLock.lock(containerEl ?? undefined);\n } else {\n // 3e. Non-modal mode. No trap, no scroll lock, no inert. Still respect\n // the configured initial focus: the primitive's `move()` algorithm\n // (falling back to the first focusable on a miss), the first\n // focusable descendant ('first'), or the host ('container').\n releasePeer = peerRegistry.registerPeer(\n host.nativeElement,\n [origin, returnFocusTarget].filter((anchor): anchor is Element => anchor !== null),\n );\n if (!skipInitialFocus) {\n const el = focusTrap.container;\n if (moveCfg) {\n if (!moveCfg.move()) {\n (findFirstFocusable(el) ?? el).focus();\n }\n } else if (markedTarget) {\n markedTarget.focus();\n } else if (literalFocus === 'container') {\n el.focus();\n } else {\n (findFirstFocusable(el) ?? el).focus();\n }\n }\n }\n };\n afterNextRenderCancellable(() => {\n let synchronous = true;\n order.after(enclosing, () => {\n if (!released) {\n activate(!synchronous);\n }\n order.release(host.nativeElement);\n });\n synchronous = false;\n });\n\n // 4. Release. Tears the side-effect stack down in the inverse order it was\n // activated, once: from `release()` at close intent when a manager drives\n // the exit animation, else from the destroy hook. Destroy hooks fire in\n // registration order; the portal's was registered inside `injectPortal()`\n // (above) so it runs BEFORE ours, scheduling the element's removal for\n // after the next frame and any finite exit animation.\n const release = (target?: HTMLElement | null): void => {\n if (released) {\n return;\n }\n released = true;\n order.release(host.nativeElement);\n releasePeer?.();\n releasePeer = null;\n dismissible.deactivate();\n // Invoke `(autoFocusOnClose)` synchronously, BEFORE either the modal or\n // non-modal teardown runs. Fires on every close path regardless of mode\n // (the consumer's `(dismiss)` flow AND a direct `open.set(false)` that\n // bypasses any close-output emission). The callback is a plain function\n // reference — input signals stay readable during destroy and there is no\n // dependency on `OutputEmitterRef` lifecycle. Non-modal mode never moves\n // focus on close, so `skipReturnFocus` is only consulted in the modal\n // branch — but the hook still fires for symmetry with the manager and so\n // consumers can wire their own focus moves on close in non-modal mode.\n const autoFocusCloseEvent = createVetoableEvent();\n config.autoFocusOnClose?.()?.(autoFocusCloseEvent);\n const skipReturnFocus = autoFocusCloseEvent.defaultPrevented;\n if (activatedAsModal) {\n // Lift inert + aria-hide BEFORE moving focus back: an `inert` ancestor\n // blocks `.focus()` on its descendants, so the return-focus target\n // needs to be live again first.\n inertHandle?.deactivate();\n inertHandle = null;\n releaseOwnedRegions?.();\n releaseOwnedRegions = null;\n const shouldReturnFocus = config.returnFocus() && !skipReturnFocus;\n const overrideTarget = target === undefined ? (config.returnFocusTarget?.() ?? null) : target;\n // Suppress the dismissible-layer dispatcher across focus-return so the\n // synthetic `focusin` triggered by `.focus()`-ing the previous element\n // does not cascade-dismiss whatever modal is now topmost (a stacked\n // dialog opened above this one).\n dismissible.suppress(() => {\n focusTrap.deactivate({ returnFocus: false });\n if (shouldReturnFocus) {\n returnFocus.resolve(overrideTarget, returnFocusTarget)?.focus();\n }\n });\n scrollLock.unlock(activatedContainer ?? undefined);\n }\n };\n inject(DestroyRef).onDestroy(() => release());\n\n return {\n isModal: () => activatedAsModal,\n modal: computed(() => activatedMode() ?? config.modal()),\n isTopmostPointerLayer: () => dismissible.isTopmostFor('pointer'),\n release,\n };\n}\n","import { DestroyRef, ElementRef, inject, Injectable, type Signal } from '@angular/core';\n\n/** The trigger state a modal-shell surface reads to recognise its own trigger. */\nexport interface ModalTriggerConfig {\n /** The trigger's open state. */\n readonly open: Signal<boolean>;\n /** The id of the surface the trigger controls, or `null` when unset. */\n readonly controls: Signal<string | null>;\n}\n\ninterface ModalTriggerEntry extends ModalTriggerConfig {\n readonly element: HTMLElement;\n}\n\n/**\n * The mounted triggers that toggle a modal-shell surface. A surface counts its own controlling\n * triggers as inside itself for outside-press and outside-focus dismissal, so the press that\n * precedes a trigger's toggling click never closes the surface the click is about to close.\n */\n@Injectable({ providedIn: 'root' })\nexport class ModalTriggerRegistry {\n readonly #entries = new Set<ModalTriggerEntry>();\n\n /** Adds a trigger and returns the function that removes it. */\n register(entry: ModalTriggerEntry): () => void {\n this.#entries.add(entry);\n return () => this.#entries.delete(entry);\n }\n\n /**\n * The open triggers controlling `surface`: those whose `controls` names the surface's id, and\n * those with no `controls`, which name no surface and so count as controlling any open one.\n */\n controlling(surface: HTMLElement): HTMLElement[] {\n const out: HTMLElement[] = [];\n for (const entry of this.#entries) {\n if (!entry.open()) {\n continue;\n }\n const controls = entry.controls();\n if (controls === null || (controls !== '' && controls === surface.id)) {\n out.push(entry.element);\n }\n }\n return out;\n }\n}\n\n/**\n * Registers the host as a trigger toggling a modal-shell surface, for as long as the host lives.\n * Must be called from an injection context.\n */\nexport function injectModalTrigger(config: ModalTriggerConfig): void {\n const element = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n const release = inject(ModalTriggerRegistry).register({ ...config, element });\n inject(DestroyRef).onDestroy(release);\n}\n","import {\n booleanAttribute,\n computed,\n Directive,\n ElementRef,\n inject,\n input,\n output,\n signal,\n type Signal,\n} from '@angular/core';\n\nimport {\n hostAriaLabel,\n hostDescribedBy,\n hostLabelledBy,\n type SingleSlot,\n type VetoableEvent,\n type VetoableNativeEvent,\n} from 'forty-cdk/core';\nimport { type ModalShellConfig, type ModalShellHandle } from './modal-shell';\nimport { ModalTriggerRegistry } from './modal-trigger';\n\n/**\n * Abstract base for free-floating modal-surface primitives — a directive that\n * mounts a modal surface as its own root, coordinates label / description\n * registration, and drives its lifecycle through {@link injectModalShell}.\n * `ForDialog` and `ForDrawer` extend it; a future modal Toast / full-screen\n * sheet / command palette can too.\n *\n * The base owns everything the two surfaces used to duplicate verbatim: the\n * `aria-labelledby` / `aria-describedby` registry, the backdrop registration,\n * the exemption of the backdrop and of the controlling triggers\n * (`injectModalTrigger`) from outside dismissal,\n * the `requestClose` dismissible gating, the `lastCloseValue` bridge read by\n * the programmatic managers, the seven shared ARIA / state host bindings (`role`, `aria-modal`, `aria-label`,\n * `aria-labelledby`, `aria-describedby`, `data-state=\"open\"`, `tabindex=\"-1\"`),\n * the non-defaults inputs and dismiss outputs, and the {@link modalShellConfig}\n * factory. Anything primitive-specific (Drawer's drag / snap / scale / stack,\n * the four defaults-backed inputs each subclass seeds from its own\n * `FOR_<PRIMITIVE>_DEFAULTS`) stays on the subclass.\n *\n * The base does **not** call {@link injectModalShell} itself —\n * each subclass calls `injectModalShell(this.modalShellConfig())` from its own\n * constructor. A base-owned call would register its `afterNextRender` during\n * `super()`, before a subclass (Drawer) could register its own pre-shell\n * `afterNextRender` (stack push + snap validation), breaking the documented\n * ordering.\n *\n * Implemented as an `@Directive()`-decorated abstract class because Angular\n * recognises signal inputs / outputs and host bindings only when the\n * `input()` / `output()` calls and the `host` block appear on a decorated\n * class; inheritance is the supported mechanism for sharing them across\n * directives.\n *\n * Internal core tier — exported from `forty-cdk/core-overlay` for the\n * library's own entry points, with no semver guarantee. Subclassing a library\n * base is not a supported contract, so it is absent from `CORE_PUBLISHERS` and\n * from every primitive's own barrel; the public-types gate ignores\n * `extends`-only heritage, which is why the base may appear in the shipped\n * `.d.ts` as the parent of `[forDialog]` / `[forDrawer]` without being blessed.\n */\n@Directive({\n host: {\n '[attr.role]': 'alert() ? \"alertdialog\" : \"dialog\"',\n '[attr.aria-modal]': 'modalInEffect() ? \"true\" : null',\n '[attr.aria-label]': 'resolvedAriaLabel()',\n 'data-state': 'open',\n tabindex: '-1',\n },\n})\nexport abstract class ModalSurfaceBase<Reason extends string> {\n /** When true, role becomes `alertdialog` (interrupts assistive tech). */\n readonly alert = input(false, { transform: booleanAttribute });\n\n /**\n * Explicit element focus returns to on close, read at close time. Overrides\n * the element the shell captures at construction — supply it when this\n * surface can be constructed while focus lives inside a *different, doomed*\n * surface, the canonical case being a close→open swap in one change-detection\n * pass. The programmatic managers thread the true origin through this input\n * automatically; declarative consumers driving such a swap by hand can bind\n * it too. `null` (default) keeps the construction-time capture, so ordinary\n * usage is unaffected. Has no effect in non-modal mode (the shell never moves\n * focus on close then).\n */\n readonly returnFocusTarget = input<HTMLElement | null>(null);\n\n /** Manual `aria-label`. Use this when no visible title element exists. */\n readonly ariaLabel = input<string | null>(null);\n\n /**\n * Resolved `aria-label`: a consumer-set static value on the surface when\n * present, else the {@link ariaLabel} input.\n */\n private readonly resolvedAriaLabel = hostAriaLabel(() => this.ariaLabel() || null);\n\n /**\n * Portal target for the surface. Defaults to `document.body`. Pair with\n * `[modal]=\"false\"` for a surface scoped to a positioned region instead of\n * the viewport. Read once at mount. The backdrop portals to the same\n * container.\n */\n readonly container = input<HTMLElement | null>(null);\n\n /**\n * Callback invoked just before the surface moves focus into itself on mount.\n * Receives a `VetoableEvent`; call `event.preventDefault()` to skip the\n * imperative focus move — useful when opening from an input you want to keep\n * focused. The focus trap (modal mode) still cycles Tab inside the surface\n * once focus enters it.\n *\n * Bound as a function reference (`[autoFocusOnOpen]=\"onOpen\"`), not as an\n * event binding. The callback shape (rather than an `output()`) lets the\n * shell invoke it during the destroy hook without depending on Angular's\n * `OutputEmitterRef` lifecycle.\n */\n readonly autoFocusOnOpen = input<((event: VetoableEvent) => void) | undefined>(undefined);\n\n /**\n * Callback invoked just before focus returns to the previously focused\n * element on unmount. Receives a `VetoableEvent`; call\n * `event.preventDefault()` to skip the return-focus — useful when the\n * consumer wants to send focus elsewhere imperatively. Fires reliably on\n * both close paths: the `(dismiss)` output flow AND a direct\n * `open.set(false)` from the consumer.\n */\n readonly autoFocusOnClose = input<((event: VetoableEvent) => void) | undefined>(undefined);\n\n /**\n * Whether dismiss interactions (Escape, backdrop, outside interaction, and\n * any primitive-specific gesture) close the surface. Implemented by the\n * subclass so its default can be seeded from the primitive's scope defaults.\n */\n abstract readonly dismissible: Signal<boolean>;\n\n /**\n * Whether the surface activates modal semantics (`aria-modal`, focus trap,\n * body scroll lock, inert siblings). Read once at mount: a later change takes\n * effect on the next mount. Implemented by the subclass so its default can be\n * seeded from the primitive's scope defaults.\n */\n abstract readonly modal: Signal<boolean>;\n\n /**\n * Whether focus returns to the previously focused element on close.\n * Implemented by the subclass so its default can be seeded from the\n * primitive's scope defaults.\n */\n abstract readonly returnFocus: Signal<boolean>;\n\n /**\n * Where to send focus on mount — `'first'` (first focusable descendant) or\n * `'container'` (the surface host). Implemented by the subclass so its\n * default can be seeded from the primitive's scope defaults.\n */\n abstract readonly initialFocus: Signal<'first' | 'container'>;\n\n /**\n * Entry-point name the shared surface errors report under, e.g. `'dialog'`.\n * The subclass supplies it because the shell's checks are shared while the\n * `[forty-cdk/<scope>]` prefix a consumer reads must name the primitive they\n * actually wrote.\n */\n protected abstract readonly entryPoint: string;\n\n /**\n * The element the primitive's initial-focus marker registered inside the surface, or `null`.\n * Implemented by the subclass, which owns the marker's registration slot. The shell focuses it on\n * mount when it is a usable target, and falls back to {@link initialFocus} otherwise.\n */\n protected abstract readonly initialFocusTarget: Signal<HTMLElement | null>;\n\n /**\n * The slot the primitive's backdrop piece registers into. Implemented by the subclass, so the\n * dev-mode duplicate warning names the primitive's own surface and backdrop selectors.\n */\n protected abstract readonly backdropSlot: SingleSlot<HTMLElement>;\n\n /**\n * Emitted when the surface wants to close. Consumers wire this to flip the\n * signal that gates the surrounding `@if`. The reason union is\n * primitive-specific.\n */\n readonly dismiss = output<Reason>();\n\n /**\n * Fires when the user presses Escape while this surface is the topmost\n * dismissible layer. Call `preventDefault()` on the emitted veto to suppress\n * the subsequent `(dismiss)` emission. The original `KeyboardEvent` is on\n * `.event`.\n */\n readonly escapeKeyDown = output<VetoableNativeEvent<KeyboardEvent>>();\n\n /**\n * Fires when a pointer goes down outside the surface. Call `preventDefault()`\n * on the emitted veto to suppress the auto `(dismiss)`. The native\n * `PointerEvent` is on `.event`.\n */\n readonly pointerDownOutside = output<VetoableNativeEvent<PointerEvent>>();\n\n /**\n * Fires when focus moves outside the surface. `preventDefault()` on the veto\n * suppresses the auto `(dismiss)`. The native `FocusEvent` is on `.event`.\n */\n readonly focusOutside = output<VetoableNativeEvent<FocusEvent>>();\n\n /**\n * Composite event: fires alongside `pointerDownOutside` and `focusOutside`\n * and shares their veto state — `preventDefault()` on either one suppresses\n * the auto `(dismiss)`.\n */\n readonly interactOutside = output<VetoableNativeEvent<PointerEvent | FocusEvent>>();\n\n readonly #labelIds = signal<readonly string[]>([]);\n readonly #describedByIds = signal<readonly string[]>([]);\n readonly #lastCloseValue = signal<unknown>(undefined);\n readonly #host = inject<ElementRef<HTMLElement>>(ElementRef);\n readonly #triggers = inject(ModalTriggerRegistry);\n #shell: ModalShellHandle | null = null;\n\n private readonly modalInEffect = computed(() => this.#shell?.modal() ?? this.modal());\n\n /**\n * Resolved `aria-labelledby`: a consumer-set static value when present, else\n * the space-joined ids of the registered titles, or `null` when none.\n */\n readonly labelledBy = hostLabelledBy(() => {\n const ids = this.#labelIds();\n return ids.length === 0 ? null : ids.join(' ');\n });\n\n /**\n * Resolved `aria-describedby`: a consumer-set static value composed with the\n * space-joined ids of the registered descriptions, or `null` when neither is\n * present.\n */\n readonly describedBy = hostDescribedBy(() => {\n const ids = this.#describedByIds();\n return ids.length === 0 ? null : ids.join(' ');\n });\n\n /** Register a title element's id into `aria-labelledby`. */\n registerLabel(id: string): void {\n this.#labelIds.update((arr) => (arr.includes(id) ? arr : [...arr, id]));\n }\n\n /** Remove a title element's id from `aria-labelledby`. */\n unregisterLabel(id: string): void {\n this.#labelIds.update((arr) => arr.filter((x) => x !== id));\n }\n\n /** Register a description element's id into `aria-describedby`. */\n registerDescription(id: string): void {\n this.#describedByIds.update((arr) => (arr.includes(id) ? arr : [...arr, id]));\n }\n\n /** Remove a description element's id from `aria-describedby`. */\n unregisterDescription(id: string): void {\n this.#describedByIds.update((arr) => arr.filter((x) => x !== id));\n }\n\n private surfaceElement(): HTMLElement {\n return this.#host.nativeElement;\n }\n\n private registerBackdrop(el: HTMLElement): void {\n this.backdropSlot.register(el);\n }\n\n private unregisterBackdrop(el: HTMLElement): void {\n this.backdropSlot.unregister(el);\n }\n\n /**\n * Request that the surface close. `'closeButton'` and `'programmatic'` always\n * emit `(dismiss)`; every other reason is gated on `dismissible()`. `value`\n * is the close result, captured for the programmatic managers' close bridge.\n */\n requestClose(reason: Reason, value?: unknown): void {\n if (reason !== 'closeButton' && reason !== 'programmatic' && !this.dismissible()) {\n return;\n }\n this.#lastCloseValue.set(value);\n this.dismiss.emit(reason);\n }\n\n /**\n * The `value` argument from the most recent `requestClose(reason, value)`\n * call. Read by the programmatic managers to bridge `[for…Close] [closeWith]`\n * into `For…Ref.close(value)`. Part of the internal composition surface with\n * no semver guarantee; declarative consumers never need this.\n */\n readonly lastCloseValue = this.#lastCloseValue.asReadonly();\n\n /**\n * The registered backdrop element, or `null` when none is rendered. Read by\n * the programmatic managers' surface registrar so `beginLeave` drives the\n * backdrop's exit animation by direct reference instead of a document query.\n * Part of the internal composition surface with no semver guarantee;\n * declarative consumers never need this.\n */\n readonly backdropElement = computed(() => this.backdropSlot.value());\n\n /**\n * Keeps the handle the subclass's `injectModalShell(this.modalShellConfig())` call returned, which\n * the backdrop piece reads through {@link isTopmostPointerLayer}. Called once from the subclass\n * constructor.\n */\n protected attachModalShell(shell: ModalShellHandle): void {\n this.#shell = shell;\n }\n\n /**\n * Ends the surface's modal side effects ahead of its destroy and returns focus, to\n * `returnFocusTarget` when one is passed. Called by the programmatic managers at close intent, so\n * only the DOM removal waits for the exit animation. Part of the internal composition surface\n * with no semver guarantee; declarative consumers never need this.\n */\n releaseModalShell(returnFocusTarget?: HTMLElement | null): void {\n this.#shell?.release(returnFocusTarget);\n }\n\n /**\n * Whether this surface is the topmost layer owning the pointer channel. Read by the backdrop\n * piece through the internal context to decide whether a press on it is this surface's.\n */\n private isTopmostPointerLayer(): boolean {\n return this.#shell?.isTopmostPointerLayer() ?? true;\n }\n\n protected modalShellConfig(): ModalShellConfig {\n return {\n modal: this.modal,\n returnFocus: this.returnFocus,\n returnFocusTarget: this.returnFocusTarget,\n initialFocus: this.initialFocus,\n initialFocusTarget: () => this.initialFocusTarget(),\n container: this.container,\n autoFocusOnOpen: () => this.autoFocusOnOpen(),\n autoFocusOnClose: () => this.autoFocusOnClose(),\n dismiss: {\n dismissible: this.dismissible,\n requestClose: (reason) => this.requestClose(reason as Reason),\n emitEscapeKeyDown: (veto) => this.escapeKeyDown.emit(veto),\n emitPointerDownOutside: (veto) => this.pointerDownOutside.emit(veto),\n emitFocusOutside: (veto) => this.focusOutside.emit(veto),\n emitInteractOutside: (veto) => this.interactOutside.emit(veto),\n exemptElements: () => {\n const backdrop = this.backdropSlot.value();\n const triggers = this.#triggers.controlling(this.#host.nativeElement);\n return backdrop ? [backdrop, ...triggers] : triggers;\n },\n },\n };\n }\n}\n","import { afterNextRender } from '@angular/core';\nimport { fortyWarn } from 'forty-cdk/core';\n\n/**\n * Identifies the piece in the dev-mode mounted-while-closed warning and tells\n * the helper how to read its surface's open state.\n */\nexport interface MountedWhileClosedConfig {\n /** Entry-point name used in the `[forty-cdk/<primitive>]` prefix (e.g. `'select'`). */\n readonly primitive: string;\n /**\n * Selector of the mounted piece (e.g. `'[forSelectContent]'`). A directive\n * with more than one selector resolves the one the consumer actually wrote,\n * so the report names a piece they can find in their template —\n * `[forMenuContent]` serves `[forMenuSubContent]` too.\n */\n readonly piece: string;\n /**\n * The `@if` condition the primitive's README uses, quoted back as the fix\n * (e.g. `'select.open()'`). Keep the two in sync — a consumer following the\n * link should read the same expression there.\n *\n * A thunk is resolved inside the render hook, which is what lets a condition\n * interpolate a bound input: `[forNavigationMenuContent]` quotes its owning\n * item's value, unreadable at construction (see below).\n */\n readonly condition: string | (() => string);\n /** The surface's open state, read once after the first render. */\n readonly open: () => boolean;\n}\n\n/**\n * Warns — dev mode only, once per instance — when an overlay surface is still mounted after its\n * first render while its own open state reports closed, which is the consumer forgetting the `@if`.\n *\n * It is the library's quietest first-use mistake: the surface renders permanently,\n * `data-state=\"closed\"` lands on a visible element, the ARIA stays internally consistent and the\n * primitive keeps working, so it reads as a CSS bug rather than a wiring one.\n *\n * Mount equals open is structural for these surfaces, so the `@if` is the whole contract and no\n * input suppresses the warning. Only pieces whose closed state has no supported mounted shape adopt\n * it, so the always-mounted panel families do not.\n *\n * **The check is mount-time**, reading the open state inside `afterNextRender` and never again,\n * which buys three things:\n *\n * - The exit-animation window stays silent. A closed surface is legitimately mounted for as long as\n * `animate.leave` keeps it, so re-checking on close would report every correct overlay.\n * - Bindings have settled. A piece deriving its open state from an `input.required` its parent has\n * not written yet would throw NG0950 on a construction-time read. `condition` takes a thunk for\n * the same reason, so the quoted fix is built where the input is readable.\n * - It is inert on the server, where `afterNextRender` never fires.\n *\n * The cost is a deliberate false negative: a surface that mounts open and is then left mounted\n * forever goes unreported, since catching it would mean re-checking on close.\n *\n * Must be called from an injection context. A production build registers no render hook at all.\n */\nexport function warnIfMountedWhileClosed(config: MountedWhileClosedConfig): void {\n if (typeof ngDevMode !== 'undefined' && !ngDevMode) {\n return;\n }\n\n afterNextRender(() => {\n if (config.open()) {\n return;\n }\n const condition =\n typeof config.condition === 'function' ? config.condition() : config.condition;\n fortyWarn({\n code: 'FORCDK-CORE-006',\n scope: config.primitive,\n message: `${config.piece} is mounted while the surface is closed.`,\n cause:\n \"Presence in the DOM is the consumer's job, and there is no forceMount input — a surface \" +\n 'kept mounted while closed never runs `animate.enter` / `animate.leave`, and the lifecycle ' +\n 'it sets up on mount stays live while closed.',\n fix: `Wrap it with \\`@if (${condition})\\` so it unmounts on close. See the ${config.primitive} README.`,\n });\n });\n}\n","import { afterNextRender, effect, inject, Injector, untracked } from '@angular/core';\nimport { fortyWarn } from 'forty-cdk/core';\n\n/**\n * Identifies the surface in the dev-mode open-without-content warning and tells\n * the helper how to read the root's open state and its registered content.\n */\nexport interface OpenWithoutContentConfig {\n /** Entry-point name used in the `[forty-cdk/<primitive>]` prefix (e.g. `'select'`). */\n readonly primitive: string;\n /** Selector of the content piece the open surface is missing (e.g. `'[forSelectContent]'`). */\n readonly piece: string;\n /**\n * The `@if` condition the primitive's README uses, quoted back as the fix\n * (e.g. `'select.open()'`). A thunk is resolved when the warning is built, so\n * a root whose open state is a value can quote the one that opened.\n */\n readonly condition: string | (() => string);\n /** The surface's open state. */\n readonly open: () => boolean;\n /** The registered content element, or `null` while none is mounted. */\n readonly content: () => HTMLElement | null;\n}\n\n/**\n * Warns — dev mode only, once per entry into the state — when a surface is still open after a\n * settled render with no content piece registered, which is the consumer leaving out the content\n * block or gating it on a condition that stays false.\n *\n * The state fails silently: the trigger reflects `aria-expanded=\"true\"` and references a content id\n * no element carries, and Escape and outside presses are handled by the mounted surface, so nothing\n * but the trigger can close it again.\n *\n * The check runs in the `read` phase of the render that follows the open, after every content piece\n * that render mounted has registered from its constructor, so a correctly wired `@if` never reports.\n * Closing, or a content piece registering, re-arms it. A surface mounted only after that render, from\n * a `@defer` block inside the `@if`, reports once before it arrives.\n *\n * It is inert on the server, where `afterNextRender` never fires. Must be called from an injection\n * context. A production build creates no effect at all.\n */\nexport function warnIfOpenWithoutContent(config: OpenWithoutContentConfig): void {\n if (typeof ngDevMode !== 'undefined' && !ngDevMode) {\n return;\n }\n\n const injector = inject(Injector);\n let reported = false;\n effect(() => {\n if (!config.open() || config.content() !== null) {\n reported = false;\n return;\n }\n if (reported) {\n return;\n }\n untracked(() => {\n afterNextRender(\n {\n read: () => {\n if (reported || !config.open() || config.content() !== null) {\n return;\n }\n reported = true;\n const condition =\n typeof config.condition === 'function' ? config.condition() : config.condition;\n fortyWarn({\n code: 'FORCDK-CORE-014',\n scope: config.primitive,\n message: `The surface is open, but no ${config.piece} is mounted.`,\n cause:\n 'The trigger already reflects the open state and references a content id no ' +\n 'element carries, and Escape and outside presses are handled by the mounted ' +\n 'surface, so only the trigger can close it again.',\n fix: `Render ${config.piece} inside \\`@if (${condition})\\`, with nothing else gating it. See the ${config.primitive} README.`,\n });\n },\n },\n { injector },\n );\n });\n });\n}\n","import { effect, type Signal } from '@angular/core';\n\n/** The trigger state the dev-mode missing-`[controls]` warning watches, and the warning itself. */\nexport interface UncontrolledTriggerConfig {\n /** The trigger's open state. */\n readonly open: Signal<boolean>;\n /** The id the trigger mirrors to `aria-controls`, or `null` when unset. */\n readonly controls: Signal<string | null>;\n /** Emits the primitive's own `fortyWarn`, so each primitive keeps its own code. */\n readonly warn: () => void;\n}\n\n/**\n * Warns — dev mode only — when a trigger that mirrors `[controls]` to `aria-controls` opens while\n * `controls` is unset, so the missing relationship is visible during development.\n *\n * It warns once per entry into that state: reopening without `controls` stays silent, and setting\n * then clearing it warns again. Must be called from an injection context. A production build\n * creates no effect at all.\n */\nexport function warnIfOpenWithoutControls(config: UncontrolledTriggerConfig): void {\n if (typeof ngDevMode !== 'undefined' && !ngDevMode) {\n return;\n }\n let warned = false;\n effect(() => {\n if (config.controls() !== null) {\n warned = false;\n } else if (config.open() && !warned) {\n warned = true;\n config.warn();\n }\n });\n}\n","import { afterNextRender, ElementRef, inject } from '@angular/core';\nimport { fortyWarn } from 'forty-cdk/core';\n\n/** Identifies the surface and its two naming channels in the dev-mode missing-name warning. */\nexport interface UnnamedDialogConfig {\n /** Entry-point name used in the `[forty-cdk/<primitive>]` prefix (e.g. `'dialog'`). */\n readonly primitive: string;\n /** Selector of the piece carrying the dialog role (e.g. `'[forDialog]'`). */\n readonly piece: string;\n /** Selector of the title piece that names the surface (e.g. `'[forDialogTitle]'`). */\n readonly title: string;\n /**\n * Where the consumer binds `ariaLabel` for this surface, quoted into the fix (e.g.\n * `'[forPopover]'`, whose content reads the root's input).\n */\n readonly ariaLabelOn: string;\n}\n\n/**\n * Warns — dev mode only, once per instance — when a surface carrying the dialog role has no\n * accessible name after its first render: neither an `aria-labelledby` nor a non-empty\n * `aria-label` resolved on its host.\n *\n * The attributes are read from the host inside `afterNextRender`, so a title registered during the\n * first render, a bound `ariaLabel` and a static `aria-label` attribute all count. Must be called\n * from an injection context on the surface's own host. A production build registers no render hook\n * at all, and the check is inert on the server.\n */\nexport function warnIfDialogUnnamed(config: UnnamedDialogConfig): void {\n if (typeof ngDevMode !== 'undefined' && !ngDevMode) {\n return;\n }\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n\n afterNextRender(() => {\n const label = host.getAttribute('aria-label')?.trim() ?? '';\n if (label !== '' || host.hasAttribute('aria-labelledby')) {\n return;\n }\n fortyWarn({\n code: 'FORCDK-CORE-011',\n scope: config.primitive,\n message: `${config.piece} has no accessible name.`,\n cause:\n 'Neither `aria-labelledby` nor a non-empty `aria-label` resolved on its host, so assistive ' +\n 'technology announces the surface as a bare \"dialog\". Automated audits tagged for WCAG ' +\n 'A / AA do not report it.',\n fix: `Render a ${config.title} inside it, or bind \\`ariaLabel\\` on ${config.ariaLabelOn}.`,\n });\n });\n}\n","import {\n ApplicationRef,\n type ComponentRef,\n computed,\n type DestroyableInjector,\n DestroyRef,\n DOCUMENT,\n EnvironmentInjector,\n inject,\n Injector,\n PLATFORM_ID,\n type Provider,\n type ProviderToken,\n type Signal,\n signal,\n untracked,\n} from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\n\nimport {\n composedClosest,\n composedContains,\n FOR_FIELD_ANCHOR_CONTEXT,\n FOR_FIELD_CONTEXT,\n IdGenerator,\n resolveActiveElement,\n} from 'forty-cdk/core';\nimport { ModalPeerRegistry } from '../inert-siblings/modal-peer-registry';\nimport type { OverlayRef } from './overlay-ref';\n\n/**\n * Minimal shape every overlay entry must satisfy so the shared core can index,\n * render, and tear it down. Per-primitive entries (`ForDialogEntry`,\n * `ForDrawerEntry`) extend this with their own directive-input fields and\n * narrow `ref` to their concrete `For<Primitive>Ref`. The core closes an\n * entry's ref and reads its `isClosed` flag (to tell a still-open parent apart\n * from one being swapped out during return-focus origin resolution), so the\n * base requires just those two members — both reason-agnostic, so the base\n * stays independent of each ref's close-reason union. `returnFocusTarget` is\n * the target threaded to the directive, which the core rewrites when the\n * overlay it points into closes first.\n *\n * Internal core tier — exported from `forty-cdk/core-overlay` for the\n * library's own entry points, with no semver guarantee.\n */\nexport interface OverlayManagerEntry {\n readonly id: string;\n readonly ref: Pick<OverlayRef, 'close' | 'isClosed'>;\n readonly returnFocusTarget?: HTMLElement | null;\n}\n\n/**\n * A rendered overlay's exit-animation surface, registered with the core at\n * attach time so `beginLeave` targets the exact host (and its backdrop) by\n * direct reference instead of re-querying the whole document on every close.\n *\n * `host` is the overlay root — the `[forDialog]` / `[forDrawer]` element the\n * outlet stamps. `backdrop()` reads the currently-registered\n * `[for<Primitive>Backdrop]` element **live at close time** (`null` when none\n * is rendered), preserving the \"read the backdrop when it closes\" semantics a\n * registration-time snapshot would lose.\n *\n * Part of the shared core composition surface; carries no semver guarantees.\n */\nexport interface OverlaySurface {\n readonly host: HTMLElement;\n backdrop(): HTMLElement | null;\n release(returnFocusTarget: HTMLElement | null): void;\n}\n\n/**\n * The reactive surface a manager's outlet component is wired with on first\n * `open()`. Mirrors `ForDialogOutletHost` / `ForDrawerOutletHost`.\n *\n * Internal core tier — exported from `forty-cdk/core-overlay` for the\n * library's own entry points, with no semver guarantee.\n */\nexport interface OverlayManagerOutletHost<TEntry extends OverlayManagerEntry> {\n readonly entries: Signal<readonly TEntry[]>;\n closeAllForDestroy(): void;\n /**\n * Registers a rendered entry's exit-animation surface under its id so\n * `beginLeave` can drive the leave classes by direct reference. Called from\n * the per-row surface-registrar directive's `afterNextRender` (so it also\n * runs for an entry whose mount was deferred to a later render). The core\n * drops the surface when the entry is removed.\n */\n registerSurface(id: string, surface: OverlaySurface): void;\n}\n\n/**\n * The minimal surface a manager's outlet component exposes so the core can\n * wire it on first `open()`. Mirrors `ForDialogOutlet` / `ForDrawerOutlet`.\n *\n * Internal core tier — exported from `forty-cdk/core-overlay` for the\n * library's own entry points, with no semver guarantee.\n */\nexport interface OverlayManagerOutlet<TEntry extends OverlayManagerEntry> {\n init(host: OverlayManagerOutletHost<TEntry>): void;\n}\n\n/**\n * Per-primitive bindings the shared core needs: how to name ids and the\n * exit-animation host / backdrop attributes, and how to create the outlet\n * component that renders the entries.\n *\n * Internal core tier — exported from `forty-cdk/core-overlay` for the\n * library's own entry points, with no semver guarantee.\n */\nexport interface OverlayManagerConfig<TEntry extends OverlayManagerEntry> {\n /**\n * Per-instance id prefix passed to `IdGenerator.next` (e.g.\n * `'for-dialog-instance'`).\n */\n readonly idPrefix: string;\n /**\n * Attribute the overlay root + backdrop reflect their per-instance id on\n * (e.g. `'data-for-dialog-id'`), read during return-focus origin resolution.\n */\n readonly idAttribute: string;\n /**\n * Attribute marking the portaled backdrop element (e.g.\n * `'data-for-dialog-backdrop'`), used to exclude the backdrop during\n * return-focus origin resolution.\n */\n readonly backdropAttribute: string;\n /** Creates the manager-owned outlet component (e.g. `ForDialogOutlet`). */\n createOutlet(\n environmentInjector: EnvironmentInjector,\n ): ComponentRef<OverlayManagerOutlet<TEntry>>;\n}\n\n/**\n * Shared imperative-overlay engine behind `ForDialogManager` and\n * `ForDrawerManager`. Owns the entries signal, the reactive `openCount`, the\n * lazily-created outlet, the public `closeAll()` and the destroy-time close-all\n * sweep, the exit-animation `beginLeave` driver, and the parent-cached\n * per-component `Injector` factory.\n *\n * In the browser the outlet host is appended to `document.body` before its\n * first render, as a `display: contents` modal peer, so opened content is\n * connected (and never under an `inert` ancestor) from its first render on\n * rather than only once its row is portaled.\n * The two managers differ only in their entry shape and directive-input\n * mapping; everything structural lives here once.\n *\n * Internal core tier — no semver guarantee; the public surface is\n * `ForDialogManager` / `ForDrawerManager`.\n */\nexport class OverlayManagerCore<TEntry extends OverlayManagerEntry> {\n readonly #appRef = inject(ApplicationRef);\n readonly #envInjector = inject(EnvironmentInjector);\n readonly #document = inject(DOCUMENT);\n readonly #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));\n readonly #peerRegistry = inject(ModalPeerRegistry);\n private readonly idGen = inject(IdGenerator);\n\n readonly #entries = signal<readonly TEntry[]>([]);\n readonly #surfaces = new Map<string, OverlaySurface>();\n readonly #config: OverlayManagerConfig<TEntry>;\n\n /**\n * Reactive count of the overlays this manager has open. A closed overlay stops counting once its\n * exit animation finishes.\n */\n readonly openCount = computed(() => this.#entries().length);\n\n #outletRef: ComponentRef<OverlayManagerOutlet<TEntry>> | null = null;\n #destroying = false;\n #lastReturnFocusOrigin: HTMLElement | null = null;\n #pendingRemovals = 0;\n\n constructor(config: OverlayManagerConfig<TEntry>) {\n this.#config = config;\n }\n\n /**\n * Resolves the element focus should return to when the overlay this `open()`\n * is about to register later closes — the \"true origin\". Threaded to the\n * directive's `returnFocusTarget` so `injectModalShell` restores focus there\n * instead of to whatever it happened to capture at construction (which breaks\n * on a close→open swap, where the incoming surface is built while focus still\n * lives inside the outgoing, doomed one).\n *\n * Read the currently-focused element **synchronously at `open()` time**,\n * before the render tick mounts the new overlay and swaps the DOM, and\n * classify it:\n *\n * - **Genuine outside element** (focus is on the trigger, not inside any\n * managed overlay host) → that element is the origin.\n * - **Inside a still-live managed overlay** (a stacked open on top of an open\n * overlay, or an open→close swap) → the focused element itself. Should that\n * overlay close first, `beginLeave` hands its own origin to this entry.\n * - **Inside an overlay that is closing / already gone** (a close→open swap:\n * its ref is closed, or it has left the entries list but its DOM host is\n * still mounted for this tick) → inherit the chain's origin.\n * - **No usable focus** (`<body>` / `documentElement` / none) → inherit the\n * chain's origin too.\n *\n * The chain's origin is inherited only while the chain is alive (some\n * overlay is still registered, or one was removed in the current task) and\n * only while it is still in the document; otherwise the result is `null`.\n *\n * `explicit` is the caller's `returnFocusTarget`, returned as is when it is\n * not `undefined`. An explicit element still becomes the chain's origin, so\n * a swap out of that overlay inherits it.\n *\n * Both halves of the resolution read the composed tree: the capture\n * descends through open shadow roots, so a trigger inside one is the origin\n * rather than its (usually unfocusable) host, and the \"am I inside a managed\n * overlay?\" walk climbs back out of them. The two go together — resolving the\n * deep element while classifying it with a plain `closest` would report every\n * shadow-nested trigger as an outside element.\n */\n protected resolveReturnFocusTarget(explicit?: HTMLElement | null): HTMLElement | null {\n const active = resolveActiveElement(this.#document);\n const captured = active instanceof HTMLElement ? active : null;\n const resolved = untracked(() => this.#computeReturnFocusOrigin(captured));\n this.#lastReturnFocusOrigin = explicit ?? resolved;\n return explicit === undefined ? resolved : explicit;\n }\n\n #computeReturnFocusOrigin(captured: HTMLElement | null): HTMLElement | null {\n const { body, documentElement } = this.#document;\n if (captured === null || captured === body || captured === documentElement) {\n return this.#chainOrigin();\n }\n const { idAttribute, backdropAttribute } = this.#config;\n const host = composedClosest(captured, `[${idAttribute}]:not([${backdropAttribute}])`);\n if (host === null) {\n return captured;\n }\n const hostId = host.getAttribute(idAttribute);\n const parentStillOpen = this.#entries().some(\n (entry) => entry.id === hostId && !entry.ref.isClosed(),\n );\n return parentStillOpen ? captured : this.#chainOrigin();\n }\n\n #chainOrigin(): HTMLElement | null {\n const origin = this.#lastReturnFocusOrigin;\n if (origin !== null && !origin.isConnected) {\n this.#lastReturnFocusOrigin = null;\n return null;\n }\n return this.#entries().length > 0 || this.#pendingRemovals > 0 ? origin : null;\n }\n\n #handOffReturnFocus(id: string): void {\n const entries = this.#entries();\n const closing = entries.find((entry) => entry.id === id);\n if (closing === undefined) {\n return;\n }\n const origin = closing.returnFocusTarget ?? null;\n const host = this.#surfaces.get(id)?.host ?? null;\n const inside = (target: HTMLElement | null | undefined): boolean =>\n host !== null && target != null && composedContains(host, target);\n if (origin !== null || inside(this.#lastReturnFocusOrigin)) {\n this.#lastReturnFocusOrigin = origin;\n }\n if (host === null) {\n return;\n }\n let handedOff = false;\n const next = entries.map((entry) => {\n if (entry.id === id || !inside(entry.returnFocusTarget)) {\n return entry;\n }\n handedOff = true;\n return { ...entry, returnFocusTarget: origin };\n });\n if (handedOff) {\n this.#entries.set(next);\n }\n }\n\n #releaseChainAfterTask(): void {\n if (this.#destroying || !this.#isBrowser) {\n if (this.#entries().length === 0) {\n this.#lastReturnFocusOrigin = null;\n }\n return;\n }\n this.#pendingRemovals += 1;\n setTimeout(() => {\n this.#pendingRemovals -= 1;\n if (this.#pendingRemovals === 0 && this.#entries().length === 0) {\n this.#lastReturnFocusOrigin = null;\n }\n }, 0);\n }\n\n /**\n * Generates the next per-instance id and a paired idempotent\n * `remove` that drops the entry. The caller builds the `ref` with a teardown\n * that drives the exit animation before invoking `remove`.\n */\n protected nextId(): { id: string; remove: () => void } {\n const id = this.idGen.next(this.#config.idPrefix);\n let removed = false;\n const remove = (): void => {\n if (removed) {\n return;\n }\n removed = true;\n this.#surfaces.delete(id);\n this.#entries.update((arr) => arr.filter((e) => e.id !== id));\n untracked(() => this.#releaseChainAfterTask());\n };\n return { id, remove };\n }\n\n #releaseSurface(id: string): void {\n const entry = this.#entries().find((candidate) => candidate.id === id);\n this.#surfaces.get(id)?.release(entry?.returnFocusTarget ?? null);\n }\n\n /**\n * Hands the closing entry's return-focus origin on (see\n * `resolveReturnFocusTarget`) and releases its surface, so the overlay stops\n * being modal and returns focus at close intent. Then drives the exit\n * animation on the overlay root and, in lockstep,\n * on the portaled backdrop (both resolved from the `OverlaySurface` stored at\n * attach time — the backdrop's template `animate.leave` never fires under the\n * manager's `ngComponentOutlet` mount), then calls `remove`. Runs `remove`\n * immediately when destroying, when `requestAnimationFrame` is unavailable,\n * when no surface was registered (nothing rendered), or when there is nothing\n * to animate.\n */\n protected beginLeave(\n id: string,\n leaveClass: string | undefined,\n backdropLeaveClass: string | undefined,\n remove: () => void,\n ): void {\n if (!this.#destroying) {\n untracked(() => {\n this.#handOffReturnFocus(id);\n this.#releaseSurface(id);\n });\n }\n if (this.#destroying || typeof requestAnimationFrame === 'undefined') {\n remove();\n return;\n }\n const surface = this.#surfaces.get(id);\n const targets: HTMLElement[] = [];\n if (surface && leaveClass && typeof surface.host.getAnimations === 'function') {\n surface.host.classList.add(leaveClass);\n targets.push(surface.host);\n }\n if (surface && backdropLeaveClass) {\n const backdrop = surface.backdrop();\n if (backdrop && typeof backdrop.getAnimations === 'function') {\n backdrop.classList.add(backdropLeaveClass);\n targets.push(backdrop);\n }\n }\n if (targets.length === 0) {\n remove();\n return;\n }\n requestAnimationFrame(() => {\n const finite = targets\n .flatMap((el) => el.getAnimations({ subtree: true }))\n .filter(isFiniteAnimation);\n if (finite.length === 0) {\n remove();\n return;\n }\n Promise.all(finite.map((animation) => animation.finished.catch(() => undefined))).then(() =>\n remove(),\n );\n });\n }\n\n /**\n * Builds a parent-cached per-component `Injector`. The returned\n * factory recreates the injector only when its parent changes, so re-renders\n * with the same enclosing `[forDialog]` / `[forDrawer]` host reuse it.\n *\n * With no `scope`, the opened component's injector is parented on the\n * declarative host's element injector (`parent`), matching the declarative\n * path. When the caller passed an `injector` on the `open()` config, `scope`\n * re-parents the opened component on that caller scope instead — so DI inside\n * the opened component resolves the scope's providers (a lazy route, a\n * component `providers`). The host's `contextToken` and the field-boundary\n * tokens are copied across as value providers so the primitive's own pieces\n * still resolve `FOR_<PRIMITIVE>_CONTEXT`, and a control in the opened\n * component stays cut off from the caller's `[forField]`, exactly as on the\n * declarative path.\n *\n * Each injector it creates is destroyed when the view owning `parent` is\n * destroyed, after the opened component it served, or when a new parent\n * replaces it, so the services passed in `providers` run their teardown.\n */\n protected createInjectorFactory(\n providers: readonly Provider[],\n scope?: { readonly injector: Injector; readonly contextToken: ProviderToken<unknown> },\n ): (parent: Injector) => Injector {\n let cached: {\n readonly parent: Injector;\n readonly injector: Injector;\n readonly release: () => void;\n } | null = null;\n return (parent: Injector): Injector => {\n if (cached?.parent === parent) {\n return cached.injector;\n }\n cached?.release();\n const injector = scope\n ? Injector.create({\n parent: scope.injector,\n providers: [\n ...[scope.contextToken, ...FIELD_BOUNDARY_TOKENS].map((token) => ({\n provide: token,\n useValue: parent.get(token),\n })),\n ...providers,\n ],\n })\n : Injector.create({ parent, providers: [...providers] });\n cached = { parent, injector, release: bindInjectorLifetime(injector, parent) };\n return injector;\n };\n }\n\n /**\n * Registers a fully-built entry, ensures the outlet exists, and requests a\n * render so the `@for` mounts it.\n *\n * The render is attempted synchronously via `ApplicationRef.tick()` so the\n * overlay DOM is available the moment `open()` returns — the common case.\n * When `open()` is itself called from within change detection (an `effect`,\n * `ngOnInit`, or an `afterNextRender` callback) a tick is already in flight\n * and a nested `tick()` is illegal (NG0101); the synchronous attempt is then\n * skipped and the `#entries` signal write drives the mount on the next\n * scheduled render instead. The entry is registered immediately either way,\n * so the returned overlay ref is usable straight away.\n */\n protected register(entry: TEntry): void {\n this.#ensureOutlet();\n this.#entries.update((arr) => [...arr, entry]);\n this.#renderNow();\n }\n\n #renderNow(): void {\n try {\n this.#appRef.tick();\n } catch (error: unknown) {\n if (isRecursiveTickError(error)) {\n return;\n }\n throw error;\n }\n }\n\n /**\n * Closes every overlay this manager has open, topmost first, with reason `'programmatic'` and\n * `result` as each close result. Each ref's `closed` resolves as it does for `ref.close()`, exit\n * animations still play, and focus ends where the bottom overlay's return focus sends it. A no-op\n * when nothing is open.\n */\n closeAll(result?: unknown): void {\n for (const entry of [...this.#entries()].reverse()) {\n entry.ref.close(result);\n }\n }\n\n #closeAllForDestroy(): void {\n this.#destroying = true;\n for (const entry of this.#entries()) {\n entry.ref.close();\n }\n }\n\n #ensureOutlet(): void {\n if (this.#outletRef) {\n return;\n }\n const outletRef = this.#config.createOutlet(this.#envInjector);\n this.#appRef.attachView(outletRef.hostView);\n if (this.#isBrowser) {\n const outletHost = outletRef.location.nativeElement as HTMLElement;\n outletHost.style.display = 'contents';\n const releasePeer = this.#peerRegistry.registerPeer(outletHost, 'always');\n this.#document.body.appendChild(outletHost);\n outletRef.onDestroy(() => {\n releasePeer();\n outletHost.remove();\n });\n }\n outletRef.instance.init({\n entries: this.#entries.asReadonly(),\n closeAllForDestroy: () => this.#closeAllForDestroy(),\n registerSurface: (id, surface) => {\n this.#surfaces.set(id, surface);\n },\n });\n this.#outletRef = outletRef;\n }\n}\n\nconst FIELD_BOUNDARY_TOKENS: readonly ProviderToken<unknown>[] = [\n FOR_FIELD_CONTEXT,\n FOR_FIELD_ANCHOR_CONTEXT,\n];\n\n/**\n * Destroys `injector` when the scope `parent` belongs to is destroyed, and\n * returns a release that destroys it early and drops that hook. Either path\n * destroys it once.\n */\nfunction bindInjectorLifetime(injector: DestroyableInjector, parent: Injector): () => void {\n let destroyed = false;\n const destroy = (): void => {\n if (!destroyed) {\n destroyed = true;\n injector.destroy();\n }\n };\n const unregister = parent.get(DestroyRef).onDestroy(destroy);\n return () => {\n unregister();\n destroy();\n };\n}\n\n/**\n * True when `error` is Angular's recursive-`ApplicationRef.tick()` runtime\n * error (`NG0101`), thrown when a change-detection tick is already in flight.\n * Matched by the stable numeric `RuntimeError.code` with a message-prefix\n * fallback so it survives production builds where the message text is stripped.\n */\nfunction isRecursiveTickError(error: unknown): boolean {\n if (error === null || typeof error !== 'object') {\n return false;\n }\n const { code, message } = error as { code?: unknown; message?: unknown };\n return code === 101 || (typeof message === 'string' && message.startsWith('NG0101'));\n}\n\n/**\n * True when `animation` will actually finish — i.e. it does not run forever.\n * An infinite exit animation (a shimmer / pulse with `animation-iteration-count:\n * infinite`) reports `Infinity` iterations, and its `finished` promise never\n * resolves; awaiting it would strand `beginLeave` and leak the overlay entry.\n * Filtering these out before awaiting `finished` lets teardown proceed once the\n * finite animations settle (or immediately, when none remain). Guards for a\n * possibly-null effect and for environments lacking `getComputedTiming`.\n */\nfunction isFiniteAnimation(animation: Animation): boolean {\n const effect = animation.effect;\n if (!effect || typeof effect.getComputedTiming !== 'function') {\n return true;\n }\n return effect.getComputedTiming().iterations !== Infinity;\n}\n","import { signal } from '@angular/core';\n\n/**\n * The awaitable close payload resolved by `OverlayRef.closed` — the reason the\n * overlay closed plus the optional close result. Homogeneous with\n * `ForToastRef.closed` so all three programmatic overlay handles expose the\n * same `{ reason, result }` shape.\n *\n * Internal core tier — exported from `forty-cdk/core-overlay` for the\n * library's own entry points, with no semver guarantee.\n */\nexport interface OverlayCloseEvent<R, Reason> {\n /** Why the overlay closed (e.g. `'escape'`, `'closeButton'`, `'programmatic'`). */\n readonly reason: Reason;\n /** The close result passed to `close(result)`, or `undefined`. */\n readonly result: R | undefined;\n}\n\n/**\n * Shared handle returned by an imperative overlay manager's `open()`.\n * `ForDialogRef` / `ForDrawerRef` extend this verbatim to keep their public\n * class identity (and DI token) while the close engine lives here once.\n *\n * Both reactive (`isClosed`, `result`) and awaitable (`closed`) APIs are\n * exposed — pick what fits the call site. `R` is the close-result type and\n * `Reason` the close-reason union (`ForDialogCloseReason` /\n * `ForDrawerCloseReason`).\n *\n * Internal core tier — no semver guarantee; the public surface is\n * `ForDialogRef` / `ForDrawerRef`.\n */\nexport class OverlayRef<R = unknown, Reason = string> {\n readonly #result = signal<R | undefined>(undefined);\n readonly #closed = signal(false);\n\n /** Reactive: `true` once `close()` has been called. */\n readonly isClosed = this.#closed.asReadonly();\n\n /** Reactive: the close result. `undefined` while open. */\n readonly result = this.#result.asReadonly();\n\n /**\n * Awaitable: resolves with `{ reason, result }` the first time `close()`\n * runs. The reason distinguishes an explicit `close(result)` (the manager's\n * default reason, `'programmatic'`) from a dismiss channel (Escape, backdrop,\n * outside-pointer, close button), which a bare result cannot.\n */\n readonly closed: Promise<OverlayCloseEvent<R, Reason>>;\n\n #resolveClosed!: (event: OverlayCloseEvent<R, Reason>) => void;\n readonly #teardown: () => void;\n readonly #defaultReason: Reason;\n\n /** Internal composition surface (no semver guarantees). */\n constructor(teardown: () => void, defaultReason: Reason) {\n this.#teardown = teardown;\n this.#defaultReason = defaultReason;\n this.closed = new Promise((resolve) => {\n this.#resolveClosed = resolve;\n });\n }\n\n /**\n * Close the overlay, optionally returning a result. Idempotent — calling\n * twice is a no-op. `reason` defaults to the manager's default (`'programmatic'`\n * for a direct imperative close); the dismiss channels pass their own reason.\n */\n close(result?: R, reason: Reason = this.#defaultReason): void {\n if (this.#closed()) {\n return;\n }\n this.#result.set(result);\n this.#closed.set(true);\n this.#resolveClosed({ reason, result });\n this.#teardown();\n }\n}\n"],"mappings":";;;;AA+CA,IAAa,iBAAb,MAAa,eAAc;CAChB,YAAY,OAAO,QAAQ;CAC3B,UAAU,KAAK,UAAU;CACzB,aAAa,kBAAkB,OAAO,WAAW,CAAC;CAElD,2BAAW,IAAI,IAAG;CAU3B,KAAK,SAAsB,KAAK,UAAU,MAAI;EAC5C,IAAI,CAAC,KAAK,YACR;EAEF,IAAI,SAAS,KAAK,SAAS,IAAI,MAAM;EACrC,IAAI,CAAC,QAAQ;GACX,SAAS;IAAE,OAAO;IAAG,mBAAmB;IAAO,mBAAmB;GAAK;GACvE,KAAK,SAAS,IAAI,QAAQ,MAAM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