Skip to content

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

TypeScript

fix(ContextMenu): the menu paints in Safari when its trigger sits in a scroll container (#7369)

Christopher Chedeau62279335c1ba
diff --git a/.changeset/context-menu-cursor-anchor-box.md b/.changeset/context-menu-cursor-anchor-box.md
new file mode 100644
index 0000000000..74f004d360
--- /dev/null
+++ b/.changeset/context-menu-cursor-anchor-box.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `ContextMenu` paints in Safari when its trigger sits inside a scroll container. The menu is anchored to a box at the pointer, and that box was empty: WebKit counts an empty anchor box inside a scroller as clipped, so the default `position-visibility: anchors-visible` hid the open menu. The anchor is now 1px, kept inside the trigger, so the menu still hides while a scroller clips the pointer position and paints again when it scrolls back. A pointer-opened menu now starts 1px lower, below the pixel under the pointer.
+
+@vjeux
diff --git a/apps/storybook/stories/ContextMenu.stories.tsx b/apps/storybook/stories/ContextMenu.stories.tsx
index fe56074798..369ed0dd64 100644
--- a/apps/storybook/stories/ContextMenu.stories.tsx
+++ b/apps/storybook/stories/ContextMenu.stories.tsx
@@ -515,3 +515,35 @@ export const InlineTrigger: Story = {
</p>
),
};
+
+export const InScrollContainer: Story = {
+ name: 'Inside a scroll container',
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'The trigger scrolls inside a box. The menu opens at the pointer, and the browser hides it while the box scrolls the pointer position out of view.',
+ },
+ },
+ },
+ render: () => (
+ <div
+ data-testid="context-menu-scroller"
+ // The box scrolls but holds nothing focusable, so it needs a tab stop
+ // and a name for keyboard scrolling (axe: scrollable-region-focusable).
+ tabIndex={0}
+ role="region"
+ aria-label="Scrolling content"
+ style={{width: 320, height: 160, overflowY: 'auto'}}>
+ <p style={{height: 240, margin: 0}}>Scroll down to the area.</p>
+ <ContextMenu
+ items={[
+ {label: 'Cut', onClick: () => {}},
+ {label: 'Copy', onClick: () => {}},
+ {label: 'Paste', onClick: () => {}},
+ ]}>
+ <div {...stylex.props(triggerStyles.area)}>Right-click this area</div>
+ </ContextMenu>
+ </div>
+ ),
+};
diff --git a/packages/core/src/ContextMenu/ContextMenu.spec.md b/packages/core/src/ContextMenu/ContextMenu.spec.md
index 51c89df3e9..7f1081c4d3 100644
--- a/packages/core/src/ContextMenu/ContextMenu.spec.md
+++ b/packages/core/src/ContextMenu/ContextMenu.spec.md
@@ -146,7 +146,7 @@ the highlight is DOM focus per `module:DropdownMenu/useMenuPress` AR1.
| Touch action row | Presents one data-driven touch action or drill-in entry using ListItem. | `component:List` | Prominent | FR1, FR3, FR4 |
The `context-menu` target intentionally appears on both alternative painted
-menu surfaces. Trigger area content stays caller-owned and the zero-size cursor
+menu surfaces. Trigger area content stays caller-owned and the 1px cursor
anchor is positioning infrastructure rather than consumer anatomy.
### Theming anatomy
diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx
index c880a9cc3b..2907da8c3f 100644
--- a/packages/core/src/ContextMenu/ContextMenu.test.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx
@@ -658,7 +658,7 @@ describe('ContextMenu compound mode', () => {
});
describe('cursor anchor positioning (#3465)', () => {
- // The menu is anchored to a zero-size element placed at the cursor point
+ // The menu is anchored to a 1px element placed at the cursor point
// *inside the trigger*, so it is positioned relative to the trigger's
// context (scroll-follow + auto-flip) rather than the viewport.
function getCursorAnchor(trigger: HTMLElement): HTMLElement {
@@ -669,7 +669,7 @@ describe('ContextMenu compound mode', () => {
return anchor;
}
- it('renders a zero-size cursor anchor inside the trigger', () => {
+ it('renders a 1px cursor anchor inside the trigger', () => {
render(
<ContextMenu items={[{label: 'Item 1'}]} data-testid="ctx">
<div>Right-click me</div>
@@ -680,6 +680,9 @@ describe('ContextMenu compound mode', () => {
// Carries an anchor-name so the menu can be anchored to it via CSS
// anchor positioning (context mode), not fixed viewport coordinates.
expect(anchor.style.anchorName).toMatch(/^--astryx-layer-/);
+ // Owns a box: WebKit counts an empty anchor box inside a scroll
+ // container as clipped, and `position-visibility` hides the menu.
+ expect(anchor).toHaveStyle({width: '1px', height: '1px'});
});
it('places the cursor anchor at the pointer position relative to the trigger', () => {
@@ -725,7 +728,37 @@ describe('ContextMenu compound mode', () => {
fireEvent.contextMenu(trigger, {clientX: 0, clientY: 0, detail: 0});
const anchor = getCursorAnchor(trigger);
expect(anchor.style.left).toBe('0px');
- expect(anchor.style.top).toBe('20px');
+ // The 1px anchor steps back into the trigger's last pixel row, so its
+ // bottom edge (where the menu starts) is still the trigger's bottom.
+ expect(anchor.style.top).toBe('19px');
+ });
+
+ it('keeps the anchor inside the trigger at its end edges, and nowhere else', () => {
+ render(
+ <ContextMenu items={[{label: 'Item 1'}]} data-testid="ctx">
+ <div>Right-click me</div>
+ </ContextMenu>,
+ );
+ const trigger = screen.getByTestId('ctx');
+ trigger.getBoundingClientRect = () =>
+ ({
+ left: 100,
+ top: 50,
+ right: 300,
+ bottom: 150,
+ width: 200,
+ height: 100,
+ }) as DOMRect;
+ const anchor = getCursorAnchor(trigger);
+ // A point on the trigger's end edges steps back by the anchor's pixel.
+ fireEvent.contextMenu(trigger, {clientX: 300, clientY: 150, detail: 1});
+ expect(anchor.style.left).toBe('199px');
+ expect(anchor.style.top).toBe('99px');
+ // A point past the trigger (content overflowing it) stays at the
+ // pointer, as does a point on the trigger's start edges.
+ fireEvent.contextMenu(trigger, {clientX: 320, clientY: 50, detail: 1});
+ expect(anchor.style.left).toBe('220px');
+ expect(anchor.style.top).toBe('0px');
});
});
});
diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx
index 4c23df71df..5dee00383b 100644
--- a/packages/core/src/ContextMenu/ContextMenu.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.tsx
@@ -9,7 +9,7 @@
* @position Core implementation; consumed by index.ts
*
* Right-click context menu positioned at the cursor. The cursor point is
- * captured as an offset *inside the trigger* and materialized as a zero-size
+ * captured as an offset *inside the trigger* and materialized as a 1px
* anchor element, so the menu is positioned relative to the trigger's context
* (via CSS anchor positioning) rather than the viewport. It therefore follows
* the content on scroll and auto-flips at viewport edges, while still appearing
@@ -112,14 +112,16 @@ const styles = stylex.create({
WebkitUserSelect: 'none',
userSelect: 'none',
},
- // Zero-size anchor placed at the cursor point within the trigger. The menu
- // is anchored to this element, so it sits under the cursor yet is positioned
+ // 1px anchor placed at the cursor point within the trigger. The menu is
+ // anchored to this element, so it sits under the cursor yet is positioned
// relative to the trigger's context — it follows the content on scroll and
- // the browser can auto-flip it against the viewport edges.
+ // the browser can auto-flip it against the viewport edges. It owns a box
+ // because WebKit counts an empty anchor box as clipped, and the default
+ // `position-visibility: anchors-visible` then hides the menu.
cursorAnchor: {
position: 'absolute',
- width: 0,
- height: 0,
+ width: '1px',
+ height: '1px',
pointerEvents: 'none',
},
menu: {
@@ -185,6 +187,17 @@ const styles = stylex.create({
},
});
+/**
+ * Keeps the 1px cursor anchor inside the trigger along one axis. A point in
+ * the trigger's last pixel (Shift+F10 opens on its bottom edge) steps back by
+ * that pixel: past the edge the anchor would add scrollable overflow, and a
+ * scroller whose edge meets the trigger's would clip it and hide the menu.
+ * Any other point, inside the trigger or not, stays where it is.
+ */
+function keepAnchorInside(offset: number, size: number): number {
+ return offset > size - 1 && offset <= size ? Math.max(size - 1, 0) : offset;
+}
+
// =============================================================================
// Types
// =============================================================================
@@ -324,7 +337,7 @@ export function ContextMenu({
const menuId = useId();
// Cursor point in the trigger's local coordinate space (offset from the
- // trigger's top-left, in-flow). Stored here and written to the zero-size
+ // trigger's top-left, in-flow). Stored here and written to the cursor
// anchor element so the menu is positioned relative to the trigger context
// — it scrolls with the content instead of sitting at a fixed viewport point.
const positionRef = useRef({x: 0, y: 0});
@@ -520,18 +533,21 @@ export function ContextMenu({
[listNavKeyDown, closeMenu, typeahead, ownsEvent],
);
- // Place the zero-size cursor anchor at a point in the trigger's local
+ // Place the 1px cursor anchor at a point in the trigger's local
// coordinate space and open the menu. Positioning the anchor inside the
// trigger (rather than storing viewport coordinates on the menu itself) is
// what makes the menu context-relative: it scrolls with the content and the
// browser auto-flips it against the viewport edges via CSS anchor positioning.
const openAtLocalPoint = useCallback(
(localX: number, localY: number, focusEl: HTMLElement | null) => {
- positionRef.current = {x: localX, y: localY};
+ const rect = triggerRef.current?.getBoundingClientRect();
+ const x = rect ? keepAnchorInside(localX, rect.width) : localX;
+ const y = rect ? keepAnchorInside(localY, rect.height) : localY;
+ positionRef.current = {x, y};
const anchorEl = cursorAnchorRef.current;
if (anchorEl) {
- anchorEl.style.left = `${localX}px`;
- anchorEl.style.top = `${localY}px`;
+ anchorEl.style.left = `${x}px`;
+ anchorEl.style.top = `${y}px`;
}
// Remember the element focused before opening so we can restore it on
// close (Escape or outside-click), instead of dropping focus to <body>.
diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuCursorAnchor.a11y.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuCursorAnchor.a11y.browser.spec.ts
new file mode 100644
index 0000000000..605dabbb51
--- /dev/null
+++ b/packages/core/src/ContextMenu/__tests__/ContextMenuCursorAnchor.a11y.browser.spec.ts
@@ -0,0 +1,153 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ContextMenuCursorAnchor.a11y.browser.spec.ts
+ * @input The built "Inside a scroll container" ContextMenu story and real
+ * Chromium/WebKit layout and paint
+ * @output Browser evidence that the menu paints at its cursor anchor inside a
+ * scroll container, hides while the container clips that anchor, and that
+ * the anchor adds no scrollable overflow
+ * @position Cross-browser proof; jsdom has no layout, anchor positioning or
+ * paint.
+ *
+ * The menu is anchored to a box at the pointer. The initial
+ * `position-visibility: anchors-visible` hides an anchored box whose anchor
+ * is clipped, and WebKit counts an empty anchor box inside a scroll container
+ * as clipped. Whether the menu painted is read from pixels: WebKit still
+ * hit-tests, and reports as visible, a box that rule hides.
+ */
+
+import {expect, test, type Locator, type Page} from '@playwright/test';
+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';
+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();
+});
+
+/** Mounts the story with the trigger scrolled fully into the box. */
+async function mount(
+ page: Page,
+): Promise<{trigger: Locator; scroller: Locator}> {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-contextmenu--in-scroll-container&viewMode=story`,
+ );
+ await holdMotionStill(page);
+ const scroller = page.getByTestId('context-menu-scroller');
+ // The trigger is the box's last child: at the end of the scroll its bottom
+ // edge is the box's bottom edge.
+ await scroller.evaluate(el => {
+ el.scrollTop = el.scrollHeight;
+ });
+ return {trigger: page.getByText('Right-click this area'), scroller};
+}
+
+/** Right-clicks the trigger 40px in and 30px down; returns that point. */
+async function rightClick(
+ page: Page,
+ trigger: Locator,
+): Promise<{x: number; y: number}> {
+ const box = await trigger.boundingBox();
+ const point = {
+ x: Math.round(box?.x ?? 0) + 40,
+ y: Math.round(box?.y ?? 0) + 30,
+ };
+ await page.mouse.click(point.x, point.y, {button: 'right'});
+ return point;
+}
+
+/** Whether the open menu is on screen: hiding it must change the pixels. */
+async function menuPainted(page: Page): Promise<boolean> {
+ const layer = page.locator('[popover]:has(> [role="menu"])');
+ const clip = await layer.boundingBox();
+ if (clip == null) {
+ return false;
+ }
+ const shown = await page.screenshot({clip});
+ await layer.evaluate(el => {
+ el.style.visibility = 'hidden';
+ });
+ const hidden = await page.screenshot({clip});
+ await layer.evaluate(el => {
+ el.style.visibility = '';
+ });
+ return !shown.equals(hidden);
+}
+
+test('a right-click inside a scroll container paints the menu at the pointer', async ({
+ page,
+}) => {
+ const {trigger} = await mount(page);
+ const point = await rightClick(page, trigger);
+ await expect(page.getByRole('menu')).toBeVisible();
+ await expect.poll(async () => menuPainted(page)).toBe(true);
+
+ const anchor = await page
+ .locator('span[aria-hidden="true"][style*="anchor-name"]')
+ .boundingBox();
+ // The anchor owns a box, so WebKit does not count it as clipped.
+ expect(anchor).toMatchObject({width: 1, height: 1});
+ expect(anchor?.x).toBeCloseTo(point.x, 0);
+ expect(anchor?.y).toBeCloseTo(point.y, 0);
+});
+
+test('the menu hides while the box scrolls its anchor out of view, and returns with it', async ({
+ page,
+}) => {
+ const {trigger, scroller} = await mount(page);
+ await rightClick(page, trigger);
+ await expect(page.getByRole('menu')).toBeVisible();
+ await expect.poll(async () => menuPainted(page)).toBe(true);
+
+ await scroller.evaluate(el => {
+ el.scrollTop -= el.clientHeight;
+ });
+ await expect(page.getByRole('menu')).toBeAttached();
+ await expect.poll(async () => menuPainted(page)).toBe(false);
+
+ await scroller.evaluate(el => {
+ el.scrollTop = el.scrollHeight;
+ });
+ await expect.poll(async () => menuPainted(page)).toBe(true);
+});
+
+test('a keyboard open on the bottom edge paints and adds no scrollable overflow', async ({
+ page,
+}) => {
+ const {trigger, scroller} = await mount(page);
+ const scrollHeight = await scroller.evaluate(el => el.scrollHeight);
+ // Several browsers report Shift+F10 as a contextmenu at (0, 0), which
+ // anchors the menu to the trigger's bottom edge, here the box's own edge.
+ await trigger.evaluate(el => {
+ el.dispatchEvent(
+ new MouseEvent('contextmenu', {
+ bubbles: true,
+ cancelable: true,
+ clientX: 0,
+ clientY: 0,
+ detail: 0,
+ }),
+ );
+ });
+ await expect(page.getByRole('menu')).toBeVisible();
+ const anchor = await page
+ .locator('span[aria-hidden="true"][style*="anchor-name"]')
+ .boundingBox();
+ const area = await trigger.boundingBox();
+ expect((anchor?.y ?? 0) + (anchor?.height ?? 0)).toBeCloseTo(
+ (area?.y ?? 0) + (area?.height ?? 0),
+ 0,
+ );
+ await expect.poll(async () => menuPainted(page)).toBe(true);
+ expect(await scroller.evaluate(el => el.scrollHeight)).toBe(scrollHeight);
+});