Skip to content

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

TypeScript

fix(Layer): defer a show() that arrives while another popover is mid show/hide (#6941)

Christopher Chedeaud4d2151b862d
diff --git a/.changeset/layer-show-during-popover-operation.md b/.changeset/layer-show-during-popover-operation.md
new file mode 100644
index 0000000000..48a81b6b49
--- /dev/null
+++ b/.changeset/layer-show-during-popover-operation.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Defer a layer `show()` that arrives while another popover is mid show/hide, so a tooltip trigger regaining focus from a closing popover no longer throws `InvalidStateError`.
+
+@vjeux
diff --git a/apps/storybook/stories/TooltipFocusReturnA11y.stories.tsx b/apps/storybook/stories/TooltipFocusReturnA11y.stories.tsx
new file mode 100644
index 0000000000..bea026c3ed
--- /dev/null
+++ b/apps/storybook/stories/TooltipFocusReturnA11y.stories.tsx
@@ -0,0 +1,62 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file TooltipFocusReturnA11y.stories.tsx
+ * @input Uses Popover, Tooltip and Button from core
+ * @output The fixture the tooltip focus-return regression spec drives in a
+ * real browser: a popover whose trigger also carries a tooltip.
+ * @position The reproduction path for
+ * `packages/core/src/Tooltip/__tests__/TooltipFocusReturn.a11y.chromium.spec.ts`
+ * (`docs/specs/AST-009/spec.md` FR30: a browser claim is checked against a
+ * checked-in story, not a page a test builds and throws away).
+ *
+ * Closing the popover from the keyboard hands focus back to its trigger while
+ * the engine is still hiding the popover, and the Popover API refuses to show
+ * another popover inside that window. The tooltip on the trigger is the layer
+ * that asks; the spec checks that the press closes the popover without an
+ * error and the tooltip still appears for the keyboard focus that returned.
+ *
+ * SYNC: The spec navigates to this story id by name. Nothing at compile time
+ * catches a renamed export — the Chromium spec does, when it finds no story.
+ */
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {Button} from '@astryxdesign/core/Button';
+import {Popover} from '@astryxdesign/core/Popover';
+import {Tooltip} from '@astryxdesign/core/Tooltip';
+
+const meta: Meta = {
+ title: 'a11y/Tooltip focus return',
+ // This fixture exists to be DRIVEN by the regression spec, not photographed:
+ // the state under test is a focus hand-off inside one keypress, which no
+ // frame can show. Excluding it costs no coverage — it is driven in a real
+ // browser.
+ tags: ['no-visual'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'A popover whose trigger carries a tooltip. Tab to the trigger, open the popover with Enter, then close it with Escape: focus returns to the trigger and the tooltip shows again, with no error.',
+ },
+ },
+ },
+};
+
+export default meta;
+
+/**
+ * A popover trigger that also carries a tooltip — the shape of any toolbar
+ * button with a hint that opens a menu or a settings surface.
+ */
+export const PopoverTriggerWithTooltip: StoryObj = {
+ name: 'popover trigger that carries a tooltip',
+ render: () => (
+ <Popover
+ label="Options"
+ content={<Button label="Inside action" onClick={() => {}} />}>
+ <Tooltip content="More options">
+ <Button label="Options" />
+ </Tooltip>
+ </Popover>
+ ),
+};
diff --git a/packages/core/src/Layer/useLayer.test.tsx b/packages/core/src/Layer/useLayer.test.tsx
index 71e79f3dd7..96aa5acb83 100644
--- a/packages/core/src/Layer/useLayer.test.tsx
+++ b/packages/core/src/Layer/useLayer.test.tsx
@@ -733,6 +733,175 @@ describe('useLayer', () => {
});
});
+ describe('show() while another popover is mid show/hide', () => {
+ /**
+ * Mirror the Popover API's re-entrancy rule: hiding a popover hands focus
+ * back to the element that had it, synchronously and while the document
+ * still counts that popover as hiding, and `showPopover()` throws while
+ * any popover in the document is being shown or hidden.
+ */
+ function installReentrantPopoverApi(
+ duringHide?: (popover: HTMLElement) => void,
+ ) {
+ let operationsInFlight = 0;
+ const previouslyFocused = new WeakMap<HTMLElement, Element | null>();
+ const showSpy = vi.fn(function (this: HTMLElement) {
+ if (operationsInFlight > 0) {
+ throw new DOMException(
+ "Failed to execute 'showPopover' on 'HTMLElement': Invalid to show a popover during another show operation",
+ 'InvalidStateError',
+ );
+ }
+ operationsInFlight += 1;
+ try {
+ previouslyFocused.set(this, this.ownerDocument.activeElement);
+ this.dataset.open = 'true';
+ } finally {
+ operationsInFlight -= 1;
+ }
+ });
+ const hideSpy = vi.fn(function (this: HTMLElement) {
+ operationsInFlight += 1;
+ try {
+ delete this.dataset.open;
+ const target = previouslyFocused.get(this);
+ previouslyFocused.delete(this);
+ if (
+ target instanceof HTMLElement &&
+ this.contains(document.activeElement)
+ ) {
+ target.focus();
+ }
+ duringHide?.(this);
+ } finally {
+ operationsInFlight -= 1;
+ }
+ });
+ HTMLElement.prototype.showPopover = showSpy;
+ HTMLElement.prototype.hidePopover = hideSpy;
+ return {showSpy, hideSpy};
+ }
+
+ /**
+ * A trigger that opens a dismissible layer and also carries a focus-driven
+ * layer (a tooltip), the shape every tooltip-bearing popover trigger has.
+ */
+ function FocusReturnHarness({onTooltipShow}: {onTooltipShow: () => void}) {
+ const popover = useLayer({mode: 'context'});
+ const tooltip = useLayer({mode: 'context', onShow: onTooltipShow});
+ return (
+ <>
+ <button
+ type="button"
+ ref={el => {
+ popover.ref(el);
+ tooltip.ref(el);
+ }}
+ onFocus={tooltip.show}
+ onBlur={tooltip.hide}
+ onClick={popover.show}>
+ Trigger
+ </button>
+ {popover.render(
+ <button
+ type="button"
+ onKeyDown={e => {
+ if (e.key === 'Escape') {
+ popover.hide();
+ }
+ }}>
+ Inside
+ </button>,
+ {role: 'dialog'},
+ )}
+ {tooltip.render(<span>Tip</span>, {role: 'tooltip'})}
+ </>
+ );
+ }
+
+ it('defers the show a returning focus requests until the hide has returned', async () => {
+ const {showSpy} = installReentrantPopoverApi();
+ 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});
+
+ // Keyboard-open the popover: the tooltip shows on focus, the popover on
+ // the press, and focus moves inside — the tooltip closes behind it.
+ act(() => trigger.focus());
+ fireEvent.click(trigger);
+ act(() => inside.focus());
+ expect(onTooltipShow).toHaveBeenCalledTimes(1);
+ expect(getByRole('dialog', {hidden: true})).toHaveAttribute(
+ 'data-open',
+ 'true',
+ );
+ expect(getByRole('tooltip', {hidden: true})).not.toHaveAttribute(
+ 'data-open',
+ );
+
+ // Escape hides the popover; the browser returns focus to the trigger
+ // inside that hide, and the tooltip asks to show.
+ fireEvent.keyDown(inside, {key: 'Escape'});
+ window.removeEventListener('error', onError);
+
+ expect(errors).toEqual([]);
+ expect(document.activeElement).toBe(trigger);
+ expect(getByRole('dialog', {hidden: true})).not.toHaveAttribute(
+ 'data-open',
+ );
+ // Nothing reached the browser while the hide was running; the deferred
+ // show runs exactly once, after the press has unwound.
+ expect(onTooltipShow).toHaveBeenCalledTimes(1);
+ await act(async () => {});
+ expect(showSpy.mock.results.every(r => r.type === 'return')).toBe(true);
+ expect(getByRole('tooltip', {hidden: true})).toHaveAttribute(
+ 'data-open',
+ 'true',
+ );
+ expect(onTooltipShow).toHaveBeenCalledTimes(2);
+ });
+
+ 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
+ // its mind before the hide returns.
+ const {showSpy} = installReentrantPopoverApi(() => {
+ api.tooltip?.show();
+ api.tooltip?.hide();
+ });
+ function Harness() {
+ api.popover = useLayer({mode: 'fixed'});
+ api.tooltip = useLayer({mode: 'fixed'});
+ return (
+ <>
+ {api.popover.render(<span>Popover</span>, {x: 0, y: 0})}
+ {api.tooltip.render(<span>Tip</span>, {x: 0, y: 0})}
+ </>
+ );
+ }
+ const {getByText} = render(<Harness />);
+
+ act(() => api.popover?.show());
+ act(() => api.popover?.hide());
+ await act(async () => {});
+
+ // Only the popover's own show reached the browser.
+ expect(showSpy).toHaveBeenCalledTimes(1);
+ expect(getByText('Tip').closest('[popover]')).not.toHaveAttribute(
+ 'data-open',
+ );
+ });
+ });
+
describe('when the Popover API is unsupported (Safari <17 / Firefox <125)', () => {
it('show() does not throw when showPopover is undefined and the layer becomes visible', () => {
// Simulate a browser without the Popover API (finding infra-4).
diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsx
index 8e1864de34..d958dc0e4b 100644
--- a/packages/core/src/Layer/useLayer.tsx
+++ b/packages/core/src/Layer/useLayer.tsx
@@ -420,6 +420,43 @@ function toCssLength(value: number | string): string {
return typeof value === 'number' ? `${value}px` : value;
}
+/**
+ * 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;
@@ -690,8 +727,10 @@ function useLayerImplementation(
const [contextMount, setContextMount] = useState<ContextLayerMount | null>(
null,
);
- // A show() that arrives before the final layer mounts is replayed when its
- // popover ref attaches.
+ // A show() that cannot run yet is remembered here and replayed: one that
+ // arrives before the final layer mounts runs when its popover ref attaches;
+ // one that arrives while another popover is mid show/hide runs once that
+ // operation has unwound. hide() forgets it either way.
const pendingShowRef = useRef(false);
// Ref mirrors isOpen for synchronous reads inside show/hide.
@@ -715,11 +754,13 @@ function useLayerImplementation(
// Firefox <125. On those browsers `showPopover` does not exist, so fall
// back to plain visibility instead of throwing.
if (typeof popover.showPopover === 'function') {
- // 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.
- popover.showPopover({source: triggerRef.current ?? undefined});
+ 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.
+ popover.showPopover({source: triggerRef.current ?? undefined});
+ });
} else {
popover.style.display = 'block';
}
@@ -789,6 +830,19 @@ 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)) {
+ pendingShowRef.current = true;
+ queueMicrotask(() => {
+ if (pendingShowRef.current) {
+ pendingShowRef.current = false;
+ showRef.current();
+ }
+ });
+ return;
+ }
showPopoverElement(popover);
isOpenRef.current = true;
setIsOpen(true);
@@ -815,7 +869,13 @@ function useLayerImplementation(
// unsupported browsers degrade gracefully instead of throwing.
if (el) {
if (typeof el.hidePopover === 'function') {
- el.hidePopover();
+ // Hiding hands focus back to the previously focused element while
+ // the browser still counts this popover as hiding; a layer that
+ // focus wakes (a tooltip on that element) defers its show until
+ // this returns.
+ runPopoverOperation(el.ownerDocument, () => {
+ el.hidePopover();
+ });
} else {
el.style.display = 'none';
}
@@ -826,6 +886,11 @@ function useLayerImplementation(
clearContextMount();
}, [onHide, clearContextMount]);
+ // A deferred show() replays through a ref so the queued closure reaches the
+ // current callback rather than the one captured when it was queued.
+ const showRef = useRef(show);
+ showRef.current = show;
+
// Stable ref for the trigger element (context mode only).
const contextRef = useCallback(
(el: HTMLElement | null) => {
diff --git a/packages/core/src/Tooltip/__tests__/TooltipFocusReturn.a11y.chromium.spec.ts b/packages/core/src/Tooltip/__tests__/TooltipFocusReturn.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..924084817a
--- /dev/null
+++ b/packages/core/src/Tooltip/__tests__/TooltipFocusReturn.a11y.chromium.spec.ts
@@ -0,0 +1,129 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file TooltipFocusReturn.a11y.chromium.spec.ts
+ * @input Uses @playwright/test, the a11y-spec static Storybook server, and the
+ * checked-in TooltipFocusReturnA11y story
+ * @output Real-browser evidence that closing a popover from the keyboard,
+ * which hands focus back to a trigger that carries a tooltip, neither
+ * throws nor loses the tooltip.
+ * @position The half of the layer's re-entrancy rule that jsdom cannot
+ * honestly reach. Whether the engine returns focus inside `hidePopover()`,
+ * and refuses a `showPopover()` that arrives inside that window, is an
+ * engine fact (`docs/specs/AST-013/spec.md`: a browser claim is made in a
+ * browser). The Vitest cases in `Layer/useLayer.test.tsx` and
+ * `Tooltip/useTooltip.test.tsx` model that rule; this file checks it against
+ * the shipping Popover API.
+ *
+ * The HTML specification makes "show popover" throw while the document is
+ * showing or hiding any popover. Chromium carries that rule behind the
+ * `PopoverHintNewBehavior` and `PopoverHintNestedShowException` runtime
+ * features, off in the Chromium build Playwright pins here, so this spec turns
+ * them on: without them the nested show silently succeeds and the regression
+ * is invisible. Engines that enforce the rule by default need no flag.
+ *
+ * SYNC: Fixture lives in
+ * /apps/storybook/stories/TooltipFocusReturnA11y.stories.tsx.
+ */
+
+import {expect, test, type Page} from '@playwright/test';
+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+const STORY_ID = 'a11y-tooltip-focus-return--popover-trigger-with-tooltip';
+
+test.use({
+ launchOptions: {
+ args: [
+ '--enable-blink-features=PopoverHintNewBehavior,PopoverHintNestedShowException',
+ ],
+ },
+});
+
+let storybook: StaticServer;
+
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+/** Load the story and wait for the trigger the keyboard will reach. */
+async function mountStory(page: Page): Promise<void> {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=${STORY_ID}&viewMode=story`,
+ {waitUntil: 'load'},
+ );
+ await holdMotionStill(page);
+ await page
+ .locator('#storybook-root')
+ .getByRole('button', {name: 'Options'})
+ .waitFor({state: 'attached'});
+}
+
+/** Whether the element the trigger's `aria-describedby` names is showing. */
+async function tooltipIsOpen(page: Page): Promise<boolean> {
+ return page
+ .locator('#storybook-root')
+ .getByRole('button', {name: 'Options'})
+ .evaluate(trigger => {
+ const id = trigger.getAttribute('aria-describedby');
+ const tooltip = id == null ? null : document.getElementById(id);
+ return tooltip != null && tooltip.matches(':popover-open');
+ });
+}
+
+test('Escape closes the popover and the returning focus still shows the tooltip, without an error', async ({
+ page,
+}) => {
+ const pageErrors: string[] = [];
+ page.on('pageerror', error => {
+ pageErrors.push(error.message);
+ });
+ page.on('console', message => {
+ if (message.type() === 'error' || message.type() === 'warning') {
+ pageErrors.push(message.text());
+ }
+ });
+ await mountStory(page);
+
+ // Tab to the trigger: keyboard focus shows the tooltip.
+ await page.keyboard.press('Tab');
+ const trigger = page
+ .locator('#storybook-root')
+ .getByRole('button', {name: 'Options'});
+ await expect(trigger).toBeFocused();
+ await expect.poll(async () => tooltipIsOpen(page)).toBe(true);
+
+ // Enter opens the popover and focus moves inside it.
+ await page.keyboard.press('Enter');
+ const dialog = page.getByRole('dialog', {name: 'Options'});
+ await expect(dialog).toBeVisible();
+ await expect(page.getByRole('button', {name: 'Inside action'})).toBeFocused();
+ await expect.poll(async () => tooltipIsOpen(page)).toBe(false);
+
+ // Escape closes the popover. The engine returns focus to the trigger while
+ // it is still hiding the popover; the tooltip's focus-in must wait for that
+ // to finish rather than ask the engine for a show it refuses.
+ await page.keyboard.press('Escape');
+ await expect(dialog).toBeHidden();
+ await expect(trigger).toBeFocused();
+ expect(
+ pageErrors.filter(text => /popover/i.test(text)),
+ 'no popover error or warning is reported for the press',
+ ).toEqual([]);
+ await expect
+ .poll(
+ async () => tooltipIsOpen(page),
+ 'the keyboard focus that returned to the trigger shows its tooltip',
+ )
+ .toBe(true);
+});
diff --git a/packages/core/src/Tooltip/useTooltip.test.tsx b/packages/core/src/Tooltip/useTooltip.test.tsx
index ac8c17b7d0..87a752f79f 100644
--- a/packages/core/src/Tooltip/useTooltip.test.tsx
+++ b/packages/core/src/Tooltip/useTooltip.test.tsx
@@ -23,6 +23,7 @@ import {
} from 'vitest';
import {render, screen, fireEvent, act} from '@testing-library/react';
import {useTooltip, type TooltipOptions} from './useTooltip';
+import {useLayer} from '../Layer/useLayer';
// jsdom implements neither the Popover API nor `:popover-open`; mirror
// Tooltip.test.tsx's shims so the layer can open.
@@ -316,3 +317,131 @@ describe('useTooltip — teardown', () => {
expect(vi.getTimerCount()).toBe(0);
});
});
+
+describe('useTooltip — focus returning from a popover the keyboard closed', () => {
+ const shimmedShowPopover = HTMLElement.prototype.showPopover;
+ const shimmedHidePopover = HTMLElement.prototype.hidePopover;
+
+ afterEach(() => {
+ HTMLElement.prototype.showPopover = shimmedShowPopover;
+ HTMLElement.prototype.hidePopover = shimmedHidePopover;
+ });
+
+ /**
+ * The Popover API's re-entrancy rule, which the file-level shims leave out:
+ * hiding hands focus back to the previously focused element while the
+ * document still counts the popover as hiding, and `showPopover()` throws
+ * while any popover in the document is being shown or hidden.
+ */
+ function installReentrantPopoverApi() {
+ let operationsInFlight = 0;
+ const previouslyFocused = new WeakMap<HTMLElement, Element | null>();
+ const showSpy = vi.fn(function (this: HTMLElement) {
+ if (operationsInFlight > 0) {
+ throw new DOMException(
+ "Failed to execute 'showPopover' on 'HTMLElement': Invalid to show a popover during another show operation",
+ 'InvalidStateError',
+ );
+ }
+ operationsInFlight += 1;
+ try {
+ previouslyFocused.set(this, this.ownerDocument.activeElement);
+ popoverOpenState.set(this, true);
+ } finally {
+ operationsInFlight -= 1;
+ }
+ });
+ HTMLElement.prototype.showPopover = showSpy;
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ operationsInFlight += 1;
+ try {
+ popoverOpenState.set(this, false);
+ const target = previouslyFocused.get(this);
+ previouslyFocused.delete(this);
+ if (
+ target instanceof HTMLElement &&
+ this.contains(document.activeElement)
+ ) {
+ target.focus();
+ }
+ } finally {
+ operationsInFlight -= 1;
+ }
+ });
+ return showSpy;
+ }
+
+ /** A popover whose trigger also carries a tooltip. */
+ function PopoverWithTooltipTrigger({onShow}: {onShow: () => void}) {
+ const popover = useLayer({mode: 'context'});
+ const tooltip = useTooltip({onShow});
+ return (
+ <div>
+ <button
+ type="button"
+ ref={el => {
+ popover.ref(el);
+ tooltip.ref(el);
+ }}
+ aria-describedby={tooltip.describedBy}
+ onClick={popover.show}>
+ Trigger
+ </button>
+ {popover.render(
+ <button
+ type="button"
+ onKeyDown={event => {
+ if (event.key === 'Escape') {
+ popover.hide();
+ }
+ }}>
+ Inside
+ </button>,
+ {role: 'dialog'},
+ )}
+ {tooltip.renderTooltip('Helpful text')}
+ </div>
+ );
+ }
+
+ it('shows the tooltip after the hide returns instead of nesting a show inside it', async () => {
+ const showSpy = installReentrantPopoverApi();
+ const errors: unknown[] = [];
+ const onError = (event: ErrorEvent) => {
+ errors.push(event.error);
+ event.preventDefault();
+ };
+ window.addEventListener('error', onError);
+ const onShow = vi.fn();
+ render(<PopoverWithTooltipTrigger onShow={onShow} />);
+ const inside = screen.getByRole('button', {name: 'Inside', hidden: true});
+ // Keyboard focus: jsdom does not model `:focus-visible`.
+ const realMatches = trigger().matches.bind(trigger());
+ vi.spyOn(trigger(), 'matches').mockImplementation((selector: string) =>
+ selector === ':focus-visible' ? true : realMatches(selector),
+ );
+
+ // Tab to the trigger (tooltip shows), open the popover, move inside.
+ act(() => trigger().focus());
+ fireEvent.click(trigger());
+ act(() => inside.focus());
+ tick(100);
+ expect(onShow).toHaveBeenCalledTimes(1);
+ expect(tooltipElement().matches(':popover-open')).toBe(false);
+
+ // Escape closes the popover; the browser returns focus to the trigger
+ // inside that hide, and the tooltip's focus-in asks to show.
+ fireEvent.keyDown(inside, {key: 'Escape'});
+ window.removeEventListener('error', onError);
+
+ expect(errors).toEqual([]);
+ expect(document.activeElement).toBe(trigger());
+ // The press that closed the popover is not also the tooltip's to take:
+ // the show waits until the dispatch has unwound, then runs once.
+ expect(onShow).toHaveBeenCalledTimes(1);
+ await act(async () => {});
+ expect(showSpy.mock.results.every(r => r.type === 'return')).toBe(true);
+ expect(onShow).toHaveBeenCalledTimes(2);
+ expect(tooltipElement().matches(':popover-open')).toBe(true);
+ });
+});