// The PDF Viewer feature. `loader.ts` imports this module when the first PDF tab opens. The file tree marks PDF files // before that, through the document type of the catalog (`../pdfDocument.ts`). // Each tab reads its file with `workspace_read_bytes` (64 MiB at most) and has its own PDF.js worker. import { flushSync, mount, unmount } from "svelte"; import { tr } from "../../i18n/index.ts"; import { workspaceReadBytes } from "../../workspace/api.ts"; import type { FeatureContext, FeatureInstance } from "../types.ts"; import PdfViewer from "./PdfViewer.svelte"; export function start(_context: FeatureContext): FeatureInstance { const tabs = new Set<() => Promise>(); let stopped = false; return { mount() { throw new Error(tr("This view is unavailable.")); }, mountDocument(type, element, file) { if (type !== "pdf") throw new Error(tr("This view is unavailable.")); if (stopped) throw new Error(tr("This feature is off.")); const viewer = mount(PdfViewer, { target: element, props: { file, readBytes: workspaceReadBytes } }); flushSync(); let closing: Promise | undefined; // Release the document and stop its worker first. Then remove the component. const dispose = () => closing ??= viewer.close().then(() => unmount(viewer)).finally(() => { tabs.delete(dispose); }); tabs.add(dispose); return dispose; }, /** The host closes the PDF tabs first. Close what is left, so no worker stays. */ async dispose() { stopped = true; await Promise.allSettled([...tabs].map(dispose => dispose())); }, }; }