An open source design system that's fully customizable and agent ready
TypeScript
fix(ContextMenu): the long press that opens the menu no longer closes it (#7308)
Christopher Chedeaucaa1f04fe244
diff --git a/.changeset/context-menu-long-press-lift.md b/.changeset/context-menu-long-press-lift.mdnew file mode 100644index 0000000000..fe735d81eb--- /dev/null+++ b/.changeset/context-menu-long-press-lift.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A ContextMenu opened by a finger's long press stays open as the finger lifts: the compatibility `mousedown` the browser sends for that press as it lifts no longer reads as a press outside. Every other press outside the menu closes it, or leaves it open, as before.++@vjeuxdiff --git a/apps/storybook/stories/MenuPressShadowRootA11y.stories.tsx b/apps/storybook/stories/MenuPressShadowRootA11y.stories.tsxindex 8ecc849c68..d161e31c11 100644--- a/apps/storybook/stories/MenuPressShadowRootA11y.stories.tsx+++ b/apps/storybook/stories/MenuPressShadowRootA11y.stories.tsx@@ -2,10 +2,12 @@/*** @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+ * @input Uses Selector and ContextMenu from core, React DOM's createRoot, an+ * open shadow root+ * @output The fixtures 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.+ * printed outside it, and a ContextMenu inside one whose host leaves a+ * margin of its own around it, with the last item picked printed outside.* @position The reproduction path for* `packages/core/src/hooks/__tests__/MenuPressShadowRoot.a11y.chromium.spec.ts`.*@@ -21,6 +23,7 @@ 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';+import {ContextMenu} from '@astryxdesign/core/ContextMenu';const meta: Meta = {title: 'a11y/Menu press in a shadow root',@@ -71,3 +74,46 @@ export const SelectorInShadowRoot: StoryObj = {);},};++function ShadowContextMenu({onPick}: {onPick: (label: string) => void}) {+ return (+ <ContextMenu+ items={[+ {label: 'Cut', onClick: () => onPick('Cut')},+ {label: 'Copy', onClick: () => onPick('Copy')},+ ]}>+ <div style={{padding: 24, border: '1px dashed'}}>+ Right-click inside the shadow root+ </div>+ </ContextMenu>+ );+}++export const ContextMenuInShadowRoot: StoryObj = {+ render: function ContextMenuInShadowRootStory() {+ const hostRef = useRef<HTMLDivElement>(null);+ const [picked, setPicked] = 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(<ShadowContextMenu onPick={setPicked} />);+ return () => {+ root.unmount();+ container.remove();+ };+ }, []);+ return (+ <>+ {/* The host's own padding is a press on the host, outside its tree. */}+ <div ref={hostRef} data-testid="shadow-host" style={{padding: 48}} />+ <output data-testid="picked-item">{picked}</output>+ </>+ );+ },+};diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.mdindex 6383127499..e75ca7ecc0 100644--- a/docs/architecture/layer-runtime.md+++ b/docs/architecture/layer-runtime.md@@ -308,7 +308,8 @@ independent:- auto popovers use native light dismiss;- native dialogs handle backdrop clicks locally;-- ContextMenu uses a local outside `mousedown` listener;+- ContextMenu uses a local outside `mousedown` listener, which skips the+ compatibility mouse events of the finger press that opened the menu;- Tooltip and HoverCard use hover/focus loss plus a touch-only outside listener;- sheets own scrim and swipe behavior; and- dropdown submenus encode their root-close relationship locally throughdiff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsxindex 5cf78ae48a..059b2bf9d4 100644--- a/packages/core/src/ContextMenu/ContextMenu.test.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx@@ -11,7 +11,15 @@import {useRef, useState} from 'react';import {createPortal} from 'react-dom';import {describe, it, expect, vi, beforeAll, beforeEach} from 'vitest';-import {render, screen, fireEvent, act, waitFor} from '@testing-library/react';+import {+ render,+ screen,+ fireEvent,+ act,+ waitFor,+ cleanup,+ createEvent,+} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {readFileSync} from 'node:fs';import {ContextMenu} from './ContextMenu';@@ -1403,3 +1411,145 @@ describe('ContextMenu inline trigger (triggerAs)', () => {expect(screen.getByTestId('area').tagName).toBe('DIV');});});++describe('ContextMenu outside dismissal', () => {+ const finger = (pointerId: number) => ({pointerType: 'touch', pointerId});++ // Holds a finger on the trigger until the long-press opens the menu. Only+ // the long-press delay is faked.+ function longPress(trigger: HTMLElement, pointerId: number) {+ vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout']});+ try {+ fireEvent.pointerDown(trigger, finger(pointerId));+ fireEvent.touchStart(trigger, {touches: [{clientX: 20, clientY: 20}]});+ act(() => {+ vi.advanceTimersByTime(500);+ });+ } finally {+ vi.useRealTimers();+ }+ }++ // What a browser sends after a touch: the lift, then compatibility mouse+ // events aimed at the element the finger held.+ function lift(target: HTMLElement, pointerId: number) {+ fireEvent.pointerUp(target, finger(pointerId));+ fireEvent.touchEnd(target);+ fireEvent.mouseDown(target);+ fireEvent.mouseUp(target);+ fireEvent.click(target);+ }++ function renderMenu(onOpenChange: (isOpen: boolean) => void) {+ render(+ <>+ <ContextMenu+ items={[{label: 'Cut'}, {label: 'Copy'}]}+ data-testid="ctx"+ onOpenChange={onOpenChange}>+ <div>Long-press me</div>+ </ContextMenu>+ <button type="button">Outside</button>+ </>,+ );+ return {+ trigger: screen.getByTestId('ctx'),+ outside: screen.getByRole('button', {name: 'Outside'}),+ };+ }++ it('the long press that opened the menu does not close it, mid-hold or as it lifts; the next press outside does', () => {+ const onOpenChange = vi.fn<(isOpen: boolean) => void>();+ const {trigger, outside} = renderMenu(onOpenChange);+ longPress(trigger, 1);+ expect(onOpenChange).toHaveBeenLastCalledWith(true);+ // iOS: a compatibility mousedown while the finger is still down.+ fireEvent.mouseDown(trigger);+ expect(onOpenChange).toHaveBeenLastCalledWith(true);+ // Chromium: the compatibility events that follow the lift.+ lift(trigger, 1);+ expect(onOpenChange).not.toHaveBeenCalledWith(false);+ // A new press is a new gesture: a mouse press outside closes the menu.+ fireEvent.pointerDown(outside, {pointerType: 'mouse', pointerId: 9});+ fireEvent.mouseDown(outside);+ expect(onOpenChange).toHaveBeenLastCalledWith(false);+ });++ it('a finger long press that opens the menu through a pointer contextmenu (Chromium) does not close it as it lifts', () => {+ const onOpenChange = vi.fn<(isOpen: boolean) => void>();+ const {trigger, outside} = renderMenu(onOpenChange);+ fireEvent.pointerDown(trigger, finger(8));+ const contextmenu = createEvent.contextMenu(trigger, {+ clientX: 20,+ clientY: 15,+ detail: 1,+ });+ Object.defineProperty(contextmenu, 'pointerType', {value: 'touch'});+ fireEvent(trigger, contextmenu);+ expect(onOpenChange).toHaveBeenLastCalledWith(true);+ lift(trigger, 8);+ expect(onOpenChange).not.toHaveBeenCalledWith(false);+ // A right-click is not a finger: its gesture's next mousedown, outside,+ // closes the menu.+ fireEvent.pointerDown(trigger, {pointerType: 'mouse', pointerId: 1});+ fireEvent.contextMenu(trigger, {clientX: 20, clientY: 15, detail: 1});+ fireEvent.mouseDown(outside);+ expect(onOpenChange).toHaveBeenLastCalledWith(false);+ });++ it('a long press that moves the open menu keeps it open as it lifts', () => {+ const onOpenChange = vi.fn<(isOpen: boolean) => void>();+ const {trigger} = renderMenu(onOpenChange);+ fireEvent.contextMenu(trigger, {clientX: 50, clientY: 15, detail: 1});+ expect(onOpenChange).toHaveBeenLastCalledWith(true);+ longPress(trigger, 2);+ lift(trigger, 2);+ expect(onOpenChange).not.toHaveBeenCalledWith(false);+ });++ it('a tap outside closes the menu through its compatibility mousedown; a scroll that starts outside leaves it open', () => {+ const onOpenChange = vi.fn<(isOpen: boolean) => void>();+ const {trigger, outside} = renderMenu(onOpenChange);+ fireEvent.contextMenu(trigger, {clientX: 50, clientY: 15, detail: 1});+ // The browser takes this finger for a scroll: no compatibility events.+ fireEvent.pointerDown(outside, finger(3));+ fireEvent.pointerCancel(outside, finger(3));+ expect(onOpenChange).toHaveBeenLastCalledWith(true);+ fireEvent.pointerDown(outside, finger(4));+ lift(outside, 4);+ expect(onOpenChange).toHaveBeenLastCalledWith(false);+ });++ it('a mouse press or a pen press outside closes the menu at the press', () => {+ for (const pointerType of ['mouse', 'pen']) {+ const onOpenChange = vi.fn<(isOpen: boolean) => void>();+ const {trigger, outside} = renderMenu(onOpenChange);+ fireEvent.contextMenu(trigger, {clientX: 50, clientY: 15, detail: 1});+ fireEvent.pointerDown(outside, {pointerType, pointerId: 7});+ fireEvent.mouseDown(outside);+ expect(onOpenChange).toHaveBeenLastCalledWith(false);+ cleanup();+ }+ });++ it('presses that send no mousedown leave the menu open, as before: a cancelled pointerdown, a finger drag, a second finger', () => {+ const onOpenChange = vi.fn<(isOpen: boolean) => void>();+ const {trigger, outside} = renderMenu(onOpenChange);+ fireEvent.contextMenu(trigger, {clientX: 50, clientY: 15, detail: 1});+ // A control that cancels its pointerdown (a NumberInput stepper, a+ // resize handle): the browser sends no mousedown.+ fireEvent.pointerDown(outside, {pointerType: 'mouse', pointerId: 1});+ fireEvent.pointerUp(outside, {pointerType: 'mouse', pointerId: 1});+ // A finger drag on a surface that does not pan (a Slider), lifted.+ fireEvent.pointerDown(outside, finger(5));+ fireEvent.pointerMove(outside, finger(5));+ fireEvent.pointerUp(outside, finger(5));+ // A second finger's tap.+ fireEvent.pointerDown(outside, finger(6));+ fireEvent.pointerDown(outside, finger(7));+ fireEvent.pointerUp(outside, finger(7));+ fireEvent.pointerCancel(outside, finger(6));+ expect(onOpenChange).toHaveBeenLastCalledWith(true);+ expect(onOpenChange).not.toHaveBeenCalledWith(false);+ });+});diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsxindex 1fc573da53..2e257bb130 100644--- a/packages/core/src/ContextMenu/ContextMenu.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.tsx@@ -52,6 +52,7 @@ import {Icon} from '../Icon';import {useLayer} from '../Layer/useLayer';import {LayerDepthProvider} from '../Layer/LayerDepthContext';import {useLayerDismissal} from '../Layer/useLayerDismissal';+import {currentGesture} from '../Layer/gestureCounter';import {MenuBottomSheetActionList} from '../DropdownMenu/MenuBottomSheetActionList';import {renderDropdownItems} from '../DropdownMenu/renderDropdownItems';import {@@ -354,6 +355,11 @@ export function ContextMenu({// Element focused before the menu opened, restored when it closes so focus// does not fall to <body> after Escape or outside-click dismissal.const triggerFocusRef = useRef<HTMLElement | null>(null);+ // The gesture of the finger press that opened the menu (`Layer/+ // gestureCounter`), null when a mouse or the keyboard opened it: the+ // browser's compatibility mouse events for that same press are not presses+ // outside.+ const openingGestureRef = useRef<number | null>(null);const [isOpen, setIsOpen] = useState(false);const [submenuPath, setSubmenuPath] = useState<ContextMenuItemData[]>([]);@@ -461,7 +467,10 @@ export function ContextMenu({// Dismiss on any click outside the menu. We use popover="manual" (not// "auto") because the native light-dismiss treats the mouseup from the// opening right-click as a dismiss event. Handling it ourselves via- // mousedown avoids that race.+ // mousedown avoids that race. A touch's compatibility mousedown for the+ // press that opened the menu (sent mid-hold by iOS, or as a long press+ // lifts by Chromium) belongs to that press's gesture, so it is not read as+ // a press outside; any later press is a new gesture and closes as before.useEffect(() => {if (!isOpen || usesBottomSheet) {return;@@ -478,6 +487,9 @@ export function ContextMenu({return;}judged.add(e);+ if (currentGesture() === openingGestureRef.current) {+ return;+ }if (menu && !menu.contains(e.target as Node)) {closeMenu();}@@ -589,6 +601,14 @@ export function ContextMenu({const localX = isKeyboardInvoked || !rect ? 0 : e.clientX - rect.left;const localY =isKeyboardInvoked || !rect ? (rect?.height ?? 0) : e.clientY - rect.top;+ // A finger's long press reaches here as a pointer `contextmenu` where+ // the browser sends one (Chromium); its compatibility mousedown then+ // belongs to the opening press. A mouse or the keyboard opens without+ // one, so every later mousedown is a press outside.+ openingGestureRef.current =+ (e.nativeEvent as Partial<PointerEvent>).pointerType === 'touch'+ ? currentGesture()+ : null;openAtLocalPoint(localX, localY, e.currentTarget as HTMLElement);},[isDisabled, openAtLocalPoint, getAnchorBaseRect],@@ -610,6 +630,9 @@ export function ContextMenu({onLongPress: useCallback((point: {x: number; y: number}) => {const rect = getAnchorBaseRect();+ // The finger is still down: the compatibility mousedown iOS sends+ // mid-hold, or Chromium as it lifts, belongs to this press.+ openingGestureRef.current = currentGesture();openAtLocalPoint(rect ? point.x - rect.left : point.x,rect ? point.y - rect.top : point.y,diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.a11y.chromium.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.a11y.chromium.spec.tsnew file mode 100644index 0000000000..29102ddf41--- /dev/null+++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.a11y.chromium.spec.ts@@ -0,0 +1,117 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ContextMenuLongPress.a11y.chromium.spec.ts+ * @input The `Core/ContextMenu` Default story in a built Storybook and CDP+ * touch input.+ * @output Real-engine proof that the long press that opens a context menu+ * does not close it as the finger lifts, and that a tap outside still does.+ * @position Run with `pnpm test:a11y-contract`; jsdom cannot produce the+ * compatibility mouse events a real browser sends after a touch.+ */++import {expect, test, type CDPSession, 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();+});++const STORY = 'core-contextmenu--default';++async function touchCdp(page: Page): Promise<CDPSession> {+ const cdp = await page.context().newCDPSession(page);+ await cdp.send('Emulation.setTouchEmulationEnabled', {+ enabled: true,+ maxTouchPoints: 1,+ });+ return cdp;+}++async function triggerCenter(page: Page): Promise<{x: number; y: number}> {+ const box = await page.getByText('Right-click this area').boundingBox();+ if (box == null) {+ throw new Error('the trigger area has no rendered bounds');+ }+ return {x: box.x + box.width / 2, y: box.y + box.height / 2};+}++/**+ * Resolves once the browser has delivered the `click` that follows a touch+ * (the last of its compatibility mouse events) and two frames have run, so+ * anything that event closes has closed.+ */+async function armCompatClick(page: Page): Promise<void> {+ await page.evaluate(() => {+ const w = window as unknown as {__compatClick?: Promise<void>};+ w.__compatClick = new Promise(resolve => {+ document.addEventListener(+ 'click',+ () =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ {once: true, capture: true},+ );+ });+ });+}++async function compatClickDelivered(page: Page): Promise<void> {+ await page.evaluate(+ async () =>+ (window as unknown as {__compatClick?: Promise<void>}).__compatClick,+ );+}++test('the long press that opens the menu leaves it open as the finger lifts', async ({+ page,+}) => {+ await page.goto(`${storybook.origin}/iframe.html?id=${STORY}&viewMode=story`);+ const cdp = await touchCdp(page);+ const center = await triggerCenter(page);+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchStart',+ touchPoints: [{x: center.x, y: center.y, id: 1}],+ });+ const menu = page.getByRole('menu');+ await expect(menu).toBeVisible({timeout: 2000});+ await armCompatClick(page);+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchEnd',+ touchPoints: [],+ });+ await compatClickDelivered(page);+ await expect(menu).toBeVisible();++ // A tap outside still closes it.+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchStart',+ touchPoints: [{x: 5, y: 5, id: 2}],+ });+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchEnd',+ touchPoints: [],+ });+ await expect(menu).toBeHidden();+});++test('a mouse press outside closes a right-click menu', async ({page}) => {+ await page.goto(`${storybook.origin}/iframe.html?id=${STORY}&viewMode=story`);+ const center = await triggerCenter(page);+ await page.mouse.click(center.x, center.y, {button: 'right'});+ const menu = page.getByRole('menu');+ await expect(menu).toBeVisible();+ await page.mouse.click(5, 5);+ await expect(menu).toBeHidden();+});diff --git a/packages/core/src/hooks/__tests__/MenuPressShadowRoot.a11y.chromium.spec.ts b/packages/core/src/hooks/__tests__/MenuPressShadowRoot.a11y.chromium.spec.tsindex c53aa33408..cb4a5ea3e0 100644--- a/packages/core/src/hooks/__tests__/MenuPressShadowRoot.a11y.chromium.spec.ts+++ b/packages/core/src/hooks/__tests__/MenuPressShadowRoot.a11y.chromium.spec.ts@@ -3,15 +3,17 @@/*** @file MenuPressShadowRoot.a11y.chromium.spec.ts- * @input The `a11y/Menu press in a shadow root` story in a built Storybook and- * real mouse input.+ * @input The `a11y/Menu press in a shadow root` stories in a built Storybook,+ * real mouse input, and CDP touch 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).+ * the row under a released pointer (module:DropdownMenu/useMenuPress FR1),+ * and that a ContextMenu there tells a press on its own rows from a press+ * outside it, a mouse's at once and a finger's on its lift.* @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 {expect, test, type Page} from '@playwright/test';import {DEFAULT_STORYBOOK_DIR,serveStorybook,@@ -49,3 +51,94 @@ test('a mouse click on an option inside a shadow root selects it', async ({await expect(page.getByTestId('selected-value')).toHaveText('Banana');});++const CONTEXT_STORY =+ 'a11y-menu-press-in-a-shadow-root--context-menu-in-shadow-root';++/** The center of a box, and a point in the host's own padding. */+async function points(page: Page) {+ const trigger = await page+ .getByText('Right-click inside the shadow root')+ .boundingBox();+ const host = await page.getByTestId('shadow-host').boundingBox();+ if (trigger == null || host == null) {+ throw new Error('the trigger or its shadow host has no layout box');+ }+ return {+ trigger: {+ x: trigger.x + trigger.width / 2,+ y: trigger.y + trigger.height / 2,+ },+ hostPadding: {x: host.x + 8, y: host.y + 8},+ };+}++test('a ContextMenu inside a shadow root picks a clicked item, and a press on its host closes it', async ({+ page,+}) => {+ await page.goto(+ `${storybook.origin}/iframe.html?id=${CONTEXT_STORY}&viewMode=story`,+ );+ const {trigger, hostPadding} = await points(page);+ const menu = page.getByRole('menu');++ // At the document, both presses land on the shadow host.+ await page.mouse.click(trigger.x, trigger.y, {button: 'right'});+ await expect(menu).toBeVisible();+ const copy = await page.getByRole('menuitem', {name: 'Copy'}).boundingBox();+ if (copy == null) {+ throw new Error('the Copy item has no layout box');+ }+ await page.mouse.click(copy.x + copy.width / 2, copy.y + copy.height / 2);+ await expect(page.getByTestId('picked-item')).toHaveText('Copy');+ await expect(menu).toBeHidden();++ await page.mouse.click(trigger.x, trigger.y, {button: 'right'});+ await expect(menu).toBeVisible();+ await page.mouse.click(hostPadding.x, hostPadding.y);+ await expect(menu).toBeHidden();+ await expect(page.getByTestId('picked-item')).toHaveText('Copy');+});++test('a ContextMenu inside a shadow root stays open as its opening long press lifts, and a tap on its host closes it', async ({+ page,+}) => {+ await page.goto(+ `${storybook.origin}/iframe.html?id=${CONTEXT_STORY}&viewMode=story`,+ );+ const {trigger, hostPadding} = await points(page);+ const menu = page.getByRole('menu');+ const cdp = await page.context().newCDPSession(page);+ await cdp.send('Emulation.setTouchEmulationEnabled', {+ enabled: true,+ maxTouchPoints: 1,+ });++ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchStart',+ touchPoints: [{x: trigger.x, y: trigger.y, id: 1}],+ });+ await expect(menu).toBeVisible({timeout: 2000});+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchEnd',+ touchPoints: [],+ });+ // Two frames after the lift, its compatibility mouse events have landed.+ await page.evaluate(async () => {+ await new Promise<void>(resolve => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ });+ });+ await expect(menu).toBeVisible();++ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchStart',+ touchPoints: [{x: hostPadding.x, y: hostPadding.y, id: 2}],+ });+ await expect(menu).toBeVisible();+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchEnd',+ touchPoints: [],+ });+ await expect(menu).toBeHidden();+});