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
This commit is contained in:
Maurice
2026-11-16 10:30:32 +01:00
parent 24bc132476
commit aa8d041a33
6 changed files with 181 additions and 5 deletions
+2 -2
View File
@@ -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 = (
<img
src={photoSrc(photoId, big)}
{...(print ? { [PRINT_SRC_ATTR]: photoSrc(photoId, big) } : { src: photoSrc(photoId, big) })}
alt=""
draggable={false}
// Lazy on the canvas, where a long book scrolls past; eager in print,
@@ -10,6 +10,18 @@
// here is exactly how #2183 happened: the renderer kept a three-font copy
// while the picker grew to seven, and everything else fell back to Poppins.
/**
* Where a printed photo keeps its source until the print view asks for it.
*
* A book's sheets are rendered in one go, and an `<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'}`
}
@@ -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) => `<img ${PRINT_SRC_ATTR}="/api/photos/${i}/original">`
).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<string, number> = {}) {
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();
});
});
@@ -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<boolean> {
return new Promise<boolean>((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<void> {
const concurrency = Math.max(1, options.concurrency ?? PRINT_IMAGES.concurrency);
const timeoutMs = options.timeoutMs ?? PRINT_IMAGES.timeoutMs;
const images = Array.from(doc.querySelectorAll<HTMLImageElement>(`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));
}
+6 -1
View File
@@ -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
})
@@ -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)
})
})