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
+38 -3
View File
@@ -1,10 +1,11 @@
// The native features of RuneStone. Each feature has an off switch in Settings → Features.
// This file is in the main bundle, so it holds only small static data: names, views, and commands.
// This file is in the main bundle, so it holds only small static data: names, views, commands, and document types.
// The code of a feature loads with a dynamic import at first need (see `loader.ts`), and never while its switch is off.
import { message, tr } from "../i18n/index.ts";
import type { PluginCommand, PluginView } from "../plugins/sdk.ts";
import type { PluginCommand, PluginDocumentType, PluginView } from "../plugins/sdk.ts";
import { identifyPdf } from "./pdfDocument.ts";
export type FeatureId = "git" | "background" | "terminal";
export type FeatureId = "git" | "background" | "terminal" | "pdf";
/** A view of a feature. The workbench shows it as a tab or in the side pane, as it shows a plugin view. */
export interface FeatureViewInfo {
@@ -26,6 +27,23 @@ export interface FeatureCommandInfo {
view?: string;
}
/**
* A document type of a feature. The file tree marks the files of the type, and a click opens them in a tab,
* without the feature code. The first tab of the type loads the feature and calls `FeatureInstance.mountDocument`.
*/
export interface FeatureDocumentInfo {
id: string;
/** Returns the title in the current language. The file tree shows it as the tooltip of the file icon. */
title: () => string;
icon: NonNullable<PluginDocumentType["icon"]>;
/** Lowercase file extensions without the dot. */
extensions: readonly string[];
/** "binary" when `identify` needs no file contents. */
content: "text" | "binary";
/** The document ID of a file, or null when the file is not of this type. */
identify(path: string, source: string): { id: string } | null;
}
export interface FeatureEntry {
id: FeatureId;
/** The ID of the old plugin package. Saved tabs and tab transfers keep it as the owner ID. */
@@ -41,6 +59,7 @@ export interface FeatureEntry {
followsPackage: boolean;
views: readonly FeatureViewInfo[];
commands: readonly FeatureCommandInfo[];
documentTypes: readonly FeatureDocumentInfo[];
}
export const FEATURES: readonly FeatureEntry[] = [
@@ -55,6 +74,7 @@ export const FEATURES: readonly FeatureEntry[] = [
{ id: "graph", title: () => tr("Git graph"), placement: "editor", icon: "git" },
],
commands: [{ id: "graph", title: () => tr("Show Git graph"), icon: "git", view: "graph" }],
documentTypes: [],
},
{
// Background replaces the Background Slideshow plugin and the background image of Appearance. Its settings are in
@@ -68,6 +88,7 @@ export const FEATURES: readonly FeatureEntry[] = [
{ id: "next", title: () => tr("Next background image"), icon: "image" },
{ id: "pause", title: () => tr("Pause background"), icon: "pause" },
],
documentTypes: [],
},
{
// Terminal replaces the Terminal plugin. Its panel is not a view: the workbench and the terminal window show it
@@ -78,6 +99,20 @@ export const FEATURES: readonly FeatureEntry[] = [
defaultOn: true, followsPackage: true,
views: [],
commands: [],
documentTypes: [],
},
{
// PDF Viewer replaces the PDF Viewer plugin. It has no view: its document type opens each PDF file in its own tab.
// The file tree marks PDF files without the module. The first PDF tab loads the module and PDF.js.
id: "pdf", owner: "runestone.pdf-viewer", name: message("PDF Viewer"),
description: message("Read PDF files of the workspace in tabs, with page controls, zoom, rotation, and text selection."),
keywords: "pdf document viewer page zoom rotate password pdf.js",
defaultOn: true, followsPackage: true,
views: [],
commands: [],
documentTypes: [
{ id: "pdf", title: () => tr("PDF document"), icon: "file", extensions: ["pdf"], content: "binary", identify: identifyPdf },
],
},
];
+1
View File
@@ -8,6 +8,7 @@ const imports: Record<FeatureId, () => Promise<FeatureModule>> = {
git: () => import("./git/index.ts"),
background: () => import("./background/index.ts"),
terminal: () => import("./terminal/index.ts"),
pdf: () => import("./pdf/index.ts"),
};
const modules = new Map<FeatureId, Promise<FeatureModule>>();
+239
View File
@@ -0,0 +1,239 @@
<script lang="ts">
// One PDF tab: the toolbar, the status line, the password form, and one page with its text layer.
// The document and its worker live as long as the tab. `close` releases both.
import { onMount } from "svelte";
import { message, t } from "$lib/i18n";
import IconButton from "$lib/ui/IconButton.svelte";
import type { PluginDocumentContext } from "$lib/plugins/sdk";
import { openPdf, TextLayer, type OpenPdf, type PDFDocumentProxy, type RenderTask } from "./engine";
import { MAX_ZOOM, MIN_ZOOM, RESIZE_SETTLE_MS, ZOOM_STEP, nextRotation, outputScale, pageNumber, zoomLevel } from "./model";
let { file, readBytes }: { file: PluginDocumentContext; readBytes: (path: string) => Promise<Uint8Array> } = $props();
type Status = { key: string; values?: Record<string, string | number>; alert?: boolean };
let page = $state(1);
let count = $state(0);
let zoom = $state(1);
let rotation = $state(0);
let fit = $state(true);
let status = $state<Status>({ key: message("Loading PDF…") });
let asking = $state<"needed" | "incorrect" | null>(null);
let reloading = $state(false);
let failed = $state(false);
let scroller: HTMLDivElement;
let sheet: HTMLDivElement;
let pageInput: HTMLInputElement;
let passwordInput: HTMLInputElement | undefined = $state();
let disposed = false;
let pdf: PDFDocumentProxy | undefined;
let opened: OpenPdf | undefined;
let answer: ((password: string) => void) | undefined;
let render: RenderTask | undefined;
let text: TextLayer | undefined;
let revision = 0;
let queue: Promise<void> = Promise.resolve();
let loading: Promise<void> = Promise.resolve();
let closing: Promise<void> | undefined;
const ready = $derived(count > 0);
function fail(reason: unknown) {
if (disposed) return;
failed = true;
status = { key: message("Cannot display this PDF. {reason}"), values: { reason: reason instanceof Error ? reason.message : String(reason) }, alert: true };
}
/** Draw the current page again. A newer request cancels the older one. */
function schedule() {
const request = ++revision;
render?.cancel(); text?.cancel();
if (pdf && !disposed) status = { key: message("Loading page {page}…"), values: { page } };
queue = queue.then(async () => {
if (disposed || request !== revision || !pdf || scroller.clientWidth === 0) return;
const pdfPage = await pdf.getPage(page);
if (disposed || request !== revision) return;
const angle = (pdfPage.rotate + rotation) % 360;
if (fit) zoom = zoomLevel((scroller.clientWidth - 32) / pdfPage.getViewport({ scale: 1, rotation: angle }).width);
const viewport = pdfPage.getViewport({ scale: zoom, rotation: angle });
const scale = outputScale(viewport.width, viewport.height, window.devicePixelRatio);
const canvas = document.createElement("canvas");
canvas.width = Math.max(1, Math.floor(viewport.width * scale));
canvas.height = Math.max(1, Math.floor(viewport.height * scale));
canvas.style.width = `${viewport.width}px`;
canvas.style.height = `${viewport.height}px`;
canvas.setAttribute("role", "img");
// The measurement tool and the smoke tests find the page by this English name. Keep "PDF page N".
canvas.setAttribute("aria-label", $t("PDF page {page}", { page }));
const layer = document.createElement("div");
layer.className = "textLayer";
sheet.style.width = `${viewport.width}px`;
sheet.style.height = `${viewport.height}px`;
sheet.style.setProperty("--total-scale-factor", String(zoom));
sheet.replaceChildren(canvas, layer);
render = pdfPage.render({ canvas, viewport, transform: scale === 1 ? undefined : [scale, 0, 0, scale, 0, 0] });
await render.promise;
if (disposed || request !== revision) return;
text = new TextLayer({ textContentSource: pdfPage.streamTextContent(), container: layer, viewport });
await text.render();
if (disposed || request !== revision) return;
status = { key: message("Page {page} of {count}"), values: { page, count } };
pdfPage.cleanup();
}).catch(reason => { if (!disposed && request === revision) fail(reason); });
}
function go(value: number) {
if (!pdf) return;
page = pageNumber(value, pdf.numPages);
pageInput.value = String(page);
scroller.scrollTop = 0;
schedule();
}
function setZoom(value: number) { fit = false; zoom = zoomLevel(value); schedule(); }
async function load() {
failed = false;
status = { key: message("Loading PDF…") };
const bytes = await readBytes(file.path);
if (disposed) return;
opened = openPdf(bytes, (reason, next) => {
if (disposed) return;
answer = next;
asking = reason;
status = reason === "incorrect" ? { key: message("Incorrect password. Try again.") } : { key: message("This PDF needs a password.") };
queueMicrotask(() => passwordInput?.focus());
});
pdf = await opened.promise;
if (disposed) return;
page = pageNumber(page, pdf.numPages);
count = pdf.numPages;
schedule();
}
async function release() {
revision++;
render?.cancel(); text?.cancel();
await queue;
const current = opened;
opened = undefined; pdf = undefined; answer = undefined; asking = null; count = 0;
sheet?.replaceChildren();
await current?.close();
}
async function reload() {
if (reloading || disposed) return;
reloading = true;
try {
await loading;
await release();
if (!disposed) await (loading = load());
} catch (reason) { fail(reason); }
finally { reloading = false; }
}
function unlock(event: SubmitEvent) {
event.preventDefault();
if (!passwordInput || !answer) return;
const value = passwordInput.value;
passwordInput.value = "";
asking = null;
status = { key: message("Loading PDF…") };
const next = answer;
answer = undefined;
next(value);
}
function pageKey(event: KeyboardEvent) {
if (event.ctrlKey || event.metaKey || event.altKey || !ready) return;
if (event.key === "PageDown" || event.key === "PageUp") {
event.preventDefault();
go(page + (event.key === "PageDown" ? 1 : -1));
}
}
/** Stop the drawing, release the document, and stop its worker. The host calls it before it removes the tab. */
export function close(): Promise<void> {
if (closing) return closing;
disposed = true;
closing = release().then(() => loading).catch(() => {});
return closing;
}
onMount(() => {
loading = load().catch(fail);
// A fit-width page follows the width of the tab. The first size draws at once. Later sizes wait until the size settles.
let width = 0;
let timer: ReturnType<typeof setTimeout> | undefined;
const observer = new ResizeObserver(() => {
const next = scroller.clientWidth;
if (next === 0 || next === width) return;
const first = width === 0;
width = next;
clearTimeout(timer);
if (!fit) return;
if (first) schedule();
else timer = setTimeout(schedule, RESIZE_SETTLE_MS);
});
observer.observe(scroller);
return () => { observer.disconnect(); clearTimeout(timer); void close(); };
});
</script>
<section class="pdf-viewer" aria-label={$t("PDF Viewer")}>
<div class="toolbar" role="group" aria-label={$t("PDF controls")}>
<IconButton icon="up" label={$t("Previous page")} disabled={!ready || page <= 1} onclick={() => go(page - 1)} />
<input bind:this={pageInput} class="page" type="number" min="1" max={Math.max(count, 1)} value={page} disabled={!ready}
aria-label={$t("Page number")} onchange={event => { if (Number(event.currentTarget.value) !== page) go(Number(event.currentTarget.value)); }}
onkeydown={event => { if (event.key === "Enter") go(Number(event.currentTarget.value)); }} />
<span class="count">/ {ready ? count : "—"}</span>
<IconButton icon="down" label={$t("Next page")} disabled={!ready || page >= count} onclick={() => go(page + 1)} />
<span class="separator" aria-hidden="true"></span>
<IconButton icon="zoom-out" label={$t("Zoom out")} disabled={!ready || zoom <= MIN_ZOOM} onclick={() => setZoom(zoom / ZOOM_STEP)} />
<span class="zoom">{ready ? `${Math.round(zoom * 100)}%` : "—"}</span>
<IconButton icon="zoom-in" label={$t("Zoom in")} disabled={!ready || zoom >= MAX_ZOOM} onclick={() => setZoom(zoom * ZOOM_STEP)} />
<IconButton icon="fit-width" label={$t("Fit width")} active={fit && ready} disabled={!ready} onclick={() => { fit = true; schedule(); }} />
<IconButton icon="rotate" label={$t("Rotate clockwise")} disabled={!ready} onclick={() => { rotation = nextRotation(rotation); schedule(); }} />
<IconButton icon="refresh" label={$t("Reload PDF")} disabled={reloading || (!ready && !failed)} onclick={() => void reload()} />
</div>
<p class="status" class:alert={status.alert} role={status.alert ? "alert" : "status"} aria-live={status.alert ? "assertive" : "polite"}>{$t(status.key, status.values)}</p>
{#if asking}
<form class="password" onsubmit={unlock}>
<label>{$t("PDF password")} <input bind:this={passwordInput} type="password" autocomplete="off" /></label>
<button class="text-button" type="submit">{$t("Unlock")}</button>
</form>
{/if}
<!-- The page area takes focus for Page Up and Page Down. -->
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions -->
<div bind:this={scroller} class="scroll" tabindex="0" role="region" aria-label={$t("PDF page. Use Page Up and Page Down to change pages.")} onkeydown={pageKey}>
<div bind:this={sheet} class="sheet"></div>
</div>
</section>
<style>
.pdf-viewer { display: flex; flex-direction: column; height: 100%; min-height: 240px; min-width: 0; color: var(--rs-text); font-size: 13px; }
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 2px; padding: 4px 8px; border-bottom: 1px solid var(--rs-border); }
.page { box-sizing: border-box; width: 64px; height: 28px; margin-left: 4px; padding: 2px 4px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; text-align: right; }
.page:disabled { color: var(--rs-text-dim); }
.count { margin: 0 4px; color: var(--rs-text-dim); white-space: nowrap; }
.separator { width: 1px; height: 18px; margin: 0 4px; background: var(--rs-border); }
.zoom { min-width: 44px; color: var(--rs-text-dim); text-align: center; white-space: nowrap; }
.status { margin: 0; padding: 4px 12px; font-size: 12px; color: var(--rs-text-dim); overflow-wrap: anywhere; }
.status.alert { color: var(--rs-error); }
.password { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 12px; }
.password input { box-sizing: border-box; height: 28px; margin-left: 4px; padding: 2px 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
.text-button { min-height: 28px; padding: 3px 10px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: inherit; }
.text-button:hover { background: var(--rs-bg-active); }
.scroll { flex: 1; min-height: 0; overflow: auto; padding: 16px; }
.scroll:focus-visible { outline-offset: -2px; }
/* A PDF page is paper: white in both themes. */
.sheet { position: relative; margin: 0 auto; background: white; box-shadow: 0 2px 10px #0003; }
.sheet :global(canvas) { display: block; }
/* The text layer geometry follows the viewer styles of PDF.js 6 (Apache-2.0). See THIRD_PARTY_NOTICES.md. */
.sheet :global(.textLayer) { position: absolute; inset: 0; overflow: clip; text-align: initial; line-height: 1; letter-spacing: normal; word-spacing: normal; text-size-adjust: none; forced-color-adjust: none; transform-origin: 0 0; --min-font-size: 1; --text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size)); --min-font-size-inv: calc(1 / var(--min-font-size)); }
.sheet :global(.textLayer :is(span, br)) { position: absolute; color: transparent; white-space: pre; cursor: text; transform-origin: 0 0; user-select: text; }
.sheet :global(.textLayer > :not(.markedContent)), .sheet :global(.markedContent span:not(.markedContent)) { z-index: 1; --font-height: 0; font-size: calc(var(--text-scale-factor) * var(--font-height)); --scale-x: 1; --rotate: 0deg; transform: rotate(var(--rotate)) scaleX(var(--scale-x)) scale(var(--min-font-size-inv)); }
.sheet :global(.markedContent) { display: contents; }
.sheet :global(.textLayer ::selection) { background: color-mix(in srgb, var(--rs-selection) 65%, transparent); color: transparent; }
</style>
+69
View File
@@ -0,0 +1,69 @@
/// <reference types="vite/client" />
// PDF.js for the PDF Viewer feature. The worker, the character maps, the standard fonts, and the WebAssembly image
// decoders come from the app (`'self'`) as Vite assets, so a PDF never causes a network request.
// Each open document has its own worker. `close` stops it.
// The reference to the Vite types serves the unit test type check, which reaches this file through `loader.ts`.
import { getDocument, PDFWorker, PasswordResponses, type PDFDocumentLoadingTask, type PDFDocumentProxy } from "pdfjs-dist/build/pdf.min.mjs";
import workerUrl from "pdfjs-dist/build/pdf.worker.min.mjs?url";
export { TextLayer, type PDFDocumentProxy, type RenderTask } from "pdfjs-dist/build/pdf.min.mjs";
// `build.assetsInlineLimit` in vite.config.js keeps these files out of the code, so each one is a file of the app.
// The JPEG 2000 and JBIG2 decoders are the only WebAssembly files that PDF.js asks for with `useWorkerFetch: false`.
// The viewer runs no PDF scripts (quickjs) and uses no ICC color profiles (qcms), as the PDF Viewer plugin did.
const assets = import.meta.glob<string>([
"/node_modules/pdfjs-dist/cmaps/*.bcmap",
"/node_modules/pdfjs-dist/standard_fonts/*.{pfb,ttf}",
"/node_modules/pdfjs-dist/wasm/{jbig2,openjpeg}.wasm",
], { query: "?url", import: "default", eager: true });
const folders: Record<string, string> = { cMapUrl: "cmaps", standardFontDataUrl: "standard_fonts", wasmUrl: "wasm" };
/** The app URL of a PDF.js data file, or undefined for an unknown kind or file. */
export function assetUrl(kind: string, filename: string): string | undefined {
const folder = folders[kind];
if (!folder || !/^[\w.-]+$/.test(filename)) return undefined;
return assets[`/node_modules/pdfjs-dist/${folder}/${filename}`];
}
/** PDF.js asks the window for its data files (`useWorkerFetch: false`). This class reads them from the app. */
class AppBinaryDataFactory {
async fetch({ kind, filename }: { kind: string; filename: string }): Promise<Uint8Array> {
const url = assetUrl(kind, filename);
if (!url) throw new Error(`PDF.js has no data file ${filename}.`);
const response = await fetch(url);
if (!response.ok) throw new Error(`PDF.js could not read ${filename}: ${response.status}.`);
return new Uint8Array(await response.arrayBuffer());
}
}
export interface OpenPdf {
/** Resolves with the document after the password, if the file needs one. */
promise: Promise<PDFDocumentProxy>;
/** Stop the load or release the document, and stop the worker. Later calls return the same promise. */
close(): Promise<void>;
}
/**
* Open the bytes of a PDF in a new worker. PDF.js calls `onPassword` for a protected file, with "incorrect" after a
* wrong password. The viewer calls `answer` with the next password.
*/
export function openPdf(data: Uint8Array, onPassword: (reason: "needed" | "incorrect", answer: (password: string) => void) => void): OpenPdf {
const port = new Worker(workerUrl, { type: "module", name: "PDF.js" });
const worker = PDFWorker.create({ port });
const task: PDFDocumentLoadingTask = getDocument({
data, worker, useWorkerFetch: false, BinaryDataFactory: AppBinaryDataFactory,
useSystemFonts: false, isImageDecoderSupported: false, enableXfa: false,
});
task.onPassword = (answer: (password: string) => void, reason: number) => {
onPassword(reason === PasswordResponses.INCORRECT_PASSWORD ? "incorrect" : "needed", answer);
};
let closing: Promise<void> | undefined;
return {
promise: task.promise,
close: () => closing ??= (async () => {
try { await task.destroy(); }
finally { worker.destroy(); port.terminate(); }
})(),
};
}
+32
View File
@@ -0,0 +1,32 @@
// The PDF Viewer feature. `loader.ts` imports this module when the first PDF tab opens. The file tree marks PDF files
// before that, through the document type of the catalog (`../pdfDocument.ts`).
// Each tab reads its file with `workspace_read_bytes` (64 MiB at most) and has its own PDF.js worker.
import { flushSync, mount, unmount } from "svelte";
import { tr } from "../../i18n/index.ts";
import { workspaceReadBytes } from "../../workspace/api.ts";
import type { FeatureContext, FeatureInstance } from "../types.ts";
import PdfViewer from "./PdfViewer.svelte";
export function start(_context: FeatureContext): FeatureInstance {
const tabs = new Set<() => Promise<void>>();
let stopped = false;
return {
mount() { throw new Error(tr("This view is unavailable.")); },
mountDocument(type, element, file) {
if (type !== "pdf") throw new Error(tr("This view is unavailable."));
if (stopped) throw new Error(tr("This feature is off."));
const viewer = mount(PdfViewer, { target: element, props: { file, readBytes: workspaceReadBytes } });
flushSync();
let closing: Promise<void> | undefined;
// Release the document and stop its worker first. Then remove the component.
const dispose = () => closing ??= viewer.close().then(() => unmount(viewer)).finally(() => { tabs.delete(dispose); });
tabs.add(dispose);
return dispose;
},
/** The host closes the PDF tabs first. Close what is left, so no worker stays. */
async dispose() {
stopped = true;
await Promise.allSettled([...tabs].map(dispose => dispose()));
},
};
}
+31
View File
@@ -0,0 +1,31 @@
// The limits of the PDF Viewer: page numbers, zoom, and the size of the page canvas.
export const MIN_ZOOM = 0.25;
export const MAX_ZOOM = 4;
/** Each zoom step multiplies or divides the zoom by this factor. */
export const ZOOM_STEP = 1.25;
/** A redraw after a resize waits until the size did not change for this time. */
export const RESIZE_SETTLE_MS = 150;
/** A whole page number from 1 to `count`. A value that is not a number gives page 1. */
export function pageNumber(value: number, count: number): number {
return Math.max(1, Math.min(count, Number.isFinite(value) ? Math.trunc(value) : 1));
}
/** A zoom factor from 0.25 to 4. A value that is not a finite number gives 1. */
export function zoomLevel(value: number): number {
return Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, Number.isFinite(value) ? value : 1));
}
/** The next clockwise rotation in degrees: 0, 90, 180, or 270. */
export function nextRotation(rotation: number): number {
return (rotation + 90) % 360;
}
/**
* The pixel scale of the page canvas. It follows the device pixel ratio up to 2, and keeps each side at most
* 8192 pixels and the area at most 16 million pixels, so a large page does not use too much memory.
*/
export function outputScale(width: number, height: number, deviceScale: number): number {
return Math.min(deviceScale || 1, 2, 8192 / width, 8192 / height, Math.sqrt(16_000_000 / (width * height)));
}
+4
View File
@@ -0,0 +1,4 @@
// The minified build of PDF.js has the same exports as the package entry.
declare module "pdfjs-dist/build/pdf.min.mjs" {
export * from "pdfjs-dist";
}
+7
View File
@@ -0,0 +1,7 @@
// The document identification of the PDF Viewer feature. It is in the main bundle, because the file tree marks
// PDF files before the feature module loads. The document ID is the workspace path, so two files never share a tab.
/** The document ID of a PDF file: its path with forward slashes. Any letter case of the extension matches. */
export function identifyPdf(path: string): { id: string } | null {
return /\.pdf$/i.test(path) ? { id: path.replaceAll("\\", "/") } : null;
}
+20 -6
View File
@@ -1,9 +1,9 @@
// A feature in the workbench of one window. Its views and commands come from the static catalog, so the
// navigation buttons and the command palette show them without the feature code. The first mount,
// A feature in the workbench of one window. Its views, commands, and document types come from the static catalog, so the
// navigation buttons, the command palette, and the file tree show them without the feature code. The first mount,
// restore, or action command loads the feature module and starts one instance for this window.
// A launch rule (`launch.ts`) can also start the instance at once.
import { tr } from "../i18n/index.ts";
import type { Dispose, PluginCommand, PluginDocumentType, PluginView } from "../plugins/sdk.ts";
import type { Dispose, PluginCommand, PluginDocumentContext, PluginDocumentType, PluginView } from "../plugins/sdk.ts";
import type { FeatureEntry } from "./catalog.ts";
import { loadFeature } from "./loader.ts";
import type { FeatureContext, FeatureInstance, FeatureModule } from "./types.ts";
@@ -32,6 +32,13 @@ export class FeatureSession {
restoreTabState: async state => { await (await this.running()).restoreTabState?.(info.id, state); },
});
}
for (const info of entry.documentTypes) {
this.documentTypes.set(info.id, {
id: info.id, get title() { return info.title(); }, icon: info.icon, extensions: [...info.extensions], content: info.content,
identify: (path, source) => info.identify(path, source),
mount: (element, document) => this.mountDocument(info.id, element, document),
});
}
for (const info of entry.commands) {
const view = info.view;
this.commands.set(info.id, { id: info.id, get title() { return info.title(); }, icon: info.icon,
@@ -53,10 +60,17 @@ export class FeatureSession {
return (await this.running()).mount(id, element);
}
async mount(id: string, element: HTMLElement): Promise<Dispose> {
const view = this.views.get(id);
private async mountDocument(type: string, element: HTMLElement, document: PluginDocumentContext): Promise<Dispose> {
const instance = await this.running();
if (!instance.mountDocument) throw new Error(tr("This view is unavailable."));
return instance.mountDocument(type, element, document);
}
/** Mount a view, or with `document`, a document of the document type `id`. */
async mount(id: string, element: HTMLElement, document?: PluginDocumentContext): Promise<Dispose> {
const view = document ? this.documentTypes.get(id) : this.views.get(id);
if (!view) throw new Error(tr("This view is unavailable."));
const dispose = await view.mount(element);
const dispose = document ? await (view as PluginDocumentType).mount(element, document) : await (view as PluginView).mount(element, { surface: "view" });
return async () => {
if (typeof dispose === "function") await dispose();
element.replaceChildren();
+6 -1
View File
@@ -1,4 +1,4 @@
import type { Dispose } from "../plugins/sdk.ts";
import type { Dispose, PluginDocumentContext } from "../plugins/sdk.ts";
/** The host services that a running feature gets. A feature also uses other host modules directly. */
export interface FeatureContext {
@@ -13,6 +13,11 @@ export interface FeatureContext {
/** One running copy of a feature in one window. */
export interface FeatureInstance {
mount(view: string, element: HTMLElement): Dispose | Promise<Dispose>;
/**
* Show a document of a catalog document type in `element`. `document.path` follows a rename of the file.
* The returned function removes the document and stops its work, for example a worker.
*/
mountDocument?(type: string, element: HTMLElement, document: PluginDocumentContext): Dispose | Promise<Dispose>;
/** Run a command of the catalog that has no view. */
run?(command: string): void | Promise<void>;
/** The state of a tab for a transfer to another window. */
+21
View File
@@ -3658,6 +3658,27 @@ export const messageRows: [string, string, string, string][] = [
["Use PowerShell for a path with quotes, % or !.", "Utilisez PowerShell pour un chemin contenant des guillemets, % ou !.", "引用符、%、! を含むパスには PowerShell を使用してください。", "对于包含引号、% 或 ! 的路径,请使用 PowerShell。"],
["{title}: choices", "{title} : choix", "{title}: 選択肢", "{title}:选项"],
["{up} {down} select · {enter} choose · {escape} close", "{up} {down} sélectionner · {enter} choisir · {escape} fermer", "{up} {down} 選択 · {enter} 決定 · {escape} 閉じる", "{up} {down} 选择 · {enter} 确定 · {escape} 关闭"],
// The PDF Viewer feature (src/lib/features/pdf/).
["PDF Viewer", "Lecteur PDF", "PDF ビューアー", "PDF 查看器"],
["Read PDF files of the workspace in tabs, with page controls, zoom, rotation, and text selection.", "Lisez les fichiers PDF de l’espace de travail dans des onglets, avec les commandes de page, le zoom, la rotation et la sélection de texte.", "ワークスペースの PDF ファイルをタブで読みます。ページ操作、ズーム、回転、テキスト選択を使えます。", "在标签页中阅读工作区的 PDF 文件,支持页面控制、缩放、旋转和文本选择。"],
["PDF document", "Document PDF", "PDF ドキュメント", "PDF 文档"],
["PDF controls", "Commandes PDF", "PDF の操作", "PDF 控件"],
["Previous page", "Page précédente", "前のページ", "上一页"],
["Next page", "Page suivante", "次のページ", "下一页"],
["Page number", "Numéro de page", "ページ番号", "页码"],
["Fit width", "Ajuster à la largeur", "幅に合わせる", "适应宽度"],
["Rotate clockwise", "Faire pivoter dans le sens horaire", "時計回りに回転", "顺时针旋转"],
["Reload PDF", "Recharger le PDF", "PDF を再読み込み", "重新加载 PDF"],
["Loading PDF…", "Chargement du PDF…", "PDF を読み込み中…", "正在加载 PDF…"],
["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 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 需要密码。"],
["Incorrect password. Try again.", "Mot de passe incorrect. Réessayez.", "パスワードが正しくありません。もう一度入力してください。", "密码不正确。请重试。"],
["Cannot display this PDF. {reason}", "Impossible d’afficher ce PDF. {reason}", "この PDF を表示できません。{reason}", "无法显示此 PDF。{reason}"],
// The native features without the desktop host.
["This feature needs the desktop app.", "Cette fonctionnalité nécessite l’application de bureau.", "この機能にはデスクトップアプリが必要です。", "此功能需要桌面应用。"],
];
+5 -1
View File
@@ -26,7 +26,7 @@
<circle cx="12" cy="12" r="9" /><path d="M9.5 9a2.5 2.5 0 1 1 4 2c-1 .6-1.5 1-1.5 3M12 17h.01" />
{:else if icon === "puzzle"}
<path d="M9 3H4v6a3 3 0 1 1 0 6v5h6a3 3 0 1 1 6 0h4v-6a3 3 0 1 0 0-6V3h-5a3 3 0 1 1-6 0Z" />
{:else if icon === "up" || icon === "down" || icon === "kanban" || icon === "link"}
{:else if icon === "up" || icon === "down" || icon === "kanban" || icon === "link" || icon === "zoom-in" || icon === "zoom-out"}
{@html actionIcons[icon]}
{:else if icon === "more"}
<circle cx="5" cy="12" r="1" /><circle cx="12" cy="12" r="1" /><circle cx="19" cy="12" r="1" />
@@ -150,6 +150,10 @@
<path d="M5 12h14" />
{:else if icon === "toggle"}
<rect x="3" y="7" width="18" height="10" rx="5" /><circle cx="16" cy="12" r="2.5" />
{:else if icon === "fit-width"}
<path d="M3 4v16M21 4v16M7 12h10M10 9l-3 3 3 3M14 9l3 3-3 3" />
{:else if icon === "rotate"}
<path d="M20 7v5h-5" /><path d="M20 12a8 8 0 1 0-2 6" />
{/if}
</svg>
<style>
+5 -1
View File
@@ -57,7 +57,11 @@
| "download"
| "upload"
| "minus"
| "toggle";
| "toggle"
| "zoom-in"
| "zoom-out"
| "fit-width"
| "rotate";
type Props = {
icon: IconName;