Skip to content

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

TypeScript

feat(core): useFingerScroll tells its caller when a finger's scroll ends (#10172)

Cindy Zhangf5cf9a5914cd
diff --git a/.changeset/finger-scroll-end.md b/.changeset/finger-scroll-end.md
new file mode 100644
index 0000000000..cc627a04f2
--- /dev/null
+++ b/.changeset/finger-scroll-end.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: `useFingerScroll(scroller, {onEnd})` calls `onEnd` each time a finger's scroll on the scroller ends, and the hook is re-exported from the internal touch subpath for Lab components that watch a finger's scroll. Internal entries are outside the public API and its compatibility promise; the hook is not exported from the package entry point or the gestures barrel.
+
+@cixzhang
diff --git a/docs/architecture/react-component-runtime.md b/docs/architecture/react-component-runtime.md
index 7944940789..4e414f2a4a 100644
--- a/docs/architecture/react-component-runtime.md
+++ b/docs/architecture/react-component-runtime.md
@@ -319,7 +319,9 @@ those contracts.
`@astryxdesign/core/internal/touch`, a subpath reserved for Astryx's own
packages: undocumented, outside the compatibility promise, versioned in
lockstep with Core, and limited by lint to Core and Lab (`spec:AST-017`
- FR21).
+ FR21). The finger-scroll watch's hook, `useFingerScroll`, is on that
+ subpath: it reports whether a scroller's scroll is a finger's and, through
+ `onEnd`, when that scroll ends.
- **INV15 — The animator animates a number.** The animator has a value mode:
it plays a number, such as a count or a chart value, on the same timing as its property channels: theme motion tokens for a program-started change, and measured springs only where `spec:AST-094` FR45 keeps them, and hands the value to an `onUpdate`
callback each frame for the component to format and write. The component owns
diff --git a/packages/core/src/gestures/README.md b/packages/core/src/gestures/README.md
index 95edc28f95..f2e2a3bb75 100644
--- a/packages/core/src/gestures/README.md
+++ b/packages/core/src/gestures/README.md
@@ -75,7 +75,10 @@ function Sheet() {
while a finger that landed inside it is down, until its `scrollend` (the
momentum is still the finger's), or, where the browser fires none (mobile
Safari before 26), until its scroll events go quiet. Pass a ref, or the
- document for the page. Outside React, `watchFingerScrolls(host, scroller)` and
+ document for the page. `options.onEnd` runs each time such a scroll ends,
+ once the reader says `false`; unmounting does not call it. It is
+ re-exported from `@astryxdesign/core/internal/touch` for Lab components
+ that watch a finger's scroll. Outside React, `watchFingerScrolls(host, scroller)` and
`isFingerScroll(host, scroller)` from `fingerScroll.ts` do the same; that
module adds passive scroll listeners only while something is watched.
diff --git a/packages/core/src/gestures/__tests__/useFingerScroll.test.tsx b/packages/core/src/gestures/__tests__/useFingerScroll.test.tsx
index ea484425d0..f38b02ea68 100644
--- a/packages/core/src/gestures/__tests__/useFingerScroll.test.tsx
+++ b/packages/core/src/gestures/__tests__/useFingerScroll.test.tsx
@@ -7,17 +7,18 @@
* @output A finger's scroll reads true until the scroller's scrollend; a
* scroll with no finger down reads false; the page's own scroll through
* the document; the watch follows the ref's node and ends on unmount, and
- * lets go of a node it stops following
+ * lets go of a node it stops following; onEnd runs once per finger scroll
+ * on each end path, for each watcher, and never on unmount
* @position Unit tests of packages/core/src/gestures/useFingerScroll.ts
*/
import {render} from '@testing-library/react';
import {useRef} from 'react';
-import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {isFingerScroll} from '../fingerScroll';
import {getGestureHost} from '../GestureHost';
import {useFingerScroll} from '../useFingerScroll';
-import {coarsePrimaryPointer} from './pointerQuery';
+import {coarsePrimaryPointer, pointerQuery} from './pointerQuery';
function touch(type: string, target: Element, down: boolean): void {
const event = new Event(type, {bubbles: true, cancelable: true});
@@ -71,6 +72,39 @@ function Follower() {
return null;
}
+/** A list that counts its finger scrolls' ends, and what it read then. */
+const ends: {count: number; readAtEnd: boolean[]} = {count: 0, readAtEnd: []};
+
+function EndingList({watchers = 1}: {watchers?: number}) {
+ const ref = useRef<HTMLDivElement>(null);
+ const onEnd = () => {
+ ends.count += 1;
+ ends.readAtEnd.push(read());
+ };
+ read = useFingerScroll(ref, {onEnd});
+ // The second watcher renders after the list, so the list's ref is set
+ // when its attachment runs.
+ return (
+ <>
+ <div ref={ref} data-testid="list">
+ <p data-testid="row">row</p>
+ </div>
+ {watchers > 1 && <SecondWatcher scroller={ref} onEnd={onEnd} />}
+ </>
+ );
+}
+
+function SecondWatcher({
+ scroller,
+ onEnd,
+}: {
+ scroller: {current: Element | null};
+ onEnd: () => void;
+}) {
+ useFingerScroll(scroller, {onEnd});
+ return null;
+}
+
function Page() {
read = useFingerScroll(document);
return <p data-testid="row">row</p>;
@@ -184,4 +218,102 @@ describe('useFingerScroll', () => {
second.element.remove();
}
});
+
+ describe('onEnd', () => {
+ beforeEach(() => {
+ ends.count = 0;
+ ends.readAtEnd = [];
+ });
+
+ it("runs once at the scroller's scrollend after the lift, with the reader already false", () => {
+ const {getByTestId} = render(<EndingList />);
+ const list = getByTestId('list');
+ fingerScroll(list, getByTestId('row'));
+ touch('touchend', getByTestId('row'), false);
+ list.dispatchEvent(new Event('scroll'));
+ expect(ends.count).toBe(0);
+ list.dispatchEvent(new Event('scrollend'));
+ expect(ends.count).toBe(1);
+ expect(ends.readAtEnd).toEqual([false]);
+ list.dispatchEvent(new Event('scrollend'));
+ expect(ends.count).toBe(1);
+ });
+
+ it('runs at the lift when the scroll ended under a resting finger', () => {
+ const {getByTestId} = render(<EndingList />);
+ const list = getByTestId('list');
+ fingerScroll(list, getByTestId('row'));
+ list.dispatchEvent(new Event('scrollend'));
+ expect(ends.count).toBe(0);
+ touch('touchend', getByTestId('row'), false);
+ expect(ends.count).toBe(1);
+ });
+
+ it('runs after the quiet fallback where the browser fires no scrollend', () => {
+ // A browser with no scrollend (mobile Safari before 26): take jsdom's
+ // handler slot away for this test.
+ let owner: object | null = window;
+ while (owner != null && !Object.hasOwn(owner, 'onscrollend')) {
+ owner = Object.getPrototypeOf(owner) as object | null;
+ }
+ const slot =
+ owner == null
+ ? undefined
+ : Object.getOwnPropertyDescriptor(owner, 'onscrollend');
+ if (owner != null) {
+ delete (owner as Record<string, unknown>).onscrollend;
+ }
+ vi.useFakeTimers();
+ try {
+ expect('onscrollend' in window).toBe(false);
+ const {getByTestId} = render(<EndingList />);
+ const list = getByTestId('list');
+ fingerScroll(list, getByTestId('row'));
+ touch('touchend', getByTestId('row'), false);
+ vi.advanceTimersByTime(149);
+ expect(ends.count).toBe(0);
+ vi.advanceTimersByTime(1);
+ expect(ends.count).toBe(1);
+ expect(ends.readAtEnd).toEqual([false]);
+ } finally {
+ vi.useRealTimers();
+ if (owner != null && slot != null) {
+ Object.defineProperty(owner, 'onscrollend', slot);
+ }
+ }
+ });
+
+ it('runs when the primary pointer stops being coarse mid-scroll', () => {
+ restorePointer();
+ const pointer = pointerQuery(true);
+ restorePointer = pointer.restore;
+ const {getByTestId} = render(<EndingList />);
+ fingerScroll(getByTestId('list'), getByTestId('row'));
+ pointer.set(false);
+ expect(ends.count).toBe(1);
+ expect(ends.readAtEnd).toEqual([false]);
+ touch('touchend', getByTestId('row'), false);
+ });
+
+ it('gives two watchers of one scroller one call each per finger scroll', () => {
+ const {getByTestId} = render(<EndingList watchers={2} />);
+ const list = getByTestId('list');
+ fingerScroll(list, getByTestId('row'));
+ lift(list, getByTestId('row'));
+ expect(ends.count).toBe(2);
+ fingerScroll(list, getByTestId('row'));
+ lift(list, getByTestId('row'));
+ expect(ends.count).toBe(4);
+ });
+
+ it('does not run on unmount, even mid-scroll', () => {
+ const {getByTestId, unmount} = render(<EndingList />);
+ const row = getByTestId('row');
+ fingerScroll(getByTestId('list'), row);
+ unmount();
+ expect(ends.count).toBe(0);
+ touch('touchend', row, false);
+ expect(ends.count).toBe(0);
+ });
+ });
});
diff --git a/packages/core/src/gestures/fingerScroll.ts b/packages/core/src/gestures/fingerScroll.ts
index 1e429e2a22..b6f9e7b9c9 100644
--- a/packages/core/src/gestures/fingerScroll.ts
+++ b/packages/core/src/gestures/fingerScroll.ts
@@ -5,7 +5,8 @@
* @input A scroller (an element, or the document for the page's own scroll),
* its document's scroll and scrollend events, and the gesture host's
* finger record
- * @output Exports watchFingerScrolls and isFingerScroll
+ * @output Exports watchFingerScrolls and isFingerScroll; a watcher can ask to
+ * be told when a finger's scroll ends
* @position Finger-scroll watch of packages/core/src/gestures (useFingerScroll
* reads it), in its own module so a page that never asks never ships it;
* internal to the touch module, not in the gestures barrel
@@ -40,11 +41,27 @@ interface Watch {
readonly fingerScrollers: Set<Node>;
/** Finger scrolls whose `scrollend` came while the finger still rested. */
readonly endedWhileDown: Set<Node>;
+ /** Per scroller, the watchers to tell when its finger scroll ends. */
+ readonly endListeners: Map<Node, Set<() => void>>;
stop: (() => void) | null;
}
const watches = new WeakMap<GestureHost, Watch>();
+/**
+ * A scroller's finger scroll is over: it stops counting as the finger's, and
+ * then its end listeners hear of it, so a listener that reads
+ * isFingerScroll already reads false.
+ */
+function endFingerScroll(watch: Watch, scroller: Node): void {
+ if (!watch.fingerScrollers.delete(scroller)) {
+ return;
+ }
+ for (const listener of [...(watch.endListeners.get(scroller) ?? [])]) {
+ listener();
+ }
+}
+
function start(host: GestureHost, watch: Watch): () => void {
const doc = host.document;
const scrollerOf = (event: Event): Node | null => {
@@ -61,7 +78,7 @@ function start(host: GestureHost, watch: Watch): () => void {
// The finger still rests there: the scroll is its until the lift.
watch.endedWhileDown.add(scroller);
} else {
- watch.fingerScrollers.delete(scroller);
+ endFingerScroll(watch, scroller);
}
};
const scrollEndFallbacks = new Map<Node, ReturnType<typeof setTimeout>>();
@@ -113,7 +130,7 @@ function start(host: GestureHost, watch: Watch): () => void {
for (const scroller of watch.endedWhileDown) {
if (!host.isFingerDownIn(scroller)) {
watch.endedWhileDown.delete(scroller);
- watch.fingerScrollers.delete(scroller);
+ endFingerScroll(watch, scroller);
}
}
};
@@ -139,8 +156,12 @@ function start(host: GestureHost, watch: Watch): () => void {
for (const scroller of [...scrollEndFallbacks.keys()]) {
clearScrollEndFallback(scroller);
}
- watch.fingerScrollers.clear();
+ // No finger scrolls once the pointer is no longer coarse: each one in
+ // progress ends here.
watch.endedWhileDown.clear();
+ for (const scroller of [...watch.fingerScrollers]) {
+ endFingerScroll(watch, scroller);
+ }
}
};
const stopWatchingPointer = watchCoarsePointer(view, listen);
@@ -158,12 +179,17 @@ function start(host: GestureHost, watch: Watch): () => void {
/**
* Keep track of whether the scrolls of `scroller` (an element in `host`'s
* document, or the document itself) are a finger's, for isFingerScroll,
- * until the returned function runs.
+ * until the returned function runs. `onEnd`, when given, runs each time a
+ * finger's scroll on the scroller ends (its `scrollend` after the lift, the
+ * lift after a `scrollend` that came while the finger rested, the quiet
+ * fallback, or the pointer turning fine), after isFingerScroll turns false.
+ * Stopping the watch does not call it.
* Internal: not exported from the package.
*/
export function watchFingerScrolls(
host: GestureHost,
scroller: Node,
+ onEnd?: () => void,
): () => void {
let watch = watches.get(host);
if (watch == null) {
@@ -171,12 +197,21 @@ export function watchFingerScrolls(
scrollers: new Map(),
fingerScrollers: new Set(),
endedWhileDown: new Set(),
+ endListeners: new Map(),
stop: null,
};
watches.set(host, watch);
}
const owned = watch;
owned.scrollers.set(scroller, (owned.scrollers.get(scroller) ?? 0) + 1);
+ // Each watch registers its own listener, so two watchers of one scroller
+ // each hear every end once.
+ const listener = onEnd == null ? null : () => onEnd();
+ if (listener != null) {
+ const listeners = owned.endListeners.get(scroller) ?? new Set();
+ listeners.add(listener);
+ owned.endListeners.set(scroller, listeners);
+ }
owned.stop ??= start(host, owned);
let isWatching = true;
return () => {
@@ -184,6 +219,13 @@ export function watchFingerScrolls(
return;
}
isWatching = false;
+ if (listener != null) {
+ const listeners = owned.endListeners.get(scroller);
+ listeners?.delete(listener);
+ if (listeners?.size === 0) {
+ owned.endListeners.delete(scroller);
+ }
+ }
const count = (owned.scrollers.get(scroller) ?? 1) - 1;
if (count > 0) {
owned.scrollers.set(scroller, count);
diff --git a/packages/core/src/gestures/useFingerScroll.ts b/packages/core/src/gestures/useFingerScroll.ts
index 51224e7f89..2d1cf15de1 100644
--- a/packages/core/src/gestures/useFingerScroll.ts
+++ b/packages/core/src/gestures/useFingerScroll.ts
@@ -7,7 +7,7 @@
* @input A scroller (a ref to an element, or the document for the page) and
* the document's gesture host
* @output useFingerScroll: whether the scroller's current scroll is a
- * finger's, read at any moment
+ * finger's, read at any moment, and an optional call when one ends
* @position Gesture hook of packages/core/src/gestures, over the
* finger-scroll watch (fingerScroll.ts), kept on the scroller's node by
* the gesture hooks' shared attachment (hooks/useAttachment.ts). An internal
@@ -33,6 +33,7 @@ import {useCallback, useRef, type RefObject} from 'react';
import {isFingerScroll, watchFingerScrolls} from './fingerScroll';
import {getGestureHost} from './GestureHost';
import {useAttachment} from '../hooks/useAttachment';
+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
function isDocument(value: unknown): value is Document {
return typeof Document !== 'undefined' && value instanceof Document;
@@ -43,6 +44,18 @@ function documentOf(node: Element | Document): Document {
return isDocument(node) ? node : node.ownerDocument;
}
+export interface UseFingerScrollOptions {
+ /**
+ * Runs each time a finger's scroll on the scroller ends, once the reader
+ * says `false`: at its `scrollend` after the lift (the momentum is still
+ * the finger's), at the lift when the scroll ended under a resting finger,
+ * after the quiet fallback where the browser fires no `scrollend`, or when
+ * the primary pointer stops being coarse. Unmounting, or the scroller
+ * changing, does not call it. The latest function is the one called.
+ */
+ onEnd?: () => void;
+}
+
/**
* Watch a scroller's finger scrolls. Pass a ref to a scrolling element, or
* the document for the page's own scroll. Returns a reader, stable across
@@ -51,9 +64,16 @@ function documentOf(node: Element | Document): Document {
*/
export function useFingerScroll(
scroller: RefObject<Element | null> | Document,
+ {onEnd}: UseFingerScrollOptions = {},
): () => boolean {
/** The node the watch is on now, for the reader. */
const watchedRef = useRef<Element | Document | null>(null);
+ // The watch outlives renders, so it calls the latest onEnd through a ref
+ // written at commit.
+ const onEndRef = useRef(onEnd);
+ useIsomorphicLayoutEffect(function keepLatestOnEnd() {
+ onEndRef.current = onEnd;
+ });
// Keeps the finger-scroll watch on the node the scroller names after each
// commit (useAttachment): a ref that now points at another element moves
// the watch to it, and unmounting releases it.
@@ -61,7 +81,11 @@ export function useFingerScroll(
isDocument(scroller) ? {current: scroller} : scroller,
node => {
watchedRef.current = node;
- const stop = watchFingerScrolls(getGestureHost(documentOf(node)), node);
+ const stop = watchFingerScrolls(
+ getGestureHost(documentOf(node)),
+ node,
+ () => onEndRef.current?.(),
+ );
return () => {
stop();
watchedRef.current = null;
diff --git a/packages/core/src/internal/touch.test.ts b/packages/core/src/internal/touch.test.ts
index 8c7d5dd507..29b43412da 100644
--- a/packages/core/src/internal/touch.test.ts
+++ b/packages/core/src/internal/touch.test.ts
@@ -84,6 +84,13 @@ describe('internal/touch', () => {
}
});
+ it('re-exports by name the finger-scroll watch Lab components read', async () => {
+ const entry: Record<string, unknown> = await import('./touch');
+ const fingerScroll = await import('../gestures/useFingerScroll');
+ expect(entry.useFingerScroll).toBe(fingerScroll.useFingerScroll);
+ expect(typeof entry.useFingerScroll).toBe('function');
+ });
+
it("re-exports by name what Lab's NavigationStack reads", async () => {
const entry: Record<string, unknown> = await import('./touch');
const edgePan = await import('../gestures/ScreenEdgePanGestureRecognizer');
diff --git a/packages/core/src/internal/touch.ts b/packages/core/src/internal/touch.ts
index 7510fb184e..b7a33df704 100644
--- a/packages/core/src/internal/touch.ts
+++ b/packages/core/src/internal/touch.ts
@@ -95,3 +95,8 @@ export {
} from '../motion/uikit/springs';
export {focusForLastInput, isFocusLost} from '../utils/focusReturn';
export {useInteractionModalityTracking} from '../utils/interactionModality';
+
+// Lab components that watch a finger's scroll read whether a scroller's
+// scroll is a finger's, and act when that scroll ends.
+export {useFingerScroll} from '../gestures/useFingerScroll';
+export type {UseFingerScrollOptions} from '../gestures/useFingerScroll';
diff --git a/scripts/touch-support-bundle.test.mjs b/scripts/touch-support-bundle.test.mjs
index 84ef5eb4b1..ff97b8737f 100644
--- a/scripts/touch-support-bundle.test.mjs
+++ b/scripts/touch-support-bundle.test.mjs
@@ -117,11 +117,13 @@ function exportsOf(entry) {
* and its query, and an element's direction. Lab's NavigationStack reads the
* screen-edge pan, the spring solver, the motion resolver, UIKit's
* navigation table and its four navigation springs. It also reads the focus
- * helpers that follow the last input.
+ * helpers that follow the last input. Lab components that watch a finger's
+ * scroll read the finger-scroll watch.
*/
const LAB_ONLY_NAMES = [
'PanGestureRecognizer',
'useGestureRecognizer',
+ 'useFingerScroll',
'createMotionEngine',
'cubicBezier',
'mapProgress',