Make PDF Viewer a native feature
- Move the PDF Viewer plugin into src/lib/features/pdf/ with pdfjs-dist 6.4.299 (minified builds). - A static pdf document type marks PDF files and opens them as tabs. The first PDF tab loads the module. - The worker, the character maps, the fonts, and the decoders come from the app. One worker for each tab. - The toolbar uses IconButton and the shared tooltip, with the new zoom-in, zoom-out, fit-width, and rotate icons. - Add THIRD_PARTY_NOTICES.md for PDF.js and xterm. - Update the tests, the menu inventory, the docs, and UI-059.
This commit is contained in:
@@ -0,0 +1,239 @@
|
||||
<script lang="ts">
|
||||
// One PDF tab: the toolbar, the status line, the password form, and one page with its text layer.
|
||||
// The document and its worker live as long as the tab. `close` releases both.
|
||||
import { onMount } from "svelte";
|
||||
import { message, t } from "$lib/i18n";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import type { PluginDocumentContext } from "$lib/plugins/sdk";
|
||||
import { openPdf, TextLayer, type OpenPdf, type PDFDocumentProxy, type RenderTask } from "./engine";
|
||||
import { MAX_ZOOM, MIN_ZOOM, RESIZE_SETTLE_MS, ZOOM_STEP, nextRotation, outputScale, pageNumber, zoomLevel } from "./model";
|
||||
|
||||
let { file, readBytes }: { file: PluginDocumentContext; readBytes: (path: string) => Promise<Uint8Array> } = $props();
|
||||
|
||||
type Status = { key: string; values?: Record<string, string | number>; alert?: boolean };
|
||||
|
||||
let page = $state(1);
|
||||
let count = $state(0);
|
||||
let zoom = $state(1);
|
||||
let rotation = $state(0);
|
||||
let fit = $state(true);
|
||||
let status = $state<Status>({ key: message("Loading PDF…") });
|
||||
let asking = $state<"needed" | "incorrect" | null>(null);
|
||||
let reloading = $state(false);
|
||||
let failed = $state(false);
|
||||
let scroller: HTMLDivElement;
|
||||
let sheet: HTMLDivElement;
|
||||
let pageInput: HTMLInputElement;
|
||||
let passwordInput: HTMLInputElement | undefined = $state();
|
||||
|
||||
let disposed = false;
|
||||
let pdf: PDFDocumentProxy | undefined;
|
||||
let opened: OpenPdf | undefined;
|
||||
let answer: ((password: string) => void) | undefined;
|
||||
let render: RenderTask | undefined;
|
||||
let text: TextLayer | undefined;
|
||||
let revision = 0;
|
||||
let queue: Promise<void> = Promise.resolve();
|
||||
let loading: Promise<void> = Promise.resolve();
|
||||
let closing: Promise<void> | undefined;
|
||||
|
||||
const ready = $derived(count > 0);
|
||||
|
||||
function fail(reason: unknown) {
|
||||
if (disposed) return;
|
||||
failed = true;
|
||||
status = { key: message("Cannot display this PDF. {reason}"), values: { reason: reason instanceof Error ? reason.message : String(reason) }, alert: true };
|
||||
}
|
||||
|
||||
/** Draw the current page again. A newer request cancels the older one. */
|
||||
function schedule() {
|
||||
const request = ++revision;
|
||||
render?.cancel(); text?.cancel();
|
||||
if (pdf && !disposed) status = { key: message("Loading page {page}…"), values: { page } };
|
||||
queue = queue.then(async () => {
|
||||
if (disposed || request !== revision || !pdf || scroller.clientWidth === 0) return;
|
||||
const pdfPage = await pdf.getPage(page);
|
||||
if (disposed || request !== revision) return;
|
||||
const angle = (pdfPage.rotate + rotation) % 360;
|
||||
if (fit) zoom = zoomLevel((scroller.clientWidth - 32) / pdfPage.getViewport({ scale: 1, rotation: angle }).width);
|
||||
const viewport = pdfPage.getViewport({ scale: zoom, rotation: angle });
|
||||
const scale = outputScale(viewport.width, viewport.height, window.devicePixelRatio);
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = Math.max(1, Math.floor(viewport.width * scale));
|
||||
canvas.height = Math.max(1, Math.floor(viewport.height * scale));
|
||||
canvas.style.width = `${viewport.width}px`;
|
||||
canvas.style.height = `${viewport.height}px`;
|
||||
canvas.setAttribute("role", "img");
|
||||
// The measurement tool and the smoke tests find the page by this English name. Keep "PDF page N".
|
||||
canvas.setAttribute("aria-label", $t("PDF page {page}", { page }));
|
||||
const layer = document.createElement("div");
|
||||
layer.className = "textLayer";
|
||||
sheet.style.width = `${viewport.width}px`;
|
||||
sheet.style.height = `${viewport.height}px`;
|
||||
sheet.style.setProperty("--total-scale-factor", String(zoom));
|
||||
sheet.replaceChildren(canvas, layer);
|
||||
render = pdfPage.render({ canvas, viewport, transform: scale === 1 ? undefined : [scale, 0, 0, scale, 0, 0] });
|
||||
await render.promise;
|
||||
if (disposed || request !== revision) return;
|
||||
text = new TextLayer({ textContentSource: pdfPage.streamTextContent(), container: layer, viewport });
|
||||
await text.render();
|
||||
if (disposed || request !== revision) return;
|
||||
status = { key: message("Page {page} of {count}"), values: { page, count } };
|
||||
pdfPage.cleanup();
|
||||
}).catch(reason => { if (!disposed && request === revision) fail(reason); });
|
||||
}
|
||||
|
||||
function go(value: number) {
|
||||
if (!pdf) return;
|
||||
page = pageNumber(value, pdf.numPages);
|
||||
pageInput.value = String(page);
|
||||
scroller.scrollTop = 0;
|
||||
schedule();
|
||||
}
|
||||
|
||||
function setZoom(value: number) { fit = false; zoom = zoomLevel(value); schedule(); }
|
||||
|
||||
async function load() {
|
||||
failed = false;
|
||||
status = { key: message("Loading PDF…") };
|
||||
const bytes = await readBytes(file.path);
|
||||
if (disposed) return;
|
||||
opened = openPdf(bytes, (reason, next) => {
|
||||
if (disposed) return;
|
||||
answer = next;
|
||||
asking = reason;
|
||||
status = reason === "incorrect" ? { key: message("Incorrect password. Try again.") } : { key: message("This PDF needs a password.") };
|
||||
queueMicrotask(() => passwordInput?.focus());
|
||||
});
|
||||
pdf = await opened.promise;
|
||||
if (disposed) return;
|
||||
page = pageNumber(page, pdf.numPages);
|
||||
count = pdf.numPages;
|
||||
schedule();
|
||||
}
|
||||
|
||||
async function release() {
|
||||
revision++;
|
||||
render?.cancel(); text?.cancel();
|
||||
await queue;
|
||||
const current = opened;
|
||||
opened = undefined; pdf = undefined; answer = undefined; asking = null; count = 0;
|
||||
sheet?.replaceChildren();
|
||||
await current?.close();
|
||||
}
|
||||
|
||||
async function reload() {
|
||||
if (reloading || disposed) return;
|
||||
reloading = true;
|
||||
try {
|
||||
await loading;
|
||||
await release();
|
||||
if (!disposed) await (loading = load());
|
||||
} catch (reason) { fail(reason); }
|
||||
finally { reloading = false; }
|
||||
}
|
||||
|
||||
function unlock(event: SubmitEvent) {
|
||||
event.preventDefault();
|
||||
if (!passwordInput || !answer) return;
|
||||
const value = passwordInput.value;
|
||||
passwordInput.value = "";
|
||||
asking = null;
|
||||
status = { key: message("Loading PDF…") };
|
||||
const next = answer;
|
||||
answer = undefined;
|
||||
next(value);
|
||||
}
|
||||
|
||||
function pageKey(event: KeyboardEvent) {
|
||||
if (event.ctrlKey || event.metaKey || event.altKey || !ready) return;
|
||||
if (event.key === "PageDown" || event.key === "PageUp") {
|
||||
event.preventDefault();
|
||||
go(page + (event.key === "PageDown" ? 1 : -1));
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop the drawing, release the document, and stop its worker. The host calls it before it removes the tab. */
|
||||
export function close(): Promise<void> {
|
||||
if (closing) return closing;
|
||||
disposed = true;
|
||||
closing = release().then(() => loading).catch(() => {});
|
||||
return closing;
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
loading = load().catch(fail);
|
||||
// A fit-width page follows the width of the tab. The first size draws at once. Later sizes wait until the size settles.
|
||||
let width = 0;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const observer = new ResizeObserver(() => {
|
||||
const next = scroller.clientWidth;
|
||||
if (next === 0 || next === width) return;
|
||||
const first = width === 0;
|
||||
width = next;
|
||||
clearTimeout(timer);
|
||||
if (!fit) return;
|
||||
if (first) schedule();
|
||||
else timer = setTimeout(schedule, RESIZE_SETTLE_MS);
|
||||
});
|
||||
observer.observe(scroller);
|
||||
return () => { observer.disconnect(); clearTimeout(timer); void close(); };
|
||||
});
|
||||
</script>
|
||||
|
||||
<section class="pdf-viewer" aria-label={$t("PDF Viewer")}>
|
||||
<div class="toolbar" role="group" aria-label={$t("PDF controls")}>
|
||||
<IconButton icon="up" label={$t("Previous page")} disabled={!ready || page <= 1} onclick={() => go(page - 1)} />
|
||||
<input bind:this={pageInput} class="page" type="number" min="1" max={Math.max(count, 1)} value={page} disabled={!ready}
|
||||
aria-label={$t("Page number")} onchange={event => { if (Number(event.currentTarget.value) !== page) go(Number(event.currentTarget.value)); }}
|
||||
onkeydown={event => { if (event.key === "Enter") go(Number(event.currentTarget.value)); }} />
|
||||
<span class="count">/ {ready ? count : "—"}</span>
|
||||
<IconButton icon="down" label={$t("Next page")} disabled={!ready || page >= count} onclick={() => go(page + 1)} />
|
||||
<span class="separator" aria-hidden="true"></span>
|
||||
<IconButton icon="zoom-out" label={$t("Zoom out")} disabled={!ready || zoom <= MIN_ZOOM} onclick={() => setZoom(zoom / ZOOM_STEP)} />
|
||||
<span class="zoom">{ready ? `${Math.round(zoom * 100)}%` : "—"}</span>
|
||||
<IconButton icon="zoom-in" label={$t("Zoom in")} disabled={!ready || zoom >= MAX_ZOOM} onclick={() => setZoom(zoom * ZOOM_STEP)} />
|
||||
<IconButton icon="fit-width" label={$t("Fit width")} active={fit && ready} disabled={!ready} onclick={() => { fit = true; schedule(); }} />
|
||||
<IconButton icon="rotate" label={$t("Rotate clockwise")} disabled={!ready} onclick={() => { rotation = nextRotation(rotation); schedule(); }} />
|
||||
<IconButton icon="refresh" label={$t("Reload PDF")} disabled={reloading || (!ready && !failed)} onclick={() => void reload()} />
|
||||
</div>
|
||||
<p class="status" class:alert={status.alert} role={status.alert ? "alert" : "status"} aria-live={status.alert ? "assertive" : "polite"}>{$t(status.key, status.values)}</p>
|
||||
{#if asking}
|
||||
<form class="password" onsubmit={unlock}>
|
||||
<label>{$t("PDF password")} <input bind:this={passwordInput} type="password" autocomplete="off" /></label>
|
||||
<button class="text-button" type="submit">{$t("Unlock")}</button>
|
||||
</form>
|
||||
{/if}
|
||||
<!-- The page area takes focus for Page Up and Page Down. -->
|
||||
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions -->
|
||||
<div bind:this={scroller} class="scroll" tabindex="0" role="region" aria-label={$t("PDF page. Use Page Up and Page Down to change pages.")} onkeydown={pageKey}>
|
||||
<div bind:this={sheet} class="sheet"></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.pdf-viewer { display: flex; flex-direction: column; height: 100%; min-height: 240px; min-width: 0; color: var(--rs-text); font-size: 13px; }
|
||||
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 2px; padding: 4px 8px; border-bottom: 1px solid var(--rs-border); }
|
||||
.page { box-sizing: border-box; width: 64px; height: 28px; margin-left: 4px; padding: 2px 4px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; text-align: right; }
|
||||
.page:disabled { color: var(--rs-text-dim); }
|
||||
.count { margin: 0 4px; color: var(--rs-text-dim); white-space: nowrap; }
|
||||
.separator { width: 1px; height: 18px; margin: 0 4px; background: var(--rs-border); }
|
||||
.zoom { min-width: 44px; color: var(--rs-text-dim); text-align: center; white-space: nowrap; }
|
||||
.status { margin: 0; padding: 4px 12px; font-size: 12px; color: var(--rs-text-dim); overflow-wrap: anywhere; }
|
||||
.status.alert { color: var(--rs-error); }
|
||||
.password { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 12px; }
|
||||
.password input { box-sizing: border-box; height: 28px; margin-left: 4px; padding: 2px 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||
.text-button { min-height: 28px; padding: 3px 10px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: inherit; }
|
||||
.text-button:hover { background: var(--rs-bg-active); }
|
||||
.scroll { flex: 1; min-height: 0; overflow: auto; padding: 16px; }
|
||||
.scroll:focus-visible { outline-offset: -2px; }
|
||||
/* A PDF page is paper: white in both themes. */
|
||||
.sheet { position: relative; margin: 0 auto; background: white; box-shadow: 0 2px 10px #0003; }
|
||||
.sheet :global(canvas) { display: block; }
|
||||
/* The text layer geometry follows the viewer styles of PDF.js 6 (Apache-2.0). See THIRD_PARTY_NOTICES.md. */
|
||||
.sheet :global(.textLayer) { position: absolute; inset: 0; overflow: clip; text-align: initial; line-height: 1; letter-spacing: normal; word-spacing: normal; text-size-adjust: none; forced-color-adjust: none; transform-origin: 0 0; --min-font-size: 1; --text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size)); --min-font-size-inv: calc(1 / var(--min-font-size)); }
|
||||
.sheet :global(.textLayer :is(span, br)) { position: absolute; color: transparent; white-space: pre; cursor: text; transform-origin: 0 0; user-select: text; }
|
||||
.sheet :global(.textLayer > :not(.markedContent)), .sheet :global(.markedContent span:not(.markedContent)) { z-index: 1; --font-height: 0; font-size: calc(var(--text-scale-factor) * var(--font-height)); --scale-x: 1; --rotate: 0deg; transform: rotate(var(--rotate)) scaleX(var(--scale-x)) scale(var(--min-font-size-inv)); }
|
||||
.sheet :global(.markedContent) { display: contents; }
|
||||
.sheet :global(.textLayer ::selection) { background: color-mix(in srgb, var(--rs-selection) 65%, transparent); color: transparent; }
|
||||
</style>
|
||||
@@ -0,0 +1,69 @@
|
||||
/// <reference types="vite/client" />
|
||||
// PDF.js for the PDF Viewer feature. The worker, the character maps, the standard fonts, and the WebAssembly image
|
||||
// decoders come from the app (`'self'`) as Vite assets, so a PDF never causes a network request.
|
||||
// Each open document has its own worker. `close` stops it.
|
||||
// The reference to the Vite types serves the unit test type check, which reaches this file through `loader.ts`.
|
||||
import { getDocument, PDFWorker, PasswordResponses, type PDFDocumentLoadingTask, type PDFDocumentProxy } from "pdfjs-dist/build/pdf.min.mjs";
|
||||
import workerUrl from "pdfjs-dist/build/pdf.worker.min.mjs?url";
|
||||
|
||||
export { TextLayer, type PDFDocumentProxy, type RenderTask } from "pdfjs-dist/build/pdf.min.mjs";
|
||||
|
||||
// `build.assetsInlineLimit` in vite.config.js keeps these files out of the code, so each one is a file of the app.
|
||||
// The JPEG 2000 and JBIG2 decoders are the only WebAssembly files that PDF.js asks for with `useWorkerFetch: false`.
|
||||
// The viewer runs no PDF scripts (quickjs) and uses no ICC color profiles (qcms), as the PDF Viewer plugin did.
|
||||
const assets = import.meta.glob<string>([
|
||||
"/node_modules/pdfjs-dist/cmaps/*.bcmap",
|
||||
"/node_modules/pdfjs-dist/standard_fonts/*.{pfb,ttf}",
|
||||
"/node_modules/pdfjs-dist/wasm/{jbig2,openjpeg}.wasm",
|
||||
], { query: "?url", import: "default", eager: true });
|
||||
|
||||
const folders: Record<string, string> = { cMapUrl: "cmaps", standardFontDataUrl: "standard_fonts", wasmUrl: "wasm" };
|
||||
|
||||
/** The app URL of a PDF.js data file, or undefined for an unknown kind or file. */
|
||||
export function assetUrl(kind: string, filename: string): string | undefined {
|
||||
const folder = folders[kind];
|
||||
if (!folder || !/^[\w.-]+$/.test(filename)) return undefined;
|
||||
return assets[`/node_modules/pdfjs-dist/${folder}/${filename}`];
|
||||
}
|
||||
|
||||
/** PDF.js asks the window for its data files (`useWorkerFetch: false`). This class reads them from the app. */
|
||||
class AppBinaryDataFactory {
|
||||
async fetch({ kind, filename }: { kind: string; filename: string }): Promise<Uint8Array> {
|
||||
const url = assetUrl(kind, filename);
|
||||
if (!url) throw new Error(`PDF.js has no data file ${filename}.`);
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) throw new Error(`PDF.js could not read ${filename}: ${response.status}.`);
|
||||
return new Uint8Array(await response.arrayBuffer());
|
||||
}
|
||||
}
|
||||
|
||||
export interface OpenPdf {
|
||||
/** Resolves with the document after the password, if the file needs one. */
|
||||
promise: Promise<PDFDocumentProxy>;
|
||||
/** Stop the load or release the document, and stop the worker. Later calls return the same promise. */
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the bytes of a PDF in a new worker. PDF.js calls `onPassword` for a protected file, with "incorrect" after a
|
||||
* wrong password. The viewer calls `answer` with the next password.
|
||||
*/
|
||||
export function openPdf(data: Uint8Array, onPassword: (reason: "needed" | "incorrect", answer: (password: string) => void) => void): OpenPdf {
|
||||
const port = new Worker(workerUrl, { type: "module", name: "PDF.js" });
|
||||
const worker = PDFWorker.create({ port });
|
||||
const task: PDFDocumentLoadingTask = getDocument({
|
||||
data, worker, useWorkerFetch: false, BinaryDataFactory: AppBinaryDataFactory,
|
||||
useSystemFonts: false, isImageDecoderSupported: false, enableXfa: false,
|
||||
});
|
||||
task.onPassword = (answer: (password: string) => void, reason: number) => {
|
||||
onPassword(reason === PasswordResponses.INCORRECT_PASSWORD ? "incorrect" : "needed", answer);
|
||||
};
|
||||
let closing: Promise<void> | undefined;
|
||||
return {
|
||||
promise: task.promise,
|
||||
close: () => closing ??= (async () => {
|
||||
try { await task.destroy(); }
|
||||
finally { worker.destroy(); port.terminate(); }
|
||||
})(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// 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<void>>();
|
||||
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<void> | 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()));
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// The limits of the PDF Viewer: page numbers, zoom, and the size of the page canvas.
|
||||
|
||||
export const MIN_ZOOM = 0.25;
|
||||
export const MAX_ZOOM = 4;
|
||||
/** Each zoom step multiplies or divides the zoom by this factor. */
|
||||
export const ZOOM_STEP = 1.25;
|
||||
/** A redraw after a resize waits until the size did not change for this time. */
|
||||
export const RESIZE_SETTLE_MS = 150;
|
||||
|
||||
/** A whole page number from 1 to `count`. A value that is not a number gives page 1. */
|
||||
export function pageNumber(value: number, count: number): number {
|
||||
return Math.max(1, Math.min(count, Number.isFinite(value) ? Math.trunc(value) : 1));
|
||||
}
|
||||
|
||||
/** A zoom factor from 0.25 to 4. A value that is not a finite number gives 1. */
|
||||
export function zoomLevel(value: number): number {
|
||||
return Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, Number.isFinite(value) ? value : 1));
|
||||
}
|
||||
|
||||
/** The next clockwise rotation in degrees: 0, 90, 180, or 270. */
|
||||
export function nextRotation(rotation: number): number {
|
||||
return (rotation + 90) % 360;
|
||||
}
|
||||
|
||||
/**
|
||||
* The pixel scale of the page canvas. It follows the device pixel ratio up to 2, and keeps each side at most
|
||||
* 8192 pixels and the area at most 16 million pixels, so a large page does not use too much memory.
|
||||
*/
|
||||
export function outputScale(width: number, height: number, deviceScale: number): number {
|
||||
return Math.min(deviceScale || 1, 2, 8192 / width, 8192 / height, Math.sqrt(16_000_000 / (width * height)));
|
||||
}
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
// The minified build of PDF.js has the same exports as the package entry.
|
||||
declare module "pdfjs-dist/build/pdf.min.mjs" {
|
||||
export * from "pdfjs-dist";
|
||||
}
|
||||
Reference in New Issue
Block a user