@ruckc/truss-pdf 0.0.0-stage → 1.68.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +122 -2
- package/dist/PdfDialog.svelte +72 -0
- package/dist/PdfDialog.svelte.d.ts +15 -0
- package/dist/PdfReview.svelte +174 -0
- package/dist/PdfReview.svelte.d.ts +120 -0
- package/dist/PdfViewer.svelte +1184 -0
- package/dist/PdfViewer.svelte.d.ts +92 -0
- package/dist/ReviewPanel.svelte +591 -0
- package/dist/ReviewPanel.svelte.d.ts +126 -0
- package/dist/assets.d.ts +9 -0
- package/dist/assets.js +29 -0
- package/dist/bidi.d.ts +2 -0
- package/dist/bidi.js +9 -0
- package/dist/cssvars.d.ts +12 -0
- package/dist/cssvars.js +32 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +7 -0
- package/dist/labels.d.ts +6 -0
- package/dist/labels.js +23 -0
- package/dist/pages.d.ts +54 -0
- package/dist/pages.js +171 -0
- package/dist/paging.d.ts +18 -0
- package/dist/paging.js +110 -0
- package/dist/pdfjs.d.ts +40 -0
- package/dist/pdfjs.js +49 -0
- package/dist/quote-match.d.ts +30 -0
- package/dist/quote-match.js +145 -0
- package/dist/types.d.ts +142 -0
- package/dist/types.js +1 -0
- package/package.json +54 -5
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
export type ReviewPanelLabels = {
|
|
2
|
+
/** Accessible name of the panel. */
|
|
3
|
+
panel: string;
|
|
4
|
+
/** Accessible name of the filter segments. */
|
|
5
|
+
filters: string;
|
|
6
|
+
/** The default filter, when the host defines none. */
|
|
7
|
+
all: string;
|
|
8
|
+
/** A filter segment: its label and the number of items it matches. */
|
|
9
|
+
filterOption: (label: string, count: number) => string;
|
|
10
|
+
/** Accessible name of the item list. */
|
|
11
|
+
list: string;
|
|
12
|
+
/** Heading of the items without a page. */
|
|
13
|
+
document: string;
|
|
14
|
+
/** Heading of a page's items. */
|
|
15
|
+
page: (page: number) => string;
|
|
16
|
+
/** Accessible name of the previous / next group. */
|
|
17
|
+
navigation: string;
|
|
18
|
+
previous: string;
|
|
19
|
+
next: string;
|
|
20
|
+
/** The indicator while an item is selected. */
|
|
21
|
+
position: (n: number, total: number) => string;
|
|
22
|
+
/** The indicator while none is. */
|
|
23
|
+
count: (total: number) => string;
|
|
24
|
+
/** Announced when an item is selected; `title` is bidi-isolated. */
|
|
25
|
+
announce: (n: number, total: number, title: string) => string;
|
|
26
|
+
/** Accessible name of the selected item's actions. */
|
|
27
|
+
actions: string;
|
|
28
|
+
/** Announced when an action has run (a sentence: the next item may follow it); `target` is the item's title or the bulk count. */
|
|
29
|
+
done: (action: string, target: string) => string;
|
|
30
|
+
/** The toast (and announcement) when an action fails. */
|
|
31
|
+
failed: (action: string, error: string) => string;
|
|
32
|
+
/** Announced when the last item of the view has gone. */
|
|
33
|
+
cleared: string;
|
|
34
|
+
/** Shown without any items. */
|
|
35
|
+
empty: string;
|
|
36
|
+
/** Shown when the filter matches no item. */
|
|
37
|
+
emptyFilter: string;
|
|
38
|
+
/** The dialog's dismissing button. */
|
|
39
|
+
cancel: string;
|
|
40
|
+
/** The note field of a confirmation. */
|
|
41
|
+
note: string;
|
|
42
|
+
/** Accessible name of an item's bulk checkbox; `title` is bidi-isolated. */
|
|
43
|
+
check: (title: string) => string;
|
|
44
|
+
/** Accessible name of the check-all box. */
|
|
45
|
+
checkAll: string;
|
|
46
|
+
/** The bulk bar's count. */
|
|
47
|
+
checked: (n: number) => string;
|
|
48
|
+
/** Accessible name of the bulk bar. */
|
|
49
|
+
bulk: string;
|
|
50
|
+
/** Clears the bulk selection. */
|
|
51
|
+
uncheck: string;
|
|
52
|
+
};
|
|
53
|
+
import { type Snippet } from 'svelte';
|
|
54
|
+
import type { HTMLAttributes } from 'svelte/elements';
|
|
55
|
+
import type { PdfGoToResult, ReviewAction, ReviewActionDetail, ReviewFilter, ReviewItem, ReviewStatuses, ReviewViewer } from './types.js';
|
|
56
|
+
declare function $$render<T extends ReviewItem>(): {
|
|
57
|
+
props: Omit<HTMLAttributes<HTMLDivElement>, "children" | "class"> & {
|
|
58
|
+
/** What to review. Update the array (e.g. a new status after an action): the selection follows the ids. */
|
|
59
|
+
items: T[];
|
|
60
|
+
/** The filter segments, each with its count. Default: one "All" segment. */
|
|
61
|
+
filters?: ReviewFilter<T>[];
|
|
62
|
+
/** The id of the active filter. Bindable. Default: the first. */
|
|
63
|
+
filter?: string;
|
|
64
|
+
/** The id of the selected item. Bindable: setting it moves the viewer there. */
|
|
65
|
+
current?: string | null;
|
|
66
|
+
/** The id of the annotation shown as selected. Bindable: bind it to the viewer's `selected` too, so a click on an annotation selects its item. */
|
|
67
|
+
selected?: string | null;
|
|
68
|
+
/** The viewer to move (`PdfViewer`, `PdfDialog`, or anything with its `goTo`). */
|
|
69
|
+
viewer?: ReviewViewer;
|
|
70
|
+
/** The actions offered on the selected item. */
|
|
71
|
+
actions?: ReviewAction<T>[];
|
|
72
|
+
/** Runs an action. May return a promise: the panel is busy until it settles, and a rejection shows a toast. Then update `items`. */
|
|
73
|
+
onaction?: (action: string, item: T, detail: ReviewActionDetail) => unknown;
|
|
74
|
+
/** Runs a bulk action on the checked items it applies to (with `bulk`). */
|
|
75
|
+
onbulkaction?: (action: string, items: T[], detail: ReviewActionDetail) => unknown;
|
|
76
|
+
/** Called after each move with the item and the outcome of the viewer's `goTo`. */
|
|
77
|
+
onnavigate?: (item: T, result: PdfGoToResult) => void;
|
|
78
|
+
/** Label and tone of each status. */
|
|
79
|
+
statuses?: ReviewStatuses;
|
|
80
|
+
/** Checkboxes on the items and a bulk bar for the actions marked `bulk`. */
|
|
81
|
+
bulk?: boolean;
|
|
82
|
+
/** The ids of the checked items. Bindable. */
|
|
83
|
+
checked?: string[];
|
|
84
|
+
/** Host content for the selected item (an excerpt, notes, an analysis). */
|
|
85
|
+
detail?: Snippet<[T]>;
|
|
86
|
+
/** Handle the keys pressed inside the panel. `PdfReview` turns it off and passes the keys of the whole review (`handleKey`). */
|
|
87
|
+
keys?: boolean;
|
|
88
|
+
labels?: Partial<ReviewPanelLabels>;
|
|
89
|
+
class?: string;
|
|
90
|
+
};
|
|
91
|
+
exports: {
|
|
92
|
+
/** Selects the next item in the list. */ next: () => void;
|
|
93
|
+
/** Selects the previous item in the list. */ previous: () => void;
|
|
94
|
+
handleKey: (e: KeyboardEvent) => boolean;
|
|
95
|
+
};
|
|
96
|
+
bindings: "filter" | "checked" | "selected" | "current";
|
|
97
|
+
slots: {};
|
|
98
|
+
events: {};
|
|
99
|
+
};
|
|
100
|
+
declare class __sveltets_Render<T extends ReviewItem> {
|
|
101
|
+
props(): ReturnType<typeof $$render<T>>['props'];
|
|
102
|
+
events(): ReturnType<typeof $$render<T>>['events'];
|
|
103
|
+
slots(): ReturnType<typeof $$render<T>>['slots'];
|
|
104
|
+
bindings(): "filter" | "checked" | "selected" | "current";
|
|
105
|
+
exports(): {
|
|
106
|
+
/** Selects the next item in the list. */ next: () => void;
|
|
107
|
+
/** Selects the previous item in the list. */ previous: () => void;
|
|
108
|
+
handleKey: (e: KeyboardEvent) => boolean;
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
interface $$IsomorphicComponent {
|
|
112
|
+
new <T extends ReviewItem>(options: import('svelte').ComponentConstructorOptions<ReturnType<__sveltets_Render<T>['props']>>): import('svelte').SvelteComponent<ReturnType<__sveltets_Render<T>['props']>, ReturnType<__sveltets_Render<T>['events']>, ReturnType<__sveltets_Render<T>['slots']>> & {
|
|
113
|
+
$$bindings?: ReturnType<__sveltets_Render<T>['bindings']>;
|
|
114
|
+
} & ReturnType<__sveltets_Render<T>['exports']>;
|
|
115
|
+
<T extends ReviewItem>(internal: unknown, props: ReturnType<__sveltets_Render<T>['props']> & {}): ReturnType<__sveltets_Render<T>['exports']>;
|
|
116
|
+
z_$$bindings?: ReturnType<__sveltets_Render<any>['bindings']>;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* A review list for a document: items grouped by page (and a "Document" group for the rest), filter segments with counts, previous / next
|
|
120
|
+
* with an "n of m" indicator and the `j`/`k` and `[`/`]` keys, host-defined actions with an optional confirmation and note, auto-advance when
|
|
121
|
+
* an action takes the item out of the filter, a detail snippet for the selected item and optional bulk selection. It drives a `PdfViewer`
|
|
122
|
+
* through `viewer` (its `goTo`) and `bind:selected` (the annotation shown as selected); `PdfReview` lays the two out side by side.
|
|
123
|
+
*/
|
|
124
|
+
declare const ReviewPanel: $$IsomorphicComponent;
|
|
125
|
+
type ReviewPanel<T extends ReviewItem> = InstanceType<typeof ReviewPanel<T>>;
|
|
126
|
+
export default ReviewPanel;
|
package/dist/assets.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** pdf.js asks the factory (main thread) for a file by kind and name; it answers with the bundled asset. */
|
|
2
|
+
export declare class BundledDataFactory {
|
|
3
|
+
fetch({ kind, filename }: {
|
|
4
|
+
kind: string;
|
|
5
|
+
filename: string;
|
|
6
|
+
}): Promise<Uint8Array>;
|
|
7
|
+
}
|
|
8
|
+
/** getDocument options that route the data files through the factory: the base URLs are placeholders that only name the kind. */
|
|
9
|
+
export declare function bundledDataOptions(found?: boolean): Record<string, unknown>;
|
package/dist/assets.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// The pdf.js data files (CMaps, standard fonts, wasm decoders) as Vite assets, and a pdf.js BinaryDataFactory that serves them by file
|
|
2
|
+
// name. Only imported together with pdf.js, when no data URLs were configured. Each file is its own hashed asset (never inlined as a
|
|
3
|
+
// data: URL, so `connect-src` needs nothing beyond 'self'), fetched only when a document needs it.
|
|
4
|
+
// Left out: the licences (not data); QuickJS, pdf.js's document-scripting sandbox, which this package never runs; and the JavaScript fallbacks
|
|
5
|
+
// of the wasm decoders, which pdf.js loads with import() from the worker by URL, so they only work with a real `wasmUrl` (configurePdf).
|
|
6
|
+
const files = import.meta.glob(['/node_modules/pdfjs-dist/cmaps/*.bcmap', '/node_modules/pdfjs-dist/standard_fonts/*', '/node_modules/pdfjs-dist/wasm/*', '!**/LICENSE*', '!**/quickjs*', '!**/*_nowasm_fallback.js'], {
|
|
7
|
+
query: '?url&no-inline',
|
|
8
|
+
import: 'default',
|
|
9
|
+
eager: true
|
|
10
|
+
});
|
|
11
|
+
const DIRS = { cMapUrl: 'cmaps', standardFontDataUrl: 'standard_fonts', wasmUrl: 'wasm' };
|
|
12
|
+
/** pdf.js asks the factory (main thread) for a file by kind and name; it answers with the bundled asset. */
|
|
13
|
+
export class BundledDataFactory {
|
|
14
|
+
async fetch({ kind, filename }) {
|
|
15
|
+
const url = files[`/node_modules/pdfjs-dist/${DIRS[kind]}/${filename}`];
|
|
16
|
+
if (!url)
|
|
17
|
+
throw new Error(`truss-pdf: no bundled ${kind} file ${filename}`);
|
|
18
|
+
const res = await fetch(url);
|
|
19
|
+
if (!res.ok)
|
|
20
|
+
throw new Error(`truss-pdf: ${kind} file ${filename} failed (${res.status})`);
|
|
21
|
+
return new Uint8Array(await res.arrayBuffer());
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** getDocument options that route the data files through the factory: the base URLs are placeholders that only name the kind. */
|
|
25
|
+
export function bundledDataOptions(found = Object.keys(files).length > 0) {
|
|
26
|
+
if (!found)
|
|
27
|
+
return {};
|
|
28
|
+
return { cMapUrl: 'truss-pdf/cmaps/', standardFontDataUrl: 'truss-pdf/standard_fonts/', wasmUrl: 'truss-pdf/wasm/', BinaryDataFactory: BundledDataFactory, useWorkerFetch: false };
|
|
29
|
+
}
|
package/dist/bidi.d.ts
ADDED
package/dist/bidi.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Bidi isolation for untrusted strings shown next to the document (annotation labels, quotes, file names). A string holding a
|
|
2
|
+
// right-to-left override (e.g. "invoicefdp.exe") must not reorder the text around it or disguise itself. In markup, wrap it in
|
|
3
|
+
// <bdi>; in plain strings (accessible names, tooltips, titles) use isolate(). Adapted from EvalBot.
|
|
4
|
+
const FSI = ''; // FIRST STRONG ISOLATE
|
|
5
|
+
const PDI = ''; // POP DIRECTIONAL ISOLATE
|
|
6
|
+
/** Wraps a string in FSI…PDI so its direction controls stay inside it. */
|
|
7
|
+
export function isolate(text) {
|
|
8
|
+
return `${FSI}${text ?? ''}${PDI}`;
|
|
9
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Attachment } from 'svelte/attachments';
|
|
2
|
+
type Value = string | number | null | undefined;
|
|
3
|
+
/**
|
|
4
|
+
* @internal Sets CSS properties (custom properties such as `--size`, or plain ones like `width`) on an element through the CSSOM (`el.style.setProperty`),
|
|
5
|
+
* which a Content-Security-Policy without `style-src 'unsafe-inline'` allows. Unlike `style=` / `style:` it renders nothing in server-rendered markup,
|
|
6
|
+
* so the component's scoped CSS must have a sensible fallback (`var(--x, default)`) for the first paint. Runs on the client after mount and re-runs when
|
|
7
|
+
* what `get` reads changes; `null` and `undefined` remove the property. A copy of the core's helper (the packages do not import core internals).
|
|
8
|
+
*/
|
|
9
|
+
export declare function cssvars(get: () => Record<string, Value>): Attachment<HTMLElement | SVGElement>;
|
|
10
|
+
/** @internal Like `cssvars` but for a whole declaration list (`'left: 4px; top: 2px'`), applied with `el.style.cssText` (CSSOM, CSP-safe). */
|
|
11
|
+
export declare function csstext(get: () => string): Attachment<HTMLElement | SVGElement>;
|
|
12
|
+
export {};
|
package/dist/cssvars.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @internal Sets CSS properties (custom properties such as `--size`, or plain ones like `width`) on an element through the CSSOM (`el.style.setProperty`),
|
|
3
|
+
* which a Content-Security-Policy without `style-src 'unsafe-inline'` allows. Unlike `style=` / `style:` it renders nothing in server-rendered markup,
|
|
4
|
+
* so the component's scoped CSS must have a sensible fallback (`var(--x, default)`) for the first paint. Runs on the client after mount and re-runs when
|
|
5
|
+
* what `get` reads changes; `null` and `undefined` remove the property. A copy of the core's helper (the packages do not import core internals).
|
|
6
|
+
*/
|
|
7
|
+
export function cssvars(get) {
|
|
8
|
+
return (el) => {
|
|
9
|
+
const now = get();
|
|
10
|
+
const set = [];
|
|
11
|
+
for (const k in now) {
|
|
12
|
+
const v = now[k];
|
|
13
|
+
if (v == null)
|
|
14
|
+
continue;
|
|
15
|
+
el.style.setProperty(k, String(v));
|
|
16
|
+
set.push(k);
|
|
17
|
+
}
|
|
18
|
+
return () => {
|
|
19
|
+
for (const k of set)
|
|
20
|
+
el.style.removeProperty(k);
|
|
21
|
+
};
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** @internal Like `cssvars` but for a whole declaration list (`'left: 4px; top: 2px'`), applied with `el.style.cssText` (CSSOM, CSP-safe). */
|
|
25
|
+
export function csstext(get) {
|
|
26
|
+
return (el) => {
|
|
27
|
+
el.style.cssText = get();
|
|
28
|
+
return () => {
|
|
29
|
+
el.style.cssText = '';
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { default as PdfViewer } from './PdfViewer.svelte';
|
|
2
|
+
export { default as PdfDialog } from './PdfDialog.svelte';
|
|
3
|
+
export { default as ReviewPanel } from './ReviewPanel.svelte';
|
|
4
|
+
export { default as PdfReview } from './PdfReview.svelte';
|
|
5
|
+
export type { PdfViewerLabels } from './PdfViewer.svelte';
|
|
6
|
+
export type { ReviewPanelLabels } from './ReviewPanel.svelte';
|
|
7
|
+
export type { PdfReviewLabels } from './PdfReview.svelte';
|
|
8
|
+
export { configurePdf, SAFE_PDF_OPTIONS, type PdfConfig } from './pdfjs.js';
|
|
9
|
+
export { findQuote, type QuoteMatch, type SegmentRange } from './quote-match.js';
|
|
10
|
+
export { isolate } from './bidi.js';
|
|
11
|
+
export type { PdfSource, PdfBox, PdfTarget, PdfGoToResult, PdfAnnotation, PdfAnnotationTone, PdfCreateDetail, ReviewItem, ReviewTone, ReviewFilter, ReviewConfirm, ReviewAction, ReviewActionDetail, ReviewStatuses, ReviewViewer } from './types.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { default as PdfViewer } from './PdfViewer.svelte';
|
|
2
|
+
export { default as PdfDialog } from './PdfDialog.svelte';
|
|
3
|
+
export { default as ReviewPanel } from './ReviewPanel.svelte';
|
|
4
|
+
export { default as PdfReview } from './PdfReview.svelte';
|
|
5
|
+
export { configurePdf, SAFE_PDF_OPTIONS } from './pdfjs.js';
|
|
6
|
+
export { findQuote } from './quote-match.js';
|
|
7
|
+
export { isolate } from './bidi.js';
|
package/dist/labels.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** One label: a string, or a function for a string with values (`(n: number) => \`${n} selected\``). That covers plurals and word order without an ICU dependency. */
|
|
2
|
+
export type LabelValue = string | ((...args: never[]) => string);
|
|
3
|
+
/** @internal The labels of a component: `prop` over the context over `configureLabels` over `defaults`, read at the moment a key is used. Call during component initialisation (it reads context). */
|
|
4
|
+
export declare function useLabels<T extends object>(component: string, defaults: T, prop: () => Partial<T> | undefined): T;
|
|
5
|
+
/** @internal One app-wide label for code outside a component (no context there): `configureLabels` over `fallback`. */
|
|
6
|
+
export declare function labelFor<T extends LabelValue>(component: string, key: string, fallback: T): T;
|
package/dist/labels.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { getContext } from 'svelte';
|
|
2
|
+
const KEY = Symbol.for('@ruckc/truss-ui:labels');
|
|
3
|
+
const STATE = Symbol.for('@ruckc/truss-ui:labels-config');
|
|
4
|
+
// What `configureLabels` set for a component. Read-only here (no copy of this file has to create the state), and `Object(undefined)` is `{}`.
|
|
5
|
+
const config = (component) => Object(Object(globalThis[STATE])[component]);
|
|
6
|
+
// The strongest defined value wins (layers run from the weakest to the strongest). This reader is written without branches on purpose
|
|
7
|
+
// (`filter`, `Object(x)`, no `?.` / `??` / `if`): it is copied into every package, and V8 coverage counts each short-circuit as a branch,
|
|
8
|
+
// so a copy would need a test under every combination of context and config to reach the per-file coverage floor.
|
|
9
|
+
const none = () => undefined;
|
|
10
|
+
const pick = (...layers) => layers.filter((v) => v !== undefined).at(-1);
|
|
11
|
+
/** @internal The labels of a component: `prop` over the context over `configureLabels` over `defaults`, read at the moment a key is used. Call during component initialisation (it reads context). */
|
|
12
|
+
export function useLabels(component, defaults, prop) {
|
|
13
|
+
const lookup = [getContext(KEY), none].filter(Boolean)[0];
|
|
14
|
+
const out = {};
|
|
15
|
+
for (const k of Object.keys(defaults))
|
|
16
|
+
Object.defineProperty(out, k, { enumerable: true, get: () => pick(labelFor(component, k, defaults[k]), Object(lookup(component))[k], Object(prop())[k]) });
|
|
17
|
+
return out;
|
|
18
|
+
}
|
|
19
|
+
/** @internal One app-wide label for code outside a component (no context there): `configureLabels` over `fallback`. */
|
|
20
|
+
export function labelFor(component, key, fallback) {
|
|
21
|
+
return pick(fallback, config(component)[key]);
|
|
22
|
+
}
|
|
23
|
+
// </reader>
|
package/dist/pages.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { PDFDocumentLoadingTask, PDFDocumentProxy, PDFPageProxy, PageViewport } from 'pdfjs-dist';
|
|
2
|
+
import type { TextContent } from 'pdfjs-dist/types/src/display/api';
|
|
3
|
+
import type { PdfBox } from './types.js';
|
|
4
|
+
/** Page size in CSS px at scale 1, rotation applied. */
|
|
5
|
+
export interface PageSize {
|
|
6
|
+
w: number;
|
|
7
|
+
h: number;
|
|
8
|
+
}
|
|
9
|
+
/** A rectangle as fractions of the page box (0..1 from the top-left of the rendered page), so it scales with the page. */
|
|
10
|
+
export interface Frac {
|
|
11
|
+
l: number;
|
|
12
|
+
t: number;
|
|
13
|
+
w: number;
|
|
14
|
+
h: number;
|
|
15
|
+
}
|
|
16
|
+
/** A link of the page: an external URL or an internal destination, at a place on the page. */
|
|
17
|
+
export interface PageLink {
|
|
18
|
+
rect: Frac;
|
|
19
|
+
url?: string;
|
|
20
|
+
dest?: string | unknown[];
|
|
21
|
+
}
|
|
22
|
+
/** An explicit destination resolved to a page and, when it names one, a point or region (page fractions). */
|
|
23
|
+
export interface ResolvedDest {
|
|
24
|
+
page: number;
|
|
25
|
+
rect?: Frac;
|
|
26
|
+
}
|
|
27
|
+
/** A user-space box as page fractions; `convertToViewportPoint` applies the view box origin (crop box) and the rotation. */
|
|
28
|
+
export declare function boxToFrac(vp: PageViewport, b: PdfBox): Frac;
|
|
29
|
+
/** The inverse of `boxToFrac`: page fractions back to a user-space box (rounded to 0.01 pt). */
|
|
30
|
+
export declare function fracToBox(vp: PageViewport, f: Frac): PdfBox;
|
|
31
|
+
/** How much of a rectangle lies on the page: `in` (all of it), `part` or `out`. */
|
|
32
|
+
export declare function onPage(f: Frac): 'in' | 'part' | 'out';
|
|
33
|
+
/** Only these links are followed by a plain click; anything else (javascript:, file:, data:, relative) is never made clickable. */
|
|
34
|
+
export declare function safeUrl(url: unknown): string | undefined;
|
|
35
|
+
export declare class PdfPages {
|
|
36
|
+
#private;
|
|
37
|
+
readonly pdf: PDFDocumentProxy;
|
|
38
|
+
constructor(task: PDFDocumentLoadingTask, pdf: PDFDocumentProxy);
|
|
39
|
+
get numPages(): number;
|
|
40
|
+
page(n: number): Promise<PDFPageProxy>;
|
|
41
|
+
/** The viewport at scale 1 (CSS px, rotation applied). */
|
|
42
|
+
viewport(n: number): Promise<PageViewport>;
|
|
43
|
+
size(n: number): Promise<PageSize>;
|
|
44
|
+
text(n: number): Promise<TextContent>;
|
|
45
|
+
/** The strings of a page's text items, in the order the text layer lays out its spans. */
|
|
46
|
+
strings(n: number): Promise<string[]>;
|
|
47
|
+
/** The page's link annotations, as page fractions (the PDF's own annotation layer is never rendered). */
|
|
48
|
+
links(n: number): Promise<PageLink[]>;
|
|
49
|
+
/** A named destination (else an outline item with that title, else an explicit destination array) resolved to its page and place. */
|
|
50
|
+
resolveDest(dest: string | unknown[]): Promise<ResolvedDest | null>;
|
|
51
|
+
/** The page rendered at `scale` device pixels per CSS px at scale 1 (cached). */
|
|
52
|
+
canvas(n: number, scale: number): Promise<HTMLCanvasElement>;
|
|
53
|
+
destroy(): void;
|
|
54
|
+
}
|
package/dist/pages.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/** Largest canvas rendered (pixels); a bigger render is scaled down (browsers cap the canvas area). */
|
|
2
|
+
const MAX_CANVAS_PIXELS = 16_000_000;
|
|
3
|
+
const MAX_CANVASES = 8;
|
|
4
|
+
/** A user-space box as page fractions; `convertToViewportPoint` applies the view box origin (crop box) and the rotation. */
|
|
5
|
+
export function boxToFrac(vp, b) {
|
|
6
|
+
const [x1, y1] = vp.convertToViewportPoint(b.x, b.y);
|
|
7
|
+
const [x2, y2] = vp.convertToViewportPoint(b.x + b.width, b.y + b.height);
|
|
8
|
+
return { l: Math.min(x1, x2) / vp.width, t: Math.min(y1, y2) / vp.height, w: Math.abs(x2 - x1) / vp.width, h: Math.abs(y2 - y1) / vp.height };
|
|
9
|
+
}
|
|
10
|
+
/** The inverse of `boxToFrac`: page fractions back to a user-space box (rounded to 0.01 pt). */
|
|
11
|
+
export function fracToBox(vp, f) {
|
|
12
|
+
const [x1, y1] = vp.convertToPdfPoint(f.l * vp.width, f.t * vp.height);
|
|
13
|
+
const [x2, y2] = vp.convertToPdfPoint((f.l + f.w) * vp.width, (f.t + f.h) * vp.height);
|
|
14
|
+
const r = (n) => Math.round(n * 100) / 100;
|
|
15
|
+
return { x: r(Math.min(x1, x2)), y: r(Math.min(y1, y2)), width: r(Math.abs(x2 - x1)), height: r(Math.abs(y2 - y1)) };
|
|
16
|
+
}
|
|
17
|
+
/** How much of a rectangle lies on the page: `in` (all of it), `part` or `out`. */
|
|
18
|
+
export function onPage(f) {
|
|
19
|
+
const e = 1e-6;
|
|
20
|
+
if (f.l + f.w <= 0 || f.t + f.h <= 0 || f.l >= 1 || f.t >= 1)
|
|
21
|
+
return 'out';
|
|
22
|
+
return f.l >= -e && f.t >= -e && f.l + f.w <= 1 + e && f.t + f.h <= 1 + e ? 'in' : 'part';
|
|
23
|
+
}
|
|
24
|
+
/** Only these links are followed by a plain click; anything else (javascript:, file:, data:, relative) is never made clickable. */
|
|
25
|
+
export function safeUrl(url) {
|
|
26
|
+
if (typeof url !== 'string')
|
|
27
|
+
return undefined;
|
|
28
|
+
try {
|
|
29
|
+
return /^(https?|mailto):$/.test(new URL(url).protocol) ? url : undefined;
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export class PdfPages {
|
|
36
|
+
pdf;
|
|
37
|
+
#task;
|
|
38
|
+
#pages = new Map();
|
|
39
|
+
#texts = new Map();
|
|
40
|
+
#canvases = new Map();
|
|
41
|
+
#destroyed = false;
|
|
42
|
+
constructor(task, pdf) {
|
|
43
|
+
this.#task = task;
|
|
44
|
+
this.pdf = pdf;
|
|
45
|
+
}
|
|
46
|
+
get numPages() {
|
|
47
|
+
return this.pdf.numPages;
|
|
48
|
+
}
|
|
49
|
+
page(n) {
|
|
50
|
+
let p = this.#pages.get(n);
|
|
51
|
+
if (!p) {
|
|
52
|
+
p = this.pdf.getPage(n);
|
|
53
|
+
this.#pages.set(n, p);
|
|
54
|
+
}
|
|
55
|
+
return p;
|
|
56
|
+
}
|
|
57
|
+
/** The viewport at scale 1 (CSS px, rotation applied). */
|
|
58
|
+
async viewport(n) {
|
|
59
|
+
return (await this.page(n)).getViewport({ scale: 1 });
|
|
60
|
+
}
|
|
61
|
+
async size(n) {
|
|
62
|
+
const vp = await this.viewport(n);
|
|
63
|
+
return { w: vp.width, h: vp.height };
|
|
64
|
+
}
|
|
65
|
+
text(n) {
|
|
66
|
+
let t = this.#texts.get(n);
|
|
67
|
+
if (!t) {
|
|
68
|
+
t = this.page(n).then((p) => p.getTextContent());
|
|
69
|
+
this.#texts.set(n, t);
|
|
70
|
+
}
|
|
71
|
+
return t;
|
|
72
|
+
}
|
|
73
|
+
/** The strings of a page's text items, in the order the text layer lays out its spans. */
|
|
74
|
+
async strings(n) {
|
|
75
|
+
return (await this.text(n)).items.map((i) => i.str); // no marked content: getTextContent() leaves it out
|
|
76
|
+
}
|
|
77
|
+
/** The page's link annotations, as page fractions (the PDF's own annotation layer is never rendered). */
|
|
78
|
+
async links(n) {
|
|
79
|
+
const page = await this.page(n);
|
|
80
|
+
const vp = page.getViewport({ scale: 1 });
|
|
81
|
+
const out = [];
|
|
82
|
+
for (const a of await page.getAnnotations({ intent: 'display' })) {
|
|
83
|
+
if (a.subtype !== 'Link')
|
|
84
|
+
continue;
|
|
85
|
+
const [x1, y1, x2, y2] = a.rect;
|
|
86
|
+
const rect = boxToFrac(vp, { x: x1, y: y1, width: x2 - x1, height: y2 - y1 });
|
|
87
|
+
const url = safeUrl(a.url);
|
|
88
|
+
if (url)
|
|
89
|
+
out.push({ rect, url });
|
|
90
|
+
else if (a.dest)
|
|
91
|
+
out.push({ rect, dest: a.dest });
|
|
92
|
+
}
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
/** A named destination (else an outline item with that title, else an explicit destination array) resolved to its page and place. */
|
|
96
|
+
async resolveDest(dest) {
|
|
97
|
+
const none = () => null;
|
|
98
|
+
let explicit = typeof dest === 'string' ? await this.pdf.getDestination(dest).catch(none) : dest;
|
|
99
|
+
if (!explicit && typeof dest === 'string') {
|
|
100
|
+
const flat = (items) => items.flatMap((i) => [i, ...flat(i.items)]);
|
|
101
|
+
const want = dest.trim().toLowerCase();
|
|
102
|
+
const hit = flat(((await this.pdf.getOutline()) ?? [])).find((i) => i.title.trim().toLowerCase() === want)?.dest;
|
|
103
|
+
explicit = typeof hit === 'string' ? await this.pdf.getDestination(hit).catch(none) : hit ?? null;
|
|
104
|
+
}
|
|
105
|
+
if (!Array.isArray(explicit) || !explicit.length)
|
|
106
|
+
return null;
|
|
107
|
+
const [ref, kind, ...args] = explicit;
|
|
108
|
+
const index = typeof ref === 'number' ? ref : await this.pdf.getPageIndex(ref).catch(none);
|
|
109
|
+
if (index === null)
|
|
110
|
+
return null;
|
|
111
|
+
const page = index + 1;
|
|
112
|
+
if (page < 1 || page > this.numPages)
|
|
113
|
+
return null;
|
|
114
|
+
const vp = await this.viewport(page);
|
|
115
|
+
const num = (v, d) => (typeof v === 'number' && Number.isFinite(v) ? v : d);
|
|
116
|
+
const [x0, y0, x1, y1] = vp.viewBox; // the crop box: [left, bottom, right, top]
|
|
117
|
+
switch (kind?.name) {
|
|
118
|
+
case 'XYZ': // left top zoom: a point, shown as a thin strip at that height
|
|
119
|
+
case 'FitH':
|
|
120
|
+
case 'FitBH': {
|
|
121
|
+
const top = num(kind.name === 'XYZ' ? args[1] : args[0], y1);
|
|
122
|
+
const left = kind.name === 'XYZ' ? num(args[0], x0) : x0;
|
|
123
|
+
return { page, rect: boxToFrac(vp, { x: left, y: top, width: 1, height: 0 }) };
|
|
124
|
+
}
|
|
125
|
+
case 'FitR': {
|
|
126
|
+
const [l, b, r, t] = args.map((v, i) => num(v, [x0, y0, x1, y1][i]));
|
|
127
|
+
return { page, rect: boxToFrac(vp, { x: l, y: b, width: r - l, height: t - b }) };
|
|
128
|
+
}
|
|
129
|
+
default:
|
|
130
|
+
return { page };
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
/** The page rendered at `scale` device pixels per CSS px at scale 1 (cached). */
|
|
134
|
+
canvas(n, scale) {
|
|
135
|
+
const key = `${n}@${scale.toFixed(3)}`;
|
|
136
|
+
const hit = this.#canvases.get(key);
|
|
137
|
+
if (hit) {
|
|
138
|
+
// refresh its LRU position
|
|
139
|
+
this.#canvases.delete(key);
|
|
140
|
+
this.#canvases.set(key, hit);
|
|
141
|
+
return hit;
|
|
142
|
+
}
|
|
143
|
+
const p = this.#render(n, scale);
|
|
144
|
+
this.#canvases.set(key, p);
|
|
145
|
+
p.catch(() => this.#canvases.delete(key));
|
|
146
|
+
while (this.#canvases.size > MAX_CANVASES)
|
|
147
|
+
this.#canvases.delete(this.#canvases.keys().next().value);
|
|
148
|
+
return p;
|
|
149
|
+
}
|
|
150
|
+
async #render(n, scale) {
|
|
151
|
+
const page = await this.page(n);
|
|
152
|
+
let vp = page.getViewport({ scale });
|
|
153
|
+
const area = vp.width * vp.height;
|
|
154
|
+
if (area > MAX_CANVAS_PIXELS)
|
|
155
|
+
vp = page.getViewport({ scale: scale * Math.sqrt(MAX_CANVAS_PIXELS / area) });
|
|
156
|
+
const canvas = document.createElement('canvas');
|
|
157
|
+
canvas.width = Math.max(1, Math.floor(vp.width));
|
|
158
|
+
canvas.height = Math.max(1, Math.floor(vp.height));
|
|
159
|
+
if (this.#destroyed)
|
|
160
|
+
throw new Error('Document closed');
|
|
161
|
+
await page.render({ canvas, viewport: vp }).promise;
|
|
162
|
+
return canvas;
|
|
163
|
+
}
|
|
164
|
+
destroy() {
|
|
165
|
+
this.#destroyed = true;
|
|
166
|
+
this.#canvases.clear();
|
|
167
|
+
this.#texts.clear();
|
|
168
|
+
this.#pages.clear();
|
|
169
|
+
this.#task.destroy().catch(() => undefined); // "Loading aborted" when destroyed while it starts
|
|
170
|
+
}
|
|
171
|
+
}
|
package/dist/paging.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export type Step = 1 | -1;
|
|
2
|
+
export declare class WheelPager {
|
|
3
|
+
#private;
|
|
4
|
+
private readonly onStep;
|
|
5
|
+
constructor(onStep: (dir: Step) => void);
|
|
6
|
+
/** Handles one wheel event on `scroller` (the element that may scroll natively). */
|
|
7
|
+
handle(e: WheelEvent, scroller: HTMLElement): void;
|
|
8
|
+
reset(): void;
|
|
9
|
+
}
|
|
10
|
+
/** Tracks one touch and reports a swipe (left/up = next page, right/down = previous). */
|
|
11
|
+
export declare class SwipePager {
|
|
12
|
+
#private;
|
|
13
|
+
private readonly onStep;
|
|
14
|
+
constructor(onStep: (dir: Step) => void);
|
|
15
|
+
start(e: TouchEvent): void;
|
|
16
|
+
/** `vertical`: also treat vertical swipes as page turns (when the page doesn't scroll). */
|
|
17
|
+
end(e: TouchEvent, vertical: boolean): void;
|
|
18
|
+
}
|
package/dist/paging.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// Turns wheel / trackpad / touch gestures into whole-page steps.
|
|
2
|
+
//
|
|
3
|
+
// Wheel: deltas are accumulated until they pass a threshold, then exactly one page is turned and the
|
|
4
|
+
// pager locks until the wheel has been quiet for a moment (a trackpad fling keeps sending decaying
|
|
5
|
+
// "momentum" events for a second or more; without the lock it would skip many pages). When the
|
|
6
|
+
// scroll container can scroll (a page taller than the viewport in fit-width mode, or a long text page),
|
|
7
|
+
// the wheel scrolls natively and only turns the page once the edge has been reached.
|
|
8
|
+
const THRESHOLD = 40; // px of accumulated delta for one page
|
|
9
|
+
const QUIET_MS = 160; // a gap this long ends a gesture
|
|
10
|
+
const MIN_LOCK_MS = 250;
|
|
11
|
+
const MAX_LOCK_MS = 2500; // a steady, continuous scroll still turns a page this often
|
|
12
|
+
const SWIPE_PX = 50;
|
|
13
|
+
export class WheelPager {
|
|
14
|
+
onStep;
|
|
15
|
+
#acc = 0;
|
|
16
|
+
#last = 0;
|
|
17
|
+
#lockedAt = 0;
|
|
18
|
+
#locked = false;
|
|
19
|
+
constructor(onStep) {
|
|
20
|
+
this.onStep = onStep;
|
|
21
|
+
}
|
|
22
|
+
/** Handles one wheel event on `scroller` (the element that may scroll natively). */
|
|
23
|
+
handle(e, scroller) {
|
|
24
|
+
if (e.ctrlKey)
|
|
25
|
+
return; // pinch-zoom / ctrl+wheel: leave to the browser
|
|
26
|
+
const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? scroller.clientHeight : 1;
|
|
27
|
+
const dx = e.deltaX * unit;
|
|
28
|
+
const dy = e.deltaY * unit;
|
|
29
|
+
const d = Math.abs(dx) > Math.abs(dy) ? dx : dy;
|
|
30
|
+
if (!d)
|
|
31
|
+
return;
|
|
32
|
+
const now = e.timeStamp || performance.now();
|
|
33
|
+
// Native scrolling inside a page taller than the viewport, until its edge.
|
|
34
|
+
const scrollable = scroller.scrollHeight > scroller.clientHeight + 1;
|
|
35
|
+
if (scrollable && Math.abs(dy) >= Math.abs(dx)) {
|
|
36
|
+
const atTop = scroller.scrollTop <= 0;
|
|
37
|
+
const atBottom = scroller.scrollTop + scroller.clientHeight >= scroller.scrollHeight - 1;
|
|
38
|
+
if ((dy > 0 && !atBottom) || (dy < 0 && !atTop)) {
|
|
39
|
+
// Treat as part of a gesture, so momentum reaching the edge doesn't also turn the page.
|
|
40
|
+
this.#lock(now);
|
|
41
|
+
this.#acc = 0;
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
e.preventDefault();
|
|
46
|
+
if (this.#locked) {
|
|
47
|
+
const quiet = now - this.#last >= QUIET_MS;
|
|
48
|
+
const held = now - this.#lockedAt;
|
|
49
|
+
if ((quiet && held >= MIN_LOCK_MS) || held >= MAX_LOCK_MS)
|
|
50
|
+
this.#locked = false;
|
|
51
|
+
else {
|
|
52
|
+
this.#last = now;
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
if (Math.sign(d) !== Math.sign(this.#acc))
|
|
57
|
+
this.#acc = 0;
|
|
58
|
+
this.#acc += d;
|
|
59
|
+
this.#last = now;
|
|
60
|
+
if (Math.abs(this.#acc) >= THRESHOLD) {
|
|
61
|
+
const dir = this.#acc > 0 ? 1 : -1;
|
|
62
|
+
this.#acc = 0;
|
|
63
|
+
this.#lock(now);
|
|
64
|
+
this.onStep(dir);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
#lock(now) {
|
|
68
|
+
if (!this.#locked)
|
|
69
|
+
this.#lockedAt = now;
|
|
70
|
+
this.#locked = true;
|
|
71
|
+
this.#last = now;
|
|
72
|
+
}
|
|
73
|
+
reset() {
|
|
74
|
+
this.#acc = 0;
|
|
75
|
+
this.#locked = false;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/** Tracks one touch and reports a swipe (left/up = next page, right/down = previous). */
|
|
79
|
+
export class SwipePager {
|
|
80
|
+
onStep;
|
|
81
|
+
#x = 0;
|
|
82
|
+
#y = 0;
|
|
83
|
+
#active = false;
|
|
84
|
+
constructor(onStep) {
|
|
85
|
+
this.onStep = onStep;
|
|
86
|
+
}
|
|
87
|
+
start(e) {
|
|
88
|
+
if (e.touches.length !== 1) {
|
|
89
|
+
this.#active = false;
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
this.#active = true;
|
|
93
|
+
this.#x = e.touches[0].clientX;
|
|
94
|
+
this.#y = e.touches[0].clientY;
|
|
95
|
+
}
|
|
96
|
+
/** `vertical`: also treat vertical swipes as page turns (when the page doesn't scroll). */
|
|
97
|
+
end(e, vertical) {
|
|
98
|
+
if (!this.#active || e.changedTouches.length !== 1)
|
|
99
|
+
return;
|
|
100
|
+
this.#active = false;
|
|
101
|
+
if (window.getSelection()?.toString())
|
|
102
|
+
return; // selecting text, not swiping
|
|
103
|
+
const dx = e.changedTouches[0].clientX - this.#x;
|
|
104
|
+
const dy = e.changedTouches[0].clientY - this.#y;
|
|
105
|
+
if (Math.abs(dx) >= SWIPE_PX && Math.abs(dx) > Math.abs(dy) * 1.5)
|
|
106
|
+
this.onStep(dx < 0 ? 1 : -1);
|
|
107
|
+
else if (vertical && Math.abs(dy) >= SWIPE_PX && Math.abs(dy) > Math.abs(dx) * 1.5)
|
|
108
|
+
this.onStep(dy < 0 ? 1 : -1);
|
|
109
|
+
}
|
|
110
|
+
}
|