Smooth phone page swipes
All checks were successful
Verify and publish Calio container / build-and-push (push) Successful in 28s

- Keep the page rail on its own compositor layer for the whole session
  instead of promoting it at every drag start
- Write the drag transform directly in touchmove rather than a later rAF
- Carry the release velocity into the settle animation (160-340ms) so
  flicks neither brake nor lurch; covered by a unit test
- Render the page change as a transition so it cannot delay the settle
- Pause bubble physics and canvas drawing while the pager is moving

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-10-22 11:06:22 -07:00
parent c3b9376508
commit bb0bc430aa
6 changed files with 103 additions and 40 deletions

View file

@ -7,3 +7,17 @@ export function swipeStep(dx, dy, elapsed, width) {
const flick = distance >= 36 && distance / Math.max(1, elapsed) >= 0.5; const flick = distance >= 36 && distance / Math.max(1, elapsed) >= 0.5;
return deliberate || flick ? (dx < 0 ? 1 : -1) : 0; return deliberate || flick ? (dx < 0 ? 1 : -1) : 0;
} }
// The settle curve's initial slope (y1 / x1 of the cubic-bezier) lets a
// released swipe continue at the finger's speed instead of braking or lurching.
export const SETTLE_EASING = "cubic-bezier(0.25, 0.8, 0.25, 1)";
const SETTLE_SLOPE = 0.8 / 0.25;
// Distance and velocity share a sign convention: px, and px/ms toward "to".
export function settleDuration(distance, width, velocity = 0) {
const remaining = Math.abs(distance);
const base = Math.min(340, Math.max(220, (remaining / Math.max(1, width)) * 340));
// Only a release moving toward the destination carries its momentum.
if (!velocity || Math.sign(velocity) !== Math.sign(distance)) return base;
return Math.min(base, Math.max(160, (SETTLE_SLOPE * remaining) / Math.abs(velocity)));
}

View file

