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
+53
View File
@@ -0,0 +1,53 @@
// The PDF fixtures of the PDF Viewer smoke test. They come from the PDF Viewer plugin (tests/fixture.mjs and tests/fixtures/password.pdf).
// `samplePdf` makes two pages with text, a filled rectangle, and a shading. `passwordPdf` is a protected copy: its password is "reader".
/** Two US Letter pages with selectable text. The second page has a shading with a PostScript function. */
export function samplePdf() {
const objects = [
'<< /Type /Catalog /Pages 2 0 R >>',
'<< /Type /Pages /Kids [3 0 R 5 0 R] /Count 2 >>',
'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> /Contents 4 0 R >>',
stream('q 0.15 0.35 0.7 rg 40 620 532 110 re f Q\nBT /F1 24 Tf 50 760 Td (RuneStone PDF test) Tj 0 -180 Td (Page one text selection) Tj ET'),
'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> /Shading << /Sh1 8 0 R >> >> /Contents 6 0 R >>',
stream('BT /F1 24 Tf 50 700 Td (Second PDF page) Tj ET\nq 50 100 512 200 re W n /Sh1 sh Q'),
'<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>',
// A PostScript (type 4) function. PDF.js compiles it to WebAssembly, so the CSP test covers 'wasm-unsafe-eval'.
'<< /ShadingType 2 /ColorSpace /DeviceRGB /Coords [50 0 562 0] /Function 9 0 R /Extend [true true] >>',
stream('{dup dup 0.5 mul exch 1 exch sub}', '/FunctionType 4 /Domain [0 1] /Range [0 1 0 1 0 1] '),
];
let source = '%PDF-1.7\n%\xff\xfe\xfd\xfc\n';
const offsets = [0];
for (const [index, object] of objects.entries()) {
offsets.push(Buffer.byteLength(source, 'latin1'));
source += `${index + 1} 0 obj\n${object}\nendobj\n`;
}
const xref = Buffer.byteLength(source, 'latin1');
source += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;
for (const offset of offsets.slice(1)) source += `${String(offset).padStart(10, '0')} 00000 n \n`;
source += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
return Buffer.from(source, 'latin1');
}
function stream(value, entries = '') { return `<< ${entries}/Length ${Buffer.byteLength(value)} >>\nstream\n${value}\nendstream`; }
/** A PDF that needs the password "reader". It is in Base64, so Git keeps its bytes. */
export function passwordPdf() {
return Buffer.from([
"JVBERi0xLjMKJeLjz9MKMSAwIG9iago8PAovVHlwZSAvQ2F0YWxvZwovUGFnZXMgMiAwIFIKPj4KZW5kb2JqCjIgMCBvYmoKPDwK",
"L1R5cGUgL1BhZ2VzCi9LaWRzIFsgMyAwIFIgNiAwIFIgXQovQ291bnQgMgo+PgplbmRvYmoKMyAwIG9iago8PAovVHlwZSAvUGFn",
"ZQovUGFyZW50IDIgMCBSCi9NZWRpYUJveCBbIDAgMCA2MTIgNzkyIF0KL1Jlc291cmNlcyA8PAovRm9udCA8PAovRjEgNCAwIFIK",
"Pj4KPj4KL0NvbnRlbnRzIDUgMCBSCj4+CmVuZG9iago0IDAgb2JqCjw8Ci9UeXBlIC9Gb250Ci9TdWJ0eXBlIC9UeXBlMQovQmFz",
"ZUZvbnQgL0hlbHZldGljYQo+PgplbmRvYmoKNSAwIG9iago8PAovTGVuZ3RoIDEyOQo+PgpzdHJlYW0KiVMq6xPVisMuZWp1BS9z",
"5/joxhOdf21xdCOrAUByO06B9ClJy0wK7H+l7flob+B4XwQ+KKd3qeABIfk8uLLWUfiax7FVaNp2eGUjy0N/ewS98OF0jZT+LA8R",
"0N0M4BiPmJfxIn77QBqq4SYw+MDG4ojtscK+qps1QL9MJXOnpwSBCmVuZHN0cmVhbQplbmRvYmoKNiAwIG9iago8PAovVHlwZSAv",
"UGFnZQovUGFyZW50IDIgMCBSCi9NZWRpYUJveCBbIDAgMCA2MTIgNzkyIF0KL1Jlc291cmNlcyA8PAovRm9udCA8PAovRjEgNCAw",
"IFIKPj4KPj4KL0NvbnRlbnRzIDcgMCBSCj4+CmVuZG9iago3IDAgb2JqCjw8Ci9MZW5ndGggNDYKPj4Kc3RyZWFtCiy55bSCEhQT",
"SUrkrVamBjYoo/MXPkuAMQr0FdQ5M5petMLGUzj2N+Fjt41Hj3gKZW5kc3RyZWFtCmVuZG9iago4IDAgb2JqCjw8Ci9WIDIKL1Ig",
"MwovTGVuZ3RoIDEyOAovUCA0Mjk0OTY3MjkyCi9GaWx0ZXIgL1N0YW5kYXJkCi9PIDxkOTJmZjZmZjA5YTk0ZDZjZGEwMjQzNTUw",
"YmIzZDlmMmJhYTA1NjM3NmQ4MmFkZTdhZTU3NGY2MTIyZWQyOTZmPgovVSA8YTAwYzdlNDVmMGY1MTgyOTIyOGE3ZjU2NGYxMGM1",
"MjAyOGJmNGU1ZTRlNzU4YTQxNjQwMDRlNTZmZmZhMDEwOD4KPj4KZW5kb2JqCnhyZWYKMCA5CjAwMDAwMDAwMDAgNjU1MzUgZiAK",
"MDAwMDAwMDAxNSAwMDAwMCBuIAowMDAwMDAwMDY0IDAwMDAwIG4gCjAwMDAwMDAxMjkgMDAwMDAgbiAKMDAwMDAwMDI1NyAwMDAw",
"MCBuIAowMDAwMDAwMzI3IDAwMDAwIG4gCjAwMDAwMDA1MDcgMDAwMDAgbiAKMDAwMDAwMDYzNSAwMDAwMCBuIAowMDAwMDAwNzMx",
"IDAwMDAwIG4gCnRyYWlsZXIKPDwKL1NpemUgOQovUm9vdCAxIDAgUgovSUQgWyA8NjI2NjY1NjIzNzY0MzUzOTM2Mzk2MjYxMzQ2",
"NTMyNjYzNDMyMzQzMjMyMzI2NjMyNjEzOTY0MzkzMjM3NjI2ND4gPDYyNjY2NTYyMzc2NDM1MzkzNjM5NjI2MTM0NjUzMjY2MzQz",
"MjM0MzIzMjMyNjYzMjYxMzk2NDM5MzIzNzYyNjQ+IF0KL0VuY3J5cHQgOCAwIFIKPj4Kc3RhcnR4cmVmCjk0NgolJUVPRgo=",
].join(""), "base64");
}
+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 } });
+2 -2
View File
@@ -20,7 +20,7 @@ await runSmoke("features/settings", async ({ browser }) => {
const sourceControl = main.locator(".header-left").getByRole("button", { name: "Source control", exact: true });
await sourceControl.waitFor();
// Without an old package, the migration stores the default of each feature.
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: true, background: true, terminal: true });
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: true, background: true, terminal: true, pdf: true });
const settings = await openPage(context, { timeout: 10000 });
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
@@ -33,7 +33,7 @@ await runSmoke("features/settings", async ({ browser }) => {
await git.click();
await sourceControl.waitFor({ state: "detached" });
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: false, background: true, terminal: true });
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: false, background: true, terminal: true, pdf: true });
assert.equal(await settings.getByRole("status").innerText(), "Changes saved.");
await git.focus();
await settings.keyboard.press("Space");
+9 -9
View File
@@ -33,9 +33,9 @@ test("switches keep known booleans only, and missing keys take the default", ()
assert.deepEqual(storedSwitches({ git: false, terminal: "no", csv: true, other: "yes" }), { git: false });
assert.deepEqual(storedSwitches(null), {});
assert.deepEqual(storedSwitches(["git"]), {});
assert.deepEqual(switchesFrom(undefined), { git: true, background: true, terminal: true });
assert.deepEqual(switchesFrom({ git: false, background: false, terminal: false }), { git: false, background: false, terminal: false });
assert.deepEqual(switchesFrom({ git: "false" }), { git: true, background: true, terminal: true });
assert.deepEqual(switchesFrom(undefined), { git: true, background: true, terminal: true, pdf: true });
assert.deepEqual(switchesFrom({ git: false, background: false, terminal: false, pdf: false }), { git: false, background: false, terminal: false, pdf: false });
assert.deepEqual(switchesFrom({ git: "false" }), { git: true, background: true, terminal: true, pdf: true });
});
test("an installed package gives its state, and without a package the default applies", () => {
@@ -71,10 +71,10 @@ test("the migration asks only for features without a switch, and keeps other key
write: async (value: unknown) => { writes.push(value); },
legacy: async (ids: string[]) => { asked.push(ids); return packages; },
});
assert.deepEqual(await migrateFeatures(host({ future: 1, background: false, terminal: true }, [{ id: "runestone.git", installed: true, enabled: false, settings: null }]), presentBackground(), presentTerminal()), ["git"]);
assert.deepEqual(await migrateFeatures(host({ future: 1, background: false, terminal: true, pdf: true }, [{ id: "runestone.git", installed: true, enabled: false, settings: null }]), presentBackground(), presentTerminal()), ["git"]);
assert.deepEqual(asked, [["runestone.git"]]);
assert.deepEqual(writes, [{ future: 1, background: false, terminal: true, git: false }]);
assert.deepEqual(await migrateFeatures(host({ git: true, background: true, terminal: true }, []), presentBackground(), presentTerminal()), []);
assert.deepEqual(writes, [{ future: 1, background: false, terminal: true, pdf: true, git: false }]);
assert.deepEqual(await migrateFeatures(host({ git: true, background: true, terminal: true, pdf: true }, []), presentBackground(), presentTerminal()), []);
assert.equal(asked.length, 1, "A stored switch needs no package read.");
assert.equal(writes.length, 1);
});
@@ -84,7 +84,7 @@ test("a missing background section asks for the slideshow package and makes the
const switches: unknown[] = [];
const sections: BackgroundSettings[] = [];
const background: BackgroundMigrationHost = { missing: () => true, hasImage: () => true, migrateFolder: async () => true, write: async value => { sections.push(value); } };
const host = { read: () => ({ git: true, background: false, terminal: true }), write: async (value: unknown) => { switches.push(value); }, legacy: async (ids: string[]) => { asked.push(ids); return []; } };
const host = { read: () => ({ git: true, background: false, terminal: true, pdf: true }), write: async (value: unknown) => { switches.push(value); }, legacy: async (ids: string[]) => { asked.push(ids); return []; } };
assert.deepEqual(await migrateFeatures(host, background, presentTerminal()), []);
assert.deepEqual(asked, [["runestone.bg-slideshow"]]);
assert.deepEqual(switches, [], "Stored switches stay.");
@@ -93,8 +93,8 @@ test("a missing background section asks for the slideshow package and makes the
// Both migrations together ask once for both packages.
asked.length = 0;
await migrateFeatures({ ...host, read: () => undefined }, background, presentTerminal());
assert.deepEqual(asked, [["runestone.git", "runestone.bg-slideshow", "runestone.terminal"]]);
assert.deepEqual(switches, [{ git: true, background: true, terminal: true }]);
assert.deepEqual(asked, [["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.pdf-viewer"]]);
assert.deepEqual(switches, [{ git: true, background: true, terminal: true, pdf: true }]);
});
test("a failed package read writes nothing, so the next start tries again", async () => {
+104
View File
@@ -0,0 +1,104 @@
// The PDF Viewer feature: the page and zoom limits, the document identification of the catalog, and the document
// mount of a feature session. The model tests come from the PDF Viewer plugin (tests/model.test.ts).
import { test } from "node:test";
import assert from "node:assert/strict";
import { featureEntry, featureOfOwner } from "../../../src/lib/features/catalog.ts";
import { identifyPdf } from "../../../src/lib/features/pdfDocument.ts";
import { nextRotation, outputScale, pageNumber, zoomLevel } from "../../../src/lib/features/pdf/model.ts";
import { FeatureSession } from "../../../src/lib/features/session.ts";
import type { FeatureContext, FeatureInstance } from "../../../src/lib/features/types.ts";
import type { PluginDocumentContext } from "../../../src/lib/plugins/sdk.ts";
test("PDF identification handles uppercase extensions and distinct paths", () => {
assert.deepEqual(identifyPdf("notes\\Report.PDF"), { id: "notes/Report.PDF" });
assert.notDeepEqual(identifyPdf("a/report.pdf"), identifyPdf("b/report.pdf"));
for (const path of ["report.pdf.md", "pdf", "report.png"]) assert.equal(identifyPdf(path), null);
});
test("page and zoom inputs stay within supported bounds", () => {
assert.equal(pageNumber(NaN, 20), 1);
assert.equal(pageNumber(-3, 20), 1);
assert.equal(pageNumber(99, 20), 20);
assert.equal(pageNumber(2.8, 20), 2);
assert.equal(zoomLevel(Infinity), 1);
assert.equal(zoomLevel(0), .25);
assert.equal(zoomLevel(10), 4);
assert.deepEqual([0, 90, 180, 270].map(nextRotation), [90, 180, 270, 0]);
});
test("large PDF pages respect canvas dimension and memory limits", () => {
for (const [width, height] of [[612, 792], [20000, 500], [20000, 20000]]) {
const scale = outputScale(width, height, 3);
assert.ok(width * scale <= 8192);
assert.ok(height * scale <= 8192);
assert.ok(width * height * scale * scale <= 16_000_001);
}
});
test("the catalog gives PDF Viewer the old package ID and one binary document type", () => {
const pdf = featureEntry("pdf");
assert.equal(pdf.owner, "runestone.pdf-viewer");
assert.equal(featureOfOwner("runestone.pdf-viewer")?.id, "pdf");
assert.equal(pdf.defaultOn, true);
assert.equal(pdf.followsPackage, true);
assert.deepEqual(pdf.views, []);
assert.deepEqual(pdf.commands, []);
assert.deepEqual(pdf.documentTypes.map(type => [type.id, type.icon, type.content, [...type.extensions], type.title()]), [["pdf", "file", "binary", ["pdf"], "PDF document"]]);
assert.deepEqual(featureEntry("git").documentTypes, []);
});
function fakeContext(): FeatureContext {
return { openView: () => {}, openFile: async () => {}, onWorkspaceChange: () => () => {} };
}
test("a feature session identifies PDF files without loading the feature", () => {
let loads = 0;
const session = new FeatureSession(featureEntry("pdf"), fakeContext(), async () => { loads++; throw new Error("not loaded"); });
const type = session.documentTypes.get("pdf");
assert.ok(type);
assert.equal(type.title, "PDF document");
assert.equal(type.content, "binary");
assert.deepEqual(type.extensions, ["pdf"]);
assert.deepEqual(type.identify("docs/Guide.PDF", ""), { id: "docs/Guide.PDF" });
assert.equal(type.identify("docs/guide.md", ""), null);
assert.equal(loads, 0, "Identification does not load the feature.");
assert.equal(session.started, false);
});
test("the first document mount starts one instance, each tab gets the document, and stop disposes it", async () => {
const events: string[] = [];
let starts = 0;
const instance: FeatureInstance = {
mount: () => { throw new Error("no views"); },
mountDocument: (type, element, document) => {
events.push(`mount ${type} ${document.path}`);
element.textContent = document.id;
return () => { events.push(`unmount ${document.path}`); };
},
dispose: () => { events.push("dispose"); },
};
const session = new FeatureSession(featureEntry("pdf"), fakeContext(), async () => ({ start: () => { starts++; return instance; } }));
const element = () => ({ textContent: "", replaceChildren(this: { textContent: string }) { this.textContent = ""; } }) as unknown as HTMLElement;
const first = element(), second = element();
const a: PluginDocumentContext = { id: "a.pdf", path: "a.pdf" };
const b: PluginDocumentContext = { id: "b/B.PDF", path: "b/B.PDF" };
const closeA = await session.mount("pdf", first, a);
const closeB = await session.mount("pdf", second, b);
assert.equal(starts, 1, "Two tabs share one instance.");
assert.equal(first.textContent, "a.pdf");
await closeA();
assert.equal(first.textContent, "", "The host empties the element after the dispose.");
await assert.rejects(session.mount("missing", element(), a), /This view is unavailable/);
await assert.rejects(session.mount("pdf", element()), /This view is unavailable/, "Without a document, the ID names a view.");
await closeB();
await session.stop();
assert.deepEqual(events, ["mount pdf a.pdf", "mount pdf b/B.PDF", "unmount a.pdf", "unmount b/B.PDF", "dispose"]);
await assert.rejects(session.mount("pdf", element(), a), /This feature is off/);
});
test("a feature without a document mount refuses a document", async () => {
const instance: FeatureInstance = { mount: () => () => {}, dispose() {} };
const session = new FeatureSession(featureEntry("pdf"), fakeContext(), async () => ({ start: () => instance }));
await assert.rejects(session.mount("pdf", { replaceChildren() {} } as unknown as HTMLElement, { id: "a.pdf", path: "a.pdf" }), /This view is unavailable/);
await session.stop();
});
+2 -2
View File
@@ -261,9 +261,9 @@ test("the feature migration copies the terminal settings also when the package r
test("the terminal switch follows the enabled state of an installed Terminal plugin", async () => {
const writes: unknown[] = [];
const host = { read: () => ({ git: true, background: true }), write: async (value: unknown) => { writes.push(value); },
const host = { read: () => ({ git: true, background: true, pdf: true }), write: async (value: unknown) => { writes.push(value); },
legacy: async (ids: string[]) => ids.map(id => ({ id, installed: true, enabled: false, settings: null })) };
const background = { missing: () => false, hasImage: () => false, migrateFolder: async () => false, write: async () => {} };
assert.deepEqual(await migrateFeatures(host, background, terminalHost(false, null)), ["terminal"]);
assert.deepEqual(writes, [{ git: true, background: true, terminal: false }]);
assert.deepEqual(writes, [{ git: true, background: true, pdf: true, terminal: false }]);
});