Skip to content

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

TypeScript

refactor(core): useLongPress runs its long press through a detector with no React (#9642)

Christopher Chedeauaa4bd1d3dedd
diff --git a/.changeset/long-press-detector.md b/.changeset/long-press-detector.md
new file mode 100644
index 0000000000..a69b38473a
--- /dev/null
+++ b/.changeset/long-press-detector.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: `useLongPress` runs its long-press detection through an internal detector with no React, so a press model that runs without React can share it. The hook and its handlers behave as before; `onLongPress` now also comes from the committed render. Not exported from the package entry point.
+
+@vjeux
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 1797107a16..0a69fcea0c 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/ ^packages/core/src/hooks/useLongPress ^apps/storybook/stories/TableRowExpansion
+// @pr-a11y scope ^packages/core/src/Table/ ^packages/core/src/ContextMenu/ ^packages/core/src/hooks/(useLongPress|longPressDetector) ^apps/storybook/stories/TableRowExpansion
/**
* @file TableCellMenus.a11y.browser.spec.ts
diff --git a/packages/core/src/hooks/longPressDetector.test.ts b/packages/core/src/hooks/longPressDetector.test.ts
new file mode 100644
index 0000000000..29fbd06b9c
--- /dev/null
+++ b/packages/core/src/hooks/longPressDetector.test.ts
@@ -0,0 +1,165 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file longPressDetector.test.ts
+ * @input vitest, createLongPressDetector
+ * @output Tests the long-press detector with no React: a hand start, a touch
+ * press on the events' clock, a second finger, a late timer, a start handled
+ * late, the movement tolerance, disabled, the latest options, and a touch
+ * with no time
+ * @position Unit coverage for longPressDetector.ts; useLongPress.test.tsx
+ * covers the hook that wraps it
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {
+ createLongPressDetector,
+ type LongPressTouchEvent,
+} from './longPressDetector';
+
+// A window whose clock reads `at` now and moves with the fake timers.
+function windowAt(at: number) {
+ const offset = at - Date.now();
+ return {performance: {now: () => Date.now() + offset}};
+}
+
+// A window whose clock reads only what the test sets: a busy page.
+function busyWindow(at: number) {
+ const view = {at, performance: {now: () => view.at}};
+ return view;
+}
+
+function touch(
+ view: unknown,
+ timeStamp: number,
+ points: {clientX: number; clientY: number}[] = [],
+): LongPressTouchEvent {
+ return {touches: points, timeStamp, view};
+}
+
+describe('createLongPressDetector', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('fires at the start point after the delay when started by hand, and not after a cancel', () => {
+ const onLongPress = vi.fn();
+ const detector = createLongPressDetector({onLongPress});
+ detector.start({x: 3, y: 4});
+ vi.advanceTimersByTime(499);
+ expect(onLongPress).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(onLongPress).toHaveBeenCalledWith({x: 3, y: 4});
+ detector.start({x: 0, y: 0});
+ detector.cancel();
+ vi.advanceTimersByTime(1000);
+ expect(onLongPress).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports a touch press first when its lift is stamped past the deadline, with no timer run', () => {
+ const page = windowAt(1000);
+ const onLongPress = vi.fn();
+ const detector = createLongPressDetector({onLongPress});
+ detector.touchStart(touch(page, 1000, [{clientX: 10, clientY: 20}]));
+ detector.touchEnd(touch(page, 1800));
+ expect(onLongPress).toHaveBeenCalledWith({x: 10, y: 20});
+ expect(detector.isPending()).toBe(false);
+ });
+
+ it('ends the press on a second finger, and reports it first when that touch is stamped past the deadline', () => {
+ const finger = {clientX: 5, clientY: 6};
+ const early = vi.fn();
+ const before = createLongPressDetector({onLongPress: early});
+ const page = windowAt(1000);
+ before.touchStart(touch(page, 1000, [finger]));
+ before.touchStart(touch(page, 1200, [finger, finger]));
+ expect(before.isPending()).toBe(false);
+ vi.advanceTimersByTime(1000);
+ expect(early).not.toHaveBeenCalled();
+
+ const late = vi.fn();
+ const after = createLongPressDetector({onLongPress: late});
+ const busy = busyWindow(1000);
+ after.touchStart(touch(busy, 1000, [finger]));
+ after.touchStart(touch(busy, 1600, [finger, finger]));
+ expect(late).toHaveBeenCalledWith({x: 5, y: 6});
+ expect(after.isPending()).toBe(false);
+ });
+
+ it('lets a lift stamped before the deadline cancel the press when its timer runs late', () => {
+ const onLongPress = vi.fn();
+ const detector = createLongPressDetector({onLongPress});
+ const busy = busyWindow(1000);
+ detector.touchStart(touch(busy, 1000, [{clientX: 0, clientY: 0}]));
+ // The page is busy past the deadline, so the timer runs late and yields
+ // once to the queued lift.
+ busy.at = 1700;
+ vi.advanceTimersByTime(500);
+ expect(onLongPress).not.toHaveBeenCalled();
+ detector.touchEnd(touch(busy, 1400));
+ vi.advanceTimersByTime(1000);
+ expect(onLongPress).not.toHaveBeenCalled();
+
+ detector.touchStart(touch(busy, 1700, [{clientX: 0, clientY: 0}]));
+ busy.at = 2400;
+ vi.advanceTimersByTime(500);
+ expect(onLongPress).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(onLongPress).toHaveBeenCalledTimes(1);
+ });
+
+ it('waits only for the rest of the hold when its start is handled late', () => {
+ const onLongPress = vi.fn();
+ const detector = createLongPressDetector({onLongPress});
+ detector.touchStart(
+ touch(windowAt(1300), 1000, [{clientX: 0, clientY: 0}]),
+ );
+ vi.advanceTimersByTime(199);
+ expect(onLongPress).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(onLongPress).toHaveBeenCalledTimes(1);
+ });
+
+ it('drops the press past the movement tolerance, or past a per-press tolerance', () => {
+ const onLongPress = vi.fn();
+ const detector = createLongPressDetector({onLongPress});
+ detector.start({x: 0, y: 0});
+ expect(detector.moveTo({x: 10, y: 0})).toBe(true);
+ expect(detector.moveTo({x: 11, y: 0})).toBe(false);
+ detector.start({x: 0, y: 0}, {moveCancelPx: 13});
+ expect(detector.moveTo({x: 13, y: 0})).toBe(true);
+ vi.advanceTimersByTime(500);
+ expect(onLongPress).toHaveBeenCalledTimes(1);
+ });
+
+ it('starts nothing while disabled, and reads the latest options at each start and fire', () => {
+ const first = vi.fn();
+ const latest = vi.fn();
+ const detector = createLongPressDetector({
+ onLongPress: first,
+ disabled: true,
+ });
+ detector.start({x: 0, y: 0});
+ expect(detector.isPending()).toBe(false);
+ detector.setOptions({onLongPress: first, delayMs: 200});
+ detector.start({x: 1, y: 1});
+ detector.setOptions({onLongPress: latest, delayMs: 200});
+ vi.advanceTimersByTime(200);
+ expect(first).not.toHaveBeenCalled();
+ expect(latest).toHaveBeenCalledWith({x: 1, y: 1});
+ });
+
+ it('waits the full delay for a touch that carries no time (a stamp of 0)', () => {
+ const onLongPress = vi.fn();
+ const detector = createLongPressDetector({onLongPress});
+ detector.touchStart(touch(windowAt(10_000), 0, [{clientX: 0, clientY: 0}]));
+ vi.advanceTimersByTime(499);
+ expect(onLongPress).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(onLongPress).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/core/src/hooks/longPressDetector.ts b/packages/core/src/hooks/longPressDetector.ts
new file mode 100644
index 0000000000..5e9eb04c42
--- /dev/null
+++ b/packages/core/src/hooks/longPressDetector.ts
@@ -0,0 +1,273 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file longPressDetector.ts
+ * @input The long-press numbers (motion/uikit/longPress.ts) and touch events
+ * @output createLongPressDetector(): one long press at a time, timed on the
+ * touch events' clock, with no React
+ * @position Internal; the core of useLongPress and useLongPressDetector
+ * (useLongPress.ts). Not in the hooks entry.
+ *
+ * SYNC: When modified, update /packages/core/src/hooks/useLongPress.ts
+ */
+
+import {
+ LONG_PRESS_ALLOWABLE_MOVEMENT_PX,
+ LONG_PRESS_DURATION_MS,
+} from '../motion/uikit/longPress';
+
+// 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. A press started by hand from a point has no stamp, so its page
+// timer waits the full delay.
+
+// The long-press numbers have one source, shared with the gesture
+// recognizers (motion/uikit/longPress.ts).
+const DEFAULT_DELAY_MS = LONG_PRESS_DURATION_MS;
+const DEFAULT_MOVE_CANCEL_PX = LONG_PRESS_ALLOWABLE_MOVEMENT_PX;
+
+/** @internal What a detector reads at each start, move and fire. */
+export interface LongPressDetectorOptions {
+ /** Fired with the start point once the press is held for `delayMs`. */
+ onLongPress: (point: {x: number; y: number}) => void;
+ /** When true, a start does nothing. */
+ 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;
+}
+
+/**
+ * @internal A press's own movement tolerance, for a core caller that decides
+ * it as the press starts (useMenuPress's trigger).
+ */
+export interface LongPressTolerance {
+ moveCancelPx?: number;
+}
+
+/**
+ * @internal The part of a touch event a detector reads, React's or the DOM's.
+ */
+export interface LongPressTouchEvent {
+ readonly touches: {
+ readonly length: number;
+ readonly [index: number]: {
+ readonly clientX: number;
+ readonly clientY: number;
+ };
+ };
+ readonly timeStamp: number;
+ readonly view?: unknown;
+}
+
+/** @internal One detector: start a press, report its touches, or drop it. */
+export interface LongPressDetector {
+ /** Begin detection at a point, dropping any press still pending. */
+ start: (
+ point: {x: number; y: number},
+ tolerance?: LongPressTolerance,
+ ) => void;
+ /** A touch started: one finger begins a press, a second one ends it. */
+ touchStart: (event: LongPressTouchEvent) => void;
+ /** A touch moved: past the tolerance the press is off. */
+ touchMove: (event: LongPressTouchEvent) => void;
+ /** The lift or the cancel. A press it is stamped past reports first. */
+ touchEnd: (event?: LongPressTouchEvent) => void;
+ /**
+ * Report the pointer's new position. Past the tolerance the press is off.
+ * Returns whether a press is still pending.
+ */
+ moveTo: (point: {x: number; y: number}) => boolean;
+ /** Drop any pending press (a lift, a cancel, or the gesture moving on). */
+ cancel: () => void;
+ /** Whether a press is in progress (started and not dropped). */
+ isPending: () => boolean;
+ /** The options the next start, move and fire read. */
+ setOptions: (options: LongPressDetectorOptions) => void;
+}
+
+/** The part of a window's performance timeline a press reads. */
+type EventClock = Pick<Performance, 'now'>;
+
+function clockOf(event: LongPressTouchEvent): EventClock | null {
+ const view = event.view as {performance?: EventClock} | null | undefined;
+ return (
+ view?.performance ??
+ (typeof performance === 'undefined' ? null : performance)
+ );
+}
+
+/**
+ * An event's time on its window's clock. jsdom stamps events with
+ * `Date.now()`. The detector 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;
+}
+
+/** @internal A long-press detector with no React (see LongPressDetector). */
+export function createLongPressDetector(
+ initial: LongPressDetectorOptions,
+): LongPressDetector {
+ let options = initial;
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ let from: {x: number; y: number} | null = null;
+ // Null for a press started by hand. It has no stamp.
+ let deadline: number | null = null;
+ let clock: EventClock | null = null;
+ let pressTolerance: LongPressTolerance | null = null;
+
+ const cancel = () => {
+ if (timer != null) {
+ clearTimeout(timer);
+ timer = null;
+ }
+ from = null;
+ deadline = null;
+ clock = null;
+ };
+
+ const fire = () => {
+ const at = from;
+ if (at == null) {
+ return;
+ }
+ cancel();
+ options.onLongPress({x: at.x, y: at.y});
+ };
+
+ // 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 = (event: LongPressTouchEvent | undefined) => {
+ const eventTime =
+ event == null ? undefined : timeOn(clock, event.timeStamp);
+ if (deadline != null && eventTime != null && eventTime >= deadline) {
+ fire();
+ }
+ };
+
+ const begin = (
+ point: {x: number; y: number},
+ tolerance: LongPressTolerance | undefined,
+ started: {at: number; clock: EventClock} | undefined,
+ ) => {
+ if (options.disabled === true) {
+ return;
+ }
+ cancel();
+ const delayMs = options.delayMs ?? DEFAULT_DELAY_MS;
+ from = {x: point.x, y: point.y};
+ pressTolerance = tolerance ?? null;
+ const pressClock = started?.clock ?? null;
+ const pressDeadline = started == null ? null : started.at + delayMs;
+ clock = pressClock;
+ deadline = pressDeadline;
+ // Wait only for the rest of the hold. A touch handled late then keeps its
+ // length, and the wait never passes the delay.
+ const remaining =
+ pressClock == null || pressDeadline == null
+ ? delayMs
+ : Math.min(delayMs, Math.max(0, pressDeadline - pressClock.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) => {
+ timer = null;
+ if (
+ mayYield &&
+ pressClock != null &&
+ pressDeadline != null &&
+ pressClock.now() > pressDeadline
+ ) {
+ timer = setTimeout(() => run(false), 0);
+ return;
+ }
+ fire();
+ };
+ timer = setTimeout(() => run(true), remaining);
+ };
+
+ const moveTo = (point: {x: number; y: number}): boolean => {
+ const at = from;
+ if (at == null) {
+ return false;
+ }
+ // This press's own tolerance when its caller chose one, on either axis.
+ const limit =
+ pressTolerance?.moveCancelPx ??
+ options.moveCancelPx ??
+ DEFAULT_MOVE_CANCEL_PX;
+ if (Math.abs(point.x - at.x) > limit || Math.abs(point.y - at.y) > limit) {
+ cancel();
+ return false;
+ }
+ return true;
+ };
+
+ return {
+ start(point, tolerance) {
+ begin(point, tolerance, undefined);
+ },
+ touchStart(event) {
+ if (options.disabled === true) {
+ return;
+ }
+ if (event.touches.length !== 1) {
+ // A second finger ends the press, unless the press was already due.
+ fireIfDue(event);
+ cancel();
+ return;
+ }
+ const touch = event.touches[0];
+ const touchClock = clockOf(event);
+ const at = timeOn(touchClock, event.timeStamp);
+ begin(
+ {x: touch.clientX, y: touch.clientY},
+ undefined,
+ touchClock == null || at == null ? undefined : {at, clock: touchClock},
+ );
+ },
+ touchMove(event) {
+ if (from == null) {
+ return;
+ }
+ fireIfDue(event);
+ if (from == null) {
+ return;
+ }
+ if (event.touches.length !== 1) {
+ cancel();
+ return;
+ }
+ const touch = event.touches[0];
+ moveTo({x: touch.clientX, y: touch.clientY});
+ },
+ touchEnd(event) {
+ fireIfDue(event);
+ cancel();
+ },
+ moveTo,
+ cancel,
+ isPending: () => from != null,
+ setOptions(next) {
+ options = next;
+ },
+ };
+}
diff --git a/packages/core/src/hooks/useLongPress.test.tsx b/packages/core/src/hooks/useLongPress.test.tsx
index ff4a22b62b..ab92e2d954 100644
--- a/packages/core/src/hooks/useLongPress.test.tsx
+++ b/packages/core/src/hooks/useLongPress.test.tsx
@@ -1,7 +1,14 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
-import {renderHook, act} from '@testing-library/react';
+import {
+ renderHook,
+ act,
+ render,
+ screen,
+ fireEvent,
+} from '@testing-library/react';
+import {Suspense, startTransition, use, useState} from 'react';
import {useLongPress} from './useLongPress';
// Minimal React.TouchEvent stand-in carrying only what the hook reads.
@@ -175,6 +182,23 @@ describe('useLongPress', () => {
expect(onLongPress).not.toHaveBeenCalled();
});
+ it('uses the options of the latest commit', () => {
+ const first = vi.fn();
+ const latest = vi.fn();
+ const {result, rerender} = renderHook(
+ (props: {disabled: boolean; onLongPress: () => void}) =>
+ useLongPress(props),
+ {initialProps: {disabled: true, onLongPress: first}},
+ );
+ rerender({disabled: false, onLongPress: latest});
+ act(() => {
+ result.current.start({x: 0, y: 0});
+ vi.advanceTimersByTime(500);
+ });
+ expect(first).not.toHaveBeenCalled();
+ expect(latest).toHaveBeenCalledTimes(1);
+ });
+
it('cancels the pending timer on unmount', () => {
const onLongPress = vi.fn();
const {result, unmount} = renderHook(() => useLongPress({onLongPress}));
@@ -208,6 +232,49 @@ describe('useLongPress', () => {
});
});
+describe('useLongPress options', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('keeps the committed options while a transition to new ones suspends', async () => {
+ const onLongPress = vi.fn();
+ const never = new Promise<void>(() => {});
+ let enable = () => {};
+ function Target({disabled}: {disabled: boolean}) {
+ const handlers = useLongPress({onLongPress, disabled});
+ if (!disabled) {
+ use(never);
+ }
+ return <div data-testid="target" {...handlers} />;
+ }
+ function Host() {
+ const [disabled, setDisabled] = useState(true);
+ enable = () => startTransition(() => setDisabled(false));
+ return (
+ <Suspense fallback={<div>loading</div>}>
+ <Target disabled={disabled} />
+ </Suspense>
+ );
+ }
+ render(<Host />);
+ await act(async () => {
+ enable();
+ });
+ // The transition suspended, so the disabled target is still on screen.
+ const target = screen.getByTestId('target');
+ act(() => {
+ fireEvent.touchStart(target, {touches: [{clientX: 0, clientY: 0}]});
+ vi.advanceTimersByTime(1000);
+ });
+ expect(onLongPress).not.toHaveBeenCalled();
+ });
+});
+
describe('useLongPress on the events\u2019 clock (spec:AST-094 FR16)', () => {
beforeEach(() => {
vi.useFakeTimers();
diff --git a/packages/core/src/hooks/useLongPress.ts b/packages/core/src/hooks/useLongPress.ts
index b1f4209c77..988f32273f 100644
--- a/packages/core/src/hooks/useLongPress.ts
+++ b/packages/core/src/hooks/useLongPress.ts
@@ -11,6 +11,7 @@
* `useMenuPress` for the held-finger menu open
*
* SYNC: When modified, update the hooks barrel /packages/core/src/hooks/index.ts
+ * and the detector it wraps, /packages/core/src/hooks/longPressDetector.ts
*/
// iOS Safari sends no `contextmenu` event on a long press. So a long press is
@@ -18,64 +19,24 @@
//
// A caller can spread the touch handlers, or call `start`, `moveTo` and
// `cancel` from its own pointer events, as `useMenuPress` does. Both ways use
-// this hook's hold time, movement tolerance and timer, so a long press means
-// the same thing on a context menu and on a menu trigger.
+// the hold time, movement tolerance and timer of createLongPressDetector. So a
+// long press means the same thing on a context menu and on a menu trigger.
//
// The defaults come from the long-press recognizer. The recognizer measures
// 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.
+// The hold is a deadline on the touch events' own clock (longPressDetector.ts).
-import {useCallback, useEffect, useRef} from 'react';
+import {useCallback, useEffect, useState} from 'react';
import {
- LONG_PRESS_ALLOWABLE_MOVEMENT_PX,
- LONG_PRESS_DURATION_MS,
-} from '../motion/uikit/longPress';
+ createLongPressDetector,
+ type LongPressTolerance,
+} from './longPressDetector';
+import {useIsomorphicLayoutEffect} from './useIsomorphicLayoutEffect';
-// The long-press numbers have one source, shared with the gesture
-// recognizers (motion/uikit/longPress.ts).
-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 type {LongPressTolerance};
export interface UseLongPressOptions {
/** Fired with the touch start point once the press is held for `delayMs`. */
@@ -88,14 +49,6 @@ export interface UseLongPressOptions {
moveCancelPx?: number;
}
-/**
- * @internal A press's own movement tolerance, for a core caller that decides
- * it as the press starts (useMenuPress's trigger). Not in the hooks entry.
- */
-export interface LongPressTolerance {
- moveCancelPx?: number;
-}
-
export interface UseLongPressHandlers {
onTouchStart: (e: React.TouchEvent) => void;
onTouchMove: (e: React.TouchEvent) => void;
@@ -153,186 +106,22 @@ export function useLongPress(
export function useLongPressDetector(
options: UseLongPressOptions,
): LongPressDetectorHandlers {
- 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);
- // 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.
- const onLongPressRef = useRef(onLongPress);
- onLongPressRef.current = onLongPress;
-
- const clear = useCallback(() => {
- if (timerRef.current != null) {
- clearTimeout(timerRef.current);
- timerRef.current = null;
- }
- startRef.current = null;
- deadlineRef.current = null;
- clockRef.current = null;
- }, []);
-
- 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;
- }
- // Clear a stale timer first, then record the start point. The clear
- // also sets startRef to null.
- clear();
- startRef.current = {x: point.x, y: point.y};
- pressToleranceRef.current = tolerance ?? 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;
- }
- fire();
- };
- timerRef.current = setTimeout(() => run(true), remaining);
- },
- [disabled, delayMs, clear, fire],
- );
-
- const start = useCallback(
- (point: {x: number; y: number}, tolerance?: LongPressTolerance) =>
- begin(point, tolerance, undefined),
- [begin],
- );
-
- const moveTo = useCallback(
- (point: {x: number; y: number}): boolean => {
- const from = startRef.current;
- if (from == null) {
- return false;
- }
- // This press's own tolerance when its caller chose one, on either axis.
- const limit = pressToleranceRef.current?.moveCancelPx ?? moveCancelPx;
- if (
- Math.abs(point.x - from.x) > limit ||
- Math.abs(point.y - from.y) > limit
- ) {
- clear();
- return false;
- }
- return true;
- },
- [moveCancelPx, clear],
- );
-
- const onTouchStart = useCallback(
- (e: React.TouchEvent) => {
- if (disabled) {
- 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];
- 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, begin, fireIfDue],
- );
-
- const onTouchMove = useCallback(
- (e: React.TouchEvent) => {
- if (startRef.current == null) {
- return;
- }
- fireIfDue(e);
- if (startRef.current == null) {
- return;
- }
- if (e.touches.length !== 1) {
- clear();
- return;
- }
- const touch = e.touches[0];
- moveTo({x: touch.clientX, y: touch.clientY});
- },
- [clear, moveTo, fireIfDue],
- );
-
- const onTouchEnd = useCallback(
- (e?: React.TouchEvent) => {
- fireIfDue(e);
- clear();
- },
- [clear, fireIfDue],
- );
-
- useEffect(() => clear, [clear]);
+ const [detector] = useState(() => createLongPressDetector(options));
+ // The detector reads only committed options. A render that React discards
+ // never reaches it.
+ useIsomorphicLayoutEffect(() => {
+ detector.setOptions(options);
+ });
+ // The detector's pending timer ends with the component.
+ useEffect(() => detector.cancel, [detector]);
return {
- onTouchStart,
- onTouchMove,
- onTouchEnd,
- onTouchCancel: onTouchEnd,
- start,
- moveTo,
- cancel: clear,
+ onTouchStart: detector.touchStart,
+ onTouchMove: detector.touchMove,
+ onTouchEnd: detector.touchEnd,
+ onTouchCancel: detector.touchEnd,
+ start: detector.start,
+ moveTo: detector.moveTo,
+ cancel: detector.cancel,
};
}