All files / components openable.ts

94.64% Statements 371/392
92.85% Branches 299/322
96.92% Functions 63/65
98.52% Lines 333/338

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752                                                                                                                                                                                                                                                                                                                    5x 5x 5x 5x 5x   5x       202x           279x   5x 182x 182x 239x       5x 130x 130x   82x 82x 82x 82x 95x 95x 95x 95x     82x 82x 39x     1x       82x 82x 39x     1x       82x 101x 101x     82x       82x 100x 100x 2x 2x         5x 702x 566x 566x 566x 130x 130x 130x 130x       566x       5x 134x 134x     5x 568x     5x 568x 568x               5x   5x 67x 67x 15x   52x     11x 11x   28x   4x 7x     39x 39x   51x   35x 4x     52x       7x       52x     52x 52x       67x 67x 67x 67x 67x 67x 67x 67x 52x 52x         5x     11x     190x 190x 190x 190x                         190x 190x 190x       190x 190x 190x     190x 479x 479x 479x       479x 479x 479x         149x 330x             190x             29x     190x 48x 48x 48x 48x 48x 48x 48x 48x 48x                     190x 1x 1x 1x 1x 1x     190x 3x 3x 1x     190x 379x 379x 379x 379x 379x 379x 379x   379x   379x 1555x       1176x   379x 379x 379x 379x 67x 67x 67x 67x 52x 52x 52x 52x 52x 52x 52x   67x 67x 52x         52x 15x 1x     67x 81x   67x     148x     67x     81x         67x 67x   67x 67x 67x 67x   67x 67x 67x 67x     67x                   5x 1x 4x 4x     7x         1x 6x     4x 1x     101x 101x 41x     37x   5x 101x 101x 101x 101x     101x 101x 41x     7x     5x 101x 101x 101x 101x     100x 100x     67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x   67x 67x   67x 67x 47x 47x 47x     47x 47x 47x 47x   67x           379x     379x 378x 378x 312x 66x 66x 66x 66x   77x     66x 379x       29x 29x           4x 25x 25x       190x 272x 272x 272x 272x   272x   272x         272x 272x 272x 164x 164x 164x 164x   272x 272x 1232x 272x 268x 272x 266x 266x 264x 264x     266x 272x           95x 95x 94x 72x 72x     265x 263x 263x   265x 106x 106x 106x 106x       190x 340x 304x 304x 304x 304x 304x 277x 277x   304x       190x 190x   190x           178x 134x 17x   73x 71x       71x 71x 71x 71x 42x 38x 38x 36x 36x         189x 189x 189x 189x 189x 189x 189x   189x   189x 189x 189x 189x 189x 189x        
import { createRuntimeId } from '../accessibility/ids';
import { createControllerHost } from '../core/host';
import { createDisposableScope } from '../core/disposables';
import type {
  ChangeDetails,
  ControllableValueOptions,
  RuntimeController,
  RuntimeEventSource,
  Unsubscribe,
} from '../core/types';
import {
  eventTargets,
  inertSiblings,
  isHTMLElement,
  listen,
  lockDocumentScroll,
  observeDocumentInteraction,
} from '../dom/dom';
import { focusInitial, restoreFocus, trapFocus } from '../focus/focus';
import { createControllableValue } from '../state/controllable';
import {
  autoUpdatePosition,
  calculatePosition,
  type FloatingPositionOptions,
  type PositionResult,
  type VirtualAnchor,
} from '../positioning/positioning';
 
/** Cause union shared by dialog, popover, menus, and navigation overlays. @public */
export type OpenChangeReason =
  | 'programmatic'
  | 'trigger'
  | 'escape-key'
  | 'outside-pointer'
  | 'focus-out'
  | 'selection'
  | 'context-menu'
  | 'keyboard'
  | 'hover'
  | 'focus';
 
/** Payload emitted before and after an overlay open-state transition. @public */
export interface OpenChangeEvent<TReason extends OpenChangeReason = OpenChangeReason> {
  /** Requested next state. */
  readonly open: boolean;
  /** Typed cause and optional native event. */
  readonly details: ChangeDetails<TReason>;
}
 
