Merge pull request 'Give canvas pans momentum' (#15) from momentum-pan into main

Reviewed-on: #15
This commit is contained in:
reudy 2026-09-30 23:18:24 +02:00
commit 49923833c9
5 changed files with 129 additions and 14 deletions

View file

@ -28,7 +28,7 @@ The image builds the PWA and serves it with nginx. Put an HTTPS reverse proxy in
- **Pages**: the "+" circles beside the active page add a page there (a quick finger flick toward a free side offers one there; turn it off under Settings → Pen & touch); `Alt+Arrow` moves to (or creates) the neighbour. Right-click a page or use its `⋯` button to insert, resize or delete it. - **Pages**: the "+" circles beside the active page add a page there (a quick finger flick toward a free side offers one there; turn it off under Settings → Pen & touch); `Alt+Arrow` moves to (or creates) the neighbour. Right-click a page or use its `⋯` button to insert, resize or delete it.
- **Grid**: the faint background grid has one cell per active page; Settings → Appearance can hide it or subdivide it. - **Grid**: the faint background grid has one cell per active page; Settings → Appearance can hide it or subdivide it.
- **Importing a PDF** into a non-empty canvas shows every free spot; click one to place the chain. Into a blank canvas it simply replaces the empty page. The Files panel can also import a PDF as a new canvas. - **Importing a PDF** into a non-empty canvas shows every free spot; click one to place the chain. Into a blank canvas it simply replaces the empty page. The Files panel can also import a PDF as a new canvas.
- **View**: wheel/trackpad pans, `Ctrl`+wheel or pinch zooms, `Ctrl+0` fits the page, `Ctrl+9` shows the whole tree, space-drag or middle-drag pans. - **View**: wheel/trackpad pans, `Ctrl`+wheel or pinch zooms, `Ctrl+0` fits the page, `Ctrl+9` shows the whole tree, space-drag or middle-drag pans. A drag keeps gliding for a moment after you let go and slows to a stop (the zoom never changes); touching the canvas catches it. The drag strength is `GLIDE_TAU` in `src/lib/ink/fling.ts`.
- **Sync**: Settings → Sync. Use a fine-grained token with *Contents: read & write* on the repo. Edits autosave locally; pushes happen every N minutes and on `Ctrl+S` / the sync button. Conflicts: newer wins. - **Sync**: Settings → Sync. Use a fine-grained token with *Contents: read & write* on the repo. Edits autosave locally; pushes happen every N minutes and on `Ctrl+S` / the sync button. Conflicts: newer wins.
## Layout ## Layout

View file

@ -21,7 +21,7 @@
import { canInsert, freeSlots, freeSlotsOf, neighbor, type Dir, type Slot } from '$lib/model/tree'; import { canInsert, freeSlots, freeSlotsOf, neighbor, type Dir, type Slot } from '$lib/model/tree';
import { A4, PAGE_PRESETS, newId, type PageImage, type Stroke } from '$lib/model/types'; import { A4, PAGE_PRESETS, newId, type PageImage, type Stroke } from '$lib/model/types';
import { PalmRejector, touchIntent } from '$lib/ink/palm'; import { PalmRejector, touchIntent } from '$lib/ink/palm';
import { flingDir, pushSample, type Sample } from '$lib/ink/fling'; import { flingDir, pushSample, releaseVelocity, type Sample } from '$lib/ink/fling';
import { StrokeRecorder, hitStroke } from '$lib/ink/stroke'; import { StrokeRecorder, hitStroke } from '$lib/ink/stroke';
import { import {
IDENTITY, IDENTITY,
@ -607,6 +607,8 @@
return; return;
} }
} }
// Touching the canvas catches a gliding view.
viewport.stopGlide();
if (plus && e.button === 0) { if (plus && e.button === 0) {
e.preventDefault(); e.preventDefault();
@ -828,9 +830,12 @@
selPreview = null; selPreview = null;
if (e.type === 'pointerup' && t && (t.k !== 1 || t.tx || t.ty)) commitTransform(t); if (e.type === 'pointerup' && t && (t.k !== 1 || t.tx || t.ty)) commitTransform(t);
} else if (g.kind === 'pan') { } else if (g.kind === 'pan') {
if (e.type === 'pointerup' && g.moved && g.pointerType === 'touch') { if (e.type === 'pointerup' && g.moved) {
pushSample(g.trail, { ...local(e), t: e.timeStamp }); pushSample(g.trail, { ...local(e), t: e.timeStamp });
offerAfterFling(g.trail); // The view coasts on in the direction of the drag (a drag that stopped before lifting has ~no velocity).
const v = releaseVelocity(g.trail);
if (v) viewport.glide(v.vx, v.vy);
if (g.pointerType === 'touch') offerAfterFling(g.trail);
} }
} else if (g.kind === 'add') { } else if (g.kind === 'add') {
if (e.type === 'pointerup' && (g.pointerType !== 'touch' || palm.evaluate(e, 'navigate').accept)) addPage(g.slot.anchor, g.slot.dir); if (e.type === 'pointerup' && (g.pointerType !== 'touch' || palm.evaluate(e, 'navigate').accept)) addPage(g.slot.anchor, g.slot.dir);

View file

@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { flingDir, pushSample, type Sample } from './fling'; import { flingDir, GLIDE_TAU, glideStep, pushSample, releaseVelocity, type Sample } from './fling';
/** A straight drag from (0,0) by (dx,dy) over `ms`, sampled every 16 ms. */ /** A straight drag from (0,0) by (dx,dy) over `ms`, sampled every 16 ms. */
function drag(dx: number, dy: number, ms: number): Sample[] { function drag(dx: number, dy: number, ms: number): Sample[] {
@ -41,3 +41,53 @@ describe('flingDir', () => {
expect(s.at(-1)!.t - s[0].t).toBeLessThanOrEqual(216); expect(s.at(-1)!.t - s[0].t).toBeLessThanOrEqual(216);
}); });
}); });
describe('releaseVelocity', () => {
it('measures the speed and direction at release', () => {
const v = releaseVelocity(drag(-200, 100, 96))!;
expect(v.vx).toBeCloseTo(-200 / 96);
expect(v.vy).toBeCloseTo(100 / 96);
});
it('is zero for a drag that stops before lifting', () => {
const s = drag(-300, 0, 96);
const end = s.at(-1)!;
for (let t = 16; t <= 160; t += 16) pushSample(s, { ...end, t: end.t + t });
expect(releaseVelocity(s)).toEqual({ vx: 0, vy: 0 });
});
it('needs at least two samples', () => {
expect(releaseVelocity([{ x: 0, y: 0, t: 0 }])).toBeNull();
});
});
describe('glideStep', () => {
it('slows down and coasts GLIDE_TAU × speed in total', () => {
let vx = 2;
let vy = -1;
let x = 0;
let y = 0;
for (let i = 0; i < 1000; i++) {
const s = glideStep(vx, vy, 16);
expect(Math.abs(s.vx)).toBeLessThan(Math.abs(vx));
({ vx, vy } = s);
x += s.dx;
y += s.dy;
}
expect(x).toBeCloseTo(2 * GLIDE_TAU);
expect(y).toBeCloseTo(-GLIDE_TAU);
});
it('does not depend on the frame rate', () => {
const once = glideStep(1, 0, 64);
let v = 1;
let x = 0;
for (let i = 0; i < 4; i++) {
const s = glideStep(v, 0, 16);
v = s.vx;
x += s.dx;
}
expect(x).toBeCloseTo(once.dx);
expect(v).toBeCloseTo(once.vx);
});
});

