Skip to content

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

TypeScript

fix(ContextMenu): a context menu mounts its layer at its first open, so a large Table shows its rows in seconds in Safari (#9278)

Christopher Chedeaueb6d2cc12e3b
diff --git a/.changeset/contextmenu-mounts-at-first-open.md b/.changeset/contextmenu-mounts-at-first-open.md
new file mode 100644
index 0000000000..db50892a8e
--- /dev/null
+++ b/.changeset/contextmenu-mounts-at-first-open.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A context menu that was never opened no longer mounts its menu surface; it mounts at the first open and shows as it attaches. A Table whose cells carry context menus (row expansion gives every body cell one) showed its first rows after a minute or more at 2,000 rows in Safari; it now shows them in a few seconds.
+@vjeux
diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md
index 4eaaf3274f..128c44674c 100644
--- a/docs/specs/components/ContextMenu/ContextMenu.spec.md
+++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md
@@ -143,7 +143,10 @@ Consumer props, content modes, and presentation policy remain documented in
close, and the
pointer menu observes its size and content to decide whether it scrolls. With
`presentation="adaptive"` it subscribes to the compact-touch query while
- mounted.
+ mounted. A menu never opened mounts no pointer menu surface, only its layer's
+ inert marker: the surface mounts at the first open and stays mounted after
+ it, so a page with many context menus (a table with one per cell) carries no
+ closed menu surfaces.
## Accessibility contract
diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx
index e4a7e98c61..8352ba2bb3 100644
--- a/packages/core/src/ContextMenu/ContextMenu.test.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx
@@ -116,6 +116,11 @@ beforeEach(() => {
};
});
+/** Opens the menu: its layer mounts at the first open (ContextMenu.tsx). */
+function openMenu() {
+ fireEvent.contextMenu(screen.getByText('Right-click me'));
+}
+
describe('ContextMenu', () => {
it('renders trigger children', () => {
render(
@@ -132,6 +137,7 @@ describe('ContextMenu', () => {
<div>Right-click me</div>
</ContextMenu>,
);
+ openMenu();
expect(screen.getByRole('menu', {hidden: true})).toBeInTheDocument();
});
@@ -155,6 +161,7 @@ describe('ContextMenu', () => {
<div>Right-click me</div>
</ContextMenu>,
);
+ openMenu();
// Defaults to "Context menu"; overridable via label.
expect(
screen.getByRole('menu', {name: 'Context menu', hidden: true}),
@@ -167,6 +174,7 @@ describe('ContextMenu', () => {
<div>Right-click me</div>
</ContextMenu>,
);
+ openMenu();
expect(
screen.getByRole('menu', {name: 'Row actions', hidden: true}),
).toBeInTheDocument();
@@ -529,6 +537,114 @@ describe('ContextMenu', () => {
expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();
});
+ describe('a menu that was never opened', () => {
+ it('adds no popover element and no menu until its first open, which mounts and shows it', () => {
+ render(
+ <ContextMenu items={[{label: 'Cut'}]}>
+ <div>Right-click me</div>
+ </ContextMenu>,
+ );
+ expect(document.querySelector('[popover]')).toBeNull();
+ expect(screen.queryByRole('menu', {hidden: true})).toBeNull();
+ openMenu();
+ const popover = document.querySelector('[popover]');
+ expect(popover).not.toBeNull();
+ expect(popover?.hasAttribute('popover-open')).toBe(true);
+ expect(
+ screen.getByRole('menuitem', {name: 'Cut', hidden: true}),
+ ).toBeInTheDocument();
+ });
+
+ it('shows a first open as its layer attaches, and a later open within the event', () => {
+ render(
+ <ContextMenu items={[{label: 'Cut'}]}>
+ <div>Right-click me</div>
+ </ContextMenu>,
+ );
+ const trigger = screen.getByText('Right-click me');
+ const open = () =>
+ trigger.dispatchEvent(
+ new MouseEvent('contextmenu', {bubbles: true, cancelable: true}),
+ );
+ const showPopover = vi.mocked(HTMLElement.prototype.showPopover);
+ act(() => {
+ open();
+ // No layer yet: the show waits for its popover element.
+ expect(showPopover).not.toHaveBeenCalled();
+ });
+ // The commit attached the layer, which showed it.
+ expect(showPopover).toHaveBeenCalledTimes(1);
+ fireEvent.keyDown(document, {key: 'Escape'});
+ act(() => {
+ open();
+ // Mounted: shown in the event itself.
+ expect(showPopover).toHaveBeenCalledTimes(2);
+ });
+ });
+
+ it('a keyboard open moves focus to the first item once the menu shows, and Escape returns it', async () => {
+ render(
+ <ContextMenu items={[{label: 'Cut'}, {label: 'Copy'}]}>
+ <button type="button">Right-click me</button>
+ </ContextMenu>,
+ );
+ const button = screen.getByRole('button', {name: 'Right-click me'});
+ button.focus();
+ // Shift+F10 / the Menu key: a contextmenu at (0, 0) with no click count.
+ fireEvent.contextMenu(button, {clientX: 0, clientY: 0, detail: 0});
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Cut', hidden: true}),
+ ).toHaveFocus();
+ });
+ fireEvent.keyDown(document, {key: 'Escape'});
+ expect(button).toHaveFocus();
+ });
+
+ it('carries the same trigger and cursor anchor attributes as after it opened', () => {
+ render(
+ <ContextMenu items={[{label: 'Cut'}]} data-testid="ctx">
+ <div>Right-click me</div>
+ </ContextMenu>,
+ );
+ const trigger = screen.getByTestId('ctx');
+ const describe = () => ({
+ trigger: [...trigger.attributes].map(a => `${a.name}=${a.value}`),
+ anchor: [...(trigger.lastElementChild?.attributes ?? [])].map(
+ a => a.name,
+ ),
+ anchorName: (
+ (trigger.lastElementChild as HTMLElement | null)?.style as unknown as
+ Record<string, string> | undefined
+ )?.anchorName,
+ });
+ const before = describe();
+ openMenu();
+ fireEvent.keyDown(document, {key: 'Escape'});
+ expect(describe()).toEqual(before);
+ expect(trigger.hasAttribute('aria-controls')).toBe(false);
+ expect(trigger.hasAttribute('aria-haspopup')).toBe(false);
+ });
+
+ it('keeps its layer mounted after the first close, and a second open shows the same menu', () => {
+ render(
+ <ContextMenu items={[{label: 'Cut'}]}>
+ <div>Right-click me</div>
+ </ContextMenu>,
+ );
+ openMenu();
+ const menu = screen.getByRole('menu', {hidden: true});
+ fireEvent.keyDown(document, {key: 'Escape'});
+ expect(menu.isConnected).toBe(true);
+ expect(
+ document.querySelector('[popover]')?.hasAttribute('popover-open'),
+ ).toBe(false);
+ openMenu();
+ expect(screen.getByRole('menu', {hidden: true})).toBe(menu);
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(2);
+ });
+ });
+
it('opens on touch long-press', () => {
vi.useFakeTimers();
try {
@@ -646,6 +762,7 @@ describe('ContextMenu items', () => {
<div>Right-click me</div>
</ContextMenu>,
);
+ openMenu();
expect(
screen.getByRole('menuitem', {name: 'Cut', hidden: true}),
).toBeInTheDocument();
@@ -662,6 +779,7 @@ describe('ContextMenu items', () => {
<div>Right-click me</div>
</ContextMenu>,
);
+ openMenu();
await user.click(screen.getByRole('menuitem', {name: 'Cut', hidden: true}));
expect(handleClick).toHaveBeenCalledTimes(1);
@@ -676,6 +794,7 @@ describe('ContextMenu items', () => {
<div>Right-click me</div>
</ContextMenu>,
);
+ openMenu();
await user.click(screen.getByRole('menuitem', {name: 'Cut', hidden: true}));
expect(handleClick).not.toHaveBeenCalled();
@@ -687,6 +806,7 @@ describe('ContextMenu items', () => {
<div>Right-click me</div>
</ContextMenu>,
);
+ openMenu();
expect(
screen.getByRole('menuitem', {name: 'Cut', hidden: true}),
).toHaveAttribute('aria-disabled', 'true');
@@ -704,6 +824,7 @@ describe('ContextMenu destructive variant', () => {
<div>Right-click me</div>
</ContextMenu>,
);
+ openMenu();
expect(
screen.getByRole('menuitem', {name: 'Delete', hidden: true}),
@@ -728,6 +849,7 @@ describe('ContextMenu sections', () => {
<div>Right-click me</div>
</ContextMenu>,
);
+ openMenu();
expect(screen.getByText('Edit')).toBeInTheDocument();
expect(
@@ -751,6 +873,7 @@ describe('ContextMenu sections', () => {
<div>Right-click me</div>
</ContextMenu>,
);
+ openMenu();
const group = screen.getByRole('group', {name: 'Edit', hidden: true});
expect(group).toBeInTheDocument();
@@ -765,6 +888,7 @@ describe('ContextMenu dividers', () => {
<div>Right-click me</div>
</ContextMenu>,
);
+ openMenu();
expect(
screen.getByRole('menuitem', {name: 'Cut', hidden: true}),
@@ -829,6 +953,7 @@ describe('ContextMenu compound mode', () => {
<div>Right-click me</div>
</ContextMenu>,
);
+ openMenu();
expect(
screen.getByRole('menuitem', {name: 'Cut', hidden: true}),
).toBeInTheDocument();
@@ -850,6 +975,7 @@ describe('ContextMenu compound mode', () => {
<div>Right-click me</div>
</ContextMenu>,
);
+ openMenu();
expect(screen.getByTestId('shortcut')).toHaveTextContent('⌘X');
});
@@ -867,6 +993,7 @@ describe('ContextMenu compound mode', () => {
<div>Right-click me</div>
</ContextMenu>,
);
+ openMenu();
expect(screen.getByRole('separator', {hidden: true})).toHaveClass(
'astryx-dropdown-menu-divider',
@@ -882,6 +1009,7 @@ describe('ContextMenu compound mode', () => {
<div>Right-click me</div>
</ContextMenu>,
);
+ openMenu();
await user.click(screen.getByRole('menuitem', {name: 'Cut', hidden: true}));
expect(handleClick).toHaveBeenCalledTimes(1);
@@ -900,6 +1028,7 @@ describe('ContextMenu compound mode', () => {
<div>Right-click me</div>
</ContextMenu>,
);
+ openMenu();
expect(
screen.getByRole('menuitem', {name: 'Cut', hidden: true}),
@@ -1035,6 +1164,7 @@ describe('ContextMenu selectable items', () => {
<div>Right-click me</div>
</ContextMenu>,
);
+ openMenu();
expect(
screen.getByRole('menuitemradio', {name: 'Sort by name', hidden: true}),
).toHaveAttribute('aria-checked', 'true');
@@ -1074,6 +1204,7 @@ describe('ContextMenu selectable items', () => {
<div>Right-click me</div>
</ContextMenu>,
);
+ openMenu();
await user.click(
screen.getByRole('menuitemradio', {name: 'Sort by date', hidden: true}),
);
diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx
index 322a6c7c85..84e95dadd0 100644
--- a/packages/core/src/ContextMenu/ContextMenu.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.tsx
@@ -22,6 +22,12 @@
*
* Both modes use useListFocus for DOM-based keyboard navigation.
* Open state is managed internally — right-click opens, click-outside/Escape closes.
+ * The menu's layer mounts at its first open, and shows as it attaches
+ * (`useLayer`'s `lazyMount`, kept mounted after the first show): a closed
+ * context menu that was never opened adds no popover element to the page (a
+ * table with a menu on every cell would otherwise carry one per cell). Once
+ * mounted it stays, so every later open and close, its exit animation
+ * included, runs as before.
* The trigger wrapper is a `div` by default; `triggerAs` makes it an inline
* `span`, so a reference inside prose can own a context menu without
* breaking the text flow.
@@ -49,7 +55,7 @@ import * as stylex from '@stylexjs/stylex';
import {Button} from '../Button';
import {Heading} from '../Heading';
import {Icon} from '../Icon';
-import {useLayer} from '../Layer/useLayer';
+import {useLayerInternal} from '../Layer/useLayer';
import {LayerDepthProvider} from '../Layer/LayerDepthContext';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
import {currentGesture} from '../Layer/gestureCounter';
@@ -375,6 +381,10 @@ export function ContextMenu({
const openingGestureRef = useRef<number | null>(null);
const [isOpen, setIsOpen] = useState(false);
+ // An open from the trigger moves focus into the menu once it shows: a frame
+ // after the show, which for a first open comes as its layer attaches.
+ const focusOnShowRef = useRef(false);
+ const focusFirstRef = useRef<() => void>(() => {});
const [submenuPath, setSubmenuPath] = useState<ContextMenuItemData[]>([]);
const currentSubmenu = submenuPath.at(-1);
const currentItems = currentSubmenu?.items ?? items;
@@ -392,8 +402,11 @@ export function ContextMenu({
[onOpenChange],
);
- const layer = useLayer({
+ const layer = useLayerInternal({
mode: 'context',
+ // Mounted at the first open and kept (see the file header).
+ lazyMount: true,
+ keepsMountAfterShow: true,
onHide: useCallback(() => {
setIsOpen(false);
onOpenChange?.(false);
@@ -407,6 +420,10 @@ export function ContextMenu({
onShow: useCallback(() => {
setIsOpen(true);
onOpenChange?.(true);
+ if (focusOnShowRef.current) {
+ focusOnShowRef.current = false;
+ requestAnimationFrame(() => focusFirstRef.current());
+ }
}, [onOpenChange]),
lightDismiss: false,
});
@@ -455,6 +472,7 @@ export function ContextMenu({
wrap: true,
hasPaging: true,
});
+ focusFirstRef.current = focusFirst;
// Join the shared stack so an Escape press dismisses exactly one top-most
// surface. BottomSheet owns its own dismissal path.
@@ -582,11 +600,14 @@ export function ContextMenu({
if (usesBottomSheet) {
updateOpenState(true);
} else {
+ // A first open mounts the layer, and the show runs from the popover
+ // element's callback ref as it attaches, in the same commit, before
+ // the browser paints; a later one shows at once.
+ focusOnShowRef.current = true;
layer.show();
- requestAnimationFrame(() => focusFirst());
}
},
- [layer, focusFirst, updateOpenState, usesBottomSheet],
+ [layer, updateOpenState, usesBottomSheet],
);
// The box the cursor anchor's offsets are measured from: the trigger, which
diff --git a/packages/core/src/Layer/useLayer.test.tsx b/packages/core/src/Layer/useLayer.test.tsx
index 262c5b9302..b7d8f1b3bc 100644
--- a/packages/core/src/Layer/useLayer.test.tsx
+++ b/packages/core/src/Layer/useLayer.test.tsx
@@ -175,6 +175,48 @@ function RelocatingOpenContextHostingHarness({
);
}
+/**
+ * A lazily mounted layer through the internal options path, optionally kept
+ * mounted after its first show, whose render call can move between a safe and
+ * an unsafe host.
+ */
+function KeptLazyContextHarness({
+ unsafe = false,
+ keepsMountAfterShow = true,
+ onHide,
+}: {
+ unsafe?: boolean;
+ keepsMountAfterShow?: boolean;
+ onHide?: () => void;
+}) {
+ const layer = useLayerInternal({
+ mode: 'context',
+ lazyMount: true,
+ keepsMountAfterShow,
+ onHide,
+ });
+ const renderedLayer = layer.render(
+ <button type="button">Layer action</button>,
+ );
+ return (
+ <>
+ <button type="button" ref={layer.ref} onClick={layer.show}>
+ Trigger
+ </button>
+ <button type="button" onClick={layer.hide}>
+ Close
+ </button>
+ {unsafe ? (
+ <div data-testid="unsafe-host">
+ <p>{renderedLayer}</p>
+ </div>
+ ) : (
+ <section data-testid="safe-host">{renderedLayer}</section>
+ )}
+ </>
+ );
+}
+
describe('useLayer identity', () => {
it('keeps the context ref and API object stable across rerenders', () => {
const {result, rerender} = renderHook(() => useLayer({mode: 'context'}));
@@ -927,6 +969,114 @@ describe('useLayer', () => {
expect(showSpy).toHaveBeenCalledTimes(2);
expect(onShow).toHaveBeenCalledOnce();
});
+
+ describe('a lazy layer kept mounted after its first show', () => {
+ const mockPopover = () => {
+ const showSpy = vi.fn(function (this: HTMLElement) {
+ this.dataset.open = 'true';
+ });
+ HTMLElement.prototype.showPopover = showSpy;
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ delete this.dataset.open;
+ });
+ return showSpy;
+ };
+
+ it('mounts only its inert marker until its first show', () => {
+ const {container} = render(<KeptLazyContextHarness />);
+
+ expect(container.querySelector('template')).not.toBeNull();
+ expect(container.querySelector('[popover]')).toBeNull();
+ expect(container).not.toHaveTextContent('Layer action');
+ });
+
+ it('stays mounted, closed, after its first hide, and its next show opens the same element at once', async () => {
+ const showSpy = mockPopover();
+ const onHide = vi.fn();
+ const {container, getByRole} = render(
+ <KeptLazyContextHarness onHide={onHide} />,
+ );
+
+ fireEvent.click(getByRole('button', {name: 'Trigger'}));
+ await waitFor(() => {
+ expect(container.querySelector('[popover]')).toHaveAttribute(
+ 'data-open',
+ 'true',
+ );
+ });
+ const layer = container.querySelector('[popover]');
+
+ fireEvent.click(getByRole('button', {name: 'Close'}));
+ expect(onHide).toHaveBeenCalledOnce();
+ // Still in the page, closed, so its close can play out.
+ expect(layer?.isConnected).toBe(true);
+ expect(container.querySelector('[popover]')).toBe(layer);
+ expect(layer).not.toHaveAttribute('data-open');
+
+ act(() => {
+ getByRole('button', {name: 'Trigger'}).click();
+ // Mounted: shown within the call, not after a commit.
+ expect(showSpy).toHaveBeenCalledTimes(2);
+ });
+ expect(container.querySelector('[popover]')).toBe(layer);
+ expect(layer).toHaveAttribute('data-open', 'true');
+ });
+
+ it('without the option, a lazy layer still unmounts on hide', async () => {
+ mockPopover();
+ const {container, getByRole} = render(
+ <KeptLazyContextHarness keepsMountAfterShow={false} />,
+ );
+
+ fireEvent.click(getByRole('button', {name: 'Trigger'}));
+ await waitFor(() => {
+ expect(container.querySelector('[popover]')).not.toBeNull();
+ });
+ fireEvent.click(getByRole('button', {name: 'Close'}));
+
+ await waitFor(() => {
+ expect(container.querySelector('[popover]')).toBeNull();
+ });
+ expect(container.querySelector('template')).not.toBeNull();
+ });
+
+ it('re-resolves its kept mount when its render call moves, closed, and opens there on the next show', async () => {
+ mockPopover();
+ const {container, getByRole, rerender} = render(
+ <KeptLazyContextHarness unsafe />,
+ );
+
+ fireEvent.click(getByRole('button', {name: 'Trigger'}));
+ await waitFor(() => {
+ expect(container.querySelector('[popover]')).toHaveAttribute(
+ 'data-open',
+ 'true',
+ );
+ });
+ // Portaled out of the paragraph, into its host.
+ expect(container.querySelector('[popover]')?.parentElement).toBe(
+ container.querySelector('[data-testid="unsafe-host"]'),
+ );
+ fireEvent.click(getByRole('button', {name: 'Close'}));
+
+ rerender(<KeptLazyContextHarness unsafe={false} />);
+
+ await waitFor(() => {
+ expect(container.querySelector('[popover]')?.parentElement).toBe(
+ container.querySelector('[data-testid="safe-host"]'),
+ );
+ });
+ expect(container.querySelector('[popover]')).not.toHaveAttribute(
+ 'data-open',
+ );
+
+ fireEvent.click(getByRole('button', {name: 'Trigger'}));
+ expect(container.querySelector('[popover]')).toHaveAttribute(
+ 'data-open',
+ 'true',
+ );
+ });
+ });
});
describe('when the Popover API is supported', () => {
diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsx
index 9d6e8ac818..e14899af63 100644
--- a/packages/core/src/Layer/useLayer.tsx
+++ b/packages/core/src/Layer/useLayer.tsx
@@ -443,6 +443,14 @@ interface InternalContextLayerOptions extends ContextLayerOptions {
* its trigger keeps open.
*/
keepsAnchorClear?: boolean;
+ /**
+ * With `lazyMount`, the layer stays mounted once its first `show()` mounted
+ * it: hiding leaves it in place, so its close plays out and every later
+ * `show()` opens it at once. A layer never shown still mounts only its inert
+ * marker. For a component with many triggers that each own a layer (a
+ * context menu on every table cell).
+ */
+ keepsMountAfterShow?: boolean;
}
type InternalContextLayerReturn = ContextLayerReturn & InternalLayerFields;
@@ -1151,6 +1159,10 @@ function useLayerImplementation(
): InternalContextLayerReturn | InternalFixedLayerReturn {
const {mode, onShow, onHide, lightDismiss = false} = options;
const lazyMount = mode === 'context' ? (options.lazyMount ?? false) : false;
+ const keepsMountAfterShow =
+ lazyMount && mode === 'context'
+ ? (options.keepsMountAfterShow ?? false)
+ : false;
const keepsAnchorClear =
mode === 'context' ? (options.keepsAnchorClear ?? false) : false;
const id = useId();
@@ -1360,12 +1372,12 @@ function useLayerImplementation(
);
const clearContextMount = useCallback(() => {
- if (mode !== 'context' || !lazyMount) {
+ if (mode !== 'context' || !lazyMount || keepsMountAfterShow) {
return;
}
contextMountRef.current = null;
mountStore.set(null);
- }, [mode, lazyMount, mountStore]);
+ }, [mode, lazyMount, keepsMountAfterShow, mountStore]);
const show = useCallback(() => {
// Every caller lands here, so this is where the dismissing press is
@@ -1682,14 +1694,21 @@ function useLayerImplementation(
const sentinelRefCallback = useCallback(
(el: HTMLTemplateElement | null) => {
sentinelRef.current = el;
- if (el && (!lazyMount || pendingShowRef.current || isOpenRef.current)) {
+ // A layer that keeps its mount re-resolves it too once it has one.
+ if (
+ el &&
+ (!lazyMount ||
+ pendingShowRef.current ||
+ isOpenRef.current ||
+ (keepsMountAfterShow && contextMountRef.current != null))
+ ) {
// The render call may have moved while the hook stayed mounted.
// Resolve again from the newly attached marker rather than reusing a
// portal target from its previous JSX position.
requestContextMount();
}
},
- [lazyMount, requestContextMount],
+ [lazyMount, keepsMountAfterShow, requestContextMount],
);
// Re-bind when the handler identity changes while the element stays mounted,
diff --git a/packages/core/src/Table/__tests__/TableCellMenus.a11y.browser.spec.ts b/packages/core/src/Table/__tests__/TableCellMenus.a11y.browser.spec.ts
new file mode 100644
index 0000000000..46a01c1eba
--- /dev/null
+++ b/packages/core/src/Table/__tests__/TableCellMenus.a11y.browser.spec.ts
@@ -0,0 +1,187 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y scope ^packages/core/src/Table/ ^packages/core/src/ContextMenu/ ^apps/storybook/stories/TableRowExpansion
+
+/**
+ * @file TableCellMenus.a11y.browser.spec.ts
+ * @input Built TableRowExpansion stories in real Chromium and WebKit
+ * @output Browser evidence that a cell's context menu adds nothing to the page
+ * until it first opens (a 2,000-row table carries no popover element per
+ * cell), and that the first right-click, keyboard open and long press still
+ * open it as before: at the pointer, at the trigger's corner, or at the
+ * finger, focus moving into it and back, and its close and a second open
+ * unchanged
+ * @position Regression proof for ContextMenu mounting its layer at its first
+ * open (row expansion gives every body cell a context menu)
+ */
+
+import {expect, test, type Locator, type Page} from '@playwright/test';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+import {tap, touchDriver} from '@astryxdesign/interaction-harness';
+
+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 mount(page: Page, story: string, args = '', timeout = 5000) {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-tablerowexpansion--${story}&viewMode=story${args}`,
+ );
+ await expect(page.locator('[data-expansion-toggle]').first()).toBeVisible({
+ timeout,
+ });
+}
+
+/** A body cell's text, away from its expansion toggle. */
+const nameCell = (page: Page) =>
+ page.locator('.astryx-table-scroll-wrapper tbody td').nth(1);
+
+/** Marks the element so the test can tell it from a replacement. */
+async function mark(locator: Locator) {
+ await locator.evaluate(el => {
+ (el as unknown as {__marked: boolean}).__marked = true;
+ });
+}
+
+test('a closed cell menu adds no popover element: none among 2,000 rows', async ({
+ page,
+}) => {
+ // 2,000 rows: a slow runner takes more than the default 5 s to render it.
+ await mount(page, 'gliding-rows-long-table', '&args=glide:!false', 30_000);
+ // Every body cell carries a context menu (the expansion toggle action).
+ expect(
+ await page.locator('.astryx-table-scroll-wrapper tbody td').count(),
+ ).toBeGreaterThan(9_000);
+ expect(
+ await page.locator('.astryx-table-scroll-wrapper [popover]').count(),
+ ).toBe(0);
+});
+
+test('the first right-click opens a cell menu at the pointer', async ({
+ page,
+}) => {
+ await mount(page, 'gliding-rows');
+ const box = await nameCell(page).boundingBox();
+ if (box == null) {
+ throw new Error('the cell has no rendered bounds');
+ }
+ const point = {x: Math.round(box.x) + 12, y: Math.round(box.y) + 9};
+ await page.mouse.click(point.x, point.y, {button: 'right'});
+ const menu = page.getByRole('menu');
+ await expect(menu).toBeVisible();
+ await expect(menu.getByRole('menuitem')).toHaveCount(1);
+ // The menu is anchored to a 1 px box at the pointer.
+ const anchor = await nameCell(page)
+ .locator('span[aria-hidden="true"][style*="anchor-name"]')
+ .boundingBox();
+ expect(Math.abs((anchor?.x ?? 0) - point.x)).toBeLessThanOrEqual(1);
+ expect(Math.abs((anchor?.y ?? 0) - point.y)).toBeLessThanOrEqual(1);
+});
+
+test("a keyboard open on a cell's toggle opens its menu at once, moves focus into it, and Escape hands focus back", async ({
+ page,
+}) => {
+ await mount(page, 'gliding-rows');
+ const toggle = page.locator('[data-expansion-toggle]').first();
+ await toggle.focus();
+ await mark(toggle);
+ // Shift+F10 and the Menu key reach the focused element as a contextmenu at
+ // (0, 0) with no click count, as several browsers send them.
+ await toggle.evaluate(el => {
+ el.dispatchEvent(
+ new MouseEvent('contextmenu', {
+ bubbles: true,
+ cancelable: true,
+ clientX: 0,
+ clientY: 0,
+ detail: 0,
+ }),
+ );
+ });
+ const menu = page.getByRole('menu');
+ await expect(menu).toBeVisible();
+ await expect(menu.getByRole('menuitem', {name: 'Expand row'})).toBeFocused();
+ await page.keyboard.press('Escape');
+ await expect(menu).toBeHidden();
+ // The same toggle has focus: the cell's content was not replaced.
+ expect(
+ await page.evaluate(
+ () =>
+ (document.activeElement as unknown as {__marked?: boolean} | null)
+ ?.__marked === true,
+ ),
+ ).toBe(true);
+});
+
+test('the first close leaves the menu mounted for its exit, and a second open shows the same menu', async ({
+ page,
+}) => {
+ await mount(page, 'gliding-rows');
+ const cell = nameCell(page);
+ const openLayer = async () =>
+ (
+ await page.waitForFunction(() =>
+ document.querySelector(
+ '.astryx-table-scroll-wrapper [popover]:popover-open',
+ ),
+ )
+ ).asElement();
+ await cell.click({button: 'right', position: {x: 12, y: 9}});
+ const layer = await openLayer();
+ if (layer == null) {
+ throw new Error('no open menu layer');
+ }
+ await layer.evaluate(el => {
+ (el as unknown as {__marked: boolean}).__marked = true;
+ });
+ const exit = await layer.evaluate(el => getComputedStyle(el).transition);
+ await page.keyboard.press('Escape');
+ await expect(page.getByRole('menu')).toBeHidden();
+ // Still in the page, with the transition its close plays.
+ expect(await layer.evaluate(el => el.isConnected)).toBe(true);
+ expect(await layer.evaluate(el => getComputedStyle(el).transition)).toBe(
+ exit,
+ );
+ await cell.click({button: 'right', position: {x: 20, y: 9}});
+ const reopened = await openLayer();
+ expect(
+ await reopened?.evaluate(
+ el => (el as unknown as {__marked?: boolean}).__marked === true,
+ ),
+ ).toBe(true);
+});
+
+test.describe('on a touch screen', () => {
+ test.use({hasTouch: true});
+
+ test('the first long press on a cell opens its menu at the finger', async ({
+ page,
+ }) => {
+ await mount(page, 'gliding-rows');
+ const cell = nameCell(page);
+ const box = await cell.boundingBox();
+ if (box == null) {
+ throw new Error('the cell has no rendered bounds');
+ }
+ const point = {x: Math.round(box.x) + 14, y: Math.round(box.y) + 10};
+ // A real touch held past the long-press delay, then lifted: the menu
+ // opens while the finger is down and stays open as it lifts.
+ const driver = await touchDriver(page);
+ await driver.play(tap(point, {holdMs: 800}));
+ await expect(page.getByRole('menu')).toBeVisible();
+ const anchor = await cell
+ .locator('span[aria-hidden="true"][style*="anchor-name"]')
+ .boundingBox();
+ expect(Math.abs((anchor?.x ?? 0) - point.x)).toBeLessThanOrEqual(1);
+ expect(Math.abs((anchor?.y ?? 0) - point.y)).toBeLessThanOrEqual(1);
+ });
+});