/** Lifecycle events consistently emitted by openable controllers. @public */
export interface OpenLifecycleEvents<TReason extends OpenChangeReason = OpenChangeReason> {
  /** Cancellable event emitted before opening. */
  readonly beforeOpen: OpenChangeEvent<TReason>;
  /** Event emitted after the open snapshot is published. */
  readonly open: OpenChangeEvent<TReason>;
  /** Event emitted after opening resources and focus are established. */
  readonly afterOpen: OpenChangeEvent<TReason>;
  /** Cancellable event emitted before closing. */
  readonly beforeClose: OpenChangeEvent<TReason>;
  /** Event emitted after the closed snapshot is published. */
  readonly close: OpenChangeEvent<TReason>;
  /** Event emitted after resources are released and focus restoration is attempted. */
  readonly afterClose: OpenChangeEvent<TReason>;
  /** Event emitted for every accepted open-state mutation. */
  readonly stateChange: OpenChangeEvent<TReason>;
}
 
/** DOM elements bound to an overlay controller. @public */
export interface OverlayElements {
  /** Optional trigger or focus restoration target. */
  readonly trigger?: HTMLElement;
  /** Floating dialog, popover, or menu element. */
  readonly content: HTMLElement;
  /** Optional backdrop treated as an outside-interaction target. */
  readonly backdrop?: HTMLElement;
  /** Optional positioned anchor; defaults to `trigger`. */
  readonly anchor?: Element | VirtualAnchor;
  /** Descendant overlay branches that remain inside this overlay. */
  readonly branches?: readonly Element[];
}
 
/** Immutable shared snapshot for openable components. @public */
export interface OpenSnapshot {
  /** Current externally observable open state. */
  readonly open: boolean;
  /** Whether state ownership belongs to the consumer. */
  readonly controlled: boolean;
  /** Whether this overlay is the topmost overlay in its owner document. */
  readonly topmost: boolean;
  /** Stable content ID used by trigger relationships. */
  readonly contentId: string;
  /** Semantic role for consumer-rendered content. */
  readonly role: string;
  /** Latest calculated coordinates, or `null` before positioning. */
  readonly position: PositionResult | null;
}
 
/** Shared options used by overlay-style component factories. @internal */
export interface OpenControllerOptions extends Partial<
  ControllableValueOptions<boolean, OpenChangeReason>
> {
  /** Consumer-provided deterministic content ID. */
  readonly id?: string;
  /** WAI-ARIA role exposed in the snapshot. */
  readonly role: string;
  /** Whether opening traps focus, locks scroll, and inerts siblings. */
  readonly modal?: boolean;
  /** Whether Escape closes the topmost overlay. @defaultValue `true` */
  readonly closeOnEscape?: boolean;
  /** Whether outside pointer interactions close the overlay. @defaultValue `true` */
  readonly closeOnOutsidePointer?: boolean;
  /** Whether focus leaving all overlay branches closes it. @defaultValue `false` */
  readonly closeOnFocusOutside?: boolean;
  /** Whether keyboard focus is contained while open. */
  readonly trapFocus?: boolean;
  /** Whether the pre-open focus target is restored on close. */
  readonly restoreFocus?: boolean;
  /** Preferred initial focus target resolved after binding. */
  readonly initialFocus?: () => HTMLElement | null;
  /** Whether opening moves focus into content. Defaults to modal/trapping overlays. */
  readonly focusOnOpen?: boolean;
  /** Whether pointer/focus-out dismissal restores the pre-open target. */
  readonly restoreFocusOnOutside?: boolean;
  /** Shared anchored positioning options. */
  readonly positioning?: FloatingPositionOptions;
}
 
/** Internal overlay primitive reused by all public overlay controllers. @internal */
export interface OpenController
  extends RuntimeController<OpenSnapshot>, RuntimeEventSource<OpenLifecycleEvents> {
  open(details: ChangeDetails<OpenChangeReason>): void;
  close(details: ChangeDetails<OpenChangeReason>): void;
  toggle(details: ChangeDetails<OpenChangeReason>): void;
  bind(elements: OverlayElements): () => void;
  updatePosition(): void;
}
 
interface StackEntry {
  readonly id: string;
  readonly content: HTMLElement;
  readonly interactionBoundaries: readonly Element[];
  readonly focusScopes: readonly Element[];
  readonly inertBranches: readonly Element[];
  readonly trapsFocus: boolean;
  readonly modal: boolean;
  readonly order: number;
  handleEscape(event: KeyboardEvent): void;
  handlePointerOutside(event: PointerEvent): void;
  handleFocusOutside(event: FocusEvent): void;
  setFocusTrap(scopes: readonly Element[] | undefined): void;
  setInertScope(branches: readonly Element[] | undefined): void;
  publish(topmost: boolean): void;
}
 
