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:
Knotty Wyvern
2026-10-29 19:41:17 -07:00
parent 833f793244
commit e6deecc092
35 changed files with 2101 additions and 49 deletions
+229
View File
@@ -0,0 +1,229 @@
// The native PDF Viewer: the file tree marks PDF files without the module, the first PDF tab loads it, and each tab
// renders a page with selectable text, page controls, zoom, rotation, Page Up and Page Down, and Reload.
// It also checks two tabs, one worker for each open tab, a protected PDF, a damaged file, Off and On, no network request,
// no text read of a PDF, the owner ID of a tab transfer, a saved tab after a reload, both themes, and a narrow toolbar.
// It replaces tests/browser.mjs of the PDF Viewer plugin.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { passwordPdf, samplePdf } from "../../fixtures/pdf/fixtures.mjs";
await runSmoke("features/pdf", async ({ page }) => {
const output = await outputDir("features/pdf");
const origin = new URL(smokeUrl).origin;
const requests = [];
page.on("request", request => {
const url = request.url();
if (!url.startsWith(origin) && !/^(blob|data):/.test(url)) requests.push(url);
});
// Count the PDF.js workers that run (src/lib/features/pdf/engine.ts names them).
await page.addInitScript(() => {
const workers = new Set();
const NativeWorker = window.Worker;
window.Worker = class extends NativeWorker {
constructor(url, options) { super(url, options); if (options?.name === "PDF.js") workers.add(this); }
terminate() { workers.delete(this); super.terminate(); }
};
window.__PDF_WORKERS__ = workers;
});
await mockTauri(page, {
state: { sample: [...samplePdf()], password: [...passwordPdf()] },
commands: test => ({
...test.workspace({ root: "C:\\pdf-feature", files: { "Sample.pdf": "", "Other.PDF": "", "Broken.pdf": "", "Protected.pdf": "", "Slow.pdf": "", "note.md": "# Note\n" } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_menu_install: () => null,
"plugin:window|is_maximized": () => false,
"plugin:window|destroy": () => null,
workspace_read_bytes: async ({ rel }) => {
if (rel === "Slow.pdf") await new Promise(resolve => setTimeout(resolve, 400));
const bytes = rel === "Broken.pdf" ? [1, 2, 3] : rel === "Protected.pdf" ? test.state.password : test.state.sample;
return new Uint8Array(bytes).buffer;
},
}),
});
// `window.requestClose()` sends the native close request, so the workbench saves its document tabs (tabs/lifecycle does the same).
await page.addInitScript(() => {
const internals = window.__TAURI_INTERNALS__;
const { transformCallback, invoke } = internals;
const callbacks = new Map(), handlers = [];
internals.transformCallback = (callback, once) => { const id = transformCallback(callback, once); callbacks.set(id, callback); return id; };
internals.invoke = (command, args = {}) => {
if (command === "plugin:event|listen" && args.event === "tauri://close-requested") handlers.push(args.handler);
return invoke(command, args);
};
window.requestClose = async () => {
for (const id of handlers) await callbacks.get(id)?.({ event: "tauri://close-requested", id, payload: null });
};
});
await page.goto(smokeUrl);
const row = name => page.locator(`[data-tree-rel="${name}"]`);
await row("Sample.pdf").waitFor();
await row("Sample.pdf").locator(".document-icon").waitFor();
assert.equal(await row("Other.PDF").locator(".document-icon").count(), 1, "Any letter case of the extension is a PDF");
assert.equal(await row("note.md").locator(".document-icon").count(), 0);
const loaded = () => page.evaluate(() => performance.getEntriesByType("resource").some(entry => {
const { pathname } = new URL(entry.name);
return pathname === "/src/lib/features/pdf/index.ts" || pathname.includes("pdfjs-dist");
}));
assert.equal(await loaded(), false, "The file tree marks PDF files without the module or PDF.js");
const workers = () => page.evaluate(() => window.__PDF_WORKERS__.size);
const active = page.locator(".plugin-editor-pane:visible");
const status = active.locator(".pdf-viewer .status");
const rendered = text => status.filter({ hasText: new RegExp(`^${text}$`) }).waitFor();
const button = name => active.getByRole("button", { name, exact: true });
const tab = name => page.getByRole("tab", { name, exact: true });
await row("Sample.pdf").click();
await rendered("Page 1 of 2");
assert.equal(await loaded(), true, "The first PDF tab loads the module");
await active.getByRole("img", { name: "PDF page 1", exact: true }).waitFor();
assert.match(await active.locator(".textLayer").innerText(), /Page one text selection/);
assert.ok(await active.locator("canvas").evaluate(canvas => {
const data = canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height).data;
let colored = 0;
for (let index = 0; index < data.length; index += 4) if (data[index] < 200 && data[index + 2] > 100) colored++;
return colored > 1000;
}), "The page shows its blue rectangle");
assert.equal(await active.getByRole("spinbutton", { name: "Page number", exact: true }).inputValue(), "1");
assert.equal(await button("Fit width").getAttribute("aria-pressed"), "true");
assert.equal(await button("Previous page").isDisabled(), true);
assert.equal(await workers(), 1);
// Both themes. The page stays white paper.
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); }, theme);
await page.waitForTimeout(100);
await page.screenshot({ path: path.join(output, `viewer-${theme}.png`) });
}
// The tooltip of an icon button shows on keyboard focus.
await button("Rotate clockwise").focus();
await page.getByRole("tooltip", { name: "Rotate clockwise" }).waitFor();
await active.locator(".toolbar").screenshot({ path: path.join(output, "toolbar-focus.png") });
// A narrow window: the toolbar wraps and keeps every control inside the pane.
await page.setViewportSize({ width: 900, height: 720 });
await rendered("Page 1 of 2");
const toolbar = active.locator(".toolbar");
assert.equal(await toolbar.evaluate(node => node.scrollWidth > node.clientWidth), false, "No horizontal scroll in the toolbar");
const box = await toolbar.boundingBox();
for (const control of await toolbar.locator("button, input").all()) {
const item = await control.boundingBox();
assert.ok(item.x >= box.x - 1 && item.x + item.width <= box.x + box.width + 1, "Each control stays inside the toolbar");
}
await page.screenshot({ path: path.join(output, "viewer-900.png") });
await page.setViewportSize({ width: 1440, height: 1000 });
// Pages, zoom, rotation, and the keyboard.
await button("Next page").click();
await rendered("Page 2 of 2");
await active.getByRole("img", { name: "PDF page 2", exact: true }).waitFor();
assert.equal(await button("Next page").isDisabled(), true);
const zoomText = () => active.locator(".zoom").innerText();
const before = await zoomText();
await button("Zoom in").click();
await rendered("Page 2 of 2");
assert.notEqual(await zoomText(), before);
assert.equal(await button("Fit width").getAttribute("aria-pressed"), "false");
await button("Rotate clockwise").click();
await rendered("Page 2 of 2");
assert.ok(await active.locator("canvas").evaluate(canvas => canvas.width > canvas.height), "A rotated page is wider than high");
await active.locator(".scroll").focus();
await page.keyboard.press("PageUp");
await rendered("Page 1 of 2");
await page.keyboard.press("PageDown");
await rendered("Page 2 of 2");
const input = active.getByRole("spinbutton", { name: "Page number", exact: true });
await input.fill("1");
await input.press("Enter");
await rendered("Page 1 of 2");
await input.fill("99");
await input.press("Enter");
await rendered("Page 2 of 2");
assert.equal(await input.inputValue(), "2", "A page number above the count goes to the last page");
// A second tab, one tab for each file, and one worker for each open tab.
await row("Other.PDF").click();
await rendered("Page 1 of 2");
assert.equal(await workers(), 2);
await row("Other.PDF").click();
assert.equal(await tab("Other").count(), 1, "A second open selects the same tab");
await page.getByRole("button", { name: "Close Other", exact: true }).click();
await tab("Other").waitFor({ state: "detached" });
await page.waitForFunction(() => window.__PDF_WORKERS__.size === 1);
// A tab that closes before its file arrives starts no worker.
await row("Slow.pdf").click();
await tab("Slow").waitFor();
await page.getByRole("button", { name: "Close Slow", exact: true }).click();
await page.waitForTimeout(600);
assert.equal(await workers(), 1);
// A protected PDF.
await row("Protected.pdf").click();
const password = active.getByLabel("PDF password");
await password.waitFor();
await status.filter({ hasText: "This PDF needs a password." }).waitFor();
assert.equal(await password.evaluate(node => node === document.activeElement), true, "The password field takes focus");
await password.fill("incorrect");
await active.getByRole("button", { name: "Unlock", exact: true }).click();
await status.filter({ hasText: "Incorrect password. Try again." }).waitFor();
await page.screenshot({ path: path.join(output, "password.png") });
await password.fill("reader");
await password.press("Enter");
await rendered("Page 1 of 2");
await page.getByRole("button", { name: "Close Protected", exact: true }).click();
await page.waitForFunction(() => window.__PDF_WORKERS__.size === 1);
// A tab that closes while it asks for the password stops its worker.
await row("Protected.pdf").click();
await active.getByLabel("PDF password").waitFor();
await page.getByRole("button", { name: "Close Protected", exact: true }).click();
await page.waitForFunction(() => window.__PDF_WORKERS__.size === 1);
// Reload keeps the page and replaces the worker.
await tab("Sample").click();
await rendered("Page 2 of 2");
await button("Reload PDF").click();
await rendered("Page 2 of 2");
assert.equal(await workers(), 1);
// A damaged file shows an error, and Reload stays available.
await row("Broken.pdf").click();
await active.getByRole("alert").filter({ hasText: "Cannot display this PDF." }).waitFor();
assert.equal(await button("Reload PDF").isDisabled(), false);
assert.equal(await button("Next page").isDisabled(), true);
await page.screenshot({ path: path.join(output, "damaged.png") });
// Off closes the PDF tabs, stops every worker, and removes the marks. On opens PDF files again.
const switches = await page.evaluate(() => window.__TEST__.settings("features"));
await page.evaluate(value => window.__TEST__.writeSettings("features", value), { ...switches, pdf: false });
await active.locator(".pdf-viewer").waitFor({ state: "detached" });
await page.waitForFunction(() => window.__PDF_WORKERS__.size === 0);
assert.equal(await page.locator(".pdf-viewer").count(), 0);
assert.equal(await tab("Sample").count(), 0);
await row("Sample.pdf").locator(".document-icon").waitFor({ state: "detached" });
await page.evaluate(value => window.__TEST__.writeSettings("features", value), { ...switches, pdf: true });
await row("Sample.pdf").locator(".document-icon").waitFor();
await row("Sample.pdf").click();
await rendered("Page 1 of 2");
assert.equal(await workers(), 1);
const textReads = await page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "workspace_read" && /\.pdf$/i.test(call.args.rel)));
assert.deepEqual(textReads, [], "A PDF is never read as text");
// A tab transfer names the old package and the document type. A reload reopens the saved PDF tab from its path.
const transfer = await page.evaluate(async () => {
const external = await import("/src/lib/plugins/external.ts");
let editors = [];
external.pluginEditors.subscribe(value => { editors = value; })();
const { owner, id, document } = external.pluginTabState(editors.find(view => view.document));
return { owner, id, document };
});
assert.deepEqual(transfer, { owner: "runestone.pdf-viewer", id: "pdf", document: { id: "Sample.pdf", path: "Sample.pdf" } });
await page.evaluate(() => window.requestClose());
await page.reload();
await rendered("Page 1 of 2");
assert.equal(await tab("Sample").count(), 1);
assert.deepEqual(requests, [], "No network request leaves the app");
console.log("PASS: PDF Viewer loads at first need, renders text and pages, zooms, rotates, reloads, unlocks, reports a damaged file, keeps one worker per tab, restores its tab, and Off removes it");
}, { timeout: 60000, viewport: { width: 1440, height: 1000 } });