Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/long-press-event-clock.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@astryxdesign/core': patch
---

[fix] `useLongPress` times a hold on the touch events' own timestamps (`spec:AST-094` FR16). When a busy page handles the lift late, a finger held for the full delay still reports its long press before the lift acts, instead of losing it, so a ContextMenu's long press opens on a loaded page too. A touch the page handled late no longer lengthens the hold, and a lift stamped before the deadline still cancels the press when its timer ran late. `onTouchEnd` and `onTouchCancel` take the touch event, optionally; spreading the handlers passes it.

@vjeux
4 changes: 2 additions & 2 deletions packages/core/src/ContextMenu/ContextMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -712,14 +712,14 @@ export function ContextMenu({
);
const handleTriggerTouchEnd = useCallback(
(event: React.TouchEvent<HTMLElement>) => {
handleLongPressTouchEnd();
handleLongPressTouchEnd(event);
onTouchEndProp?.(event);
},
[handleLongPressTouchEnd, onTouchEndProp],
);
const handleTriggerTouchCancel = useCallback(
(event: React.TouchEvent<HTMLElement>) => {
handleLongPressTouchCancel();
handleLongPressTouchCancel(event);
onTouchCancelProp?.(event);
},
[handleLongPressTouchCancel, onTouchCancelProp],
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
// @pr-a11y scope ^packages/core/src/Table/ ^packages/core/src/ContextMenu/ ^apps/storybook/stories/TableRowExpansion
// @pr-a11y scope ^packages/core/src/Table/ ^packages/core/src/ContextMenu/ ^packages/core/src/hooks/useLongPress ^apps/storybook/stories/TableRowExpansion

/**
* @file TableCellMenus.a11y.browser.spec.ts
Expand All @@ -9,7 +9,9 @@
* 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
* unchanged; and that a long press held through a busy main thread still
* opens it (spec:AST-094 FR16: the hold is timed on the touch events' own
* clock, so a late lift reports the press first)
* @position Regression proof for ContextMenu mounting its layer at its first
* open (row expansion gives every body cell a context menu)
*/
Expand Down Expand Up @@ -184,4 +186,46 @@ test.describe('on a touch screen', () => {
expect(Math.abs((anchor?.x ?? 0) - point.x)).toBeLessThanOrEqual(1);
expect(Math.abs((anchor?.y ?? 0) - point.y)).toBeLessThanOrEqual(1);
});

test('a long press held through a busy main thread still opens the menu at the finger (spec:AST-094 FR16)', 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};
// The page's main thread is busy for 1,200 ms from just after the touch
// starts, through the 800 ms hold: a listener on the window, which runs
// after the cell's own touch handlers, so the long press is timed by then.
// The lift and the press's timer both wait behind that task.
await page.evaluate(() => {
window.addEventListener(
'touchstart',
() => {
const end = performance.now() + 1200;
while (performance.now() < end) {
// Busy.
}
},
{once: true, passive: true},
);
});
const driver = await touchDriver(page);
await driver.play(tap(point, {holdMs: 800}));
// The menu is there and painted before anything is measured on it.
const menu = page.getByRole('menu');
await expect(menu).toHaveCount(1);
await expect(menu).toBeVisible();
const menuBox = await menu.boundingBox();
expect(menuBox?.width ?? 0).toBeGreaterThan(0);
expect(menuBox?.height ?? 0).toBeGreaterThan(0);
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);
});
});
4 changes: 2 additions & 2 deletions packages/core/src/hooks/useLongPress.doc.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export const docs = {
],
usage: {
description:
'Detects a single-finger press-and-hold and reports where it happened, so touch users can reach affordances that a pointer gets from right-click. iOS Safari never synthesizes a contextmenu event on long-press, which makes this the only touch route into a cursor-positioned surface such as ContextMenu. The press cancels on movement, lift, multi-touch or unmount.',
'Detects a single-finger press-and-hold and reports where it happened, so touch users can reach affordances that a pointer gets from right-click. iOS Safari never synthesizes a contextmenu event on long-press, which makes this the only touch route into a cursor-positioned surface such as ContextMenu. The press cancels on movement, lift, multi-touch or unmount. The hold is timed on the touch events\u2019 own timestamps: when a busy page handles the lift late, a finger held for the full delay still reports its long press, before the lift acts.',
bestPractices: [
{
guidance: true,
Expand Down Expand Up @@ -102,7 +102,7 @@ export const docsDense = {
},
usage: {
description:
'Touch press-and-hold for affordances a pointer reaches by right-click (e.g. ContextMenu). Reports the point so the surface opens under the finger.',
"Touch press-and-hold for affordances a pointer reaches by right-click (e.g. ContextMenu). Reports the point so the surface opens under the finger. Timed on the touch events' timestamps: a busy page delays the report, never drops it.",
bestPractices: [
{
guidance: true,
Expand Down
228 changes: 228 additions & 0 deletions packages/core/src/hooks/useLongPress.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,25 @@ function touchEvent(touches: {clientX: number; clientY: number}[]) {
return {touches} as unknown as React.TouchEvent;
}

// A window's clock (`performance`): `now()` reads `at` now and moves with
// the fake timers. A same-origin iframe or Picture-in-Picture window has a
// time origin of its own.
const EPOCH_ORIGIN = 1_700_000_000_000;
function windowClock(at: number, timeOrigin = EPOCH_ORIGIN) {
const offset = at - Date.now();
return {performance: {now: () => Date.now() + offset, timeOrigin}};
}

// The same stand-in, dispatched in `view` and stamped on its clock
// (`event.timeStamp`).
function stamped(
view: ReturnType<typeof windowClock>,
timeStamp: number,
touches: {clientX: number; clientY: number}[] = [],
) {
return {touches, timeStamp, view} as unknown as React.TouchEvent;
}

describe('useLongPress', () => {
beforeEach(() => {
vi.useFakeTimers();
Expand Down Expand Up @@ -188,3 +207,212 @@ describe('useLongPress', () => {
expect(onLongPress).not.toHaveBeenCalled();
});
});

describe('useLongPress on the events\u2019 clock (spec:AST-094 FR16)', () => {
beforeEach(() => {
vi.useFakeTimers();
});

afterEach(() => {
vi.restoreAllMocks();
vi.useRealTimers();
});

it('reports the press first when the lift is stamped past the deadline, though the page timer has not run (a blocked main thread)', () => {
const page = windowClock(1000);
const onLongPress = vi.fn();
const {result} = renderHook(() => useLongPress({onLongPress}));
act(() => {
result.current.onTouchStart(
stamped(page, 1000, [{clientX: 10, clientY: 20}]),
);
result.current.onTouchEnd(stamped(page, 1800));
});
expect(onLongPress).toHaveBeenCalledTimes(1);
expect(onLongPress).toHaveBeenCalledWith({x: 10, y: 20});
act(() => {
vi.advanceTimersByTime(1000);
});
expect(onLongPress).toHaveBeenCalledTimes(1);
});

it('reports the press first when a move within the allowance is stamped past the deadline', () => {
const page = windowClock(1000);
const onLongPress = vi.fn();
const {result} = renderHook(() => useLongPress({onLongPress}));
act(() => {
result.current.onTouchStart(
stamped(page, 1000, [{clientX: 10, clientY: 20}]),
);
result.current.onTouchMove(
stamped(page, 1600, [{clientX: 12, clientY: 21}]),
);
});
expect(onLongPress).toHaveBeenCalledTimes(1);
expect(onLongPress).toHaveBeenCalledWith({x: 10, y: 20});
});

it('reports the press first when a second finger lands after the deadline, then ends it', () => {
const page = windowClock(1000);
const onLongPress = vi.fn();
const {result} = renderHook(() => useLongPress({onLongPress}));
act(() => {
result.current.onTouchStart(
stamped(page, 1000, [{clientX: 10, clientY: 20}]),
);
result.current.onTouchStart(
stamped(page, 1700, [
{clientX: 10, clientY: 20},
{clientX: 90, clientY: 20},
]),
);
vi.advanceTimersByTime(1000);
});
expect(onLongPress).toHaveBeenCalledTimes(1);
});

it('reports the press when a cancel is stamped past the deadline, and drops it when stamped before', () => {
const page = windowClock(1000);
const onLongPress = vi.fn();
const {result} = renderHook(() => useLongPress({onLongPress}));
act(() => {
result.current.onTouchStart(
stamped(page, 1000, [{clientX: 0, clientY: 0}]),
);
result.current.onTouchCancel(stamped(page, 1300));
vi.advanceTimersByTime(1000);
});
expect(onLongPress).not.toHaveBeenCalled();
const later = windowClock(5000);
act(() => {
result.current.onTouchStart(
stamped(later, 5000, [{clientX: 0, clientY: 0}]),
);
result.current.onTouchCancel(stamped(later, 5600));
});
expect(onLongPress).toHaveBeenCalledTimes(1);
});

it('does not lengthen the hold of a touch the page handled late: the timer waits only for the rest', () => {
const page = windowClock(1300);
const onLongPress = vi.fn();
const {result} = renderHook(() => useLongPress({onLongPress}));
act(() => {
result.current.onTouchStart(
stamped(page, 1000, [{clientX: 0, clientY: 0}]),
);
vi.advanceTimersByTime(199);
});
expect(onLongPress).not.toHaveBeenCalled();
act(() => {
vi.advanceTimersByTime(1);
});
expect(onLongPress).toHaveBeenCalledTimes(1);
});

it('lets a lift stamped before the deadline cancel the press, though its timer ran late', () => {
const page = windowClock(2000);
const onLongPress = vi.fn();
const {result} = renderHook(() => useLongPress({onLongPress}));
act(() => {
// Handled 1,000 ms late: the press was due 500 ms ago, so its timer
// runs at once, finds itself late, and yields to queued input once.
result.current.onTouchStart(
stamped(page, 1000, [{clientX: 0, clientY: 0}]),
);
vi.advanceTimersByTime(0);
});
expect(onLongPress).not.toHaveBeenCalled();
act(() => {
// The lift queued behind the long task: 300 ms after the touch.
result.current.onTouchEnd(stamped(page, 1300));
vi.advanceTimersByTime(100);
});
expect(onLongPress).not.toHaveBeenCalled();
});

it('reads a touch in a same-origin iframe or Picture-in-Picture window on that window\u2019s clock, whose origin is later than the page\u2019s', () => {
// The page's own clock reads far ahead of the iframe's.
vi.spyOn(performance, 'now').mockImplementation(() => Date.now() + 5000);
const frame = windowClock(100);
const onLongPress = vi.fn();
const {result} = renderHook(() => useLongPress({onLongPress}));
// A tap of 120 ms in the iframe opens nothing.
act(() => {
result.current.onTouchStart(
stamped(frame, 100, [{clientX: 0, clientY: 0}]),
);
vi.advanceTimersByTime(120);
result.current.onTouchEnd(stamped(frame, 220));
vi.advanceTimersByTime(1000);
});
expect(onLongPress).not.toHaveBeenCalled();
// A finger held there for the delay opens it at the delay, not before.
const held = windowClock(2000);
act(() => {
result.current.onTouchStart(
stamped(held, 2000, [{clientX: 4, clientY: 6}]),
);
vi.advanceTimersByTime(499);
});
expect(onLongPress).not.toHaveBeenCalled();
act(() => {
vi.advanceTimersByTime(1);
});
expect(onLongPress).toHaveBeenCalledWith({x: 4, y: 6});
});

it('reads an event stamped in epoch milliseconds (jsdom) by its age on Date.now()', () => {
// Handled 300 ms after it was stamped: the press is due in 200 ms, not
// the full delay.
const page = windowClock(1300);
const onLongPress = vi.fn();
const {result} = renderHook(() => useLongPress({onLongPress}));
act(() => {
result.current.onTouchStart(
stamped(page, Date.now() - 300, [{clientX: 0, clientY: 0}]),
);
vi.advanceTimersByTime(199);
});
expect(onLongPress).not.toHaveBeenCalled();
act(() => {
vi.advanceTimersByTime(1);
});
expect(onLongPress).toHaveBeenCalledTimes(1);
});

it('keeps a tap a tap in a test that freezes the system time at an earlier date', () => {
vi.setSystemTime(new Date(2026, 2, 15));
// The window's time origin stays the real one, months after the frozen
// date; jsdom stamps events with the frozen Date.now().
const page = windowClock(1000, Date.UTC(2026, 10, 2));
const onLongPress = vi.fn();
const {result} = renderHook(() => useLongPress({onLongPress}));
act(() => {
result.current.onTouchStart(
stamped(page, Date.now(), [{clientX: 0, clientY: 0}]),
);
vi.advanceTimersByTime(100);
result.current.onTouchEnd(stamped(page, Date.now()));
vi.advanceTimersByTime(1000);
});
expect(onLongPress).not.toHaveBeenCalled();
});

it('never waits longer than the delay when a touch is stamped ahead of its clock', () => {
const page = windowClock(1000);
const onLongPress = vi.fn();
const {result} = renderHook(() => useLongPress({onLongPress}));
act(() => {
result.current.onTouchStart(
stamped(page, 1400, [{clientX: 0, clientY: 0}]),
);
vi.advanceTimersByTime(499);
});
expect(onLongPress).not.toHaveBeenCalled();
act(() => {
vi.advanceTimersByTime(1);
});
expect(onLongPress).toHaveBeenCalledTimes(1);
});
});
Loading