const overlayStacks = new WeakMap<Document, StackEntry[]>();
const overlayStackOrders = new WeakMap<Document, number>();
const overlayReconcileQueue = new Set<Document>();
let overlayMutationDepth = 0;
let flushingOverlayReconcileQueue = false;
 
const sameElements = (
  left: readonly Element[] | undefined,
  right: readonly Element[] | undefined,
): boolean =>
  left === right ||
  (left !== undefined &&
    right !== undefined &&
    left.length === right.length &&
    left.every((element, index) => element === right[index]));
 
const uniqueElements = (elements: readonly Element[]): readonly Element[] => [...new Set(elements)];
 
const stackMatches = (ownerDocument: Document, expected: readonly StackEntry[]): boolean => {
  const current = overlayStacks.get(ownerDocument) ?? [];
  return (
    current.length === expected.length && current.every((entry, index) => entry === expected[index])
  );
};
 
const reconcileOverlayDocument = (ownerDocument: Document): void => {
  const stack = [...(overlayStacks.get(ownerDocument) ?? [])];
  if (stack.length === 0) return;
 
  let focusOwnerIndex = -1;
  let modalOwnerIndex = -1;
  let index = stack.length;
  for (const entry of [...stack].reverse()) {
    index -= 1;
    if (focusOwnerIndex < 0 && entry.trapsFocus) focusOwnerIndex = index;
    if (modalOwnerIndex < 0 && entry.modal) modalOwnerIndex = index;
    if (focusOwnerIndex >= 0 && modalOwnerIndex >= 0) break;
  }
 
  const focusOwner = stack[focusOwnerIndex];
  if (focusOwner) {
    focusOwner.setFocusTrap(
      uniqueElements([
        ...focusOwner.focusScopes,
        ...stack.slice(focusOwnerIndex + 1).flatMap((entry) => entry.focusScopes),
      ]),
    );
  }
  const modalOwner = stack[modalOwnerIndex];
  if (modalOwner) {
    modalOwner.setInertScope(
      uniqueElements([
        ...modalOwner.inertBranches,
        ...stack.slice(modalOwnerIndex + 1).flatMap((entry) => entry.focusScopes),
      ]),
    );
  }
  for (const entry of stack) {
    if (entry !== focusOwner) entry.setFocusTrap(undefined);
    if (entry !== modalOwner) entry.setInertScope(undefined);
  }
 
  Iif (!stackMatches(ownerDocument, stack)) {
    overlayReconcileQueue.add(ownerDocument);
    return;
  }
  for (const [index, entry] of stack.entries()) {
    entry.publish(index === stack.length - 1);
    if (!stackMatches(ownerDocument, stack)) {
      overlayReconcileQueue.add(ownerDocument);
      return;
    }
  }
};
 
const flushOverlayReconcileQueue = (): void => {
  if (overlayMutationDepth > 0 || flushingOverlayReconcileQueue) return;
  flushingOverlayReconcileQueue = true;
  try {
    while (overlayReconcileQueue.size > 0) {
      for (const ownerDocument of overlayReconcileQueue) {
        overlayReconcileQueue.delete(ownerDocument);
        reconcileOverlayDocument(ownerDocument);
        break;
      }
    }
  } finally {
    flushingOverlayReconcileQueue = false;
  }
};
 
const requestOverlayReconcile = (ownerDocument: Document): void => {
  overlayReconcileQueue.add(ownerDocument);
  flushOverlayReconcileQueue();
};
 
const beginOverlayMutation = (): void => {
  overlayMutationDepth += 1;
};
 
const endOverlayMutation = (): void => {
  overlayMutationDepth -= 1;
  flushOverlayReconcileQueue();
};
 
interface OverlayDocumentDispatcher {
  count: number;
  readonly release: Unsubscribe;
}
 
const overlayDocumentDispatchers = new WeakMap<Document, OverlayDocumentDispatcher>();
 
