Skip to content

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

TypeScript

fix(core): a long press held through a busy main thread still reports, on the touch events' clock (#9455)

Christopher Chedeauacca58968c8e
diff --git a/.changeset/long-press-event-clock.md b/.changeset/long-press-event-clock.md
new file mode 100644
index 0000000000..fe84f56b79
--- /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 ade7f678a7..ffc0999b77 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<HTMLElement>) => {
- handleLongPressTouchEnd();
+ handleLongPressTouchEnd(event);
onTouchEndProp?.(event);
},
[handleLongPressTouchEnd, onTouchEndProp],
);
const handleTriggerTouchCancel = useCallback(
(event: React.TouchEvent<HTMLElement>) => {
- 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 46a01c1eba..1797107a16 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 1d502878a9..e5699df809 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 175b53235f..ff4a22b62b 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<typeof windowClock>,
+ timeStamp: number,
+ touches: {clientX: number; clientY: number}[] = [],
+) {
+ return {touches, timeStamp, view} as unknown as React.TouchEvent;
+}
+
describe('useLongPress', () => {
beforeEach(() => {
vi.useFakeTimers();
@@ -188,3 +207,256 @@ 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('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<typeof windowClock>, Date.now(), [
+ {clientX: 0, clientY: 0},
+ ]),
+ );
+ vi.advanceTimersByTime(100);
+ result.current.onTouchEnd(
+ stamped(page as unknown as ReturnType<typeof windowClock>, 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();
+ 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 c70cfdcbfa..b1f4209c77 100644
--- a/packages/core/src/hooks/useLongPress.ts
+++ b/packages/core/src/hooks/useLongPress.ts
@@ -25,6 +25,11 @@
// 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' 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 {
@@ -37,6 +42,41 @@ 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<Performance, 'now'>;
+
+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 with
+ * `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 {
+ // 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 (
+ clock != null &&
+ Math.abs(Date.now() - timeStamp) < Math.abs(clock.now() - timeStamp)
+ ) {
+ return clock.now() - (Date.now() - timeStamp);
+ }
+ 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 +99,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 +162,9 @@ export function useLongPressDetector(
const timerRef = useRef<ReturnType<typeof setTimeout> | 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<number | null>(null);
+ const clockRef = useRef<EventClock | null>(null);
// The press in progress's tolerance, when its caller chose one at start.
const pressToleranceRef = useRef<LongPressTolerance | null>(null);
// Keep the latest callback without re-creating handlers on every render.
@@ -130,10 +177,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 +218,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 +280,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 +313,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 +329,8 @@ export function useLongPressDetector(
return {
onTouchStart,
onTouchMove,
- onTouchEnd: clear,
- onTouchCancel: clear,
+ onTouchEnd,
+ onTouchCancel: onTouchEnd,
start,
moveTo,
cancel: clear,