View file

@ -1,4 +1,4 @@
// Fling detection for one-finger pans: a quick flick that ends the drag. // Fling detection and momentum for pans: a quick flick that ends the drag.
import type { Dir } from '$lib/model/tree'; import type { Dir } from '$lib/model/tree';
@ -15,25 +15,48 @@ const MIN_SPEED = 0.6;
/** The main axis must dominate by this much. */ /** The main axis must dominate by this much. */
const MIN_RATIO = 2; const MIN_RATIO = 2;
/** /** Pointer velocity at release in px/ms, from the last stretch of the drag; null if there is too little trail to tell. */
* Side of the canvas a fling heads for, or null. Moving the finger left pulls in export function releaseVelocity(samples: readonly Sample[]): { vx: number; vy: number } | null {
* what's on the right, so a leftward flick returns 'right'.
*/
export function flingDir(samples: readonly Sample[]): Dir | null {
const last = samples.at(-1); const last = samples.at(-1);
if (!last) return null; if (!last) return null;
const first = samples.find((s) => last.t - s.t <= WINDOW_MS); const first = samples.find((s) => last.t - s.t <= WINDOW_MS);
if (!first || first === last) return null; if (!first || first === last) return null;
const dt = last.t - first.t; const dt = last.t - first.t;
if (dt <= 0) return null; if (dt <= 0) return null;
const dx = last.x - first.x; return { vx: (last.x - first.x) / dt, vy: (last.y - first.y) / dt };
const dy = last.y - first.y; }
if (Math.hypot(dx, dy) / dt < MIN_SPEED) return null;
/**
* Side of the canvas a fling heads for, or null. Moving the finger left pulls in
* what's on the right, so a leftward flick returns 'right'.
*/
export function flingDir(samples: readonly Sample[]): Dir | null {
const v = releaseVelocity(samples);
if (!v || Math.hypot(v.vx, v.vy) < MIN_SPEED) return null;
const { vx: dx, vy: dy } = v;
if (Math.abs(dx) >= Math.abs(dy) * MIN_RATIO) return dx < 0 ? 'right' : 'left'; if (Math.abs(dx) >= Math.abs(dy) * MIN_RATIO) return dx < 0 ? 'right' : 'left';
if (Math.abs(dy) >= Math.abs(dx) * MIN_RATIO) return dy < 0 ? 'down' : 'up'; if (Math.abs(dy) >= Math.abs(dx) * MIN_RATIO) return dy < 0 ? 'down' : 'up';
return null; return null;
} }
// Momentum: after release the view keeps moving and slows under drag, with
// velocity decaying exponentially (v' = -v / GLIDE_TAU). It coasts
// GLIDE_TAU × release speed in total, e.g. 325 px after a 1 px/ms flick.
/** Decay time constant, ms. Larger = less drag, longer glide. */
export const GLIDE_TAU = 325;
/** px/ms; releases slower than this don't glide, and a glide stops once it drops below it. */
export const GLIDE_MIN_SPEED = 0.02;
/** px/ms; caps a wild flick so it can't throw the view miles away. */
export const GLIDE_MAX_SPEED = 6;
/** Advances a glide by `dt` ms: how far it moves and the velocity left afterwards. */
export function glideStep(vx: number, vy: number, dt: number) {
const decay = Math.exp(-dt / GLIDE_TAU);
const travel = GLIDE_TAU * (1 - decay);
return { dx: vx * travel, dy: vy * travel, vx: vx * decay, vy: vy * decay };
}
/** Keeps a short trail of pointer samples for flingDir. */ /** Keeps a short trail of pointer samples for flingDir. */
export function pushSample(samples: Sample[], s: Sample) { export function pushSample(samples: Sample[], s: Sample) {
samples.push(s); samples.push(s);

View file

@ -1,6 +1,7 @@
// Pan/zoom of the canvas view. World units are PDF points. // Pan/zoom of the canvas view. World units are PDF points.
import type { Rect } from '$lib/model/layout'; import type { Rect } from '$lib/model/layout';
import { GLIDE_MAX_SPEED, GLIDE_MIN_SPEED, glideStep } from '$lib/ink/fling';
export const MIN_SCALE = 0.04; export const MIN_SCALE = 0.04;
export const MAX_SCALE = 8; export const MAX_SCALE = 8;
@ -13,6 +14,8 @@ class Viewport {
/** Size of the stage element. */ /** Size of the stage element. */
width = $state(0); width = $state(0);
height = $state(0); height = $state(0);
/** Pending animation frame of a momentum glide, 0 when still. */
private glideFrame = 0;
toWorld(sx: number, sy: number) { toWorld(sx: number, sy: number) {
return { x: (sx - this.x) / this.scale, y: (sy - this.y) / this.scale }; return { x: (sx - this.x) / this.scale, y: (sy - this.y) / this.scale };
@ -28,6 +31,7 @@ class Viewport {
} }
zoomAt(factor: number, sx = this.width / 2, sy = this.height / 2) { zoomAt(factor: number, sx = this.width / 2, sy = this.height / 2) {
this.stopGlide();
const next = Math.min(MAX_SCALE, Math.max(MIN_SCALE, this.scale * factor)); const next = Math.min(MAX_SCALE, Math.max(MIN_SCALE, this.scale * factor));
const w = this.toWorld(sx, sy); const w = this.toWorld(sx, sy);
this.scale = next; this.scale = next;
@ -36,12 +40,44 @@ class Viewport {
} }
panBy(dx: number, dy: number) { panBy(dx: number, dy: number) {
this.stopGlide();
this.x += dx; this.x += dx;
this.y += dy; this.y += dy;
} }
/**
* Keep panning after a drag is released, at velocity (vx, vy) px/ms, slowing to
* a stop. Only the position moves; the zoom stays as it is. Any other view change
* (pan, zoom, fit) stops it.
*/
glide(vx: number, vy: number) {
this.stopGlide();
const speed = Math.hypot(vx, vy);
if (speed < GLIDE_MIN_SPEED) return;
if (speed > GLIDE_MAX_SPEED) {
vx *= GLIDE_MAX_SPEED / speed;
vy *= GLIDE_MAX_SPEED / speed;
}
let last = performance.now();
const frame = (now: number) => {
const s = glideStep(vx, vy, Math.max(0, now - last));
last = now;
this.x += s.dx;
this.y += s.dy;
({ vx, vy } = s);
this.glideFrame = Math.hypot(vx, vy) < GLIDE_MIN_SPEED ? 0 : requestAnimationFrame(frame);
};
this.glideFrame = requestAnimationFrame(frame);
}
stopGlide() {
if (this.glideFrame) cancelAnimationFrame(this.glideFrame);
this.glideFrame = 0;
}
/** Fit a world rectangle into the stage with some padding. */ /** Fit a world rectangle into the stage with some padding. */
fit(r: Rect, pad = 24) { fit(r: Rect, pad = 24) {
this.stopGlide();
if (!this.width || !this.height) return; if (!this.width || !this.height) return;
const s = Math.min((this.width - 2 * pad) / r.width, (this.height - 2 * pad) / r.height); const s = Math.min((this.width - 2 * pad) / r.width, (this.height - 2 * pad) / r.height);
this.scale = Math.min(MAX_SCALE, Math.max(MIN_SCALE, s)); this.scale = Math.min(MAX_SCALE, Math.max(MIN_SCALE, s));
@ -51,6 +87,7 @@ class Viewport {
/** Pan so the rectangle is centred, keeping the zoom. */ /** Pan so the rectangle is centred, keeping the zoom. */
center(r: Rect) { center(r: Rect) {
this.stopGlide();
this.x = this.width / 2 - (r.x + r.width / 2) * this.scale; this.x = this.width / 2 - (r.x + r.width / 2) * this.scale;
this.y = this.height / 2 - (r.y + r.height / 2) * this.scale; this.y = this.height / 2 - (r.y + r.height / 2) * this.scale;
} }