const acquireOverlayDocumentDispatcher = (ownerDocument: Document): Unsubscribe => {
  const current = overlayDocumentDispatchers.get(ownerDocument);
  if (current) {
    current.count += 1;
  } else {
    const releaseInteractions = observeDocumentInteraction({
      ownerDocument,
      onPointerDown(event) {
        const topmost = overlayStacks.get(ownerDocument)?.at(-1);
        if (
          !topmost ||
          topmost.interactionBoundaries.some((boundary) => eventTargets(event, boundary))
        )
          return;
        topmost.handlePointerOutside(event);
      },
      onFocusIn(event) {
        const topmost = overlayStacks.get(ownerDocument)?.at(-1);
        if (
          !topmost ||
          topmost.interactionBoundaries.some((boundary) => eventTargets(event, boundary))
        )
          return;
        topmost.handleFocusOutside(event);
      },
    });
    const releaseEscape = listen<KeyboardEvent>(
      ownerDocument,
      'keydown',
      (event) => {
        if (event.key === 'Escape') overlayStacks.get(ownerDocument)?.at(-1)?.handleEscape(event);
      },
      true,
    );
    overlayDocumentDispatchers.set(ownerDocument, {
      count: 1,
      release() {
        releaseEscape();
        releaseInteractions();
      },
    });
  }
  let active = true;
  return () => {
    Iif (!active) return;
    active = false;
    const dispatcher = overlayDocumentDispatchers.get(ownerDocument);
    Iif (!dispatcher) return;
    dispatcher.count -= 1;
    if (dispatcher.count === 0) {
      dispatcher.release();
      overlayDocumentDispatchers.delete(ownerDocument);
    }
  };
};
 
const details = <TReason extends OpenChangeReason>(
  reason: TReason,
  event: Event,
): ChangeDetails<TReason> => ({ reason, event });
 
