Skip to content

The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.

Studio: the viewer's picture zooms about the pointer and pans (#300)

riverisbuildinga17102cf042b
diff --git a/.changeset/viewer-zoom.md b/.changeset/viewer-zoom.md
new file mode 100644
index 0000000..e52039a
--- /dev/null
+++ b/.changeset/viewer-zoom.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+Studio: the picture in the viewer zooms and pans. Pinch on a trackpad, or hold ⌘ (Ctrl on Windows) and turn the mouse wheel, to zoom about the pointer; while it is zoomed, scroll (Shift + wheel: sideways) or drag with the middle button to pan. The zoom shows in the viewer's bar, and pressing it fits the picture again. Selecting, moving and resizing on the picture work at any zoom, with handles the same size on screen. Once a zoom has settled, the film is drawn again behind the picture for its new size, so canvas and 3D pages are as sharp as they are seen, past the film's own size up to 64 megapixels a page; a drag, words typed in place or a crop meanwhile carry on, and the new drawing is shown when they end, with what they kept. When the film is drawn again (after a zoom or a resized viewer), the picture no longer flashes blank. The zoom changes only the viewer, never the film or its exports.
diff --git a/packages/openfilm/studio/server/bridge.js b/packages/openfilm/studio/server/bridge.js
index 71e8f85..65d434c 100644
--- a/packages/openfilm/studio/server/bridge.js
+++ b/packages/openfilm/studio/server/bridge.js
@@ -201,6 +201,9 @@
Playing, the next frame draws it */
if (inPlace && line) lastT = null;
else if (inPlace && !next) { next = { t: asked, seq: m.seq }; draw(); }
+ /* a draw already waiting draws it too: it says so under this update's seq, which the editor waits for (a load
+ behind the picture is shown once it has drawn the film as it is now) */
+ else if (inPlace) next.seq = Math.max(Number(next.seq) || 0, Number(m.seq) || 0);
}
if (m.type === 'renders') editor()?.renders?.(m.list);
if (m.type === 'preview') editor()?.preview(m.clip, m.overrides);
diff --git a/packages/openfilm/studio/server/bridge.test.mjs b/packages/openfilm/studio/server/bridge.test.mjs
index cab309c..3fd1c19 100644
--- a/packages/openfilm/studio/server/bridge.test.mjs
+++ b/packages/openfilm/studio/server/bridge.test.mjs
@@ -61,6 +61,23 @@ test('an edit changed in place while the first moment is still drawing is drawn
assert.deepEqual(page.said.filter((m) => m.type === 'seeked').map((m) => m.t), [5, 5]);
});
+test('edits that come one after another while a moment is drawing: the draw that shows them says so under the last edit\'s seq', async () => {
+ const page = filmPage();
+ await page.settle();
+ page.send({ type: 'seek', t: 2, seq: 1, behind: true });
+ await page.settle();
+ /* two edits while 2 s is still drawing: the first queues a draw, the second finds it waiting */
+ await page.send({ type: 'update', film: {}, seq: 2 });
+ await page.settle();
+ await page.send({ type: 'update', film: {}, seq: 3 });
+ await page.settle();
+ page.drawn[0].done();
+ await page.settle();
+ page.drawn[1].done();
+ await page.settle();
+ assert.deepEqual(page.said.filter((m) => m.type === 'seeked').map((m) => [m.t, m.seq]), [[2, 1], [2, 3]]);
+});
+
test('a load of the film behind the picture shown says its first moment is drawn only once it is, however long that takes', async () => {
const page = filmPage();
await page.settle();
diff --git a/packages/openfilm/studio/server/stage.js b/packages/openfilm/studio/server/stage.js
index bd8a943..d641dd9 100644
--- a/packages/openfilm/studio/server/stage.js
+++ b/packages/openfilm/studio/server/stage.js
@@ -13,6 +13,8 @@
* { type: 'stage-event', event: 'text', handle, commit, value?, before? } an in-place edit ended
* { type: 'stage-event', event: 'key', key, code, repeat, metaKey, ctrlKey, shiftKey, altKey }
* a key pressed in the picture (not while typing in it)
+ * { type: 'stage-event', event: 'wheel', x, y, deltaX, deltaY, deltaMode, ctrlKey, metaKey, shiftKey, buttons }
+ * a wheel or pinch over the picture (the viewer's zoom)
*
* Points and boxes are in stage px (the film's own size, before the editor scales its frame). A layer is named by a
* `handle` (a number, good while its element is in the page) and by `loc`: its selector, with `#n` when the selector
@@ -28,8 +30,10 @@
const hooks = () => window.__filmEditor?.stage;
const clips = () => hooks()?.clips() ?? [];
- /* ── handles: a number per element, kept weakly ── */
- let nextHandle = 1;
+ /* ── handles: a number per element, kept weakly; counted from this load of the film's own base (its `load`, see
+ editor/Preview), so a handle the editor kept from an earlier load names nothing here, and the layer is found by its
+ selector instead ── */
+ let nextHandle = (Number(new URL(location.href).searchParams.get('load')) || 0) * 2 ** 32 + 1;
const byHandle = new Map();
const handles = new WeakMap();
const handleOf = (el) => {
@@ -1028,12 +1032,32 @@
if ((EDITOR_KEYS.has(e.key) && !mod) || (mod && (k === 'z' || (k === 'a' && !e.shiftKey && !e.altKey) || (e.shiftKey && (k === 'h' || k === 'l'))))) e.preventDefault();
post({ type: 'stage-event', event: 'key', key: e.key, code: e.code, repeat: e.repeat, metaKey: e.metaKey, ctrlKey: e.ctrlKey, shiftKey: e.shiftKey, altKey: e.altKey });
};
+ /*
+ * A wheel or a pinch over the picture reaches here only while words are typed in it (the editor's overlay steps aside
+ * then): sent on for the viewer's zoom and pan, at its place in stage px. ⌘/Ctrl + wheel is never the page's (a
+ * browser would zoom all of Studio).
+ */
+ const onWheel = (e) => {
+ if (e.ctrlKey || e.metaKey) e.preventDefault();
+ let x = e.clientX, y = e.clientY;
+ for (let win = e.view; win && win !== window && win.frameElement; win = win.parent) {
+ const frame = win.frameElement;
+ const r = frame.getBoundingClientRect();
+ x = r.left + x * (r.width / (frame.clientWidth || r.width));
+ y = r.top + y * (r.height / (frame.clientHeight || r.height));
+ }
+ post({
+ type: 'stage-event', event: 'wheel', x, y, deltaX: e.deltaX, deltaY: e.deltaY, deltaMode: e.deltaMode,
+ ctrlKey: e.ctrlKey, metaKey: e.metaKey, shiftKey: e.shiftKey, buttons: e.buttons,
+ });
+ };
/* by document: a page closed and opened again (the timeline does, far from the playhead) is a new one to hear */
const listening = new WeakSet();
const listen = (win) => {
if (!win?.document || listening.has(win.document)) return;
listening.add(win.document);
win.addEventListener('keydown', onKey, true);
+ win.addEventListener('wheel', onWheel, { capture: true, passive: false });
};
const listenAll = () => { listen(window); for (const c of clips()) if (c.win) listen(c.win); };
listen(window);
diff --git a/packages/openfilm/studio/server/stage.test.mjs b/packages/openfilm/studio/server/stage.test.mjs
index 045956c..e9aa472 100644
--- a/packages/openfilm/studio/server/stage.test.mjs
+++ b/packages/openfilm/studio/server/stage.test.mjs
@@ -16,7 +16,7 @@ const STAGE = readFileSync(new URL('./stage.js', import.meta.url), 'utf8');
const samePlace = (now, was, message) => assert.ok(now.every((v, i) => Math.abs(v - was[i]) < 0.5), `${message} (${JSON.stringify(now)}, was ${JSON.stringify(was)})`);
/** A film served with Studio's stage in it, the page itself standing in for the editor (its own origin). */
-async function stageOf(dir) {
+async function stageOf(dir, query = '') {
let files = null;
const server = createServer((req, res) => {
const url = new URL(req.url, 'http://x');
@@ -30,7 +30,7 @@ async function stageOf(dir) {
const page = await browser.newPage({ viewport: { width: 320, height: 180 } });
/* a setup that fails closes what it opened: a browser left open keeps the test file, and the run, from ending */
try {
- await page.goto(`${origin}/film.html`);
+ await page.goto(`${origin}/film.html${query}`);
/* window.film may not be there yet when the page has loaded */
await page.waitForFunction(() => Boolean(window.film));
await page.evaluate(async () => { await window.film.ready; await window.film.frame(0.5); });
@@ -77,6 +77,27 @@ test('a click on a page\'s backdrop (a box filling the page) takes the clip, not
}
});
+test('handles are counted from the load of the film: one kept from an earlier load names nothing, and the layer is found by its selector', { timeout: 60_000 }, async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-stage-handles-'));
+ writeFileSync(join(dir, 'card.html'), `<!doctype html><body style="margin:0">
+ <h1 id="title" style="position:absolute;left:20px;top:20px;margin:0;font:700 24px sans-serif">Every parcel</h1>
+ <div id="card" style="position:absolute;left:200px;top:100px;width:80px;height:50px;background:#f60"></div>
+<script>window.film={duration:2,frame(){}}</script></body>`);
+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [{ id: 'card', src: 'card.html' }] }] }));
+ const stage = await stageOf(dir, '?load=3');
+ try {
+ const title = await stage.ask('hit', { x: 40, y: 30, detail: true });
+ const card = await stage.ask('hit', { x: 240, y: 125, detail: true });
+ assert.ok(title.handle > 3 * 2 ** 32 && card.handle > 3 * 2 ** 32, 'counted from the load');
+ /* the card's handle in the first load of the film was a small number, maybe the title's here once: never now */
+ const kept = await stage.ask('layer', { handle: card.handle - 3 * 2 ** 32, clip: card.clip, at: card.at, n: card.n });
+ assert.equal(kept?.handle, card.handle, 'found by its selector: the card, not another layer');
+ assert.equal(kept?.kind, 'box');
+ } finally {
+ await stage.close();
+ }
+});
+
test('a click on a title under a full-frame overlay (letterbox, vignette) takes the title; on nothing but the overlay, the clip', { timeout: 60_000 }, async () => {
const dir = mkdtempSync(join(tmpdir(), 'of-stage-overlay-'));
writeFileSync(join(dir, 'title.html'), `<!doctype html><body style="margin:0">
diff --git a/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx b/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx
index da1a8cb..8736e57 100644
--- a/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx
+++ b/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx
@@ -60,7 +60,7 @@ import { spanShows, type ClipSpan } from '@/lib/film-shape';
import {
mgSize, moveTransform, rotateTransform, sameMgTransform, snapMove, type MgBox, type MgGuide, type MgTransform,
} from '@/lib/mg-transform';
-import { compactBox, transformOf } from '@/lib/stage-clip';
+import { compactBox, liveLookStands, transformOf } from '@/lib/stage-clip';
import {
aspectRatio, CROP_ASPECTS, cropOfRect, cropPreviewCss, croppedCss, cropRect, draggedCrop, fitAspect, frameAabb, pannedCrop,
positionOf, roundOf, transformOfVisible, visibleFrame, type CropAspect, type Rect,
@@ -566,6 +566,10 @@ function FilmStageSelectImpl({
const [lookLive, setLookLive] = React.useState<{ clipLoc: string; css: string; written: string } | null>(null);
const lookLiveRef = React.useRef(lookLive);
lookLiveRef.current = lookLive;
+ /* film.html's style changed under it (kept, undone): over for good, so another load of the film does not show it */
+ React.useEffect(() => {
+ if (lookLiveRef.current && !liveLookStands(doc, lookLiveRef.current)) setLookLive(null);
+ }, [doc]);
const infoOf = (loc: string) => {
const live = lookLiveRef.current;
return clipInfo(docRef.current, spansRef.current, stage, loc, live?.clipLoc === loc ? live : null);
@@ -1277,9 +1281,11 @@ function FilmStageSelectImpl({
if (textEdit.current) { textEdit.current = null; setEditingText(null); }
syncFilmOffsetRef.current();
syncGeomSoon();
+ reshowRef.current();
}
});
}, [previewRef, syncGeomSoon]);
+ const reshowRef = React.useRef<() => void>(() => {});
const onTextDoneRef = React.useRef(onTextDone);
onTextDoneRef.current = onTextDone;
const onTypingRef = React.useRef(onTyping);
@@ -1746,6 +1752,15 @@ function FilmStageSelectImpl({
const [maskSession, setMaskSession] = React.useState<MaskSession | null>(null);
const cropRef = React.useRef<CropSession | null>(null);
const cropPaint = React.useMemo(() => new Latest<{ clip: string; css: string | null }>(async (a) => { await ask('look', a); }), [ask]);
+ /* another load of the film shown: the looks shown on the old one, not kept yet (the inspector's, a crop's), shown on it */
+ reshowRef.current = () => {
+ const live = lookLiveRef.current;
+ const at = live ? parseFilmDocLoc(live.clipLoc) : null;
+ const id = at ? docRef.current?.tracks[at.track]?.clips[at.clip]?.id : undefined;
+ if (live && id && liveLookStands(docRef.current, live)) void ask('look', { clip: id, css: live.css });
+ const crop = cropRef.current;
+ if (crop) cropPaint.push({ clip: crop.clipId, css: cropPreviewCss(crop.css0, crop.pos0, crop.pos) });
+ };
const setCrop = (next: CropSession | null) => {
cropRef.current = next;
setCroppingState(next);
@@ -2827,6 +2842,9 @@ function FilmStageSelectImpl({
<div
ref={host}
data-film-select
+ /* words typed in place or a crop open: a film loaded again behind the picture waits (ViewerZoom's busy); a mask
+ is only while its knobs are held, as any drag */
+ data-stage-busy={editingText != null || cropping ? '' : undefined}
/* below the subtitles (z-5): they must get the pointer in their own box to be dragged */
/* the cursor stays an arrow: text cursors over the size label would read as "this can be typed in" */
className="absolute inset-0 z-[4] cursor-default overflow-visible"
diff --git a/packages/openfilm/studio/ui/src/components/ProjectView.tsx b/packages/openfilm/studio/ui/src/components/ProjectView.tsx
index 2fbe53a..c5af0e3 100644
--- a/packages/openfilm/studio/ui/src/components/ProjectView.tsx
+++ b/packages/openfilm/studio/ui/src/components/ProjectView.tsx
@@ -49,6 +49,7 @@ import { useLoadedThumbs } from '@/lib/use-loaded-thumbs';
import { droppedOverrides, overrideTarget, undoneFields, type DroppedEdits, type PersonEdit } from '@/lib/dropped-overrides';
import { filmFrameBox, type FilmFrameId } from '@/lib/film-frame';
import { canvasFor, firstPictureSize, fitToCanvas } from '@/lib/canvas-fit';
+import { createViewerZoom } from '@/lib/viewer-zoom';
import { factsOfProbe, mediaListingOf, resourceKindOf, srcHitsAsset, warmProjectMedia, type MediaListing, type MediaProxy, type MediaResult, type MediaSources, type WorkspaceResource } from '@/lib/workspace-resources';
import { BrandLoadingScreen } from './BrandLoadingScreen';
import { BrandLogo } from './BrandLogo';
@@ -90,6 +91,7 @@ import { historyMoved } from '@/lib/project-history';
import { ProjectsPopover } from './ProjectsLibrary';
import { FilmFullscreenBar, useFullscreenKeys } from './FilmFullscreenBar';
import { ViewerBar } from './ViewerBar';
+import { ViewerZoom, ViewerZoomButton } from './ViewerZoom';
import { LiveTime, type PlaybackClock } from './LiveTime';
import { Toast, useToast } from './Toast';
import { SpendAsks } from './SpendAsks';
@@ -150,10 +152,6 @@ const TITLE_MAX_CHARS = 56;
const TOP_BTN =
'flex h-[26px] w-[26px] shrink-0 items-center justify-center rounded-md text-[var(--text-dim)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]';
-const fitBox = (w: number, h: number): React.CSSProperties => ({
- width: `min(100cqw, 100cqh * ${w} / ${h})`,
- height: `min(100cqh, 100cqw * ${h} / ${w})`,
-});
const clampTitle = (title: string) => (title.length > TITLE_MAX_CHARS ? `${title.slice(0, TITLE_MAX_CHARS)}…` : title);
/**
@@ -1232,6 +1230,8 @@ export function ProjectView({ projectId, onProject, onLeave }: {
const lookPreviewRef = React.useRef<((clipLoc: string, css: string | null) => void) | null>(null);
/* where the thing in hand is, for the inspector only: it changes every frame of a drag */
const geometryStore = React.useMemo(() => createGeometryStore(), []);
+ /* the viewer's zoom: only the picture and its fit button re-render as it changes (components/ViewerZoom) */
+ const viewerZoom = React.useMemo(() => createViewerZoom(), []);
const [stageSelectRequest, setStageSelectRequest] = React.useState<{ loc: string; clipLoc?: string; seq: number } | null>(null);
const [inlineTextFailure, setInlineTextFailure] = React.useState<{ loc: string; value: string; failure: StageEditFailure; seq: number } | null>(null);
const setSelectedLocs = React.useCallback((locs: readonly string[]) => {
@@ -2919,8 +2919,23 @@ export function ProjectView({ projectId, onProject, onLeave }: {
{value ? (
<div ref={stageFullRef} className={`relative flex h-full w-full items-center justify-center ${fullscreen ? 'bg-black' : ''}`}
style={{ containerType: 'size' }} onClick={fullscreen ? toggle : undefined}>
- <div className={`relative bg-black ${frameBox.inner.left < -0.5 || frameBox.inner.top < -0.5 ? 'overflow-hidden' : 'overflow-visible'}`}
- style={{ ...fitBox(frameBox.w, frameBox.h), containerType: 'size' }}>
+ <ViewerZoom store={viewerZoom} frame={frameBox} off={fullscreen}
+ className={`relative bg-black ${frameBox.inner.left < -0.5 || frameBox.inner.top < -0.5 ? 'overflow-hidden' : 'overflow-visible'}`}
+ notices={<>
+ {/* a clip under the playhead whose file is gone plays as nothing (src/timeline.mjs, film-missing):
+ said here, over the picture, with what to do; in sight at any zoom */}
+ {statsOn && playing && played ? (
+ <div data-playback-stats="" className="pointer-events-none absolute right-2 top-2 z-10 rounded-[4px] bg-black/75 px-2 py-1 font-mono text-[11px] tabular-nums text-white">
+ {t('viewer.stats').replace('{fps}', String(Math.round((played.drawn * 1000) / Math.max(1, played.ms)))).replace('{late}', String(Math.round((played.late * 1000) / Math.max(1, played.ms))))}
+ {played.rendered ? ` · ${t('viewer.statsRendered')}` : ''}
+ </div>
+ ) : null}
+ {missingHere && !fullscreen ? (
+ <div data-preview-missing="" className="pointer-events-none absolute left-2 top-2 z-10 max-w-[80%] truncate rounded-[4px] bg-black/75 px-2 py-1 text-[11px] text-white">
+ {t('project.previewMissing').replace('{file}', missingHere)}
+ </div>
+ ) : null}
+ </>}>
<div className="absolute" style={{
left: `${(frameBox.inner.left / frameBox.w) * 100}%`,
top: `${(frameBox.inner.top / frameBox.h) * 100}%`,
@@ -2967,19 +2982,6 @@ export function ProjectView({ projectId, onProject, onLeave }: {
) : null}
</Preview>
</div>
- {/* a clip under the playhead whose file is gone plays as nothing (src/timeline.mjs, film-missing):
- said here, over the picture, with what to do */}
- {statsOn && playing && played ? (
- <div data-playback-stats="" className="pointer-events-none absolute right-2 top-2 z-10 rounded-[4px] bg-black/75 px-2 py-1 font-mono text-[11px] tabular-nums text-white">
- {t('viewer.stats').replace('{fps}', String(Math.round((played.drawn * 1000) / Math.max(1, played.ms)))).replace('{late}', String(Math.round((played.late * 1000) / Math.max(1, played.ms))))}
- {played.rendered ? ` · ${t('viewer.statsRendered')}` : ''}
- </div>
- ) : null}
- {missingHere && !fullscreen ? (
- <div data-preview-missing="" className="pointer-events-none absolute left-2 top-2 z-10 max-w-[80%] truncate rounded-[4px] bg-black/75 px-2 py-1 text-[11px] text-white">
- {t('project.previewMissing').replace('{file}', missingHere)}
- </div>
- ) : null}
{!viewerReady && !empty && !previewError ? (
<div className="pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center gap-3 bg-black">
<span role="status" className="text-sweep relative text-[13px] text-white/60">{t('project.previewStageMount')}</span>
@@ -2997,7 +2999,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
onPick={fullscreen ? undefined : showSubtitleLook}
/>
)}</LiveTime>
- </div>
+ </ViewerZoom>
{fullscreen ? (
<FilmFullscreenBar
hostRef={stageFullRef}
@@ -3043,6 +3045,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
onSpeed: setSpeed,
}}
onFullscreen={toggleFullscreen}
+ extra={<ViewerZoomButton store={viewerZoom} />}
/>
</div>
diff --git a/packages/openfilm/studio/ui/src/components/ViewerZoom.tsx b/packages/openfilm/studio/ui/src/components/ViewerZoom.tsx
new file mode 100644
index 0000000..c1d1037
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/components/ViewerZoom.tsx
@@ -0,0 +1,252 @@
+/**
+ * The viewer's picture, zoomed and panned (lib/viewer-zoom): a pinch or ⌘/Ctrl + wheel zooms about
+ * the pointer; while it is not fitted, a scroll (Shift + wheel: sideways) or a drag with the middle button pans. The
+ * picture is laid out at its zoomed size, not scaled by a transform, so the stage's handles, outlines and snapping,
+ * all measured on screen, keep their size and feel at any zoom. ViewerZoomButton, in the viewer's bar, fits it again.
+ * Nothing zooms or pans while a button is held: a drag on the stage keeps the places it measured at the press.
+ * The film is drawn for the zoom once it settles (ZOOM_SETTLE_MS still, nothing held, typed or cropped): loaded again
+ * behind the picture, as for a resized viewer, so a page's canvas is as sharp as it is seen; that load is shown only
+ * when nothing is under way (`busy`), so a drag or a line typed in place started meanwhile goes on in the film it began in.
+ */
+import React from 'react';
+import { useT } from '@/i18n';
+import {
+ FIT_VIEW, PictureZoom, ZOOM_SETTLE_MS, fittedSize, isFit, panBy, shownRect, wheelPx, wheelZoomFactor, zoomAt, zoomLayout, zoomMax,
+ type ViewerView, type ViewerZoomStore,
+} from '@/lib/viewer-zoom';
+import { PANE_BTN } from './dock-pane-bar';
+import { Tooltip } from './Tooltip';
+
+type Size = { w: number; h: number };
+
+/** How long after a drag or an edit in place ends a new drawing of the film still waits: its edit is written by then. */
+const BUSY_AFTER_MS = 600;
+
+/** The picture fitted in its container (the container's size, CSS container units). */
+const fitBox = (w: number, h: number): React.CSSProperties => ({
+ width: `min(100cqw, 100cqh * ${w} / ${h})`,
+ height: `min(100cqh, 100cqw * ${h} / ${w})`,
+});
+
+export function ViewerZoom({ store, frame, off, className, notices, children }: {
+ store: ViewerZoomStore;
+ /** The film's canvas, px. */
+ frame: Size;
+ /** Fitted and still (full screen): the zoom is kept for when it comes back. */
+ off?: boolean;
+ /** The picture's box's classes. */
+ className?: string;
+ /** Over the part of the picture on screen, not on it: notices that must stay in sight at any zoom. */
+ notices?: React.ReactNode;
+ children?: React.ReactNode;
+}) {
+ const scroller = React.useRef<HTMLDivElement>(null);
+ const { view } = React.useSyncExternalStore(store.subscribe, store.get, store.get);
+ const [viewer, setViewer] = React.useState<Size | null>(null);
+ React.useLayoutEffect(() => {
+ const el = scroller.current;
+ if (!el) return undefined;
+ const size = () => setViewer((had) => (had && had.w === el.clientWidth && had.h === el.clientHeight ? had : { w: el.clientWidth, h: el.clientHeight }));
+ size();
+ const observer = new ResizeObserver(size);
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, []);
+ const fitted = viewer && viewer.w > 0 && viewer.h > 0 ? fittedSize(viewer, frame) : null;
+ React.useEffect(() => { store.setFitK(fitted ? fitted.w / frame.w : null); }, [store, fitted?.w, frame.w]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ const layout = !off && viewer && fitted && !isFit(view) ? zoomLayout(view, viewer, fitted) : null;
+ /* the scroll is the view's center: put there in the same frame as the size, so a zoom never jumps */
+ React.useLayoutEffect(() => {
+ const el = scroller.current;
+ if (!el || !layout) return;
+ el.scrollLeft = layout.scroll.x;
+ el.scrollTop = layout.scroll.y;
+ });
+
+ /* a button held anywhere (a drag on the stage, a pan): no zoom, and the film is not drawn again under it */
+ const held = React.useRef(false);
+ /* when the last of them ended (performance.now()): what it kept reaches the film a moment later */
+ const ended = React.useRef(-Infinity);
+ React.useEffect(() => {
+ const onPress = (e: PointerEvent) => {
+ if (held.current && e.buttons === 0) ended.current = performance.now();
+ held.current = e.buttons !== 0;
+ };
+ const onLetGo = () => {
+ if (held.current) ended.current = performance.now();
+ held.current = false;
+ };
+ window.addEventListener('pointerdown', onPress, true);
+ window.addEventListener('pointerup', onPress, true);
+ window.addEventListener('pointercancel', onLetGo, true);
+ window.addEventListener('blur', onLetGo);
+ /* the stage says when words are typed in place or a crop is open (FilmStageSelect, data-stage-busy) */
+ const stage = new MutationObserver((changes) => {
+ if (changes.some((c) => c.oldValue != null && !(c.target as Element).hasAttribute('data-stage-busy'))) ended.current = performance.now();
+ });
+ if (scroller.current) stage.observe(scroller.current, { subtree: true, attributes: true, attributeOldValue: true, attributeFilter: ['data-stage-busy'] });
+ return () => {
+ window.removeEventListener('pointerdown', onPress, true);
+ window.removeEventListener('pointerup', onPress, true);
+ window.removeEventListener('pointercancel', onLetGo, true);
+ window.removeEventListener('blur', onLetGo);
+ stage.disconnect();
+ };
+ }, []);
+
+ /**
+ * A button held (a mask's knobs too), words typed in place, a crop open, or one of them just ended (what it kept is
+ * on its way to the film, BUSY_AFTER_MS): the film is not drawn again, nor a new drawing shown.
+ */
+ const busy = React.useCallback(() => held.current || performance.now() - ended.current < BUSY_AFTER_MS
+ || Boolean(scroller.current?.querySelector('[data-film-select][data-stage-busy]')), []);
+
+ /* the zoom the film is drawn for: the shown one once it has been still a while, with nothing held or typed in */
+ const z = layout ? view.z : 1;
+ const [drawn, setDrawn] = React.useState(1);
+ React.useEffect(() => {
+ if (z === drawn) return undefined;
+ let timer = 0;
+ const settle = () => {
+ timer = window.setTimeout(() => { if (busy()) settle(); else setDrawn(z); }, ZOOM_SETTLE_MS);
+ };
+ settle();
+ return () => window.clearTimeout(timer);
+ }, [z, drawn, busy]);
+ const zoom = React.useMemo(() => ({ z, drawn, busy }), [z, drawn, busy]);
+
+ const now = React.useRef({ viewer, fitted, off });
+ now.current = { viewer, fitted, off };
+ React.useEffect(() => {
+ const el = scroller.current;
+ const area = el?.closest<HTMLElement>('[data-viewer-picture]') ?? el;
+ if (!el || !area) return undefined;
+ /* one step per frame: a pinch sends a hundred wheel events a second */
+ let factor = 1, dx = 0, dy = 0;
+ let anchor = { x: 0, y: 0 };
+ let raf = 0;
+ const flush = () => {
+ raf = 0;
+ const { viewer: v, fitted: f } = now.current;
+ if (!v || !f) { factor = 1; dx = 0; dy = 0; return; }
+ let next: ViewerView = store.get().view;
+ if (factor !== 1) next = zoomAt(next, factor, anchor, v, f, zoomMax(f.w / frame.w));
+ if (dx || dy) next = panBy(next, dx, dy, f);
+ factor = 1; dx = 0; dy = 0;
+ store.set(next);
+ };
+ const schedule = () => { if (!raf) raf = requestAnimationFrame(flush); };
+ const onWheel = (e: WheelEvent) => {
+ if (now.current.off) return;
+ if (e.ctrlKey || e.metaKey) {
+ e.preventDefault();
+ if (e.buttons) return;
+ factor *= wheelZoomFactor(wheelPx(e, e.deltaY));
+ const r = el.getBoundingClientRect();
+ anchor = { x: e.clientX - r.left, y: e.clientY - r.top };
+ schedule();
+ return;
+ }
+ if (isFit(store.get().view)) return;
+ e.preventDefault();
+ if (e.buttons) return;
+ /* a mouse's wheel turned with Shift scrolls sideways (macOS does it itself, as deltaX) */
+ const sideways = e.shiftKey && !e.deltaX;
+ dx += wheelPx(e, sideways ? e.deltaY : e.deltaX);
+ dy += sideways ? 0 : wheelPx(e, e.deltaY);
+ schedule();
+ };
+ /* the middle button drags the picture (Windows' autoscroll would take it otherwise) */
+ const onDown = (e: PointerEvent) => {
+ if (e.button !== 1 || now.current.off || isFit(store.get().view)) return;
+ e.preventDefault();
+ e.stopPropagation();
+ let last = { x: e.clientX, y: e.clientY };
+ const move = (m: PointerEvent) => {
+ dx += last.x - m.clientX;
+ dy += last.y - m.clientY;
+ last = { x: m.clientX, y: m.clientY };
+ schedule();
+ };
+ const up = () => {
+ window.removeEventListener('pointermove', move);
+ window.removeEventListener('pointerup', up);
+ window.removeEventListener('pointercancel', up);
+ };
+ window.addEventListener('pointermove', move);
+ window.addEventListener('pointerup', up);
+ window.addEventListener('pointercancel', up);
+ };
+ /* Safari sends a pinch as gesture events, its scale since the pinch began, rather than as Ctrl + wheel */
+ let pinched = 1;
+ const onGesture = (e: Event) => {
+ const g = e as Event & { scale: number; clientX: number; clientY: number };
+ e.preventDefault();
+ if (e.type === 'gesturestart') pinched = 1;
+ if (now.current.off || held.current || !(g.scale > 0)) return;
+ factor *= g.scale / pinched;
+ pinched = g.scale;
+ const r = el.getBoundingClientRect();
+ anchor = { x: g.clientX - r.left, y: g.clientY - r.top };
+ schedule();
+ };
+ area.addEventListener('wheel', onWheel, { passive: false });
+ area.addEventListener('pointerdown', onDown, true);
+ area.addEventListener('gesturestart', onGesture);
+ area.addEventListener('gesturechange', onGesture);
+ return () => {
+ area.removeEventListener('wheel', onWheel);
+ area.removeEventListener('pointerdown', onDown, true);
+ area.removeEventListener('gesturestart', onGesture);
+ area.removeEventListener('gesturechange', onGesture);
+ if (raf) cancelAnimationFrame(raf);
+ };
+ }, [store, frame.w]);
+
+ const shown = viewer && fitted ? shownRect(layout ? view : FIT_VIEW, viewer, fitted) : null;
+ /* one tree fitted or zoomed (only its styles change): the film's frames inside are never loaded again by a zoom */
+ return (
+ <>
+ <div ref={scroller} className="absolute inset-0" data-viewer-zoom={layout ? '' : undefined}
+ style={{ overflow: layout ? 'hidden' : 'visible', overflowAnchor: 'none' }}>
+ <div className={layout ? 'relative' : 'flex h-full w-full items-center justify-center'}
+ style={layout ? { width: layout.box.w, height: layout.box.h } : undefined}>
+ <div className={className}
+ style={{
+ ...(layout
+ ? { position: 'absolute', left: layout.picture.x, top: layout.picture.y, width: layout.picture.w, height: layout.picture.h }
+ : fitBox(frame.w, frame.h)),
+ containerType: 'size',
+ }}>
+ <PictureZoom.Provider value={zoom}>{children}</PictureZoom.Provider>
+ </div>
+ </div>
+ </div>
+ {notices && shown ? (
+ <div className="pointer-events-none absolute" style={{ left: shown.x, top: shown.y, width: shown.w, height: shown.h }}>{notices}</div>
+ ) : null}
+ </>
+ );
+}
+
+/** The zoom, in the viewer's bar while the picture is not fitted: a press fits it again. */
+export function ViewerZoomButton({ store }: { store: ViewerZoomStore }) {
+ const t = useT();
+ const { view, fitK } = React.useSyncExternalStore(store.subscribe, store.get, store.get);
+ if (isFit(view) || fitK == null) return null;
+ return (
+ <Tooltip label={t('viewer.zoomFit')}>
+ <button
+ type="button"
+ onClick={() => store.set(FIT_VIEW)}
+ onMouseDown={(e) => e.preventDefault()}
+ aria-label={t('viewer.zoomFit')}
+ data-viewer-zoom-fit=""
+ className={`${PANE_BTN} !w-auto min-w-[22px] px-1 text-[12px] tabular-nums outline-none focus-visible:ring-1 focus-visible:ring-[var(--accent)]`}
+ >
+ {Math.round(view.z * fitK * 100)}%
+ </button>
+ </Tooltip>
+ );
+}
diff --git a/packages/openfilm/studio/ui/src/editor/Preview.tsx b/packages/openfilm/studio/ui/src/editor/Preview.tsx
index a263c49..d4db185 100644
--- a/packages/openfilm/studio/ui/src/editor/Preview.tsx
+++ b/packages/openfilm/studio/ui/src/editor/Preview.tsx
@@ -10,14 +10,16 @@
* second, hidden frame that replaces the shown one once its first picture is drawn whole (its videos loaded, however
* long that takes), and is told the edits made meanwhile. Either way the picture never goes black for an edit.
*/
-import { forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
+import { forwardRef, useContext, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
+import { flushSync } from 'react-dom';
import type { Film } from '../api';
import { useT } from '@/i18n';
import type { ClipSpan } from '@/lib/film-shape';
import type { Anchor, Sound } from './player';
-import { pageScaleFor, reloaded, shownAfter, updateKeys, type Frame } from './preview-frames';
+import { heldNext, reloaded, shownAfter, updateKeys, zoomedPageScale, type Frame } from './preview-frames';
import { usePreviewPrefs } from '@/lib/preview-prefs';
import { chromiumBased } from '@/lib/browser';
+import { PictureZoom } from '@/lib/viewer-zoom';
/** How far the film's frame reaches past the picture's box on each side, in px (see the `stage-frames` clip). */
const BLEED = 1;
@@ -102,6 +104,8 @@ type Props = {
const CLOCK_PINGS = 5;
/** How long the viewer keeps another size before the film is loaded again for it (ms): not at each step of a drag. */
const RESCALE_MS = 600;
+/** How often a load held back for a drag or a line typed in place looks whether it may be shown, ms. */
+const HOLD_POLL_MS = 100;
export const Preview = forwardRef<PreviewHandle, Props>(function Preview({ folder, stage, time, fps, onInfo, onKey, onError, onPlayed, onSpans, children }, ref) {
const t = useT();
@@ -125,7 +129,11 @@ export const Preview = forwardRef<PreviewHandle, Props>(function Preview({ folde
* the film again behind the picture.
*/
const { fitPages } = usePreviewPrefs();
- const pageScale = fitPages && fit.w > 0 ? pageScaleFor(fit.k, window.devicePixelRatio || 1) : null;
+ /* for the zoom the picture settled at: one on the move only scales it (components/ViewerZoom) */
+ const zoom = useContext(PictureZoom);
+ const pageScale = fitPages && fit.w > 0 ? zoomedPageScale(fit.k, zoom.z, zoom.drawn, window.devicePixelRatio || 1, stage) : null;
+ const busyRef = useRef(zoom.busy);
+ busyRef.current = zoom.busy;
const scaleOf = useRef(new Map<number, number | null>());
const framesRef = useRef(frames);
framesRef.current = frames;
@@ -186,7 +194,7 @@ export const Preview = forwardRef<PreviewHandle, Props>(function Preview({ folde
if (!ref) {
ref = (el) => {
if (el) { elements.current.set(key, el); return; }
- elements.current.delete(key); up.current.delete(key); clocks.current.delete(key); scaleOf.current.delete(key); refs.current.delete(key);
+ elements.current.delete(key); up.current.delete(key); clocks.current.delete(key); scaleOf.current.delete(key); refs.current.delete(key); updateSeq.current.delete(key);
};
refs.current.set(key, ref);
}
@@ -218,7 +226,10 @@ export const Preview = forwardRef<PreviewHandle, Props>(function Preview({ folde
if (head != null) latestHead.current = head;
/* a film that failed is loaded again as it is now, rather than changed in place */
if (!shownRef.current || failedRef.current) { reload(); return; }
- for (const key of updateKeys(shownRef.current.key, up.current)) post(key, { type: 'update', film, head: latestHead.current, seq: ++seq.current });
+ for (const key of updateKeys(shownRef.current.key, up.current)) {
+ updateSeq.current.set(key, ++seq.current);
+ post(key, { type: 'update', film, head: latestHead.current, seq: seq.current });
+ }
},
preview(clip, overrides) {
post(shownRef.current?.key, { type: 'preview', clip, overrides });
@@ -266,6 +277,56 @@ export const Preview = forwardRef<PreviewHandle, Props>(function Preview({ folde
tell({ event: 'reset' });
}, [shownKey]);
+ /**
+ * Show the frame `key`, drawn at `t`: the film playing, it plays on from the line; still, the playhead may have moved
+ * while it drew, and seeks went to the frame shown then.
+ */
+ const show = (key: number, t: number, swap: boolean) => {
+ setFrames((list) => shownAfter(list, key));
+ if (swap && line.current) tellPlay(key);
+ else if (swap && Math.abs(time() - t) > 1e-6) post(key, { type: 'seek', t: time(), seq: ++seq.current });
+ };
+ const showRef = useRef(show);
+ showRef.current = show;
+ /** The seq of the last film update sent to each frame: a frame behind the picture is shown once it has drawn it. */
+ const updateSeq = useRef(new Map<number, number>());
+ /** Whether a frame behind the picture must wait (see 'seeked'): something under way, or the film it has drawn is old. */
+ const mustWait = (key: number, drawn: number) => busyRef.current() || (updateSeq.current.get(key) ?? 0) > drawn;
+ const mustWaitRef = useRef(mustWait);
+ mustWaitRef.current = mustWait;
+ /*
+ * A load held back (see 'seeked'): shown when it may be, let go when another load took its place. A zoom not drawn
+ * for yet is waited for, and a load made for a zoom since left is replaced by one for the zoom now, not shown first.
+ */
+ const held = useRef<{ key: number; t: number; seq: number } | null>(null);
+ const [holding, setHolding] = useState(false);
+ const pageScaleRef = useRef(pageScale);
+ pageScaleRef.current = pageScale;
+ const zoomRef = useRef(zoom);
+ zoomRef.current = zoom;
+ useEffect(() => {
+ if (!holding) return undefined;
+ let free = performance.now();
+ const timer = setInterval(() => {
+ const h = held.current;
+ const busy = busyRef.current();
+ const zoomPending = zoomRef.current.z !== zoomRef.current.drawn;
+ if (busy || zoomPending) free = performance.now();
+ const next = !h ? 'drop' : heldNext({
+ there: framesRef.current.some((f) => f.key === h.key), busy, zoomPending,
+ sent: updateSeq.current.get(h.key) ?? 0, drawn: h.seq, waited: performance.now() - free,
+ scale: scaleOf.current.get(h.key), needed: pageScaleRef.current,
+ });
+ if (next === 'wait') return;
+ held.current = null;
+ setHolding(false);
+ if (next === 'load') reload();
+ else if (next === 'show' && h) showRef.current(h.key, h.t, true);
+ }, HOLD_POLL_MS);
+ return () => clearInterval(timer);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [holding]);
+
/* the folder (a project) changed: start over */
useEffect(() => {
updates.current = 0;
@@ -289,7 +350,10 @@ export const Preview = forwardRef<PreviewHandle, Props>(function Preview({ folde
if (Number(m.origin) > 0) clocks.current.set(key, { offset: performance.timeOrigin - Number(m.origin), rtt: Infinity });
for (let i = 0; i < CLOCK_PINGS; i++) setTimeout(() => post(key, { type: 'clock', ping: performance.now() }), 40 * i);
/* the film changed here while this frame was loading: it gets the latest before its first picture */
- if ((born.current.get(key) ?? 0) < updates.current && latest.current) post(key, { type: 'update', film: latest.current, head: latestHead.current, seq: ++seq.current });
+ if ((born.current.get(key) ?? 0) < updates.current && latest.current) {
+ updateSeq.current.set(key, ++seq.current);
+ post(key, { type: 'update', film: latest.current, head: latestHead.current, seq: seq.current });
+ }
/* behind the picture shown: its first picture is waited for whole (its videos loaded), as it replaces that one */
const behind = shownRef.current != null && shownRef.current.key !== key;
post(key, { type: 'seek', t: time(), seq: ++seq.current, ...(behind ? { behind: true } : {}) });
@@ -307,11 +371,14 @@ export const Preview = forwardRef<PreviewHandle, Props>(function Preview({ folde
if (line.current && key === shownRef.current?.key) tellPlay(key);
} else if (m.type === 'seeked') {
const swap = !framesRef.current.find((f) => f.key === key)?.ready;
- setFrames((list) => shownAfter(list, key));
- /* shown now: the film playing, it plays on from the line; still, the playhead may have moved while it drew,
- and seeks went to the frame shown then */
- if (swap && line.current) tellPlay(key);
- else if (swap && Math.abs(time() - Number(m.t)) > 1e-6) post(key, { type: 'seek', t: time(), seq: ++seq.current });
+ /* a load behind the picture, ready while a drag or a line typed in place is under way, or before it has drawn
+ the film as it is now: shown once it may be (the first load, with nothing shown yet, is shown at once) */
+ if (swap && shownRef.current && (mustWaitRef.current(key, Number(m.seq)) || held.current?.key === key)) {
+ held.current = { key, t: Number(m.t), seq: Math.max(Number(m.seq) || 0, held.current?.key === key ? held.current.seq : 0) };
+ setHolding(true);
+ return;
+ }
+ showRef.current(key, Number(m.t), swap);
} else if (m.type === 'updated') {
if (m.inPlace) onInfo(m as FilmInfo);
else reload();
@@ -334,6 +401,18 @@ export const Preview = forwardRef<PreviewHandle, Props>(function Preview({ folde
});
tell({ event: 'key', key });
onKeyRef.current?.(key);
+ } else if (m.event === 'wheel') {
+ /* a wheel over the film while its words are typed in (the frame has the pointer then): sent on from the
+ frame, at its place on screen, for the viewer's zoom */
+ const el = elements.current.get(key);
+ const r = el?.getBoundingClientRect();
+ if (!el || !r) return;
+ el.dispatchEvent(new WheelEvent('wheel', {
+ clientX: r.left + (Number(m.x) * r.width) / stage.w, clientY: r.top + (Number(m.y) * r.height) / stage.h,
+ deltaX: Number(m.deltaX) || 0, deltaY: Number(m.deltaY) || 0, deltaMode: Number(m.deltaMode) || 0,
+ ctrlKey: Boolean(m.ctrlKey), metaKey: Boolean(m.metaKey), shiftKey: Boolean(m.shiftKey), buttons: Number(m.buttons) || 0,
+ bubbles: true, cancelable: true,
+ }));
} else if (m.event === 'typing') {
tell({ event: 'typing', handle: Number(m.handle), value: String(m.value ?? '') });
} else if (m.event === 'text') {
@@ -362,18 +441,23 @@ export const Preview = forwardRef<PreviewHandle, Props>(function Preview({ folde
/* measured now, before the first picture: the film loads once, for this size */
if (el.clientWidth > 0 && el.clientHeight > 0) size(el.clientWidth, el.clientHeight);
setMeasured(true);
- const observer = new ResizeObserver(([entry]) => size(entry.contentRect.width, entry.contentRect.height));
+ /* sized before the frame is painted: a pinch moves the picture's box every frame, and the film keeps up with it */
+ const observer = new ResizeObserver(([entry]) => flushSync(() => size(entry.contentRect.width, entry.contentRect.height)));
observer.observe(el);
return () => observer.disconnect();
}, [stage.w, stage.h]);
/* a load keeps the scale it was made with */
if (measured) for (const f of frames) if (!scaleOf.current.has(f.key)) scaleOf.current.set(f.key, pageScale);
- /* the viewer kept another size (fullscreen, a pane resized), or the switch changed: the film loads again behind */
+ /* the viewer kept another size (fullscreen, a pane resized), or the switch changed: the film loads again behind; at
+ once for a zoom that has settled (it waited already) */
const shownScale = shown ? scaleOf.current.get(shown.key) : undefined;
+ const drawnFor = useRef(zoom.drawn);
+ const zoomSettled = drawnFor.current !== zoom.drawn;
+ useEffect(() => { drawnFor.current = zoom.drawn; }, [zoom.drawn]);
useEffect(() => {
if (!shown || shownScale === undefined || shownScale === pageScale || frames.some((f) => !f.ready)) return undefined;
- const timer = setTimeout(reload, RESCALE_MS);
+ const timer = setTimeout(reload, zoomSettled ? 0 : RESCALE_MS);
return () => clearTimeout(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [pageScale, shownScale, shown?.key, frames.length]);
@@ -397,13 +481,14 @@ export const Preview = forwardRef<PreviewHandle, Props>(function Preview({ folde
allow="autoplay"
scrolling="no"
title="film"
- /* the one loading is transparent, not hidden: the film is on another site, in a process of its own, and a
- frame hidden from there is not drawn at all, so a page that waits to draw (an image's decode()) would
- never be ready */
+ /* the one loading is all but transparent, not hidden: the film is on another site, in a process of its own,
+ and a frame hidden from there is not drawn at all, so a page that waits to draw (an image's decode()) would
+ never be ready; nor quite 0, or it is not put on screen at all, and is blank for a moment when it is shown */
+ data-loading={f === shown ? undefined : ''}
style={{
width: stage.w, height: stage.h,
transform: `translate(${-BLEED}px, ${-BLEED}px) scale(${(fit.w + 2 * BLEED) / stage.w}, ${(fit.h + 2 * BLEED) / stage.h})`,
- ...(f === shown ? {} : { opacity: 0, pointerEvents: 'none' }),
+ ...(f === shown ? {} : { opacity: 0.001, pointerEvents: 'none' }),
}}
/>
))}
diff --git a/packages/openfilm/studio/ui/src/editor/preview-frames.test.ts b/packages/openfilm/studio/ui/src/editor/preview-frames.test.ts
index 2b5342d..478642e 100644
--- a/packages/openfilm/studio/ui/src/editor/preview-frames.test.ts
+++ b/packages/openfilm/studio/ui/src/editor/preview-frames.test.ts
@@ -1,6 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { pageScaleFor, reloaded, shownAfter, updateKeys } from './preview-frames.ts';
+import { HELD_DRAWN_MAX_MS, ZOOMED_AREA_MAX, ZOOMED_SIDE_MAX, heldNext, pageScaleFor, reloaded, shownAfter, updateKeys, zoomedPageScale } from './preview-frames.ts';
test('a load behind the picture: the frame shown stays until the new one has drawn, and only then goes', () => {
const first = [{ key: 1, ready: true }];
@@ -31,3 +31,47 @@ test('a page draws at what the viewer shows of the film: in quarter steps up, ne
assert.equal(pageScaleFor(0.5, 1), 0.5);
assert.equal(pageScaleFor(0.05, 1), 0.25, 'a tiny viewer: a quarter at least');
});
+
+test('a zoom on the move keeps the film as it was drawn; settled, the film is drawn as sharp as it is seen', () => {
+ const hd = { w: 1920, h: 1080 };
+ /* a 1920-wide film fitted at 480 px on a 2× screen: drawn at 0.5 */
+ const fitted = 480 / 1920;
+ assert.equal(zoomedPageScale(fitted, 1, 1, 2, hd), 0.5);
+ /* pinched to 1.5× and 3×: still drawn for the fitted picture */
+ assert.equal(zoomedPageScale(fitted * 1.5, 1.5, 1, 2, hd), 0.5);
+ assert.equal(zoomedPageScale(fitted * 3, 3, 1, 2, hd), 0.5);
+ /* settled at 3×: 0.75 px per film px on screen, 1.5 device px */
+ assert.equal(zoomedPageScale(fitted * 3, 3, 3, 2, hd), 1.5);
+ /* back to fitted: drawn for it again once that settles */
+ assert.equal(zoomedPageScale(fitted, 1, 6, 2, hd), 3);
+ assert.equal(zoomedPageScale(fitted, 1, 1, 2, hd), 0.5);
+});
+
+test('zoomed in past the film\'s own size, a page is drawn past the screen\'s pixels, up to a cap for memory', () => {
+ const hd = { w: 1920, h: 1080 };
+ const fitted = 480 / 1920;
+ /* settled at 8×: 2 screen px per film px, 4 device px, more than the screen's 2 */
+ assert.equal(zoomedPageScale(fitted * 8, 8, 8, 2, hd), 4);
+ /* settled at 32× (8 screen px per film px): the cap, 64 MP for a 1920×1080 page, in quarter steps down */
+ const capped = zoomedPageScale(fitted * 32, 32, 32, 2, hd);
+ assert.equal(capped, 5.5);
+ assert.ok(1920 * capped <= ZOOMED_SIDE_MAX && 1920 * capped * 1080 * capped <= ZOOMED_AREA_MAX);
+ /* a page too large for the cap at the screen's pixels: the screen's pixels still, as when fitted */
+ assert.equal(zoomedPageScale(fitted * 32, 32, 32, 2, { w: 7680, h: 4320 }), 2);
+ /* fitted and zoomed out stay within the screen's pixels */
+ assert.equal(zoomedPageScale(1.5, 1, 1, 2, hd), 2);
+ assert.equal(zoomedPageScale(1.5 * 0.5, 0.5, 0.5, 2, hd), 1.5);
+});
+
+test('a load held behind the picture waits for what is under way and for the latest film, then is shown, or made again for the zoom now', () => {
+ const ready = { there: true, busy: false, sent: 0, drawn: 7, waited: 0, zoomPending: false, scale: 1.5, needed: 1.5 };
+ assert.equal(heldNext(ready), 'show');
+ assert.equal(heldNext({ ...ready, busy: true }), 'wait', 'a drag, words typed in place, a crop or a mask open');
+ assert.equal(heldNext({ ...ready, sent: 9 }), 'wait', 'an edit sent to it it has not drawn yet: it would show the old words');
+ assert.equal(heldNext({ ...ready, sent: 9, drawn: 9 }), 'show', 'drawn since');
+ assert.equal(heldNext({ ...ready, sent: 9, waited: HELD_DRAWN_MAX_MS }), 'show', 'never said it drew it: shown after a while, not held for good');
+ assert.equal(heldNext({ ...ready, busy: true, sent: 9, waited: HELD_DRAWN_MAX_MS }), 'wait', 'never while something is under way');
+ assert.equal(heldNext({ ...ready, zoomPending: true }), 'wait', 'a zoom not drawn for yet');
+ assert.equal(heldNext({ ...ready, needed: 2.75 }), 'load', 'made for a zoom since left: not shown, then loaded again at once');
+ assert.equal(heldNext({ ...ready, there: false }), 'drop');
+});
diff --git a/packages/openfilm/studio/ui/src/editor/preview-frames.ts b/packages/openfilm/studio/ui/src/editor/preview-frames.ts
index fb11d0d..c008282 100644
--- a/packages/openfilm/studio/ui/src/editor/preview-frames.ts
+++ b/packages/openfilm/studio/ui/src/editor/preview-frames.ts
@@ -30,7 +30,40 @@ export function updateKeys(shown: number, up: ReadonlySet<number>): number[] {
* film (`k`, viewer px per stage px, times the screen's `dpr`), in quarter steps rounded up, so a small resize does not
* load the film again; never more than the screen's own, nor under a quarter.
*/
-export function pageScaleFor(k: number, dpr: number): number {
+export function pageScaleFor(k: number, dpr: number, most = dpr): number {
const shown = Math.max(0.25, k * dpr);
- return Math.min(dpr, Math.ceil(shown * 4 - 1e-9) / 4);
+ return Math.min(most, Math.ceil(shown * 4 - 1e-9) / 4);
+}
+
+/** How long a load held behind the picture waits, nothing under way, to say it drew the latest film, ms: then shown. */
+export const HELD_DRAWN_MAX_MS = 3000;
+
+/**
+ * What becomes of a load held behind the picture (editor/Preview): it waits while something is under way on the stage
+ * (`busy`), while it has not drawn the latest film sent to it (`sent` and `drawn`: those updates' seqs; for at most
+ * HELD_DRAWN_MAX_MS of `waited`, the time since nothing was under way, should it never say) or a zoom is not drawn for
+ * yet (`zoomPending`); then it is shown, or, made at another scale than the one needed now, another load is made
+ * instead of showing it first. Let go when another load already took its place (`there` false).
+ */
+export function heldNext(h: { there: boolean; busy: boolean; sent: number; drawn: number; waited: number; zoomPending: boolean; scale: number | null | undefined; needed: number | null }): 'wait' | 'show' | 'load' | 'drop' {
+ if (!h.there) return 'drop';
+ if (h.busy || h.zoomPending || (h.sent > h.drawn && h.waited < HELD_DRAWN_MAX_MS)) return 'wait';
+ return h.scale !== h.needed ? 'load' : 'show';
+}
+
+/** A page zoomed in draws at most this many device px a side and in all: a larger canvas costs more than it shows. */
+export const ZOOMED_SIDE_MAX = 16384;
+export const ZOOMED_AREA_MAX = 64e6;
+
+/**
+ * The page scale of a picture zoomed `zoom` times its fitted size (`k`: what the viewer shows now) whose pages are drawn
+ * for `drawn` times it, the zoom it last settled at (components/ViewerZoom): a zoom on the move never loads the film
+ * again, and once it settles the film is drawn as sharp as it is seen. Zoomed in, that may be more than the screen's
+ * pixels per film px, up to ZOOMED_SIDE_MAX and ZOOMED_AREA_MAX for the film's `stage`.
+ */
+export function zoomedPageScale(k: number, zoom: number, drawn: number, dpr: number, stage: { w: number; h: number }): number {
+ const shown = (k / zoom) * drawn;
+ if (drawn <= 1) return pageScaleFor(shown, dpr);
+ const fits = Math.min(ZOOMED_SIDE_MAX / Math.max(stage.w, stage.h), Math.sqrt(ZOOMED_AREA_MAX / (stage.w * stage.h)));
+ return pageScaleFor(shown, dpr, Math.max(dpr, Math.floor(fits * 4) / 4));
}
diff --git a/packages/openfilm/studio/ui/src/i18n/en.ts b/packages/openfilm/studio/ui/src/i18n/en.ts
index 28c0cbb..9c94c21 100644
--- a/packages/openfilm/studio/ui/src/i18n/en.ts
+++ b/packages/openfilm/studio/ui/src/i18n/en.ts
@@ -1015,6 +1015,7 @@ export const en = {
frameCustomApply: 'Use this ratio',
frameCustomRange: 'From 1:4 to 4:1',
fullscreen: 'Full screen',
+ zoomFit: 'Fit the picture to the viewer',
playback: 'Playback',
speed: 'Speed',
},
diff --git a/packages/openfilm/studio/ui/src/i18n/es.ts b/packages/openfilm/studio/ui/src/i18n/es.ts
index b0ac215..ebd1d54 100644
--- a/packages/openfilm/studio/ui/src/i18n/es.ts
+++ b/packages/openfilm/studio/ui/src/i18n/es.ts
@@ -1014,6 +1014,7 @@ export const es: Words = {
frameCustomApply: 'Usar esta proporción',
frameCustomRange: 'De 1:4 a 4:1',
fullscreen: 'Pantalla completa',
+ zoomFit: 'Ajustar la imagen al visor',
playback: 'Reproducción',
speed: 'Velocidad',
},
diff --git a/packages/openfilm/studio/ui/src/i18n/ja.ts b/packages/openfilm/studio/ui/src/i18n/ja.ts
index 5b57e3c..a0923e2 100644
--- a/packages/openfilm/studio/ui/src/i18n/ja.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ja.ts
@@ -1014,6 +1014,7 @@ export const ja: Words = {
frameCustomApply: 'この比率を使う',
frameCustomRange: '1:4 から 4:1 まで',
fullscreen: '全画面表示',
+ zoomFit: '画面をビューアに合わせる',
playback: '再生設定',
speed: '再生速度',
},
diff --git a/packages/openfilm/studio/ui/src/i18n/ko.ts b/packages/openfilm/studio/ui/src/i18n/ko.ts
index 0f9d9c8..0b51fe2 100644
--- a/packages/openfilm/studio/ui/src/i18n/ko.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ko.ts
@@ -1011,6 +1011,7 @@ export const ko: Words = {
frameCustomApply: '이 비율 사용',
frameCustomRange: '1:4부터 4:1까지',
fullscreen: '전체 화면',
+ zoomFit: '화면을 뷰어에 맞추기',
playback: '재생 설정',
speed: '재생 속도',
},
diff --git a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
index 6c28010..31545a2 100644
--- a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
+++ b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
@@ -1015,6 +1015,7 @@ export const zhCN: Words = {
frameCustomApply: '使用这个比例',
frameCustomRange: '范围 1:4 到 4:1',
fullscreen: '全屏',
+ zoomFit: '画面适应窗口',
playback: '播放设置',
speed: '播放速度',
},
diff --git a/packages/openfilm/studio/ui/src/lib/stage-clip.test.ts b/packages/openfilm/studio/ui/src/lib/stage-clip.test.ts
new file mode 100644
index 0000000..3b39a08
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/stage-clip.test.ts
@@ -0,0 +1,15 @@
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+
+import { liveLookStands } from './stage-clip.ts';
+import type { FilmDoc } from './film.ts';
+
+const docWith = (style?: string) => ({ tracks: [{ clips: [{ id: 'v', src: 'v.mp4', ...(style == null ? {} : { style }) }] }] }) as unknown as FilmDoc;
+
+test('a look shown and not kept stands while film.html\'s style is the one it was shown over, and is over once that changes', () => {
+ const live = { clipLoc: 'film.html#0.0', written: '' };
+ assert.equal(liveLookStands(docWith(), live), true, 'being dragged: film.html as it was');
+ assert.equal(liveLookStands(docWith('opacity: 0.5'), live), false, 'kept: film.html has it now');
+ assert.equal(liveLookStands(docWith(''), { ...live, written: 'opacity: 0.5' }), false, 'undone to another style');
+ assert.equal(liveLookStands(docWith(), { ...live, clipLoc: 'film.html#0.3' }), false, 'its clip gone');
+});
diff --git a/packages/openfilm/studio/ui/src/lib/stage-clip.ts b/packages/openfilm/studio/ui/src/lib/stage-clip.ts
index edf9dca..da6ba82 100644
--- a/packages/openfilm/studio/ui/src/lib/stage-clip.ts
+++ b/packages/openfilm/studio/ui/src/lib/stage-clip.ts
@@ -6,7 +6,7 @@
* width, and the height only when it does not follow from the picture.
*/
import { pictureRect } from '../../../../src/film-doc.mjs';
-import type { FilmBox, FilmSrcKind } from '@/lib/film';
+import { parseFilmDocLoc, type FilmBox, type FilmDoc, type FilmSrcKind } from './film.ts';
import type { MgBox, MgTransform } from '@/lib/stage-types';
/**
@@ -58,3 +58,14 @@ export function clipFieldPart(field: 'x' | 'y' | 'w' | 'h', n: number, box: MgBo
const k = field === 'w' ? n / (box.w || 1) : n / (box.h || 1);
return { scaleX: k, scaleY: k };
}
+
+/**
+ * Whether a look the inspector shows on a clip, not kept yet (`live`: its clip, and film.html's style it was shown
+ * over), still stands: film.html's style for the clip is still that one. Once it is another (the look kept, then maybe
+ * undone back to the same style), the look shown is over, and is never shown again, on another load of the film either.
+ */
+export function liveLookStands(doc: FilmDoc, live: { clipLoc: string; written: string }): boolean {
+ const at = parseFilmDocLoc(live.clipLoc);
+ const clip = at ? doc.tracks[at.track]?.clips[at.clip] : undefined;
+ return Boolean(clip) && (clip?.style ?? '') === live.written;
+}
diff --git a/packages/openfilm/studio/ui/src/lib/viewer-zoom.test.ts b/packages/openfilm/studio/ui/src/lib/viewer-zoom.test.ts
new file mode 100644
index 0000000..ab827da
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/viewer-zoom.test.ts
@@ -0,0 +1,138 @@
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+
+import {
+ FIT_VIEW, ZOOM_MIN, createViewerZoom, fittedSize, isFit, panBy, shownRect, wheelPx, wheelZoomFactor, zoomAt, zoomLayout,
+ zoomMax, type ViewerView,
+} from './viewer-zoom.ts';
+
+/* a 1920×1080 film in a 1000×800 viewer: fitted at 1000×562.5 */
+const viewer = { w: 1000, h: 800 };
+const frame = { w: 1920, h: 1080 };
+const fitted = fittedSize(viewer, frame);
+const max = zoomMax(fitted.w / frame.w);
+
+/** Where a point of the picture (shares of its size) is on screen, in viewer px. */
+const onScreen = (view: ViewerView, u: number, v: number) => {
+ const l = zoomLayout(view, viewer, fitted);
+ return { x: l.picture.x - l.scroll.x + u * l.picture.w, y: l.picture.y - l.scroll.y + v * l.picture.h };
+};
+const near = (a: number, b: number) => assert.ok(Math.abs(a - b) < 1e-6, `${a} ≉ ${b}`);
+
+test('the picture is fitted whole in the viewer, as the CSS fits it', () => {
+ assert.deepEqual(fittedSize(viewer, frame), { w: 1000, h: 562.5 });
+ assert.deepEqual(fittedSize({ w: 1000, h: 800 }, { w: 1080, h: 1920 }), { w: 450, h: 800 });
+});
+
+test('fitted is 1×, centered; the zoomed layout of the fitted view is the fitted picture, centered', () => {
+ assert.ok(isFit(FIT_VIEW));
+ assert.ok(!isFit({ z: 1, cx: 0.4, cy: 0.5 }));
+ assert.ok(!isFit({ z: 1.5, cx: 0.5, cy: 0.5 }));
+ const at = onScreen(FIT_VIEW, 0, 0);
+ near(at.x, 0);
+ near(at.y, (800 - 562.5) / 2);
+});
+
+test('a zoom keeps the point under the pointer where it is', () => {
+ let view: ViewerView = FIT_VIEW;
+ const pointer = { x: 700, y: 300 };
+ const u = (pointer.x - onScreen(view, 0, 0).x) / fitted.w;
+ const v = (pointer.y - onScreen(view, 0, 0).y) / fitted.h;
+ view = zoomAt(view, 2, pointer, viewer, fitted, max);
+ assert.equal(view.z, 2);
+ const after = onScreen(view, u, v);
+ near(after.x, pointer.x);
+ near(after.y, pointer.y);
+ /* in again elsewhere, then out: the point under each pointer stays */
+ const p2 = { x: 120, y: 650 };
+ const l = zoomLayout(view, viewer, fitted);
+ const u2 = (p2.x - (l.picture.x - l.scroll.x)) / l.picture.w;
+ const v2 = (p2.y - (l.picture.y - l.scroll.y)) / l.picture.h;
+ view = zoomAt(view, 1.5, p2, viewer, fitted, max);
+ near(onScreen(view, u2, v2).x, p2.x);
+ near(onScreen(view, u2, v2).y, p2.y);
+ view = zoomAt(view, 0.8, p2, viewer, fitted, max);
+ near(onScreen(view, u2, v2).x, p2.x);
+});
+
+test('a zoom about the center keeps the picture centered', () => {
+ const view = zoomAt(FIT_VIEW, 3, { x: 500, y: 400 }, viewer, fitted, max);
+ assert.deepEqual(view, { z: 3, cx: 0.5, cy: 0.5 });
+});
+
+test('the zoom stays between a quarter of fitted and 8 screen px per film px', () => {
+ /* fitted at 1000 / 1920 px per film px: 8 px per film px is 15.36× */
+ near(max, 8 * 1920 / 1000);
+ let view: ViewerView = FIT_VIEW;
+ for (let i = 0; i < 40; i += 1) view = zoomAt(view, 1.5, { x: 500, y: 400 }, viewer, fitted, max);
+ near(view.z, max);
+ assert.equal(zoomAt(view, 2, { x: 500, y: 400 }, viewer, fitted, max), view);
+ for (let i = 0; i < 40; i += 1) view = zoomAt(view, 0.5, { x: 500, y: 400 }, viewer, fitted, max);
+ assert.equal(view.z, ZOOM_MIN);
+ /* a film smaller than the viewer still zooms in to its fitted size at least */
+ assert.equal(zoomMax(20), 1);
+});
+
+test('a zoom past the largest (the viewer grew since) is not brought down by a zoom in, only by a zoom out', () => {
+ const past: ViewerView = { z: max * 1.4, cx: 0.5, cy: 0.5 };
+ assert.equal(zoomAt(past, 1.2, { x: 500, y: 400 }, viewer, fitted, max), past);
+ near(zoomAt(past, 0.9, { x: 500, y: 400 }, viewer, fitted, max).z, max * 1.4 * 0.9);
+});
+
+test('a pan moves the picture the other way, until an edge reaches the viewer\'s middle', () => {
+ const zoomed = zoomAt(FIT_VIEW, 2, { x: 500, y: 400 }, viewer, fitted, max);
+ const panned = panBy(zoomed, 100, -50, fitted);
+ near(onScreen(panned, 0.5, 0.5).x, onScreen(zoomed, 0.5, 0.5).x - 100);
+ near(onScreen(panned, 0.5, 0.5).y, onScreen(zoomed, 0.5, 0.5).y + 50);
+ const far = panBy(zoomed, 1e6, -1e6, fitted);
+ assert.deepEqual([far.cx, far.cy], [1, 0]);
+ /* the picture's right edge at the middle, its top edge at the middle */
+ near(onScreen(far, 1, 0).x, 500);
+ near(onScreen(far, 1, 0).y, 400);
+ assert.equal(panBy(far, 10, -10, fitted), far);
+});
+
+test('the zoomed box is the picture with half a viewer around it; its scroll is the view\'s center point', () => {
+ const l = zoomLayout({ z: 2, cx: 0.25, cy: 0.75 }, viewer, { w: 1000, h: 562.5 });
+ assert.deepEqual(l.box, { w: 3000, h: 1925 });
+ assert.deepEqual(l.picture, { x: 500, y: 400, w: 2000, h: 1125 });
+ assert.deepEqual(l.scroll, { x: 500, y: 843.75 });
+});
+
+test('a wheel zooms as a pinch\'s fingers move, a mouse\'s notch by one step', () => {
+ near(wheelZoomFactor(-10), Math.exp(0.1));
+ near(wheelZoomFactor(10), Math.exp(-0.1));
+ near(wheelZoomFactor(-100), wheelZoomFactor(-25));
+ near(wheelZoomFactor(40), wheelZoomFactor(25));
+ assert.ok(wheelZoomFactor(-100) < 1.3);
+ assert.equal(wheelPx({ deltaMode: 0 }, 3), 3);
+ assert.equal(wheelPx({ deltaMode: 1 }, 3), 48);
+ assert.equal(wheelPx({ deltaMode: 2 }, 1), 400);
+});
+
+test('the store tells its listeners only of a change', () => {
+ const store = createViewerZoom();
+ let told = 0;
+ const stop = store.subscribe(() => { told += 1; });
+ assert.deepEqual(store.get(), { view: FIT_VIEW, fitK: null });
+ store.set(FIT_VIEW);
+ store.setFitK(null);
+ assert.equal(told, 0);
+ store.setFitK(0.5);
+ store.set({ z: 2, cx: 0.5, cy: 0.5 });
+ assert.equal(told, 2);
+ assert.deepEqual(store.get(), { view: { z: 2, cx: 0.5, cy: 0.5 }, fitK: 0.5 });
+ stop();
+ store.set(FIT_VIEW);
+ assert.equal(told, 2);
+});
+
+test('notices go over the part of the picture on screen: the picture fitted, the whole viewer zoomed in', () => {
+ assert.deepEqual(shownRect(FIT_VIEW, viewer, fitted), { x: 0, y: 118.75, w: 1000, h: 562.5 });
+ assert.deepEqual(shownRect({ z: 4, cx: 0.5, cy: 0.5 }, viewer, fitted), { x: 0, y: 0, w: 1000, h: 800 });
+ /* panned to the picture's right edge at the middle: the left half of the viewer */
+ assert.deepEqual(shownRect({ z: 4, cx: 1, cy: 0.5 }, viewer, fitted), { x: 0, y: 0, w: 500, h: 800 });
+ /* zoomed out: the small picture, centered */
+ const small = shownRect({ z: 0.5, cx: 0.5, cy: 0.5 }, viewer, fitted);
+ assert.deepEqual(small, { x: 250, y: 259.375, w: 500, h: 281.25 });
+});
diff --git a/packages/openfilm/studio/ui/src/lib/viewer-zoom.ts b/packages/openfilm/studio/ui/src/lib/viewer-zoom.ts
new file mode 100644
index 0000000..d488ab8
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/viewer-zoom.ts
@@ -0,0 +1,132 @@
+/**
+ * The viewer's zoom: a pinch or ⌘/Ctrl + wheel zooms the picture about the pointer, and a
+ * scroll pans it while it is not fitted. A view is how many times its fitted size the picture is drawn (`z`) and which
+ * point of the picture is at the viewer's center (`cx`, `cy`: shares of its width and height, 0 to 1). Fitted: 1×,
+ * centered. Only the viewer changes; the film and its exports never do.
+ *
+ * Zoomed, the picture is laid out at its size in a box one viewer larger each way, half a viewer of margin around it,
+ * and that box is scrolled: the scroll is the point at the center (`cx` × the picture's width), so a picture can be
+ * panned until an edge reaches the viewer's middle, and no farther.
+ */
+import { createContext } from 'react';
+
+type Size = { w: number; h: number };
+type Point = { x: number; y: number };
+
+export type ViewerView = { z: number; cx: number; cy: number };
+export const FIT_VIEW: ViewerView = { z: 1, cx: 0.5, cy: 0.5 };
+
+/** Zoomed out to a quarter of the fitted size at most; in, to 8 screen px per film px (never less than fitted). */
+export const ZOOM_MIN = 0.25;
+export const ZOOM_MAX_PX = 8;
+/** One wheel event zooms by at most e^(25/100) ≈ 1.28×: a mouse's notch (100 px on Windows, 40 on a Mac). */
+const WHEEL_STEP_MAX = 25;
+const WHEEL_PX_PER_E = 100;
+
+export const isFit = (v: ViewerView) => v.z === 1 && v.cx === 0.5 && v.cy === 0.5;
+
+const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
+
+/** The largest zoom for a picture fitted at `fitK` screen px per film px. */
+export const zoomMax = (fitK: number) => Math.max(1, ZOOM_MAX_PX / fitK);
+
+/** The picture's size fitted whole in the viewer (as the viewer's CSS fits it). */
+export function fittedSize(viewer: Size, frame: Size): Size {
+ return viewer.w / viewer.h < frame.w / frame.h
+ ? { w: viewer.w, h: (viewer.w * frame.h) / frame.w }
+ : { w: (viewer.h * frame.w) / frame.h, h: viewer.h };
+}
+
+/** Wheel deltas in px (Firefox reports lines or pages). */
+export const wheelPx = (e: { deltaMode: number }, d: number) => (e.deltaMode === 1 ? d * 16 : e.deltaMode === 2 ? d * 400 : d);
+
+/**
+ * How much a ⌘/Ctrl + wheel event zooms: a trackpad's pinch (Chromium sends it as Ctrl + wheel, 100 × the log of its
+ * scale) follows the fingers; a mouse's notch is one step.
+ */
+export const wheelZoomFactor = (deltaPx: number) => Math.exp(-clamp(deltaPx, -WHEEL_STEP_MAX, WHEEL_STEP_MAX) / WHEEL_PX_PER_E);
+
+/**
+ * The view zoomed by `factor` about `at` (viewer px from its top left): the point of the picture under it stays under
+ * it. `fitted` is the picture's fitted size, `max` the largest zoom (zoomMax). A zoom past `max` (the viewer grew since)
+ * is not brought down by a zoom in.
+ */
+export function zoomAt(view: ViewerView, factor: number, at: Point, viewer: Size, fitted: Size, max: number): ViewerView {
+ const z = clamp(view.z * factor, ZOOM_MIN, Math.max(ZOOM_MIN, max, view.z));
+ if (z === view.z) return view;
+ const pw = fitted.w * view.z, ph = fitted.h * view.z;
+ /* the share of the picture under the pointer, then the center that keeps it there at the new size */
+ const ux = (at.x - viewer.w / 2) / pw + view.cx;
+ const uy = (at.y - viewer.h / 2) / ph + view.cy;
+ return {
+ z,
+ cx: clamp(ux - (at.x - viewer.w / 2) / (fitted.w * z), 0, 1),
+ cy: clamp(uy - (at.y - viewer.h / 2) / (fitted.h * z), 0, 1),
+ };
+}
+
+/** The view panned by a scroll of `dx`, `dy` screen px (the picture moves the other way). */
+export function panBy(view: ViewerView, dx: number, dy: number, fitted: Size): ViewerView {
+ const next = {
+ z: view.z,
+ cx: clamp(view.cx + dx / (fitted.w * view.z), 0, 1),
+ cy: clamp(view.cy + dy / (fitted.h * view.z), 0, 1),
+ };
+ return next.cx === view.cx && next.cy === view.cy ? view : next;
+}
+
+/**
+ * The zoomed layout: the scrolled box's size, the picture's place and size in it, and the scroll that puts the view's
+ * center point at the viewer's center.
+ */
+export function zoomLayout(view: ViewerView, viewer: Size, fitted: Size): { box: Size; picture: Point & Size; scroll: Point } {
+ const w = fitted.w * view.z, h = fitted.h * view.z;
+ return {
+ box: { w: w + viewer.w, h: h + viewer.h },
+ picture: { x: viewer.w / 2, y: viewer.h / 2, w, h },
+ scroll: { x: view.cx * w, y: view.cy * h },
+ };
+}
+
+/**
+ * The part of the viewer the picture covers, viewer px (fitted: the picture): notices about the picture are put there,
+ * so a zoom never takes them off screen.
+ */
+export function shownRect(view: ViewerView, viewer: Size, fitted: Size): Point & Size {
+ const w = fitted.w * view.z, h = fitted.h * view.z;
+ const left = viewer.w / 2 - view.cx * w, top = viewer.h / 2 - view.cy * h;
+ const x = Math.max(0, left), y = Math.max(0, top);
+ return { x, y, w: Math.max(0, Math.min(viewer.w, left + w) - x), h: Math.max(0, Math.min(viewer.h, top + h) - y) };
+}
+
+/**
+ * For the film's frames inside the picture (editor/Preview): how many times its fitted size the picture is shown (`z`,
+ * 1: fitted), the zoom its pages are drawn for (`drawn`), which follows `z` once a zoom has settled, and whether the
+ * person is in the middle of something on it (`busy`: a button held, words typed in place, a crop open),
+ * which a film loaded again behind the picture waits for before it is shown.
+ */
+export const PictureZoom = createContext<{ z: number; drawn: number; busy: () => boolean }>({ z: 1, drawn: 1, busy: () => false });
+
+/** How long a zoom is still before the film is drawn for it, ms: a pinch's pauses do not load the film again. */
+export const ZOOM_SETTLE_MS = 700;
+
+/** The viewer's zoom, shared by the picture and the button that fits it again (only they re-render as it changes). */
+export interface ViewerZoomStore {
+ get: () => { view: ViewerView; fitK: number | null };
+ set: (view: ViewerView) => void;
+ /** The fitted picture's screen px per film px (the zoom shown is `z` × it), null until the viewer is measured. */
+ setFitK: (k: number | null) => void;
+ subscribe: (fn: () => void) => () => void;
+}
+
+export function createViewerZoom(): ViewerZoomStore {
+ let value = { view: FIT_VIEW, fitK: null as number | null };
+ const listeners = new Set<() => void>();
+ const put = (next: typeof value) => { value = next; for (const fn of listeners) fn(); };
+ return {
+ get: () => value,
+ set: (view) => { if (view !== value.view) put({ ...value, view }); },
+ setFitK: (fitK) => { if (fitK !== value.fitK) put({ ...value, fitK }); },
+ subscribe: (fn) => { listeners.add(fn); return () => { listeners.delete(fn); }; },
+ };
+}