An open source design system that's fully customizable and agent ready
TypeScript
fix(HoverCard,Tooltip): wait for the trigger to have a layout box before showing (#5398)
Ojas Mutreja59881c7cc3c2
diff --git a/.changeset/hovercard-tooltip-controlled-open-anchoring.md b/.changeset/hovercard-tooltip-controlled-open-anchoring.mdnew file mode 100644index 0000000000..601c9cd7e1--- /dev/null+++ b/.changeset/hovercard-tooltip-controlled-open-anchoring.md@@ -0,0 +1,15 @@+---+'@astryxdesign/core': patch+---++[fix] `HoverCard` and `Tooltip`: a controlled `isOpen={true}` (or `isDefaultOpen`) no longer strands the layer in the viewport corner when its trigger mounts with no layout box yet, for example inside a `Dialog` that has not called `showModal()` yet.++`Dialog` mounts its children before it opens (`isOpen` gates `showModal()`, not rendering), so a `HoverCard` or `Tooltip` inside one with a controlled `isOpen={true}` runs its show effect while the trigger sits in a still non-modal `<dialog>` and has no box. A trigger with no box is not a valid CSS anchor: the popover resolves to its fallback position in the viewport corner, and unlike a live layout change that resolution is not revisited once the trigger later gets a box.++`Layer`'s `show()` now opens immediately when the trigger already has a layout box (an empty one, such as a ContextMenu's cursor anchor, counts), so a menu or popover still opens in the same task as the press that asked for it. Only a trigger with no layout box (`display: none`, or inside a `<dialog>` that is not showing) waits: first for it to get a layout box and for its dialog to show, then for any running animation on the document timeline that ends on its own, on the trigger or an ancestor, to finish, so the layer anchors to the trigger's settled position and not to a mid-transition one. Paused, infinite, and scroll- or view-driven animations are not waited on.++The box wait is driven by signals and polls nothing: a `ResizeObserver` for a trigger that gains a layout box, an `IntersectionObserver` for a purely `display: inline` trigger (such as the wrapper `<span>` of a text-only trigger), which a `ResizeObserver` never delivers an entry for, and the enclosing dialog's `open` attribute and `toggle` event. A dialog counts as showing when it is open or shown as a popover, so triggers inside a non-modal `Drawer` still open their layers. The wait has no time limit and ends when the trigger gets a box inside a showing dialog or the open is cancelled (a later `show()` or `hide()`, or unmount). If the trigger element is replaced while waiting, the wait restarts on the new one, and a trigger that unmounts for good stops observing. Without a layout engine to wait on (no `ResizeObserver` or no Web Animations API, as in jsdom) the layer opens immediately.++A transient `null` then same-element call on the trigger ref, as a combined ref utility makes when a handler changes identity, no longer removes and re-adds the element's `anchor-name`, which could also leave an open layer stranded in the corner.++@HelloOjasMutrejadiff --git a/apps/storybook/stories/LayerDismissal.stories.tsx b/apps/storybook/stories/LayerDismissal.stories.tsxindex fdbd3c0d7d..d2f715c819 100644--- a/apps/storybook/stories/LayerDismissal.stories.tsx+++ b/apps/storybook/stories/LayerDismissal.stories.tsx@@ -1061,3 +1061,164 @@ function PressInsideLayerExample() {export const PressInsideLayer: Story = {render: () => <PressInsideLayerExample />,};++/**+ * Same closed-then-open Dialog shape as PinnedTooltipInModal, but the+ * Tooltip's trigger is bare text — Tooltip wraps text-only children in an+ * inline `<span>` rather than a block-level control, which is exactly the+ * shape whose content box can stay empty in the delayed (ResizeObserver)+ * anchor-readiness path (#5398): a browser regression against a+ * button-shaped trigger cannot prove that fallback.+ */+function TextOnlyTriggerInModalExample() {+ const [isOpen, setIsOpen] = useState(false);+ const [isTipOpen, setIsTipOpen] = useState(true);++ return (+ <>+ <Button+ label="Open modal"+ variant="secondary"+ onClick={() => {+ setIsTipOpen(true);+ setIsOpen(true);+ }}+ />+ <Dialog+ isOpen={isOpen}+ onOpenChange={setIsOpen}+ width={520}+ aria-label="Modal with a text-only pinned tooltip">+ <Layout+ header={+ <DialogHeader+ title="Modal with a text-only pinned tooltip"+ onOpenChange={setIsOpen}+ />+ }+ content={+ <LayoutContent>+ <Tooltip+ isOpen={isTipOpen}+ onOpenChange={setIsTipOpen}+ content="Still anchors">+ Text-only trigger+ </Tooltip>+ </LayoutContent>+ }+ />+ </Dialog>+ </>+ );+}++export const TextOnlyTriggerInModal: Story = {+ render: () => <TextOnlyTriggerInModalExample />,+};++/**+ * The trigger only gains a real layout box a full 1.5s after the Dialog+ * opens (a placeholder with no size stands in until then) — well past any+ * fixed frame/time bound a readiness wait might give up after. The layer+ * must still end up anchored to the trigger once it's actually ready, not+ * opened early against a boxless placeholder (#5398): the current Layer+ * contract is that layered UI stays positioned against its trigger, with no+ * time limit on how long that trigger is allowed to take.+ */+function DelayedTriggerLayoutInModalExample() {+ const [isOpen, setIsOpen] = useState(false);+ const [isTipOpen, setIsTipOpen] = useState(true);+ const [triggerReady, setTriggerReady] = useState(false);++ return (+ <>+ <Button+ label="Open modal"+ variant="secondary"+ onClick={() => {+ setTriggerReady(false);+ setIsTipOpen(true);+ setIsOpen(true);+ setTimeout(() => setTriggerReady(true), 1500);+ }}+ />+ <Dialog+ isOpen={isOpen}+ onOpenChange={setIsOpen}+ width={520}+ aria-label="Modal with a delayed-layout tooltip trigger">+ <Layout+ header={+ <DialogHeader+ title="Modal with a delayed-layout tooltip trigger"+ onOpenChange={setIsOpen}+ />+ }+ content={+ <LayoutContent>+ {+ // One stable element throughout (not swapped), so the+ // ref Tooltip attaches to it never has to move mid-wait —+ // display:none is what keeps it boxless for the first+ // 1.5s, independent of the Dialog's own (much faster)+ // open transition.+ }+ <Tooltip+ isOpen={isTipOpen}+ onOpenChange={setIsTipOpen}+ content="Anchors once ready">+ <Button+ label="Late trigger"+ variant="secondary"+ style={triggerReady ? undefined : {display: 'none'}}+ />+ </Tooltip>+ </LayoutContent>+ }+ />+ </Dialog>+ </>+ );+}++export const DelayedTriggerLayoutInModal: Story = {+ render: () => <DelayedTriggerLayoutInModalExample />,+};++const pulse = stylex.keyframes({+ '0%': {transform: 'scale(1)'},+ '50%': {transform: 'scale(1.4)'},+ '100%': {transform: 'scale(1)'},+});++const continuousAnimationStyles = stylex.create({+ wrapper: {+ display: 'inline-block',+ animationName: pulse,+ animationDuration: '600ms',+ animationIterationCount: 'infinite',+ },+});++/**+ * A controlled Tooltip anchored to a trigger sitting inside a continuously+ * (infinitely) animating ancestor. `waitForAncestorAnimations` must not wait+ * on that animation's `finished` promise, which never resolves for one with+ * `iterationCount: Infinity` — only a genuinely finite entry animation+ * (Dialog's own open transition, e.g.) should hold the layer open.+ */+function ContinuouslyAnimatingTriggerExample() {+ const [isOpen, setIsOpen] = useState(true);++ return (+ <div {...stylex.props(continuousAnimationStyles.wrapper)}>+ <Tooltip isOpen={isOpen} onOpenChange={setIsOpen} content="Still opens">+ <Button label="Pulsing trigger" variant="secondary" />+ </Tooltip>+ </div>+ );+}++export const ContinuouslyAnimatingTrigger: Story = {+ render: () => <ContinuouslyAnimatingTriggerExample />,+};diff --git a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.jsonindex b67aa2e22f..80662ad048 100644--- a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json+++ b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json@@ -546,7 +546,6 @@"FR4","FR4","FR4",- "FR4","FR5","FR5","FR5",@@ -555,8 +554,6 @@"FR8","FR8","INV12",- "INV6",- "spec quote","spec quote","spec quote","spec quote",diff --git a/packages/core/src/Layer/__tests__/anchorReadiness.a11y.browser.spec.ts b/packages/core/src/Layer/__tests__/anchorReadiness.a11y.browser.spec.tsnew file mode 100644index 0000000000..93f4d52946--- /dev/null+++ b/packages/core/src/Layer/__tests__/anchorReadiness.a11y.browser.spec.ts@@ -0,0 +1,184 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file anchorReadiness.a11y.browser.spec.ts+ * @input Uses Playwright, a built Storybook, the LayerDismissal stories+ * @output Real-Chromium and real-WebKit proof that a controlled+ * Tooltip/HoverCard opened inside a Dialog anchors to its trigger instead+ * of the viewport corner+ * @position High-fidelity lane; jsdom's getBoundingClientRect and+ * ResizeObserver are both no-ops, so the anchor-readiness wait in+ * useLayer's show() (#5398) can only be proven against a real layout+ * engine. Cross-browser because anchor-geometry resolution is exactly the+ * kind of engine-specific behavior a single browser cannot speak for.+ *+ * SYNC: The story this reads is PinnedTooltipInModal in+ * apps/storybook/stories/LayerDismissal.stories.tsx.+ */++import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';++let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});++test.afterAll(async () => {+ await storybook?.close();+});++async function openStory(page: Page, storyId: string): Promise<void> {+ await page.goto(+ `${storybook.origin}/iframe.html?id=${storyId}&viewMode=story`,+ {+ waitUntil: 'load',+ },+ );+ await holdMotionStill(page);+}++/**+ * A layer stuck at the CSS anchor-positioning fallback (no valid anchor at+ * resolution time) lands at the viewport's top-left corner, boxes apart from+ * the trigger. Anchored correctly, the two boxes sit flush or a spacing-token+ * gap apart. The gap between the closest edges (0 while overlapping, the+ * straight-line distance between them otherwise) captures exactly that, and+ * stays small for any legitimate placement/alignment/fallback flip while+ * blowing up for the corner-stuck failure mode.+ */+function edgeGap(+ a: {x: number; y: number; width: number; height: number},+ b: {x: number; y: number; width: number; height: number},+): number {+ const dx = Math.max(0, a.x - (b.x + b.width), b.x - (a.x + a.width));+ const dy = Math.max(0, a.y - (b.y + b.height), b.y - (a.y + a.height));+ return Math.sqrt(dx * dx + dy * dy);+}++// The layer's own `offset` prop defaults to 0 (flush), and these stories+// don't set one, so a correctly anchored layer sits within a handful of+// pixels of its trigger. 60px comfortably covers any placement/alignment+// fallback flip while staying far below the ~300-450px gap the corner-stuck+// failure mode (#5398) produces in these stories' layouts.+const MAX_ANCHOR_GAP_PX = 60;++test('a controlled Tooltip opened inside a Dialog anchors to its trigger', async ({+ page,+}) => {+ await openStory(page, 'core-layer-dismissal--pinned-tooltip-in-modal');+ const root = page.locator('#storybook-root');+ await root.getByRole('button', {name: 'Open modal'}).click();++ const trigger = root.getByRole('button', {name: 'Tip trigger'});+ const tooltip = page.getByRole('tooltip');+ await expect(tooltip).toBeVisible();++ const triggerBox = await trigger.boundingBox();+ const tooltipBox = await tooltip.boundingBox();+ expect(triggerBox).not.toBeNull();+ expect(tooltipBox).not.toBeNull();+ if (triggerBox == null || tooltipBox == null) {+ return;+ }+ expect(edgeGap(tooltipBox, triggerBox)).toBeLessThan(MAX_ANCHOR_GAP_PX);+});++test('a controlled Tooltip with a text-only trigger opened inside a Dialog anchors to it', async ({+ page,+}) => {+ // Tooltip wraps text-only children in an inline <span> rather than a+ // block-level control — the shape whose content box can stay empty in the+ // delayed (ResizeObserver) anchor-readiness path, which a button-shaped+ // trigger cannot prove (#5398).+ await openStory(page, 'core-layer-dismissal--text-only-trigger-in-modal');+ const root = page.locator('#storybook-root');+ await root.getByRole('button', {name: 'Open modal'}).click();++ const trigger = root.getByText('Text-only trigger');+ // By text, not role: the Dialog's own header Close button also carries a+ // tooltip, so an unscoped/unnamed role query is ambiguous.+ const tooltip = page.getByText('Still anchors');+ await expect(tooltip).toBeVisible();++ const triggerBox = await trigger.boundingBox();+ const tooltipBox = await tooltip.boundingBox();+ expect(triggerBox).not.toBeNull();+ expect(tooltipBox).not.toBeNull();+ if (triggerBox == null || tooltipBox == null) {+ return;+ }+ expect(edgeGap(tooltipBox, triggerBox)).toBeLessThan(MAX_ANCHOR_GAP_PX);+});++test('a controlled Tooltip whose trigger gains layout well past any fixed bound still anchors to it', async ({+ page,+}) => {+ // The trigger stays boxless (display: none) for a full 1.5s after the+ // Dialog opens — well past a fixed frame/time bound a readiness wait+ // might give up after. The layer must still end up anchored once the+ // trigger is actually ready, not opened early against a boxless+ // placeholder: the current Layer contract puts no time limit on how long+ // a trigger is allowed to take (#5398).+ await openStory(+ page,+ 'core-layer-dismissal--delayed-trigger-layout-in-modal',+ );+ const root = page.locator('#storybook-root');+ await root.getByRole('button', {name: 'Open modal'}).click();++ const trigger = root.getByRole('button', {name: 'Late trigger'});+ const tooltip = page.getByText('Anchors once ready');+ await expect(tooltip).toBeVisible({timeout: 3_000});++ const triggerBox = await trigger.boundingBox();+ const tooltipBox = await tooltip.boundingBox();+ expect(triggerBox).not.toBeNull();+ expect(tooltipBox).not.toBeNull();+ if (triggerBox == null || tooltipBox == null) {+ return;+ }+ expect(edgeGap(tooltipBox, triggerBox)).toBeLessThan(MAX_ANCHOR_GAP_PX);+});++test('a controlled HoverCard opened inside a Dialog anchors to its trigger', async ({+ page,+}) => {+ await openStory(page, 'core-layer-dismissal--stuck-hover-card-in-modal');+ const root = page.locator('#storybook-root');+ await root.getByRole('button', {name: 'Open modal'}).click();++ const trigger = root.getByRole('button', {name: 'Card trigger'});+ const card = page.getByText('Stuck card');+ await expect(card).toBeVisible();++ const triggerBox = await trigger.boundingBox();+ const cardBox = await card.boundingBox();+ expect(triggerBox).not.toBeNull();+ expect(cardBox).not.toBeNull();+ if (triggerBox == null || cardBox == null) {+ return;+ }+ expect(edgeGap(cardBox, triggerBox)).toBeLessThan(MAX_ANCHOR_GAP_PX);+});++test('a controlled Tooltip still opens when its trigger sits inside a continuously animating ancestor', async ({+ page,+}) => {+ // `Animation.finished` never resolves for an infinite-iteration animation,+ // so the anchor-readiness wait must not treat it the way it treats a+ // finite entry transition (e.g. Dialog's own open animation) — otherwise a+ // trigger that never stops animating (a pulsing StatusDot, e.g.) would+ // leave its Tooltip stuck waiting forever.+ await openStory(page, 'core-layer-dismissal--continuously-animating-trigger');+ const tooltip = page.getByRole('tooltip');+ await expect(tooltip).toBeVisible({timeout: 5_000});+});diff --git a/packages/core/src/Layer/useLayer.test.tsx b/packages/core/src/Layer/useLayer.test.tsxindex 12ef2fa689..cdb3f64f23 100644--- a/packages/core/src/Layer/useLayer.test.tsx+++ b/packages/core/src/Layer/useLayer.test.tsx@@ -18,7 +18,13 @@ import {waitFor,} from '@testing-library/react';import userEvent from '@testing-library/user-event';-import {Profiler, useEffect, useState} from 'react';+import {+ Profiler,+ useCallback,+ useEffect,+ useLayoutEffect,+ useState,+} from 'react';import {hydrateRoot} from 'react-dom/client';import {renderToString} from 'react-dom/server';import * as stylex from '@stylexjs/stylex';@@ -1221,14 +1227,23 @@ describe('useLayer', () => {function FocusReturnHarness({onTooltipShow}: {onTooltipShow: () => void}) {const popover = useLayer({mode: 'context'});const tooltip = useLayer({mode: 'context', onShow: onTooltipShow});+ // A stable ref: an inline one detaches and reattaches the trigger on+ // every render, and each detach queues a microtask of its own that these+ // tests, which hold the ledger's microtasks by hand, do not mean to hold.+ const {ref: popoverRef} = popover;+ const {ref: tooltipRef} = tooltip;+ const triggerRef = useCallback(+ (el: HTMLButtonElement | null) => {+ popoverRef(el);+ tooltipRef(el);+ },+ [popoverRef, tooltipRef],+ );return (<><buttontype="button"- ref={el => {- popover.ref(el);- tooltip.ref(el);- }}+ ref={triggerRef}onFocus={tooltip.show}onBlur={tooltip.hide}onClick={popover.show}>@@ -3640,3 +3655,615 @@ describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {);});});++describe('contextRef anchor-name churn (#5398)', () => {+ // Both candidate trigger elements always mount; only which one currently+ // receives `layer.ref` changes, so switching `refTarget` makes React call+ // the outgoing element's ref with `null` and the incoming one's ref with+ // itself in the same commit — the exact churn shape a combined ref utility+ // (e.g. Tooltip's) produces.+ // A trigger is an anchor only while its layer is shown, so each case opens+ // the layer first.+ function ChurnHarness({+ refTarget,+ onReady,+ onShow,+ }: {+ refTarget: 'x' | 'y' | 'none';+ onReady?: (anchorId: string) => void;+ onShow?: (show: () => void) => void;+ }) {+ const layer = useLayerInternal({mode: 'context'});+ onReady?.(layer.anchorId);+ onShow?.(layer.show);+ return (+ <>+ <button+ type="button"+ data-testid="x"+ ref={refTarget === 'x' ? layer.ref : undefined}>+ X+ </button>+ <button+ type="button"+ data-testid="y"+ ref={refTarget === 'y' ? layer.ref : undefined}>+ Y+ </button>+ {layer.render(<span>Layer content</span>)}+ </>+ );+ }++ function anchorNamesOf(el: HTMLElement): string[] {+ return el.style.anchorName+ .split(',')+ .map(name => name.trim())+ .filter(Boolean);+ }++ it('keeps the anchor name through a transient null-then-same-element reattach', () => {+ let anchorId = '';+ let show = () => {};+ const {getByTestId, rerender} = render(+ <ChurnHarness+ refTarget="x"+ onReady={id => (anchorId = id)}+ onShow={s => (show = s)}+ />,+ );+ const x = getByTestId('x');+ act(() => show());+ expect(anchorNamesOf(x)).toContain(anchorId);+ // Records every write to the trigger's style: a removal and re-add of+ // the name ends in the same state, so only the writes tell them apart.+ const styleWrites = new MutationObserver(() => {});+ styleWrites.observe(x, {attributes: true, attributeFilter: ['style']});++ // No await between these two: the churn (null, then the same element+ // again) happens within one synchronous stretch, before the pending+ // removal's microtask ever gets a chance to run.+ rerender(<ChurnHarness refTarget="none" onReady={id => (anchorId = id)} />);+ rerender(<ChurnHarness refTarget="x" onReady={id => (anchorId = id)} />);++ expect(anchorNamesOf(x)).toContain(anchorId);+ expect(styleWrites.takeRecords()).toEqual([]);+ styleWrites.disconnect();+ });++ it('removes the old element and adds the new one when a different element takes over the ref', () => {+ let anchorId = '';+ let show = () => {};+ const {getByTestId, rerender} = render(+ <ChurnHarness+ refTarget="x"+ onReady={id => (anchorId = id)}+ onShow={s => (show = s)}+ />,+ );+ const x = getByTestId('x');+ const y = getByTestId('y');+ act(() => show());+ expect(anchorNamesOf(x)).toContain(anchorId);+ expect(anchorNamesOf(y)).not.toContain(anchorId);++ rerender(<ChurnHarness refTarget="y" onReady={id => (anchorId = id)} />);++ expect(anchorNamesOf(x)).not.toContain(anchorId);+ expect(anchorNamesOf(y)).toContain(anchorId);+ });++ it('removes the anchor name once a persistent (still-mounted) anchor genuinely lets go of the ref', async () => {+ let anchorId = '';+ let show = () => {};+ const {getByTestId, rerender} = render(+ <ChurnHarness+ refTarget="x"+ onReady={id => (anchorId = id)}+ onShow={s => (show = s)}+ />,+ );+ const x = getByTestId('x');+ act(() => show());+ expect(anchorNamesOf(x)).toContain(anchorId);++ // `x` stays mounted — only the ref moves off it, nothing reattaches.+ await act(async () => {+ rerender(+ <ChurnHarness refTarget="none" onReady={id => (anchorId = id)} />,+ );+ // Let the deferred-removal microtask actually run.+ await Promise.resolve();+ });++ expect(anchorNamesOf(x)).not.toContain(anchorId);+ });+});++describe('show() anchor readiness (#5398)', () => {+ // jsdom reports every box as 0x0 and has no layout engine, so each piece of+ // one is stubbed: per-element boxes, a manual frame queue, a ResizeObserver+ // the test can watch, and the Web Animations API whose presence marks a real+ // layout environment.+ const boxes = new WeakMap<Element, {width: number; height: number}>();+ // Elements that render an empty box: one client rect of 0x0, as an empty+ // inline `<span>` has, unlike `display: none`, which has none.+ const emptyBoxes = new WeakSet<Element>();+ let frames: (FrameRequestCallback | null)[] = [];+ let observers: {disconnected: boolean}[] = [];+ let intersections: {disconnected: boolean; callback: () => void}[] = [];+ let animations: unknown[] = [];++ const originalRect = Element.prototype.getBoundingClientRect;+ const originalClientRects = Element.prototype.getClientRects;++ class FakeKeyframeEffect {+ constructor(public target: Element) {}+ getComputedTiming() {+ return {iterations: 1, endTime: 300};+ }+ }++ beforeEach(() => {+ frames = [];+ observers = [];+ intersections = [];+ animations = [];+ vi.stubGlobal('KeyframeEffect', FakeKeyframeEffect);+ vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback): number =>+ frames.push(cb),+ );+ vi.stubGlobal('cancelAnimationFrame', (handle: number) => {+ frames[handle - 1] = null;+ });+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ state = {disconnected: false};+ constructor() {+ observers.push(this.state);+ }+ observe() {}+ unobserve() {}+ disconnect() {+ this.state.disconnected = true;+ }+ },+ );+ vi.stubGlobal(+ 'IntersectionObserver',+ class {+ state: {disconnected: boolean; callback: () => void};+ constructor(callback: () => void) {+ this.state = {disconnected: false, callback};+ intersections.push(this.state);+ }+ observe() {}+ unobserve() {}+ disconnect() {+ this.state.disconnected = true;+ }+ },+ );+ Object.defineProperty(document, 'getAnimations', {+ configurable: true,+ value: () => animations,+ });+ Element.prototype.getBoundingClientRect = function () {+ const box = boxes.get(this) ?? {width: 0, height: 0};+ return {+ ...box,+ x: 0,+ y: 0,+ top: 0,+ left: 0,+ right: box.width,+ bottom: box.height,+ toJSON: () => ({}),+ };+ };+ Element.prototype.getClientRects = function () {+ const box = boxes.get(this);+ const hasBox =+ emptyBoxes.has(this) ||+ (box != null && (box.width > 0 || box.height > 0));+ return (hasBox+ ? [this.getBoundingClientRect()]+ : []) as unknown as DOMRectList;+ };+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ Element.prototype.getBoundingClientRect = originalRect;+ Element.prototype.getClientRects = originalClientRects;+ delete (document as unknown as {getAnimations?: unknown}).getAnimations;+ });++ /** Run every queued frame callback once, as one animation frame would. */+ function flushFrame() {+ const pending = frames;+ frames = [];+ act(() => {+ for (const cb of pending) {+ cb?.(performance.now());+ }+ });+ }++ /** Deliver an IntersectionObserver entry, as a trigger gaining a box does. */+ function signal() {+ act(() => {+ for (const {disconnected, callback} of [...intersections]) {+ if (!disconnected) {+ callback();+ }+ }+ });+ }++ function Harness({target}: {target: 'a' | 'b' | 'none'}) {+ const layer = useLayerInternal({mode: 'context'});+ return (+ <>+ <button+ type="button"+ data-testid="a"+ ref={target === 'a' ? layer.ref : undefined}+ onClick={layer.show}>+ A+ </button>+ <button+ type="button"+ data-testid="b"+ ref={target === 'b' ? layer.ref : undefined}+ onClick={layer.show}>+ B+ </button>+ <button type="button" data-testid="hide" onClick={layer.hide}>+ Hide+ </button>+ <span data-testid="state">{layer.isOpen ? 'open' : 'closed'}</span>+ {layer.render(<span>Layer content</span>)}+ </>+ );+ }++ it('opens in the same task when the trigger already has a box', () => {+ const {getByTestId} = render(<Harness target="a" />);+ boxes.set(getByTestId('a'), {width: 80, height: 24});++ fireEvent.click(getByTestId('a'));++ expect(getByTestId('state')).toHaveTextContent('open');+ expect(observers).toHaveLength(0);+ expect(frames).toHaveLength(0);+ });++ it('opens at once for a trigger that renders an empty box (a ContextMenu cursor anchor)', () => {+ const {getByTestId} = render(<Harness target="a" />);+ emptyBoxes.add(getByTestId('a'));++ fireEvent.click(getByTestId('a'));++ // A 0x0 box is still a box: the wait is for `display: none` and closed+ // dialogs only, so an empty anchor does not hold the layer closed.+ expect(getByTestId('state')).toHaveTextContent('open');+ expect(observers).toHaveLength(0);+ });++ it('waits for a box on a boxless trigger, then settles, then opens', () => {+ const {getByTestId} = render(<Harness target="a" />);++ fireEvent.click(getByTestId('a'));+ expect(getByTestId('state')).toHaveTextContent('closed');+ // The runtime polls nothing (INV12): no frame is queued while it waits.+ expect(frames).toHaveLength(0);++ // The trigger gains a box; the observer signal sees it and starts the+ // settle frame, and only after that does the layer open.+ boxes.set(getByTestId('a'), {width: 80, height: 24});+ signal();+ expect(getByTestId('state')).toHaveTextContent('closed');+ flushFrame();+ expect(getByTestId('state')).toHaveTextContent('open');+ });++ it('does not hold the layer closed for a paused animation on an ancestor', () => {+ const {getByTestId} = render(<Harness target="a" />);+ const trigger = getByTestId('a');+ animations.push({+ effect: new FakeKeyframeEffect(trigger.parentElement as Element),+ timeline: document.timeline,+ playState: 'paused',+ finished: new Promise(() => {}),+ });++ fireEvent.click(trigger);+ boxes.set(trigger, {width: 80, height: 24});+ signal();+ flushFrame();++ expect(getByTestId('state')).toHaveTextContent('open');+ });++ it('does not hold the layer closed for a scroll-driven animation on an ancestor', () => {+ const {getByTestId} = render(<Harness target="a" />);+ const trigger = getByTestId('a');+ // A scroll() or view() timeline is not the document's, and its animation+ // finishes only when the person scrolls to the end of its range.+ animations.push({+ effect: new FakeKeyframeEffect(trigger.parentElement as Element),+ timeline: {},+ playState: 'running',+ finished: new Promise(() => {}),+ });++ fireEvent.click(trigger);+ boxes.set(trigger, {width: 80, height: 24});+ signal();+ flushFrame();++ expect(getByTestId('state')).toHaveTextContent('open');+ });++ it('still waits for a running animation on an ancestor to finish', async () => {+ const {getByTestId} = render(<Harness target="a" />);+ const trigger = getByTestId('a');+ let finish = () => {};+ animations.push({+ effect: new FakeKeyframeEffect(trigger.parentElement as Element),+ timeline: document.timeline,+ playState: 'running',+ finished: new Promise<void>(resolve => {+ finish = resolve;+ }),+ });++ fireEvent.click(trigger);+ boxes.set(trigger, {width: 80, height: 24});+ signal();+ flushFrame();+ expect(getByTestId('state')).toHaveTextContent('closed');++ await act(async () => {+ finish();+ await Promise.resolve();+ });+ expect(getByTestId('state')).toHaveTextContent('open');+ });++ it('opens without waiting when there is no layout engine, whatever the ResizeObserver does', () => {+ delete (document as unknown as {getAnimations?: unknown}).getAnimations;+ const {getByTestId} = render(<Harness target="a" />);++ fireEvent.click(getByTestId('a'));++ expect(getByTestId('state')).toHaveTextContent('open');+ expect(observers).toHaveLength(0);+ });++ it('restarts the wait on the new trigger when a boxless one is replaced', async () => {+ const {getByTestId, rerender} = render(<Harness target="a" />);+ boxes.set(getByTestId('b'), {width: 80, height: 24});++ fireEvent.click(getByTestId('a'));+ expect(getByTestId('state')).toHaveTextContent('closed');++ // The ref moves to `b`, which has a box. The wait that was polling `a`+ // would never end, so the layer has to be re-shown against `b`.+ await act(async () => {+ rerender(<Harness target="b" />);+ await Promise.resolve();+ });++ expect(getByTestId('state')).toHaveTextContent('open');+ });++ it('stops observing a trigger that unmounts without a replacement', async () => {+ const {getByTestId, rerender} = render(<Harness target="a" />);++ fireEvent.click(getByTestId('a'));+ expect(observers).toHaveLength(1);++ await act(async () => {+ rerender(<Harness target="none" />);+ await Promise.resolve();+ });++ expect(observers[0].disconnected).toBe(true);+ expect(intersections[0].disconnected).toBe(true);+ expect(frames.every(cb => cb === null)).toBe(true);+ expect(getByTestId('state')).toHaveTextContent('closed');+ });++ function SwapHarness({+ target,+ hideOnSwap = false,+ }: {+ target: 'a' | 'b';+ hideOnSwap?: boolean;+ }) {+ const layer = useLayerInternal({mode: 'context'});+ const {hide} = layer;+ useLayoutEffect(() => {+ if (hideOnSwap) {+ hide();+ }+ }, [hideOnSwap, hide]);+ return (+ <>+ <button+ type="button"+ data-testid="a"+ ref={target === 'a' ? layer.ref : undefined}+ onClick={layer.show}>+ A+ </button>+ <button+ type="button"+ data-testid="b"+ ref={target === 'b' ? layer.ref : undefined}+ onClick={layer.show}>+ B+ </button>+ <span data-testid="state">{layer.isOpen ? 'open' : 'closed'}</span>+ {layer.render(<span>Layer content</span>)}+ </>+ );+ }++ it('does not restart a wait that a hide() in the same commit cancelled', async () => {+ const {getByTestId, rerender} = render(<SwapHarness target="a" />);+ boxes.set(getByTestId('b'), {width: 80, height: 24});++ fireEvent.click(getByTestId('a'));+ expect(getByTestId('state')).toHaveTextContent('closed');++ // The trigger moves to `b` and the layer is hidden in that same commit.+ await act(async () => {+ rerender(<SwapHarness target="b" hideOnSwap />);+ await Promise.resolve();+ });++ expect(getByTestId('state')).toHaveTextContent('closed');+ });++ it('forgets a finished wait, so a later trigger swap does not reopen the layer', async () => {+ const {container, getByTestId, rerender} = render(+ <SwapHarness target="a" />,+ );+ boxes.set(getByTestId('b'), {width: 80, height: 24});++ fireEvent.click(getByTestId('a'));+ boxes.set(getByTestId('a'), {width: 80, height: 24});+ signal();+ flushFrame();+ expect(getByTestId('state')).toHaveTextContent('open');++ const popover = container.querySelector('[popover]') as HTMLElement;+ act(() => {+ popover.dispatchEvent(+ Object.assign(new Event('toggle'), {+ oldState: 'open',+ newState: 'closed',+ }),+ );+ });++ await act(async () => {+ rerender(<SwapHarness target="b" />);+ await Promise.resolve();+ });++ expect(getByTestId('state')).toHaveTextContent('closed');+ });++ it('waits for the dialog around the trigger to be open, even though the trigger has a box', async () => {+ function DialogHarness() {+ const layer = useLayerInternal({mode: 'context'});+ return (+ <>+ <dialog data-testid="dialog">+ <button+ type="button"+ data-testid="a"+ ref={layer.ref}+ onClick={layer.show}>+ A+ </button>+ </dialog>+ <span data-testid="state">{layer.isOpen ? 'open' : 'closed'}</span>+ {layer.render(<span>Layer content</span>)}+ </>+ );+ }+ const {getByTestId} = render(<DialogHarness />);+ boxes.set(getByTestId('a'), {width: 80, height: 24});++ fireEvent.click(getByTestId('a'));+ signal();+ flushFrame();+ expect(getByTestId('state')).toHaveTextContent('closed');++ // The dialog goes modal: its `open` attribute is the signal.+ await act(async () => {+ getByTestId('dialog').setAttribute('open', '');+ await Promise.resolve();+ });+ flushFrame();+ expect(getByTestId('state')).toHaveTextContent('open');+ });++ it('opens once a non-modal dialog shown as a popover (a Drawer) is showing', () => {+ function DrawerHarness() {+ const layer = useLayerInternal({mode: 'context'});+ return (+ <>+ <dialog data-testid="drawer">+ <button+ type="button"+ data-testid="a"+ ref={layer.ref}+ onClick={layer.show}>+ A+ </button>+ </dialog>+ <span data-testid="state">{layer.isOpen ? 'open' : 'closed'}</span>+ {layer.render(<span>Layer content</span>)}+ </>+ );+ }+ const {getByTestId} = render(<DrawerHarness />);+ const drawer = getByTestId('drawer');+ let isShowing = false;+ const originalMatches = drawer.matches.bind(drawer);+ Object.defineProperty(drawer, 'matches', {+ configurable: true,+ value: (selector: string) =>+ selector === ':popover-open' ? isShowing : originalMatches(selector),+ });+ boxes.set(getByTestId('a'), {width: 80, height: 24});++ fireEvent.click(getByTestId('a'));+ signal();+ flushFrame();+ expect(getByTestId('state')).toHaveTextContent('closed');++ // `showPopover()` never sets `open`; the `toggle` event is the signal.+ isShowing = true;+ act(() => {+ drawer.dispatchEvent(new Event('toggle'));+ });+ flushFrame();+ expect(getByTestId('state')).toHaveTextContent('open');+ });++ it('hide() cancels a settle wait that is already pending', async () => {+ const {getByTestId} = render(<Harness target="a" />);+ const trigger = getByTestId('a');+ let finish = () => {};+ animations.push({+ effect: new FakeKeyframeEffect(trigger.parentElement as Element),+ timeline: document.timeline,+ playState: 'running',+ finished: new Promise<void>(resolve => {+ finish = resolve;+ }),+ });++ fireEvent.click(trigger);+ boxes.set(trigger, {width: 80, height: 24});+ signal();+ flushFrame();+ expect(getByTestId('state')).toHaveTextContent('closed');++ fireEvent.click(getByTestId('hide'));+ await act(async () => {+ finish();+ await Promise.resolve();+ });++ expect(getByTestId('state')).toHaveTextContent('closed');+ });+});diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsxindex e013648f4b..89955c554b 100644--- a/packages/core/src/Layer/useLayer.tsx+++ b/packages/core/src/Layer/useLayer.tsx@@ -58,6 +58,8 @@ import {preserveAnimations} from './preserveAnimations';import {useLayerContext} from './LayerContext';import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';import {overlayPaddingReset} from '../Layout/overlayPaddingReset.stylex';+import {observeResize} from '../utils/sharedResizeObserver';+import {observeMutations} from '../utils/sharedMutationObserver';import {containsAlongFlatTree, parentAcrossShadow} from '../utils/flatTree';import {isShadowRoot} from '../utils/nodeType';import {subscribeInput} from '../utils/inputStream';@@ -517,6 +519,18 @@ function placeAfresh(layer: HTMLElement): void {});}+/**+ * Whether an animation is running and ends on its own. A paused or idle+ * animation does not end by itself. An animation with an infinite end time+ * never ends. Waiting on either holds the layer for good.+ */+function endsOnItsOwn(animation: Animation): boolean {+ return (+ animation.playState === 'running' &&+ animation.effect?.getComputedTiming().endTime !== Infinity+ );+}+/*** The finite animations still running on `layer` and its content. A layer* that fades out keeps running them after the browser hides it, and it stays@@ -526,13 +540,7 @@ function exitAnimations(layer: HTMLElement | null): Animation[] {if (layer == null || typeof layer.getAnimations !== 'function') {return [];}- return layer- .getAnimations({subtree: true})- .filter(- animation =>- animation.playState === 'running' &&- animation.effect?.getComputedTiming().endTime !== Infinity,- );+ return layer.getAnimations({subtree: true}).filter(endsOnItsOwn);}/**@@ -770,6 +778,116 @@ function observeAnchorClearance(};}+/** Whether `element` is shown as a popover (`:popover-open`). */+function isShownAsPopover(element: HTMLElement): boolean {+ try {+ return element.matches(':popover-open');+ } catch {+ // An engine without the pseudo-class has no popovers to be shown as.+ return false;+ }+}++/**+ * Whether `anchor` is a valid CSS anchor right now: it has a layout box, and+ * any `<dialog>` it sits in is showing, as a modal (`open`) or as a popover+ * (a non-modal `Drawer` is shown with `showPopover()` and never `open`).+ * `Dialog` displays its element during render but only calls `showModal()` in+ * a later Effect, so in that window the trigger already has a box while the+ * dialog is not yet in the top layer; opening a layer then paints it before+ * the dialog is modal.+ */+function isAnchorReady(anchor: HTMLElement): boolean {+ // No layout box at all: `display: none`, or inside a closed `<dialog>`. An+ // element that renders but is empty (an inline `<span>` with no content, such+ // as a ContextMenu's cursor anchor in a shadow root without Astryx's styles)+ // still has one 0x0 client rect and is a valid anchor.+ if (anchor.getClientRects().length === 0) {+ return false;+ }+ const dialog = anchor.closest('dialog');+ return dialog == null || dialog.open || isShownAsPopover(dialog);+}++/**+ * Calls `onReady` one frame later, once every running animation that ends on+ * its own, on the document timeline, on `anchor` or an ancestor, has finished.+ * Calls it synchronously if `document.getAnimations` does not exist (jsdom).+ * Returns a cancel function.+ *+ * `getBoundingClientRect()` reflects an ancestor's CSS transform, so an+ * anchor sitting inside a running entry animation — Dialog's own+ * scale/translate enter transition, e.g. — keeps reporting a different box+ * every frame for as long as that animation runs, even though a+ * `ResizeObserver` sees no size change at all (a transform never changes the+ * anchor's own layout box). Anchoring a layer to the trigger's box mid+ * transition, rather than the one it settles into, has produced a CSS+ * anchor-positioning resolution that never gets revisited once the trigger+ * stops moving: the layer is stranded at its unanchored fallback position+ * for the rest of that open.+ *+ * The check itself waits one frame before reading `document.getAnimations()`:+ * a CSS animation just triggered by a `display`/class change (exactly what+ * unhides a Dialog's content) is not yet in that list in the same task —+ * measured directly, not assumed — so checking synchronously would always see+ * zero animations and defeat the whole guard. One frame is enough for the UA+ * to have started it.+ *+ * The wait skips an animation that never ends by itself: a paused one, an+ * infinite one such as `StatusDot`'s pulse, and a scroll- or view-driven one.+ * `Animation.finished` never resolves for these, so waiting on them would+ * block a layer that anchors to them from ever opening.+ */++function waitForAncestorAnimations(+ anchor: HTMLElement,+ onReady: () => void,+): () => void {+ if (typeof document.getAnimations !== 'function') {+ onReady();+ return () => {};+ }+ let cancelled = false;+ const handle = requestAnimationFrame(() => {+ if (cancelled) {+ return;+ }+ const running = document.getAnimations().filter(animation => {+ const target =+ animation.effect instanceof KeyframeEffect+ ? animation.effect.target+ : null;+ if (+ !(target instanceof Node) ||+ !(target === anchor || target.contains(anchor))+ ) {+ return false;+ }+ // A scroll- or view-driven animation finishes only when the person+ // scrolls to the end of its range, so it is not a settle to wait on.+ if (animation.timeline !== document.timeline) {+ return false;+ }+ return endsOnItsOwn(animation);+ });+ if (running.length === 0) {+ onReady();+ return;+ }+ void Promise.all(+ running.map(async animation => animation.finished.catch(() => {})),+ ).then(() => {+ if (!cancelled) {+ onReady();+ }+ });+ });+ return () => {+ cancelled = true;+ cancelAnimationFrame(handle);+ };+}+interface ContextLayerMount {/** Null means the marker's parent is safe and the layer stays inline. */portalTarget: HTMLElement | null;@@ -1121,6 +1239,13 @@ function useLayerImplementation(// reference lets the ref callback recognize and reopen its replacement.const openedPopoverRef = useRef<HTMLElement | null>(null);const triggerRef = useRef<HTMLElement | null>(null);+ // A detach (contextRef(null)) still in its transient window — cancelled if+ // the same element reattaches before the microtask runs, applied+ // (removing the anchor name) otherwise. See contextRef below.+ const pendingTriggerDetachRef = useRef<{+ element: HTMLElement;+ cancelled: boolean;+ } | null>(null);// Context layers place a persistent inert marker at their real JSX position.// Its parent tells us whether the final layer can stay inline or needs a// corrective portal, including after the render call moves.@@ -1348,7 +1473,7 @@ function useLayerImplementation(mountStore.set(null);}, [mode, lazyMount, keepsMountAfterShow, mountStore]);- const show = useCallback(() => {+ const openNow = useCallback(() => {// Every caller lands here, so this is where the dismissing press is// absorbed: opening now would reopen the popup that same press closed.if (wasJustDismissed()) {@@ -1432,7 +1557,155 @@ function useLayerImplementation(wasJustDismissed,]);+ // A wait for the trigger to get a layout box, started by a show() that+ // found none. Cancelled by the next show()/hide() or by+ // unmount, so a stale wait from a closed-then-reopened layer never fires+ // openNow() after the fact.+ const pendingAnchorWaitRef = useRef<(() => void) | null>(null);+ // The element that wait is observing, so a trigger swapped out underneath it+ // can restart the wait on the new element (see `contextRef`).+ const pendingAnchorElementRef = useRef<HTMLElement | null>(null);++ // The deferred restart `contextRef` queues after a trigger swap. Any+ // show()/hide() or a new wait supersedes it, so a layer that was hidden in+ // the same commit never reopens by itself.+ const pendingRestartRef = useRef<{cancelled: boolean} | null>(null);++ const cancelPendingAnchorWait = useCallback(() => {+ pendingAnchorWaitRef.current?.();+ pendingAnchorWaitRef.current = null;+ pendingAnchorElementRef.current = null;+ if (pendingRestartRef.current) {+ pendingRestartRef.current.cancelled = true;+ pendingRestartRef.current = null;+ }+ }, []);++ // A wait that reached its end: nothing is pending any more, so a later+ // trigger swap must not restart it.+ const finishAnchorWait = useCallback(() => {+ pendingAnchorWaitRef.current = null;+ pendingAnchorElementRef.current = null;+ }, []);++ // A trigger with no layout box (no client rect) is not a valid CSS anchor. Opening against it now resolves the popover to+ // its fallback position (the viewport corner), and unlike a live layout+ // change, that resolution does not get revisited once the trigger later+ // gets a box: the popover is stuck there for the rest of this open.+ //+ // The concrete case this guards: a Dialog mounts its children before it+ // opens (`isOpen` gates only `showModal()`, not rendering), so a context+ // layer with `isDefaultOpen` or a controlled `isOpen={true}` inside one can+ // mount, and show() can run, while the trigger sits inside a `<dialog>`+ // that hasn't gone modal yet and so has no box. Anchor readiness lives here+ // rather than in each caller because this is the one place that already+ // owns the trigger element (`triggerRef`, set by `contextRef` below) and the+ // one place every context-mode show() funnels through.+ const show = useCallback(() => {+ cancelPendingAnchorWait();++ const anchor = mode === 'context' ? triggerRef.current : null;+ if (!anchor) {+ openNow();+ return;+ }+ if (isAnchorReady(anchor)) {+ // A trigger that already has a layout box is a valid anchor: open now, in the+ // same task as the interaction that asked, so a menu still opens on+ // press and not on the next frame. Only a trigger with no layout box has to wait.+ openNow();+ return;+ }+ // No layout engine to wait on (jsdom, an old browser): same fallback+ // sharedResizeObserver.ts uses for the same gap. Skip the wait rather than+ // throw, and open against whatever box is available now. A missing+ // `document.getAnimations` is the signal for "no real layout" here: jsdom+ // reports every box as 0x0 forever, so a ResizeObserver stub that never+ // fires would otherwise hold every layer closed.+ if (+ typeof ResizeObserver === 'undefined' ||+ typeof document.getAnimations !== 'function'+ ) {+ openNow();+ return;+ }+ // The wait is driven by signals, never by polling. Any of them re-reads `isAnchorReady`; the first that+ // finds the anchor ready wins. None resolves against a boxless trigger, so+ // a layer whose container gains layout much later still ends up anchored,+ // not opened against a 0x0 box because a cap gave up first:+ //+ // - ResizeObserver: a block-level trigger gaining a box.+ // - IntersectionObserver: reports a `display: inline` trigger, which+ // ResizeObserver never delivers an entry for, such as the wrapper+ // `<span>` of a text-only Tooltip or HoverCard. It also fires+ // when a hidden ancestor is displayed.+ // - The enclosing `<dialog>`'s `open` attribute and `toggle` event: the+ // trigger can have a box before the dialog is modal (see+ // `isAnchorReady`), and a popover-shown dialog never sets `open`.+ //+ // A ResizeObserver stub that fires synchronously (several component tests+ // use one) resolves exactly as fast as it always did. Environments with no+ // real layout ever are excluded before this point.+ const anchorElement: HTMLElement = anchor;+ const dialog = anchor.closest('dialog');+ let cancelSettleWait: () => void = () => {};+ let resolved = false;+ // The shared observers hand back an unsubscribe for this+ // registration only, so the teardown does not touch other observers of the+ // same element.+ let stopResize: () => void = () => {};+ let stopMutations: () => void = () => {};+ const release = () => {+ stopResize();+ intersection?.disconnect();+ stopMutations();+ dialog?.removeEventListener('toggle', check);+ };+ const resolve = () => {+ resolved = true;+ release();+ // Once the box exists, a short settle wait lets an ancestor's running+ // entry animation finish before the layer anchors to it.+ cancelSettleWait = waitForAncestorAnimations(anchor, () => {+ finishAnchorWait();+ openNow();+ });+ };+ function check() {+ if (!resolved && isAnchorReady(anchorElement)) {+ resolve();+ }+ }+ const intersection =+ typeof IntersectionObserver === 'undefined'+ ? null+ : new IntersectionObserver(check);+ stopResize = observeResize(anchor, check);+ if (!resolved) {+ intersection?.observe(anchor);+ if (dialog) {+ stopMutations = observeMutations(+ dialog,+ {attributes: true, attributeFilter: ['open']},+ check,+ );+ dialog.addEventListener('toggle', check);+ }+ } else {+ // The registration itself resolved the wait before its unsubscribe+ // existed, so release it now.+ release();+ }+ pendingAnchorWaitRef.current = () => {+ resolved = true;+ release();+ cancelSettleWait();+ };+ pendingAnchorElementRef.current = anchor;+ }, [mode, openNow, cancelPendingAnchorWait, finishAnchorWait]);+const hide = useCallback(() => {+ cancelPendingAnchorWait();pendingShowRef.current = false;if (isOpenRef.current) {const el = popoverRef.current;@@ -1465,7 +1738,7 @@ function useLayerImplementation(}releaseAnchor(popoverRef.current);clearContextMount();- }, [onHide, clearContextMount, releaseAnchor]);+ }, [onHide, clearContextMount, releaseAnchor, cancelPendingAnchorWait]);// A deferred show() replays through a ref so the queued closure reaches the// current callback rather than the one captured when it was queued.@@ -1479,8 +1752,46 @@ function useLayerImplementation(const clearObserversRef = useRef<(() => void) | null>(null);// Stable ref for the trigger element (context mode only).+ //+ // A combined ref can call this ref with `null` and then with the same+ // element. Removing `anchor-name` in that gap strands an open layer at its+ // fallback position. So a `null` call removes the name one microtask later,+ // unless the same element attaches again first. A different element takes+ // over at once, and a `null` with nothing after it (an unmount) removes the+ // name.const contextRef = useCallback((el: HTMLElement | null) => {+ if (!el) {+ const stale = triggerRef.current;+ if (!stale) {+ return;+ }+ const pending = {element: stale, cancelled: false};+ pendingTriggerDetachRef.current = pending;+ queueMicrotask(() => {+ if (pending.cancelled || triggerRef.current !== stale) {+ return;+ }+ removeAnchorName(stale, anchorId);+ triggerRef.current = null;+ // A real unmount: stop waiting on an element that will never get a+ // box, and release the observers an open layer kept on it.+ if (pendingAnchorElementRef.current === stale) {+ cancelPendingAnchorWait();+ }+ if (keepsAnchorClear && isOpenRef.current) {+ clearObserversRef.current?.();+ clearObserversRef.current = null;+ }+ });+ return;+ }+ // Reattaching the exact element a pending detach targeted: cancel it,+ // the churn never happened as far as the anchor name is concerned.+ if (pendingTriggerDetachRef.current?.element === el) {+ pendingTriggerDetachRef.current.cancelled = true;+ pendingTriggerDetachRef.current = null;+ }// Remove only THIS layer's anchor name from the previous element so// other layers sharing the same trigger keep their anchors.if (triggerRef.current && triggerRef.current !== el) {@@ -1500,13 +1811,13 @@ function useLayerImplementation(// A trigger replaced while the layer is open (React detaches the old// node with `null`, then attaches the new one): the old trigger's- // observers are removed before the new trigger's are added (INV6), and+ // observers are removed before the new trigger's are added, and// binding them reads the new trigger's geometry at once.if (keepsAnchorClear && isOpenRef.current && el !== previous) {clearObserversRef.current?.();clearObserversRef.current = null;const layer = popoverRef.current;- if (el && layer) {+ if (layer) {clearObserversRef.current = observeAnchorClearance(layer,el,@@ -1515,8 +1826,27 @@ function useLayerImplementation(keepAnchorClear(layer, el);}}++ // A show() is still waiting for a box on a different trigger: that wait+ // observes the element it started with, so it would never end for this+ // one. Restart it on the new trigger, after the commit that attached it.+ const waitingOn = pendingAnchorElementRef.current;+ if (waitingOn && waitingOn !== el) {+ cancelPendingAnchorWait();+ const restart = {cancelled: false};+ pendingRestartRef.current = restart;+ queueMicrotask(() => {+ if (restart.cancelled) {+ return;+ }+ pendingRestartRef.current = null;+ if (triggerRef.current === el && !isOpenRef.current) {+ showRef.current();+ }+ });+ }},- [anchorId, keepsAnchorClear],+ [anchorId, cancelPendingAnchorWait, keepsAnchorClear],);// Arm only when the dismissing gesture's click is still ahead of us. Some@@ -1559,11 +1889,14 @@ function useLayerImplementation(}, []);// Syncs the document's capture-phase gesture tracking with this mount.- // Unmount forgets the layer's dismissal.+ // Unmount forgets the layer's dismissal and releases a pending anchor wait.useEffect(() => {// Install capture-phase gesture tracking before the first interaction.currentGesture();- return () => forgetDismissalRef.current?.();+ return () => {+ forgetDismissalRef.current?.();+ pendingAnchorWaitRef.current?.();+ };}, []);// Reconcile browser-initiated closes (light-dismiss, popover="auto" stack@@ -1808,7 +2141,7 @@ function useLayerImplementation(return () => observer.disconnect();}, [isOpen, mode, updateAnchorInView]);- // A layer that keeps its anchor clear (FR4) re-reads its geometry while it+ // A layer that keeps its anchor clear re-reads its geometry while it// is open: content that grows, an anchor that resizes or moves (in layout or// by a scroll) or a viewport resize can each re-settle the standard list over the anchor or// give the layer a scroll range (`observeAnchorClearance`). The external