// The lightbox's gesture and spring state, without any DOM. Ported from the // core of @oomfware/lightbox (0BSD), the engine behind the Bluesky web // client's image viewer, trimmed to the settings this client uses. export interface Size { width: number; height: number; } interface Point { x: number; y: number; } /** One image's zoom (relative to its fitted size) and pan from centre. */ export interface Transform { scale: number; x: number; y: number; } /** What to draw for one frame. */ export interface LightboxState { index: number; transforms: Transform[]; fitted: Size[]; trackX: number; dismissY: number; backdropOpacity: number; dragging: boolean; /** A drag committed to paging, panning, or dismissing, or a pinch. */ moved: boolean; zoomed: boolean; } const IDENTITY: Transform = { scale: 1, x: 0, y: 0 }; const AXIS_LOCK_PX = 10; const PAGE_THRESHOLD = 0.2; const PAGE_FLING = 500; const DISMISS_THRESHOLD_PX = 50; const DISMISS_VELOCITY = 700; const DISMISS_FADE_PX = 400; const MIN_SCALE = 1; const MAX_SCALE = 4; const DOUBLE_TAP_SCALE = 2.5; /** Small images rest at natural size, but cover at least half the viewport. */ const MIN_COVERAGE = 0.5; const RUBBER = 0.55; export const DOUBLE_TAP_MS = 300; const DOUBLE_TAP_DIST = 30; const VELOCITY_WINDOW_MS = 100; interface SpringConfig { stiffness: number; damping: number; restVelocity: number; restDistance: number; } const DEFAULT: SpringConfig = { stiffness: 220, damping: 30, restVelocity: 0.5, restDistance: 0.5, }; const SCALE: SpringConfig = { stiffness: 220, damping: 30, restVelocity: 0.01, restDistance: 0.001, }; class Spring { value: number; target: number; velocity = 0; animating = false; constructor( value: number, private config = DEFAULT, ) { this.value = this.target = value; } set(value: number) { this.value = this.target = value; this.velocity = 0; this.animating = false; } animateTo(target: number, velocity?: number) { this.target = target; if (velocity !== undefined) this.velocity = velocity; this.animating = true; } /** * Advances `dt` seconds in small steps, so a slow frame moves it further * rather than slowing it down; false once at rest. */ step(dt: number): boolean { if (!this.animating) return false; const { stiffness, damping, restVelocity, restDistance } = this.config; for (let left = Math.min(dt, 0.25); left > 0; left -= 1 / 120) { const h = Math.min(left, 1 / 120); const accel = -stiffness * (this.value - this.target) - damping * this.velocity; this.velocity += accel * h; this.value += this.velocity * h; } if ( Math.abs(this.velocity) < restVelocity && Math.abs(this.value - this.target) < restDistance ) { this.set(this.target); return false; } return true; } } const clamp = (v: number, min: number, max: number) => Math.min(max, Math.max(min, v)); /** iOS-style resistance past a bound. */ function rubber(value: number, min: number, max: number, dimension: number) { const over = value < min ? value - min : value > max ? value - max : 0; if (over === 0 || dimension === 0) return value; const eased = Math.sign(over) * (1 - 1 / (Math.abs(over) / dimension / RUBBER + 1)) * dimension; return (over < 0 ? min : max) + eased; } /** Travel left in an inertial glide from `velocity` px/s. */ const glide = (velocity: number) => (velocity * 0.92) / 0.08 / 60; const distance = (a: Point, b: Point) => Math.hypot(a.x - b.x, a.y - b.y); class Velocity { private samples: { x: number; y: number; t: number }[] = []; reset(x: number, y: number, t: number) { this.samples = [{ x, y, t }]; } add(x: number, y: number, t: number) { this.samples.push({ x, y, t }); while ( this.samples.length > 2 && this.samples[0].t < t - VELOCITY_WINDOW_MS ) this.samples.shift(); } /** Average px/s over the last 100 ms. */ get(): Point { const first = this.samples[0]; const last = this.samples.at(-1); if (!first || !last || first === last || last.t <= first.t) return { x: 0, y: 0 }; const dt = (last.t - first.t) / 1000; return { x: (last.x - first.x) / dt, y: (last.y - first.y) / dt }; } } type Gesture = | { kind: 'idle' } | { kind: 'pending'; paging: { target: number; velocity: number } | null; returning: boolean; pan: Point; } | { kind: 'page' | 'dismiss' } | { kind: 'pan'; pan: Point } | { kind: 'pinch'; distance: number; scale: number; mid: Point; pan: Point }; interface Pointer extends Point { startX: number; startY: number; } /** * Turns pointer, wheel and key input into a paged, zoomable carousel. Points * are in px relative to the viewport's top left; `subscribe` hears every frame. */ export class LightboxEngine { index: number; private count = 1; private viewport: Size = { width: 0, height: 0 }; private natural: (Size | undefined)[] = []; private fitted: Size[] = []; private transforms: Transform[] = []; private trackX = new Spring(0); private dismissY = new Spring(0); private scale = new Spring(1, SCALE); private panX = new Spring(0); private panY = new Spring(0); private springs = [ this.trackX, this.dismissY, this.scale, this.panX, this.panY, ]; private gesture: Gesture = { kind: 'idle' }; private pointers = new Map(); private velocity = new Velocity(); private lastTap = { t: -Infinity, x: 0, y: 0 }; private frame: number | null = null; private lastFrame = 0; private listeners = new Set<(state: LightboxState) => void>(); constructor( index: number, private onDismiss: () => void, ) { this.index = index; } subscribe(listener: (state: LightboxState) => void): () => void { this.listeners.add(listener); listener(this.state()); return () => this.listeners.delete(listener); } /** Takes the viewport size and the images' natural sizes, as they become known. */ setGeometry(viewport: Size, natural: (Size | undefined)[]) { this.viewport = viewport; this.count = Math.max(1, natural.length); this.natural = natural; this.transforms = Array.from( { length: this.count }, (_, i) => this.transforms[i] ?? { ...IDENTITY }, ); this.fitted = Array.from({ length: this.count }, (_, i) => this.fit(i)); if (this.pointers.size === 0 && !this.springs.some((s) => s.animating)) { this.trackX.set(-this.index * viewport.width); this.clampPan(); } this.emit(); } /** Pages to `index`, clamped to the images, resetting the departing image's zoom. */ goTo(index: number, animated = true) { const target = clamp(index, 0, this.count - 1); if (target === this.index) return; this.transforms[this.index] = { ...IDENTITY }; this.index = target; this.loadTransform(); const x = -target * this.viewport.width; if (!animated) { this.trackX.set(x); this.emit(); return; } this.trackX.animateTo(x); this.run(); } pointerDown(id: number, x: number, y: number) { const returning = this.scale.animating && this.scale.value > MIN_SCALE + 0.001 && this.scale.target <= MIN_SCALE + 0.01; const paging = this.trackX.animating ? { target: this.trackX.target, velocity: this.trackX.velocity } : null; this.stop(); const t = performance.now(); if (this.pointers.size === 0) { if ( t - this.lastTap.t < DOUBLE_TAP_MS && distance({ x, y }, this.lastTap) < DOUBLE_TAP_DIST ) { this.lastTap.t = -Infinity; this.doubleTap(x, y); return; } this.lastTap = { t, x, y }; } this.pointers.set(id, { x, y, startX: x, startY: y }); this.velocity.reset(x, y, t); if (this.pointers.size === 2) this.beginPinch(); else if (this.pointers.size === 1) { const pan = { x: this.panX.value, y: this.panY.value }; this.gesture = { kind: 'pending', paging, returning, pan }; if (returning) this.fitBack(); } this.emit(); } pointerMove(id: number, x: number, y: number) { const p = this.pointers.get(id); if (!p) return; p.x = x; p.y = y; this.velocity.add(x, y, performance.now()); if (this.gesture.kind === 'pinch' && this.pointers.size >= 2) { this.updatePinch(this.gesture); this.emit(); } else if (this.updateDrag(p)) this.emit(); } pointerUp(id: number, x?: number, y?: number) { if (!this.pointers.has(id)) return; if (x !== undefined && y !== undefined) this.velocity.add(x, y, performance.now()); this.pointers.delete(id); const v = this.velocity.get(); if (this.gesture.kind === 'pinch' && this.pointers.size < 2) { const [survivor] = this.pointers.values(); if (!survivor) { this.gesture = { kind: 'idle' }; this.settleZoom(v); return; } // The finger left on the glass carries on as a pan. survivor.startX = survivor.x; survivor.startY = survivor.y; this.velocity.reset(survivor.x, survivor.y, performance.now()); const pan = { x: this.panX.value, y: this.panY.value }; this.gesture = { kind: 'pan', pan }; if (this.scale.value <= 1) this.fitBack(); this.emit(); return; } if (this.pointers.size === 0) this.endDrag(v); } /** Zooms around the cursor; negative `deltaY` zooms in. */ wheel(x: number, y: number, deltaY: number) { this.stop(); this.trackX.set(-this.index * this.viewport.width); const focal = this.centred(x, y); const s = clamp( this.scale.value * Math.exp(-deltaY * 0.01), MIN_SCALE, MAX_SCALE, ); const c = this.content(focal, this.panNow(), this.scale.value); this.scale.set(s); this.panX.set(focal.x - c.x * s); this.panY.set(focal.y - c.y * s); this.clampPan(); this.emit(); } /** Clears every pointer, as when the browser stops sending them. */ release() { for (const id of [...this.pointers.keys()]) this.pointerUp(id); } destroy() { this.stop(); this.listeners.clear(); this.pointers.clear(); } private beginPinch() { this.trackX.set(-this.index * this.viewport.width); const [a, b] = [...this.pointers.values()]; this.gesture = { kind: 'pinch', distance: distance(a, b), scale: this.scale.value, mid: this.centred((a.x + b.x) / 2, (a.y + b.y) / 2), pan: this.panNow(), }; } private updatePinch(pinch: Extract) { const [a, b] = [...this.pointers.values()]; const mid = this.centred((a.x + b.x) / 2, (a.y + b.y) / 2); const raw = (pinch.scale * distance(a, b)) / Math.max(pinch.distance, 0.001); const s = clamp(raw, MIN_SCALE * 0.85, MAX_SCALE * 1.1); const c = this.content(pinch.mid, pinch.pan, pinch.scale); const bounds = this.bounds(s); this.scale.set(s); this.panX.set(clamp(mid.x - c.x * s, bounds.minX, bounds.maxX)); this.panY.set(clamp(mid.y - c.y * s, bounds.minY, bounds.maxY)); } private updateDrag(p: Pointer): boolean { const dx = p.x - p.startX; const dy = p.y - p.startY; let g = this.gesture; if (g.kind === 'pending') { if (this.scale.value > 1.001 && !g.returning) g = { kind: 'pan', pan: g.pan }; else if (Math.abs(dx) > AXIS_LOCK_PX || Math.abs(dy) > AXIS_LOCK_PX) g = { kind: Math.abs(dx) > Math.abs(dy) ? 'page' : 'dismiss' }; else return false; this.gesture = g; } const { width, height } = this.viewport; if (g.kind === 'dismiss') this.dismissY.set(dy); else if (g.kind === 'page') { const x = -this.index * width + dx; this.trackX.set(rubber(x, -(this.count - 1) * width, 0, width)); } else if (g.kind === 'pan') { const b = this.bounds(this.scale.value); this.panX.set(rubber(g.pan.x + dx, b.minX, b.maxX, width)); this.panY.set(rubber(g.pan.y + dy, b.minY, b.maxY, height)); } return true; } private endDrag(v: Point) { const g = this.gesture; this.gesture = { kind: 'idle' }; if (g.kind === 'dismiss') { const pulled = Math.abs(this.dismissY.value); if (pulled > DISMISS_THRESHOLD_PX || Math.abs(v.y) > DISMISS_VELOCITY) this.onDismiss(); this.dismissY.animateTo(0, v.y); this.run(); } else if (g.kind === 'page') this.commitPage(v.x); else if (g.kind === 'pan') this.settleZoom(v); else if (g.kind === 'pending' && g.paging) { this.trackX.animateTo(g.paging.target, g.paging.velocity); this.run(); } else this.emit(); } private commitPage(vx: number) { const width = this.viewport.width; const dragged = this.trackX.value + this.index * width; let target = this.index; if (Math.abs(dragged / width) > PAGE_THRESHOLD || Math.abs(vx) > PAGE_FLING) target += dragged < 0 ? 1 : -1; target = clamp(target, 0, this.count - 1); if (target !== this.index) { this.transforms[this.index] = { ...IDENTITY }; this.index = target; this.loadTransform(); } this.trackX.animateTo(-this.index * width, vx); this.run(); } private settleZoom(v: Point) { if (this.scale.value <= MIN_SCALE + 0.001) { this.scale.animateTo(MIN_SCALE, 0); this.panX.animateTo(0, v.x); this.panY.animateTo(0, v.y); } else { const s = clamp(this.scale.value, MIN_SCALE, MAX_SCALE); const b = this.bounds(s); this.scale.animateTo(s, 0); this.panX.animateTo( clamp(this.panX.value + glide(v.x), b.minX, b.maxX), v.x, ); this.panY.animateTo( clamp(this.panY.value + glide(v.y), b.minY, b.maxY), v.y, ); } this.run(); } private doubleTap(x: number, y: number) { this.trackX.animateTo(-this.index * this.viewport.width, 0); if (this.scale.value > MIN_SCALE + 0.01) this.fitBack(); else { const focal = this.centred(x, y); const c = this.content(focal, this.panNow(), this.scale.value); const s = DOUBLE_TAP_SCALE; const b = this.bounds(s); this.scale.animateTo(s, 0); this.panX.animateTo(clamp(focal.x - c.x * s, b.minX, b.maxX), 0); this.panY.animateTo(clamp(focal.y - c.y * s, b.minY, b.maxY), 0); } this.run(); } /** Springs the image back to its fitted size. */ private fitBack() { this.scale.animateTo(MIN_SCALE, 0); this.panX.animateTo(0, 0); this.panY.animateTo(0, 0); this.run(); } private panNow(): Point { return { x: this.panX.value, y: this.panY.value }; } private centred(x: number, y: number): Point { return { x: x - this.viewport.width / 2, y: y - this.viewport.height / 2 }; } /** The point of the unzoomed image under `focal`. */ private content(focal: Point, pan: Point, scale: number): Point { return { x: (focal.x - pan.x) / scale, y: (focal.y - pan.y) / scale }; } private fit(i: number): Size { const natural = this.natural[i]; const { width, height } = this.viewport; if (!natural?.width || !natural.height || !width || !height) return { width: 0, height: 0 }; const contain = Math.min(width / natural.width, height / natural.height); const k = contain <= 1 ? contain : Math.min(contain, Math.max(1, MIN_COVERAGE * contain)); return { width: natural.width * k, height: natural.height * k }; } private bounds(scale: number) { const fit = this.fitted[this.index] ?? this.fit(this.index); const overX = Math.max(0, (fit.width * scale - this.viewport.width) / 2); const overY = Math.max(0, (fit.height * scale - this.viewport.height) / 2); return { minX: -overX, maxX: overX, minY: -overY, maxY: overY }; } private clampPan() { const b = this.bounds(this.scale.value); this.panX.set(clamp(this.panX.value, b.minX, b.maxX)); this.panY.set(clamp(this.panY.value, b.minY, b.maxY)); } private loadTransform() { const t = this.transforms[this.index] ?? IDENTITY; this.scale.set(t.scale); this.panX.set(t.x); this.panY.set(t.y); } private stop() { if (this.frame !== null) cancelAnimationFrame(this.frame); this.frame = null; for (const s of this.springs) s.set(s.value); } private run() { if (this.frame !== null) return; this.lastFrame = performance.now(); const tick = (t: number) => { const dt = Math.max(0, (t - this.lastFrame) / 1000); this.lastFrame = t; let moving = false; for (const s of this.springs) if (s.step(dt)) moving = true; this.frame = moving ? requestAnimationFrame(tick) : null; this.emit(); }; this.frame = requestAnimationFrame(tick); } private state(): LightboxState { const transforms = this.transforms.map((t, i) => i === this.index ? { scale: this.scale.value, x: this.panX.value, y: this.panY.value } : t, ); const g = this.gesture.kind; return { index: this.index, transforms, fitted: this.fitted, trackX: this.trackX.value, dismissY: this.dismissY.value, backdropOpacity: clamp( 1 - Math.abs(this.dismissY.value) / DISMISS_FADE_PX, 0, 1, ), dragging: this.pointers.size > 0, moved: g === 'page' || g === 'dismiss' || g === 'pan' || g === 'pinch', zoomed: this.scale.value > 1.01, }; } private emit() { const state = this.state(); for (const listener of this.listeners) listener(state); } }