Skip to content

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

TypeScript

fix(useMenuPress): hit-test in the menu's own shadow root (#7914)

Cindy Zhang97dda3cb474a
diff --git a/.changeset/menu-press-shadow-root.md b/.changeset/menu-press-shadow-root.md
new file mode 100644
index 0000000000..a4a06913c3
--- /dev/null
+++ b/.changeset/menu-press-shadow-root.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Selector, DropdownMenu and ContextMenu: clicking an option inside a shadow root (open, closed or nested) selects it. The menus used to read the document's view of the click, which names the shadow host, so the click closed the menu without selecting anything.
+
+@cixzhang
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 690c903092..9c64d57fa0 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1459,6 +1459,16 @@ jobs:
--project chromium \
--output menu-header-footer-output
+ # A menu inside a shadow root must act on the row under a released
+ # pointer; at the document level a real engine resolves that point to
+ # the shadow host, which jsdom cannot show.
+ - name: Run menu press shadow-root contract
+ run: |
+ pnpm exec playwright test \
+ packages/core/src/hooks/__tests__/MenuPressShadowRoot.a11y.chromium.spec.ts \
+ --project chromium \
+ --output menu-press-shadow-root-output
+
# A sub-menu with a header or footer is a modal dialog beside the root's
# menu, outside every role="menu" element. Its Tab order, a header radio
# group the browser moves focus in after the pointer leaves, the
diff --git a/apps/storybook/stories/MenuPressShadowRootA11y.stories.tsx b/apps/storybook/stories/MenuPressShadowRootA11y.stories.tsx
new file mode 100644
index 0000000000..8ecc849c68
--- /dev/null
+++ b/apps/storybook/stories/MenuPressShadowRootA11y.stories.tsx
@@ -0,0 +1,73 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file MenuPressShadowRootA11y.stories.tsx
+ * @input Uses Selector from core, React DOM's createRoot, an open shadow root
+ * @output The fixture the menu-press shadow-root spec drives in a real
+ * browser: a Selector rendered inside an open shadow root, with its value
+ * printed outside it.
+ * @position The reproduction path for
+ * `packages/core/src/hooks/__tests__/MenuPressShadowRoot.a11y.chromium.spec.ts`.
+ *
+ * Inside a shadow root `document.elementFromPoint` answers with the shadow
+ * host, so a menu that hit-tests through the document never finds the row
+ * under a released pointer. Unstyled on purpose: the hit test, not the paint,
+ * is under test.
+ *
+ * SYNC: The spec navigates to this story id by name.
+ */
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {useEffect, useRef, useState} from 'react';
+import {createRoot} from 'react-dom/client';
+import {Selector} from '@astryxdesign/core/Selector';
+
+const meta: Meta = {
+ title: 'a11y/Menu press in a shadow root',
+ tags: ['no-visual'],
+};
+
+export default meta;
+
+function ShadowSelector({onChange}: {onChange: (value: string) => void}) {
+ const [value, setValue] = useState('');
+ return (
+ <Selector
+ label="Fruit"
+ options={['Apple', 'Banana', 'Orange']}
+ value={value}
+ onChange={next => {
+ setValue(next);
+ onChange(next);
+ }}
+ />
+ );
+}
+
+export const SelectorInShadowRoot: StoryObj = {
+ render: function SelectorInShadowRootStory() {
+ const hostRef = useRef<HTMLDivElement>(null);
+ const [value, setValue] = useState('');
+ useEffect(() => {
+ const host = hostRef.current;
+ if (host == null) {
+ return;
+ }
+ const shadow = host.shadowRoot ?? host.attachShadow({mode: 'open'});
+ const container = document.createElement('div');
+ shadow.append(container);
+ const root = createRoot(container);
+ root.render(<ShadowSelector onChange={setValue} />);
+ return () => {
+ root.unmount();
+ container.remove();
+ };
+ }, []);
+ return (
+ <>
+ <div ref={hostRef} data-testid="shadow-host" />
+ <output data-testid="selected-value">{value}</output>
+ </>
+ );
+ },
+};
diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx
index ecf94122a4..2015dc90c3 100644
--- a/packages/core/src/ContextMenu/ContextMenu.test.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx
@@ -346,6 +346,40 @@ describe('ContextMenu', () => {
expect(HTMLElement.prototype.hidePopover).toHaveBeenCalled();
});
+ it.each(['open', 'closed', 'nested'] as const)(
+ 'judges presses once inside a %s shadow root',
+ mode => {
+ const host = document.createElement('div');
+ document.body.append(host);
+ let root = host.attachShadow({mode: mode === 'open' ? 'open' : 'closed'});
+ if (mode === 'nested') {
+ const innerHost = document.createElement('div');
+ root.append(innerHost);
+ root = innerHost.attachShadow({mode: 'closed'});
+ }
+ const container = document.createElement('div');
+ root.append(container);
+ try {
+ render(
+ <ContextMenu items={[{label: 'Item 1'}]}>
+ <div>Right-click me</div>
+ </ContextMenu>,
+ {container},
+ );
+ fireEvent.contextMenu(container.querySelector('div div')!);
+ // At the document a press on the menu is retargeted to a shadow host.
+ const item = container.querySelector('[role="menuitem"]')!;
+ fireEvent.mouseDown(item, {composed: true});
+ expect(HTMLElement.prototype.hidePopover).not.toHaveBeenCalled();
+ // A press on the host itself is outside the menu.
+ fireEvent.mouseDown(host);
+ expect(HTMLElement.prototype.hidePopover).toHaveBeenCalled();
+ } finally {
+ host.remove();
+ }
+ },
+ );
+
it('closes the menu when Tab is pressed inside it (APG menu pattern)', () => {
render(
<ContextMenu items={[{label: 'Item 1'}]}>
diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx
index e35fe9134e..1fc573da53 100644
--- a/packages/core/src/ContextMenu/ContextMenu.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.tsx
@@ -466,15 +466,27 @@ export function ContextMenu({
if (!isOpen || usesBottomSheet) {
return;
}
- const handleClickOutside = (e: MouseEvent) => {
+ // Inside a shadow root, even a closed or nested one, the document sees a
+ // press on the menu as a press on an outer shadow host, so the menu's own
+ // tree judges its presses first and the document skips those.
+ const tree = listRef.current?.getRootNode();
+ const shadow = tree instanceof ShadowRoot ? tree : null;
+ const judged = new WeakSet<Event>();
+ const handleClickOutside = (e: Event) => {
const menu = listRef.current;
+ if (judged.has(e)) {
+ return;
+ }
+ judged.add(e);
if (menu && !menu.contains(e.target as Node)) {
closeMenu();
}
};
document.addEventListener('mousedown', handleClickOutside);
+ shadow?.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
+ shadow?.removeEventListener('mousedown', handleClickOutside);
};
}, [isOpen, closeMenu, listRef, usesBottomSheet]);
diff --git a/packages/core/src/hooks/__tests__/MenuPressShadowRoot.a11y.chromium.spec.ts b/packages/core/src/hooks/__tests__/MenuPressShadowRoot.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..b7eff77e35
--- /dev/null
+++ b/packages/core/src/hooks/__tests__/MenuPressShadowRoot.a11y.chromium.spec.ts
@@ -0,0 +1,50 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file MenuPressShadowRoot.a11y.chromium.spec.ts
+ * @input The `a11y/Menu press in a shadow root` story in a built Storybook and
+ * real mouse input.
+ * @output Real-engine proof that a menu rendered inside a shadow root acts on
+ * the row under a released pointer (module:DropdownMenu/useMenuPress FR1).
+ * @position Run with `pnpm test:a11y-contract`. Only a real engine resolves a
+ * point inside a shadow root to the shadow host at the document level.
+ */
+
+import {expect, test} 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();
+});
+
+const STORY = 'a11y-menu-press-in-a-shadow-root--selector-in-shadow-root';
+
+test('a mouse click on an option inside a shadow root selects it', async ({
+ page,
+}) => {
+ await page.goto(`${storybook.origin}/iframe.html?id=${STORY}&viewMode=story`);
+ // Playwright's role locators pierce open shadow roots.
+ await page.getByRole('combobox', {name: 'Fruit'}).click();
+ const option = page.getByRole('option', {name: 'Banana'});
+ await expect(option).toBeVisible();
+ const box = await option.boundingBox();
+ if (box == null) {
+ throw new Error('the Banana option has no layout box');
+ }
+
+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
+
+ await expect(page.getByTestId('selected-value')).toHaveText('Banana');
+});
diff --git a/packages/core/src/hooks/useMenuPress.test.tsx b/packages/core/src/hooks/useMenuPress.test.tsx
index 0d5646c72c..f8e6571ff8 100644
--- a/packages/core/src/hooks/useMenuPress.test.tsx
+++ b/packages/core/src/hooks/useMenuPress.test.tsx
@@ -11,7 +11,7 @@
*/
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-import {act, fireEvent, render, screen} from '@testing-library/react';
+import {act, fireEvent, render, screen, within} from '@testing-library/react';
import {useRef, useState} from 'react';
import {
MENU_PRESS_AUTOSCROLL_ZONE_PX,
@@ -145,6 +145,32 @@ describe('useMenuPress — tracking inside the menu', () => {
expect(onSelect).toHaveBeenCalledTimes(1);
});
+ it('hit-tests in the shadow root that holds the menu, not the document', () => {
+ const host = document.createElement('div');
+ document.body.append(host);
+ const shadow = host.attachShadow({mode: 'open'});
+ const container = document.createElement('div');
+ shadow.append(container);
+ const onSelect = vi.fn();
+ render(<Harness onSelect={onSelect} />, {container});
+ const inShadow = (label: string) =>
+ within(container).getByRole('menuitem', {name: label});
+ // As in a browser: the document answers with the shadow host; only the
+ // shadow root knows the row under the point.
+ Object.assign(document, {elementFromPoint: () => host});
+ Object.assign(shadow, {elementFromPoint: () => inShadow('C')});
+ try {
+ const events = {...mouse(), composed: true, bubbles: true};
+ fireEvent.pointerDown(inShadow('A'), events);
+ fireEvent.pointerUp(inShadow('A'), events);
+ expect(onSelect).toHaveBeenCalledWith('C');
+ expect(onSelect).toHaveBeenCalledTimes(1);
+ } finally {
+ delete (document as {elementFromPoint?: unknown}).elementFromPoint;
+ host.remove();
+ }
+ });
+
it('moves the highlight as focus with preventScroll', () => {
render(<Harness />);
const b = row('B');
diff --git a/packages/core/src/hooks/useMenuPress.ts b/packages/core/src/hooks/useMenuPress.ts
index 91375393b5..695810656b 100644
--- a/packages/core/src/hooks/useMenuPress.ts
+++ b/packages/core/src/hooks/useMenuPress.ts
@@ -209,8 +209,8 @@ export interface UseMenuPressOptions {
getScroller?: () => HTMLElement | null;
/**
* Resolve the element under a viewport point. Defaults to
- * `document.elementFromPoint`, falling back to the event target where the
- * document lacks it (jsdom). A test seam.
+ * `elementFromPoint` on the menu's own document or shadow root, falling back
+ * to the event target where the document lacks it (jsdom). A test seam.
*/
hitTest?: (x: number, y: number) => Element | null;
/** @default 500 */
@@ -364,7 +364,16 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
if (hitTest != null) {
element = hitTest(event.clientX, event.clientY);
} else if (typeof doc.elementFromPoint === 'function') {
- element = doc.elementFromPoint(event.clientX, event.clientY);
+ // Hit-test in the menu's own tree: inside a shadow root the document
+ // answers with the shadow host, never the row under the pointer.
+ const tree = menu?.getRootNode();
+ const scope: Pick<Document, 'elementFromPoint'> =
+ tree != null &&
+ tree !== doc &&
+ typeof (tree as ShadowRoot).elementFromPoint === 'function'
+ ? (tree as ShadowRoot)
+ : doc;
+ element = scope.elementFromPoint(event.clientX, event.clientY);
} else {
element = event.target instanceof Element ? event.target : null;
}