@ -43,9 +43,6 @@
height: 100%; height: 100%;
transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0);
} }
.page-rail.pager-dragging {
user-select: none;
}
.mobile-pager .page-panel { .mobile-pager .page-panel {
display: flex; display: flex;
flex-direction: column; flex-direction: column;

19
src/pagerMotion.ts Normal file
View file

@ -0,0 +1,19 @@
// Set while the phone pager is being dragged or is settling, so main-thread
// work such as the bubble simulation can yield every frame to the gesture.
let moving = false;
const listeners = new Set<() => void>();
export const pagerMoving = () => moving;
export function setPagerMoving(value: boolean) {
if (moving === value) return;
moving = value;
listeners.forEach((fn) => fn());
}
export function onPagerMotion(fn: () => void) {
listeners.add(fn);
return () => {
listeners.delete(fn);
};
}

View file

@ -1,6 +1,7 @@
import { useContext, useEffect, useRef, useState } from "react"; import { useContext, useEffect, useRef, useState } from "react";
import { PageActivity } from "./PageActivity"; import { PageActivity } from "./PageActivity";
import { useTilt } from "./useTilt"; import { useTilt } from "./useTilt";
import { onPagerMotion, pagerMoving } from "./pagerMotion";
import { import {
createBubbleWorld, createBubbleWorld,
screenGravity, screenGravity,
@ -109,7 +110,8 @@ export function useBubblePhysics(count: number) {
}); });
function tick(now: number) { function tick(now: number) {
frame = 0; frame = 0;
if (document.hidden || disposed || !activeRef.current) { // Yield every frame to a page swipe; the bubbles resume where they were.
if (document.hidden || disposed || !activeRef.current || pagerMoving()) {
previous = 0; previous = 0;
return; return;
} }
@ -129,7 +131,8 @@ export function useBubblePhysics(count: number) {
!document.hidden && !document.hidden &&
!reduced && !reduced &&
!disposed && !disposed &&
activeRef.current activeRef.current &&
!pagerMoving()
) )
frame = requestAnimationFrame(tick); frame = requestAnimationFrame(tick);
}; };
@ -150,6 +153,9 @@ export function useBubblePhysics(count: number) {
} else start(); } else start();
}; };
document.addEventListener("visibilitychange", visibility); document.addEventListener("visibilitychange", visibility);
const stopMotionListener = onPagerMotion(() => {
if (!pagerMoving()) start();
});
palette(); palette();
resize(); resize();
start(); start();
@ -159,6 +165,7 @@ export function useBubblePhysics(count: number) {
observer.disconnect(); observer.disconnect();
theme.disconnect(); theme.disconnect();
document.removeEventListener("visibilitychange", visibility); document.removeEventListener("visibilitychange", visibility);
stopMotionListener();
simulation.dispose(); simulation.dispose();
world.current = null; world.current = null;
kick.current = () => {}; kick.current = () => {};

View file

@ -1,11 +1,17 @@
import { import {
startTransition,
useCallback, useCallback,
useEffect, useEffect,
useLayoutEffect, useLayoutEffect,
useRef, useRef,
useState, useState,
} from "react"; } from "react";
import { swipeStep } from "../shared/navigation.js"; import {
SETTLE_EASING,
settleDuration,
swipeStep,
} from "../shared/navigation.js";
import { setPagerMoving } from "./pagerMotion";
export const pages = ["today", "library", "weight", "settings"] as const; export const pages = ["today", "library", "weight", "settings"] as const;
export type Page = (typeof pages)[number]; export type Page = (typeof pages)[number];
@ -13,7 +19,6 @@ const mobileQuery =
"(max-width: 760px), (max-width: 1000px) and (max-height: 500px)"; "(max-width: 760px), (max-width: 1000px) and (max-height: 500px)";
const reduced = () => matchMedia("(prefers-reduced-motion: reduce)").matches; const reduced = () => matchMedia("(prefers-reduced-motion: reduce)").matches;
const transform = (x: number) => `translate3d(${x}px, 0, 0)`; const transform = (x: number) => `translate3d(${x}px, 0, 0)`;
export function useNavigation(enabled: boolean) { export function useNavigation(enabled: boolean) {
const [page, setPage] = useState<Page>("today"); const [page, setPage] = useState<Page>("today");
const current = useRef<Page>(page); const current = useRef<Page>(page);
@ -23,7 +28,6 @@ export function useNavigation(enabled: boolean) {
const width = useRef(0); const width = useRef(0);
const position = useRef(0); const position = useRef(0);
const animation = useRef<Animation | null>(null); const animation = useRef<Animation | null>(null);
const frame = useRef(0);
const scroll = useRef<Partial<Record<Page, number>>>({}); const scroll = useRef<Partial<Record<Page, number>>>({});
const suppressClick = useRef(0); const suppressClick = useRef(0);
const motionReduced = useRef(reduced()); const motionReduced = useRef(reduced());
@ -34,14 +38,13 @@ export function useNavigation(enabled: boolean) {
locked: boolean; locked: boolean;
dx: number; dx: number;
base: number; base: number;
samples: { x: number; t: number }[];
} | null>(null); } | null>(null);
const paint = useCallback((x: number) => { const paint = useCallback((x: number) => {
position.current = x; position.current = x;
if (railRef.current) railRef.current.style.transform = transform(x); if (railRef.current) railRef.current.style.transform = transform(x);
}, []); }, []);
const stop = useCallback(() => { const stop = useCallback(() => {
cancelAnimationFrame(frame.current);
frame.current = 0;
if (animation.current) { if (animation.current) {
// Read once when interrupting a settle, never in the touch-move loop. // Read once when interrupting a settle, never in the touch-move loop.
const x = railRef.current const x = railRef.current
@ -50,55 +53,52 @@ export function useNavigation(enabled: boolean) {
animation.current.cancel(); animation.current.cancel();
animation.current = null; animation.current = null;
paint(x); paint(x);
setPagerMoving(false);
} }
}, [paint]); }, [paint]);
const settle = useCallback( const settle = useCallback(
(index: number, animate = true) => { (index: number, animate = true, velocity = 0) => {
stop(); stop();
const rail = railRef.current; const rail = railRef.current;
const from = position.current; const from = position.current;
const to = -index * width.current; const to = -index * width.current;
paint(to); paint(to);
if (!rail) return; if (!rail || !animate || reduced() || Math.abs(from - to) < 1) {
rail.classList.remove("pager-dragging"); setPagerMoving(false);
if (!animate || reduced() || Math.abs(from - to) < 1) {
rail.style.removeProperty("will-change");
return; return;
} }
rail.style.willChange = "transform"; setPagerMoving(true);
// A compositor animation: it keeps running while React renders.
const next = rail.animate( const next = rail.animate(
[{ transform: transform(from) }, { transform: transform(to) }], [{ transform: transform(from) }, { transform: transform(to) }],
{ {
duration: Math.min( duration: settleDuration(to - from, width.current, velocity),
260, easing: SETTLE_EASING,
Math.max(
140,
(Math.abs(to - from) / Math.max(1, width.current)) * 260,
),
),
easing: "cubic-bezier(.22,.75,.25,1)",
}, },
); );
animation.current = next; animation.current = next;
next.onfinish = () => { next.onfinish = () => {
if (animation.current !== next) return; if (animation.current !== next) return;
animation.current = null; animation.current = null;
rail.style.removeProperty("will-change"); setPagerMoving(false);
}; };
}, },
[paint, stop], [paint, stop],
); );
const navigate = useCallback( const navigate = useCallback(
(next: Page) => { (next: Page, velocity = 0) => {
const previous = current.current; const previous = current.current;
if (mobile) if (mobile)
settle( settle(
pages.indexOf(next), pages.indexOf(next),
Math.abs(pages.indexOf(next) - pages.indexOf(previous)) <= 1, Math.abs(pages.indexOf(next) - pages.indexOf(previous)) <= 1,
velocity,
); );
else scroll.current[previous] = window.scrollY; else scroll.current[previous] = window.scrollY;
current.current = next; current.current = next;
setPage(next); // Re-rendering all four pages must not delay the first settle frame.
if (mobile) startTransition(() => setPage(next));
else setPage(next);
}, },
[mobile, settle], [mobile, settle],
); );
@ -127,8 +127,12 @@ export function useNavigation(enabled: boolean) {
if (!mobile) { if (!mobile) {
stop(); stop();
rail.style.removeProperty("transform"); rail.style.removeProperty("transform");
rail.style.removeProperty("will-change");
return; return;
} }
// Keep the rail on its own layer for the whole session. Promoting it when
// a drag starts re-rasterizes four screens and stalls the first frames.
rail.style.willChange = "transform";
const resize = () => { const resize = () => {
const nextWidth = viewport.getBoundingClientRect().width; const nextWidth = viewport.getBoundingClientRect().width;
if (nextWidth === width.current && width.current > 0) return; if (nextWidth === width.current && width.current > 0) return;
@ -143,6 +147,7 @@ export function useNavigation(enabled: boolean) {
return () => { return () => {
observer.disconnect(); observer.disconnect();
stop(); stop();
setPagerMoving(false);
}; };
}, [enabled, mobile, settle, stop]); }, [enabled, mobile, settle, stop]);
useLayoutEffect(() => { useLayoutEffect(() => {
@ -200,6 +205,7 @@ export function useNavigation(enabled: boolean) {
locked: false, locked: false,
dx: 0, dx: 0,
base: position.current, base: position.current,
samples: [{ x: touch.clientX, t: event.timeStamp }],
}; };
}; };
const dragPosition = (dx: number) => { const dragPosition = (dx: number) => {
@ -226,18 +232,20 @@ export function useNavigation(enabled: boolean) {
} }
if (Math.abs(dx) < 12 || Math.abs(dx) < Math.abs(dy) * 1.4) return; if (Math.abs(dx) < 12 || Math.abs(dx) < Math.abs(dy) * 1.4) return;
drag.locked = true; drag.locked = true;
rail.classList.add("pager-dragging"); setPagerMoving(true);
rail.style.willChange = "transform";
} }
event.preventDefault(); event.preventDefault();
drag.dx = dx; drag.dx = dx;
// Coalesce touch events: one composited transform per display frame, with drag.samples.push({ x: event.touches[0].clientX, t: event.timeStamp });
// both live pages already laid out. No state updates or layout reads here. while (
if (!frame.current && !motionReduced.current) drag.samples.length > 2 &&
frame.current = requestAnimationFrame(() => { event.timeStamp - drag.samples[0].t > 100
frame.current = 0; )
if (gesture.current) paint(dragPosition(gesture.current.dx)); drag.samples.shift();
}); // iOS delivers one touchmove per display frame. Writing the composited
// transform now, not in a later rAF, keeps the page under the finger.
// No state updates or layout reads here.
if (!motionReduced.current) paint(dragPosition(dx));
}; };
const end = (event: TouchEvent) => { const end = (event: TouchEvent) => {
const drag = gesture.current; const drag = gesture.current;
@ -252,15 +260,19 @@ export function useNavigation(enabled: boolean) {
width.current, width.current,
) )
: 0; : 0;
let velocity = 0;
if (drag.locked) { if (drag.locked) {
suppressClick.current = performance.now() + 400; suppressClick.current = performance.now() + 400;
cancelAnimationFrame(frame.current);
frame.current = 0;
if (!reduced()) paint(dragPosition(drag.dx)); if (!reduced()) paint(dragPosition(drag.dx));
// Release velocity over the last ~100ms, in px/ms.
const first = drag.samples[0];
const last = drag.samples.at(-1)!;
if (last.t > first.t)
velocity = (last.x - first.x) / (last.t - first.t);
} }
gesture.current = null; gesture.current = null;
const next = pages[pages.indexOf(current.current) + step]; const next = pages[pages.indexOf(current.current) + step];
navigate(step && next ? next : current.current); navigate(step && next ? next : current.current, velocity);
}; };
const click = (event: MouseEvent) => { const click = (event: MouseEvent) => {
if (event.detail !== 0 && performance.now() < suppressClick.current) { if (event.detail !== 0 && performance.now() < suppressClick.current) {

View file

@ -1,6 +1,6 @@
import test from "node:test"; import test from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { swipeStep } from "../shared/navigation.js"; import { settleDuration, swipeStep } from "../shared/navigation.js";
test("phone swipes accept deliberate travel and short fast flicks in both directions", () => { test("phone swipes accept deliberate travel and short fast flicks in both directions", () => {
assert.equal(swipeStep(-100, 8, 500, 393), 1); assert.equal(swipeStep(-100, 8, 500, 393), 1);
@ -14,3 +14,17 @@ test("scrolling, diagonal travel, slow small movements and jitter never switch t
assert.equal(swipeStep(40, 2, 500, 393), 0); assert.equal(swipeStep(40, 2, 500, 393), 0);
assert.equal(swipeStep(8, 0, 5, 393), 0); assert.equal(swipeStep(8, 0, 5, 393), 0);
}); });
test("a released swipe settles at the finger's speed, within natural bounds", () => {
// Tab taps and slow releases use a distance-based duration.
assert.equal(settleDuration(-393, 393), 340);
assert.equal(settleDuration(-60, 393), 220);
// A fast flick toward the destination shortens the settle so it starts at
// the release velocity: 3.2 * 200px / 4px/ms = 160ms.
assert.equal(settleDuration(-200, 393, -4), 160);
// A gentle release never stretches the settle beyond the base duration.
assert.equal(settleDuration(-250, 393, -2), 220);
// Momentum away from the destination (a cancelled swipe) is ignored.
assert.equal(settleDuration(150, 393, -3), Math.max(220, 340 * (150 / 393)));
// Extremely fast flicks are clamped so the settle stays visible.
assert.equal(settleDuration(-300, 393, -20), 160);
});