Skip to content

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

TypeScript

fix(BottomSheet): a drag reads its release from Core's tracker (#10463)

Christopher Chedeau0a656fe4e92a
diff --git a/.changeset/bottom-sheet-release-velocity-tracker.md b/.changeset/bottom-sheet-release-velocity-tracker.md
new file mode 100644
index 0000000000..7ebc110c44
--- /dev/null
+++ b/.changeset/bottom-sheet-release-velocity-tracker.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] BottomSheet: a drag reads its release velocity from Core's velocity tracker, on each event's own timestamp, also when a touch drag starts on the sheet's content. The release depends on the last two moves, so a move that reaches the page late earlier in a flick no longer slows the flick. A hold weighs on the first move after it, as iOS's filter does. Two rules differ from iOS: a finger that holds still for more than 40 ms before the lift releases nothing in motion, and a release needs two moves.
+
+@vjeux
diff --git a/packages/core/src/BottomSheet/BottomSheet.test.tsx b/packages/core/src/BottomSheet/BottomSheet.test.tsx
index 864cfcaace..3e1f442d37 100644
--- a/packages/core/src/BottomSheet/BottomSheet.test.tsx
+++ b/packages/core/src/BottomSheet/BottomSheet.test.tsx
@@ -319,30 +319,32 @@ function getHandle(): HTMLElement {
// Drive a pointer drag on the grab handle. jsdom PointerEvents don't carry
// clientY, so dispatch plain events with the coords the handlers read.
+// One clock for the drags: each event comes 16 ms after the one before, so
+// a drag's release velocity follows its events' own timestamps.
+let dragTime = 0;
+
function drag(
handle: HTMLElement,
points: {y: number}[],
pointerType: 'mouse' | 'touch' | 'pen' = 'mouse',
) {
const [down, ...rest] = points;
- fireEvent.pointerDown(handle, {
- pointerId: 1,
- clientY: down.y,
- button: 0,
- isPrimary: true,
- pointerType,
- });
+ const at = (y: number) => {
+ dragTime += 16;
+ return {time: dragTime, y, pointerType};
+ };
+ fireTimedPointer(handle, 'pointerdown', at(down.y));
for (const p of rest) {
- fireEvent.pointerMove(handle, {pointerId: 1, clientY: p.y, pointerType});
+ fireTimedPointer(handle, 'pointermove', at(p.y));
}
const last = points[points.length - 1];
- fireEvent.pointerUp(handle, {pointerId: 1, clientY: last.y, pointerType});
+ fireTimedPointer(handle, 'pointerup', at(last.y));
}
function fireTimedPointer(
target: Element,
type: 'pointerdown' | 'pointermove' | 'pointerup',
- {time, y}: {time: number; y: number},
+ {time, y, pointerType}: {time: number; y: number; pointerType?: string},
) {
const event = new Event(type, {bubbles: true, cancelable: true});
Object.defineProperties(event, {
@@ -352,6 +354,9 @@ function fireTimedPointer(
pointerId: {value: 1},
timeStamp: {value: time},
});
+ if (pointerType != null) {
+ Object.defineProperty(event, 'pointerType', {value: pointerType});
+ }
return fireEvent(target, event);
}
diff --git a/packages/core/src/BottomSheet/BottomSheetDragExit.test.tsx b/packages/core/src/BottomSheet/BottomSheetDragExit.test.tsx
index ed9500653e..58cab0eb23 100644
--- a/packages/core/src/BottomSheet/BottomSheetDragExit.test.tsx
+++ b/packages/core/src/BottomSheet/BottomSheetDragExit.test.tsx
@@ -176,19 +176,41 @@ function getHandle(label = 'Sheet'): HTMLElement {
return handle;
}
+// Pointer events on one clock, 16 ms apart, so a drag's release velocity
+// follows its events' own timestamps.
+let pointerTime = 0;
+
+function firePointer(
+ target: Element,
+ type: 'pointerdown' | 'pointermove' | 'pointerup',
+ init: {pointerId: number; clientY: number; pointerType?: string},
+) {
+ pointerTime += 16;
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ Object.defineProperties(event, {
+ button: {value: 0},
+ clientY: {value: init.clientY},
+ isPrimary: {value: true},
+ pointerId: {value: init.pointerId},
+ timeStamp: {value: pointerTime},
+ });
+ if (init.pointerType != null) {
+ Object.defineProperty(event, 'pointerType', {value: init.pointerType});
+ }
+ fireEvent(target, event);
+}
+
/** A fast downward touch drag on the handle: a flick, which closes the sheet. */
function flickDown(label = 'Sheet') {
const handle = getHandle(label);
- fireEvent.pointerDown(handle, {
+ firePointer(handle, 'pointerdown', {
pointerId: 1,
pointerType: 'touch',
clientY: 0,
- button: 0,
- isPrimary: true,
});
- fireEvent.pointerMove(handle, {pointerId: 1, clientY: 40});
- fireEvent.pointerMove(handle, {pointerId: 1, clientY: 120});
- fireEvent.pointerUp(handle, {pointerId: 1, clientY: 120});
+ firePointer(handle, 'pointermove', {pointerId: 1, clientY: 40});
+ firePointer(handle, 'pointermove', {pointerId: 1, clientY: 120});
+ firePointer(handle, 'pointerup', {pointerId: 1, clientY: 120});
}
it('plays the close spring when a drag closes the sheet', () => {
@@ -336,16 +358,14 @@ it("leaves the scrim's fade alone when a mouse drag closes the sheet", () => {
render(<Host />);
layOutSheet();
const handle = getHandle();
- fireEvent.pointerDown(handle, {
+ firePointer(handle, 'pointerdown', {
pointerId: 2,
pointerType: 'mouse',
clientY: 0,
- button: 0,
- isPrimary: true,
});
- fireEvent.pointerMove(handle, {pointerId: 2, clientY: 200});
- fireEvent.pointerMove(handle, {pointerId: 2, clientY: 390});
- fireEvent.pointerUp(handle, {pointerId: 2, clientY: 390});
+ firePointer(handle, 'pointermove', {pointerId: 2, clientY: 200});
+ firePointer(handle, 'pointermove', {pointerId: 2, clientY: 390});
+ firePointer(handle, 'pointerup', {pointerId: 2, clientY: 390});
expect(exits).toHaveLength(0);
expect(scrimFade()).toBe('');
});
diff --git a/packages/core/src/BottomSheet/BottomSheetStacking.test.tsx b/packages/core/src/BottomSheet/BottomSheetStacking.test.tsx
index c311eeed56..73841c57d4 100644
--- a/packages/core/src/BottomSheet/BottomSheetStacking.test.tsx
+++ b/packages/core/src/BottomSheet/BottomSheetStacking.test.tsx
@@ -281,20 +281,33 @@ function fireCancel(dialog: Element): Event {
}
// Drive a pointer drag on a grab handle. jsdom PointerEvents don't carry
-// clientY, so dispatch plain events with the coords the handlers read.
+// clientY, so dispatch plain events with the coords the handlers read. Each
+// event comes 16 ms after the one before, so the release velocity follows
+// the events' own timestamps.
+let dragTime = 0;
+
function drag(handle: HTMLElement, points: {y: number}[]) {
+ const fire = (
+ type: 'pointerdown' | 'pointermove' | 'pointerup',
+ y: number,
+ ) => {
+ dragTime += 16;
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ Object.defineProperties(event, {
+ button: {value: 0},
+ clientY: {value: y},
+ isPrimary: {value: true},
+ pointerId: {value: 1},
+ timeStamp: {value: dragTime},
+ });
+ fireEvent(handle, event);
+ };
const [down, ...rest] = points;
- fireEvent.pointerDown(handle, {
- pointerId: 1,
- clientY: down.y,
- button: 0,
- isPrimary: true,
- });
+ fire('pointerdown', down.y);
for (const point of rest) {
- fireEvent.pointerMove(handle, {pointerId: 1, clientY: point.y});
+ fire('pointermove', point.y);
}
- const last = points[points.length - 1];
- fireEvent.pointerUp(handle, {pointerId: 1, clientY: last.y});
+ fire('pointerup', points[points.length - 1].y);
}
function classes(element: Element): string {
diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx b/packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx
index 7a93a0df38..1ff819e440 100644
--- a/packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx
+++ b/packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx
@@ -495,6 +495,30 @@ function mockSheetTop(sheet: HTMLElement, top: number) {
}
}
+// A fast downward drag on a handle: two moves, 16 ms apart on the events'
+// own timestamps, so it releases at 3,750 px/s.
+let flickTime = 0;
+
+function flick(handle: HTMLElement) {
+ for (const [type, y] of [
+ ['pointerdown', 0],
+ ['pointermove', 60],
+ ['pointermove', 120],
+ ['pointerup', 120],
+ ] as const) {
+ flickTime += 16;
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ Object.defineProperties(event, {
+ button: {value: 0},
+ clientY: {value: y},
+ isPrimary: {value: true},
+ pointerId: {value: 1},
+ timeStamp: {value: flickTime},
+ });
+ fireEvent(handle, event);
+ }
+}
+
describe('BottomSheetSwitcher', () => {
it('opens only the sheet selected by activeSheet', () => {
render(<Flow />);
@@ -979,14 +1003,7 @@ describe('BottomSheetSwitcher', () => {
}
fireEvent.click(dialog);
- fireEvent.pointerDown(handle, {
- pointerId: 1,
- clientY: 0,
- button: 0,
- isPrimary: true,
- });
- fireEvent.pointerMove(handle, {pointerId: 1, clientY: 120});
- fireEvent.pointerUp(handle, {pointerId: 1, clientY: 120});
+ flick(handle);
expect(onActiveSheetChange).not.toHaveBeenCalled();
expect(dialog).toHaveStyle({'--_sheet-scrim-opacity': '1'});
@@ -1049,14 +1066,7 @@ describe('BottomSheetSwitcher', () => {
fireEvent.click(dialog);
fireEvent.keyDown(dialog, {key: 'Escape'});
fireEvent(dialog, new Event('cancel', {cancelable: true}));
- fireEvent.pointerDown(handle, {
- pointerId: 1,
- clientY: 0,
- button: 0,
- isPrimary: true,
- });
- fireEvent.pointerMove(handle, {pointerId: 1, clientY: 120});
- fireEvent.pointerUp(handle, {pointerId: 1, clientY: 120});
+ flick(handle);
expect(onActiveSheetChange).not.toHaveBeenCalled();
expect(dialog).toHaveStyle({'--_sheet-scrim-opacity': '1'});
diff --git a/packages/core/src/BottomSheet/__tests__/BottomSheetDetent.interaction.browser.spec.ts b/packages/core/src/BottomSheet/__tests__/BottomSheetDetent.interaction.browser.spec.ts
index 885b04c609..4599cef805 100644
--- a/packages/core/src/BottomSheet/__tests__/BottomSheetDetent.interaction.browser.spec.ts
+++ b/packages/core/src/BottomSheet/__tests__/BottomSheetDetent.interaction.browser.spec.ts
@@ -4,12 +4,13 @@
* @file BottomSheetDetent.interaction.browser.spec.ts
* @input The built "Snap points" BottomSheet story, real touch input
* (Chromium CDP / WebKit's input command) and the interaction harness
- * @output Interaction and animation proofs for dragging the sheet to a
- * detent: the drag follows the finger and a slow release settles on the
- * nearest detent; a flick dismisses; the settle lands on the detent, its
- * sampled curve recorded; the settle keeps advancing every frame through a blocked
- * main thread; the settle does no Layout or Paint per frame; a storyboard of
- * the drag and the settle.
+ * @output Interaction and animation proofs for dragging the sheet to a detent.
+ * The drag follows the finger, and a slow release settles on the nearest
+ * detent. A flick dismisses. A softer flick lands on the half detent, also
+ * when one early move arrives late. The settle lands on the detent, its
+ * sampled curve recorded. It keeps advancing every frame through a blocked
+ * main thread, and does no Layout or Paint per frame. A storyboard shows the
+ * drag and the settle.
* @position The exemplar for `*.interaction.browser.spec.ts`: component lanes
* copy this shape. Each test names the instrument it uses from
* @astryxdesign/interaction-harness, so the evidence layer is explicit.
@@ -70,6 +71,16 @@ import {
const storybook = withStorybook(test);
+// How far a flick's release, as WebKit stamps its touches on arrival, may
+// stray from the script's before the play fails by name. Each keeps the
+// release where the test's landing holds.
+// 1,200 px/s from tall: the script reads 1,225. It lands on half from the
+// flick speed, 1,008, up to 2,048, where its projection passes half.
+const HALF_FLICK_TOLERANCE = 0.17;
+// 2,000 px/s from tall, 160 px of travel: the 0.1 s projection passes half
+// above 1,409 px/s.
+const DISMISS_FLICK_TOLERANCE = 0.29;
+
// The settle's timing, from the theme the story renders in: `--ease-standard`
// is the default cubic-bezier(0.24, 1, 0.4, 1), and `--duration-medium` is the
// neutral theme's motion `medium` (300 ms; the base theme's is 410 ms).
@@ -186,7 +197,10 @@ test('a downward flick dismisses the sheet', async ({page}) => {
hz: 120,
});
expect(releaseVelocity(script).y).toBeCloseTo(2000, -1);
- await driver.play(script);
+ await driver.play(script, {
+ pacing: 'spacing',
+ releaseTolerance: DISMISS_FLICK_TOLERANCE,
+ });
await expect(page.getByRole('dialog', {name: 'Nearby places'})).toBeHidden();
});
@@ -202,7 +216,41 @@ test('a softer downward flick from the tall detent lands on the half detent', as
hz: 120,
});
expect(releaseVelocity(script).y).toBeCloseTo(1200, -1);
- await driver.play(script);
+ await driver.play(script, {
+ pacing: 'spacing',
+ releaseTolerance: HALF_FLICK_TOLERANCE,
+ });
+ await waitForRest(sheet);
+ await expect(page.getByRole('dialog', {name: 'Nearby places'})).toBeVisible();
+ expect(await sheetTop(sheet)).toBeCloseTo(halfTop, 0);
+});
+
+test('a softer flick with one early move 70 ms late still lands on the half detent', async ({
+ page,
+ browserName,
+}) => {
+ test.skip(
+ browserName !== 'webkit',
+ 'only WebKit stamps a touch when it arrives; Chromium carries the scripted times',
+ );
+ const {driver, sheet, handle, halfTop} = await openSheet(page);
+ const script = flick(handle, {
+ velocity: {x: 0, y: 1200},
+ durationMs: 80,
+ hz: 120,
+ });
+ // The move after this step reaches the page 70 ms late, as a stalled
+ // dispatch delivers it. The last two moves keep their spacing.
+ const late = toTouchEvents(script).length - 5;
+ await driver.play(script, {
+ pacing: 'spacing',
+ releaseTolerance: HALF_FLICK_TOLERANCE,
+ onEvent: async (_, index) => {
+ if (index === late) {
+ await new Promise(resolve => setTimeout(resolve, 70));
+ }
+ },
+ });
await waitForRest(sheet);
await expect(page.getByRole('dialog', {name: 'Nearby places'})).toBeVisible();
expect(await sheetTop(sheet)).toBeCloseTo(halfTop, 0);
diff --git a/packages/core/src/BottomSheet/useSheetGestures.test.ts b/packages/core/src/BottomSheet/useSheetGestures.test.ts
index a917aab7f0..6bbd90d004 100644
--- a/packages/core/src/BottomSheet/useSheetGestures.test.ts
+++ b/packages/core/src/BottomSheet/useSheetGestures.test.ts
@@ -113,6 +113,8 @@ function touchDown(hook: Hook, y: number, t: number, target: HTMLElement) {
} as unknown as React.PointerEvent),
);
}
+// A release velocity needs two moves or more: Core's velocity tracker reads
+// none from fewer. So each flick here moves at least twice.
function move(hook: Hook, y: number, t: number, target: HTMLElement) {
act(() =>
hook.result.current.handleProps.onPointerMove(pointerEvent(y, t, target)),
@@ -180,6 +182,7 @@ describe('useSheetGestures', () => {
touchDown(hook, 0, 0, t);
// 60px in 20ms = 3,000 px/s. Projected 0.1 s ahead it lands at 360px,
// nearer closed (400px) than the 200px detent.
+ move(hook, 30, 10, t);
move(hook, 60, 20, t);
up(hook, 60, 22, t);
expect(onDismiss).toHaveBeenCalledTimes(1);
@@ -255,6 +258,7 @@ describe('useSheetGestures', () => {
});
const t = makeTarget();
down(hook, 0, 0, t);
+ move(hook, 30, 10, t);
move(hook, 60, 20, t);
up(hook, 60, 22, t);
@@ -277,6 +281,7 @@ describe('useSheetGestures', () => {
onSnap.mockClear();
// Now flick up fast: 60px in 20ms = 3px/ms, over the distance floor.
down(hook, 200, 1000, t);
+ move(hook, 170, 1010, t);
move(hook, 140, 1020, t);
up(hook, 140, 1022, t);
expect(onDismiss).not.toHaveBeenCalled();
@@ -315,7 +320,7 @@ describe('useSheetGestures', () => {
expect(onSnap).toHaveBeenLastCalledWith(200);
});
- it('reads the release speed over the last stretch, so one slow sample does not cancel a throw', () => {
+ it('keeps a throw whose last sample is slow, because the newest interval weighs a fifth', () => {
const {hook, onDismiss} = setup({snapHeights: () => [200]});
const t = makeTarget();
down(hook, 0, 0, t);
@@ -325,24 +330,43 @@ describe('useSheetGestures', () => {
expect(onDismiss).toHaveBeenCalledTimes(1);
});
- it('reads a throw that begins after a hold at its own speed, not the average since touch-down', () => {
+ it('reads a throw that begins after a hold at its own speed once two of its moves are in', () => {
const {hook, onDismiss} = setup({snapHeights: () => [200]});
const t = makeTarget();
down(hook, 0, 0, t);
move(hook, 0, 250, t); // a still hold on the handle
- move(hook, 30, 275, t); // then 60px in 50ms
+ // Then 60px in 50ms. The hold weighs on the first move only.
+ move(hook, 15, 262, t);
+ move(hook, 30, 275, t);
+ move(hook, 45, 287, t);
move(hook, 60, 300, t);
up(hook, 60, 302, t);
expect(onDismiss).toHaveBeenCalledTimes(1);
});
- it('reads a single move after a hold as a move, not as the whole hold', () => {
+ it('weighs a hold into the first move after it, as iOS does', () => {
+ const {hook, onDismiss} = setup({snapHeights: () => [200]});
+ const t = makeTarget();
+ down(hook, 0, 0, t);
+ move(hook, 0, 250, t); // a still hold on the handle
+ // Two moves of 30px in 25ms. The first one counts the hold's time, so
+ // the release reads about 330 px/s and the sheet stops at the 200px
+ // detent.
+ move(hook, 30, 275, t);
+ move(hook, 60, 300, t);
+ up(hook, 60, 302, t);
+ expect(onDismiss).not.toHaveBeenCalled();
+ expect(hook.result.current.settledOffset).toBe(200);
+ });
+
+ it('releases a single move at no speed', () => {
const {hook, onDismiss} = setup({snapHeights: () => [200]});
const t = makeTarget();
down(hook, 0, 0, t);
move(hook, 60, 300, t); // one sample, 300ms after touch-down
up(hook, 60, 302, t);
- expect(onDismiss).toHaveBeenCalledTimes(1);
+ expect(onDismiss).not.toHaveBeenCalled();
+ expect(hook.result.current.settledOffset).toBe(0);
});
it('releases no throw from a finger that rested before lifting', () => {
@@ -355,6 +379,27 @@ describe('useSheetGestures', () => {
expect(hook.result.current.settledOffset).toBe(0);
});
+ it('releases no throw from a finger that rested 50ms before lifting', () => {
+ const {hook, onDismiss} = setup({snapHeights: () => [200]});
+ const t = makeTarget();
+ down(hook, 0, 0, t);
+ move(hook, 30, 10, t);
+ move(hook, 60, 20, t); // 3px/ms ...
+ up(hook, 60, 70, t); // ... then 50ms of rest, past the 40ms stillness
+ expect(onDismiss).not.toHaveBeenCalled();
+ expect(hook.result.current.settledOffset).toBe(0);
+ });
+
+ it('keeps a throw after a 30ms rest before the lift', () => {
+ const {hook, onDismiss} = setup({snapHeights: () => [200]});
+ const t = makeTarget();
+ down(hook, 0, 0, t);
+ move(hook, 30, 10, t);
+ move(hook, 60, 20, t); // 3px/ms, then 30ms of rest
+ up(hook, 60, 50, t);
+ expect(onDismiss).toHaveBeenCalledTimes(1);
+ });
+
it('settles a throw that would coast past the line at the shortest detent when canDismiss is false', () => {
const {hook, onDismiss} = setup({
canDismiss: false,
@@ -370,6 +415,42 @@ describe('useSheetGestures', () => {
});
});
+ it('lands a flick on the next detent when one of its early moves arrives late', () => {
+ const onSnap = vi.fn();
+ const {hook, onDismiss} = setup({snapHeights: () => [100], onSnap});
+ const t = makeTarget();
+ // 9.6px every 8ms = 1,200 px/s, a flick. The eighth of ten moves comes
+ // 70ms late, stamped when it arrives, at its own position. The last two
+ // moves keep the 8ms spacing.
+ touchDown(hook, 0, 0, t);
+ for (let k = 1; k <= 7; k += 1) {
+ move(hook, 9.6 * k, 8 * k, t);
+ }
+ move(hook, 76.8, 134, t);
+ move(hook, 86.4, 142, t);
+ move(hook, 96, 150, t);
+ up(hook, 96, 152, t);
+ // A flick from the tallest detent goes one position down: the 100px
+ // detent, 300px below.
+ expect(onDismiss).not.toHaveBeenCalled();
+ expect(onSnap).toHaveBeenLastCalledWith(100);
+ });
+
+ it('reads a lift at a new position as the last move', () => {
+ const onSnap = vi.fn();
+ const {hook, onDismiss} = setup({snapHeights: () => [100], onSnap});
+ const t = makeTarget();
+ // Two moves at 900 px/s, then a lift 30px further on 10ms later. The
+ // lift's move makes the release about 1,320 px/s: a flick, so the sheet
+ // goes one position down, to the 100px detent.
+ touchDown(hook, 0, 0, t);
+ move(hook, 9, 10, t);
+ move(hook, 18, 20, t);
+ up(hook, 48, 30, t);
+ expect(onDismiss).not.toHaveBeenCalled();
+ expect(onSnap).toHaveBeenLastCalledWith(100);
+ });
+
it('takes a fast short flick from the tallest of two detents to the next one down', () => {
const onSnap = vi.fn();
const {hook, onDismiss} = setup({snapHeights: () => [200], onSnap});
@@ -378,6 +459,7 @@ describe('useSheetGestures', () => {
// 145px, short of the 200px detent. A flick goes at least one position
// down: the 200px detent.
touchDown(hook, 0, 0, t);
+ move(hook, 10, 8, t);
move(hook, 20, 16, t);
up(hook, 20, 18, t);
expect(onDismiss).not.toHaveBeenCalled();
@@ -388,6 +470,7 @@ describe('useSheetGestures', () => {
const {hook, onDismiss} = setup(); // one detent: fully open
const t = makeTarget();
touchDown(hook, 0, 0, t);
+ move(hook, 10, 5, t);
move(hook, 20, 10, t);
up(hook, 20, 12, t);
expect(onDismiss).toHaveBeenCalledTimes(1);
@@ -398,6 +481,7 @@ describe('useSheetGestures', () => {
const t = makeTarget();
// 20px in 25ms = 800 px/s: below the flick speed, so it settles back.
touchDown(hook, 0, 0, t);
+ move(hook, 8, 10, t);
move(hook, 20, 25, t);
up(hook, 20, 27, t);
expect(onDismiss).not.toHaveBeenCalled();
@@ -415,6 +499,7 @@ describe('useSheetGestures', () => {
up(hook, 180, 1100, t);
expect(onSnap).toHaveBeenLastCalledWith(200);
touchDown(hook, 400, 2000, t);
+ move(hook, 390, 2005, t);
move(hook, 380, 2010, t);
up(hook, 380, 2012, t);
expect(onSnap).toHaveBeenLastCalledWith(400);
@@ -424,6 +509,7 @@ describe('useSheetGestures', () => {
const {hook, onDismiss} = setup();
const t = makeTarget();
touchDown(hook, 0, 0, t);
+ move(hook, 10, 5, t);
move(hook, 20, 10, t);
// The host takes the close in the same update, as a controlled host does.
act(() => {
@@ -1236,12 +1322,16 @@ describe('useSheetGestures', () => {
y: number,
id = 1,
touchType = 'direct',
+ time?: number,
) {
const ev = new Event(type, {bubbles: true, cancelable: true});
// jsdom lacks TouchEvent; attach the fields the handler reads.
Object.defineProperty(ev, 'changedTouches', {
value: [{identifier: id, clientY: y, touchType}],
});
+ if (time != null) {
+ Object.defineProperty(ev, 'timeStamp', {value: time});
+ }
Object.defineProperty(ev, 'touches', {
value:
type === 'touchend' || type === 'touchcancel'
@@ -1295,6 +1385,30 @@ describe('useSheetGestures', () => {
expect(liveOffset(hook)).toBe(150);
});
+ it("lands a content pull-down flick by the touch events' own timestamps", () => {
+ const onSnap = vi.fn();
+ const {hook, onDismiss} = setup({snapHeights: () => [200], onSnap});
+ const el = makeScroller({
+ scrollTop: 0,
+ clientHeight: 200,
+ scrollHeight: 800,
+ });
+ act(() => hook.result.current.sheetRef(el));
+ act(() => hook.result.current.bodyProps.ref(el));
+ // 17.6px every 16ms = 1,100 px/s, a flick, dispatched all at once, so
+ // only the events' own timestamps carry the speed. Its 0.1 s projection
+ // stops at 180px, so the flick goes one position down, to 200px.
+ act(() => {
+ touch(el, 'touchstart', 0, 1, 'direct', 0);
+ for (let k = 1; k <= 4; k += 1) {
+ touch(el, 'touchmove', 17.6 * k, 1, 'direct', 16 * k);
+ }
+ touch(el, 'touchend', 70.4, 1, 'direct', 66);
+ });
+ expect(onDismiss).not.toHaveBeenCalled();
+ expect(onSnap).toHaveBeenLastCalledWith(200);
+ });
+
it('stretches the sheet with a pull up past a list already at its end, at the tallest detent, without claiming the touch', () => {
const {hook} = setup({
snapHeights: () => [200],
diff --git a/packages/core/src/BottomSheet/useSheetGestures.ts b/packages/core/src/BottomSheet/useSheetGestures.ts
index e93d56a5ea..f6d82836c9 100644
--- a/packages/core/src/BottomSheet/useSheetGestures.ts
+++ b/packages/core/src/BottomSheet/useSheetGestures.ts
@@ -64,6 +64,7 @@ import {
type UIEvent as ReactUIEvent,
} from 'react';
+import {VelocityTracker} from '../gestures/VelocityTracker';
import {resolveSnapPoint} from '../motion/resolveSnapPoint';
import {rubberBand} from '../motion/rubberBand';
import {scroll} from '../motion/uikit/scroll';
@@ -93,10 +94,6 @@ interface SheetDetents {
const DECELERATION_RATE = 0.998;
const PROJECTION_FACTOR = DECELERATION_RATE / (1 - DECELERATION_RATE); // ms
const PROJECTION_MIN_TRAVEL = 48; // px traveled during the gesture
-// The release speed is the finger's speed over its last stretch, not between
-// its last two samples: one slow sample before the lift must not cancel a
-// throw, and a finger that paused before lifting has no speed at all.
-const VELOCITY_WINDOW_MS = 100;
// On a slow drag below the shortest detent, dismiss once dragged past it by
// more than this fraction of that detent's height; otherwise snap back to it.
const DISMISS_OVERSHOOT_RATIO = 0.4;
@@ -762,12 +759,9 @@ export function useSheetGestures({
pointerType: string;
pointerId: number;
startCoord: number;
- lastCoord: number;
- lastTime: number;
- // The finger's recent positions, oldest first, kept to VELOCITY_WINDOW_MS
- // (and never fewer than two) for the release speed.
- samples: {t: number; y: number}[];
- velocity: number;
+ // The finger's positions on the timestamps their events carry, for the
+ // release velocity (Core's one velocity tracker).
+ tracker: VelocityTracker;
height: number;
/** The surface kept below the screen when the drag began. */
reserve: number;
@@ -1295,15 +1289,14 @@ export function useSheetGestures({
const start = startCoord ?? event.clientY;
const naturalEndGap = naturalEndGapFor(bodyNodeRef.current);
const baseLayoutOffset = settledLayoutOffsetRef.current;
+ const tracker = new VelocityTracker();
+ tracker.add(0, event.clientY, event.timeStamp);
dragStateRef.current = {
syntheticTouch,
pointerType: event.pointerType,
pointerId: event.pointerId,
startCoord: start,
- lastCoord: event.clientY,
- lastTime: event.timeStamp,
- samples: [{t: event.timeStamp, y: event.clientY}],
- velocity: 0,
+ tracker,
height: sheetHeight,
reserve: offscreenBlockEndInsetRef.current,
baseOffset: settledOffset,
@@ -1380,26 +1373,9 @@ export function useSheetGestures({
return;
}
const delta = event.clientY - state.startCoord;
- const dt = event.timeStamp - state.lastTime;
- if (dt > 0) {
- state.lastCoord = event.clientY;
- state.lastTime = event.timeStamp;
- state.samples.push({t: event.timeStamp, y: event.clientY});
- // Drop what fell out of the window while a partner remains: a throw
- // that begins after a rest reads its own speed, not the average since
- // touch-down.
- while (
- state.samples.length > 2 &&
- event.timeStamp - state.samples[0].t > VELOCITY_WINDOW_MS
- ) {
- state.samples.shift();
- }
- const first = state.samples[0];
- // A lone partner older than the window says only where the finger
- // rested; the move it precedes is read as if it took the window.
- const span = Math.min(event.timeStamp - first.t, VELOCITY_WINDOW_MS);
- state.velocity = span > 0 ? (event.clientY - first.y) / span : 0;
- }
+ // One sample per event, on the event's own timestamp: when the finger
+ // was there, however late a busy main thread handles the event.
+ state.tracker.add(0, event.clientY, event.timeStamp);
const {offsets, peekOffset} = resolveDetents(state.height);
const raw = state.baseOffset + delta;
@@ -1497,11 +1473,13 @@ export function useSheetGestures({
const delta = event.clientY - state.startCoord;
const offset = Math.max(0, state.baseOffset + delta);
const dir = delta === 0 ? 0 : delta > 0 ? 1 : -1;
- // A finger that rested before lifting released nothing in motion.
- const velocity =
- event.timeStamp - state.lastTime < VELOCITY_WINDOW_MS
- ? state.velocity
- : 0;
+ // The release velocity, px/ms. A lift at a new position is the last
+ // sample. A finger that held still for longer than the stillness
+ // interval before the lift releases nothing in motion.
+ if (state.tracker.lastSample?.y !== event.clientY) {
+ state.tracker.add(0, event.clientY, event.timeStamp);
+ }
+ const velocity = state.tracker.velocity(event.timeStamp).y / 1000;
dragStateRef.current = null;
if (!state.syntheticTouch) {
target.releasePointerCapture?.(event.pointerId);
@@ -1659,13 +1637,15 @@ export function useSheetGestures({
});
const bodyRef = useCallback((node: HTMLElement | null) => {
- const asPointer = (touch: Touch, target: HTMLElement) =>
+ const asPointer = (touch: Touch, target: HTMLElement, event: TouchEvent) =>
({
syntheticTouch: true,
pointerId: touch.identifier,
pointerType: touchPointerType(touch),
clientY: touch.clientY,
- timeStamp: Date.now(),
+ // The touch event's own time: when the finger was there, however
+ // late this handler runs.
+ timeStamp: event.timeStamp,
currentTarget: target,
setPointerCapture: () => {},
releasePointerCapture: () => {},
@@ -1744,11 +1724,11 @@ export function useSheetGestures({
// Deliberately NOT preventDefault()ed: the scroller is clamped at
// its end, so there is no scrolling left to cancel, and claiming the
// gesture would strand the content for as long as the finger is down.
- pointerMoveRef.current(asPointer(t, scroller));
+ pointerMoveRef.current(asPointer(t, scroller, event));
return;
}
event.preventDefault();
- pointerMoveRef.current(asPointer(t, scroller));
+ pointerMoveRef.current(asPointer(t, scroller, event));
return;
}
if (!armed) {
@@ -1774,11 +1754,11 @@ export function useSheetGestures({
releaseContentHold(armed);
touchDragRef.current = null;
beginDragRef.current(
- asPointer(t, scroller),
+ asPointer(t, scroller, event),
measureHeightRef.current(),
armed.startY,
);
- pointerMoveRef.current(asPointer(t, scroller));
+ pointerMoveRef.current(asPointer(t, scroller, event));
return;
}
if ((armed.top && delta < 0) || (armed.bottom && delta > 0)) {
@@ -1802,11 +1782,11 @@ export function useSheetGestures({
} else if (armed.contentEndY - t.clientY >= CONTENT_END_HANDOFF_SLOP) {
armed.promotedAtContentEnd = true;
beginDragRef.current(
- asPointer(t, scroller),
+ asPointer(t, scroller, event),
measureHeightRef.current(),
armed.contentEndY,
);
- pointerMoveRef.current(asPointer(t, scroller));
+ pointerMoveRef.current(asPointer(t, scroller, event));
}
} else {
armed.contentEndY = null;
@@ -1826,7 +1806,7 @@ export function useSheetGestures({
);
const target = event.currentTarget as HTMLElement;
if (t) {
- endDragRef.current(asPointer(t, target));
+ endDragRef.current(asPointer(t, target, event));
} else if (event.touches.length === 0) {
// Some interrupted multi-touch sequences omit the active touch from
// changedTouches. If no fingers remain, the drag cannot finish later.