The PDF tab shows all pages in one column. The wheel, Page Up, and Page Down scroll. They do not change the page, and they draw nothing again at the start or the end of the document. - The zoom percent is a field. A typed percent sets the zoom. Ctrl and the wheel also change the zoom. - The toolbar, the status line, and the password form are opaque, so a background image does not hide them. - Ctrl+Tab and Ctrl+Shift+Tab give keyboard focus to the new plugin tab. Cards: 9b7b246e, 59ff5dc1, 2e425cbc, 7bd092d2, 2142ca04, c0900ae8.
318 lines
17 KiB
JavaScript
318 lines
17 KiB
JavaScript
// The native PDF Viewer: the file tree marks PDF files without the module, the first PDF tab loads it, and each tab
|
|
// renders its pages in one column with selectable text, page controls, zoom, a typed zoom, rotation, scrolling by wheel and
|
|
// keyboard, and Reload. It also checks the opaque toolbar and the focus after Ctrl+Tab.
|
|
// 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();
|
|
const sheet = number => active.locator(`.sheet[data-page="${number}"]`);
|
|
const scroll = active.locator(".scroll");
|
|
const scrollTop = () => scroll.evaluate(node => node.scrollTop);
|
|
await sheet(1).locator(".textLayer span").first().waitFor();
|
|
assert.match(await sheet(1).locator(".textLayer").innerText(), /Page one text selection/);
|
|
assert.equal(await active.locator(".sheet").count(), 2, "Each page has a sheet in the column");
|
|
assert.ok(await sheet(1).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);
|
|
// The toolbar and the status line are opaque, so a background image does not show through them.
|
|
for (const selector of [".toolbar", ".status"]) {
|
|
assert.match(await active.locator(selector).evaluate(node => getComputedStyle(node).backgroundColor), /^rgb\(/, `${selector} has an opaque fill`);
|
|
}
|
|
|
|
// 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 zoomField = active.getByRole("textbox", { name: "Zoom percent", exact: true });
|
|
const zoomText = () => zoomField.inputValue();
|
|
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 sheet(2).locator("canvas").evaluate(canvas => canvas.width > canvas.height), "A rotated page is wider than high");
|
|
for (let turn = 0; turn < 3; turn++) await button("Rotate clockwise").click();
|
|
// A typed zoom.
|
|
await zoomField.fill("137");
|
|
await zoomField.press("Enter");
|
|
assert.equal(await zoomText(), "137%");
|
|
await zoomField.fill("text");
|
|
await zoomField.press("Enter");
|
|
assert.equal(await zoomText(), "137%", "Text that is not a number keeps the zoom");
|
|
await zoomField.fill("9000");
|
|
await zoomField.press("Enter");
|
|
assert.equal(await zoomText(), "400%", "A typed zoom stays in the limits");
|
|
const unfitted = button("Fit width").and(page.locator('[aria-pressed="false"]'));
|
|
await unfitted.waitFor();
|
|
const fitted = button("Fit width").and(page.locator('[aria-pressed="true"]'));
|
|
const input = active.getByRole("spinbutton", { name: "Page number", exact: true });
|
|
await input.fill("1");
|
|
await input.press("Enter");
|
|
await rendered("Page 1 of 2");
|
|
// Page Down and Page Up scroll. At 400%, a page is higher than the tab. They do not jump to the next page, and they do not draw a page again at the ends.
|
|
assert.equal(await scrollTop(), 0);
|
|
await scroll.focus();
|
|
const keepCanvas = number => sheet(number).locator("canvas").evaluate(canvas => { window.__PDF_CANVAS__ = canvas; });
|
|
const sameCanvas = number => sheet(number).locator("canvas").evaluate(canvas => window.__PDF_CANVAS__ === canvas);
|
|
await keepCanvas(1);
|
|
await page.keyboard.press("PageUp");
|
|
await page.waitForTimeout(300);
|
|
assert.equal(await scrollTop(), 0);
|
|
assert.equal(await sameCanvas(1), true, "Page Up at the start does not draw the page again");
|
|
await rendered("Page 1 of 2");
|
|
await page.keyboard.press("PageDown");
|
|
await page.waitForFunction(() => document.activeElement.scrollTop > 0);
|
|
await page.waitForTimeout(400);
|
|
assert.ok(await scrollTop() < await sheet(2).evaluate(node => node.offsetTop - node.previousElementSibling.offsetTop), "Page Down scrolls less than one page");
|
|
await rendered("Page 1 of 2");
|
|
assert.equal(await input.inputValue(), "1");
|
|
await page.keyboard.press("End");
|
|
await rendered("Page 2 of 2");
|
|
assert.equal(await input.inputValue(), "2", "The page field follows the scroll position");
|
|
await page.waitForTimeout(400);
|
|
const end = await scrollTop();
|
|
await keepCanvas(2);
|
|
await page.keyboard.press("PageDown");
|
|
await page.waitForTimeout(300);
|
|
assert.equal(await scrollTop(), end);
|
|
assert.equal(await sameCanvas(2), true, "Page Down at the end does not draw the page again");
|
|
await rendered("Page 2 of 2");
|
|
// The wheel shows the other pages.
|
|
await page.keyboard.press("Home");
|
|
await rendered("Page 1 of 2");
|
|
await scroll.hover();
|
|
await page.mouse.wheel(0, 5000);
|
|
await rendered("Page 2 of 2");
|
|
await active.getByRole("img", { name: "PDF page 2", exact: true }).waitFor();
|
|
// Ctrl and the wheel change the zoom.
|
|
await button("Fit width").click();
|
|
await fitted.waitFor();
|
|
await scroll.hover();
|
|
await page.keyboard.down("Control");
|
|
await page.mouse.wheel(0, -100);
|
|
await page.keyboard.up("Control");
|
|
await unfitted.waitFor();
|
|
await button("Fit width").click();
|
|
await rendered("Page 2 of 2");
|
|
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");
|
|
// The tabs are New tab, Sample, and Other. Ctrl+Tab and Ctrl+Shift+Tab give the keyboard to the page area of the PDF tab.
|
|
const focused = () => page.waitForFunction(() => document.activeElement?.matches(".pdf-viewer .scroll") && document.activeElement.offsetParent !== null);
|
|
await page.keyboard.press("Control+Shift+Tab");
|
|
await focused();
|
|
assert.equal(await tab("Sample").getAttribute("aria-selected"), "true");
|
|
await input.fill("1");
|
|
await input.press("Enter");
|
|
await rendered("Page 1 of 2");
|
|
await page.keyboard.press("Control+Tab");
|
|
await focused();
|
|
await page.keyboard.press("Control+Shift+Tab");
|
|
await focused();
|
|
assert.equal(await tab("Sample").getAttribute("aria-selected"), "true");
|
|
await page.keyboard.press("PageDown");
|
|
await page.waitForFunction(() => document.activeElement.scrollTop > 0);
|
|
await page.keyboard.press("Control+Tab");
|
|
await rendered("Page 1 of 2");
|
|
assert.equal(await tab("Other").getAttribute("aria-selected"), "true");
|
|
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 input.fill("2");
|
|
await input.press("Enter");
|
|
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, scrolls, 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 } });
|