An open source design system that's fully customizable and agent ready
TypeScript
fix(contextmenu): touch long-press + keyboard invocation (menus-8) (#3392)
Cindy Zhang40753a701c70
diff --git a/.changeset/contextmenu-touch-keyboard.md b/.changeset/contextmenu-touch-keyboard.mdnew file mode 100644index 0000000000..308913165b--- /dev/null+++ b/.changeset/contextmenu-touch-keyboard.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] ContextMenu: can now be opened on touch (long-press) and by keyboard. A long-press (500ms, cancelled by a 10px finger move) opens the menu at the touch point — previously context menus were unreachable on iOS Safari, which never fires `contextmenu` on long-press. A keyboard-initiated `contextmenu` (Shift+F10 / the Menu key), whose coordinates are (0,0), now anchors the menu to the trigger's box instead of the viewport corner (#3343).+@cixzhangdiff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsxindex 763917bbff..2e91d488ff 100644--- a/packages/core/src/ContextMenu/ContextMenu.test.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx@@ -9,7 +9,7 @@*/import {describe, it, expect, vi, beforeEach} from 'vitest';-import {render, screen, fireEvent} from '@testing-library/react';+import {render, screen, fireEvent, act} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {ContextMenu} from './ContextMenu';import {ContextMenuItem} from './index';@@ -193,6 +193,72 @@ describe('ContextMenu', () => {);expect(screen.getByTestId('my-context-menu')).toBeInTheDocument();});++ it('opens from a keyboard-invoked contextmenu (Shift+F10 / Menu key)', () => {+ render(+ <ContextMenu items={[{label: 'Item 1'}]} data-testid="ctx">+ <div>Right-click me</div>+ </ContextMenu>,+ );+ const trigger = screen.getByTestId('ctx');+ // Anchor the trigger box so the rect fallback has a position to read.+ trigger.getBoundingClientRect = () =>+ ({+ left: 40,+ top: 10,+ bottom: 30,+ right: 100,+ width: 60,+ height: 20,+ }) as DOMRect;+ // Keyboard-initiated contextmenu: coords are (0,0) and detail is 0.+ fireEvent.contextMenu(trigger, {clientX: 0, clientY: 0, detail: 0});+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();+ });++ it('opens on touch long-press', () => {+ vi.useFakeTimers();+ try {+ render(+ <ContextMenu items={[{label: 'Item 1'}]} data-testid="ctx">+ <div>Long-press me</div>+ </ContextMenu>,+ );+ const trigger = screen.getByTestId('ctx');+ fireEvent.touchStart(trigger, {+ touches: [{clientX: 20, clientY: 20}],+ });+ // Not open until the long-press threshold elapses.+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();+ act(() => {+ vi.advanceTimersByTime(500);+ });+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });++ it('cancels the long-press when the finger moves past the threshold', () => {+ vi.useFakeTimers();+ try {+ render(+ <ContextMenu items={[{label: 'Item 1'}]} data-testid="ctx">+ <div>Long-press me</div>+ </ContextMenu>,+ );+ const trigger = screen.getByTestId('ctx');+ fireEvent.touchStart(trigger, {touches: [{clientX: 20, clientY: 20}]});+ // Move past MOVE_CANCEL_PX (10px) — treated as a scroll, not a press.+ fireEvent.touchMove(trigger, {touches: [{clientX: 20, clientY: 40}]});+ act(() => {+ vi.advanceTimersByTime(500);+ });+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });});describe('ContextMenu items', () => {diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsxindex 0e85b4c88c..621519fe9b 100644--- a/packages/core/src/ContextMenu/ContextMenu.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.tsx@@ -43,6 +43,7 @@ import {} from '../DropdownMenu/DropdownMenuContext';import {useListFocus} from '../hooks/useListFocus';import {useTypeahead} from '../hooks/useTypeahead';+import {useLongPress} from '../hooks/useLongPress';import {layerAnimations} from '../Layer/layerAnimations.stylex';import {colorVars,@@ -63,6 +64,11 @@ import type {} from '../DropdownMenu/DropdownMenu';const styles = stylex.create({+ // Trigger wrapper: suppress the iOS long-press callout/selection so the+ // long-press opens our context menu instead of the native text/callout UI.+ trigger: {+ WebkitTouchCallout: 'none',+ },menu: {boxSizing: 'border-box',display: 'flex',@@ -325,7 +331,18 @@ export function ContextMenu({return;}e.preventDefault();- positionRef.current = {x: e.clientX, y: e.clientY};+ // A keyboard-initiated contextmenu (Shift+F10 / the Menu key) fires a+ // `contextmenu` event whose coordinates are (0, 0) in several browsers.+ // Detect that and anchor the menu to the trigger's box instead, so the+ // menu is reachable without a pointer (menus-8).+ const isKeyboardInvoked =+ e.clientX === 0 && e.clientY === 0 && e.detail === 0;+ if (isKeyboardInvoked && e.currentTarget instanceof HTMLElement) {+ const rect = e.currentTarget.getBoundingClientRect();+ positionRef.current = {x: rect.left, y: rect.bottom};+ } else {+ positionRef.current = {x: e.clientX, y: e.clientY};+ }// Remember the element focused before opening so we can restore it on// close (Escape or outside-click), instead of dropping focus to <body>.triggerFocusRef.current =@@ -340,6 +357,24 @@ export function ContextMenu({[isDisabled, layer, hasAutoFocus, focusFirst],);+ // Touch long-press invocation (menus-8). iOS Safari never synthesizes a+ // `contextmenu` event on long-press, so a context menu is otherwise+ // unreachable on touch. Open the menu at the touch point once the press is+ // held long enough (see useLongPress for timer/move-cancel/cleanup logic).+ const longPressHandlers = useLongPress({+ disabled: isDisabled,+ onLongPress: useCallback(+ (point: {x: number; y: number}) => {+ positionRef.current = {x: point.x, y: point.y};+ layer.show();+ if (hasAutoFocus) {+ requestAnimationFrame(() => focusFirst());+ }+ },+ [layer, hasAutoFocus, focusFirst],+ ),+ });+const popoverXstyle = menuWidth? styles.popoverCustomWidth(menuWidth): styles.popover;@@ -354,7 +389,12 @@ export function ContextMenu({return (<>- <div ref={ref} onContextMenu={handleContextMenu} data-testid={testId}>+ <div+ ref={ref}+ onContextMenu={handleContextMenu}+ {...longPressHandlers}+ data-testid={testId}+ {...stylex.props(styles.trigger)}>{children}</div>diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.tsindex 79a98f8f60..05113d7790 100644--- a/packages/core/src/hooks/index.ts+++ b/packages/core/src/hooks/index.ts@@ -65,3 +65,9 @@ export type {InteractiveRole,UseInteractiveRoleOptions,} from './useInteractiveRole';++export {useLongPress} from './useLongPress';+export type {+ UseLongPressOptions,+ UseLongPressHandlers,+} from './useLongPress';diff --git a/packages/core/src/hooks/useLongPress.test.tsx b/packages/core/src/hooks/useLongPress.test.tsxnew file mode 100644index 0000000000..17675bad84--- /dev/null+++ b/packages/core/src/hooks/useLongPress.test.tsx@@ -0,0 +1,134 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';+import {renderHook, act} from '@testing-library/react';+import {useLongPress} from './useLongPress';++// Minimal React.TouchEvent stand-in carrying only what the hook reads.+function touchEvent(touches: {clientX: number; clientY: number}[]) {+ return {touches} as unknown as React.TouchEvent;+}++describe('useLongPress', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('fires onLongPress with the start point after the delay', () => {+ const onLongPress = vi.fn();+ const {result} = renderHook(() => useLongPress({onLongPress}));++ act(() => {+ result.current.onTouchStart(touchEvent([{clientX: 10, clientY: 20}]));+ });+ expect(onLongPress).not.toHaveBeenCalled();++ act(() => {+ vi.advanceTimersByTime(500);+ });+ expect(onLongPress).toHaveBeenCalledTimes(1);+ expect(onLongPress).toHaveBeenCalledWith({x: 10, y: 20});+ });++ it('respects a custom delayMs', () => {+ const onLongPress = vi.fn();+ const {result} = renderHook(() =>+ useLongPress({onLongPress, delayMs: 1000}),+ );++ act(() => {+ result.current.onTouchStart(touchEvent([{clientX: 1, clientY: 2}]));+ vi.advanceTimersByTime(999);+ });+ expect(onLongPress).not.toHaveBeenCalled();++ act(() => {+ vi.advanceTimersByTime(1);+ });+ expect(onLongPress).toHaveBeenCalledTimes(1);+ });++ it('does nothing when disabled', () => {+ const onLongPress = vi.fn();+ const {result} = renderHook(() =>+ useLongPress({onLongPress, disabled: true}),+ );++ act(() => {+ result.current.onTouchStart(touchEvent([{clientX: 0, clientY: 0}]));+ vi.advanceTimersByTime(500);+ });+ expect(onLongPress).not.toHaveBeenCalled();+ });++ it('ignores multi-touch starts', () => {+ const onLongPress = vi.fn();+ const {result} = renderHook(() => useLongPress({onLongPress}));++ act(() => {+ result.current.onTouchStart(+ touchEvent([+ {clientX: 0, clientY: 0},+ {clientX: 5, clientY: 5},+ ]),+ );+ vi.advanceTimersByTime(500);+ });+ expect(onLongPress).not.toHaveBeenCalled();+ });++ it('cancels when the finger moves past the threshold', () => {+ const onLongPress = vi.fn();+ const {result} = renderHook(() => useLongPress({onLongPress}));++ act(() => {+ result.current.onTouchStart(touchEvent([{clientX: 0, clientY: 0}]));+ // Move past the default 10px threshold.+ result.current.onTouchMove(touchEvent([{clientX: 15, clientY: 0}]));+ vi.advanceTimersByTime(500);+ });+ expect(onLongPress).not.toHaveBeenCalled();+ });++ it('does not cancel for movement within the threshold', () => {+ const onLongPress = vi.fn();+ const {result} = renderHook(() => useLongPress({onLongPress}));++ act(() => {+ result.current.onTouchStart(touchEvent([{clientX: 0, clientY: 0}]));+ result.current.onTouchMove(touchEvent([{clientX: 5, clientY: 5}]));+ vi.advanceTimersByTime(500);+ });+ expect(onLongPress).toHaveBeenCalledTimes(1);+ });++ it('cancels on touch end', () => {+ const onLongPress = vi.fn();+ const {result} = renderHook(() => useLongPress({onLongPress}));++ act(() => {+ result.current.onTouchStart(touchEvent([{clientX: 0, clientY: 0}]));+ result.current.onTouchEnd();+ vi.advanceTimersByTime(500);+ });+ expect(onLongPress).not.toHaveBeenCalled();+ });++ it('cancels the pending timer on unmount', () => {+ const onLongPress = vi.fn();+ const {result, unmount} = renderHook(() => useLongPress({onLongPress}));++ act(() => {+ result.current.onTouchStart(touchEvent([{clientX: 0, clientY: 0}]));+ });+ unmount();+ act(() => {+ vi.advanceTimersByTime(500);+ });+ expect(onLongPress).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/hooks/useLongPress.ts b/packages/core/src/hooks/useLongPress.tsnew file mode 100644index 0000000000..ea38de01ca--- /dev/null+++ b/packages/core/src/hooks/useLongPress.ts@@ -0,0 +1,119 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useLongPress.ts+ * @input Long-press options: onLongPress callback, disabled, delayMs, moveCancelPx+ * @output Touch handlers to spread onto an element+ * @position Core hook for touch long-press invocation; used by ContextMenu+ *+ * SYNC: When modified, update the hooks barrel /packages/core/src/hooks/index.ts+ *+ * Detects a single-finger long-press: fires `onLongPress` with the touch+ * start point after `delayMs`. Cancels if the finger moves past+ * `moveCancelPx` (treated as a scroll/drag), lifts, or the touch is+ * cancelled. The pending timer is also cleared on unmount.+ *+ * Motivation: iOS Safari never synthesizes a `contextmenu` event on+ * long-press, so long-press is the only touch affordance for opening+ * cursor-positioned surfaces.+ */++import {useCallback, useEffect, useRef} from 'react';++// Default long-press tuning.+const DEFAULT_DELAY_MS = 500;+const DEFAULT_MOVE_CANCEL_PX = 10;++export interface UseLongPressOptions {+ /** Fired with the touch start point once the press is held for `delayMs`. */+ onLongPress: (point: {x: number; y: number}) => void;+ /** When true, touch handlers are inert. */+ disabled?: boolean;+ /** Hold duration before the press fires, in ms. Defaults to 500. */+ delayMs?: number;+ /** Movement past this distance (px, either axis) cancels the press. Defaults to 10. */+ moveCancelPx?: number;+}++export interface UseLongPressHandlers {+ onTouchStart: (e: React.TouchEvent) => void;+ onTouchMove: (e: React.TouchEvent) => void;+ onTouchEnd: () => void;+ onTouchCancel: () => void;+}++export function useLongPress(+ options: UseLongPressOptions,+): UseLongPressHandlers {+ const {+ onLongPress,+ disabled = false,+ delayMs = DEFAULT_DELAY_MS,+ moveCancelPx = DEFAULT_MOVE_CANCEL_PX,+ } = options;++ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const startRef = useRef<{x: number; y: number} | null>(null);+ // Keep the latest callback without re-creating handlers on every render.+ const onLongPressRef = useRef(onLongPress);+ onLongPressRef.current = onLongPress;++ const clear = useCallback(() => {+ if (timerRef.current != null) {+ clearTimeout(timerRef.current);+ timerRef.current = null;+ }+ startRef.current = null;+ }, []);++ const onTouchStart = useCallback(+ (e: React.TouchEvent) => {+ if (disabled || e.touches.length !== 1) {+ return;+ }+ const touch = e.touches[0];+ // Clear any stale timer first, THEN record the start point — clearing+ // also nulls startRef, so order matters.+ clear();+ startRef.current = {x: touch.clientX, y: touch.clientY};+ timerRef.current = setTimeout(() => {+ const start = startRef.current;+ if (start == null) {+ return;+ }+ onLongPressRef.current({x: start.x, y: start.y});+ }, delayMs);+ },+ [disabled, delayMs, clear],+ );++ const onTouchMove = useCallback(+ (e: React.TouchEvent) => {+ const start = startRef.current;+ if (start == null || e.touches.length !== 1) {+ return;+ }+ const touch = e.touches[0];+ if (+ Math.abs(touch.clientX - start.x) > moveCancelPx ||+ Math.abs(touch.clientY - start.y) > moveCancelPx+ ) {+ // Treat as a scroll/drag, not a long-press.+ clear();+ }+ },+ [moveCancelPx, clear],+ );++ // Cancel any pending long-press timer on unmount.+ useEffect(() => clear, [clear]);++ return {+ onTouchStart,+ onTouchMove,+ onTouchEnd: clear,+ onTouchCancel: clear,+ };+}