{"version":3,"file":"styloviz-core-overlay.mjs","names":[],"sources":["../../../../projects/core/overlay/close-guard.ts","../../../../projects/core/overlay/sheet-mode.ts","../../../../projects/core/overlay/overlay-route.ts","../../../../projects/core/overlay/anchor-scroll-guard.ts","../../../../projects/core/overlay/body-scroll-lock.ts","../../../../projects/core/overlay/focusable.ts","../../../../projects/core/overlay/focus-scope.ts","../../../../projects/core/overlay/focus-recovery.ts","../../../../projects/core/overlay/anchored-position.ts","../../../../projects/core/overlay/fixed-origin.ts","../../../../projects/core/overlay/portal-host.ts","../../../../projects/core/overlay/tooltip-group.ts","../../../../projects/core/overlay/overlay-stack.ts","../../../../projects/core/overlay/stacked-popup.ts"],"sourcesContent":["import { computed, signal, type Signal } from '@angular/core';\n\n/**\n * One vocabulary for \"why is this surface closing?\", shared by every\n * dismissible family.\n *\n * ★★ MODAL AND DRAWER ALREADY HAD THIS, IDENTICALLY AND SEPARATELY — four\n *    string literals each, declared twice. That is the half the audit called\n *    \"the right primitive\"; the policy built on top of it is what was missing\n *    (`X-11`). Both component unions are subsets of this one, so their public\n *    types keep working unchanged.\n *\n * `route` and `history` are here for `X-13`: a surface closed by a navigation\n * did not close because the user dismissed it, and a host that logs dismissals\n * needs to be able to tell those apart.\n */\nexport type SvCloseReason =\n  | 'backdrop'\n  | 'escape'\n  | 'close-button'\n  | 'programmatic'\n  | 'route'\n  | 'history';\n\n/**\n * The reasons a component's own published close-reason union can carry —\n * `ModalCloseReason` and `DrawerCloseReason` are exactly this set.\n */\nexport type SvDismissReason = Exclude<SvCloseReason, 'route' | 'history'>;\n\n/**\n * Fold a close reason into the published component unions.\n *\n * ★★ THOSE UNIONS PREDATE `X-13` AND CANNOT GROW. A host's exhaustive\n *    `switch (reason)` over `ModalCloseReason` stops compiling the day a member\n *    is added, so a navigation or Back close used to be emitted as `'route'` /\n *    `'history'` through a cast — a value the declared type says is\n *    impossible. It is reported as `'programmatic'` instead (the surface closed\n *    on the app's behalf, not through its own controls), and the exact reason\n *    goes out on each component's `dismissedBy` output.\n */\nexport function svDismissReason(reason: SvCloseReason): SvDismissReason {\n  return reason === 'route' || reason === 'history' ? 'programmatic' : reason;\n}\n\n/**\n * What a host's own guard said about a close attempt.\n *\n * `false` refuses it. Anything else — `true`, `undefined`, no return at all —\n * is \"no objection\", so a guard that only cares about one reason can just\n * `return` for the rest.\n */\nexport type SvCloseVerdict = boolean | void;\n\nexport interface SvCloseGuardOptions {\n  /**\n   * Is there unsaved work? A getter so a component can pass its own input\n   * signal and have changes take effect immediately.\n   */\n  readonly dirty?: () => boolean;\n  /**\n   * The host's own veto, consulted before the dirty check.\n   *\n   * ★ A getter returning the function, not the function, because it is\n   *   normally an `input()` the host may not have set.\n   */\n  readonly guard?: () => ((reason: SvCloseReason) => SvCloseVerdict) | null | undefined;\n  /**\n   * Reasons that skip the dirty prompt entirely.\n   *\n   * ★★ DEFAULTS TO `['programmatic']`, AND THAT IS A DECISION, NOT AN\n   *    OVERSIGHT. The dirty prompt exists for ACCIDENTAL dismissal — a\n   *    backdrop click, a stray Escape, the back button. A programmatic close\n   *    is the host's own code saying \"close now\": a component that\n   *    second-guesses its own API call is unusable, and the host is the one\n   *    place that already knows whether the work was saved. Pass `[]` to\n   *    prompt on those too.\n   */\n  readonly alwaysAllow?: () => readonly SvCloseReason[];\n}\n\nexport interface SvCloseGuard {\n  /** True while a close attempt is waiting on the unsaved-changes prompt. */\n  readonly prompting: Signal<boolean>;\n  /** The reason that raised the prompt, or `null`. */\n  readonly pendingReason: Signal<SvCloseReason | null>;\n  /**\n   * May the surface close right now?\n   *\n   * Returns `true` to close immediately. `false` means either the host vetoed\n   * it outright or the prompt is now up — `prompting()` says which.\n   */\n  request(reason: SvCloseReason): boolean;\n  /**\n   * The user chose to discard their changes. Returns the reason the close\n   * should be reported with, or `null` if nothing was pending.\n   *\n   * ★★ THE ORIGINAL REASON, NOT `'programmatic'`. The user dismissed this with\n   *    Escape; the prompt is an interruption in the middle of that, not a new\n   *    kind of close. A surface that reports `programmatic` here tells its\n   *    host's analytics that code closed a dialog the user closed.\n   */\n  discard(): SvCloseReason | null;\n  /** The user chose to stay. Clears the prompt and closes nothing. */\n  keep(): void;\n  /** Forget any pending prompt — for a surface that closed by other means. */\n  reset(): void;\n}\n\nconst DEFAULT_ALWAYS_ALLOW: readonly SvCloseReason[] = ['programmatic'];\n\n/**\n * The shared controlled-close policy: a host veto, and one unsaved-changes\n * prompt.\n *\n * ── Why this is shared and not per-component (`X-11`) ───────────────────────\n *\n * ★★★ \"YOU HAVE UNSAVED CHANGES\" IMPLEMENTED FOUR TIMES WILL BEHAVE FOUR\n *     WAYS. The audit says so and it is right: the interesting part is not the\n *     prompt, it is the ORDER of the questions and what each answer means.\n *     Does a host veto suppress the prompt or stack with it? Does a\n *     programmatic close prompt? What reason does the eventual close report?\n *     Four components answering those independently is four contracts.\n *\n * ★★ A HOST VETO AND A DIRTY PROMPT ARE DIFFERENT REFUSALS. `guard` returning\n *    `false` is the host saying \"not now\", for its own reasons, with its own\n *    messaging — so it does NOT raise the unsaved-changes prompt. Conflating\n *    them produces the surface that tells a user their changes are unsaved\n *    when the real reason was a request in flight.\n *\n * ★ Synchronous by design. Every close path in this kit — a backdrop click, a\n *   keydown, an `@Output` — is synchronous, and an `async` verdict would mean\n *   every one of them had to become a promise for a question that is almost\n *   always answered from a signal. The prompt IS the asynchronous case, and it\n *   is modelled as state rather than as a pending promise.\n *\n * ```ts\n * private readonly closeGuard = createCloseGuard({\n *   dirty: () => this.dirty(),\n *   guard: () => this.closeGuard_(),\n * });\n *\n * close(reason: ModalCloseReason = 'programmatic'): void {\n *   if (!this.closeGuard.request(reason)) return;   // vetoed, or prompting\n *   …\n * }\n * ```\n */\nexport function createCloseGuard(options: SvCloseGuardOptions = {}): SvCloseGuard {\n  const pending = signal<SvCloseReason | null>(null);\n\n  const api: SvCloseGuard = {\n    // Derived rather than a second signal: \"is the prompt up?\" cannot then\n    // disagree with \"what raised it?\".\n    prompting: computed(() => pending() !== null),\n    pendingReason: pending.asReadonly(),\n\n    request: (reason: SvCloseReason): boolean => {\n      // ★ Already prompting: refuse, and leave the reason alone. Idempotent\n      //   for the same reason `createWaitEscalation.start()` is — the caller\n      //   is a template event that can fire repeatedly (a user clicking the\n      //   backdrop behind the prompt), and re-raising the prompt on each one\n      //   would be indistinguishable from never having raised it.\n      if (pending() !== null) return false;\n\n      const guard = options.guard?.();\n      if (guard && guard(reason) === false) return false;\n\n      const dirty = options.dirty?.() ?? false;\n      const allowed = options.alwaysAllow?.() ?? DEFAULT_ALWAYS_ALLOW;\n      if (dirty && !allowed.includes(reason)) {\n        pending.set(reason);\n        return false;\n      }\n\n      return true;\n    },\n\n    discard: (): SvCloseReason | null => {\n      const reason = pending();\n      pending.set(null);\n      return reason;\n    },\n\n    keep: (): void => { pending.set(null); },\n\n    reset: (): void => { pending.set(null); },\n  };\n\n  return api;\n}\n","import { DestroyRef, computed, inject, signal, type Signal } from '@angular/core';\n\n/**\n * sheet-mode.ts — one answer to \"what does this surface do on a phone?\"\n * (`X-16`).\n *\n * ★★★ FIVE FAMILIES ASK FOR THE SAME FALLBACK. A centred dialog, an anchored\n *     popover, a dropdown menu, a context menu and a command palette all have\n *     the same problem at 375px: there is no room beside the anchor, so an\n *     anchored surface is clamped until it covers the thing it points at, and\n *     a centred one is a postage stamp in the middle of the screen with the\n *     keyboard over it. Implemented five times, it would be five slightly\n *     different breakpoints and five different bugs.\n *\n * ★★ AND THE HARD PART IS NOT THE BREAKPOINT — it is the two things everyone\n *    forgets: the safe area (a sheet's last row sits under the home indicator)\n *    and the virtual keyboard (a sheet with a field in it is covered by the\n *    keyboard the field just raised). Both are here, so an adopter gets them\n *    by adopting rather than by remembering.\n */\n\n/** Options for {@link createSheetMode}. */\nexport interface SvSheetModeOptions {\n  /**\n   * Viewport width, in px, at or below which a surface becomes a sheet.\n   * @default 640\n   *\n   * ★ 640 is Tailwind's `sm` boundary, so a host's own responsive classes and\n   *   this switch change at the same width. A surface that becomes a sheet 8px\n   *   before the layout around it reflows looks like a bug in the sheet.\n   */\n  readonly maxWidth?: number;\n  /**\n   * Also require a pointer that cannot hover. @default false\n   *\n   * ★ Off by default because a NARROW WINDOW ON A DESKTOP has the same problem\n   *   — there is no room beside the anchor either way. Turn it on for a\n   *   surface whose sheet form is really about the finger rather than the\n   *   width.\n   */\n  readonly requireTouch?: boolean;\n  /** Read on every evaluation, so a host can turn the fallback off entirely. */\n  readonly enabled?: () => boolean;\n}\n\n/** A live sheet-mode subscription. */\nexport interface SvSheetMode {\n  /** True when this surface should render as a bottom sheet. */\n  readonly asSheet: Signal<boolean>;\n  /**\n   * Pixels of the viewport currently hidden by the virtual keyboard.\n   *\n   * ★★★ A SHEET WITH A FIELD IN IT IS COVERED BY THE KEYBOARD THAT FIELD JUST\n   *     RAISED, and `window.innerHeight` does not change when it appears — so\n   *     `bottom: 0` is behind the keyboard, and the input the user tapped is\n   *     the part that is hidden. Bind this to the sheet's `bottom` and it sits\n   *     on top of the keyboard instead.\n   *\n   * `0` where `visualViewport` is unavailable, which is the desktop answer and\n   * the safe one.\n   */\n  readonly keyboardInset: Signal<number>;\n  /** Stop listening. Idempotent. Called for you on destroy. */\n  release(): void;\n}\n\n/**\n * The bottom padding a sheet needs so its last row clears the home indicator.\n *\n * ★★ `env()` WITH A FALLBACK, and the fallback is the point: `env()` resolves\n *    to nothing at all in a browser that does not know the variable, and\n *    `padding-bottom:` with nothing after it is a dropped declaration rather\n *    than a zero — so the whole rule silently disappears, which is the shape\n *    that ships looking fine on the developer's desktop.\n *\n * ★ It ALSO needs `viewport-fit=cover` in the host's `<meta name=\"viewport\">`,\n *   without which the browser reports a zero inset on a notched device. That\n *   is the host's document, not ours, so it is documentation rather than code.\n */\nexport const SV_SHEET_SAFE_AREA_PADDING = 'env(safe-area-inset-bottom, 0px)';\n\n/**\n * Watch the viewport for sheet mode.\n *\n * Must be called in an injection context: it takes a `DestroyRef` so a host\n * cannot forget to unsubscribe.\n */\nexport function createSheetMode(options: SvSheetModeOptions = {}): SvSheetMode {\n  const maxWidth = options.maxWidth ?? 640;\n  const requireTouch = options.requireTouch ?? false;\n  const enabled = options.enabled ?? (() => true);\n\n  const narrow = signal(false);\n  const noHover = signal(false);\n  const keyboardInset = signal(0);\n  const stops: (() => void)[] = [];\n\n  const hasWindow = typeof window !== 'undefined' && typeof window.matchMedia === 'function';\n\n  if (hasWindow) {\n    // ★ `(max-width: Npx)` rather than reading `innerWidth` once: a phone\n    //   rotating changes width without any scroll or resize the component sees\n    //   otherwise, and a desktop window is dragged narrow all the time.\n    const widthMql = window.matchMedia(`(max-width: ${maxWidth}px)`);\n    narrow.set(widthMql.matches);\n    const onWidth = (e: MediaQueryListEvent): void => narrow.set(e.matches);\n    widthMql.addEventListener('change', onWidth);\n    stops.push(() => widthMql.removeEventListener('change', onWidth));\n\n    const hoverMql = window.matchMedia('(hover: none)');\n    noHover.set(hoverMql.matches);\n    const onHover = (e: MediaQueryListEvent): void => noHover.set(e.matches);\n    hoverMql.addEventListener('change', onHover);\n    stops.push(() => hoverMql.removeEventListener('change', onHover));\n\n    const vv = window.visualViewport;\n    if (vv) {\n      const measure = (): void => {\n        // ★★ THE FORMULA IS NOT `innerHeight - vv.height`. On iOS the page\n        //    scrolls under the keyboard, so `vv.offsetTop` is how far the\n        //    visual viewport has moved down the layout viewport — and ignoring\n        //    it reports a keyboard that is taller than it is the moment the\n        //    user scrolls, pushing the sheet off the top of the screen.\n        const hidden = window.innerHeight - (vv.height + vv.offsetTop);\n        // Negative readings happen mid-animation on Android.\n        keyboardInset.set(Math.max(0, Math.round(hidden)));\n      };\n      measure();\n      vv.addEventListener('resize', measure);\n      vv.addEventListener('scroll', measure);\n      stops.push(() => {\n        vv.removeEventListener('resize', measure);\n        vv.removeEventListener('scroll', measure);\n      });\n    }\n  }\n\n  const release = (): void => {\n    while (stops.length) stops.pop()!();\n  };\n\n  // ★ A `DestroyRef` rather than asking the caller to call `release()`: an\n  //   overlay that forgets leaves two media-query listeners and two\n  //   visualViewport listeners per instance, and overlays are created per row.\n  inject(DestroyRef).onDestroy(release);\n\n  return {\n    asSheet: computed(\n      () => enabled() && narrow() && (!requireTouch || noHover()),\n    ),\n    keyboardInset: computed(() => keyboardInset()),\n    release,\n  };\n}\n","import { Injectable, inject, PLATFORM_ID } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\nimport type { SvCloseReason } from './close-guard';\n\n/**\n * What a dismissible surface tells this service about itself.\n *\n * Both flags are getters, so a component can hand over its own inputs and a\n * host can change its mind while the surface is open.\n */\nexport interface SvRouteAwareOptions {\n  /** Close the surface. The reason is `'route'` or `'history'`. */\n  readonly close: (reason: SvCloseReason) => void;\n  /**\n   * Does a navigation close it?\n   *\n   * ★★ THE DEFAULT IS YES, AND THE AUDIT IS BLUNT ABOUT WHY: a modal that\n   *    outlives its route and floats over an unrelated page is the most\n   *    common overlay bug in shipped dashboards. A surface that genuinely\n   *    belongs to the shell rather than the page — a global command palette,\n   *    a support widget — says so by returning false.\n   */\n  readonly closeOnNavigation?: () => boolean;\n  /**\n   * Does the browser Back button close it?\n   *\n   * ★★ THE DEFAULT IS NO, AND THAT IS THE OPPOSITE DECISION FROM THE ONE\n   *    ABOVE. Back closing a dialog is right when the dialog is a\n   *    destination the user navigated TO — a details panel, a wizard step —\n   *    and wrong when it is a transient question, where it would eat a Back\n   *    press the user meant for the page. Opting in is a statement about what\n   *    the surface IS, so the surface cannot make it for the host.\n   */\n  readonly backCloses?: () => boolean;\n  /** For diagnostics only. */\n  readonly label?: string;\n  /**\n   * Does the surface hold unsaved work right now? Consulted by `requestLeave`.\n   * Optional: a surface without it is never asked to hold a navigation.\n   */\n  readonly dirty?: () => boolean;\n  /**\n   * A navigation wants to leave the page this surface belongs to, and the\n   * surface is dirty. Raise the surface's own unsaved-changes prompt and\n   * return `true` to hold the navigation; call `proceed` once the user chose\n   * to discard (after starting the close). Return `false` to let it through.\n   *\n   * ★ Optional and additive — it is what `svOverlayCanDeactivate` in\n   *   `@styloviz/layout` calls, so core itself never touches the router.\n   */\n  readonly requestLeave?: (proceed: () => void) => boolean;\n}\n\nexport interface SvRouteAwareHandle {\n  /**\n   * The surface closed. Call it on every close path, including the ones this\n   * service triggered.\n   *\n   * ★ It is what pops the history entry a `backCloses` surface pushed — a\n   *   dialog closed with its own × button must not leave the user one Back\n   *   press away from reopening it.\n   */\n  release(): void;\n}\n\n/** Marker key on `history.state`, namespaced so a host's own state survives. */\nconst SV_HISTORY_KEY = '__svOverlay';\n\ninterface Entry {\n  readonly id: number;\n  readonly options: SvRouteAwareOptions;\n  /** Token written into `history.state`, or `null` when none was pushed. */\n  readonly token: number | null;\n  /** True once this surface has been closed BY a navigation or a Back press. */\n  closedByHistory: boolean;\n  released: boolean;\n  /** True once the user discarded to let a held navigation through. */\n  leaving?: boolean;\n}\n\n/**\n * Route and history integration for dismissible surfaces (`X-13`).\n *\n * ── Why this service and not `inject(Router)` in each component ─────────────\n *\n * ★★★ `@styloviz/core` DOES NOT DEPEND ON `@angular/router`, AND MUST NOT.\n *     Core is the base every other package builds on, including in apps that\n *     never route; a hard peer on the router to answer \"did we navigate?\"\n *     would be the tail wagging the dog. So the service owns the POLICY and\n *     the history plumbing, which need no router at all, and takes the one\n *     fact it cannot observe — that a navigation happened — as a call.\n *\n * ★★ `provideSvOverlayRouteClose()` in `@styloviz/layout` is the router half:\n *     three lines subscribing to `NavigationEnd`. Layout already has the\n *     router as a peer and is where an app's shell lives. An app that wires\n *     nothing keeps today's behaviour exactly, which is why this is safe to\n *     land in a published kit.\n *\n * ★ The Back button needs no router either: an overlay that wants Back to\n *   close it pushes a marked history entry and listens for `popstate`. That\n *   is the whole mechanism, and it is why `backCloses` works with any router\n *   or none.\n */\n@Injectable({ providedIn: 'root' })\nexport class SvOverlayRouteService {\n  private readonly _platformId = inject(PLATFORM_ID);\n  private readonly _entries: Entry[] = [];\n  private _nextId = 1;\n  /**\n   * How many `popstate` events this service caused itself.\n   *\n   * ★★ WITHOUT THIS THE SERVICE CLOSES SURFACES IT IS ALREADY CLOSING. A\n   *    surface that pops its own entry on `release()` gets the `popstate`\n   *    back a moment later, sees a state without its marker, and calls\n   *    `close()` a second time — which for a family that emits `dismissed` on\n   *    close means two dismissals for one action.\n   */\n  private _selfPops = 0;\n  private _listening = false;\n\n  /** Register an open surface. Release the handle when it closes. */\n  register(options: SvRouteAwareOptions): SvRouteAwareHandle {\n    const browser = isPlatformBrowser(this._platformId) && typeof window !== 'undefined';\n    const wantsHistory = browser && (options.backCloses?.() ?? false);\n\n    const id = this._nextId++;\n    let token: number | null = null;\n\n    if (wantsHistory) {\n      token = id;\n      // ★ The host's own state is preserved and the URL is untouched: this is\n      //   a history ENTRY, not a route. A surface that wanted its own URL\n      //   would be a page, and `X-13` is explicit that routing overlays is\n      //   the host's decision, not the kit's.\n      window.history.pushState(\n        { ...(window.history.state as object | null), [SV_HISTORY_KEY]: token },\n        '',\n      );\n    }\n\n    const entry: Entry = { id, options, token, closedByHistory: false, released: false };\n    this._entries.push(entry);\n    if (browser) this._listen();\n\n    return {\n      release: (): void => this._release(entry),\n    };\n  }\n\n  /**\n   * The application navigated. Closes every surface that says a navigation\n   * should close it.\n   *\n   * ★ Iterates a SNAPSHOT: `close()` normally leads straight to `release()`,\n   *   which mutates the list being walked.\n   */\n  /**\n   * A navigation is about to leave the page: does an open, dirty surface want\n   * to hold it? Returns `true` when one raised its unsaved-changes prompt (the\n   * caller cancels the navigation); `proceed` re-issues it after Discard.\n   * Keep editing simply never calls it. Topmost surface first.\n   *\n   * ★★ WITHOUT THIS THE PROMPT ARRIVED TOO LATE: `navigated()` runs on\n   *    `NavigationEnd`, so a dirty dialog asked \"discard?\" over a page the user\n   *    had already been taken to, and Keep editing kept a form about a page\n   *    that was gone. Used by `svOverlayCanDeactivate` (`@styloviz/layout`).\n   */\n  requestLeave(proceed: () => void): boolean {\n    for (const entry of [...this._entries].reverse()) {\n      if (entry.released || entry.leaving || !entry.options.requestLeave) continue;\n      if (!(entry.options.closeOnNavigation?.() ?? true)) continue;\n      if (!(entry.options.dirty?.() ?? false)) continue;\n      const held = entry.options.requestLeave(() => {\n        // ★ The navigation about to be re-issued supersedes this surface's\n        //   history entry: popping it now would race the new navigation and\n        //   the router would read the pop as a Back press.\n        entry.leaving = true;\n        entry.closedByHistory = true;\n        proceed();\n      });\n      if (held) return true;\n    }\n    return false;\n  }\n\n  navigated(): void {\n    // ★ No `released` check in this loop, nor in the `popstate` one: release\n    //   SPLICES the entry out, so a released surface is not in the list to\n    //   begin with. I wrote the check in both places, a mutation deleting it\n    //   stayed green in both, and the flag now earns its keep only inside\n    //   `_release`, where it stops a second release popping a second entry.\n    for (const entry of [...this._entries]) {\n      if (!(entry.options.closeOnNavigation?.() ?? true)) continue;\n      // ★ Marked BEFORE the close, because the close calls back into\n      //   `release()` synchronously — and `release()` has to know not to pop a\n      //   history entry the navigation has already left behind.\n      entry.closedByHistory = true;\n      entry.options.close('route');\n    }\n  }\n\n  /** Test seam: how many surfaces are currently registered. */\n  get openCount(): number {\n    return this._entries.filter((e) => !e.released).length;\n  }\n\n  private _release(entry: Entry): void {\n    if (entry.released) return;\n    entry.released = true;\n    const index = this._entries.indexOf(entry);\n    if (index >= 0) this._entries.splice(index, 1);\n\n    if (entry.token === null) return;\n    if (entry.closedByHistory) return;\n    if (typeof window === 'undefined') return;\n\n    // ★★ ONLY IF OUR ENTRY IS STILL THE CURRENT ONE. The user may have\n    //    navigated three pages on since; calling `back()` then would take\n    //    them somewhere they never asked to go, which is a far worse bug than\n    //    a stale history entry.\n    const state = window.history.state as Record<string, unknown> | null;\n    if (state?.[SV_HISTORY_KEY] !== entry.token) return;\n\n    this._selfPops++;\n    window.history.back();\n  }\n\n  private _listen(): void {\n    if (this._listening) return;\n    this._listening = true;\n    window.addEventListener('popstate', this._onPopState);\n  }\n\n  private readonly _onPopState = (): void => {\n    if (this._selfPops > 0) {\n      this._selfPops--;\n      return;\n    }\n\n    const state = window.history.state as Record<string, unknown> | null;\n    const marker = state?.[SV_HISTORY_KEY];\n\n    // Topmost first: a Back press dismisses the surface the user opened last.\n    for (const entry of [...this._entries].reverse()) {\n      if (entry.token === null) continue;\n      if (marker === entry.token) break;   // its entry is still there\n      entry.closedByHistory = true;\n      entry.options.close('history');\n      break;                               // one Back press, one surface\n    }\n  };\n}\n","/**\n * anchor-scroll-guard — tell a scroll EVENT apart from the anchor having MOVED.\n *\n * Portalled panels pin themselves to a trigger with fixed coordinates read from\n * `getBoundingClientRect()`, so they listen for scroll and close. But the\n * browser also emits scroll when the document grows, when a focused input is\n * revealed, and when a panel's own insertion lengthens the page — `sv-mention`\n * shipped a bug where it closed the panel it had just opened, for that last\n * reason. Closing on the event is wrong twice: it fires when nothing moved, and\n * users read it as the panel vanishing for free.\n *\n * This records where the anchor sat at open and only acts once it really moved.\n * rAF throttling, ignoring scrolls from inside the panel, and an optional grace\n * window after opening are folded in so callers do not re-derive them.\n *\n * Nothing touches the DOM at construction, so it is safe in a field initialiser\n * under SSR. See [[portal-insertion-order]] for the full history.\n */\n\n/** Viewport position of the anchor. Only the origin matters for pinning. */\ninterface AnchorPosition {\n  readonly top: number;\n  readonly left: number;\n}\n\nexport interface SvAnchorScrollGuardOptions {\n  /** Element the panel is pinned to. Read lazily, so a late `viewChild` works. */\n  readonly anchor: () => Element | null | undefined;\n\n  /** Whether the panel is open. Checked before any DOM work. */\n  readonly isOpen: () => boolean;\n\n  /** Run when the anchor has genuinely moved — typically `close()`. */\n  readonly onMoved: () => void;\n\n  /** Portal host — scrolling inside the panel is not the anchor moving. */\n  readonly portal?: () => Element | null | undefined;\n\n  /**\n   * Movement below this many px is no movement — sub-pixel jitter from zoom and\n   * fractional layout is not a scroll. @default 1\n   */\n  readonly threshold?: number;\n\n  /**\n   * Ignore scrolls within this many ms of `capture()`. Opening often focuses\n   * something inside the panel, and a short viewport scrolls to reveal it — a\n   * real move the user never asked for. @default 0 (disabled)\n   */\n  readonly graceMs?: number;\n}\n\nexport interface SvAnchorScrollGuard {\n  /** Pass straight to `addEventListener('scroll', …, { capture: true })`. */\n  readonly handler: (event: Event) => void;\n  /** Call immediately after the panel is inserted and positioned. */\n  capture(): void;\n  /** Cancel any pending frame. Call from `ngOnDestroy`. */\n  destroy(): void;\n}\n\n/** `performance.now()` where available, so the grace survives a clock change. */\nfunction now(): number {\n  return typeof performance !== 'undefined' && typeof performance.now === 'function'\n    ? performance.now()\n    : Date.now();\n}\n\n/**\n * `event.target` is not always a Node — a scroll dispatched on `window` makes it\n * a Window, and handing that to `Node.contains()` throws. A regression test here\n * once passed against unfixed code because that throw skipped the branch under\n * test, so duck-type rather than trusting the cast.\n */\nfunction isNode(value: unknown): value is Node {\n  return !!value && typeof (value as Node).nodeType === 'number';\n}\n\nexport function createAnchorScrollGuard(\n  options: SvAnchorScrollGuardOptions,\n): SvAnchorScrollGuard {\n  const threshold = options.threshold ?? 1;\n  const graceMs = options.graceMs ?? 0;\n\n  let anchorAt: AnchorPosition | null = null;\n  let capturedAt = 0;\n  let rafId: number | null = null;\n\n  const read = (): AnchorPosition | null => {\n    const el = options.anchor();\n    if (!el || typeof el.getBoundingClientRect !== 'function') return null;\n    const rect = el.getBoundingClientRect();\n    return { top: rect.top, left: rect.left };\n  };\n\n  const handler = (event: Event): void => {\n    if (!options.isOpen()) return;\n\n    const target = event.target;\n    const portal = options.portal?.();\n    if (portal && isNode(target) && portal.contains(target)) return;\n\n    if (graceMs > 0 && now() - capturedAt < graceMs) return;\n    if (rafId !== null) return;\n\n    rafId = requestAnimationFrame(() => {\n      rafId = null;\n      if (!options.isOpen()) return;\n\n      const current = read();\n      // Cannot prove it moved. Staying open is the safer failure: a lingering\n      // panel is recoverable, one that vanishes mid-interaction is not.\n      if (!current || !anchorAt) return;\n      if (\n        Math.abs(current.top - anchorAt.top) < threshold &&\n        Math.abs(current.left - anchorAt.left) < threshold\n      ) {\n        return;\n      }\n\n      options.onMoved();\n    });\n  };\n\n  return {\n    handler,\n    capture(): void {\n      anchorAt = read();\n      capturedAt = now();\n    },\n    destroy(): void {\n      if (rafId !== null) {\n        cancelAnimationFrame(rafId);\n        rafId = null;\n      }\n    },\n  };\n}\n","/**\n * Body scroll lock, shared by every surface on the page that takes one.\n *\n * ★★★ IT IS REFERENCE-COUNTED, AND THAT IS THE WHOLE POINT.\n *\n * Each surface locking and unlocking on its own is correct right up to the\n * moment two are open — which the imperative `SvModalService` makes ordinary: a\n * dialog opens a confirm on top of itself. Close the top one and a per-instance\n * `unlockScroll()` clears `body.overflow`, so the page starts scrolling\n * underneath a dialog that is still open. Nothing errors; the background just\n * begins moving behind a modal overlay, which reads as a rendering glitch and\n * is nearly impossible to attribute to the dialog that closed.\n *\n * ★★ THIS LIVED IN `@styloviz/modal` AND THREE OTHER FAMILIES HAD THEIR OWN,\n *    UNCOUNTED COPY. Drawer, Confirm Dialog and Command Palette each wrote the\n *    four lines above with no depth and no saved previous value, so every\n *    combination of them hit the bug this file's first paragraph describes —\n *    and `X-5` is the backlog item for exactly that. Moved into core so there\n *    is one; `@styloviz/modal` still re-exports it, so its consumers are\n *    unaffected.\n *\n * The count also fixes the subtler half: `paddingInlineEnd` compensates for the\n * scrollbar that hiding the overflow removes. Measured a second time while the\n * lock is already on, the scrollbar is already gone, so the measurement comes\n * back 0 and the compensation is lost — the page shifts sideways under the\n * second dialog. The width measured by the FIRST lock is the only correct one,\n * so it is the one kept until the last unlock.\n */\n\ninterface LockState {\n  /** How many modals currently want the page not to scroll. */\n  depth: number;\n  /** What `body.style.overflow` was before the first lock. */\n  overflow: string;\n  /**\n   * What `body.style.paddingInlineEnd` was before the first lock. The inline\n   * end, because that is the scrollbar's side: Chromium and Firefox move the\n   * page's scrollbar to the left in an RTL document.\n   */\n  paddingInlineEnd: string;\n}\n\nconst state: LockState = { depth: 0, overflow: '', paddingInlineEnd: '' };\n\n/**\n * Take a lock. Returns the new depth, which is what the tests assert on.\n *\n * The first caller measures and applies; later callers only increment.\n */\nexport function svLockBodyScroll(doc: Document): number {\n  if (state.depth === 0) {\n    const body = doc.body;\n    // ★ The PREVIOUS values are saved, not assumed to be empty. A host with its\n    // own `overflow: hidden` on `<body>` — a full-height app shell, which is\n    // most dashboards — would otherwise have it wiped by the first modal that\n    // closed, and the page would start scrolling for the rest of the session.\n    state.overflow = body.style.overflow;\n    state.paddingInlineEnd = body.style.paddingInlineEnd;\n\n    const scrollbar = doc.defaultView\n      ? doc.defaultView.innerWidth - doc.documentElement.clientWidth\n      : 0;\n    body.style.overflow = 'hidden';\n    if (scrollbar > 0) body.style.paddingInlineEnd = `${scrollbar}px`;\n  }\n  return ++state.depth;\n}\n\n/**\n * Release a lock. Only the last one out restores the page.\n *\n * Releasing more times than you locked cannot drive the depth negative — a\n * modal destroyed while open unlocks from `ngOnDestroy`, and a double release\n * would otherwise leave the count at -1 and the NEXT lock would never apply\n * anything.\n */\nexport function svUnlockBodyScroll(doc: Document): number {\n  if (state.depth === 0) return 0;\n  state.depth--;\n  if (state.depth === 0) {\n    doc.body.style.overflow = state.overflow;\n    doc.body.style.paddingInlineEnd = state.paddingInlineEnd;\n  }\n  return state.depth;\n}\n\n/** Current depth. Exported for tests and for diagnosing a stuck page. */\nexport function svBodyScrollLockDepth(): number {\n  return state.depth;\n}\n\n/**\n * Drop every lock and restore the page.\n *\n * For `closeAll()` and for test teardown: a spec that leaves the depth above\n * zero poisons every spec after it in the same document, and the failure lands\n * somewhere unrelated.\n */\nexport function svResetBodyScrollLock(doc: Document): void {\n  if (state.depth > 0) {\n    doc.body.style.overflow = state.overflow;\n    doc.body.style.paddingInlineEnd = state.paddingInlineEnd;\n  }\n  state.depth = 0;\n  state.overflow = '';\n  state.paddingInlineEnd = '';\n}\n","/**\n * What counts as focusable, in one place.\n *\n * ★★ THE KIT HAD TEN COPIES OF THIS SELECTOR AND THEY DID NOT AGREE. Some\n *    excluded disabled controls, some did not; some counted `[role=\"button\"]`,\n *    some counted `[contenteditable]`, most counted neither. A focus trap built\n *    on a selector that matches a DISABLED input will happily nominate that\n *    input as its \"first focusable\" — and `focus()` on a disabled control is a\n *    no-op, so Tab wraps into nothing and the trap leaks. The disagreements are\n *    not cosmetic; they are the difference between a working trap and a silent\n *    one.\n */\nexport const SV_FOCUSABLE_SELECTOR = [\n  'a[href]',\n  'area[href]',\n  'button:not([disabled])',\n  'input:not([disabled]):not([type=\"hidden\"])',\n  'select:not([disabled])',\n  'textarea:not([disabled])',\n  'summary',\n  'audio[controls]',\n  'video[controls]',\n  'iframe',\n  '[contenteditable]:not([contenteditable=\"false\"])',\n  '[tabindex]:not([tabindex=\"-1\"])',\n].join(',');\n\n/**\n * Is this element one the browser would actually put focus on?\n *\n * ★ Deliberately NOT a layout test. The obvious extra check — does it render,\n *   via `getClientRects()` or `offsetParent` — is worse than useless here: it\n *   is wrong under `content-visibility`, wrong for an element inside a\n *   collapsing transition, and in jsdom it reports EVERY element as invisible,\n *   which would make every one of these helpers return nothing under test\n *   while behaving correctly in a browser. A guard that only works where it is\n *   never exercised is not a guard. So this checks the things that are true of\n *   the DOM itself — detached, `hidden`, `inert`, `disabled` — and leaves\n *   visibility to the caller, which usually knows.\n */\nexport function svIsFocusable(el: Element | null | undefined): el is HTMLElement {\n  // `typeof` guard: with no DOM (SSR) `HTMLElement` is undefined and a bare\n  // `instanceof` would throw a ReferenceError rather than answer false.\n  if (!el || typeof HTMLElement === 'undefined' || !(el instanceof HTMLElement)) return false;\n  if (!el.isConnected) return false;\n  if (el.hasAttribute('disabled')) return false;\n  if (el.hidden) return false;\n  // ★ `closest`, not a check on the element itself: both of these are\n  //   INHERITED. A button three levels inside an `inert` or `aria-hidden`\n  //   subtree carries neither attribute and is still unreachable.\n  if (el.closest('[inert], [aria-hidden=\"true\"]')) return false;\n  return el.matches(SV_FOCUSABLE_SELECTOR) || el.tabIndex >= 0;\n}\n\n/**\n * Every focusable element inside `root`, in tab order, `root` itself excluded.\n *\n * Elements inside an `inert` or `aria-hidden` subtree are dropped — a focus\n * trap that hands back a node no browser will focus is how a trap starts\n * failing silently.\n */\nexport function svFocusableWithin(root: Element | null | undefined): HTMLElement[] {\n  if (!root) return [];\n  return [...root.querySelectorAll<HTMLElement>(SV_FOCUSABLE_SELECTOR)].filter(svIsFocusable);\n}\n\n/** The first focusable element inside `root`, or `null`. */\nexport function svFirstFocusableWithin(root: Element | null | undefined): HTMLElement | null {\n  return svFocusableWithin(root)[0] ?? null;\n}\n","import { svFirstFocusableWithin } from './focusable';\n\n/**\n * What `restore()` actually did. Returned rather than logged, because these are\n * the cases a test has to be able to tell apart — \"focus went somewhere\" is the\n * assertion that lets all three of X-6's defects through.\n */\nexport type SvFocusRestoreOutcome =\n  /** The element that opened the overlay is still there and took focus back. */\n  | 'opener'\n  /** The opener is gone; focus landed in the nearest part of the page that survived it. */\n  | 'neighbour'\n  /** The opener's whole scope is gone; focus landed in the surface underneath. */\n  | 'below'\n  /** The page itself changed; focus landed on its main landmark. */\n  | 'fallback'\n  /** The user had already moved on. Nothing was touched — this is a success. */\n  | 'moved'\n  /** Nothing focusable survived. The caller should say so in dev mode. */\n  | 'none';\n\nexport interface SvFocusScopeOptions {\n  /**\n   * The overlay's own root. Focus inside it still belongs to the overlay, so\n   * restoring is correct; focus anywhere else means the user has already moved\n   * and restoring would YANK THEM BACK.\n   *\n   * A getter, not an element: the panel is usually portalled a tick after the\n   * scope is created.\n   */\n  readonly within?: () => Element | null | undefined;\n  /** The surface this overlay was opened from, when it was opened from one. */\n  readonly below?: () => Element | null | undefined;\n  /**\n   * The element to treat as the opener, when the surface knows it outright.\n   *\n   * ★ For a menu or a popover the trigger IS the opener, and it is a better\n   *   answer than `document.activeElement` — Safari does not focus a button on\n   *   click, so the capture would be `<body>` on one engine and the trigger on\n   *   the other two, and the family would restore correctly only where the\n   *   browser happened to cooperate.\n   */\n  readonly opener?: () => Element | null | undefined;\n  /** Last resort when the page itself has changed. Defaults to the main landmark. */\n  readonly fallback?: () => Element | null | undefined;\n  /**\n   * A region that is being emptied, and is therefore not somewhere to land.\n   *\n   * ★★ THE IN-PLACE CASE NEEDS THIS AND THE PORTALLED ONE DOES NOT. An overlay\n   *    tears down its whole panel, so the ancestor walk starts outside it\n   *    naturally. A banner that dismisses itself does not: its HOST ELEMENT\n   *    survives — only the content inside it is removed — so the nearest\n   *    \"surviving ancestor\" of the close button is an empty, invisible wrapper.\n   *    Focusing that is barely better than `<body>`: nothing is announced and\n   *    there is nothing there to read. Naming the region excludes it and its\n   *    descendants from the walk, so focus continues outward to the part of\n   *    the page that still has content.\n   */\n  readonly skip?: () => Element | null | undefined;\n  /** Injectable for SSR and tests. */\n  readonly document?: Document;\n}\n\nexport interface SvFocusScope {\n  /** Call as the overlay opens, BEFORE it moves focus into itself. */\n  capture(): void;\n  /** Call as the overlay closes. Safe to call twice; the second is a no-op. */\n  restore(): SvFocusRestoreOutcome;\n  /** The element captured at open time, if it is still in the document. */\n  readonly opener: HTMLElement | null;\n}\n\n/**\n * ★★★ RESTORING FOCUS IS NOT \"FOCUS THE ELEMENT I SAVED\".\n *\n * Every family in this kit saved `document.activeElement` on open and called\n * `.focus()` on it on close, and every one of them was right about the case\n * they tested: open a dialog from a button, close it, the button gets focus\n * back. The three cases nobody tested all end the same way — `focus()` on a\n * detached element does NOTHING, silently, and focus falls to `<body>`, where\n * the next Tab starts again from the top of the document and a screen reader\n * says nothing at all. The user has no idea where they are.\n *\n *   1. **The trigger was removed while the overlay was open.** This is not an\n *      edge case, it is the SINGLE MOST COMMON DIALOG THERE IS: a confirm\n *      dialog whose whole purpose is to delete the row the trigger sits in.\n *      The better the dialog works, the more reliably it loses focus.\n *   2. **A route changed underneath it.** The opener's entire subtree is gone.\n *   3. **The overlay was nested inside another scope** that closed first, so\n *      the opener is in a portal that no longer exists.\n *\n * So this walks OUTWARD from where the user was until it finds something that\n * survived, and it is specific about what it found. The order is the order of\n * least surprise: the opener, then the nearest surviving ancestor of the\n * opener, then the surface underneath, then the page's main landmark.\n *\n * ★★ THE ANCESTOR CHAIN IS RECORDED AT OPEN TIME, AND IT HAS TO BE.\n *    The tempting version of this function records nothing and walks\n *    `parentElement` from the detached opener at close time. It is wrong, and\n *    it is wrong in the exact case it was written for: removing the row CUTS\n *    THE LINK AT THE ROW. The opener keeps its parent — the `<li>` — but that\n *    `<li>`'s own `parentElement` is `null` the moment it leaves the list, so\n *    the walk dead-ends one step above the opener and never reaches the\n *    container that survived. A detached subtree keeps its links INSIDE\n *    itself; it does not keep the one that was severed. The chain must\n *    therefore be captured while it is still whole — which is exactly when\n *    `capture()` runs.\n *\n * ★ `<body>` is never an answer. A walk that reaches it has found nothing —\n *   body is connected by definition, so accepting it would turn every failure\n *   back into the silent one this exists to prevent.\n */\nfunction canTakeFocusAgain(el: HTMLElement | null): el is HTMLElement {\n  return (\n    !!el &&\n    el.isConnected &&\n    !el.hasAttribute('disabled') &&\n    !el.hidden &&\n    !el.closest('[inert]')\n  );\n}\n\n/**\n * ★★ SAFARI DOES NOT FOCUS A BUTTON ON A CLICK OR A TAP.\n *    An overlay opened from a button's click handler therefore captured\n *    `<body>` on WebKit and the button on Blink and Gecko, and only two engines\n *    got focus back on close (FL-F8, the action sheet's phone e2e). A surface\n *    that knows its trigger passes `opener`; one opened programmatically — a\n *    sheet, a drawer, a modal behind `[(open)]` — cannot. So the document's\n *    last press is remembered: when `activeElement` is `<body>` at capture, the\n *    focusable control the user pressed a moment ago is the opener.\n */\nconst PRESS_WINDOW_MS = 1000;\nconst FOCUSABLE_PRESS_TARGET =\n  'button, a[href], input, select, textarea, summary, [tabindex]:not([tabindex=\"-1\"]), [contenteditable=\"true\"]';\nconst lastPress = new WeakMap<Document, { el: HTMLElement; at: number }>();\n\nfunction trackPresses(doc: Document): void {\n  if (lastPress.has(doc) || !doc.defaultView) return;\n  lastPress.set(doc, { el: doc.body, at: 0 });\n  doc.addEventListener(\n    'pointerdown',\n    (event) => {\n      const target = event.target instanceof Element ? event.target.closest<HTMLElement>(FOCUSABLE_PRESS_TARGET) : null;\n      if (target) lastPress.set(doc, { el: target, at: Date.now() });\n    },\n    { capture: true, passive: true },\n  );\n}\n\nfunction recentPress(doc: Document): HTMLElement | null {\n  const press = lastPress.get(doc);\n  return press && press.el !== doc.body && Date.now() - press.at <= PRESS_WINDOW_MS && press.el.isConnected ? press.el : null;\n}\n\nexport function createFocusScope(options: SvFocusScopeOptions = {}): SvFocusScope {\n  const doc = options.document ?? (typeof document !== 'undefined' ? document : null);\n  if (doc) trackPresses(doc);\n  let opener: HTMLElement | null = null;\n  /** The opener's ancestors, outermost last, as they stood when it had focus. */\n  let ancestors: HTMLElement[] = [];\n\n  const focusIn = (container: Element | null | undefined): HTMLElement | null => {\n    const first = svFirstFocusableWithin(container);\n    if (first) { first.focus(); return first; }\n    return null;\n  };\n\n  /**\n   * Focus a container that has nothing focusable inside it.\n   *\n   * `tabindex=\"-1\"` is added and left: removing it on blur is a listener per\n   * restore for no benefit, and `-1` changes nothing about tab order — it only\n   * makes the element a legal `focus()` target.\n   */\n  const focusContainer = (el: Element | null | undefined): HTMLElement | null => {\n    if (!(el instanceof HTMLElement) || !el.isConnected) return null;\n    if (el.tabIndex < 0 && !el.hasAttribute('tabindex')) el.setAttribute('tabindex', '-1');\n    el.focus();\n    return el;\n  };\n\n  return {\n    get opener() { return opener?.isConnected ? opener : null; },\n\n    capture(): void {\n      if (!doc) return;\n      const explicit = options.opener?.();\n      const focused = doc.activeElement === doc.body ? null : doc.activeElement;\n      const active = explicit ?? focused ?? recentPress(doc);\n      opener = active instanceof HTMLElement && active !== doc.body ? active : null;\n      ancestors = [];\n      for (let n = opener?.parentElement ?? null; n; n = n.parentElement) ancestors.push(n);\n    },\n\n    restore(): SvFocusRestoreOutcome {\n      if (!doc) return 'none';\n      const saved = opener;\n      const chain = ancestors;\n      opener = null;\n      ancestors = [];\n\n      // 1. Has the user already moved on? Focus that is neither nowhere nor\n      //    inside this overlay belongs to something the user chose — an\n      //    outside click that landed on another control, most often. Taking it\n      //    away is a bug of its own, and the one families \"fixed\" by restoring\n      //    unconditionally.\n      //    ★ The opener itself is not \"somewhere else\". Focus often never left\n      //      it — a popover that never took focus, a dialog closed before it\n      //      mounted — and calling that a user move would turn the commonest\n      //      no-op into a reported failure.\n      const active = doc.activeElement;\n      const elsewhere =\n        active instanceof HTMLElement &&\n        active !== doc.body &&\n        active !== doc.documentElement &&\n        active !== saved &&\n        !(options.within?.()?.contains(active) ?? false);\n      if (elsewhere) return 'moved';\n\n      // Nothing had focus when this opened, so there is nothing to put back.\n      // Moving focus anyway would be an unsolicited jump the user did not ask\n      // for — a different bug, not a smaller one.\n      if (!saved) return 'none';\n\n      // 2. The opener itself, if it is still there AND can still take focus. A\n      //    button that survived but is now disabled is not an answer either —\n      //    `focus()` on it is the same silent no-op.\n      //\n      //    ★ The test here is deliberately weaker than `svIsFocusable`: this\n      //      element DID have focus, so a `tabindex=\"-1\"` panel or any other\n      //      programmatic target still qualifies. Only the things that make\n      //      `focus()` a no-op disqualify it.\n      if (canTakeFocusAgain(saved)) {\n        // ★ Already there: report success without touching it. Re-focusing the\n        //   element that already has focus is not free — it can interrupt an\n        //   IME composition and reset a scroll position — and it is the case\n        //   an auto-dismiss hits while the user is typing somewhere else.\n        if (active !== saved) saved.focus();\n        return 'opener';\n      }\n\n      // 3. Outward from where the opener was, to the first ancestor that\n      //    outlived it. `<body>` and `<html>` do not count.\n      const skip = options.skip?.();\n      for (const node of chain) {\n        if (!node.isConnected) continue;\n        if (node === doc.body || node === doc.documentElement) break;\n        // The region being emptied is not a landing place — see `skip`.\n        if (skip && (node === skip || skip.contains(node))) continue;\n        if (focusIn(node) ?? focusContainer(node)) return 'neighbour';\n      }\n\n      // 4. The surface underneath — the nested case, where the scope that\n      //    contained the opener closed before this one did.\n      const below = options.below?.();\n      if (below && (focusIn(below) ?? focusContainer(below))) return 'below';\n\n      // 5. The page changed. The main landmark is where a screen reader should\n      //    resume, so focus the landmark ITSELF rather than its first control:\n      //    the user needs to hear what page they are on, not to be dropped\n      //    into a nav link three levels in.\n      const fallback =\n        options.fallback?.() ?? doc.querySelector('main, [role=\"main\"]');\n      if (focusContainer(fallback)) return 'fallback';\n\n      return 'none';\n    },\n  };\n}\n","import { svFocusableWithin, svIsFocusable } from './focusable';\nimport type { SvLiveAnnouncer } from '@styloviz/core/a11y';\n\n/**\n * ============================================================================\n *  Where focus goes when the thing holding it disappears — `X-14`\n * ============================================================================\n *\n * Five navigation families drop focus to `<body>` in the same situation and each\n * described it as its own bug: close the active tab (`NV-06-I1`), collapse a\n * panel containing focus (`NV-01-I4`), replace a page of results\n * (`NV-04-I6`), follow an anchor (`NV-02-M7`), dismiss a menu.\n *\n * ── ★ Why `<body>` is the specific failure, and not just untidy ─────────────\n * Focus on `<body>` is not \"focus nowhere\". It is focus at the **top of the\n * document**, so the next Tab goes to the first link on the page — the skip\n * link, the logo — and a keyboard user who deleted one tab out of six is\n * returned to the start of the site with no announcement. They have to find\n * their way back through everything to reach the tab strip they were in. A\n * sighted mouse user sees none of it, which is why it survives review.\n *\n * ── The rule, implemented once ──────────────────────────────────────────────\n * **Move focus to the nearest stable equivalent, announce what happened, and\n * never drop to `<body>`.** Callers supply the equivalents in priority order —\n * for a closed tab that is *next tab, then previous, then the tablist* — and a\n * `fallback` container that will take focus when none of them can.\n *\n * ── ★ Announce WHAT HAPPENED, not WHERE YOU ARE ─────────────────────────────\n * Assistive technology already announces a newly focused element; repeating it\n * is noise, and noise is what gets a live region switched off. The message is\n * for the thing the AT cannot know — *\"Tab closed\"*, *\"Page 3 of 12 loaded\"* —\n * and it is optional, because sometimes the focus move alone says everything.\n */\n\n/**\n * ── The mutation rule — `X-12` ───────────────────────────────────────────────\n * One rule for every collection whose item holding focus is removed by a\n * mutation — a comment posts, a file is removed, a card moves, a tree node is\n * deleted, a lightbox closes, a row is filtered away:\n *\n * 1. **The successor at the same index** — the item that slid into the removed\n *    one's place, so a reader deleting three rows in a row keeps pressing the\n *    same key;\n * 2. else **the predecessor** — the removed item was the last one;\n * 3. else **the container** — the list is now empty (passed as `fallback`);\n * 4. **never `<body>`.**\n *\n * A dialog-like surface that closes (a lightbox) follows the same rule through\n * `createFocusScope`: back to the control that opened it — or, if that control\n * no longer represents what was last shown, to its equivalent (the thumbnail of\n * the image last viewed) — then the component root.\n *\n * {@link svSuccessorIndex} computes step 1–2 on the post-mutation list;\n * {@link svRecoverFocus} applies steps 1–4 to elements.\n *\n * @param removedIndex where the removed item sat in the list BEFORE the mutation.\n * @param remaining how many items the list holds AFTER it.\n * @returns the index to focus in the post-mutation list, or `-1` when the list\n * is empty and focus belongs to the container.\n */\nexport function svSuccessorIndex(removedIndex: number, remaining: number): number {\n  if (remaining <= 0) return -1;\n  if (removedIndex < 0) return 0;\n  return Math.min(removedIndex, remaining - 1);\n}\n\n/** How {@link svRecoverFocus} chooses where focus lands. */\nexport interface SvFocusRecoveryOptions {\n  /**\n   * Candidates in priority order. The first one still in the document and\n   * actually focusable wins.\n   *\n   * Nulls are allowed and skipped, so a caller can write its preference list\n   * without guarding each entry — `[next, previous, list]` reads as the policy\n   * it is.\n   */\n  readonly to: readonly (Element | null | undefined)[];\n\n  /**\n   * Where focus goes when nothing in {@link to} can take it — a container that\n   * still exists, such as the tablist or the nav landmark.\n   *\n   * ★ **This is what \"never drop to `<body>`\" actually means.** It is made\n   * programmatically focusable (`tabindex=\"-1\"`) if it is not already, and the\n   * attribute is removed again when focus leaves, so a container does not stay\n   * marked as a focus target for the rest of the session.\n   */\n  readonly fallback?: Element | null;\n\n  /** What to tell a screen reader about the EVENT. See the note above. */\n  readonly announce?: string;\n\n  /** The announcer to say it through. Injected by the caller; omit for silence. */\n  readonly announcer?: SvLiveAnnouncer | null;\n\n  /**\n   * Focus without scrolling. For a caller that has already scrolled the target\n   * into place itself — a plain `focus()` scrolls too, and in doing so cancels\n   * a smooth scroll that is still running (`SR-11`).\n   * @default false\n   */\n  readonly preventScroll?: boolean;\n}\n\n/**\n * Move focus somewhere sensible after the element holding it has gone.\n *\n * ⚠️ **Call this AFTER the removal has rendered.** Focus cannot move to an\n * element that is not in the document yet, and it cannot be taken from one the\n * browser has already discarded — call it too early and the browser moves focus\n * to `<body>` first, which is the thing being avoided. In a component that means\n * `afterNextRender`, or a task scheduled after the host has re-rendered.\n *\n * @returns the element that received focus, or `null` if nothing could.\n */\nexport function svRecoverFocus(options: SvFocusRecoveryOptions): HTMLElement | null {\n  // ★ `typeof` first: on the server `HTMLElement` is not a global at all, and\n  //   `x instanceof HTMLElement` throws a ReferenceError even when `x` is null.\n  //   Under SSR there is no focus to recover, so this is a no-op returning null.\n  if (typeof HTMLElement === 'undefined') return null;\n\n  const { to, fallback, announce, announcer } = options;\n  const focusOptions: FocusOptions = { preventScroll: options.preventScroll === true };\n\n  const say = (): void => {\n    if (announce && announcer) announcer.announce(announce);\n  };\n\n  for (const candidate of to) {\n    if (!svIsFocusable(candidate)) continue;\n    candidate.focus(focusOptions);\n    say();\n    return candidate;\n  }\n\n  if (fallback instanceof HTMLElement && fallback.isConnected) {\n    // Not `svIsFocusable`: the whole point of a fallback is that it is a plain\n    // container which is not focusable yet, and is about to be made so.\n    const borrowed = !fallback.hasAttribute('tabindex');\n    if (borrowed) fallback.setAttribute('tabindex', '-1');\n\n    fallback.focus(focusOptions);\n\n    if (borrowed) {\n      // Given back when focus leaves. `tabindex=\"-1\"` keeps it out of the tab\n      // order either way, so this is tidiness rather than a fix — but a\n      // container that silently accumulates attributes over a session is how a\n      // later reader concludes it was always meant to be focusable.\n      fallback.addEventListener(\n        'blur',\n        () => fallback.removeAttribute('tabindex'),\n        { once: true },\n      );\n    }\n\n    say();\n    return fallback;\n  }\n\n  return null;\n}\n\n/** Where focus sat inside a keyed collection, taken BEFORE a mutation renders. */\nexport interface SvFocusedItemSnapshot {\n  /** The focused item's key (the value of its key attribute). */\n  readonly key: string;\n  /** The item's position among the rendered items. */\n  readonly index: number;\n  /** Which focusable inside the item held focus (`-1`: the item itself). */\n  readonly control: number;\n}\n\n/**\n * Record which rendered item of a keyed collection holds focus.\n *\n * `items` are the rendered item elements in order; each carries `keyAttr`.\n * Returns `null` when focus is not inside any of them.\n */\nexport function svSnapshotFocusedItem(\n  items: readonly Element[],\n  keyAttr: string,\n): SvFocusedItemSnapshot | null {\n  const active = typeof document === 'undefined' ? null : document.activeElement;\n  if (!active) return null;\n  const index = items.findIndex(item => item === active || item.contains(active));\n  if (index < 0) return null;\n  const item = items[index];\n  const key = item.getAttribute(keyAttr);\n  if (key === null) return null;\n  const control = item === active ? -1 : svFocusableWithin(item).indexOf(active as HTMLElement);\n  return { key, index, control };\n}\n\n/**\n * Apply the mutation rule to a keyed collection after it re-rendered: if the\n * item in `snapshot` is gone, focus the same control in the item now at its\n * index (then its predecessor), else `fallback` — never `<body>`.\n *\n * An item that is itself the focus target (a roving row) is given\n * `tabindex=\"0\"` first, so it owns the collection's tab stop.\n *\n * @returns the element focused, or `null` when the item is still there (no\n * recovery needed) or nothing could take focus.\n */\nexport function svRestoreFocusedItem(\n  items: readonly Element[],\n  keyAttr: string,\n  snapshot: SvFocusedItemSnapshot,\n  options: Omit<SvFocusRecoveryOptions, 'to'> = {},\n): HTMLElement | null {\n  if (items.some(item => item.getAttribute(keyAttr) === snapshot.key)) return null;\n  const successor = items[svSuccessorIndex(snapshot.index, items.length)] as HTMLElement | undefined;\n  let target: Element | null = null;\n  if (successor) {\n    if (snapshot.control < 0) {\n      successor.tabIndex = 0;\n      target = successor;\n    } else {\n      const controls = svFocusableWithin(successor);\n      target = controls[Math.min(snapshot.control, controls.length - 1)] ?? null;\n    }\n  }\n  return svRecoverFocus({ ...options, to: [target] });\n}\n","/**\n * One positioning engine for every anchored surface.\n *\n * ★★★ FOUR IMPLEMENTATIONS OF ONE ALGORITHM, DIVERGING ON EXACTLY THE PARTS\n *     THAT MATTER. Popover, Dropdown Menu and Popout each carried their own\n *     rect → flip → switch → clamp routine, and Tooltip had a static CSS class\n *     map with no measurement at all. They agreed on the easy 80%: put the\n *     panel under the trigger. They disagreed, or were silent, on every case\n *     that actually breaks — RTL, a transformed ancestor, an anchor that\n *     disappears, a cursor at the edge of the screen, where the arrow points.\n *     `X-7`.\n *\n * ★★ A PURE FUNCTION, DELIBERATELY. Everything here is arithmetic over two\n *    rectangles and a viewport, so it is testable without a browser, a DOM or\n *    a layout — which matters because the defects being fixed are all\n *    arithmetic and none of them can be reproduced in jsdom through a\n *    component. The caller measures; this decides.\n */\n\n/** The part of a `DOMRect` this engine needs. */\nexport interface SvRect {\n  readonly top: number;\n  readonly left: number;\n  readonly width: number;\n  readonly height: number;\n}\n\n/** Twelve placements: four sides, each with start / center / end alignment. */\nexport type SvPlacementSide = 'top' | 'bottom' | 'left' | 'right';\nexport type SvPlacementAlign = 'start' | 'center' | 'end';\nexport type SvPlacement =\n  | 'top' | 'top-start' | 'top-end'\n  | 'bottom' | 'bottom-start' | 'bottom-end'\n  | 'left' | 'left-start' | 'left-end'\n  | 'right' | 'right-start' | 'right-end';\n\nexport interface SvPositionRequest {\n  /** The trigger's rect, or a zero-size rect at a cursor point. */\n  readonly anchor: SvRect;\n  /** The panel's measured size. */\n  readonly panel: { readonly width: number; readonly height: number };\n  readonly placement: SvPlacement;\n  /** Gap between anchor and panel, in px. @default 8 */\n  readonly offset?: number;\n  /** Flip to the opposite side when the preferred one does not fit. @default true */\n  readonly flip?: boolean;\n  /** Minimum gap to the viewport edge, in px. @default 8 */\n  readonly margin?: number;\n  /** @default the window's inner size */\n  readonly viewport?: { readonly width: number; readonly height: number };\n  /**\n   * Mirror `start`/`end` for right-to-left text.\n   *\n   * ★ `start` means \"the edge text starts at\", which is the RIGHT edge in RTL.\n   *   Every one of the four implementations hard-coded it to the left, so a\n   *   menu on an Arabic or Hebrew page opened away from its trigger.\n   */\n  readonly rtl?: boolean;\n  /**\n   * The containing block the returned coordinates are relative to.\n   *\n   * ★★★ THIS IS `OF-12-I5`, AND IT IS NOT AN EDGE CASE ON A MODERN PAGE. A\n   *     `position: fixed` panel is normally positioned against the viewport,\n   *     so viewport-relative rects can be used directly — but ANY ancestor\n   *     with a `transform`, `filter`, `perspective`, `backdrop-filter` or\n   *     `will-change` becomes the containing block instead, and every\n   *     coordinate is then off by that element's offset. A page-transition\n   *     animation on a wrapper is enough to do it, which is why the symptom\n   *     is \"the menu is fine until the route animates\".\n   *\n   *     Pass the containing block's own rect and the result is corrected for\n   *     it. Omit it when the panel is a child of `<body>` with no transformed\n   *     ancestor, which is the common case.\n   */\n  readonly container?: SvRect | null;\n  /** Distance the arrow is kept from the panel's corners, in px. @default 16 */\n  readonly arrowInset?: number;\n}\n\nexport interface SvPositionResult {\n  /** Coordinates for the panel, relative to the containing block. */\n  readonly top: number;\n  readonly left: number;\n  /** The placement actually used, after flipping. */\n  readonly placement: SvPlacement;\n  /** Whether the panel had to be pulled back from a viewport edge. */\n  readonly clamped: boolean;\n  /** Arrow offset along the panel's cross axis, relative to the panel. */\n  readonly arrowX: number;\n  readonly arrowY: number;\n}\n\nconst DEFAULTS = { offset: 8, margin: 8, arrowInset: 16 } as const;\n\nconst sideOf = (placement: SvPlacement): SvPlacementSide =>\n  placement.split('-')[0] as SvPlacementSide;\n\nconst alignOf = (placement: SvPlacement): SvPlacementAlign => {\n  const part = placement.split('-')[1];\n  return part === 'start' || part === 'end' ? part : 'center';\n};\n\nconst compose = (side: SvPlacementSide, align: SvPlacementAlign): SvPlacement =>\n  (align === 'center' ? side : `${side}-${align}`) as SvPlacement;\n\nconst OPPOSITE: Record<SvPlacementSide, SvPlacementSide> = {\n  top: 'bottom', bottom: 'top', left: 'right', right: 'left',\n};\n\n/** Flip `start` ⇄ `end`; `center` is unchanged. */\nconst mirror = (align: SvPlacementAlign): SvPlacementAlign =>\n  align === 'start' ? 'end' : align === 'end' ? 'start' : 'center';\n\n/** Does a panel of this size fit on `side` of the anchor? */\nfunction fits(\n  side: SvPlacementSide,\n  anchor: SvRect,\n  panel: { width: number; height: number },\n  offset: number,\n  margin: number,\n  vw: number,\n  vh: number,\n): boolean {\n  switch (side) {\n    case 'bottom': return anchor.top + anchor.height + offset + panel.height + margin <= vh;\n    case 'top':    return anchor.top - offset - panel.height - margin >= 0;\n    case 'right':  return anchor.left + anchor.width + offset + panel.width + margin <= vw;\n    case 'left':   return anchor.left - offset - panel.width - margin >= 0;\n  }\n}\n\n/**\n * Where an anchored panel goes.\n *\n * Returns coordinates, the placement actually used, whether it had to be\n * clamped, and where its arrow should point.\n */\nexport function svPositionAnchored(request: SvPositionRequest): SvPositionResult {\n  const offset = request.offset ?? DEFAULTS.offset;\n  const margin = request.margin ?? DEFAULTS.margin;\n  const arrowInset = request.arrowInset ?? DEFAULTS.arrowInset;\n  const { anchor, panel } = request;\n  const vw = request.viewport?.width ?? (typeof window !== 'undefined' ? window.innerWidth : 0);\n  const vh = request.viewport?.height ?? (typeof window !== 'undefined' ? window.innerHeight : 0);\n\n  let side = sideOf(request.placement);\n  // ★ RTL mirrors the ALIGNMENT, not the side. A `bottom-start` menu opens\n  //   below its trigger in both directions; what changes is which edge they\n  //   line up on.\n  const align = request.rtl ? mirror(alignOf(request.placement)) : alignOf(request.placement);\n\n  if ((request.flip ?? true) && !fits(side, anchor, panel, offset, margin, vw, vh)) {\n    // ★★ ONLY FLIP IF THE OTHER SIDE IS ACTUALLY BETTER. Flipping into a space\n    //    that does not fit either just moves the clamping to the other end and\n    //    puts the panel over the trigger the user is looking at.\n    if (fits(OPPOSITE[side], anchor, panel, offset, margin, vw, vh)) side = OPPOSITE[side];\n  }\n\n  const anchorCenterX = anchor.left + anchor.width / 2;\n  const anchorCenterY = anchor.top + anchor.height / 2;\n\n  let top: number;\n  let left: number;\n\n  if (side === 'top' || side === 'bottom') {\n    top = side === 'bottom' ? anchor.top + anchor.height + offset : anchor.top - offset - panel.height;\n    left =\n      align === 'start' ? anchor.left\n      : align === 'end' ? anchor.left + anchor.width - panel.width\n      : anchorCenterX - panel.width / 2;\n  } else {\n    left = side === 'right' ? anchor.left + anchor.width + offset : anchor.left - offset - panel.width;\n    top =\n      align === 'start' ? anchor.top\n      : align === 'end' ? anchor.top + anchor.height - panel.height\n      : anchorCenterY - panel.height / 2;\n  }\n\n  // ★ Clamp to the viewport. `Math.max(margin, …)` on the upper bound matters\n  //   for a panel TALLER than the viewport: without it the upper bound falls\n  //   below the lower one and the panel is pinned to the bottom edge, showing\n  //   its end instead of its beginning.\n  const maxLeft = Math.max(margin, vw - panel.width - margin);\n  const maxTop = Math.max(margin, vh - panel.height - margin);\n  const clampedLeft = Math.min(Math.max(left, margin), maxLeft);\n  const clampedTop = Math.min(Math.max(top, margin), maxTop);\n  const clamped = clampedLeft !== left || clampedTop !== top;\n\n  // ★★ THE ARROW IS MEASURED FROM THE CLAMPED PANEL, NOT THE INTENDED ONE.\n  //    That is the whole point of computing it here: once a panel has been\n  //    pulled back from an edge, an arrow placed at the panel's centre no\n  //    longer points at the trigger — it points at where the panel WOULD have\n  //    been, which reads as pointing at nothing.\n  const arrowX = Math.min(\n    Math.max(anchorCenterX - clampedLeft, arrowInset),\n    Math.max(arrowInset, panel.width - arrowInset),\n  );\n  const arrowY = Math.min(\n    Math.max(anchorCenterY - clampedTop, arrowInset),\n    Math.max(arrowInset, panel.height - arrowInset),\n  );\n\n  // Correct for a containing block that is not the viewport — see `container`.\n  const originX = request.container?.left ?? 0;\n  const originY = request.container?.top ?? 0;\n\n  return {\n    top: clampedTop - originY,\n    left: clampedLeft - originX,\n    placement: compose(side, align),\n    clamped,\n    arrowX,\n    arrowY,\n  };\n}\n\n/**\n * Has the anchor stopped being something a panel can point at?\n *\n * ★★★ AN ORPHANED PANEL IS WORSE THAN A CLOSED ONE. `OF-12-I3`, `OF-11-I3`:\n *     the row a menu was opened from is deleted, or the toolbar it hangs off\n *     collapses, and the panel stays exactly where it was — floating over\n *     unrelated content, still listing actions for a thing that is gone. The\n *     caller closes on `true`.\n *\n * ★★ ZERO SIZE COUNTS, AND THAT IS THE HALF A `isConnected` CHECK MISSES. An\n *    anchor inside a collapsed accordion, a `display: none` sidebar or a\n *    closed `<details>` is still in the document and still has a parent — it\n *    just has no position any more, and a rect of 0×0 at 0,0 sends the panel\n *    to the top-left corner of the screen. Which is what it did.\n */\nexport function svAnchorLost(anchor: Element | null | undefined): boolean {\n  if (!anchor || !anchor.isConnected) return true;\n  const rect = anchor.getBoundingClientRect();\n  return rect.width === 0 && rect.height === 0;\n}\n\n/**\n * Is the pointer inside the corridor between a trigger and its panel?\n *\n * ★★★ THE GAP IS THE BUG. A hover popover sits `offset` pixels away from its\n *     trigger, so travelling to it means leaving the trigger — and a plain\n *     `mouseleave` close fires while the pointer is in mid-air over that gap.\n *     Every library that gets this right uses the same trick: treat the\n *     triangle between where the pointer left and the panel's near edge as\n *     still being \"on\" the trigger. `OF-12-I1`, `OF-12-M2`.\n *\n * ★★ A TRIANGLE, NOT A BOUNDING BOX. The union of trigger and panel is much\n *    easier to compute and much too generous: with a panel below-left of its\n *    trigger it keeps the popover open while the pointer moves down-RIGHT,\n *    away from both. A safe area you cannot leave is not a safe area, it is a\n *    stuck popover.\n *\n * `from` is the pointer position at the moment it left the trigger.\n */\nexport function svInSafeCorridor(\n  point: { x: number; y: number },\n  from: { x: number; y: number },\n  panel: SvRect,\n  options: SvSafeCorridorOptions = {},\n): boolean {\n  const right = panel.left + panel.width;\n  const bottom = panel.top + panel.height;\n\n  // Inside the panel itself is always safe.\n  if (point.x >= panel.left && point.x <= right && point.y >= panel.top && point.y <= bottom) {\n    return true;\n  }\n  const [apex, a, b] = svSafeCorridorTriangle(from, panel, options);\n  return pointInTriangle(point, [apex.x, apex.y], [a.x, a.y], [b.x, b.y]);\n}\n\n/** Tuning for {@link svInSafeCorridor} and {@link svSafeCorridorTriangle}. */\nexport interface SvSafeCorridorOptions {\n  /**\n   * How far behind the departure point the corridor's apex sits, in px. Larger\n   * forgives more backwards wobble as the hand sets off; it never widens the\n   * wedge's far edge, which is always the panel's near side.\n   * @default 6\n   */\n  readonly slop?: number;\n}\n\n/**\n * The corridor as three points — apex, then the panel's two near corners —\n * for a host that wants to SEE it (a hover-intent visualiser, a debug overlay).\n * Same geometry {@link svInSafeCorridor} tests against.\n */\nexport function svSafeCorridorTriangle(\n  from: { x: number; y: number },\n  panel: SvRect,\n  options: SvSafeCorridorOptions = {},\n): readonly [{ x: number; y: number }, { x: number; y: number }, { x: number; y: number }] {\n  const slop = Math.max(0, options.slop ?? CORRIDOR_SLOP);\n  // The panel's two corners nearest the departure point, forming the far edge\n  // of the corridor.\n  const right = panel.left + panel.width;\n  const bottom = panel.top + panel.height;\n  const corners: [number, number][] =\n    from.y <= panel.top ? [[panel.left, panel.top], [right, panel.top]]\n    : from.y >= bottom ? [[panel.left, bottom], [right, bottom]]\n    : from.x <= panel.left ? [[panel.left, panel.top], [panel.left, bottom]]\n    : [[right, panel.top], [right, bottom]];\n\n  // ★★ THE APEX SITS A FEW PIXELS BEHIND THE DEPARTURE POINT, NOT ON IT.\n  //    `from` comes from a `pointerleave`, whose coordinates are fractional\n  //    (150.4), and the moves that follow are often `mousemove`s, whose are\n  //    whole pixels (150). With the apex exactly on the departure point, the\n  //    very first move after leaving the trigger — straight toward the panel —\n  //    rounded to a point fractionally BEHIND the apex, fell outside the wedge,\n  //    and closed the panel on the spot: the store's \"All Categories\" menu\n  //    vanished as the pointer crossed the 8px gap below its trigger. A hand\n  //    also wobbles a pixel or two backwards when it sets off. Moving the apex\n  //    `slop` px away from the panel absorbs both without widening the wedge\n  //    anywhere a pointer heading elsewhere could use it.\n  const apex =\n    from.y <= panel.top ? { x: from.x, y: from.y - slop }\n    : from.y >= bottom ? { x: from.x, y: from.y + slop }\n    : from.x <= panel.left ? { x: from.x - slop, y: from.y }\n    : { x: from.x + slop, y: from.y };\n  return [apex, { x: corners[0][0], y: corners[0][1] }, { x: corners[1][0], y: corners[1][1] }];\n}\n\n/** How far behind the departure point the corridor's apex sits. See above. */\nconst CORRIDOR_SLOP = 6;\n\n/** Barycentric sign test — no square roots, no trigonometry, no epsilon. */\nfunction pointInTriangle(\n  p: { x: number; y: number },\n  a: [number, number],\n  b: [number, number],\n  c: [number, number],\n): boolean {\n  const cross = (\n    ax: number, ay: number, bx: number, by: number, cx: number, cy: number,\n  ) => (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);\n\n  const d1 = cross(a[0], a[1], b[0], b[1], p.x, p.y);\n  const d2 = cross(b[0], b[1], c[0], c[1], p.x, p.y);\n  const d3 = cross(c[0], c[1], a[0], a[1], p.x, p.y);\n  const hasNeg = d1 < 0 || d2 < 0 || d3 < 0;\n  const hasPos = d1 > 0 || d2 > 0 || d3 > 0;\n  return !(hasNeg && hasPos);\n}\n\n/** What {@link svInlineAnchor} needs: the trigger's inline extent and the panel's width. */\nexport interface SvInlineAnchorRequest {\n  /**\n   * The trigger's rect — `left` and `width`, or `right` when present (a\n   * `DOMRect` carries both; `right` wins so a partial rect cannot disagree).\n   */\n  readonly anchor: Pick<SvRect, 'left' | 'width'> & { readonly right?: number };\n  /** The panel's width, or the trigger's width for a panel that matches it. */\n  readonly panelWidth: number;\n  /** @default window.innerWidth */\n  readonly viewportWidth?: number;\n  /** Lay the panel out right-to-left — `start` is then the trigger's RIGHT edge. @default false */\n  readonly rtl?: boolean;\n  /** Minimum gap to the viewport edge, in px. @default 8 */\n  readonly margin?: number;\n}\n\n/** Where an edge-pinned panel sits on the inline axis. */\nexport interface SvInlineAnchor {\n  /**\n   * `true` when the panel lines up on the trigger's END edge because lining\n   * it up on the start edge would run it off the viewport.\n   */\n  readonly alignEnd: boolean;\n  /** The PHYSICAL viewport edge the panel is pinned to. */\n  readonly edge: 'left' | 'right';\n  /** Distance from {@link edge}, never closer than the margin. */\n  readonly offset: number;\n  /** The room from the pinned edge to the opposite one, minus the margin. */\n  readonly maxWidth: number;\n  /** The same placement as one clamped `left` coordinate, for panels positioned by `left` only. */\n  readonly left: number;\n}\n\n/**\n * The inline-axis half of {@link svPositionAnchored}, for a panel pinned to a\n * viewport EDGE rather than placed at a measured coordinate.\n *\n * ★★★ WHY FORM PANELS PIN TO AN EDGE. A picker opens before its panel has\n *     been measured — the panel is rendered into its portal on the same tick —\n *     so it cannot be placed by its size the way a popover is. Pinning it to a\n *     viewport edge (`left`/`right`, and `bottom` when it opens above) makes\n *     the real size irrelevant: the panel hangs from the edge whatever it\n *     turns out to be. Eleven form overlays did that arithmetic by hand and\n *     all eleven hard-coded the LEFT edge as the start (`X-7`), so on an RTL\n *     page a calendar wider than its trigger opened away from it.\n *\n * ★★ THE DECISION IS `svPositionAnchored`'S. Start alignment is tried through\n *    the shared engine — which owns the RTL mirror — and the panel falls back\n *    to the end edge only when the engine had to pull it back from the FAR\n *    edge. A trigger hanging off the NEAR edge keeps start alignment and is\n *    clamped by the margin, which is what every hand-rolled copy did too.\n */\nexport function svInlineAnchor(request: SvInlineAnchorRequest): SvInlineAnchor {\n  const margin = request.margin ?? DEFAULTS.margin;\n  const vw = request.viewportWidth ?? (typeof window !== 'undefined' ? window.innerWidth : 0);\n  const { anchor, panelWidth } = request;\n  const rtl = request.rtl ?? false;\n  const right = anchor.right ?? anchor.left + anchor.width;\n  const width = right - anchor.left;\n\n  // A zero-height probe on an unbounded block axis: only the inline result\n  // can be clamped, so the engine's pull-back reads as an inline overflow.\n  const probe = (placement: SvPlacement, gap: number) =>\n    svPositionAnchored({\n      anchor: { top: 0, left: anchor.left, width, height: 0 },\n      panel: { width: panelWidth, height: 0 },\n      placement,\n      rtl,\n      flip: false,\n      offset: 0,\n      margin: gap,\n      viewport: { width: vw, height: Number.MAX_SAFE_INTEGER },\n    });\n\n  const start = probe('bottom-start', 0);\n  const rawStart = rtl ? right - panelWidth : anchor.left;\n  // Pulled back from the far edge: left in LTR, right in RTL.\n  const alignEnd = rtl ? start.left > rawStart : start.left < rawStart;\n\n  // Start in LTR and end in RTL both line up on the trigger's left edge.\n  const edge: 'left' | 'right' = alignEnd !== rtl ? 'right' : 'left';\n  const offset = Math.max(margin, edge === 'left' ? anchor.left : vw - right);\n\n  return {\n    alignEnd,\n    edge,\n    offset,\n    maxWidth: vw - offset - margin,\n    left: probe(alignEnd ? 'bottom-end' : 'bottom-start', margin).left,\n  };\n}\n","/**\n * ============================================================================\n *  svFixedOrigin — where a `position: fixed` child of this element really sits\n * ============================================================================\n *\n * ★★★ THE HEURISTIC THIS REPLACES WAS WRONG IN THE COMMON CASE, AND THE BUG\n *     ONLY SHOWED UP AT A VIEWPORT EDGE.\n *\n *     `svPositionAnchored` takes a `container` rect so a panel whose containing\n *     block is NOT the viewport can be corrected for it — a real problem, since\n *     any ancestor with `transform`, `filter`, `perspective`, `backdrop-filter`\n *     or `will-change` steals containment from a `fixed` child.\n *\n *     Four components decided whether they were in that situation by asking\n *     whether the portal host's rect was at the origin:\n *\n *         container: host.left !== 0 || host.top !== 0 ? host : null\n *\n *     But a portal host is a plain `<div>` appended to `<body>`. Nothing\n *     positions it, so it lands in normal flow at the END of the document and\n *     its rect is at whatever y the page content happens to end — never zero on\n *     a page with content. The correction therefore fired on every page, with\n *     the wrong number, and the panel was translated by the length of the\n *     document above it.\n *\n *     Why it survived: the correction moves the panel UP by that offset, and a\n *     panel opened in the middle of a tall page is clamped back into view by\n *     the very next step. It is only when the trigger sits at the bottom edge —\n *     where the panel flips upward and has nowhere left to be clamped to — that\n *     the offset survives to the screen. `e2e/overlay-positioning.spec.ts`\n *     parks the trigger at the edge deliberately, and caught three components\n *     drawing their panel 253px above the top of the window: Dropdown Menu,\n *     Popout and Popover.\n *\n * ★★ SO MEASURE IT, DO NOT INFER IT. A zero-size `position: fixed` probe\n *    inside the host reports exactly one thing: the offset a fixed child of\n *    that host is re-based by. `{0, 0}` means the viewport is still the\n *    containing block — whatever the host's own rect says — and anything else\n *    IS the correction, whichever of the six CSS properties caused it and\n *    whichever ancestor carries it.\n *\n * ★ Cheap enough to call per position pass: one append, one\n *   `getBoundingClientRect` (the callers already force layout twice), one\n *   removal. It never paints — the probe has no size and is gone before the\n *   frame ends.\n */\n\n/** The offset a `position: fixed` child of `host` is re-based by. */\nexport interface SvFixedOrigin {\n  readonly top: number;\n  readonly left: number;\n}\n\n// sv-physical: a re-base for getBoundingClientRect coordinates, which are physical and have no logical twin\nconst ZERO: SvFixedOrigin = { top: 0, left: 0 };\n\n/**\n * Measure where a `position: fixed` child of `host` is anchored.\n *\n * Returns `{ top: 0, left: 0 }` when the viewport is the containing block —\n * the common case, and the one where no correction should be applied.\n *\n * @param host The element the panel is portalled into.\n */\nexport function svFixedOrigin(host: Element | null | undefined): SvFixedOrigin {\n  if (!host || typeof document === 'undefined') return ZERO;\n\n  const probe = document.createElement('div');\n  // `visibility: hidden` rather than `display: none`: a display-none element\n  // has no box, so it would report a zero rect on every page and the measure\n  // would always agree with itself.\n  probe.style.cssText = // sv-physical: the probe marks the containing block's physical top-left, which is what a fixed child is offset from\n    'position:fixed;top:0;left:0;width:0;height:0;visibility:hidden;pointer-events:none;'; // sv-i18n-ignore: inline CSS\n  probe.setAttribute('aria-hidden', 'true');\n\n  host.appendChild(probe);\n  const rect = probe.getBoundingClientRect();\n  probe.remove();\n\n  // Sub-pixel noise is not a containing block.\n  const top = Math.abs(rect.top) < 0.5 ? 0 : rect.top;\n  const left = Math.abs(rect.left) < 0.5 ? 0 : rect.left;\n  return top === 0 && left === 0 ? ZERO : { top, left };\n}\n\n/**\n * The `container` rect to hand `svPositionAnchored` for a panel portalled into\n * `host` — or `null` when the viewport is still the containing block.\n *\n * `svPositionAnchored` only reads `top`/`left` off it, so the size is carried\n * for completeness rather than used.\n */\nexport function svFixedContainer(\n  host: HTMLElement | null | undefined,\n): { top: number; left: number; width: number; height: number } | null {\n  const origin = svFixedOrigin(host);\n  if (origin.top === 0 && origin.left === 0) return null;\n  const rect = host!.getBoundingClientRect();\n  return { top: origin.top, left: origin.left, width: rect.width, height: rect.height };\n}\n","/**\n * The scoped context a body portal drops, and what to do about it.\n *\n * ★★★ THE SIX THINGS X-8 NAMES ARE NOT SIX PROBLEMS. Portalling to `<body>`\n *     is how an overlay escapes an `overflow: hidden` ancestor, and it costs\n *     the surface everything it was inheriting from where it used to live:\n *     theme, directionality, density, custom properties, the transformed\n *     coordinate space, and the test fixture's DOM root. Sorted by what can\n *     actually be done about each, they are three different kinds of thing:\n *\n *     • **CARRIED** — `dir`, `lang`, and the theme marker. Each has exactly\n *       one correct value, findable with one `closest()` from the origin, and\n *       copying it is unambiguous. Done automatically, here.\n *     • **DECLARED** — custom properties. The set is unbounded and, worse, not\n *       enumerable: `getComputedStyle` will not list inherited custom\n *       properties in every engine, so \"copy them all\" cannot be written at\n *       all, let alone written portably. The caller names the ones that matter\n *       and they are copied by value.\n *     • **ABANDONED ON PURPOSE** — the transformed coordinate space. Escaping\n *       it IS the reason to portal. Positioning code must therefore measure\n *       against the viewport rather than the origin's parent, which is the\n *       positioning engine's job (`X-7`), not this one's.\n *\n *     The sixth, the test fixture's root, is not a context at all — it is why\n *     every spec for a portalled surface queries `document.body`. `root` makes\n *     it configurable rather than implicit.\n *\n * ★★ WHY THE THEME MARKER IS NOT ALREADY FINE. The usual claim is that the\n *    theme survives, because `.dark` is toggled on `documentElement` and a\n *    body portal inherits from there. That is true and it is not the case that\n *    breaks: a LOCALLY dark section — a preview pane, a code sample, an editor\n *    surface — carries its own `.dark`, and a menu opened from inside it\n *    renders light on a dark page. The marker is copied only when the nearest\n *    one is NOT the document element, so the common case stays a no-op.\n */\n\nimport type { DestroyRef } from '@angular/core';\n\n/** Attributes that carry unambiguously and are copied without being asked. */\nconst CARRIED_ATTRIBUTES = ['dir', 'lang'] as const;\n\nexport interface SvPortalHostOptions {\n  /**\n   * The element the surface would have rendered inside — its component host.\n   * The context is read from here; with no origin nothing is copied.\n   */\n  readonly origin?: Element | null;\n  /** Where the host is appended. @default document.body */\n  readonly root?: Element | null;\n  /** Classes for the host element itself. */\n  readonly className?: string;\n  /**\n   * Custom properties to copy by value from the origin's computed style.\n   *\n   * ★ Named, not enumerated, and the reason is not laziness: inherited custom\n   *   properties cannot be listed from `getComputedStyle` portably, so a\n   *   \"copy everything\" implementation would silently copy a different subset\n   *   in every browser. Naming them makes the set a decision instead of an\n   *   accident.\n   */\n  readonly customProperties?: readonly string[];\n  /** Marks the host in the DOM as `data-sv-portal=\"<label>\"`, for debugging. */\n  readonly label?: string;\n  /** Injectable for SSR and tests. */\n  readonly document?: Document;\n  /**\n   * The OWNER whose destruction also destroys this host (`N-4` ownership\n   * cleanup).\n   *\n   * ★ Optional, and additive: every existing caller destroys in its own\n   *   `ngOnDestroy` and keeps working. Passing the owner's `DestroyRef` makes\n   *   the orphaned `<div>` in `<body>` impossible rather than merely unlikely —\n   *   a component that forgets its teardown path, or throws before reaching it,\n   *   still takes its portal with it.\n   */\n  readonly destroyRef?: DestroyRef;\n}\n\nexport interface SvPortalHost {\n  /**\n   * The host element. Append the surface's nodes to this, THEN `attach()`.\n   *\n   * ⚠️ **With no document (SSR) this is `null` at runtime**, despite the type.\n   *    Typed non-null because every caller creates its host on open — a user\n   *    gesture, which never happens on the server — and widening it now would\n   *    break each of them at compile time for a branch they cannot reach.\n   *    Code that may run without a document checks {@link available} first.\n   */\n  readonly element: HTMLElement;\n  /**\n   * `false` for the server stub returned when there is no document: its\n   * {@link element} is `null` and every method is a no-op. `true` otherwise.\n   */\n  readonly available: boolean;\n  /**\n   * Put the host into the document. Idempotent.\n   *\n   * ★★★ SEPARATE FROM CREATION ON PURPOSE, and the repo has a script about\n   *     why (`scripts/fix-portal-insertion-order.mjs`, proven against\n   *     `sv-mention`): a host that enters `<body>` EMPTY and is filled\n   *     afterwards spends a frame as a static-positioned block at the end of\n   *     the document. If the panel is tall enough the page grows, the browser\n   *     queues a `scroll` event, and any component that closes on scroll\n   *     closes the panel it has just opened. Render first, insert once — so\n   *     this API makes the order explicit instead of hoping each caller\n   *     remembers it.\n   */\n  attach(): void;\n  /**\n   * Re-read the origin's context and re-apply it.\n   *\n   * ★ Not decoration: a theme toggle while a menu is open changes the marker\n   *   under it, and nothing about a copied attribute updates itself.\n   */\n  sync(): void;\n  /** Remove the host from the document. Idempotent. */\n  destroy(): void;\n}\n\n/**\n * The nearest theme marker above `el`, or `null` when the only one is the\n * document element — which a body portal already inherits.\n */\nfunction scopedThemeMarker(\n  el: Element,\n  doc: Document,\n): { className: string | null; theme: string | null } {\n  const darkHost = el.closest('.dark');\n  const themeHost = el.closest('[data-theme]');\n  return {\n    className: darkHost && darkHost !== doc.documentElement ? 'dark' : null,\n    theme:\n      themeHost && themeHost !== doc.documentElement\n        ? themeHost.getAttribute('data-theme')\n        : null,\n  };\n}\n\n/** Create a context-carrying portal host. */\nexport function createPortalHost(options: SvPortalHostOptions = {}): SvPortalHost {\n  const doc = options.document ?? (typeof document !== 'undefined' ? document : null);\n  if (!doc) {\n    // SSR: a stub that does nothing and cannot be appended to anything. The\n    // one cast in this file, and it is the documented one on `element`: there\n    // is no document to create an element from, so `null` is the honest value\n    // and `available: false` is how a caller finds out.\n    return {\n      element: null as unknown as HTMLElement,\n      available: false,\n      attach: () => undefined,\n      sync: () => undefined,\n      destroy: () => undefined,\n    };\n  }\n\n  const element = doc.createElement('div');\n  if (options.className) element.className = options.className;\n  if (options.label) element.setAttribute('data-sv-portal', options.label);\n\n  const apply = (): void => {\n    const origin = options.origin;\n    if (!origin) return;\n\n    for (const attr of CARRIED_ATTRIBUTES) {\n      const marked = origin.closest(`[${attr}]`);\n      const value = marked?.getAttribute(attr);\n      // ★ Only a SCOPED value is copied. Taking the document element's `dir`\n      //   would pin the host to the value it already inherits, so a later\n      //   change to it would stop reaching this surface and only this one.\n      if (value && marked !== doc.documentElement) element.setAttribute(attr, value);\n      else element.removeAttribute(attr);\n    }\n\n    const { className, theme } = scopedThemeMarker(origin, doc);\n    element.classList.toggle('dark', className === 'dark');\n    if (theme) element.setAttribute('data-theme', theme);\n    else element.removeAttribute('data-theme');\n\n    const names = options.customProperties;\n    if (names?.length && typeof window !== 'undefined') {\n      const computed = window.getComputedStyle(origin);\n      for (const name of names) {\n        const value = computed.getPropertyValue(name).trim();\n        if (value) element.style.setProperty(name, value);\n        else element.style.removeProperty(name);\n      }\n    }\n  };\n\n  apply();\n\n  let destroyed = false;\n  // ★ Keep the unregister function. A surface that makes a fresh host on every\n  //   open (Speed Dial) and destroys it on close would otherwise leave one dead\n  //   callback on its owner's DestroyRef per open, all retained until the owner\n  //   itself is destroyed.\n  let unregister: (() => void) | null = null;\n  const destroy = (): void => {\n    if (destroyed) return;\n    destroyed = true;\n    unregister?.();\n    unregister = null;\n    element.remove();\n  };\n  unregister = options.destroyRef?.onDestroy(destroy) ?? null;\n  return {\n    element,\n    available: true,\n    attach: () => {\n      if (destroyed || element.isConnected) return;\n      (options.root ?? doc.body).appendChild(element);\n    },\n    sync: () => { if (!destroyed) apply(); },\n    destroy,\n  };\n}\n","import { InjectionToken, type Provider } from '@angular/core';\n\n/**\n * A tooltip group (SR-35) — the Radix `TooltipProvider` behaviour for a row of\n * controls: the first tooltip waits its delay, and moving to a sibling shows\n * the next one at once, because the user has already shown they are reading\n * the toolbar. Only one tooltip of a group is visible at a time.\n *\n * Provide it with `provideSvTooltipGroup()` in a component's `providers`, or\n * put `svTooltipGroup` (from `@styloviz/overlays`) on the toolbar element.\n */\nexport interface SvTooltipGroup {\n  /** How long a member should wait before showing, given its own `delay`. */\n  delayFor(ownDelay: number): number;\n  /** A member became visible; `close` hides it if another one opens. */\n  opened(id: string, close: () => void): void;\n  /** A member hid. */\n  closed(id: string): void;\n}\n\nexport interface SvTooltipGroupOptions {\n  /** The delay before the FIRST tooltip of the group shows, in ms. @default 600 */\n  readonly delay?: number | (() => number);\n  /** For this long after one hides, the next shows without a delay, in ms. @default 300 */\n  readonly skipDelay?: number | (() => number);\n  /** Clock seam for tests. @default Date.now */\n  readonly now?: () => number;\n}\n\nexport const SV_TOOLTIP_GROUP = new InjectionToken<SvTooltipGroup>('SV_TOOLTIP_GROUP');\n\nconst read = (v: number | (() => number) | undefined, fallback: number): number =>\n  Math.max(0, (typeof v === 'function' ? v() : v) ?? fallback);\n\n/** A group, without DI — for tests, or a host composing its own. */\nexport function createSvTooltipGroup(options: SvTooltipGroupOptions = {}): SvTooltipGroup {\n  const now = options.now ?? Date.now;\n  const open = new Map<string, () => void>();\n  let lastClosed = Number.NEGATIVE_INFINITY;\n  return {\n    delayFor(ownDelay) {\n      // ★ Already reading: a sibling is up, or one went down a moment ago.\n      if (open.size > 0 || now() - lastClosed < read(options.skipDelay, 300)) return 0;\n      return ownDelay > 0 ? ownDelay : read(options.delay, 600);\n    },\n    opened(id, close) {\n      for (const [other, hide] of [...open]) if (other !== id) hide();\n      open.set(id, close);\n    },\n    closed(id) {\n      if (open.delete(id)) lastClosed = now();\n    },\n  };\n}\n\n/** Provide a tooltip group to every tooltip under this injector. */\nexport function provideSvTooltipGroup(options: SvTooltipGroupOptions = {}): Provider[] {\n  return [{ provide: SV_TOOLTIP_GROUP, useFactory: () => createSvTooltipGroup(options) }];\n}\n","import { Injectable } from '@angular/core';\nimport { svWarnOnce } from '@styloviz/core/dev';\n\n/**\n * Which band of the stacking order a surface belongs to.\n *\n * The band decides how surfaces of DIFFERENT kinds sit relative to each other;\n * push order decides how surfaces of the same kind do. The ordering is the one\n * users already expect: a tooltip describing a button inside a dialog has to\n * draw over that dialog, and a toast reporting the result of what you just did\n * has to draw over everything.\n */\nexport type SvOverlayLayer =\n  | 'anchored'   // popover, dropdown, menubar panel, context menu\n  | 'sheet'      // drawer\n  | 'modal'      // modal, confirm dialog, command palette, fullscreen spinner\n  | 'toast'      // toast stack, alert banner\n  | 'tooltip';   // tooltip — always on top, never dismissible\n\n/**\n * ★★★ TWO KINDS OF SURFACE, AND ONLY ONE OF THEM STACKS BY PUSH ORDER.\n *\n * **Interactive** surfaces — anchored, sheet, modal — are things the user\n * navigates INTO, and they nest: a popover opened from a drawer, a select\n * opened from a dialog. Whatever was opened last must paint on top, exactly as\n * it must own Escape. Ranking them by band gets this backwards — a popover\n * (a band below the sheets) opened inside a drawer would RENDER BEHIND THE DRAWER\n * THAT OPENED IT. Measured, not reasoned: the first cut of this file did that\n * and a DOM probe caught it before it shipped. So they share ONE monotonic\n * counter and push order decides.\n *\n * **Ambient** surfaces — toast, tooltip — are not navigated into. They are\n * raised AT the user, and they must clear whatever is on screen whether they\n * arrived before it or after. Push order is wrong for them in the other\n * direction: a toast shown before a dialog opens would be buried by it. So they\n * sit in fixed high bands and do not participate in the counter at all.\n *\n * That is the whole model. Trying to serve both with one rule is what produced\n * two rounds of wrong answers.\n */\n/**\n * The z-index of the first interactive surface (popover, dropdown, drawer,\n * dialog); each one opened after it goes higher.\n *\n * ★★★ IT IS 9999 BECAUSE THE KIT LIVES INSIDE SOMEBODY ELSE'S PAGE. The panels\n *     were `z-[9999]` before the stack existed, and their docs still say so\n *     (`SV_MODEL_OVERLAY_Z_INDEX`, the AI-04-I3 / AI-07-I3 browser tests). The\n *     stack's first cut started the band at 1000, which silently put every kit\n *     dropdown BELOW the overlay systems a host is likely to already have —\n *     Bootstrap's modal (1050–1070), MUI's (1300–1500), the CDK overlay\n *     container (1000) — so a select opened inside the host's own dialog\n *     rendered behind that dialog. 9999 clears them, and stays far below the\n *     ambient bands (toast 100,000, tooltip 200,000): ~9,000 nested surfaces'\n *     headroom. A host whose layers sit above 9999 sets the component's own\n *     z-index input, which wins.\n */\nexport const SV_OVERLAY_Z_FLOOR = 9999;\n\nconst INTERACTIVE_BASE = SV_OVERLAY_Z_FLOOR;\n\n/** Fixed bands for surfaces that never take part in push order. */\nconst AMBIENT_BASE: Partial<Record<SvOverlayLayer, number>> = {\n  toast:   100_000,\n  tooltip: 200_000,\n};\n\n/**\n * z-indexes reserved for each surface, so one registration can paint more than\n * one element.\n *\n * ★ A drawer is a backdrop AND a panel, and the panel must sit above its own\n *   backdrop but below the next surface's backdrop. One number cannot express\n *   that. Each surface therefore owns `zIndex` … `zIndex + 9` and may use the\n *   spare values for its own internal layering.\n *\n * ★ The gap to the ambient bands is ~99,000 — about ten thousand interactive\n *   surfaces' worth. A page that exhausts it has a different problem.\n */\nconst PER_SURFACE = 10;\n\n/**\n * Is this body child one of `SvLiveAnnouncer`'s shared regions?\n *\n * ★★★ AN INERT LIVE REGION IS A SILENT ONE. `inert` removes a subtree from the\n *     accessibility tree, and the announcer's two regions are body children\n *     created once and kept forever — so the first blocking surface to open\n *     used to mark them inert along with the page, and every announcement made\n *     while ANY dialog was open went nowhere: the toast confirming the dialog's\n *     own save, the form error summary's new count, the async confirm's\n *     failure. The regions contain no focusable content, so leaving them live\n *     costs the modal nothing.\n *\n * Matched by the announcer's own `data-sv-live-region` hook rather than by\n * `aria-live`, so a consumer's region is still theirs to manage.\n */\nfunction isSharedLiveRegion(el: Element): boolean {\n  return el.hasAttribute('data-sv-live-region');\n}\n\nexport interface SvOverlayPushOptions {\n  /**\n   * The surface's own rendered root, for outside-click routing.\n   *\n   * ★★ A GETTER, NOT AN ELEMENT, because the panel usually does not exist yet\n   *    at `push()` time — it is portalled into `<body>` a tick later, and for\n   *    some families not until an animation frame has passed. Capturing the\n   *    node here would capture `null` forever.\n   *\n   *    Omit it and the surface simply cannot be asked about; it still stacks\n   *    and still owns Escape. That is the right default for anything with no\n   *    panel of its own.\n   */\n  readonly element?: () => Element | null | undefined;\n\n  /**\n   * Does this surface block interaction with everything behind it?\n   *\n   * ★★★ INERTNESS IS THE ONE OVERLAY DUTY NO COMPONENT CAN DISCHARGE ALONE,\n   *     and that is why it lives here rather than in seven `ngOnInit`s. \"What\n   *     must be inert\" is a fact about every open surface AT ONCE: a modal\n   *     needs the page behind it inert, AND the drawer it was opened from (that\n   *     is background now too), but not the select it opens itself, and not a\n   *     toast — and no single component can see that set. Two components each doing it locally do not converge on the\n   *     right answer, they fight: the modal marks the drawer inert while the\n   *     drawer marks the modal inert, and whichever ran last wins.\n   *\n   * ★ `aria-modal=\"true\"` without this is a LIE THE KIT WAS TELLING. Four tour\n   *   variants and several dialogs assert it over a page that is still fully\n   *   focusable and still fully in the accessibility tree. `aria-modal` is a\n   *   claim about the rest of the document; `inert` is what makes it true.\n   *\n   * @default false\n   */\n  readonly blocking?: boolean;\n\n  /**\n   * Whether this surface can be dismissed by Escape. @default true\n   *\n   * ★ A non-dismissible surface still gets a z-index and still participates in\n   *   ordering — it is simply invisible to `isTopmost()`. Tooltips and toasts\n   *   are the cases: both sit ABOVE a modal, and neither may take Escape from\n   *   it. Without this distinction a toast arriving mid-dialog would silently\n   *   become the thing Escape closes.\n   */\n  readonly dismissible?: boolean;\n}\n\n/** A surface's registration. Release it when the surface closes. */\nexport interface SvOverlayHandle {\n  /**\n   * The z-index this surface should render at. Stable for its lifetime.\n   *\n   * The surface also owns the nine values above it — see `PER_SURFACE`. A\n   * drawer paints its backdrop at `zIndex` and its panel at `zIndex + 1`.\n   */\n  readonly zIndex: number;\n  /**\n   * True only when this is the topmost DISMISSIBLE surface on the stack.\n   *\n   * This is the Escape test. Call it in the Escape handler and return early\n   * when it is false.\n   */\n  isTopmost(): boolean;\n  /**\n   * Did this click land inside a surface opened ABOVE this one?\n   *\n   * ★★★ THE BUG THIS ANSWERS. Every anchored family closes on an outside\n   *     click, and each decides \"outside\" by asking whether the target is\n   *     inside its own trigger or its own panel. But a nested overlay —\n   *     a select inside a popover, a confirm dialog over a menu — is\n   *     PORTALLED TO `<body>`, so it is inside neither. Clicking one of its\n   *     options therefore reads as a click outside the parent, and the parent\n   *     closes while the user is still using the thing it opened.\n   *\n   *     Local containment cannot see this, because the nesting is a fact about\n   *     the stack rather than about the DOM. Call this before closing.\n   */\n  isInsideHigherSurface(target: Node): boolean;\n\n  /**\n   * The rendered root of the nearest surface pushed BEFORE this one, or `null`.\n   *\n   * ★★ THIS IS THE ONLY PLACE THAT CAN ANSWER IT. \"What was I opened from?\" is\n   *    a fact about the stack, not about the DOM: both surfaces are portalled\n   *    to `<body>` as siblings, so nothing in the tree records that one of them\n   *    was opened from inside the other. Focus restoration needs it for the\n   *    nested case — when the scope that contained the opener is torn down\n   *    before this surface closes, the opener's parent chain leads nowhere and\n   *    the surface underneath is the only sensible place left to land.\n   */\n  surfaceBelow(): Element | null;\n\n  /** Remove this surface from the stack. Idempotent. */\n  release(): void;\n}\n\ninterface Entry {\n  readonly id: number;\n  readonly layer: SvOverlayLayer;\n  readonly dismissible: boolean;\n  readonly blocking: boolean;\n  readonly zIndex: number;\n  readonly element?: () => Element | null | undefined;\n}\n\n/**\n * The overlay stack — who is on top, and who owns Escape.\n *\n * ★★★ THE DEFECT THIS EXISTS TO FIX IS NOT THEORETICAL, AND IT SHIPPED.\n *     `sv-drawer` and `sv-popover` each carried an unconditioned\n *     `@HostListener('document:keydown.escape')` gated only on their OWN\n *     `open()`. The listener is on `document`, so it fires for every instance\n *     at once: with two drawers open, ONE ESCAPE CLOSED BOTH. Same for two\n *     popovers, and for a popover opened from inside a drawer. Every family\n *     answered \"is this keystroke mine?\" locally, and locally the answer is\n *     always yes.\n *\n * ★★★ WHY PUSH ORDER AND NOT THE LAYER DECIDES ESCAPE. It is tempting to say\n *     a modal outranks a popover, so the modal owns Escape. That is wrong, and\n *     it is wrong in the commonest nesting there is: a select dropdown opened\n *     inside a dialog. The user presses Escape expecting the dropdown to close\n *     and the dialog to stay — and a layer-ranked rule closes the dialog out\n *     from under a half-finished form. The surface the user opened LAST is the\n *     one they are interacting with, whatever band it belongs to. So push order\n *     decides ownership; the layer decides only how things paint.\n *\n * ★★ WHY `isTopmost()` IS A QUERY AND NOT AN EVENT. A pushed-based design —\n *    the service listening on `document` and calling the top entry — would\n *    have to own each surface's close semantics, which differ: the drawer\n *    refuses Escape while `loading`, the popover has `closeOnEsc`, the confirm\n *    dialog blocks mid-request. Asking rather than telling leaves those rules\n *    where they belong and makes this service a fact, not a controller.\n *\n * Root-scoped deliberately: one document, one stack. Two instances would each\n * believe they held the top.\n */\n@Injectable({ providedIn: 'root' })\nexport class SvOverlayStackService {\n  private readonly _entries: Entry[] = [];\n  private _nextId = 0;\n\n  /**\n   * The highest z-index handed to an INTERACTIVE surface so far.\n   *\n   * ★ Monotonic, and never reset on release: restarting it would let a newly\n   *   opened panel land on the value of one still on screen, and which of the\n   *   two paints on top would then depend on DOM order — i.e. on nothing the\n   *   component controls.\n   */\n  private _lastZ = INTERACTIVE_BASE - PER_SURFACE;\n\n  /** Per-band ordinal for the ambient layers, which do not share the counter. */\n  private readonly _ambient: Record<string, number> = {};\n\n  /**\n   * The elements this service marked `inert`, so it can unmark exactly those.\n   */\n  private readonly _inertedByUs = new Set<Element>();\n\n  /** Register an opening surface. Call `release()` on the handle when it closes. */\n  push(layer: SvOverlayLayer, options: SvOverlayPushOptions = {}): SvOverlayHandle {\n    const entry: Entry = {\n      id: this._nextId++,\n      layer,\n      dismissible: options.dismissible ?? true,\n      blocking: options.blocking ?? false,\n      element: options.element,\n      zIndex: this._assignZ(layer),\n    };\n    this._entries.push(entry);\n    this._syncInert();\n\n    let released = false;\n    return {\n      zIndex: entry.zIndex,\n      isTopmost: () => this._topDismissibleId() === entry.id,\n      isInsideHigherSurface: (target: Node) => this._isInsideAbove(entry, target),\n      surfaceBelow: () => this._surfaceBelow(entry),\n      release: () => {\n        if (released) return;\n        released = true;\n        const i = this._entries.indexOf(entry);\n        if (i !== -1) this._entries.splice(i, 1);\n        this._syncInert();\n      },\n    };\n  }\n\n  /** How many surfaces are currently registered. Tests and diagnostics. */\n  get size(): number { return this._entries.length; }\n\n  private _assignZ(layer: SvOverlayLayer): number {\n    const ambient = AMBIENT_BASE[layer];\n    if (ambient !== undefined) {\n      const n = this._ambient[layer] ?? 0;\n      this._ambient[layer] = n + 1;\n      return ambient + n * PER_SURFACE;\n    }\n    // Interactive: strictly above everything already open.\n    this._lastZ += PER_SURFACE;\n    return this._lastZ;\n  }\n\n  /**\n   * Walk only the entries pushed AFTER this one.\n   *\n   * ★ Push order, not z-index: an ambient toast painting at 100,000 is above\n   *   everything, but a click on it is not a click \"inside\" the popover\n   *   underneath and must not keep that popover open.\n   */\n  private _isInsideAbove(entry: Entry, target: Node): boolean {\n    const from = this._entries.indexOf(entry);\n    if (from === -1) return false;\n    for (let i = from + 1; i < this._entries.length; i++) {\n      const el = this._entries[i].element?.();\n      if (el?.contains(target)) return true;\n    }\n    return false;\n  }\n\n  /**\n   * The nearest surface below this one that actually has a rendered root.\n   *\n   * ★ Surfaces pushed without an `element` getter are skipped rather than\n   *   terminating the search: they are invisible to every other stack query\n   *   too, and stopping at one would report \"nothing below\" for a surface that\n   *   plainly has something below it.\n   */\n  private _surfaceBelow(entry: Entry): Element | null {\n    const from = this._entries.indexOf(entry);\n    if (from <= 0) return null;\n    for (let i = from - 1; i >= 0; i--) {\n      const el = this._entries[i].element?.();\n      if (el?.isConnected) return el;\n    }\n    return null;\n  }\n\n  /**\n   * Make everything that is not part of an open surface `inert`, or undo it.\n   *\n   * ★★ MARKS BODY CHILDREN, AND THAT IS THE WHOLE TECHNIQUE. Every surface in\n   *    this kit is portalled to `<body>`, so the page and the surfaces are\n   *    SIBLINGS: one pass over `body.children`, excluding any child that holds\n   *    a live surface, is the complete answer. Walking into the page to find\n   *    \"the focusable things behind the dialog\" would be a much larger\n   *    operation and a strictly worse one — it has to run again every time the\n   *    page changes, and it cannot express \"and the accessibility tree too\",\n   *    which `inert` gets for free.\n   *\n   * ★ Only attributes WE set are removed again. A consumer may have its own\n   *   `inert` on a collapsed region, and taking that off when a dialog closes\n   *   would hand them a bug they cannot explain.\n   *\n   * ★★ AND THE SNAPSHOT IS WHAT PROTECTS THE OVERLAY'S OWN PORTAL. `push()`\n   *    runs a tick before the panel is portalled, so at pass time there is\n   *    nothing of this surface's in `<body>` yet — and because the pass only\n   *    ever marks children that ALREADY EXIST, the portal that arrives a tick\n   *    later is never marked. I wrote a `syncInert()` hook for the handle\n   *    first, to \"catch up\" after mounting, and then could not write a test\n   *    that failed without it: every family's portal either predates the push\n   *    or arrives after the pass. It is gone rather than kept as an API nobody\n   *    can justify. If a `MutationObserver` is ever added here, the exclusion\n   *    below is what will keep the overlay's own nodes interactive.\n   *\n   * ⚠️ A body child appended WHILE a blocking surface is open is not marked.\n   *   Fixing that needs a `MutationObserver` on `<body>` for the lifetime of\n   *   every modal, and the case it buys — a third-party widget injecting\n   *   itself mid-dialog — is not worth that. Said plainly rather than left to\n   *   be discovered.\n   */\n  private _syncInert(): void {\n    const doc = typeof document !== 'undefined' ? document : null;\n    if (!doc?.body) return;\n\n    if (!this._entries.some((e) => e.blocking)) {\n      this._clearInert();\n      return;\n    }\n\n    // ★★★ ONLY WHAT IS ABOVE THE TOPMOST BLOCKING SURFACE STAYS LIVE (`X-4`:\n    //     \"who is inert? Everything below the topmost modal surface, including\n    //     other overlays\"). A drawer with a confirm dialog over it is BACKGROUND\n    //     to that dialog: its controls must not be tabbable, and a screen\n    //     reader's virtual cursor must not wander into it while `aria-modal`\n    //     says the dialog is all there is. The first cut kept EVERY open\n    //     surface live, which made the drawer under the dialog exactly as\n    //     reachable as if the dialog were not modal at all.\n    //\n    //     What stays live: the topmost blocking surface, everything opened\n    //     after it (the select inside the dialog), and the AMBIENT bands at\n    //     any depth — a toast or tooltip is raised at the user, not navigated\n    //     into, and switching it off would silence the very thing that reports\n    //     the outcome of what the dialog just did.\n    let topBlocking = -1;\n    for (let i = this._entries.length - 1; i >= 0; i--) {\n      if (this._entries[i].blocking) { topBlocking = i; break; }\n    }\n    const live = this._entries\n      .filter((e, i) => i >= topBlocking || AMBIENT_BASE[e.layer] !== undefined)\n      .map((e) => e.element?.())\n      .filter((el): el is Element => !!el?.isConnected);\n\n    let marked = 0;\n    for (const child of Array.from(doc.body.children)) {\n      const holdsSurface = live.some((el) => child === el || child.contains(el));\n      if (holdsSurface || isSharedLiveRegion(child)) {\n        if (this._inertedByUs.delete(child)) child.removeAttribute('inert');\n        continue;\n      }\n      if (child.hasAttribute('inert')) continue;\n      child.setAttribute('inert', '');\n      this._inertedByUs.add(child);\n      marked++;\n    }\n\n    // ★★ A BLOCKING SURFACE THAT IS NOT PORTALLED CANNOT MAKE ANYTHING INERT,\n    //    because it lives inside the very page it is trying to switch off —\n    //    excluding its body-level ancestor excludes the whole app. The pass\n    //    then does nothing at all, silently, and `aria-modal` goes on lying.\n    //    Saying so is the only useful thing this code can do about it.\n    if (marked === 0 && this._inertedByUs.size === 0) {\n      svWarnOnce(\n        'overlay-stack:inert-noop',\n        'a blocking overlay is open but nothing could be made inert — the surface is ' +\n          'probably not portalled to <body>, so the page behind it is still focusable ' +\n          'and still in the accessibility tree.',\n      );\n    }\n  }\n\n  private _clearInert(): void {\n    for (const el of this._inertedByUs) el.removeAttribute('inert');\n    this._inertedByUs.clear();\n  }\n\n  private _topDismissibleId(): number | null {\n    for (let i = this._entries.length - 1; i >= 0; i--) {\n      if (this._entries[i].dismissible) return this._entries[i].id;\n    }\n    return null;\n  }\n}\n","import { DestroyRef, effect, inject, signal, untracked, type Signal } from '@angular/core';\nimport { SvOverlayStackService, type SvOverlayHandle, type SvOverlayLayer } from './overlay-stack';\n\nexport interface SvStackedPopupOptions {\n  /** Whether the popup is open. Read inside an effect, so pass a signal read. */\n  readonly open: () => boolean;\n  /**\n   * The popup's rendered panel, for outside-click routing and inertness.\n   * A getter, because a portalled panel usually does not exist yet when the\n   * popup opens — see `SvOverlayPushOptions.element`.\n   */\n  readonly element?: () => Element | null | undefined;\n  /** @default 'anchored' */\n  readonly layer?: SvOverlayLayer;\n}\n\nexport interface SvStackedPopup {\n  /**\n   * Does this popup own Escape right now?\n   *\n   * `true` when it is the topmost dismissible surface — and ALSO when it is\n   * not registered at all (closed, or SSR), so a handler can gate on it\n   * unconditionally: `if (!popup.ownsEscape()) return;`.\n   */\n  ownsEscape(): boolean;\n  /**\n   * Did this pointer event land inside a surface opened ABOVE this popup (a\n   * dialog opened from one of its options, a nested menu)? Such a click is\n   * not \"outside\", and must not close the popup.\n   */\n  isInsideHigherSurface(target: EventTarget | null): boolean;\n  /** z-index from the stack while open, `null` while closed. */\n  readonly zIndex: Signal<number | null>;\n}\n\n/**\n * Put a small popup (a picker, a suggestion list, a select panel) on the\n * overlay stack for exactly as long as it is open (`X-4`, `OF-09-I1`).\n *\n * ★★★ THE DEFECT THIS CLOSES. The form popups each closed on their own\n *     `document:keydown.escape` and `document:mousedown`, and none of them was\n *     on the stack. So the stack's answer to \"who owns Escape?\" skipped them:\n *     a time picker opened inside a modal left the MODAL topmost, the modal's\n *     own keydown (which runs before any document listener) closed the modal,\n *     and one Escape took the picker and the half-filled dialog with it. The\n *     popup was open and the stack did not know.\n *\n * ★★ WHY A HELPER AND NOT FOUR LINES IN EACH COMPONENT. Register on open,\n *    release on close, release on destroy while open — every popup needs the\n *    same three, and the destroy case is the one a hand-written copy forgets\n *    (a picker removed by an `@if` while open would hold Escape forever).\n *\n * Call in an injection context (a field initializer or the constructor).\n */\nexport function svStackedPopup(options: SvStackedPopupOptions): SvStackedPopup {\n  const stack = inject(SvOverlayStackService);\n  const zIndex = signal<number | null>(null);\n  let handle: SvOverlayHandle | null = null;\n\n  const release = (): void => {\n    handle?.release();\n    handle = null;\n    zIndex.set(null);\n  };\n\n  effect(() => {\n    const open = options.open();\n    untracked(() => {\n      if (typeof document === 'undefined') return;\n      if (open && !handle) {\n        handle = stack.push(options.layer ?? 'anchored', { element: options.element });\n        zIndex.set(handle.zIndex);\n      } else if (!open && handle) {\n        release();\n      }\n    });\n  });\n\n  inject(DestroyRef).onDestroy(release);\n\n  return {\n    ownsEscape: () => !handle || handle.isTopmost(),\n    isInsideHigherSurface: (target) =>\n      !!handle && target instanceof Node && handle.isInsideHigherSurface(target),\n    zIndex: zIndex.asReadonly(),\n  };\n}\n"],"mappings":";;;;AAyCA,SAAgB,gBAAgB,QAAqB;CACnD,OAAO,WAAW,WAAW,WAAW,YAAY,iBAAiB;AACvE;AAkEA,MAAM,uBAAiD,CAAC,cAAc;AAuCtE,SAAgB,iBAAiB,UAA+B,CAAA,GAAE;CAChE,MAAM,UAAU,OAA6B,MAAK,GAAA,YAAA,CAAA,EAAA,WAAA,UAAA,CAAA,+BAAA,CAAA,CAAA;CAwClD,OAAO;EAnCL,WAAW,eAAe,QAAO,MAAO,IAAI;EAC5C,eAAe,QAAQ,WAAU;EAEjC,UAAU,WAAkC;GAM1C,IAAI,QAAO,MAAO,MAAM,OAAO;GAE/B,MAAM,QAAQ,QAAQ,QAAO;GAC7B,IAAI,SAAS,MAAM,MAAM,MAAM,OAAO,OAAO;GAE7C,MAAM,QAAQ,QAAQ,QAAO,KAAM;GACn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