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;
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%;
transform: translate3d(0, 0, 0);
}
.page-rail.pager-dragging {
user-select: none;
}
.mobile-pager .page-panel {
display: flex;
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 { PageActivity } from "./PageActivity";
import { useTilt } from "./useTilt";
import { onPagerMotion, pagerMoving } from "./pagerMotion";
import {
createBubbleWorld,
screenGravity,
@ -109,7 +110,8 @@ export function useBubblePhysics(count: number) {
});
function tick(now: number) {
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;
return;
}
@ -129,7 +131,8 @@ export function useBubblePhysics(count: number) {
!document.hidden &&
!reduced &&
!disposed &&
activeRef.current
activeRef.current &&
!pagerMoving()
)
frame = requestAnimationFrame(tick);
};
@ -150,6 +153,9 @@ export function useBubblePhysics(count: number) {
} else start();
};
document.addEventListener("visibilitychange", visibility);
const stopMotionListener = onPagerMotion(() => {
if (!pagerMoving()) start();
});
palette();
resize();
start();
@ -159,6 +165,7 @@ export function useBubblePhysics(count: number) {
observer.disconnect();
theme.disconnect();
document.removeEventListener("visibilitychange", visibility);
stopMotionListener();
simulation.dispose();
world.current = null;
kick.current = () => {};

View file

@ -1,11 +1,17 @@
import {
startTransition,
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
} 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 type Page = (typeof pages)[number];
@ -13,7 +19,6 @@ const mobileQuery =
"(max-width: 760px), (max-width: 1000px) and (max-height: 500px)";
const reduced = () => matchMedia("(prefers-reduced-motion: reduce)").matches;
const transform = (x: number) => `translate3d(${x}px, 0, 0)`;
export function useNavigation(enabled: boolean) {
const [page, setPage] = useState<Page>("today");
const current = useRef<Page>(page);
@ -23,7 +28,6 @@ export function useNavigation(enabled: boolean) {
const width = useRef(0);
const position = useRef(0);
const animation = useRef<Animation | null>(null);
const frame = useRef(0);
const scroll = useRef<Partial<Record<Page, number>>>({});
const suppressClick = useRef(0);
const motionReduced = useRef(reduced());
@ -34,14 +38,13 @@ export function useNavigation(enabled: boolean) {
locked: boolean;
dx: number;
base: number;
samples: { x: number; t: number }[];
} | null>(null);
const paint = useCallback((x: number) => {
position.current = x;
if (railRef.current) railRef.current.style.transform = transform(x);
}, []);
const stop = useCallback(() => {
cancelAnimationFrame(frame.current);
frame.current = 0;
if (animation.current) {
// Read once when interrupting a settle, never in the touch-move loop.
const x = railRef.current
@ -50,55 +53,52 @@ export function useNavigation(enabled: boolean) {
animation.current.cancel();
animation.current = null;
paint(x);
setPagerMoving(false);
}
}, [paint]);
const settle = useCallback(
(index: number, animate = true) => {
(index: number, animate = true, velocity = 0) => {
stop();
const rail = railRef.current;
const from = position.current;
const to = -index * width.current;
paint(to);
if (!rail) return;
rail.classList.remove("pager-dragging");
if (!animate || reduced() || Math.abs(from - to) < 1) {
rail.style.removeProperty("will-change");
if (!rail || !animate || reduced() || Math.abs(from - to) < 1) {
setPagerMoving(false);
return;
}
rail.style.willChange = "transform";
setPagerMoving(true);
// A compositor animation: it keeps running while React renders.
const next = rail.animate(
[{ transform: transform(from) }, { transform: transform(to) }],
{
duration: Math.min(
260,
Math.max(
140,
(Math.abs(to - from) / Math.max(1, width.current)) * 260,
),
),
easing: "cubic-bezier(.22,.75,.25,1)",
duration: settleDuration(to - from, width.current, velocity),
easing: SETTLE_EASING,
},
);
animation.current = next;
next.onfinish = () => {
if (animation.current !== next) return;
animation.current = null;
rail.style.removeProperty("will-change");
setPagerMoving(false);
};
},
[paint, stop],
);
const navigate = useCallback(
(next: Page) => {
(next: Page, velocity = 0) => {
const previous = current.current;
if (mobile)
settle(
pages.indexOf(next),
Math.abs(pages.indexOf(next) - pages.indexOf(previous)) <= 1,
velocity,
);
else scroll.current[previous] = window.scrollY;
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],
);
@ -127,8 +127,12 @@ export function useNavigation(enabled: boolean) {
if (!mobile) {
stop();
rail.style.removeProperty("transform");
rail.style.removeProperty("will-change");
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 nextWidth = viewport.getBoundingClientRect().width;
if (nextWidth === width.current && width.current > 0) return;
@ -143,6 +147,7 @@ export function useNavigation(enabled: boolean) {
return () => {
observer.disconnect();
stop();
setPagerMoving(false);
};
}, [enabled, mobile, settle, stop]);
useLayoutEffect(() => {
@ -200,6 +205,7 @@ export function useNavigation(enabled: boolean) {
locked: false,
dx: 0,
base: position.current,
samples: [{ x: touch.clientX, t: event.timeStamp }],
};
};
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;
drag.locked = true;
rail.classList.add("pager-dragging");
rail.style.willChange = "transform";
setPagerMoving(true);
}
event.preventDefault();
drag.dx = dx;
// Coalesce touch events: one composited transform per display frame, with
// both live pages already laid out. No state updates or layout reads here.
if (!frame.current && !motionReduced.current)
frame.current = requestAnimationFrame(() => {
frame.current = 0;
if (gesture.current) paint(dragPosition(gesture.current.dx));
});
drag.samples.push({ x: event.touches[0].clientX, t: event.timeStamp });
while (
drag.samples.length > 2 &&
event.timeStamp - drag.samples[0].t > 100
)
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 drag = gesture.current;
@ -252,15 +260,19 @@ export function useNavigation(enabled: boolean) {
width.current,
)
: 0;
let velocity = 0;
if (drag.locked) {
suppressClick.current = performance.now() + 400;
cancelAnimationFrame(frame.current);
frame.current = 0;
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;
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) => {
if (event.detail !== 0 && performance.now() < suppressClick.current) {

View file

@ -1,6 +1,6 @@
import test from "node:test";
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", () => {
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(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);
});