From aa8d041a33620ec8a853eac335177fe1d4b9c5b5 Mon Sep 17 00:00:00 2001 From: Maurice Date: Mon, 16 Nov 2026 10:30:32 +0100 Subject: [PATCH] fix(studio): load a large book's photos a few at a time for the PDF export Every printed photo got its src at once, off screen in the editor and again in the print frame, so a journey with a few hundred photos asked for every original in parallel and the browser failed with insufficient resources. The print markup now holds the source back, and the print view hands it over four at a time, retries a failed photo once, gives up on one that never answers and shows the progress on the Save button. Closes #3102 --- client/src/components/Studio/PhotoView.tsx | 4 +- client/src/components/Studio/bookRender.ts | 12 +++ .../src/components/Studio/printImages.test.ts | 86 +++++++++++++++++++ client/src/components/Studio/printImages.ts | 71 +++++++++++++++ client/src/components/Studio/printSheets.ts | 7 +- .../tests/unit/studio/BookSheetsView.test.tsx | 6 +- 6 files changed, 181 insertions(+), 5 deletions(-) create mode 100644 client/src/components/Studio/printImages.test.ts create mode 100644 client/src/components/Studio/printImages.ts diff --git a/client/src/components/Studio/PhotoView.tsx b/client/src/components/Studio/PhotoView.tsx index f3313042e..0b45eb63f 100644 --- a/client/src/components/Studio/PhotoView.tsx +++ b/client/src/components/Studio/PhotoView.tsx @@ -2,7 +2,7 @@ import { photoLookOf, type BookFrame, type BookPhotoElement, type BookShapeId, t import type { CSSProperties, ReactNode } from 'react'; import { fontStack } from './bookFonts'; -import { photoSrc } from './bookRender'; +import { PRINT_SRC_ATTR, photoSrc } from './bookRender'; import { usePaintId } from './paint/usePaintId'; import { pictureFilter, silhouetteShadows, svgFilterMatrices, zoomPlacement } from './photo/photoLook'; import { photoClip } from './shapeOutline'; @@ -172,7 +172,7 @@ function Picture({ const zoom = zoomPlacement(look.zoom, el.focalX, el.focalY); const img = ( ` starts loading the + * moment it has a `src`. A journey of a few hundred photos asked the server for + * every original at once, twice (off screen in the editor, then in the print + * frame), and the browser gave up with "insufficient resources" (#3102). So the + * print markup carries the source here and `loadPrintImages` hands it over a + * few at a time. + */ +export const PRINT_SRC_ATTR = 'data-print-src' + export function photoSrc(photoId: number, big: boolean): string { return `/api/photos/${photoId}/${big ? 'original' : 'thumbnail'}` } diff --git a/client/src/components/Studio/printImages.test.ts b/client/src/components/Studio/printImages.test.ts new file mode 100644 index 000000000..7658c22e4 --- /dev/null +++ b/client/src/components/Studio/printImages.test.ts @@ -0,0 +1,86 @@ +/** + * FE-STUDIO-PRINTIMG-001 to FE-STUDIO-PRINTIMG-004 + * + * The print view hands a book's photographs their sources a few at a time, so + * a large journey does not ask for every original at once (#3102). + */ +import { describe, expect, it } from 'vitest'; + +import { PRINT_SRC_ATTR } from './bookRender'; +import { loadPrintImages } from './printImages'; + +/** A print document with `count` deferred photos. */ +function printDoc(count: number): { doc: Document; imgs: HTMLImageElement[] } { + const doc = document.implementation.createHTMLDocument('print'); + doc.body.innerHTML = Array.from( + { length: count }, + (_, i) => `` + ).join(''); + return { doc, imgs: Array.from(doc.images) }; +} + +/** + * Answers each source the loader sets, on the next tick, the way a browser fires + * load or error. `fails` says how many times a source errors before it loads; + * a source mapped to Infinity never answers. Tracks the most in flight at once. + */ +function answer(imgs: HTMLImageElement[], fails: Record = {}) { + const state = { inFlight: 0, maxInFlight: 0, requests: [] as string[] }; + for (const img of imgs) { + Object.defineProperty(img, 'src', { + configurable: true, + get: () => img.getAttribute('src') ?? '', + set: (src: string) => { + img.setAttribute('src', src); + state.requests.push(src); + if (fails[src] === Infinity) return; + state.inFlight++; + state.maxInFlight = Math.max(state.maxInFlight, state.inFlight); + setTimeout(() => { + state.inFlight--; + const left = fails[src] ?? 0; + if (left > 0) { + fails[src] = left - 1; + img.dispatchEvent(new Event('error')); + } else img.dispatchEvent(new Event('load')); + }, 0); + }, + }); + } + return state; +} + +describe('loadPrintImages', () => { + it('FE-STUDIO-PRINTIMG-001: loads every deferred photo with no more than the limit in flight', async () => { + const { doc, imgs } = printDoc(10); + const state = answer(imgs); + const progress: string[] = []; + await loadPrintImages(doc, { concurrency: 3, onProgress: (done, total) => progress.push(`${done}/${total}`) }); + expect(state.maxInFlight).toBe(3); + expect(imgs.every((img) => img.getAttribute('src')?.startsWith('/api/photos/'))).toBe(true); + expect(imgs.some((img) => img.hasAttribute(PRINT_SRC_ATTR))).toBe(false); + expect(progress.at(-1)).toBe('10/10'); + }); + + it('FE-STUDIO-PRINTIMG-002: asks once more for a photo that failed', async () => { + const { doc, imgs } = printDoc(1); + const state = answer(imgs, { '/api/photos/0/original': 1 }); + await loadPrintImages(doc); + expect(state.requests).toEqual(['/api/photos/0/original', '/api/photos/0/original']); + expect(imgs[0].getAttribute('src')).toBe('/api/photos/0/original'); + }); + + it('FE-STUDIO-PRINTIMG-003: gives up on a photo that never answers, so the others and the button still finish', async () => { + const { doc, imgs } = printDoc(2); + answer(imgs, { '/api/photos/0/original': Infinity }); + const progress: number[] = []; + await loadPrintImages(doc, { timeoutMs: 5, onProgress: (done) => progress.push(done) }); + expect(progress).toEqual([1, 2]); + expect(imgs[1].getAttribute('src')).toBe('/api/photos/1/original'); + }); + + it('FE-STUDIO-PRINTIMG-004: a book without photos is ready at once', async () => { + const { doc } = printDoc(0); + await expect(loadPrintImages(doc)).resolves.toBeUndefined(); + }); +}); diff --git a/client/src/components/Studio/printImages.ts b/client/src/components/Studio/printImages.ts new file mode 100644 index 000000000..8cb740531 --- /dev/null +++ b/client/src/components/Studio/printImages.ts @@ -0,0 +1,71 @@ +/** + * Loading a book's photographs into its print view a few at a time. + * + * The sheets carry each photo's source in `PRINT_SRC_ATTR` rather than in + * `src` (see bookRender.ts), so nothing loads until this hands the sources + * over. A handful run at once: enough to keep the connection busy, few enough + * that a book of several hundred originals does not exhaust the browser + * (#3102). A photo that fails is asked for once more before it is left blank, + * and one that never answers is given up on after a while, so the Save button + * always comes on in the end. + */ + +import { PRINT_SRC_ATTR } from './bookRender'; + +const PRINT_IMAGES = { + concurrency: 4, + timeoutMs: 60_000, + retries: 1, +} as const; + +export interface PrintImageOptions { + concurrency?: number; + timeoutMs?: number; + /** Called after each photo has loaded or been given up on. */ + onProgress?: (done: number, total: number) => void; +} + +/** Point `img` at `src` and resolve with whether it loaded, or false after `timeoutMs`. */ +function loadOne(img: HTMLImageElement, src: string, timeoutMs: number): Promise { + return new Promise((resolve) => { + const finish = (ok: boolean) => { + clearTimeout(timer); + img.removeEventListener('load', onLoad); + img.removeEventListener('error', onError); + resolve(ok); + }; + const onLoad = () => finish(true); + const onError = () => finish(false); + const timer = setTimeout(() => finish(false), timeoutMs); + img.addEventListener('load', onLoad); + img.addEventListener('error', onError); + img.src = src; + }); +} + +/** Resolves once every deferred photo in `doc` has loaded or been given up on. */ +export async function loadPrintImages(doc: Document, options: PrintImageOptions = {}): Promise { + const concurrency = Math.max(1, options.concurrency ?? PRINT_IMAGES.concurrency); + const timeoutMs = options.timeoutMs ?? PRINT_IMAGES.timeoutMs; + const images = Array.from(doc.querySelectorAll(`img[${PRINT_SRC_ATTR}]`)); + const total = images.length; + let next = 0; + let done = 0; + + const worker = async () => { + while (next < images.length) { + const img = images[next++]; + const src = img.getAttribute(PRINT_SRC_ATTR) ?? ''; + img.removeAttribute(PRINT_SRC_ATTR); + for (let attempt = 0; attempt <= PRINT_IMAGES.retries; attempt++) { + if (await loadOne(img, src, timeoutMs)) break; + // A second request for the same URL needs the attribute to change to fire again. + img.removeAttribute('src'); + } + done++; + options.onProgress?.(done, total); + } + }; + + await Promise.all(Array.from({ length: Math.min(concurrency, total) }, worker)); +} diff --git a/client/src/components/Studio/printSheets.ts b/client/src/components/Studio/printSheets.ts index f5ef2b745..215fbb29b 100644 --- a/client/src/components/Studio/printSheets.ts +++ b/client/src/components/Studio/printSheets.ts @@ -23,6 +23,7 @@ * standalone PWA. An overlay with a `srcdoc` iframe works everywhere. */ +import { loadPrintImages } from './printImages' import { whenReady } from './printReady' /* @@ -248,7 +249,11 @@ ${singleRule(input)} iframe.addEventListener('load', () => { fitPreview() - void whenReady(iframe).then(() => { + const frameDoc = iframe.contentDocument + const photos = frameDoc ? loadPrintImages(frameDoc, { + onProgress: (done, total) => { save.textContent = `${input.labels.preparing} ${done}/${total}` }, + }) : Promise.resolve() + void photos.then(() => whenReady(iframe)).then(() => { save.disabled = false save.textContent = input.labels.save }) diff --git a/client/tests/unit/studio/BookSheetsView.test.tsx b/client/tests/unit/studio/BookSheetsView.test.tsx index 88d4ba873..41e914ba2 100644 --- a/client/tests/unit/studio/BookSheetsView.test.tsx +++ b/client/tests/unit/studio/BookSheetsView.test.tsx @@ -219,7 +219,9 @@ describe('what the sheets are made of', () => { const img = container.querySelector('img') expect(img).not.toBeNull() // `original`, not `thumbnail` — the print is the one place the big file is - // worth waiting for. - expect(img!.getAttribute('src')).toContain('/original') + // worth waiting for. Held back from `src` until the print view loads it a + // few at a time (#3102). + expect(img!.getAttribute('data-print-src')).toContain('/original') + expect(img!.hasAttribute('src')).toBe(false) }) })