From 43721709200be9c8c7dfb24257ea541a5a4c1623 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 2 Nov 2026 03:43:52 -0800 Subject: [PATCH 1/3] fix(core): a long press held through a busy main thread still reports, on the touch events' clock useLongPress timed a hold with a page timer set at touchstart and cleared by touchend. When the main thread was busy through the hold, the page ran the queued touchend before the overdue timer, and the long press was lost: a Table cell's ContextMenu opened nothing after an 800 ms hold. spec:AST-094 FR16 asks a gesture to keep the event clock: a blocked main thread delays the report and never the moment reported. - The hold is a deadline on the touch events' own timestamps (touchstart.timeStamp + delay). A move, a second finger, or a lift stamped at or past it reports the pending press first, at its start point, then acts. - The page timer waits only for what is left of the hold, so a touch the page handled late does not lengthen it. A timer that fires late yields once to queued input, so a lift stamped before the deadline still cancels the press: the gesture arena's rule (gestures/GestureArena.ts). - The clock is the touch's own window's, (e.view ?? window).performance, captured at touchstart: a same-origin iframe or a Picture-in-Picture window has its own time origin. Epoch stamps (jsdom) come onto it through its time origin, and the timer never waits past the delay. - onTouchEnd and onTouchCancel take the touch event, optionally; ContextMenu passes it. Tests: useLongPress's event-clock cases (six fail on main), among them a touch on a window clock whose origin is later than the page's, and a TableCellMenus browser case whose first long press is held through a 1,200 ms busy main thread (fails on main). A [fix] changeset. --- .changeset/long-press-event-clock.md | 7 + packages/core/src/ContextMenu/ContextMenu.tsx | 4 +- .../TableCellMenus.a11y.browser.spec.ts | 48 +++- packages/core/src/hooks/useLongPress.doc.mjs | 4 +- packages/core/src/hooks/useLongPress.test.tsx | 210 ++++++++++++++++++ packages/core/src/hooks/useLongPress.ts | 146 ++++++++++-- 6 files changed, 398 insertions(+), 21 deletions(-) create mode 100644 .changeset/long-press-event-clock.md diff --git a/.changeset/long-press-event-clock.md b/.changeset/long-press-event-clock.md new file mode 100644 index 0000000000000..fe84f56b794b0 --- /dev/null +++ b/.changeset/long-press-event-clock.md @@ -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 diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index ade7f678a70dd..ffc0999b774fe 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -712,14 +712,14 @@ export function ContextMenu({ ); const handleTriggerTouchEnd = useCallback( (event: React.TouchEvent) => { - handleLongPressTouchEnd(); + handleLongPressTouchEnd(event); onTouchEndProp?.(event); }, [handleLongPressTouchEnd, onTouchEndProp], ); const handleTriggerTouchCancel = useCallback( (event: React.TouchEvent) => { - handleLongPressTouchCancel(); + handleLongPressTouchCancel(event); onTouchCancelProp?.(event); }, [handleLongPressTouchCancel, onTouchCancelProp], diff --git a/packages/core/src/Table/__tests__/TableCellMenus.a11y.browser.spec.ts b/packages/core/src/Table/__tests__/TableCellMenus.a11y.browser.spec.ts index 46a01c1ebae39..1797107a168b7 100644 --- a/packages/core/src/Table/__tests__/TableCellMenus.a11y.browser.spec.ts +++ b/packages/core/src/Table/__tests__/TableCellMenus.a11y.browser.spec.ts @@ -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 @@ -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) */ @@ -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); + }); }); diff --git a/packages/core/src/hooks/useLongPress.doc.mjs b/packages/core/src/hooks/useLongPress.doc.mjs index 1d502878a90cb..e5699df809575 100644 --- a/packages/core/src/hooks/useLongPress.doc.mjs +++ b/packages/core/src/hooks/useLongPress.doc.mjs @@ -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, @@ -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, diff --git a/packages/core/src/hooks/useLongPress.test.tsx b/packages/core/src/hooks/useLongPress.test.tsx index 175b53235fb4b..f8e2664d52451 100644 --- a/packages/core/src/hooks/useLongPress.test.tsx +++ b/packages/core/src/hooks/useLongPress.test.tsx @@ -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, + timeStamp: number, + touches: {clientX: number; clientY: number}[] = [], +) { + return {touches, timeStamp, view} as unknown as React.TouchEvent; +} + describe('useLongPress', () => { beforeEach(() => { vi.useFakeTimers(); @@ -188,3 +207,194 @@ 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('brings an event stamped in epoch milliseconds (jsdom) onto its window\u2019s clock through the time origin', () => { + // Handled 300 ms late on a clock whose events arrive in epoch ms: on the + // window's clock 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, EPOCH_ORIGIN + 1000, [{clientX: 0, clientY: 0}]), + ); + vi.advanceTimersByTime(199); + }); + expect(onLongPress).not.toHaveBeenCalled(); + act(() => { + vi.advanceTimersByTime(1); + }); + expect(onLongPress).toHaveBeenCalledTimes(1); + }); + + 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); + }); +}); diff --git a/packages/core/src/hooks/useLongPress.ts b/packages/core/src/hooks/useLongPress.ts index c70cfdcbfaac0..1ac3806ddca71 100644 --- a/packages/core/src/hooks/useLongPress.ts +++ b/packages/core/src/hooks/useLongPress.ts @@ -25,6 +25,12 @@ // its tolerance as a distance, as UIKit does. This hook measures it on each // axis. The context menu's own movement allowance is a guess and is not // measured yet (AST-094). +// +// The hold is a deadline on the touch events' own timestamps, read on the +// clock of the window the touch came from (an iframe or a Picture-in-Picture +// window has its own). A busy main thread can hold the timer back past the +// deadline; a touch stamped past it then reports the long press before it +// acts, so a busy page delays the report and never drops it. import {useCallback, useEffect, useRef} from 'react'; import { @@ -37,6 +43,35 @@ import { const DEFAULT_DELAY_MS = LONG_PRESS_DURATION_MS; const DEFAULT_MOVE_CANCEL_PX = LONG_PRESS_ALLOWABLE_MOVEMENT_PX; +/** The part of a window's performance timeline a press reads. */ +type EventClock = Pick; + +/** The clock of the window a touch came from. */ +function clockOf(e: React.TouchEvent): EventClock | null { + const view = e.view as unknown as {performance?: EventClock} | null; + return ( + view?.performance ?? + (typeof performance === 'undefined' ? null : performance) + ); +} + +/** + * An event's time on its window's clock. jsdom stamps events in epoch + * milliseconds; those come onto the clock through its time origin. + */ +function timeOn( + clock: EventClock | null, + timeStamp: number | undefined, +): number | undefined { + if (timeStamp == null || !Number.isFinite(timeStamp)) { + return undefined; + } + if (timeStamp > 1e12 && clock != null && clock.timeOrigin > 0) { + return timeStamp - clock.timeOrigin; + } + return timeStamp; +} + export interface UseLongPressOptions { /** Fired with the touch start point once the press is held for `delayMs`. */ onLongPress: (point: {x: number; y: number}) => void; @@ -59,8 +94,12 @@ export interface LongPressTolerance { export interface UseLongPressHandlers { onTouchStart: (e: React.TouchEvent) => void; onTouchMove: (e: React.TouchEvent) => void; - onTouchEnd: () => void; - onTouchCancel: () => void; + /** + * The lift. Pass the event, so a press it is stamped past (its timer held + * back by a busy page) still reports first. Spreading the handlers does. + */ + onTouchEnd: (e?: React.TouchEvent) => void; + onTouchCancel: (e?: React.TouchEvent) => void; /** * Begin detection at a point, for a caller driving this from its own * pointer events rather than the touch handlers above. @@ -118,6 +157,9 @@ export function useLongPressDetector( const timerRef = useRef | null>(null); const startRef = useRef<{x: number; y: number} | null>(null); + // The pending press's deadline and clock, when it started from a touch. + const deadlineRef = useRef(null); + const clockRef = useRef(null); // The press in progress's tolerance, when its caller chose one at start. const pressToleranceRef = useRef(null); // Keep the latest callback without re-creating handlers on every render. @@ -130,10 +172,39 @@ export function useLongPressDetector( timerRef.current = null; } startRef.current = null; + deadlineRef.current = null; + clockRef.current = null; }, []); - const start = useCallback( - (point: {x: number; y: number}, tolerance?: LongPressTolerance) => { + const fire = useCallback(() => { + const from = startRef.current; + if (from == null) { + return; + } + clear(); + onLongPressRef.current({x: from.x, y: from.y}); + }, [clear]); + + // A touch stamped at or past the deadline: the finger was down for the + // whole delay, so the press reports before the touch acts. + const fireIfDue = useCallback( + (e: React.TouchEvent | undefined) => { + const deadline = deadlineRef.current; + const eventTime = + e == null ? undefined : timeOn(clockRef.current, e.timeStamp); + if (deadline != null && eventTime != null && eventTime >= deadline) { + fire(); + } + }, + [fire], + ); + + const begin = useCallback( + ( + point: {x: number; y: number}, + tolerance: LongPressTolerance | undefined, + started: {at: number; clock: EventClock} | undefined, + ) => { if (disabled) { return; } @@ -142,15 +213,40 @@ export function useLongPressDetector( clear(); startRef.current = {x: point.x, y: point.y}; pressToleranceRef.current = tolerance ?? null; - timerRef.current = setTimeout(() => { - const from = startRef.current; - if (from == null) { + const clock = started?.clock ?? null; + const deadline = started == null ? null : started.at + delayMs; + clockRef.current = clock; + deadlineRef.current = deadline; + // Wait only for the rest of the hold, so a touch handled late does not + // lengthen it, and never past the delay. + const remaining = + clock == null || deadline == null + ? delayMs + : Math.min(delayMs, Math.max(0, deadline - clock.now())); + // A late timer yields to queued input once, so a lift stamped before + // the deadline still cancels the press. The gesture arena does the same. + const run = (mayYield: boolean) => { + timerRef.current = null; + if ( + mayYield && + clock != null && + deadline != null && + clock.now() > deadline + ) { + timerRef.current = setTimeout(() => run(false), 0); return; } - onLongPressRef.current({x: from.x, y: from.y}); - }, delayMs); + fire(); + }; + timerRef.current = setTimeout(() => run(true), remaining); }, - [disabled, delayMs, clear], + [disabled, delayMs, clear, fire], + ); + + const start = useCallback( + (point: {x: number; y: number}, tolerance?: LongPressTolerance) => + begin(point, tolerance, undefined), + [begin], ); const moveTo = useCallback( @@ -179,17 +275,29 @@ export function useLongPressDetector( return; } if (e.touches.length !== 1) { + // A second finger ends the press, unless the press was already due. + fireIfDue(e); clear(); return; } const touch = e.touches[0]; - start({x: touch.clientX, y: touch.clientY}); + const clock = clockOf(e); + const at = timeOn(clock, e.timeStamp); + begin( + {x: touch.clientX, y: touch.clientY}, + undefined, + clock == null || at == null ? undefined : {at, clock}, + ); }, - [disabled, clear, start], + [disabled, clear, begin, fireIfDue], ); const onTouchMove = useCallback( (e: React.TouchEvent) => { + if (startRef.current == null) { + return; + } + fireIfDue(e); if (startRef.current == null) { return; } @@ -200,7 +308,15 @@ export function useLongPressDetector( const touch = e.touches[0]; moveTo({x: touch.clientX, y: touch.clientY}); }, - [clear, moveTo], + [clear, moveTo, fireIfDue], + ); + + const onTouchEnd = useCallback( + (e?: React.TouchEvent) => { + fireIfDue(e); + clear(); + }, + [clear, fireIfDue], ); useEffect(() => clear, [clear]); @@ -208,8 +324,8 @@ export function useLongPressDetector( return { onTouchStart, onTouchMove, - onTouchEnd: clear, - onTouchCancel: clear, + onTouchEnd, + onTouchCancel: onTouchEnd, start, moveTo, cancel: clear, From cab4f23b65c060028c4a62eb2315d728c67b01a1 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 2 Nov 2026 04:45:57 -0800 Subject: [PATCH 2/3] fix(core): a long press reads a jsdom stamp's age on Date.now() jsdom stamps events with Date.now(). The hold converted such a stamp by subtracting the window's real time origin, so in a test that freezes the system time at an earlier date the touch landed months in the past, its timer fired at once, and a 100 ms tap opened ContextMenu. An epoch stamp's age is now read on Date.now(), the clock that made it, and placed on the window's clock: clock.now() - (Date.now() - timeStamp). Tests: an epoch stamp handled 300 ms late is due in 200 ms, and a tap under a frozen earlier system time opens nothing; both fail on the previous version. --- packages/core/src/hooks/useLongPress.test.tsx | 26 ++++++++++++++++--- packages/core/src/hooks/useLongPress.ts | 21 +++++++-------- 2 files changed, 32 insertions(+), 15 deletions(-) diff --git a/packages/core/src/hooks/useLongPress.test.tsx b/packages/core/src/hooks/useLongPress.test.tsx index f8e2664d52451..3fe0a10e4337c 100644 --- a/packages/core/src/hooks/useLongPress.test.tsx +++ b/packages/core/src/hooks/useLongPress.test.tsx @@ -362,15 +362,15 @@ describe('useLongPress on the events\u2019 clock (spec:AST-094 FR16)', () => { expect(onLongPress).toHaveBeenCalledWith({x: 4, y: 6}); }); - it('brings an event stamped in epoch milliseconds (jsdom) onto its window\u2019s clock through the time origin', () => { - // Handled 300 ms late on a clock whose events arrive in epoch ms: on the - // window's clock the press is due in 200 ms, not the full delay. + 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, EPOCH_ORIGIN + 1000, [{clientX: 0, clientY: 0}]), + stamped(page, Date.now() - 300, [{clientX: 0, clientY: 0}]), ); vi.advanceTimersByTime(199); }); @@ -381,6 +381,24 @@ describe('useLongPress on the events\u2019 clock (spec:AST-094 FR16)', () => { 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(); diff --git a/packages/core/src/hooks/useLongPress.ts b/packages/core/src/hooks/useLongPress.ts index 1ac3806ddca71..0eb8752f27fd3 100644 --- a/packages/core/src/hooks/useLongPress.ts +++ b/packages/core/src/hooks/useLongPress.ts @@ -26,11 +26,10 @@ // axis. The context menu's own movement allowance is a guess and is not // measured yet (AST-094). // -// The hold is a deadline on the touch events' own timestamps, read on the -// clock of the window the touch came from (an iframe or a Picture-in-Picture -// window has its own). A busy main thread can hold the timer back past the -// deadline; a touch stamped past it then reports the long press before it -// acts, so a busy page delays the report and never drops it. +// The hold is a deadline on the touch events' timestamps, on the clock of the +// touch's own window. A busy main thread can delay the timer past the +// deadline. A touch stamped after the deadline then reports the press before +// it acts. import {useCallback, useEffect, useRef} from 'react'; import { @@ -44,9 +43,8 @@ const DEFAULT_DELAY_MS = LONG_PRESS_DURATION_MS; const DEFAULT_MOVE_CANCEL_PX = LONG_PRESS_ALLOWABLE_MOVEMENT_PX; /** The part of a window's performance timeline a press reads. */ -type EventClock = Pick; +type EventClock = Pick; -/** The clock of the window a touch came from. */ function clockOf(e: React.TouchEvent): EventClock | null { const view = e.view as unknown as {performance?: EventClock} | null; return ( @@ -56,8 +54,9 @@ function clockOf(e: React.TouchEvent): EventClock | null { } /** - * An event's time on its window's clock. jsdom stamps events in epoch - * milliseconds; those come onto the clock through its time origin. + * An event's time on its window's clock. jsdom stamps events with + * `Date.now()`, so such a stamp's age is read on that clock: a test that + * freezes or moves the system time keeps the press's timing. */ function timeOn( clock: EventClock | null, @@ -66,8 +65,8 @@ function timeOn( if (timeStamp == null || !Number.isFinite(timeStamp)) { return undefined; } - if (timeStamp > 1e12 && clock != null && clock.timeOrigin > 0) { - return timeStamp - clock.timeOrigin; + if (timeStamp > 1e12 && clock != null) { + return clock.now() - (Date.now() - timeStamp); } return timeStamp; } From 5153bfbe7e5a16108f9cdf65e526e5a9ec81bf95 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 2 Nov 2026 06:02:39 -0800 Subject: [PATCH 3/3] fix(core): a long press tells a Date.now() stamp from a window-clock one by distance A stamp counted as a Date.now() stamp only above 1e12, so in a jsdom test that froze the date at 0 and left performance real, a small Date.now() stamp read as a window-clock time seconds in the past and a 100 ms tap opened ContextMenu. A stamp nearer Date.now() than the window's clock is now read as a Date.now() stamp, by its age. A stamp of 0 carries no time, so the hold falls back to the full delay on the page's timer. Tests: a tap under a date frozen at 0 with a real window clock, and a touch stamped 0; each fails on the previous version. --- packages/core/src/hooks/useLongPress.test.tsx | 44 +++++++++++++++++++ packages/core/src/hooks/useLongPress.ts | 14 ++++-- 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/packages/core/src/hooks/useLongPress.test.tsx b/packages/core/src/hooks/useLongPress.test.tsx index 3fe0a10e4337c..ff4a22b62b713 100644 --- a/packages/core/src/hooks/useLongPress.test.tsx +++ b/packages/core/src/hooks/useLongPress.test.tsx @@ -399,6 +399,50 @@ describe('useLongPress on the events\u2019 clock (spec:AST-094 FR16)', () => { expect(onLongPress).not.toHaveBeenCalled(); }); + it('keeps a tap a tap in a test that freezes the date at 0 and leaves the window clock real', () => { + vi.setSystemTime(0); + // The window's clock is not faked: it reads a few seconds into the run + // and does not move with the fake timers. + const page = {performance: {now: () => 5000}}; + const onLongPress = vi.fn(); + const {result} = renderHook(() => useLongPress({onLongPress})); + act(() => { + result.current.onTouchStart( + stamped(page as unknown as ReturnType, Date.now(), [ + {clientX: 0, clientY: 0}, + ]), + ); + vi.advanceTimersByTime(100); + result.current.onTouchEnd( + stamped(page as unknown as ReturnType, Date.now()), + ); + vi.advanceTimersByTime(1000); + }); + expect(onLongPress).not.toHaveBeenCalled(); + }); + + it('waits the full delay for a touch that carries no time (a stamp of 0)', () => { + const page = windowClock(10_000); + const onLongPress = vi.fn(); + const {result} = renderHook(() => useLongPress({onLongPress})); + act(() => { + result.current.onTouchStart(stamped(page, 0, [{clientX: 0, clientY: 0}])); + vi.advanceTimersByTime(100); + result.current.onTouchEnd(stamped(page, 0)); + vi.advanceTimersByTime(1000); + }); + expect(onLongPress).not.toHaveBeenCalled(); + act(() => { + result.current.onTouchStart(stamped(page, 0, [{clientX: 0, clientY: 0}])); + vi.advanceTimersByTime(499); + }); + expect(onLongPress).not.toHaveBeenCalled(); + act(() => { + vi.advanceTimersByTime(1); + }); + expect(onLongPress).toHaveBeenCalledTimes(1); + }); + it('never waits longer than the delay when a touch is stamped ahead of its clock', () => { const page = windowClock(1000); const onLongPress = vi.fn(); diff --git a/packages/core/src/hooks/useLongPress.ts b/packages/core/src/hooks/useLongPress.ts index 0eb8752f27fd3..b1f4209c77341 100644 --- a/packages/core/src/hooks/useLongPress.ts +++ b/packages/core/src/hooks/useLongPress.ts @@ -55,17 +55,23 @@ function clockOf(e: React.TouchEvent): EventClock | null { /** * An event's time on its window's clock. jsdom stamps events with - * `Date.now()`, so such a stamp's age is read on that clock: a test that - * freezes or moves the system time keeps the press's timing. + * `Date.now()`. The hook reads the age of such a stamp on that clock, so a + * frozen system time keeps the hold's length. A stamp nearer `Date.now()` than + * the window's clock is that kind of stamp. */ function timeOn( clock: EventClock | null, timeStamp: number | undefined, ): number | undefined { - if (timeStamp == null || !Number.isFinite(timeStamp)) { + // A stamp of 0 means the event carries no time, so the hold falls back to + // the full delay on the page's timer. + if (timeStamp == null || !Number.isFinite(timeStamp) || timeStamp <= 0) { return undefined; } - if (timeStamp > 1e12 && clock != null) { + if ( + clock != null && + Math.abs(Date.now() - timeStamp) < Math.abs(clock.now() - timeStamp) + ) { return clock.now() - (Date.now() - timeStamp); } return timeStamp;