From b2f9cf487c094dda2e80d47b11b1c22a546c2754 Mon Sep 17 00:00:00 2001 From: Leslie Owusu-Appiah Date: Sat, 7 Nov 2026 19:43:07 +0100 Subject: [PATCH 1/3] perf(example): benchmark 10,000 nodes, a pinch in from fit and double-tap zooms The benchmark measures canvases of 500 to 10,000 nodes, and optionally big-10000.canvas with its images (BENCH_FIXTURE_DIR). Two phases join pinch, pan and pan zoomed in: zooming in from the fitted scale to four times it and back, and a double-tap's zoom to the middle card and back. Each phase logs its window on the UI thread's clock, so frames that reached the screen can be counted outside the app. Co-Authored-By: Claude Opus 5.5 --- example/shared/Bench.tsx | 255 +++++++++++++++++++++++++--------- example/shared/benchConfig.ts | 12 ++ 2 files changed, 200 insertions(+), 67 deletions(-) diff --git a/example/shared/Bench.tsx b/example/shared/Bench.tsx index 9f2aafd..3442d4a 100644 --- a/example/shared/Bench.tsx +++ b/example/shared/Bench.tsx @@ -1,27 +1,66 @@ -// The renderer's benchmark (react-native-jsoncanvas#83): canvases of 500, -// 2,000 and 5,000 mixed nodes (generateCanvas.ts), each fitted, left to -// settle, then moved by a script on the UI thread as a pinch and then a pan -// move it: 4 s of pinch-zoom about the centre (drawn from the recorded -// picture, as a pinch is), 4 s of pan, and 4 s of pan zoomed in 8 times -// (few enough nodes near the viewport to be drawn live). Frame times are recorded -// on the UI thread (each frame's time since the last) and on the JavaScript -// thread (requestAnimationFrame), and summed up as frames per second, the -// 95th percentile, and frames over 25 ms (a dropped frame at 60 Hz). +// The renderer's benchmark (react-native-jsoncanvas#83): canvases of 500 to +// 10,000 mixed nodes (generateCanvas.ts, benchConfig.ts), each fitted, left to +// settle, then moved by a script while frame times are recorded: +// +// - pinch: 4 s of pinch-zoom about the centre, from the fitted scale; +// - pan: 4 s of pan at the fitted scale; +// - close: 4 s of pan zoomed in 8 times; +// - pinch in: 4 s of zooming in from the fitted scale to 4 times it and +// back, as fingers spreading from a fitted canvas do (the text is drawn +// from the first frame: a canvas of 2,000 nodes or more opens at the +// smallest scale, 0.1, on a phone); +// - double-tap: zooming to the card in the middle and back again, as a +// double-tap does (a 300 ms ease-out from the JavaScript thread, culling +// held still until it ends, as CanvasView's own camera animation does). +// +// Frame times are recorded on the UI thread (each frame's time since the +// last) and on the JavaScript thread (requestAnimationFrame), and summed up +// as frames per second, the 95th percentile, and frames over 25 ms (a dropped +// frame at 60 Hz). Skia draws on threads of its own, so what reaches the +// screen is measured outside the app (on Android, `dumpsys gfxinfo`): each +// phase logs its window on the UI thread's clock, as `[BENCH-WIN]`. import {useCallback, useEffect, useRef, useState} from 'react'; import {Platform, ScrollView, StyleSheet, Text, View} from 'react-native'; import {GestureHandlerRootView} from 'react-native-gesture-handler'; import {useFrameCallback, useSharedValue, type SharedValue} from 'react-native-reanimated'; import {CanvasView, type CanvasCamera} from '@workspace.sh/react-native-jsoncanvas'; -import {generateCanvas} from './generateCanvas'; +import {generateCanvas, type CanvasImages} from './generateCanvas'; import {SAMPLE_CANVAS} from './fixtures'; -import {BENCH_REMOUNTS} from './benchConfig'; +import {BENCH_FIXTURE_DIR, BENCH_REMOUNTS, BENCH_SIZES} from './benchConfig'; -const SIZES = [500, 2000, 5000]; const SETTLE_MS = 2500; const PHASE_MS = 4000; const BUCKETS = 101; // 0–99 ms, and 100 ms or more +/** generateCanvas's grid: each node sits in a cell this size, and a text card is 260 × 160. */ +const CELL_W = 320; +const CELL_H = 220; +const CARD_W = 260; +const CARD_H = 160; +/** CanvasView's zoom to a node: its padding, soft maximum scale and duration. */ +const NODE_FIT_PADDING = 32; +const NODE_FIT_MAX_SCALE = 3; +const ZOOM_MS = 300; + +/** big-10000.canvas's images, beside it in workspace-fixtures (Fixtures/canvas). */ +const FIXTURE_IMAGES: CanvasImages = { + rasters: ['amara-okafor', 'freya-lindqvist', 'hana-kim', 'isabela-costa', 'karim-haddad', 'lucia-moreno', 'marco-bianchi', 'nia-mensah', 'noor-rahman', 'rafael-santos', 'tama-faleolo'].map((name) => `portraits/portrait-${name}.jpg`), + svg: 'drawings/shapes.svg', +}; + +interface BenchCase { + label: string; + nodes: number; + images?: CanvasImages; + basePath?: string; +} + +const CASES: BenchCase[] = [ + ...BENCH_SIZES.map((nodes) => ({label: `${nodes}`, nodes})), + ...(BENCH_FIXTURE_DIR ? [{label: 'big-10000.canvas', nodes: 10000, images: FIXTURE_IMAGES, basePath: BENCH_FIXTURE_DIR}] : []), +]; + interface Stats { frames: number; fps: number; @@ -29,15 +68,16 @@ interface Stats { over25: number; } +type PhaseName = 'pinch' | 'pan' | 'close' | 'pinchIn' | 'doubleTap'; +const PHASES: PhaseName[] = ['pinch', 'pan', 'close', 'pinchIn', 'doubleTap']; +/** The Driver's phase numbers: 0 is idle. */ +const PHASE_NUMBER: Record = {pinch: 1, pan: 2, close: 3, pinchIn: 4, doubleTap: 5}; + export interface BenchRow { + label: string; nodes: number; readyMs: number; - pinchUi: Stats; - pinchJs: Stats; - panUi: Stats; - panJs: Stats; - closeUi: Stats; - closeJs: Stats; + phases: Record; } /** `histogram`: frames by their time in whole ms; `total`: their exact times added up. */ @@ -57,6 +97,13 @@ function statsOf(histogram: number[], total: number): Stats { return {frames, fps: Math.round((1000 * frames) / Math.max(1, total)), p95, over25}; } +/** A phase's first and last UI frames, on the UI thread's frame clock, and the wall clock at the first. */ +interface PhaseWindow { + first: number; + last: number; + wall: number; +} + interface DriverProps { camera: CanvasCamera; phase: SharedValue; @@ -65,14 +112,16 @@ interface DriverProps { viewport: SharedValue<{w: number; h: number}>; histogram: SharedValue; total: SharedValue; + phaseWindow: SharedValue; } /** * Moves the camera on the UI thread, every frame, while a phase runs, and * records each frame's time. Mounted once the canvas has handed over its - * camera, so the frame callback has it from the start. + * camera, so the frame callback has it from the start. The double-tap phase + * moves the camera from the JavaScript thread instead, as CanvasView does. */ -function Driver({camera, phase, t0, start, viewport, histogram, total}: DriverProps) { +function Driver({camera, phase, t0, start, viewport, histogram, total, phaseWindow}: DriverProps) { const last = useSharedValue(-1); useFrameCallback((info) => { 'worklet'; @@ -82,8 +131,10 @@ function Driver({camera, phase, t0, start, viewport, histogram, total}: DriverPr if (phase.value === 0) return; if (t0.value < 0) { t0.value = now; + phaseWindow.value = {first: now, last: now, wall: Date.now()}; return; } + phaseWindow.value = {...phaseWindow.value, last: now}; if (dt !== null && dt > 0) { const at = Math.min(BUCKETS - 1, Math.floor(dt)); const h = histogram.value.slice(); @@ -93,14 +144,18 @@ function Driver({camera, phase, t0, start, viewport, histogram, total}: DriverPr } const t = (now - t0.value) / 1000; const st = start.value; - if (phase.value === 1) { - const s = st.s * (1 + 0.6 * Math.sin(t * Math.PI)); - const cx = viewport.value.w / 2; - const cy = viewport.value.h / 2; + const cx = viewport.value.w / 2; + const cy = viewport.value.h / 2; + const zoomTo = (s: number) => { camera.scale.value = s; camera.translateX.value = cx - (cx - st.tx) * (s / st.s); camera.translateY.value = cy - (cy - st.ty) * (s / st.s); - } else { + }; + if (phase.value === 1) { + zoomTo(st.s * (1 + 0.6 * Math.sin(t * Math.PI))); + } else if (phase.value === 4) { + zoomTo(st.s * (1 + 1.5 * (1 - Math.cos(t * Math.PI)))); + } else if (phase.value === 2 || phase.value === 3) { camera.translateX.value = st.tx + 600 * Math.sin(t * Math.PI); camera.translateY.value = st.ty + 300 * Math.sin((t * Math.PI) / 2); } @@ -118,8 +173,51 @@ const OWN_CLOCK = Platform.OS === 'macos'; const wait = (ms: number) => new Promise((done) => setTimeout(done, ms)); +interface Camera { + tx: number; + ty: number; + s: number; +} + +/** + * Moves the camera to `to` over ZOOM_MS from the JavaScript thread, eased + * out, as CanvasView's camera animation (a double-tap's zoom) does, with the + * culling held still until the end, as that animation holds it. + */ +function tween(camera: CanvasCamera, to: Camera): Promise { + const from = {tx: camera.translateX.value, ty: camera.translateY.value, s: camera.scale.value}; + const began = Date.now(); + camera.isPinching.value = true; + return new Promise((done) => { + const tick = () => { + const t = Math.min(1, (Date.now() - began) / ZOOM_MS); + const eased = 1 - Math.pow(1 - t, 3); + camera.translateX.value = from.tx + (to.tx - from.tx) * eased; + camera.translateY.value = from.ty + (to.ty - from.ty) * eased; + camera.scale.value = from.s + (to.s - from.s) * eased; + if (t < 1) { + requestAnimationFrame(tick); + } else { + camera.isPinching.value = false; + done(); + } + }; + requestAnimationFrame(tick); + }); +} + +/** Where a double-tap on the card nearest the middle of the view takes the camera. */ +function zoomedToMiddleCard(nodes: number, fitted: Camera, w: number, h: number): Camera { + const columns = Math.ceil(Math.sqrt(nodes)); + const rows = Math.ceil(nodes / columns); + const col = Math.max(0, Math.min(columns - 1, Math.floor((w / 2 - fitted.tx) / fitted.s / CELL_W))); + const row = Math.max(0, Math.min(rows - 1, Math.floor((h / 2 - fitted.ty) / fitted.s / CELL_H))); + const s = Math.min(NODE_FIT_MAX_SCALE, (w - NODE_FIT_PADDING * 2) / CARD_W, (h - NODE_FIT_PADDING * 2) / CARD_H); + return {tx: w / 2 - (col * CELL_W + CARD_W / 2) * s, ty: h / 2 - (row * CELL_H + CARD_H / 2) * s, s}; +} + export function Bench({autorun = true, label}: {autorun?: boolean; label: string}) { - const [size, setSize] = useState(null); + const [benchCase, setBenchCase] = useState<{key: number; basePath?: string} | null>(null); const [content, setContent] = useState(''); const [rows, setRows] = useState([]); const [status, setStatus] = useState('Waiting'); @@ -127,17 +225,21 @@ export function Bench({autorun = true, label}: {autorun?: boolean; label: string const [camera, setCamera] = useState(null); const ready = useRef<((c: {fitToViewport: () => void; camera: CanvasCamera}) => void) | null>(null); - const phase = useSharedValue(0); // 0 idle, 1 pinch, 2 pan + const phase = useSharedValue(0); const t0 = useSharedValue(-1); const start = useSharedValue({tx: 0, ty: 0, s: 1}); const viewport = useSharedValue({w: 0, h: 0}); const histogram = useSharedValue(new Array(BUCKETS).fill(0)); - const total = useSharedValue(0); + const phaseWindow = useSharedValue({first: 0, last: 0, wall: 0}); - /** One phase: the UI thread's frames from the frame callback, the JS thread's from requestAnimationFrame. */ + /** + * One phase: the UI thread's frames from the frame callback, the JS + * thread's from requestAnimationFrame. `drive` moves the camera from the + * JavaScript thread, for a phase the Driver leaves alone. + */ const measure = useCallback( - async (which: 1 | 2 | 3): Promise<{ui: Stats; js: Stats}> => { + async (caseLabel: string, which: PhaseName, drive?: () => Promise): Promise<{ui: Stats; js: Stats}> => { histogram.value = new Array(BUCKETS).fill(0); total.value = 0; const js = new Array(BUCKETS).fill(0); @@ -156,15 +258,22 @@ export function Bench({autorun = true, label}: {autorun?: boolean; label: string }; requestAnimationFrame(tick); t0.value = -1; - phase.value = which; + phase.value = PHASE_NUMBER[which]; const shown = setInterval(() => setLive(`${histogram.value.reduce((a, b) => a + b, 0)} UI frames, ${Math.round(total.value)} ms`), 500); - await wait(PHASE_MS); + const began = Date.now(); + if (drive) { + while (Date.now() - began < PHASE_MS) await drive(); + } else { + await wait(PHASE_MS); + } clearInterval(shown); phase.value = 0; running = false; + const w = phaseWindow.value; + console.warn(`[BENCH-WIN] ${JSON.stringify({bench: label, case: caseLabel, phase: which, first: w.first, last: w.last, wall: w.wall})}`); return {ui: statsOf([...histogram.value], total.value), js: statsOf(js, jsTotal)}; }, - [histogram, phase, t0, total], + [histogram, label, phase, t0, total, phaseWindow], ); /** Mounts and unmounts the sample canvas `times` times, then leaves it shown: a remount must still draw. */ @@ -172,58 +281,69 @@ export function Bench({autorun = true, label}: {autorun?: boolean; label: string for (let i = 1; i <= times; i++) { setStatus(`remount ${i} of ${times}`); setContent(SAMPLE_CANVAS); - setSize(i); + setBenchCase({key: i}); await wait(400); - setSize(null); + setBenchCase(null); await wait(150); } setContent(SAMPLE_CANVAS); - setSize(times + 1); + setBenchCase({key: times + 1}); setStatus(`remounted ${times} times, now shown`); }, []); const run = useCallback(async () => { if (BENCH_REMOUNTS > 0) return remount(BENCH_REMOUNTS); const out: BenchRow[] = []; - for (const nodes of SIZES) { - setStatus(`${nodes} nodes: opening`); + for (const [index, c] of CASES.entries()) { + setStatus(`${c.label}: opening`); const opened = new Promise<{fitToViewport: () => void; camera: CanvasCamera}>((done) => (ready.current = done)); const began = performance.now(); setCamera(null); - setContent(generateCanvas(nodes)); - setSize(nodes); + setContent(generateCanvas(c.nodes, 1, c.images)); + setBenchCase({key: index + 1, basePath: c.basePath}); const controls = await opened; const readyMs = Math.round(performance.now() - began); setCamera(controls.camera); controls.fitToViewport(); await wait(SETTLE_MS); const cam = controls.camera; - phase.value = 0; - start.value = {tx: cam.translateX.value, ty: cam.translateY.value, s: cam.scale.value}; - setStatus(`${nodes} nodes: pinch`); - cam.isPinching.value = true; - const pinch = await measure(1); - cam.isPinching.value = false; - start.value = {tx: cam.translateX.value, ty: cam.translateY.value, s: cam.scale.value}; - setStatus(`${nodes} nodes: pan`); - const pan = await measure(2); - setStatus(`${nodes} nodes: pan zoomed in`); + const here = (): Camera => ({tx: cam.translateX.value, ty: cam.translateY.value, s: cam.scale.value}); + const fitted = here(); const {w, h} = viewport.value; - const s = cam.scale.value; - cam.scale.value = s * 8; - cam.translateX.value = w / 2 - (w / 2 - cam.translateX.value) * 8; - cam.translateY.value = h / 2 - (h / 2 - cam.translateY.value) * 8; - await wait(1500); - start.value = {tx: cam.translateX.value, ty: cam.translateY.value, s: cam.scale.value}; - const close = await measure(3); - const row = {nodes, readyMs, pinchUi: pinch.ui, pinchJs: pinch.js, panUi: pan.ui, panJs: pan.js, closeUi: close.ui, closeJs: close.js}; + const phases = {} as BenchRow['phases']; + for (const which of PHASES) { + cam.translateX.value = fitted.tx; + cam.translateY.value = fitted.ty; + cam.scale.value = fitted.s; + if (which === 'close') { + cam.scale.value = fitted.s * 8; + cam.translateX.value = w / 2 - (w / 2 - fitted.tx) * 8; + cam.translateY.value = h / 2 - (h / 2 - fitted.ty) * 8; + } + // Culling catches up with the camera before the phase starts. + await wait(which === 'pinch' ? 0 : 1500); + start.value = here(); + setStatus(`${c.label}: ${which}`); + if (which === 'pinch') cam.isPinching.value = true; + if (which === 'doubleTap') { + const card = zoomedToMiddleCard(c.nodes, fitted, w, h); + phases[which] = await measure(c.label, which, async () => { + await tween(cam, card); + await tween(cam, fitted); + }); + } else { + phases[which] = await measure(c.label, which); + } + if (which === 'pinch') cam.isPinching.value = false; + } + const row: BenchRow = {label: c.label, nodes: c.nodes, readyMs, phases}; out.push(row); setRows([...out]); console.warn(`[BENCH] ${label} ${JSON.stringify(row)}`); } setStatus('Done'); - setSize(null); - }, [label, measure, phase, remount, start, viewport]); + setBenchCase(null); + }, [label, measure, remount, start, viewport]); useEffect(() => { if (autorun) void run(); @@ -234,13 +354,14 @@ export function Bench({autorun = true, label}: {autorun?: boolean; label: string return ( (viewport.value = {w: e.nativeEvent.layout.width, h: e.nativeEvent.layout.height})}> - {size !== null && camera !== null ? ( - + {benchCase !== null && camera !== null ? ( + ) : null} - {size !== null ? ( + {benchCase !== null ? ( ready.current?.({fitToViewport: c.fitToViewport, camera: c.camera})} /> @@ -249,8 +370,8 @@ export function Bench({autorun = true, label}: {autorun?: boolean; label: string {`${label}: ${status} ${live}`} {rows.map((r) => ( - - {`${r.nodes} nodes, ready in ${r.readyMs} ms\n pinch UI ${cell(r.pinchUi)}\n JS ${cell(r.pinchJs)}\n pan UI ${cell(r.panUi)}\n JS ${cell(r.panJs)}\n close UI ${cell(r.closeUi)}\n JS ${cell(r.closeJs)}`} + + {`${r.label} nodes, ready in ${r.readyMs} ms` + PHASES.map((p) => `\n ${p.padEnd(9)} UI ${cell(r.phases[p].ui)}\n JS ${cell(r.phases[p].js)}`).join('')} ))} @@ -264,7 +385,7 @@ const styles = StyleSheet.create({ results: {maxHeight: 330, backgroundColor: '#111'}, resultsBody: {padding: 10, gap: 6}, title: {color: '#fff', fontWeight: '600'}, - row: {color: '#ddd', fontFamily: 'Menlo', fontSize: 11}, + row: {color: '#ddd', fontFamily: Platform.select({android: 'monospace', default: 'Menlo'}), fontSize: 11}, }); /** The benchmark as an app's whole screen, for an entry point to register instead of the app (benchConfig.ts). */ diff --git a/example/shared/benchConfig.ts b/example/shared/benchConfig.ts index 3ae51b7..2d11afa 100644 --- a/example/shared/benchConfig.ts +++ b/example/shared/benchConfig.ts @@ -4,3 +4,15 @@ export const BENCH_AUTORUN = false; /** With BENCH_AUTORUN: mount and unmount the canvas this many times first, then show it (a remount must still draw). */ export const BENCH_REMOUNTS = 0; + +/** The generated canvases measured, by node count (generateCanvas.ts). */ +export const BENCH_SIZES = [500, 2000, 5000, 10000]; + +/** + * A folder (a file:// URI ending in `/`) holding workspace-fixtures' + * Fixtures/canvas images (`portraits/`, `drawings/shapes.svg`), to measure + * big-10000.canvas as well: the 10,000-node canvas with those images in place + * of the web ones, which is what that fixture is (scripts/big-canvas.mts). + * null leaves it out. + */ +export const BENCH_FIXTURE_DIR: string | null = null; From 55483c34fcf3bdd0e2d1950fb4b46b4a6e7e68a8 Mon Sep 17 00:00:00 2001 From: Leslie Owusu-Appiah Date: Sat, 7 Nov 2026 22:18:01 +0100 Subject: [PATCH 2/3] perf(example): the benchmark waits for the JavaScript thread before measuring A large canvas records its Picture once it opens, holding the JavaScript thread for seconds at 10,000 nodes, and the first phase measured that. Each canvas now waits for a second of frames with none over 50 ms, and reports how long the thread was busy after the fit (busyMs). Co-Authored-By: Claude Opus 5.5 --- example/shared/Bench.tsx | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/example/shared/Bench.tsx b/example/shared/Bench.tsx index 3442d4a..4da4ec8 100644 --- a/example/shared/Bench.tsx +++ b/example/shared/Bench.tsx @@ -77,6 +77,8 @@ export interface BenchRow { label: string; nodes: number; readyMs: number; + /** From the fit until the JavaScript thread is free again (it records the Picture meanwhile), less the second of calm it waits for. */ + busyMs: number; phases: Record; } @@ -173,6 +175,28 @@ const OWN_CLOCK = Platform.OS === 'macos'; const wait = (ms: number) => new Promise((done) => setTimeout(done, ms)); +/** + * Resolves once the JavaScript thread has run a second of frames with none + * over 50 ms: a large canvas records its Picture after it opens, which holds + * the thread for seconds at 10,000 nodes, and a phase measured then measures + * that instead. Gives up after 20 s. + */ +function jsIdle(): Promise { + return new Promise((done) => { + const began = Date.now(); + let calm = Date.now(); + let last = Date.now(); + const tick = () => { + const now = Date.now(); + if (now - last > 50) calm = now; + last = now; + if (now - calm >= 1000 || now - began > 20000) done(); + else requestAnimationFrame(tick); + }; + requestAnimationFrame(tick); + }); +} + interface Camera { tx: number; ty: number; @@ -305,7 +329,10 @@ export function Bench({autorun = true, label}: {autorun?: boolean; label: string const readyMs = Math.round(performance.now() - began); setCamera(controls.camera); controls.fitToViewport(); + const fittedAt = performance.now(); await wait(SETTLE_MS); + await jsIdle(); + const busyMs = Math.round(performance.now() - fittedAt - 1000); const cam = controls.camera; const here = (): Camera => ({tx: cam.translateX.value, ty: cam.translateY.value, s: cam.scale.value}); const fitted = here(); @@ -336,12 +363,13 @@ export function Bench({autorun = true, label}: {autorun?: boolean; label: string } if (which === 'pinch') cam.isPinching.value = false; } - const row: BenchRow = {label: c.label, nodes: c.nodes, readyMs, phases}; + const row: BenchRow = {label: c.label, nodes: c.nodes, readyMs, busyMs, phases}; out.push(row); setRows([...out]); console.warn(`[BENCH] ${label} ${JSON.stringify(row)}`); } setStatus('Done'); + console.warn('[BENCH-DONE]'); setBenchCase(null); }, [label, measure, remount, start, viewport]); @@ -371,7 +399,7 @@ export function Bench({autorun = true, label}: {autorun?: boolean; label: string {`${label}: ${status} ${live}`} {rows.map((r) => ( - {`${r.label} nodes, ready in ${r.readyMs} ms` + PHASES.map((p) => `\n ${p.padEnd(9)} UI ${cell(r.phases[p].ui)}\n JS ${cell(r.phases[p].js)}`).join('')} + {`${r.label} nodes, ready in ${r.readyMs} ms, JS busy ${r.busyMs} ms` + (Object.keys(r.phases) as PhaseName[]).map((p) => `\n ${p.padEnd(9)} UI ${cell(r.phases[p].ui)}\n JS ${cell(r.phases[p].js)}`).join('')} ))} From af9f7d296939a6c2103d122bd189e8c939632717 Mon Sep 17 00:00:00 2001 From: Leslie Owusu-Appiah Date: Sat, 7 Nov 2026 22:44:54 +0100 Subject: [PATCH 3/3] perf(renderer): record the canvas once at open, and only its images when they load The canvas was recorded twice as it opened, all of it and again without text for the overview, and both again when its images finished loading. On a Samsung Galaxy A15 each recording of 10,000 nodes held the JavaScript thread for 3.5 to 4 s, so a double-tap (a camera animation driven from that thread) could wait seconds after a canvas opened. The recording is now one Picture per layer (group cards, group images, edges and cards, text, file images, group labels), drawn one after another. The overview is the same layers less text, with nothing recorded again, and images that finish loading record only the two layers that draw them. What is drawn, and its order, is unchanged. A15 (release), JavaScript thread recording at open, before -> after: 2,000 nodes 1.9 s -> 0.7 s; 10,000 nodes 7.9 s -> 3.5 s. Co-Authored-By: Claude Opus 5.5 --- src/renderer/useCanvasPicture.ts | 130 +++++++++++++++++++++++-------- 1 file changed, 96 insertions(+), 34 deletions(-) diff --git a/src/renderer/useCanvasPicture.ts b/src/renderer/useCanvasPicture.ts index 6b00d7c..b2fac06 100644 --- a/src/renderer/useCanvasPicture.ts +++ b/src/renderer/useCanvasPicture.ts @@ -776,18 +776,10 @@ interface RecordingInputs { */ export type RecordingDetail = 'full' | 'overview' | 'shapes'; -function recordCanvasPicture(inputs: RecordingInputs, imageCache: ImageCache, detail: RecordingDetail = 'full'): SkPicture { - const {allNodes, edges, nodeMap, colorScheme, basePath, imageNames = 'onReveal'} = inputs; - const text = detail === 'full'; - const images = detail !== 'shapes'; - +/** What `recordCanvasPicture` and `recordLayers` draw from: the nodes' kinds sorted out once. */ +function sortInputs(inputs: RecordingInputs) { + const {allNodes, edges, nodeMap} = inputs; const groupNodes = allNodes.filter((n): n is GroupNode => n.type === 'group'); - const nonGroupNodes = allNodes.filter(n => n.type !== 'group'); - const textNodes = allNodes.filter((n): n is TextNode => n.type === 'text'); - const linkNodes = allNodes.filter((n): n is LinkNode => n.type === 'link'); - const fileNodes = allNodes.filter((n): n is FileNode => n.type === 'file'); - const labelledGroups = groupNodes.filter(n => !!n.label); - const resolvedEdges = edges .map(e => { const f = nodeMap.get(e.fromNode); @@ -809,30 +801,88 @@ function recordCanvasPicture(inputs: RecordingInputs, imageCache: ImageCache, de ? {x: minX - pad, y: minY - pad, width: maxX - minX + pad * 2, height: maxY - minY + pad * 2} : {x: 0, y: 0, width: 1, height: 1}; + return { + groupNodes, + nonGroupNodes: allNodes.filter(n => n.type !== 'group'), + textNodes: allNodes.filter((n): n is TextNode => n.type === 'text'), + linkNodes: allNodes.filter((n): n is LinkNode => n.type === 'link'), + fileNodes: allNodes.filter((n): n is FileNode => n.type === 'file'), + labelledGroups: groupNodes.filter(n => !!n.label), + resolvedEdges, + bounds, + }; +} + +type Sorted = ReturnType; + +/** + * The canvas's drawing, layer by layer, bottom to top. Each layer is its own + * Picture, so a change that touches one (images finishing loading) records + * that one again rather than everything, and the overview is the full + * drawing less its text layers rather than a second recording. Drawn one + * after another they make exactly the drawing one recording makes. + */ +const LAYERS = { + /** Layer 1: group cards. */ + groups: (canvas: SkCanvas, d: Sorted, inputs: RecordingInputs) => { + for (const node of d.groupNodes) drawCard(canvas, node, inputs.colorScheme); + }, + /** Layer 2: group background images. */ + groupImages: (canvas: SkCanvas, d: Sorted, inputs: RecordingInputs, images: ImageCache) => { + for (const node of d.groupNodes) drawGroupBackground(canvas, node, images, inputs.basePath); + }, + /** Layers 3 and 4: edges, then the other cards. */ + shapes: (canvas: SkCanvas, d: Sorted, inputs: RecordingInputs) => { + for (const {edge, fromNode, toNode} of d.resolvedEdges) drawEdge(canvas, edge, fromNode, toNode); + for (const node of d.nonGroupNodes) drawCard(canvas, node, inputs.colorScheme); + }, + /** Layer 5: text, links and file labels. */ + text: (canvas: SkCanvas, d: Sorted, inputs: RecordingInputs) => { + for (const node of d.textNodes) drawTextNode(canvas, node, inputs.colorScheme); + for (const node of d.linkNodes) drawLinkNode(canvas, node, inputs.colorScheme); + for (const node of d.fileNodes) drawFileLabel(canvas, node, inputs.colorScheme, inputs.imageNames ?? 'onReveal'); + }, + /** Layer 5: file images. */ + fileImages: (canvas: SkCanvas, d: Sorted, inputs: RecordingInputs, images: ImageCache) => { + for (const node of d.fileNodes) drawFileImage(canvas, node, images, inputs.basePath, inputs.imageNames ?? 'onReveal'); + }, + /** Layer 6: group labels. */ + groupLabels: (canvas: SkCanvas, d: Sorted, inputs: RecordingInputs) => { + for (const node of d.labelledGroups) drawGroupLabel(canvas, node, inputs.colorScheme); + }, +}; + +type LayerName = keyof typeof LAYERS; +const LAYER_ORDER: LayerName[] = ['groups', 'groupImages', 'shapes', 'text', 'fileImages', 'groupLabels']; +/** The layers that draw images: recorded again when images finish loading. */ +const IMAGE_LAYERS: LayerName[] = ['groupImages', 'fileImages']; +/** What each recording holds (see RecordingDetail). */ +const DETAIL_LAYERS: Record = { + full: LAYER_ORDER, + overview: ['groups', 'groupImages', 'shapes', 'fileImages'], + shapes: ['groups', 'shapes'], +}; + +function recordLayer(name: LayerName, d: Sorted, inputs: RecordingInputs, images: ImageCache): SkPicture { + return createPicture((canvas: SkCanvas) => LAYERS[name](canvas, d, inputs, images), d.bounds); +} + +function composeLayers(layers: Partial>, names: LayerName[], bounds: Sorted['bounds']): SkPicture { return createPicture((canvas: SkCanvas) => { - // Layer 1: group cards - for (const node of groupNodes) drawCard(canvas, node, colorScheme); - // Layer 2: group background images - if (images) for (const node of groupNodes) drawGroupBackground(canvas, node, imageCache, basePath); - // Layer 3: edges - for (const {edge, fromNode, toNode} of resolvedEdges) drawEdge(canvas, edge, fromNode, toNode); - // Layer 4: non-group cards - for (const node of nonGroupNodes) drawCard(canvas, node, colorScheme); - if (text) { - // Layer 5: text - for (const node of textNodes) drawTextNode(canvas, node, colorScheme); - // Layer 5: links - for (const node of linkNodes) drawLinkNode(canvas, node, colorScheme); - // Layer 5: file labels - for (const node of fileNodes) drawFileLabel(canvas, node, colorScheme, imageNames); + for (const name of names) { + const layer = layers[name]; + if (layer) canvas.drawPicture(layer); } - // Layer 5: file images - if (images) for (const node of fileNodes) drawFileImage(canvas, node, imageCache, basePath, imageNames); - // Layer 6: group labels - if (text) for (const node of labelledGroups) drawGroupLabel(canvas, node, colorScheme); }, bounds); } +function recordCanvasPicture(inputs: RecordingInputs, imageCache: ImageCache, detail: RecordingDetail = 'full'): SkPicture { + const d = sortInputs(inputs); + return createPicture((canvas: SkCanvas) => { + for (const name of DETAIL_LAYERS[detail]) LAYERS[name](canvas, d, inputs, imageCache); + }, d.bounds); +} + /** The canvas's cards and edges as one Picture, for the minimap: drawn every frame as a single replay rather than thousands of live shapes. */ export function recordShapesPicture(allNodes: CanvasNode[], edges: CanvasEdge[], colorScheme: ColorScheme): SkPicture { const nodeMap = new Map(allNodes.map(n => [n.id, n] as const)); @@ -923,8 +973,10 @@ export function useCanvasPicture(inputs: RecordingInputs): CanvasPictures | null const inputsRef = useRef(inputs); inputsRef.current = inputs; - // Effect 2 — Picture recording. Depends on content identity (nodeMap, - // colorScheme) and cacheVersion. + // Effect 2 — Picture recording, layer by layer (LAYERS). New content, a + // new colour scheme or a change to how image names show records every + // layer; images finishing loading records only the layers that draw them. + const layersRef = useRef<{key: unknown[]; sorted: Sorted; layers: Partial>} | null>(null); useEffect(() => { let cancelled = false; @@ -932,9 +984,19 @@ export function useCanvasPicture(inputs: RecordingInputs): CanvasPictures | null if (cancelled) return; requestAnimationFrame(() => { if (cancelled) return; + const current = inputsRef.current; + const key = [current.nodeMap, current.colorScheme, current.imageNames, current.allNodes, current.edges]; + const kept = layersRef.current; + const same = kept != null && kept.key.every((k, i) => k === key[i]); + const sorted = same ? kept.sorted : sortInputs(current); + const layers: Partial> = same ? {...kept.layers} : {}; + for (const name of LAYER_ORDER) { + if (!layers[name] || IMAGE_LAYERS.includes(name)) layers[name] = recordLayer(name, sorted, current, imageCacheRef.current); + } + layersRef.current = {key, sorted, layers}; setPicture({ - full: recordCanvasPicture(inputsRef.current, imageCacheRef.current, 'full'), - overview: recordCanvasPicture(inputsRef.current, imageCacheRef.current, 'overview'), + full: composeLayers(layers, DETAIL_LAYERS.full, sorted.bounds), + overview: composeLayers(layers, DETAIL_LAYERS.overview, sorted.bounds), }); }); });