Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(Layer): a show that a browser-run hide wakes waits for that hide (#8543)

Christopher Chedeaud6697625e262
diff --git a/.changeset/layer-browser-hide-ledger.md b/.changeset/layer-browser-hide-ledger.md
new file mode 100644
index 0000000000..34315ce316
--- /dev/null
+++ b/.changeset/layer-browser-hide-ledger.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] useLayer: a show that a browser-run popover hide refuses (Chromium 156 throws an `InvalidStateError`) is replayed once that hide has ended, so the layer ends shown. For example, when the browser's own Escape closes a light-dismissible layer, the tooltip on the button that opened it now shows instead of failing.
+
+@vjeux
diff --git a/apps/storybook/stories/Layer.stories.tsx b/apps/storybook/stories/Layer.stories.tsx
index 7b1656148b..0a8916d402 100644
--- a/apps/storybook/stories/Layer.stories.tsx
+++ b/apps/storybook/stories/Layer.stories.tsx
@@ -1520,3 +1520,68 @@ export const Playground: Story = {
},
render: () => <PlaygroundDemo />,
};
+
+/**
+ * A trigger that carries a focus-driven layer (the shape of a tooltip, shown
+ * on plain focus) and opens a light-dismissible layer. An Escape the browser's
+ * close watcher answers is a hide the browser runs itself: with focus inside
+ * the layer, it returns focus to the trigger while the document still counts
+ * the layer as hiding, and the focus-driven layer asks to show inside that
+ * window. A tap outside is the browser's hide too, but it returns no focus:
+ * the press itself took it.
+ */
+function BrowserHideWakesAFocusLayerDemo() {
+ const content = useLayer({mode: 'context', lightDismiss: true});
+ const hint = useLayer({mode: 'context'});
+ // A second light-dismissible layer, opened by a press that light-dismisses
+ // the first one; like a menu, it moves focus into itself right after the
+ // show, which only works when the show ran at once.
+ const other = useLayer({mode: 'context', lightDismiss: true});
+ const otherInsideRef = useRef<HTMLButtonElement | null>(null);
+ return (
+ <div {...stylex.props(styles.demoArea)}>
+ <Button
+ ref={el => {
+ content.ref(el);
+ hint.ref(el);
+ }}
+ label="Show layer"
+ onFocus={hint.show}
+ onBlur={hint.hide}
+ onClick={() => (content.isOpen ? content.hide() : content.show())}
+ />
+ {content.render(
+ <div {...stylex.props(styles.popoverContent)}>
+ <Text type="body">A light-dismissible layer.</Text>
+ <Button label="Inside" onClick={content.hide} />
+ </div>,
+ {placement: 'below', alignment: 'center'},
+ )}
+ {hint.render(
+ <div {...stylex.props(styles.popoverContent)} role="tooltip">
+ <Text type="body">Shown while the trigger has focus.</Text>
+ </div>,
+ {placement: 'above', alignment: 'center'},
+ )}
+ <Button
+ ref={other.ref}
+ label="Show the other layer"
+ onClick={() => {
+ other.show();
+ otherInsideRef.current?.focus();
+ }}
+ />
+ {other.render(
+ <div {...stylex.props(styles.popoverContent)}>
+ <Text type="body">The other layer.</Text>
+ <Button ref={otherInsideRef} label="Inside the other" />
+ </div>,
+ {placement: 'below', alignment: 'center'},
+ )}
+ </div>
+ );
+}
+
+export const BrowserHideWakesAFocusLayer: Story = {
+ render: () => <BrowserHideWakesAFocusLayerDemo />,
+};
diff --git a/packages/core/src/Layer/__tests__/LayerBrowserHide.a11y.chromium.spec.ts b/packages/core/src/Layer/__tests__/LayerBrowserHide.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..11bb6c99b4
--- /dev/null
+++ b/packages/core/src/Layer/__tests__/LayerBrowserHide.a11y.chromium.spec.ts
@@ -0,0 +1,126 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y scope core/Layer
+
+/**
+ * @file LayerBrowserHide.a11y.chromium.spec.ts
+ * @input The `Core/Layer` BrowserHideWakesAFocusLayer story in a built
+ * Storybook, driven by real Chromium pointer and keyboard input.
+ * @output Real-engine proof that a show the browser's own hide wakes — its
+ * close watcher's Escape returning focus to a trigger whose focus-driven
+ * layer asks to show — reaches the page as no error and ends with that
+ * layer shown; that a tap outside, which returns no focus, hides the
+ * layer with no error and wakes nothing; and that a press which
+ * light-dismisses one layer and opens another opens it at once. Only a real engine
+ * decides when a popover operation is in flight and refuses a show inside
+ * it; the unit suite (useLayer.test.tsx) covers the same rules on a
+ * mirrored Popover API. The in-flight rule is Chromium 150+: on the
+ * Chromium this repository's Playwright pins (149) the first case passes
+ * with or without the fix, so until that pin moves it guards the end state
+ * only.
+ * @position Run with `pnpm test:a11y-contract`.
+ */
+
+import {expect, test, type Page} from '@playwright/test';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+/** Every error the page reports while the test runs: a refused show is one. */
+function collectPageErrors(page: Page): string[] {
+ const errors: string[] = [];
+ page.on('pageerror', error => {
+ errors.push(`${error.name}: ${error.message}`);
+ });
+ return errors;
+}
+
+async function openStory(page: Page, id: string): Promise<void> {
+ await page.goto(`${storybook.origin}/iframe.html?id=${id}&viewMode=story`);
+ await page.locator('#storybook-root button').first().waitFor();
+}
+
+test('an Escape the browser answers, with focus inside the layer, returns focus to the trigger and shows its focus-driven layer, without an error', async ({
+ page,
+}) => {
+ const errors = collectPageErrors(page);
+ await openStory(page, 'core-layer--browser-hide-wakes-a-focus-layer');
+ const trigger = page.getByRole('button', {name: 'Show layer'});
+ const inside = page.getByRole('button', {name: 'Inside', exact: true});
+ const hint = page.getByRole('tooltip');
+
+ // Keyboard focus shows the focus-driven layer; the press opens the content
+ // and Tab moves into it, which hides the focus-driven layer.
+ await page.keyboard.press('Tab');
+ await expect(trigger).toBeFocused();
+ await expect(hint).toBeVisible();
+ await page.keyboard.press('Enter');
+ await expect(inside).toBeVisible();
+ await page.keyboard.press('Tab');
+ await expect(inside).toBeFocused();
+ await expect(hint).toBeHidden();
+
+ // No layer handles Escape here: the browser's own close watcher hides the
+ // content layer and returns focus to the trigger inside that hide.
+ await page.keyboard.press('Escape');
+ await expect(inside).toBeHidden();
+ await expect(trigger).toBeFocused();
+ await expect(hint).toBeVisible();
+ expect(errors).toEqual([]);
+});
+
+test('a tap outside the layer, with focus inside it, hides the layer without an error; it returns no focus, so the focus-driven layer stays hidden', async ({
+ page,
+}) => {
+ const errors = collectPageErrors(page);
+ await openStory(page, 'core-layer--browser-hide-wakes-a-focus-layer');
+ const trigger = page.getByRole('button', {name: 'Show layer'});
+ const inside = page.getByRole('button', {name: 'Inside', exact: true});
+ const hint = page.getByRole('tooltip');
+
+ await page.keyboard.press('Tab');
+ await page.keyboard.press('Enter');
+ await expect(inside).toBeVisible();
+ await page.keyboard.press('Tab');
+ await expect(inside).toBeFocused();
+
+ // A light dismiss returns no focus: the press moves focus to the page
+ // before the hide runs, so nothing wakes the focus-driven layer.
+ await page.mouse.click(5, 5);
+ await expect(inside).toBeHidden();
+ await expect(trigger).not.toBeFocused();
+ await expect(hint).toBeHidden();
+ expect(errors).toEqual([]);
+});
+
+test('a press that light-dismisses one layer and opens another opens it at once: focus moves into it, without an error', async ({
+ page,
+}) => {
+ const errors = collectPageErrors(page);
+ await openStory(page, 'core-layer--browser-hide-wakes-a-focus-layer');
+ const inside = page.getByRole('button', {name: 'Inside', exact: true});
+ const otherTrigger = page.getByRole('button', {name: 'Show the other layer'});
+ const otherInside = page.getByRole('button', {name: 'Inside the other'});
+
+ await page.getByRole('button', {name: 'Show layer'}).click();
+ await expect(inside).toBeVisible();
+
+ // The browser light-dismisses the first layer at pointerup; the click opens
+ // the other one in the same gesture and focuses into it right away.
+ await otherTrigger.click();
+ await expect(inside).toBeHidden();
+ await expect(otherInside).toBeVisible();
+ await expect(otherInside).toBeFocused();
+ expect(errors).toEqual([]);
+});
diff --git a/packages/core/src/Layer/popoverOperations.test.ts b/packages/core/src/Layer/popoverOperations.test.ts
new file mode 100644
index 0000000000..5e77b6123b
--- /dev/null
+++ b/packages/core/src/Layer/popoverOperations.test.ts
@@ -0,0 +1,205 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file popoverOperations.test.ts
+ * @input Uses vitest, the popoverOperations ledger
+ * @output Unit tests for the per-document ledger of popover operations
+ * @position Core testing; validates popoverOperations.ts
+ */
+
+import {afterEach, describe, it, expect, vi} from 'vitest';
+import {
+ afterPopoverOperations,
+ isBrowserHideInFlight,
+ isPopoverOperationInFlight,
+ observeBrowserHide,
+ runPopoverOperation,
+} from './popoverOperations';
+
+/** The replay runs a microtask after the end, then one microtask per callback. */
+async function settle(): Promise<void> {
+ await Promise.resolve();
+ await Promise.resolve();
+}
+
+describe('popoverOperations', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('runs a callback at once when the document has no operation in flight', () => {
+ const callback = vi.fn();
+ afterPopoverOperations(document, callback);
+ expect(callback).toHaveBeenCalledTimes(1);
+ });
+
+ it('counts one of the layers’ own operations while it runs and replays a show that arrived inside it once the script has unwound', async () => {
+ const callback = vi.fn();
+ runPopoverOperation(document, () => {
+ expect(isPopoverOperationInFlight(document)).toBe(true);
+ afterPopoverOperations(document, callback);
+ expect(callback).not.toHaveBeenCalled();
+ });
+ // The operation has ended, but its caller is still on the stack.
+ expect(isPopoverOperationInFlight(document)).toBe(false);
+ expect(callback).not.toHaveBeenCalled();
+ await settle();
+ expect(callback).toHaveBeenCalledTimes(1);
+ });
+
+ it('counts the browser’s own hide apart from the layers’ operations, from its start until the element’s toggle', async () => {
+ const popover = document.createElement('div');
+ document.body.appendChild(popover);
+ try {
+ const callback = vi.fn();
+ observeBrowserHide(popover);
+ observeBrowserHide(popover);
+ // A show asked now is not refused ahead of time: the engine decides.
+ expect(isPopoverOperationInFlight(document)).toBe(false);
+ expect(isBrowserHideInFlight(document)).toBe(true);
+ afterPopoverOperations(document, callback);
+ await settle();
+ expect(callback).not.toHaveBeenCalled();
+
+ popover.dispatchEvent(new Event('toggle'));
+ expect(isBrowserHideInFlight(document)).toBe(false);
+ await settle();
+ expect(callback).toHaveBeenCalledTimes(1);
+ // The toggle ended it once; the next task finds nothing to end.
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(isBrowserHideInFlight(document)).toBe(false);
+ } finally {
+ popover.remove();
+ }
+ });
+
+ it('ends each hide exactly once: the loser of toggle and backstop is released, so a second in-flight hide keeps its count', () => {
+ vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout']});
+ const first = document.createElement('div');
+ const second = document.createElement('div');
+ document.body.append(first, second);
+ try {
+ const removeListener = vi.spyOn(second, 'removeEventListener');
+ observeBrowserHide(first);
+ observeBrowserHide(second);
+ expect(isBrowserHideInFlight(document)).toBe(true);
+ expect(vi.getTimerCount()).toBe(2);
+
+ // The first hide's toggle wins: its backstop is cleared, not left to
+ // run later against another hide's count.
+ first.dispatchEvent(new Event('toggle'));
+ expect(isBrowserHideInFlight(document)).toBe(true);
+ expect(vi.getTimerCount()).toBe(1);
+ // The second hide's backstop wins: it ends the hide once and drops the
+ // one-shot toggle listener.
+ vi.runOnlyPendingTimers();
+ expect(isBrowserHideInFlight(document)).toBe(false);
+ expect(removeListener).toHaveBeenCalledWith(
+ 'toggle',
+ expect.any(Function),
+ );
+
+ // A toggle after the backstop won, and a second toggle after the toggle
+ // won, change nothing: the one-shot listeners are gone.
+ observeBrowserHide(first);
+ expect(isBrowserHideInFlight(document)).toBe(true);
+ second.dispatchEvent(new Event('toggle'));
+ expect(isBrowserHideInFlight(document)).toBe(true);
+ first.dispatchEvent(new Event('toggle'));
+ first.dispatchEvent(new Event('toggle'));
+ expect(isBrowserHideInFlight(document)).toBe(false);
+
+ // Nothing drifted negative: a later hide is still counted.
+ observeBrowserHide(second);
+ expect(isBrowserHideInFlight(document)).toBe(true);
+ vi.runOnlyPendingTimers();
+ expect(isBrowserHideInFlight(document)).toBe(false);
+ } finally {
+ first.remove();
+ second.remove();
+ }
+ });
+
+ it('ends a counted hide at the next task when its toggle never arrives (the element left the document)', async () => {
+ const popover = document.createElement('div');
+ document.body.appendChild(popover);
+ const callback = vi.fn();
+ observeBrowserHide(popover);
+ popover.remove();
+ afterPopoverOperations(document, callback);
+ await settle();
+ expect(callback).not.toHaveBeenCalled();
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(isBrowserHideInFlight(document)).toBe(false);
+ await settle();
+ expect(callback).toHaveBeenCalledTimes(1);
+ });
+
+ it('postpones the replay when another operation starts before it runs', async () => {
+ const callback = vi.fn();
+ runPopoverOperation(document, () => {
+ afterPopoverOperations(document, callback);
+ });
+ // Before the replay's microtask: a browser-run hide starts, and ends.
+ const second = document.createElement('div');
+ document.body.appendChild(second);
+ try {
+ observeBrowserHide(second);
+ await settle();
+ expect(callback).not.toHaveBeenCalled();
+ second.dispatchEvent(new Event('toggle'));
+ await settle();
+ expect(callback).toHaveBeenCalledTimes(1);
+ } finally {
+ second.remove();
+ }
+ });
+
+ it('replays each callback in its own microtask, so a throw in one reaches the page alone and leaves the rest to run', async () => {
+ const queued = vi.spyOn(globalThis, 'queueMicrotask');
+ try {
+ const first = vi.fn();
+ const second = vi.fn();
+ runPopoverOperation(document, () => {
+ afterPopoverOperations(document, first);
+ afterPopoverOperations(document, second);
+ });
+ // One microtask replays the batch; it queues one more per callback.
+ expect(queued).toHaveBeenCalledTimes(1);
+ await Promise.resolve();
+ expect(queued).toHaveBeenCalledTimes(3);
+ expect(first).not.toHaveBeenCalled();
+ await Promise.resolve();
+ expect(first).toHaveBeenCalledTimes(1);
+ expect(second).toHaveBeenCalledTimes(1);
+ expect(first.mock.invocationCallOrder[0]).toBeLessThan(
+ second.mock.invocationCallOrder[0] ?? 0,
+ );
+ } finally {
+ queued.mockRestore();
+ }
+ });
+
+ it('keeps one ledger per document', async () => {
+ const frame = document.createElement('iframe');
+ document.body.appendChild(frame);
+ const other = frame.contentDocument;
+ if (other == null) {
+ throw new Error('the iframe has no document');
+ }
+ try {
+ const callback = vi.fn();
+ const popover = other.createElement('div');
+ other.body.appendChild(popover);
+ observeBrowserHide(popover);
+ expect(isBrowserHideInFlight(document)).toBe(false);
+ afterPopoverOperations(document, callback);
+ expect(callback).toHaveBeenCalledTimes(1);
+ expect(isBrowserHideInFlight(other)).toBe(true);
+ popover.dispatchEvent(new Event('toggle'));
+ expect(isBrowserHideInFlight(other)).toBe(false);
+ } finally {
+ frame.remove();
+ }
+ });
+});
diff --git a/packages/core/src/Layer/popoverOperations.ts b/packages/core/src/Layer/popoverOperations.ts
new file mode 100644
index 0000000000..70381e2751
--- /dev/null
+++ b/packages/core/src/Layer/popoverOperations.ts
@@ -0,0 +1,172 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file popoverOperations.ts
+ * @input Popover API events (`beforetoggle`, `toggle`) and the layers' own show/hide calls
+ * @output The per-document ledger of popover operations in flight, and the deferral of a show that arrives inside one
+ * @position Internal to the layer runtime; used by useLayer
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/Layer/useLayer.tsx
+ * - /packages/core/src/Layer/popoverOperations.test.ts
+ */
+
+/**
+ * Popover operations in flight, per document.
+ *
+ * The Popover API refuses to show a popover while the document is in the
+ * middle of showing or hiding ANY popover: `showPopover()` throws an
+ * `InvalidStateError` ("Invalid to show a popover during another show
+ * operation"; Chromium 150+, where 149 still accepts such a show).
+ * Hiding a popover restores focus to the element that had it —
+ * synchronously, inside that window — so a focus-driven layer on the element
+ * receiving focus (a tooltip on the trigger that just closed a popover) asks
+ * to show while the hide is still running.
+ *
+ * Two kinds of operation are counted:
+ *
+ * - The layers' own shows and hides pass through `runPopoverOperation`, so
+ * their windows are known exactly: a `show()` that arrives inside one is
+ * deferred ahead of asking the browser.
+ * - A hide the browser runs on its own — an Escape its close watcher answers,
+ * a light dismiss, an `auto` popover evicted by another one opening — never
+ * passes through here. It is observable from its element's events:
+ * `beforetoggle` fires synchronously as the hide starts, and `toggle` in a
+ * task once it has ended; `observeBrowserHide` counts it between the two.
+ * That window is wider than the engine's, which ends when the hide returns,
+ * so a show inside it is asked of the browser first and deferred only when
+ * the browser refuses it: a light dismiss at `pointerup` followed by a show
+ * at `click` in the same gesture still opens at once.
+ *
+ * A deferred show waits in `afterPopoverOperations` and replays, one
+ * microtask each, once the document's last operation of either kind has
+ * ended and the script that started it has unwound.
+ */
+const ownOperationsByDocument = new WeakMap<Document, number>();
+const browserHidesByDocument = new WeakMap<Document, number>();
+const settledCallbacksByDocument = new WeakMap<Document, (() => void)[]>();
+
+function count(map: WeakMap<Document, number>, doc: Document, delta: number) {
+ map.set(doc, Math.max(0, (map.get(doc) ?? 0) + delta));
+}
+
+function anyInFlight(doc: Document): boolean {
+ return (
+ (ownOperationsByDocument.get(doc) ?? 0) > 0 ||
+ (browserHidesByDocument.get(doc) ?? 0) > 0
+ );
+}
+
+function ended(doc: Document): void {
+ if (!anyInFlight(doc) && settledCallbacksByDocument.has(doc)) {
+ // The operation's own script is still on the stack (the `finally` of a
+ // `runPopoverOperation`, a `toggle` listener): replay once it has unwound.
+ queueMicrotask(() => replaySettled(doc));
+ }
+}
+
+function replaySettled(doc: Document): void {
+ if (anyInFlight(doc)) {
+ // Another operation started before the replay ran; its end replays.
+ return;
+ }
+ const callbacks = settledCallbacksByDocument.get(doc);
+ if (callbacks == null) {
+ return;
+ }
+ settledCallbacksByDocument.delete(doc);
+ // One microtask each: a replay that throws reaches the page on its own and
+ // leaves the ones after it to run.
+ for (const callback of callbacks) {
+ queueMicrotask(callback);
+ }
+}
+
+/** Runs `operation`, counting it as one of the layers' own popover operations in `doc`. */
+export function runPopoverOperation(
+ doc: Document,
+ operation: () => void,
+): void {
+ count(ownOperationsByDocument, doc, 1);
+ try {
+ operation();
+ } finally {
+ count(ownOperationsByDocument, doc, -1);
+ ended(doc);
+ }
+}
+
+/** Whether one of the layers' own shows or hides is running in `doc`: a show asked now would be refused. */
+export function isPopoverOperationInFlight(doc: Document): boolean {
+ return (ownOperationsByDocument.get(doc) ?? 0) > 0;
+}
+
+/**
+ * Whether a hide the browser runs itself is counted in `doc`. The count
+ * outlasts the engine's own window (it ends at the element's `toggle`, a task
+ * later), so a show asked inside it may well succeed; one the browser refuses
+ * is deferred to the count's end.
+ */
+export function isBrowserHideInFlight(doc: Document): boolean {
+ return (browserHidesByDocument.get(doc) ?? 0) > 0;
+}
+
+/** Popovers whose browser-run hide is being counted, so one hide is counted once. */
+const browserHidesInFlight = new WeakSet<Element>();
+
+/**
+ * Counts a hide the browser runs itself. Called as the element's `beforetoggle`
+ * fires, which the hide dispatches synchronously as it starts; the count ends
+ * at the element's `toggle`, which the browser queues for the task after the
+ * hide, and in any case at the next task: the hide is synchronous, so the task
+ * after it is past the window even when the element has left the document and
+ * its `toggle` never arrives. Calling it again for the same hide is a no-op.
+ */
+export function observeBrowserHide(popover: HTMLElement): void {
+ if (browserHidesInFlight.has(popover)) {
+ return;
+ }
+ browserHidesInFlight.add(popover);
+ const doc = popover.ownerDocument;
+ count(browserHidesByDocument, doc, 1);
+ const view = doc.defaultView ?? globalThis;
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ let done = false;
+ const finish = () => {
+ if (done) {
+ return;
+ }
+ done = true;
+ popover.removeEventListener('toggle', finish);
+ if (timer != null) {
+ view.clearTimeout(timer);
+ timer = null;
+ }
+ browserHidesInFlight.delete(popover);
+ count(browserHidesByDocument, doc, -1);
+ ended(doc);
+ };
+ popover.addEventListener('toggle', finish);
+ timer = view.setTimeout(finish, 0);
+}
+
+/**
+ * Runs `callback` once no popover operation of either kind is in flight in
+ * `doc`: at once when none is, otherwise in its own microtask after the last
+ * one has ended and the script that started it has unwound.
+ */
+export function afterPopoverOperations(
+ doc: Document,
+ callback: () => void,
+): void {
+ if (!anyInFlight(doc)) {
+ callback();
+ return;
+ }
+ const callbacks = settledCallbacksByDocument.get(doc);
+ if (callbacks == null) {
+ settledCallbacksByDocument.set(doc, [callback]);
+ } else {
+ callbacks.push(callback);
+ }
+}
diff --git a/packages/core/src/Layer/useLayer.test.tsx b/packages/core/src/Layer/useLayer.test.tsx
index 54738b9c73..f23e30e7d7 100644
--- a/packages/core/src/Layer/useLayer.test.tsx
+++ b/packages/core/src/Layer/useLayer.test.tsx
@@ -18,7 +18,7 @@ import {
waitFor,
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
-import {Profiler, useEffect} from 'react';
+import {Profiler, useEffect, useState} from 'react';
import {hydrateRoot} from 'react-dom/client';
import {renderToString} from 'react-dom/server';
import * as stylex from '@stylexjs/stylex';
@@ -1143,6 +1143,353 @@ describe('useLayer', () => {
expect(onTooltipShow).toHaveBeenCalledTimes(2);
});
+ /**
+ * The browser's own hide: an Escape its close watcher answers never calls
+ * the hook's hide(). The engine fires `beforetoggle` synchronously as the
+ * hide starts, restores focus inside the hide when focus was inside the
+ * popover, and fires `toggle` in a task once it has ended; `showPopover()`
+ * throws throughout.
+ */
+ function installBrowserHidePopoverApi() {
+ // The ledger's backstop for a hide whose `toggle` never arrives is the
+ // next task; under fake timers, the test decides when that task runs,
+ // so the `toggle` tasks below end a hide first, as in a browser.
+ vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout']});
+ let operationsInFlight = 0;
+ const previouslyFocused = new WeakMap<HTMLElement, Element | null>();
+ const toggleTasks: (() => void)[] = [];
+ const fireToggle = (
+ popover: HTMLElement,
+ type: 'beforetoggle' | 'toggle',
+ newState: 'open' | 'closed',
+ ) => {
+ const event = new Event(type, {bubbles: false});
+ Object.defineProperty(event, 'newState', {
+ value: newState,
+ configurable: true,
+ });
+ popover.dispatchEvent(event);
+ };
+ const hide = (popover: HTMLElement) => {
+ operationsInFlight += 1;
+ try {
+ fireToggle(popover, 'beforetoggle', 'closed');
+ delete popover.dataset.open;
+ toggleTasks.push(() => fireToggle(popover, 'toggle', 'closed'));
+ const target = previouslyFocused.get(popover);
+ previouslyFocused.delete(popover);
+ if (
+ target instanceof HTMLElement &&
+ popover.contains(document.activeElement)
+ ) {
+ target.focus();
+ }
+ } finally {
+ operationsInFlight -= 1;
+ }
+ };
+ let refusals = 0;
+ const showSpy = vi.fn(function (this: HTMLElement) {
+ if (operationsInFlight > 0 || refusals > 0) {
+ refusals = Math.max(0, refusals - 1);
+ throw new DOMException(
+ "Failed to execute 'showPopover' on 'HTMLElement': Invalid to show a popover during another show operation",
+ 'InvalidStateError',
+ );
+ }
+ operationsInFlight += 1;
+ try {
+ fireToggle(this, 'beforetoggle', 'open');
+ previouslyFocused.set(this, this.ownerDocument.activeElement);
+ this.dataset.open = 'true';
+ toggleTasks.push(() => fireToggle(this, 'toggle', 'open'));
+ } finally {
+ operationsInFlight -= 1;
+ }
+ });
+ const hideSpy = vi.fn(function (this: HTMLElement) {
+ hide(this);
+ });
+ HTMLElement.prototype.showPopover = showSpy;
+ HTMLElement.prototype.hidePopover = hideSpy;
+ return {
+ showSpy,
+ hideSpy,
+ /** The browser hides the popover itself: a close watcher's Escape. */
+ browserHide: (popover: HTMLElement) => hide(popover),
+ /** The task after the hide: the queued `toggle` events fire. */
+ runToggleTasks: () => {
+ for (const task of toggleTasks.splice(0)) {
+ task();
+ }
+ },
+ /** The engine refuses the next show too, whatever is in flight. */
+ refuseNextShow: () => {
+ refusals += 1;
+ },
+ };
+ }
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('defers the show a browser-run hide wakes until that hide has ended, and replays it at its toggle', async () => {
+ const {showSpy, browserHide, runToggleTasks} =
+ installBrowserHidePopoverApi();
+ const errors: unknown[] = [];
+ const onError = (event: ErrorEvent) => {
+ errors.push(event.error);
+ event.preventDefault();
+ };
+ window.addEventListener('error', onError);
+ const onTooltipShow = vi.fn();
+ const {getByRole} = render(
+ <FocusReturnHarness onTooltipShow={onTooltipShow} />,
+ );
+ const trigger = getByRole('button', {name: 'Trigger'});
+ const inside = getByRole('button', {name: 'Inside', hidden: true});
+ const popover = getByRole('dialog', {hidden: true});
+
+ act(() => trigger.focus());
+ fireEvent.click(trigger);
+ act(() => inside.focus());
+ runToggleTasks();
+ expect(onTooltipShow).toHaveBeenCalledTimes(1);
+ expect(popover).toHaveAttribute('data-open', 'true');
+
+ // Escape, answered by the browser's close watcher: it hides the popover
+ // on its own and returns focus to the trigger inside that hide; the
+ // tooltip asks to show.
+ act(() => browserHide(popover));
+ window.removeEventListener('error', onError);
+
+ expect(errors).toEqual([]);
+ expect(document.activeElement).toBe(trigger);
+ expect(popover).not.toHaveAttribute('data-open');
+ // The show was asked of the browser inside the hide and refused; the
+ // hook kept the refusal to itself and parked the show. Nothing else is
+ // asked before the hide ends at its `toggle`, not even after the
+ // script unwound.
+ await act(async () => {});
+ const refusals = () =>
+ showSpy.mock.results.filter(r => r.type === 'throw').length;
+ expect(refusals()).toBe(1);
+ expect(getByRole('tooltip', {hidden: true})).not.toHaveAttribute(
+ 'data-open',
+ );
+ expect(onTooltipShow).toHaveBeenCalledTimes(1);
+
+ // The task after the hide: the popover's `toggle` fires, the hook
+ // reconciles its state, and the parked show runs exactly once.
+ act(() => runToggleTasks());
+ await act(async () => {});
+ expect(refusals()).toBe(1);
+ expect(getByRole('tooltip', {hidden: true})).toHaveAttribute(
+ 'data-open',
+ 'true',
+ );
+ expect(onTooltipShow).toHaveBeenCalledTimes(2);
+ expect(popover).not.toHaveAttribute('data-open');
+ });
+
+ it('lets a replay the browser refuses again reach the page, and parks nothing more', async () => {
+ const {showSpy, browserHide, runToggleTasks, refuseNextShow} =
+ installBrowserHidePopoverApi();
+ const onTooltipShow = vi.fn();
+ const {getByRole} = render(
+ <FocusReturnHarness onTooltipShow={onTooltipShow} />,
+ );
+ const trigger = getByRole('button', {name: 'Trigger'});
+ const inside = getByRole('button', {name: 'Inside', hidden: true});
+ const popover = getByRole('dialog', {hidden: true});
+ act(() => trigger.focus());
+ fireEvent.click(trigger);
+ act(() => inside.focus());
+ runToggleTasks();
+ const refusals = () =>
+ showSpy.mock.results.filter(r => r.type === 'throw').length;
+
+ // The hide wakes the tooltip; the browser refuses; the show is parked.
+ act(() => browserHide(popover));
+ expect(refusals()).toBe(1);
+
+ // Hold the microtasks the ledger queues, to run the replay by hand.
+ const held: (() => void)[] = [];
+ const queue = vi
+ .spyOn(globalThis, 'queueMicrotask')
+ .mockImplementation(callback => {
+ held.push(callback);
+ });
+ try {
+ act(() => runToggleTasks());
+ // The hide's end queued the batch; the batch queues the one replay.
+ expect(held).toHaveLength(1);
+ held.shift()?.();
+ expect(held).toHaveLength(1);
+ const replay = held.shift();
+ // The replay runs outside the hide, so a browser that refuses again
+ // throws to the page from the replay's own microtask: nothing catches
+ // it, and nothing is parked again.
+ refuseNextShow();
+ expect(replay).toThrow(
+ expect.objectContaining({name: 'InvalidStateError'}),
+ );
+ expect(held).toHaveLength(0);
+ } finally {
+ queue.mockRestore();
+ }
+ await act(async () => {});
+ expect(refusals()).toBe(2);
+ expect(getByRole('tooltip', {hidden: true})).not.toHaveAttribute(
+ 'data-open',
+ );
+ expect(onTooltipShow).toHaveBeenCalledTimes(1);
+ });
+
+ it('opens a layer at once when the press that closed another one opens it after the hide has returned', () => {
+ // A light dismiss runs at pointerup and the click that follows opens the
+ // next layer in the same gesture: the browser accepts that show (its
+ // hide has returned) although the hidden layer's `toggle` has not fired.
+ const {showSpy, browserHide, runToggleTasks} =
+ installBrowserHidePopoverApi();
+ const api: {first?: FixedLayerReturn; second?: FixedLayerReturn} = {};
+ const onSecondShow = vi.fn();
+ function Harness() {
+ api.first = useLayer({mode: 'fixed'});
+ api.second = useLayer({mode: 'fixed', onShow: onSecondShow});
+ return (
+ <>
+ {api.first.render(<span>First</span>, {x: 0, y: 0})}
+ {api.second.render(<span>Second</span>, {x: 0, y: 0})}
+ </>
+ );
+ }
+ const {getByText} = render(<Harness />);
+ act(() => api.first?.show());
+ const first = getByText('First').closest('[popover]') as HTMLElement;
+ const second = getByText('Second').closest('[popover]') as HTMLElement;
+
+ act(() => {
+ browserHide(first);
+ api.second?.show();
+ });
+ expect(showSpy.mock.results.every(r => r.type === 'return')).toBe(true);
+ expect(second).toHaveAttribute('data-open', 'true');
+ expect(onSecondShow).toHaveBeenCalledTimes(1);
+ expect(api.second?.isOpen).toBe(true);
+ // The first layer's hide ends at its toggle, with nothing left to replay.
+ act(() => runToggleTasks());
+ expect(onSecondShow).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps counting a browser-run hide across a render it causes (an inline onHide, a state update in the focus handler)', async () => {
+ const {showSpy, browserHide, runToggleTasks} =
+ installBrowserHidePopoverApi();
+ const errors: unknown[] = [];
+ const onError = (event: ErrorEvent) => {
+ errors.push(event.error);
+ event.preventDefault();
+ };
+ window.addEventListener('error', onError);
+ const onTooltipShow = vi.fn();
+ // The host re-renders inside the hide: the focus handler sets state,
+ // and `onHide` is a new function each render, so React rebinds the
+ // layer's `toggle` listener and ref while the hide is still running.
+ function RerenderingHarness() {
+ const [focusCount, setFocusCount] = useState(0);
+ const popover = useLayer({mode: 'context', onHide: () => {}});
+ const tooltip = useLayer({mode: 'context', onShow: onTooltipShow});
+ return (
+ <>
+ <button
+ type="button"
+ ref={el => {
+ popover.ref(el);
+ tooltip.ref(el);
+ }}
+ onFocus={() => {
+ setFocusCount(count => count + 1);
+ tooltip.show();
+ }}
+ onBlur={tooltip.hide}
+ onClick={popover.show}>
+ Trigger {focusCount}
+ </button>
+ {popover.render(<button type="button">Inside</button>, {
+ role: 'dialog',
+ })}
+ {tooltip.render(<span>Tip</span>, {role: 'tooltip'})}
+ </>
+ );
+ }
+ const {getByRole} = render(<RerenderingHarness />);
+ const trigger = getByRole('button', {name: /Trigger/});
+ const inside = getByRole('button', {name: 'Inside', hidden: true});
+ const popover = getByRole('dialog', {hidden: true});
+
+ act(() => trigger.focus());
+ fireEvent.click(trigger);
+ act(() => inside.focus());
+ runToggleTasks();
+ expect(onTooltipShow).toHaveBeenCalledTimes(1);
+
+ act(() => browserHide(popover));
+ window.removeEventListener('error', onError);
+ expect(errors).toEqual([]);
+ await act(async () => {});
+ const refusals = () =>
+ showSpy.mock.results.filter(r => r.type === 'throw').length;
+ // One refusal, kept by the hook; still inside the hide's window, so
+ // nothing replayed yet, however the host re-rendered meanwhile.
+ expect(refusals()).toBe(1);
+ expect(onTooltipShow).toHaveBeenCalledTimes(1);
+
+ act(() => runToggleTasks());
+ await act(async () => {});
+ expect(refusals()).toBe(1);
+ expect(getByRole('tooltip', {hidden: true})).toHaveAttribute(
+ 'data-open',
+ 'true',
+ );
+ expect(onTooltipShow).toHaveBeenCalledTimes(2);
+ });
+
+ it('releases a browser-run hide whose element detaches before its toggle, so later shows run', async () => {
+ const {showSpy, browserHide} = installBrowserHidePopoverApi();
+ const api: {popover?: FixedLayerReturn; tooltip?: FixedLayerReturn} = {};
+ function Harness({withPopover}: {withPopover: boolean}) {
+ api.popover = useLayer({mode: 'fixed'});
+ api.tooltip = useLayer({mode: 'fixed'});
+ return (
+ <>
+ {withPopover &&
+ api.popover.render(<span>Popover</span>, {x: 0, y: 0})}
+ {api.tooltip.render(<span>Tip</span>, {x: 0, y: 0})}
+ </>
+ );
+ }
+ const {getByText, rerender} = render(<Harness withPopover />);
+ act(() => api.popover?.show());
+ const popover = getByText('Popover').closest('[popover]') as HTMLElement;
+ // The browser hides it, and React unmounts it before the `toggle` task.
+ act(() => browserHide(popover));
+ rerender(<Harness withPopover={false} />);
+ expect(popover.isConnected).toBe(false);
+
+ // The hide was synchronous: the task after it is past the window.
+ act(() => {
+ vi.runOnlyPendingTimers();
+ });
+ act(() => api.tooltip?.show());
+ await act(async () => {});
+ expect(showSpy).toHaveBeenCalledTimes(2);
+ expect(getByText('Tip').closest('[popover]')).toHaveAttribute(
+ 'data-open',
+ 'true',
+ );
+ });
+
it('drops a deferred show that hide() cancels before it replays', async () => {
const api: {popover?: FixedLayerReturn; tooltip?: FixedLayerReturn} = {};
// While the popover hides, the tooltip asks to show and then changes
diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsx
index 3c0a6fe442..cd02511470 100644
--- a/packages/core/src/Layer/useLayer.tsx
+++ b/packages/core/src/Layer/useLayer.tsx
@@ -4,7 +4,7 @@
/**
* @file useLayer.tsx
- * @input Uses React hooks, Popover API, CSS anchor positioning, shared text/provider boundaries
+ * @input Uses React hooks, Popover API (its `beforetoggle`/`toggle` events through the popoverOperations ledger), CSS anchor positioning, shared text/provider boundaries
* @output Exports the public useLayer hook plus internal trigger helpers.
* @position Core layer utility; used by useHoverCard, useTooltip, etc.
*
@@ -46,6 +46,13 @@ import {
getAnchorClearFallbacks,
slideRuleName,
} from './layerSlideRules';
+import {
+ afterPopoverOperations,
+ isBrowserHideInFlight,
+ isPopoverOperationInFlight,
+ observeBrowserHide,
+ runPopoverOperation,
+} from './popoverOperations';
import {preserveAnimations} from './preserveAnimations';
import {useLayerContext} from './LayerContext';
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
@@ -808,43 +815,6 @@ function observeAnchorClearance(
};
}
-/**
- * Popover operations in flight, per document.
- *
- * The Popover API refuses to show a popover while the document is in the
- * middle of showing or hiding ANY popover: `showPopover()` throws an
- * `InvalidStateError` ("Invalid to show a popover during another show
- * operation"); an engine still rolling the rule out instead refuses silently
- * with a console warning, which would leave this hook open with nothing
- * shown. Hiding a popover restores focus to the element that had it —
- * synchronously, inside that window — so a focus-driven layer on the element
- * receiving focus (a tooltip on the trigger that just closed a popover) asks
- * to show while the hide is still running. Every layer's show and hide passes
- * through here, so the window is observable: a `show()` that arrives inside
- * it is replayed in a microtask, which runs once the script that started the
- * operation — and the event dispatch it answered — has unwound.
- */
-const popoverOperationsByDocument = new WeakMap<Document, number>();
-
-function runPopoverOperation(doc: Document, operation: () => void): void {
- popoverOperationsByDocument.set(
- doc,
- (popoverOperationsByDocument.get(doc) ?? 0) + 1,
- );
- try {
- operation();
- } finally {
- popoverOperationsByDocument.set(
- doc,
- (popoverOperationsByDocument.get(doc) ?? 1) - 1,
- );
- }
-}
-
-function isPopoverOperationInFlight(doc: Document): boolean {
- return (popoverOperationsByDocument.get(doc) ?? 0) > 0;
-}
-
interface ContextLayerMount {
/** Null means the marker's parent is safe and the layer stays inline. */
portalTarget: HTMLElement | null;
@@ -1223,37 +1193,61 @@ function useLayerImplementation(
return dismissedByGestureRef.current === gesture;
}, []);
- const showPopoverElement = useCallback((popover: HTMLElement) => {
+ /**
+ * Asks the browser to show the popover. Returns false when the browser
+ * refused with an `InvalidStateError` while a hide it runs itself is still
+ * in flight (the ledger counts it from `beforetoggle`); the caller then
+ * replays the show once that hide has ended. Any other failure, and a
+ * refusal outside such a hide, reaches the caller: a replay runs outside
+ * the hide, so one that fails is not caught here.
+ */
+ const showPopoverElement = useCallback((popover: HTMLElement): boolean => {
// Finding infra-4: the Popover API is unsupported on Safari <17 and
// Firefox <125. On those browsers `showPopover` does not exist, so fall
// back to plain visibility instead of throwing.
if (typeof popover.showPopover === 'function') {
- runPopoverOperation(popover.ownerDocument, () => {
- // The trigger is passed as the popover's invoker `source`: a layer
- // hosted away from its trigger then still takes its sequential focus
- // order (and its popover nesting) from the trigger rather than from
- // its own DOM position. Browsers without the option ignore it.
- // `source` is declared as an `HTMLElement`. A caller-rendered icon
- // trigger is an `SVGElement`, whose dictionary conversion throws
- // before the popover opens. Omitting the option for it still anchors
- // the layer, because positioning reads the anchor-name pair, and only
- // gives up the invoker's focus order. The check asks the trigger's own
- // window: an HTML trigger rendered into another document (an iframe,
- // a Picture-in-Picture window) is not an instance of this window's
- // `HTMLElement`, and keeps its source.
- const trigger = triggerRef.current;
- const triggerView = trigger?.ownerDocument.defaultView;
- popover.showPopover({
- source:
- triggerView != null && trigger instanceof triggerView.HTMLElement
- ? trigger
- : undefined,
+ const doc = popover.ownerDocument;
+ const duringBrowserHide = isBrowserHideInFlight(doc);
+ try {
+ runPopoverOperation(doc, () => {
+ // The trigger is passed as the popover's invoker `source`: a layer
+ // hosted away from its trigger then still takes its sequential
+ // focus order (and its popover nesting) from the trigger rather
+ // than from its own DOM position. Browsers without the option
+ // ignore it. `source` is declared as an `HTMLElement`. A
+ // caller-rendered icon trigger is an `SVGElement`, whose dictionary
+ // conversion throws before the popover opens. Omitting the option
+ // for it still anchors the layer, because positioning reads the
+ // anchor-name pair, and only gives up the invoker's focus order.
+ // The check asks the trigger's own window: an HTML trigger rendered
+ // into another document (an iframe, a Picture-in-Picture window) is
+ // not an instance of this window's `HTMLElement`, and keeps its
+ // source.
+ const trigger = triggerRef.current;
+ const triggerView = trigger?.ownerDocument.defaultView;
+ popover.showPopover({
+ source:
+ triggerView != null && trigger instanceof triggerView.HTMLElement
+ ? trigger
+ : undefined,
+ });
});
- });
+ } catch (error) {
+ // The name, not the constructor: a popover in another document throws
+ // that document's `DOMException`.
+ if (
+ duringBrowserHide &&
+ (error as {name?: unknown} | null)?.name === 'InvalidStateError'
+ ) {
+ return false;
+ }
+ throw error;
+ }
} else {
popover.style.display = 'block';
}
openedPopoverRef.current = popover;
+ return true;
}, []);
const isCurrentContextPopover = useCallback(
@@ -1369,23 +1363,35 @@ function useLayerImplementation(
return;
}
if (!isOpenRef.current) {
- // Another popover is mid show/hide (typically one whose hide is handing
- // focus back to this layer's trigger): the browser would refuse the
- // show, so replay this call once that operation has returned.
- if (isPopoverOperationInFlight(popover.ownerDocument)) {
+ const replayWhenSettled = () => {
pendingShowRef.current = true;
- queueMicrotask(() => {
+ afterPopoverOperations(popover.ownerDocument, () => {
if (pendingShowRef.current) {
pendingShowRef.current = false;
showRef.current();
}
});
+ };
+ // Another layer's own show or hide is running (typically a hide that is
+ // handing focus back to this layer's trigger): the browser would refuse
+ // the show, so replay this call once that operation has returned.
+ if (isPopoverOperationInFlight(popover.ownerDocument)) {
+ replayWhenSettled();
return;
}
popover.removeAttribute(LAYER_CLEARS_ANCHOR_ATTRIBUTE);
popover.removeAttribute(LAYER_SCROLLS_ATTRIBUTE);
applyDeferredWritingContext(popover);
- showPopoverElement(popover);
+ // A hide the browser runs itself (an Escape its close watcher answers)
+ // is counted too, from `beforetoggle` until the element's `toggle`, a
+ // task after the hide has returned. The show is asked of the browser
+ // first, because the browser accepts it once its hide has returned (a
+ // light dismiss at pointerup, then this show at the click); only a show
+ // it refuses replays once the hide's count has ended.
+ if (!showPopoverElement(popover)) {
+ replayWhenSettled();
+ return;
+ }
if (keepsAnchorClear) {
keepAnchorClear(popover, triggerRef.current);
}
@@ -1536,6 +1542,22 @@ function useLayerImplementation(
// The isOpenRef guard prevents double-firing: when our hide() already set
// the ref to false, the subsequent toggle event (which the browser fires
// as a side-effect of hidePopover) sees false and skips.
+ // A hide the browser runs itself (light dismiss, popover="auto" stack
+ // eviction, an Escape its close watcher answers) never passes through
+ // hide(), so the ledger of popover operations would not know the document
+ // is mid-hide, and a layer that the hide's focus restore wakes would ask the
+ // browser to show inside it. `beforetoggle` fires synchronously as such a
+ // hide starts; the ledger counts the hide from there until the element's
+ // own `toggle`, independent of this hook's bindings, which a render inside
+ // the hide can replace.
+ const handleBeforeToggle = useCallback((e: Event) => {
+ const toggleEvent = e as ToggleEvent;
+ const el = e.currentTarget as HTMLElement | null;
+ if (toggleEvent.newState === 'closed' && isOpenRef.current && el != null) {
+ observeBrowserHide(el);
+ }
+ }, []);
+
const handleToggle = useCallback(
(e: Event) => {
const toggleEvent = e as ToggleEvent;
@@ -1572,16 +1594,21 @@ function useLayerImplementation(
'toggle',
listenedHandlerRef.current,
);
+ listenedElRef.current.removeEventListener(
+ 'beforetoggle',
+ handleBeforeToggle,
+ );
listenedElRef.current = null;
listenedHandlerRef.current = null;
}
if (el && listenedElRef.current !== el) {
el.addEventListener('toggle', handler);
+ el.addEventListener('beforetoggle', handleBeforeToggle);
listenedElRef.current = el;
listenedHandlerRef.current = handler;
}
},
- [],
+ [handleBeforeToggle],
);
const popoverRefCallback = useCallback(
@@ -1599,9 +1626,25 @@ function useLayerImplementation(
) {
// Changing a portal target remounts the popover. Preserve the logical
// open state without firing onShow again for the replacement element.
- showPopoverElement(el);
- if (keepsAnchorClear) {
- keepAnchorClear(el, triggerRef.current);
+ // A show the browser refused during one of its own hides replays once
+ // that hide has ended, for the element still mounted then.
+ if (showPopoverElement(el)) {
+ if (keepsAnchorClear) {
+ keepAnchorClear(el, triggerRef.current);
+ }
+ } else {
+ afterPopoverOperations(el.ownerDocument, () => {
+ const current = popoverRef.current;
+ if (
+ isOpenRef.current &&
+ current === el &&
+ openedPopoverRef.current !== el &&
+ showPopoverElement(el) &&
+ keepsAnchorClear
+ ) {
+ keepAnchorClear(el, triggerRef.current);
+ }
+ });
}
}
},
@@ -1640,11 +1683,15 @@ function useLayerImplementation(
'toggle',
listenedHandlerRef.current,
);
+ listenedElRef.current.removeEventListener(
+ 'beforetoggle',
+ handleBeforeToggle,
+ );
listenedElRef.current = null;
listenedHandlerRef.current = null;
}
};
- }, [handleToggle, bindToggleListener]);
+ }, [handleToggle, bindToggleListener, handleBeforeToggle]);
// Anchor visibility (FR5). The first frame must already be right (FR8), so
// the opening read is synchronous — a layout effect runs before paint, and a