Show PDF pages in one column that scrolls
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.
This commit is contained in:
@@ -1139,3 +1139,19 @@ Update 2026-10-29: The native Terminal feature keeps the 65% cap on `--rs-select
|
||||
- Evidence: `tests/smoke/layout/titleBar.smoke.mjs` checks a drag area that fills the header with one tab, and a drag area of 48 pixels at the end of the header when 11 tabs scroll.
|
||||
- Replaces / replaced by: The drag area rule of [UI-050](#ui-050--global-actions-tabs-and-platform-title-bars).
|
||||
- Limits: Browser checks use desktop service mocks. The native window drag on the smaller area needs native acceptance.
|
||||
|
||||
### UI-063 — PDF pages in one column
|
||||
|
||||
- Type: Rule change
|
||||
- Date: 2026-11-09
|
||||
- Status: Implemented for user review
|
||||
- Decision source: Cards 9b7b246e, 59ff5dc1, 2e425cbc, 7bd092d2, 2142ca04, and c0900ae8 report a PDF toolbar that a background image hides, no custom zoom, no scroll between pages, lost focus after Ctrl+Tab, and Page Up and Page Down that change pages.
|
||||
- Previous rule: [UI-059](#ui-059--the-pdf-toolbar-on-shared-controls). The tab showed one page at a time. Page Up and Page Down changed the page. The zoom percent was text. The tab had no surface of its own, so a background image showed through the toolbar and the status line.
|
||||
- New rule: The tab shows all pages in one column that scrolls. The wheel, the scroll bar, Page Up, Page Down, Home, End, and the arrow keys scroll. The page field shows the page that fills most of the tab. **Previous page**, **Next page**, and the page field show the top of a page. The zoom percent is a field: a typed percent and Enter set the zoom from 25% to 400%. Ctrl and the wheel also change the zoom. The toolbar, the status line, and the password form are opaque (`--rs-bg-elevated`) with and without a background image. The page area uses the editor surface (`--rs-workarea-editor-bg`). Ctrl+Tab and Ctrl+Shift+Tab give keyboard focus to the new plugin tab.
|
||||
- Reason: A reader scrolls through a document. A page change on Page Down hides the rest of a page that is higher than the tab. A toolbar must stay readable over each image, as headers do.
|
||||
- Scope: The PDF tab. The focus rule applies to each plugin tab: the host focuses the element that the view marks with `data-tab-focus`, or the view.
|
||||
- Shared implementation: `src/lib/features/pdf/PdfViewer.svelte`, `src/lib/features/pdf/model.ts`, `src/lib/plugins/PluginEditor.svelte` (`focus`), and the tab commands in `src/lib/layout/Workbench.svelte`.
|
||||
- Exceptions: A click on a tab or an arrow key in the tab bar keeps the focus in the tab bar.
|
||||
- Evidence: `tests/smoke/features/pdf.smoke.mjs` and `tests/unit/features/pdf.spec.ts`.
|
||||
- Replaces / replaced by: The one-page rule and the zoom text of [UI-059](#ui-059--the-pdf-toolbar-on-shared-controls).
|
||||
- Limits: Only the pages near the visible area have a drawing. Until the viewer reads the size of a page, the page has the size of the first page. Browser checks use desktop service mocks. Native desktop acceptance remains open.
|
||||
|
||||
+6
-4
@@ -136,15 +136,17 @@ Select a PDF file in the file tree. It opens in its own tab. The file tree marks
|
||||
|
||||
| Action | How |
|
||||
| --- | --- |
|
||||
| Change the page | Select **Previous page** or **Next page**. Or type a number in the page field and press Enter. With the page area focused, press Page Up or Page Down. |
|
||||
| Zoom | Select **Zoom in** or **Zoom out**, from 25% to 400%. **Fit width** fits the page to the tab again. |
|
||||
| Rotate | Select **Rotate clockwise**. Each click turns the page by 90 degrees. |
|
||||
| Scroll through the pages | Use the wheel or the scroll bar. With the page area focused, use Page Up, Page Down, Home, End, and the arrow keys. |
|
||||
| Go to a page | Select **Previous page** or **Next page**. Or type a number in the page field and press Enter. |
|
||||
| Zoom | Select **Zoom in** or **Zoom out**. Or type a percent in the zoom field and press Enter. Or hold Ctrl and turn the wheel. The zoom is from 25% to 400%. **Fit width** fits the pages to the tab again. |
|
||||
| Rotate | Select **Rotate clockwise**. Each click turns the pages by 90 degrees. |
|
||||
| Copy text | Select text on the page with the pointer, then press Ctrl+C. |
|
||||
| Show changes from another program | Select **Reload PDF**. The tab stays on the same page. |
|
||||
| Open a protected PDF | Type the password, then select **Unlock**. RuneStone does not save the password. |
|
||||
|
||||
- A PDF file must be in the workspace and at most 64 MiB.
|
||||
- The tab shows one page at a time. It does not edit PDF files, fill forms, open links, run scripts in a PDF, or print.
|
||||
- The tab shows all pages in one column. The page field shows the page that fills most of the tab. After Ctrl+Tab, the keyboard scrolls the new PDF tab at once.
|
||||
- The tab does not edit PDF files, fill forms, open links, run scripts in a PDF, or print.
|
||||
- Scanned pages show as images, so you cannot select their text.
|
||||
- If a PDF does not open, the tab shows the error. Select **Reload PDF**, or try another copy of the file.
|
||||
|
||||
|
||||
@@ -1,28 +1,32 @@
|
||||
<script lang="ts">
|
||||
// One PDF tab: the toolbar, the status line, the password form, and one page with its text layer.
|
||||
// One PDF tab: the toolbar, the status line, the password form, and all pages in one column that scrolls.
|
||||
// Only the pages near the visible area have a canvas and a text layer. The other pages are empty sheets.
|
||||
// The document and its worker live as long as the tab. `close` releases both.
|
||||
import { onMount } from "svelte";
|
||||
import { flushSync, 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";
|
||||
import { MAX_ZOOM, MIN_ZOOM, PAGE_GAP, PAGE_MARGIN, RESIZE_SETTLE_MS, ZOOM_STEP, fitZoom, mostVisiblePage, nextRotation, outputScale, pageBoxes, pageNumber, pagesInRange, zoomFromText, zoomLevel, type PageSize } from "./model";
|
||||
|
||||
let { file, readBytes }: { file: PluginDocumentContext; readBytes: (path: string) => Promise<Uint8Array> } = $props();
|
||||
|
||||
type Status = { key: string; values?: Record<string, string | number>; alert?: boolean };
|
||||
/** One page that has a drawing, or waits for one. `key` names the zoom, the rotation, and the pixel ratio. */
|
||||
type Drawing = { key: string; done: boolean; cancel(): void };
|
||||
|
||||
let page = $state(1);
|
||||
let count = $state(0);
|
||||
let zoom = $state(1);
|
||||
let rotation = $state(0);
|
||||
let fit = $state(true);
|
||||
let sizes = $state.raw<PageSize[]>([]);
|
||||
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 sheets: HTMLDivElement[] = $state([]);
|
||||
let pageInput: HTMLInputElement;
|
||||
let passwordInput: HTMLInputElement | undefined = $state();
|
||||
|
||||
@@ -30,14 +34,20 @@
|
||||
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 generation = 0;
|
||||
const drawings = new Map<number, Drawing>();
|
||||
let queue: Promise<void> = Promise.resolve();
|
||||
let loading: Promise<void> = Promise.resolve();
|
||||
let closing: Promise<void> | undefined;
|
||||
// The place in the document: a page and the part of its height above the top of the visible area.
|
||||
let anchor = { index: 0, part: 0 };
|
||||
// The scroll position that the viewer set. A scroll event at this position keeps the page number.
|
||||
let settled = -1;
|
||||
let frame = 0;
|
||||
|
||||
const ready = $derived(count > 0);
|
||||
const boxes = $derived(pageBoxes(sizes, zoom, rotation));
|
||||
const zoomText = $derived(ready ? `${Math.round(zoom * 100)}%` : "—");
|
||||
|
||||
function fail(reason: unknown) {
|
||||
if (disposed) return;
|
||||
@@ -45,53 +55,137 @@
|
||||
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 } };
|
||||
const drawingKey = () => `${zoom}:${rotation}:${window.devicePixelRatio}`;
|
||||
|
||||
/** The status line names the current page when its drawing is complete. */
|
||||
function report() {
|
||||
if (disposed || failed || !pdf) return;
|
||||
const drawing = drawings.get(page);
|
||||
status = drawing?.done && drawing.key === drawingKey()
|
||||
? { key: message("Page {page} of {count}"), values: { page, count } }
|
||||
: { key: message("Loading page {page}…"), values: { page } };
|
||||
}
|
||||
|
||||
/** Draw one page. The jobs run one at a time. A cancelled job ends at its next step. */
|
||||
function draw(number: number, key: string) {
|
||||
let cancelled = false;
|
||||
let render: RenderTask | undefined;
|
||||
let text: TextLayer | undefined;
|
||||
const drawing: Drawing = { key, done: false, cancel() { cancelled = true; render?.cancel(); text?.cancel(); } };
|
||||
drawings.set(number, drawing);
|
||||
const source = pdf;
|
||||
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 });
|
||||
if (cancelled || disposed || !source) return;
|
||||
const pdfPage = await source.getPage(number);
|
||||
const sheet = sheets[number - 1];
|
||||
if (cancelled || disposed || !sheet) return;
|
||||
const viewport = pdfPage.getViewport({ scale: zoom, rotation: (pdfPage.rotate + rotation) % 360 });
|
||||
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 }));
|
||||
canvas.setAttribute("aria-label", $t("PDF page {page}", { page: number }));
|
||||
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);
|
||||
layer.style.setProperty("--total-scale-factor", String(viewport.scale));
|
||||
render = pdfPage.render({ canvas, viewport, transform: scale === 1 ? undefined : [scale, 0, 0, scale, 0, 0] });
|
||||
await render.promise;
|
||||
if (disposed || request !== revision) return;
|
||||
if (cancelled || disposed) return;
|
||||
// The old drawing of the page stays until the new one is complete.
|
||||
sheet.replaceChildren(canvas, layer);
|
||||
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 } };
|
||||
if (cancelled || disposed) return;
|
||||
drawing.done = true;
|
||||
pdfPage.cleanup();
|
||||
}).catch(reason => { if (!disposed && request === revision) fail(reason); });
|
||||
report();
|
||||
}).catch(reason => { if (!cancelled && !disposed) fail(reason); });
|
||||
}
|
||||
|
||||
/** Draw the pages near the visible area, the current page first. Empty the pages that are far from it. */
|
||||
function refresh() {
|
||||
if (!pdf || disposed || scroller.clientWidth === 0) return;
|
||||
const key = drawingKey();
|
||||
const height = scroller.clientHeight;
|
||||
const wanted = pagesInRange(boxes, scroller.scrollTop - height, scroller.scrollTop + 2 * height);
|
||||
for (const [number, drawing] of drawings) {
|
||||
const keep = wanted.includes(number);
|
||||
if (keep && drawing.key === key) continue;
|
||||
drawing.cancel();
|
||||
drawings.delete(number);
|
||||
if (!keep) sheets[number - 1]?.replaceChildren();
|
||||
}
|
||||
for (const number of wanted.sort((a, b) => Math.abs(a - page) - Math.abs(b - page))) if (!drawings.has(number)) draw(number, key);
|
||||
report();
|
||||
}
|
||||
|
||||
/** Put the remembered place at the top of the visible area again, after the page boxes changed. */
|
||||
function restore() {
|
||||
flushSync();
|
||||
const box = boxes[anchor.index];
|
||||
if (!box || scroller.clientWidth === 0) return;
|
||||
scroller.scrollTop = Math.max(0, box.top + anchor.part * box.height);
|
||||
settled = scroller.scrollTop;
|
||||
refresh();
|
||||
}
|
||||
|
||||
function remember() {
|
||||
const box = boxes[page - 1];
|
||||
anchor = { index: page - 1, part: box ? (scroller.scrollTop - box.top) / box.height : 0 };
|
||||
}
|
||||
|
||||
function scrolled() {
|
||||
if (frame) return;
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = 0;
|
||||
if (disposed || !ready || scroller.clientWidth === 0) return;
|
||||
if (scroller.scrollTop !== settled) {
|
||||
settled = -1;
|
||||
page = mostVisiblePage(boxes, scroller.scrollTop, scroller.scrollTop + scroller.clientHeight);
|
||||
remember();
|
||||
}
|
||||
refresh();
|
||||
});
|
||||
}
|
||||
|
||||
/** Show the top of a page. */
|
||||
function go(value: number) {
|
||||
if (!pdf) return;
|
||||
page = pageNumber(value, pdf.numPages);
|
||||
pageInput.value = String(page);
|
||||
scroller.scrollTop = 0;
|
||||
schedule();
|
||||
// The first page shows with the margin above it. Each other page shows with half of the gap above it.
|
||||
anchor = { index: page - 1, part: -(page === 1 ? PAGE_MARGIN : PAGE_GAP / 2) / (boxes[page - 1]?.height ?? 1) };
|
||||
restore();
|
||||
}
|
||||
|
||||
function setZoom(value: number) { fit = false; zoom = zoomLevel(value); schedule(); }
|
||||
function applyFit() {
|
||||
if (fit && scroller.clientWidth > 0 && sizes.length) zoom = fitZoom(sizes, rotation, scroller.clientWidth - 2 * PAGE_MARGIN);
|
||||
}
|
||||
|
||||
function setZoom(value: number) { fit = false; zoom = zoomLevel(value); restore(); }
|
||||
|
||||
function typedZoom(input: HTMLInputElement) {
|
||||
const value = zoomFromText(input.value);
|
||||
if (value !== null && Math.round(value * 100) !== Math.round(zoom * 100)) setZoom(value);
|
||||
input.value = zoomText;
|
||||
}
|
||||
|
||||
/** Read the size of each page after the first. Until then, a page has the size of the first page. */
|
||||
async function measure(source: PDFDocumentProxy, current: number) {
|
||||
const next = [...sizes];
|
||||
let changed = false;
|
||||
for (let number = 2; number <= source.numPages; number++) {
|
||||
const { width, height } = (await source.getPage(number)).getViewport({ scale: 1 });
|
||||
if (disposed || current !== generation) return;
|
||||
if (width !== next[number - 1].width || height !== next[number - 1].height) { next[number - 1] = { width, height }; changed = true; }
|
||||
}
|
||||
if (!changed) return;
|
||||
sizes = next;
|
||||
applyFit();
|
||||
restore();
|
||||
}
|
||||
|
||||
async function load() {
|
||||
failed = false;
|
||||
@@ -105,20 +199,27 @@
|
||||
status = reason === "incorrect" ? { key: message("Incorrect password. Try again.") } : { key: message("This PDF needs a password.") };
|
||||
queueMicrotask(() => passwordInput?.focus());
|
||||
});
|
||||
pdf = await opened.promise;
|
||||
const source = await opened.promise;
|
||||
if (disposed) return;
|
||||
page = pageNumber(page, pdf.numPages);
|
||||
count = pdf.numPages;
|
||||
schedule();
|
||||
const current = ++generation;
|
||||
const { width, height } = (await source.getPage(1)).getViewport({ scale: 1 });
|
||||
if (disposed) return;
|
||||
pdf = source;
|
||||
sizes = Array.from({ length: source.numPages }, () => ({ width, height }));
|
||||
count = source.numPages;
|
||||
applyFit();
|
||||
go(page);
|
||||
report();
|
||||
void measure(source, current).catch(reason => { if (current === generation) fail(reason); });
|
||||
}
|
||||
|
||||
async function release() {
|
||||
revision++;
|
||||
render?.cancel(); text?.cancel();
|
||||
generation++;
|
||||
for (const drawing of drawings.values()) drawing.cancel();
|
||||
drawings.clear();
|
||||
await queue;
|
||||
const current = opened;
|
||||
opened = undefined; pdf = undefined; answer = undefined; asking = null; count = 0;
|
||||
sheet?.replaceChildren();
|
||||
opened = undefined; pdf = undefined; answer = undefined; asking = null; count = 0; sizes = [];
|
||||
await current?.close();
|
||||
}
|
||||
|
||||
@@ -145,12 +246,11 @@
|
||||
next(value);
|
||||
}
|
||||
|
||||
function pageKey(event: KeyboardEvent) {
|
||||
if (event.ctrlKey || event.metaKey || event.altKey || !ready) return;
|
||||
if (event.key === "PageDown" || event.key === "PageUp") {
|
||||
/** Ctrl and the wheel change the zoom. The wheel alone scrolls the pages. */
|
||||
function wheel(event: WheelEvent) {
|
||||
if (!(event.ctrlKey || event.metaKey) || !ready || event.deltaY === 0) return;
|
||||
event.preventDefault();
|
||||
go(page + (event.key === "PageDown" ? 1 : -1));
|
||||
}
|
||||
setZoom(event.deltaY < 0 ? zoom * 1.1 : zoom / 1.1);
|
||||
}
|
||||
|
||||
/** Stop the drawing, release the document, and stop its worker. The host calls it before it removes the tab. */
|
||||
@@ -163,21 +263,23 @@
|
||||
|
||||
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.
|
||||
// Fit-width pages follow the width of the tab. A tab that shows again draws at once. Later sizes wait until the size settles.
|
||||
let width = 0;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const resized = () => { applyFit(); restore(); };
|
||||
const observer = new ResizeObserver(() => {
|
||||
const next = scroller.clientWidth;
|
||||
if (next === 0 || next === width) return;
|
||||
const first = width === 0;
|
||||
if (next === width) return;
|
||||
const shown = width === 0;
|
||||
width = next;
|
||||
clearTimeout(timer);
|
||||
if (!fit) return;
|
||||
if (first) schedule();
|
||||
else timer = setTimeout(schedule, RESIZE_SETTLE_MS);
|
||||
if (next === 0) return;
|
||||
if (shown) resized();
|
||||
else timer = setTimeout(resized, RESIZE_SETTLE_MS);
|
||||
});
|
||||
observer.observe(scroller);
|
||||
return () => { observer.disconnect(); clearTimeout(timer); void close(); };
|
||||
scroller.addEventListener("wheel", wheel, { passive: false });
|
||||
return () => { observer.disconnect(); clearTimeout(timer); cancelAnimationFrame(frame); scroller.removeEventListener("wheel", wheel); void close(); };
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -191,10 +293,12 @@
|
||||
<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>
|
||||
<input class="zoom" type="text" inputmode="decimal" value={zoomText} disabled={!ready} aria-label={$t("Zoom percent")}
|
||||
onfocus={event => event.currentTarget.select()} onchange={event => typedZoom(event.currentTarget)}
|
||||
onkeydown={event => { if (event.key === "Enter") typedZoom(event.currentTarget); }} />
|
||||
<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="fit-width" label={$t("Fit width")} active={fit && ready} disabled={!ready} onclick={() => { fit = true; applyFit(); restore(); }} />
|
||||
<IconButton icon="rotate" label={$t("Rotate clockwise")} disabled={!ready} onclick={() => { rotation = nextRotation(rotation); applyFit(); restore(); }} />
|
||||
<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>
|
||||
@@ -204,32 +308,39 @@
|
||||
<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>
|
||||
<!-- The page area takes focus, so the keyboard scrolls the pages. The host gives it focus after a tab change by keyboard. -->
|
||||
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
|
||||
<div bind:this={scroller} class="scroll" tabindex="0" role="region" aria-label={$t("PDF pages")} data-tab-focus onscroll={scrolled}>
|
||||
<div class="pages">
|
||||
{#each boxes as box, index (index)}
|
||||
<div bind:this={sheets[index]} class="sheet" data-page={index + 1} style:width={`${box.width}px`} style:height={`${box.height}px`}></div>
|
||||
{/each}
|
||||
</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); }
|
||||
/* The toolbar, the status line, and the password form are opaque, so a background image never hides them. */
|
||||
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 2px; padding: 4px 8px; border-bottom: 1px solid var(--rs-border); background: var(--rs-bg-elevated); }
|
||||
.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); }
|
||||
.page:disabled, .zoom: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; }
|
||||
.zoom { box-sizing: border-box; width: 60px; height: 28px; 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: center; }
|
||||
.status { margin: 0; padding: 4px 12px; border-bottom: 1px solid var(--rs-border); background: var(--rs-bg-elevated); 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 { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 12px; border-bottom: 1px solid var(--rs-border); background: var(--rs-bg-elevated); }
|
||||
.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-hover-bg); }
|
||||
.scroll { flex: 1; min-height: 0; overflow: auto; padding: 16px; }
|
||||
.text-button { min-height: 28px; padding: 3px 10px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||
.text-button:hover { background: var(--rs-bg-active); }
|
||||
/* The padding and the gap match PAGE_MARGIN and PAGE_GAP in model.ts. */
|
||||
.scroll { flex: 1; min-height: 0; overflow: auto; padding: 16px; background: var(--rs-workarea-editor-bg); }
|
||||
.scroll:focus-visible { outline-offset: -2px; }
|
||||
.pages { display: flex; flex-direction: column; align-items: center; gap: 12px; width: max-content; min-width: 100%; }
|
||||
/* 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; }
|
||||
.sheet { position: relative; flex: none; background: white; box-shadow: 0 2px 10px #0003; }
|
||||
.sheet :global(canvas) { display: block; width: 100%; height: 100%; }
|
||||
/* 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; }
|
||||
|
||||
@@ -29,3 +29,60 @@ export function nextRotation(rotation: number): number {
|
||||
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)));
|
||||
}
|
||||
|
||||
/** The space around the pages and between two pages, in CSS pixels. `PdfViewer.svelte` uses the same values in its styles. */
|
||||
export const PAGE_MARGIN = 16;
|
||||
export const PAGE_GAP = 12;
|
||||
|
||||
/** The size of a page at zoom 1, with the rotation of the file. */
|
||||
export interface PageSize { width: number; height: number }
|
||||
/** The place of a page in the column of pages, in whole CSS pixels. */
|
||||
export interface PageBox { top: number; width: number; height: number }
|
||||
|
||||
/** The zoom factor for typed text such as "150" or "150 %". Text that is not a number gives null. */
|
||||
export function zoomFromText(text: string): number | null {
|
||||
const value = Number(text.replace("%", "").replace(",", ".").trim());
|
||||
return text.trim() && Number.isFinite(value) && value > 0 ? zoomLevel(value / 100) : null;
|
||||
}
|
||||
|
||||
/** The zoom that fits the widest page in `available` pixels. */
|
||||
export function fitZoom(sizes: readonly PageSize[], rotation: number, available: number): number {
|
||||
const turned = rotation % 180 !== 0;
|
||||
const widest = Math.max(0, ...sizes.map(size => turned ? size.height : size.width));
|
||||
return zoomLevel(widest > 0 ? available / widest : 1);
|
||||
}
|
||||
|
||||
/** One box for each page, from the top of the column to the bottom. */
|
||||
export function pageBoxes(sizes: readonly PageSize[], zoom: number, rotation: number): PageBox[] {
|
||||
const turned = rotation % 180 !== 0;
|
||||
let top = PAGE_MARGIN;
|
||||
return sizes.map(size => {
|
||||
const width = Math.max(1, Math.floor((turned ? size.height : size.width) * zoom));
|
||||
const height = Math.max(1, Math.floor((turned ? size.width : size.height) * zoom));
|
||||
const box = { top, width, height };
|
||||
top += height + PAGE_GAP;
|
||||
return box;
|
||||
});
|
||||
}
|
||||
|
||||
/** The numbers of the pages that touch the range from `from` to `to`. */
|
||||
export function pagesInRange(boxes: readonly PageBox[], from: number, to: number): number[] {
|
||||
const pages: number[] = [];
|
||||
for (let index = 0; index < boxes.length; index++) {
|
||||
if (boxes[index].top >= to) break;
|
||||
if (boxes[index].top + boxes[index].height > from) pages.push(index + 1);
|
||||
}
|
||||
return pages;
|
||||
}
|
||||
|
||||
/** The number of the page that shows the most in the range from `from` to `to`. The first such page wins. */
|
||||
export function mostVisiblePage(boxes: readonly PageBox[], from: number, to: number): number {
|
||||
let page = 1, most = 0;
|
||||
for (let index = 0; index < boxes.length; index++) {
|
||||
const { top, height } = boxes[index];
|
||||
if (top >= to) break;
|
||||
const shown = Math.min(top + height, to) - Math.max(top, from);
|
||||
if (shown > most) { most = shown; page = index + 1; }
|
||||
}
|
||||
return page;
|
||||
}
|
||||
|
||||
@@ -3680,7 +3680,8 @@ export const messageRows: [string, string, string, string][] = [
|
||||
["Loading page {page}…", "Chargement de la page {page}…", "{page} ページを読み込み中…", "正在加载第 {page} 页…"],
|
||||
["Page {page} of {count}", "Page {page} sur {count}", "{page} / {count} ページ", "第 {page} 页,共 {count} 页"],
|
||||
["PDF page {page}", "Page PDF {page}", "PDF の {page} ページ", "PDF 第 {page} 页"],
|
||||
["PDF page. Use Page Up and Page Down to change pages.", "Page PDF. Utilisez Page préc. et Page suiv. pour changer de page.", "PDF のページ。Page Up と Page Down でページを切り替えます。", "PDF 页面。使用 Page Up 和 Page Down 翻页。"],
|
||||
["PDF pages", "Pages du PDF", "PDF のページ", "PDF 页面"],
|
||||
["Zoom percent", "Pourcentage de zoom", "ズームの倍率", "缩放百分比"],
|
||||
["PDF password", "Mot de passe du PDF", "PDF のパスワード", "PDF 密码"],
|
||||
["Unlock", "Déverrouiller", "ロック解除", "解锁"],
|
||||
["This PDF needs a password.", "Ce PDF nécessite un mot de passe.", "この PDF にはパスワードが必要です。", "此 PDF 需要密码。"],
|
||||
|
||||
@@ -945,7 +945,10 @@
|
||||
if (!workingTabs.length) return false;
|
||||
const index = workingTabs.findIndex(tab => tab.relPath === activeTabPath);
|
||||
const next = (index + (command === "previous-tab" ? -1 : 1) + workingTabs.length) % workingTabs.length;
|
||||
selectWorkingTab(workingTabs[next].relPath);
|
||||
const target = workingTabs[next];
|
||||
selectWorkingTab(target.relPath);
|
||||
// A document tab takes focus in `selectTab`. A plugin tab takes it here, so the keyboard works in the new tab.
|
||||
if ("plugin" in target) void tick().then(() => { if ($pluginView?.key === target.plugin.key) pluginPaneComponents[target.plugin.key]?.focus(); });
|
||||
return true;
|
||||
}
|
||||
case "command-palette": palette = true; return true;
|
||||
|
||||
@@ -28,6 +28,11 @@
|
||||
findPanel?.focus();
|
||||
}
|
||||
|
||||
/** Give the keyboard to the tab: to the element that the view marks with `data-tab-focus`, or to the view. */
|
||||
export function focus() {
|
||||
(host?.querySelector<HTMLElement>("[data-tab-focus]") ?? host)?.focus({ preventScroll: true });
|
||||
}
|
||||
|
||||
function searchKey(event: KeyboardEvent) {
|
||||
if (event.target instanceof Element && event.target.closest('dialog, [role="dialog"], [role="menu"]')) return;
|
||||
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === "f") {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// 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.
|
||||
// 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.
|
||||
@@ -78,8 +79,13 @@ await runSmoke("features/pdf", async ({ page }) => {
|
||||
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 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++;
|
||||
@@ -89,6 +95,10 @@ await runSmoke("features/pdf", async ({ page }) => {
|
||||
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"]) {
|
||||
@@ -119,7 +129,8 @@ await runSmoke("features/pdf", async ({ page }) => {
|
||||
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 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");
|
||||
@@ -127,13 +138,70 @@ await runSmoke("features/pdf", async ({ page }) => {
|
||||
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();
|
||||
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");
|
||||
const input = active.getByRole("spinbutton", { name: "Page number", exact: true });
|
||||
await input.fill("1");
|
||||
await input.press("Enter");
|
||||
await rendered("Page 1 of 2");
|
||||
@@ -148,6 +216,24 @@ await runSmoke("features/pdf", async ({ page }) => {
|
||||
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);
|
||||
@@ -182,6 +268,8 @@ await runSmoke("features/pdf", async ({ page }) => {
|
||||
|
||||
// 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");
|
||||
@@ -225,5 +313,5 @@ await runSmoke("features/pdf", async ({ page }) => {
|
||||
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");
|
||||
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 } });
|
||||
|
||||
@@ -4,7 +4,7 @@ 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 { PAGE_GAP, PAGE_MARGIN, fitZoom, mostVisiblePage, nextRotation, outputScale, pageBoxes, pageNumber, pagesInRange, zoomFromText, 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";
|
||||
@@ -26,6 +26,38 @@ test("page and zoom inputs stay within supported bounds", () => {
|
||||
assert.deepEqual([0, 90, 180, 270].map(nextRotation), [90, 180, 270, 0]);
|
||||
});
|
||||
|
||||
test("a typed zoom is a percent within the limits", () => {
|
||||
assert.equal(zoomFromText("137"), 1.37);
|
||||
assert.equal(zoomFromText(" 150 % "), 1.5);
|
||||
assert.equal(zoomFromText("112,5"), 1.125);
|
||||
assert.equal(zoomFromText("9000"), 4);
|
||||
assert.equal(zoomFromText("1"), .25);
|
||||
for (const text of ["", " ", "text", "-50", "0", "1e999"]) assert.equal(zoomFromText(text), null);
|
||||
});
|
||||
|
||||
test("the pages are one column, and the scroll position gives the current page", () => {
|
||||
const sizes = [{ width: 600, height: 800 }, { width: 800, height: 600 }, { width: 600, height: 800 }];
|
||||
const boxes = pageBoxes(sizes, .5, 0);
|
||||
assert.deepEqual(boxes, [
|
||||
{ top: PAGE_MARGIN, width: 300, height: 400 },
|
||||
{ top: PAGE_MARGIN + 400 + PAGE_GAP, width: 400, height: 300 },
|
||||
{ top: PAGE_MARGIN + 700 + 2 * PAGE_GAP, width: 300, height: 400 },
|
||||
]);
|
||||
assert.deepEqual(pageBoxes(sizes, 1, 90).map(box => [box.width, box.height]), [[800, 600], [600, 800], [800, 600]]);
|
||||
assert.equal(fitZoom(sizes, 0, 400), .5);
|
||||
assert.equal(fitZoom(sizes, 90, 400), .5);
|
||||
assert.equal(fitZoom([{ width: 600, height: 900 }], 90, 450), .5);
|
||||
assert.equal(fitZoom([], 0, 400), 1);
|
||||
assert.deepEqual(pagesInRange(boxes, 0, 100), [1]);
|
||||
assert.deepEqual(pagesInRange(boxes, 400, 800), [1, 2, 3]);
|
||||
assert.deepEqual(pagesInRange(boxes, 5000, 6000), []);
|
||||
assert.equal(mostVisiblePage(boxes, 0, 300), 1);
|
||||
assert.equal(mostVisiblePage(boxes, 300, 600), 2);
|
||||
assert.equal(mostVisiblePage(boxes, 900, 1200), 3);
|
||||
assert.equal(mostVisiblePage(boxes, 0, 2000), 1, "The first page wins when several pages show in full");
|
||||
assert.equal(mostVisiblePage([], 0, 100), 1);
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
Reference in New Issue
Block a user