export function createOpenController(options: OpenControllerOptions): OpenController {
  const id = options.id ?? createRuntimeId(options.role);
  const controlled = options.getValue !== undefined;
  const initialOpen = options.getValue?.() ?? options.defaultValue ?? false;
  const host = createControllerHost<OpenSnapshot, OpenLifecycleEvents>({
    open: initialOpen,
    controlled,
    topmost: false,
    contentId: id,
    role: options.role,
    position: null,
  });
  interface BindingRegistration {
    readonly elements: OverlayElements;
    readonly token: symbol;
  }
  let binding: BindingRegistration | undefined;
  let openResources = createDisposableScope();
  let restoreTarget: HTMLElement | null = null;
  let restoreTargetCaptured = false;
  let activeEntry: StackEntry | undefined;
  let sessionDocument: Document | undefined;
  let sessionOrder: number | undefined;
  let currentPosition: PositionResult | null = null;
  let resourceGeneration = 0;
  let transitionGeneration = 0;
  let lifecycleRequestInFlight: boolean | undefined;
 
  const refreshSnapshot = (topmost?: boolean): void => {
    const open = state.get();
    const currentBinding = binding;
    const stack = currentBinding
      ? overlayStacks.get(currentBinding.elements.content.ownerDocument)
      : undefined;
    const resolvedTopmost =
      open && (topmost ?? (activeEntry !== undefined && stack?.at(-1) === activeEntry));
    const current = host.getSnapshot();
    if (
      current.open === open &&
      current.topmost === resolvedTopmost &&
      current.position === currentPosition
    )
      return;
    host.update({
      ...current,
      open,
      topmost: resolvedTopmost,
      position: currentPosition,
    });
  };
  const state = createControllableValue<boolean, OpenChangeReason>(
    {
      defaultValue: options.defaultValue ?? false,
      ...(options.getValue ? { getValue: options.getValue } : {}),
      ...(options.onValueChange ? { onValueChange: options.onValueChange } : {}),
      ...(options.subscribeValue ? { subscribeValue: options.subscribeValue } : {}),
    },
    (open, changeDetails) => commit(open, changeDetails),
  );
 
  const calculateBoundPosition = (currentBinding: BindingRegistration): PositionResult | null => {
    const { content } = currentBinding.elements;
    const anchor = currentBinding.elements.anchor ?? currentBinding.elements.trigger;
    Iif (!anchor) return null;
    const rectangle = anchor.getBoundingClientRect();
    const floating = content.getBoundingClientRect();
    const ownerWindow = content.ownerDocument.defaultView;
    const viewportWidth = options.positioning?.viewportWidth ?? ownerWindow?.innerWidth;
    const viewportHeight = options.positioning?.viewportHeight ?? ownerWindow?.innerHeight;
    return calculatePosition(
      rectangle,
      { width: floating.width, height: floating.height },
      {
        ...options.positioning,
        ...(viewportWidth !== undefined ? { viewportWidth } : {}),
        ...(viewportHeight !== undefined ? { viewportHeight } : {}),
      },
    );
  };
 
  const updatePositionFor = (currentBinding: BindingRegistration, generation: number): void => {
    Iif (resourceGeneration !== generation || binding !== currentBinding || !state.get()) return;
    const position = calculateBoundPosition(currentBinding);
    Iif (resourceGeneration !== generation || binding !== currentBinding || !state.get()) return;
    currentPosition = position;
    refreshSnapshot();
  };
 
  const updatePosition = (): void => {
    const currentBinding = binding;
    if (!currentBinding) return;
    updatePositionFor(currentBinding, resourceGeneration);
  };
 
  const syncResources = (): void => {
    resourceGeneration += 1;
    const generation = resourceGeneration;
    const currentBinding = binding;
    const previousResources = openResources;
    const localResources = createDisposableScope();
    openResources = localResources;
    currentPosition = null;
    let createdEntry: StackEntry | undefined;
    let establishingSessionBinding = false;
 
    const isCurrent = (): boolean =>
      host.alive() &&
      resourceGeneration === generation &&
      openResources === localResources &&
      binding === currentBinding;
    const isCurrentOpen = (): boolean => isCurrent() && state.get();
 
    beginOverlayMutation();
    try {
      previousResources.dispose();
      if (isCurrentOpen() && currentBinding) {
        const { content, trigger, backdrop, anchor, branches = [] } = currentBinding.elements;
        const ownerDocument = content.ownerDocument;
        let activeSessionOrder = sessionOrder;
        if (sessionDocument !== ownerDocument || activeSessionOrder === undefined) {
          const order = (overlayStackOrders.get(ownerDocument) ?? 0) + 1;
          overlayStackOrders.set(ownerDocument, order);
          sessionDocument = ownerDocument;
          sessionOrder = order;
          activeSessionOrder = order;
          restoreTarget = null;
          restoreTargetCaptured = false;
        }
        establishingSessionBinding = !restoreTargetCaptured;
        if (establishingSessionBinding) {
          restoreTarget =
            trigger ??
            (isHTMLElement(ownerDocument.activeElement, ownerDocument)
              ? ownerDocument.activeElement
              : null);
          restoreTargetCaptured = true;
        } else if (!restoreTarget?.isConnected && trigger?.isConnected) {
          restoreTarget = trigger;
        }
 
        const focusScopes = uniqueElements(
          [content, ...branches].filter((scope) => scope.ownerDocument === ownerDocument),
        );
        const interactionBoundaries = uniqueElements(
          [content, trigger, ...branches].filter(
            (boundary): boundary is Element =>
              boundary !== undefined && boundary.ownerDocument === ownerDocument,
          ),
        );
        const inertBranches = uniqueElements(
          [backdrop, ...branches].filter(
            (branch): branch is Element =>
              branch !== undefined && branch.ownerDocument === ownerDocument,
          ),
        );
        let installedFocusScopes: readonly Element[] | undefined;
        let installedInertBranches: readonly Element[] | undefined;
        let releaseFocusTrap: Unsubscribe = () => undefined;
        let releaseInertScope: Unsubscribe = () => undefined;
 
        localResources.add(() => {
          releaseFocusTrap();
          releaseFocusTrap = () => undefined;
          installedFocusScopes = undefined;
        });
        localResources.add(() => {
          releaseInertScope();
          releaseInertScope = () => undefined;
          installedInertBranches = undefined;
        });
 
        const entry: StackEntry = {
          id,
          content,
          interactionBoundaries,
          focusScopes,
          inertBranches,
          trapsFocus: options.trapFocus ?? options.modal ?? false,
          modal: options.modal ?? false,
          order: activeSessionOrder,
          handleEscape(event) {
            if (!isCurrentOpen() || activeEntry !== entry || !(options.closeOnEscape ?? true))
              return;
            event.preventDefault();
            change(false, details('escape-key', event));
          },
          handlePointerOutside(event) {
            if (
              !isCurrentOpen() ||
              activeEntry !== entry ||
              !(options.closeOnOutsidePointer ?? true)
            )
              return;
            change(false, details('outside-pointer', event));
          },
          handleFocusOutside(event) {
            if (!isCurrentOpen() || activeEntry !== entry || !options.closeOnFocusOutside) return;
            change(false, details('focus-out', event));
          },
          setFocusTrap(scopes) {
            Iif (!isCurrentOpen() || activeEntry !== entry) return;
            if (sameElements(installedFocusScopes, scopes)) return;
            const nextRelease = scopes
              ? trapFocus(
                  content,
                  scopes.filter((scope) => scope !== content),
                )
              : () => undefined;
            const previousRelease = releaseFocusTrap;
            releaseFocusTrap = nextRelease;
            installedFocusScopes = scopes;
            previousRelease();
          },
          setInertScope(nextBranches) {
            Iif (!isCurrentOpen() || activeEntry !== entry) return;
            if (sameElements(installedInertBranches, nextBranches)) return;
            const nextRelease = nextBranches
              ? inertSiblings(
                  content,
                  nextBranches.filter((branch) => branch !== content),
                  activeSessionOrder,
                )
              : () => undefined;
            const previousRelease = releaseInertScope;
            releaseInertScope = nextRelease;
            installedInertBranches = nextBranches;
            previousRelease();
          },
          publish(topmost) {
            Iif (!isCurrentOpen() || activeEntry !== entry) return;
            refreshSnapshot(topmost);
          },
        };
        createdEntry = entry;
        activeEntry = entry;
        const stack = overlayStacks.get(ownerDocument) ?? [];
        const orderedIndex = stack.findIndex((candidate) => candidate.order > activeSessionOrder);
        stack.splice(orderedIndex < 0 ? stack.length : orderedIndex, 0, entry);
        overlayStacks.set(ownerDocument, stack);
        localResources.add(() => {
          const currentStack = overlayStacks.get(ownerDocument);
          const index = currentStack?.indexOf(entry) ?? -1;
          Eif (currentStack && index >= 0) currentStack.splice(index, 1);
          if (currentStack?.length === 0) overlayStacks.delete(ownerDocument);
          Eif (activeEntry === entry) activeEntry = undefined;
          requestOverlayReconcile(ownerDocument);
        });
        localResources.add(acquireOverlayDocumentDispatcher(ownerDocument));
        if (options.modal) localResources.add(lockDocumentScroll(ownerDocument));
 
        const positionedAnchor = anchor ?? trigger;
        if (positionedAnchor) {
          let installing = true;
          const releasePositioning = autoUpdatePosition(positionedAnchor, content, () => {
            Eif (installing) return;
            updatePositionFor(currentBinding, generation);
          });
          localResources.add(releasePositioning);
          installing = false;
          const position = calculateBoundPosition(currentBinding);
          Eif (isCurrentOpen() && activeEntry === entry) currentPosition = position;
        }
        requestOverlayReconcile(ownerDocument);
      }
    } catch (error) {
      localResources.dispose();
      throw error;
    } finally {
      endOverlayMutation();
    }
 
    if (!isCurrent()) return;
    refreshSnapshot();
    if (!isCurrentOpen() || !currentBinding || !createdEntry || activeEntry !== createdEntry)
      return;
    const { content, branches = [] } = currentBinding.elements;
    const stack = overlayStacks.get(content.ownerDocument);
    const activeElement = content.ownerDocument.activeElement;
    const focusWithinBinding = [content, ...branches].some(
      (scope) =>
        activeElement !== null && (scope === activeElement || scope.contains(activeElement)),
    );
    const shouldFocusBinding =
      stack?.at(-1) === createdEntry && (establishingSessionBinding || !focusWithinBinding);
    if (
      shouldFocusBinding &&
      (options.focusOnOpen ?? options.modal ?? options.trapFocus ?? false)
    ) {
      const preferredFocus = options.initialFocus?.();
      if (
        !isCurrentOpen() ||
        binding !== currentBinding ||
        activeEntry !== createdEntry ||
        overlayStacks.get(content.ownerDocument)?.at(-1) !== createdEntry
      )
        return;
      focusInitial(content, preferredFocus, (cleanup) => localResources.add(cleanup));
      Iif (!isCurrentOpen() || activeEntry !== createdEntry) return;
    }
  };
 
  const commit = (open: boolean, changeDetails?: ChangeDetails<OpenChangeReason>): void => {
    transitionGeneration += 1;
    const generation = transitionGeneration;
    const closingDocument = activeEntry?.content.ownerDocument ?? sessionDocument;
    const closingOrder = activeEntry?.order ?? sessionOrder;
    const stackBeforeClose =
      !open && closingDocument ? overlayStacks.get(closingDocument) : undefined;
    const hasHigherOverlay =
      closingOrder !== undefined &&
      (stackBeforeClose?.some(
        (candidate) => candidate !== activeEntry && candidate.order > closingOrder,
      ) ??
        false);
    const closingRestoreTarget = restoreTarget;
    const closingCurrentTrigger = binding?.elements.trigger;
    if (open) {
      restoreTarget = null;
      restoreTargetCaptured = false;
      sessionDocument = undefined;
      sessionOrder = undefined;
    }
    syncResources();
    const transitionIsCurrent = (): boolean =>
      host.alive() && transitionGeneration === generation && state.get() === open;
    if (!transitionIsCurrent()) return;
    const payload = changeDetails ? { open, details: changeDetails } : undefined;
    if (payload) {
      host.emit(open ? 'open' : 'close', payload);
      if (!transitionIsCurrent()) return;
      host.emit('stateChange', payload);
      Iif (!transitionIsCurrent()) return;
    }
    const dismissedOutside =
      changeDetails?.reason === 'outside-pointer' || changeDetails?.reason === 'focus-out';
    if (
      !open &&
      !hasHigherOverlay &&
      (options.restoreFocus ?? true) &&
      (!dismissedOutside || (options.restoreFocusOnOutside ?? options.modal ?? false))
    ) {
      const restoredOriginal = restoreFocus(closingRestoreTarget);
      if (!transitionIsCurrent()) return;
      if (!restoredOriginal && closingCurrentTrigger !== closingRestoreTarget) {
        restoreFocus(closingCurrentTrigger);
        Iif (!transitionIsCurrent()) return;
      }
    }
    if (payload) {
      host.emit(open ? 'afterOpen' : 'afterClose', payload);
      Iif (!transitionIsCurrent()) return;
    }
    if (!open) {
      restoreTarget = null;
      restoreTargetCaptured = false;
      sessionDocument = undefined;
      sessionOrder = undefined;
    }
  };
 
  const change = (open: boolean, changeDetails: ChangeDetails<OpenChangeReason>): void => {
    if (!host.alive() || state.get() === open || lifecycleRequestInFlight === open) return;
    const payload = { open, details: changeDetails };
    const generation = transitionGeneration;
    lifecycleRequestInFlight = open;
    try {
      if (!host.emit(open ? 'beforeOpen' : 'beforeClose', payload)) return;
      Iif (!host.alive() || transitionGeneration !== generation || state.get() === open) return;
      if (state.set(open, changeDetails)) commit(open, changeDetails);
    } finally {
      if (lifecycleRequestInFlight === open) lifecycleRequestInFlight = undefined;
    }
  };
 
  host.resources.add(() => state.destroy());
  host.resources.add(() => openResources.dispose());
 
  return {
    getSnapshot: host.getSnapshot,
    subscribe: host.subscribe,
    on: host.on,
    off: host.off,
    once: host.once,
    open: (changeDetails) => change(true, changeDetails),
    close: (changeDetails) => change(false, changeDetails),
    toggle: (changeDetails) => change(!state.get(), changeDetails),
    bind(elements) {
      if (!host.alive()) return () => undefined;
      const registration: BindingRegistration = {
        elements,
        token: Symbol('overlay-binding'),
      };
      binding = registration;
      syncResources();
      let active = true;
      return () => {
        if (!active) return;
        active = false;
        if (binding !== registration) return;
        binding = undefined;
        syncResources();
      };
    },
    updatePosition,
    destroy() {
      Iif (!host.alive()) return;
      transitionGeneration += 1;
      resourceGeneration += 1;
      binding = undefined;
      beginOverlayMutation();
      try {
        host.destroy();
      } finally {
        endOverlayMutation();
      }
      activeEntry = undefined;
      currentPosition = null;
      restoreTarget = null;
      restoreTargetCaptured = false;
      sessionDocument = undefined;
      sessionOrder = undefined;
    },
  };
}