@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,1184 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
@component
|
|
3
|
+
An inline PDF viewer built on pdf.js, with hardened defaults for untrusted documents: one page at a time, fitted to the page or to the
|
|
4
|
+
width, turned by whole pages (buttons, PgUp/PgDn, arrows, Home/End, wheel, trackpad and swipe), a selectable text layer, jumps to a page,
|
|
5
|
+
region, quote or destination, and host-supplied annotation overlays. Adapted from EvalBot's DocumentViewer.
|
|
6
|
+
-->
|
|
7
|
+
<script module lang="ts">
|
|
8
|
+
export type PdfViewerLabels = {
|
|
9
|
+
/** Accessible name of the page area when no `title` is given. */
|
|
10
|
+
document: string;
|
|
11
|
+
/** Accessible name of the toolbar. */
|
|
12
|
+
toolbar: string;
|
|
13
|
+
previous: string;
|
|
14
|
+
next: string;
|
|
15
|
+
/** Accessible name of the page number box. */
|
|
16
|
+
pageNumber: string;
|
|
17
|
+
/** After the page number box. */
|
|
18
|
+
of: (total: number) => string;
|
|
19
|
+
/** Announced on a page turn, and part of the page area's name. */
|
|
20
|
+
pageStatus: (page: number, total: number) => string;
|
|
21
|
+
/** Accessible name of the zoom switch. */
|
|
22
|
+
zoom: string;
|
|
23
|
+
fitPage: string;
|
|
24
|
+
fitWidth: string;
|
|
25
|
+
loading: string;
|
|
26
|
+
rendering: string;
|
|
27
|
+
loadFailed: string;
|
|
28
|
+
renderFailed: string;
|
|
29
|
+
retry: string;
|
|
30
|
+
/** The draw-a-box tool (shown with `oncreate`). */
|
|
31
|
+
drawBox: string;
|
|
32
|
+
/** Creates an annotation from the selected text (shown with `oncreate`). */
|
|
33
|
+
annotateSelection: string;
|
|
34
|
+
/** Accessible name of an annotation without a label (its 1-based position on the page). */
|
|
35
|
+
annotation: (n: number) => string;
|
|
36
|
+
quoteFound: string;
|
|
37
|
+
quotePartial: string;
|
|
38
|
+
quoteMissing: string;
|
|
39
|
+
regionFound: string;
|
|
40
|
+
regionPartial: string;
|
|
41
|
+
regionMissing: string;
|
|
42
|
+
/** Accessible name of a link of the document to a web address. */
|
|
43
|
+
link: (url: string) => string;
|
|
44
|
+
/** Accessible name of a link of the document to one of its pages. */
|
|
45
|
+
goToPage: (page: number) => string;
|
|
46
|
+
};
|
|
47
|
+
const DEFAULTS: PdfViewerLabels = {
|
|
48
|
+
document: 'Document',
|
|
49
|
+
toolbar: 'Document controls',
|
|
50
|
+
previous: 'Previous page',
|
|
51
|
+
next: 'Next page',
|
|
52
|
+
pageNumber: 'Page number',
|
|
53
|
+
of: (total) => `of ${total}`,
|
|
54
|
+
pageStatus: (page, total) => `Page ${page} of ${total}`,
|
|
55
|
+
zoom: 'Zoom',
|
|
56
|
+
fitPage: 'Fit page',
|
|
57
|
+
fitWidth: 'Fit width',
|
|
58
|
+
loading: 'Loading PDF',
|
|
59
|
+
rendering: 'Rendering page',
|
|
60
|
+
loadFailed: 'Could not load this PDF',
|
|
61
|
+
renderFailed: 'Could not render this page',
|
|
62
|
+
retry: 'Retry',
|
|
63
|
+
drawBox: 'Draw a box to annotate',
|
|
64
|
+
annotateSelection: 'Annotate the selected text',
|
|
65
|
+
annotation: (n) => `Annotation ${n}`,
|
|
66
|
+
quoteFound: 'Quote highlighted',
|
|
67
|
+
quotePartial: 'Part of the quote highlighted',
|
|
68
|
+
quoteMissing: 'Quote not found on this page',
|
|
69
|
+
regionFound: 'Area outlined',
|
|
70
|
+
regionPartial: 'The area lies partly outside the page',
|
|
71
|
+
regionMissing: 'The area lies outside the page',
|
|
72
|
+
link: (url) => `Link: ${url}`,
|
|
73
|
+
goToPage: (page) => `Go to page ${page}`
|
|
74
|
+
};
|
|
75
|
+
</script>
|
|
76
|
+
|
|
77
|
+
<script lang="ts">
|
|
78
|
+
import { tick, untrack, type Snippet } from 'svelte';
|
|
79
|
+
import type { HTMLAttributes } from 'svelte/elements';
|
|
80
|
+
import type { TextLayer } from 'pdfjs-dist';
|
|
81
|
+
import { Button, EmptyState, SegmentedControl, Spinner, Tag, Tooltip } from '@ruckc/truss-ui';
|
|
82
|
+
import { useLabels } from './labels.js';
|
|
83
|
+
import { cssvars, csstext } from './cssvars.js';
|
|
84
|
+
import { isolate } from './bidi.js';
|
|
85
|
+
import { loadPdfJs, openPdf } from './pdfjs.js';
|
|
86
|
+
import { findQuote, rangesBySegment } from './quote-match.js';
|
|
87
|
+
import { PdfPages, boxToFrac, fracToBox, onPage, type Frac, type PageLink, type PageSize, type ResolvedDest } from './pages.js';
|
|
88
|
+
import { SwipePager, WheelPager, type Step } from './paging.js';
|
|
89
|
+
import type { PdfAnnotation, PdfBox, PdfCreateDetail, PdfGoToResult, PdfSource, PdfTarget } from './types.js';
|
|
90
|
+
import type { PageViewport, PDFDocumentLoadingTask } from 'pdfjs-dist';
|
|
91
|
+
|
|
92
|
+
type Mode = 'page' | 'fit-width';
|
|
93
|
+
|
|
94
|
+
let {
|
|
95
|
+
src,
|
|
96
|
+
page = $bindable(1),
|
|
97
|
+
pageCount = $bindable(0),
|
|
98
|
+
mode = $bindable('page'),
|
|
99
|
+
annotations = [],
|
|
100
|
+
selected = $bindable(null),
|
|
101
|
+
onselect,
|
|
102
|
+
oncreate,
|
|
103
|
+
target,
|
|
104
|
+
targetKey,
|
|
105
|
+
ontarget,
|
|
106
|
+
onlink,
|
|
107
|
+
title,
|
|
108
|
+
height,
|
|
109
|
+
toolbar = true,
|
|
110
|
+
actions,
|
|
111
|
+
labels,
|
|
112
|
+
class: klass,
|
|
113
|
+
...rest
|
|
114
|
+
}: Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'class' | 'title'> & {
|
|
115
|
+
/** The document: a URL, or its bytes (`ArrayBuffer` or `Uint8Array`, copied before pdf.js takes them). Nothing loads until this is set. */
|
|
116
|
+
src?: PdfSource | null;
|
|
117
|
+
/** The 1-based page on screen. Bindable. */
|
|
118
|
+
page?: number;
|
|
119
|
+
/** The document's page count once loaded (0 before). Bindable, read-only. */
|
|
120
|
+
pageCount?: number;
|
|
121
|
+
/** `page` fits the whole page; `fit-width` fits the width and scrolls a tall page. Bindable. */
|
|
122
|
+
mode?: Mode;
|
|
123
|
+
/** Overlays drawn over the pages (never written into the PDF). Update the array to change them; selection is kept by id. */
|
|
124
|
+
annotations?: PdfAnnotation[];
|
|
125
|
+
/** The id of the emphasized annotation. Bindable: a click or Enter on an annotation sets it. */
|
|
126
|
+
selected?: string | null;
|
|
127
|
+
/** Called with an annotation's id when the user selects it (click, Enter or Space). */
|
|
128
|
+
onselect?: (id: string) => void;
|
|
129
|
+
/** Turns on creating annotations: a draw-a-box tool and an "annotate the selected text" button. Called with what was drawn or selected. */
|
|
130
|
+
oncreate?: (detail: PdfCreateDetail) => void;
|
|
131
|
+
/** Where to go: applied when the document has loaded, and again when `target` or `targetKey` changes. */
|
|
132
|
+
target?: PdfTarget | null;
|
|
133
|
+
/** Change it to apply the same `target` again (e.g. a counter). */
|
|
134
|
+
targetKey?: unknown;
|
|
135
|
+
/** Called with the outcome of each `target` (and `goTo`), so the host can say "quote not found on page 4". */
|
|
136
|
+
ontarget?: (result: PdfGoToResult, target: PdfTarget) => void;
|
|
137
|
+
/**
|
|
138
|
+
* Called when the user activates a link of the document to a web address, instead of opening it, so the host can ask first. Without it,
|
|
139
|
+
* http(s) and mailto links open in a new tab with `rel="noopener noreferrer"`; other schemes are never clickable.
|
|
140
|
+
*/
|
|
141
|
+
onlink?: (url: string) => void;
|
|
142
|
+
/** The document's name, for the page area's accessible name (bidi-isolated). */
|
|
143
|
+
title?: string;
|
|
144
|
+
/** CSS height (px when a number). Default: 32rem; `100%` fills a sized parent. */
|
|
145
|
+
height?: number | string;
|
|
146
|
+
/** Show the toolbar (paging, page number, zoom, create tools). */
|
|
147
|
+
toolbar?: boolean;
|
|
148
|
+
/** Extra controls at the end of the toolbar (a download button, a close button). */
|
|
149
|
+
actions?: Snippet;
|
|
150
|
+
labels?: Partial<PdfViewerLabels>;
|
|
151
|
+
class?: string;
|
|
152
|
+
} = $props();
|
|
153
|
+
|
|
154
|
+
const L = useLabels('PdfViewer', DEFAULTS, () => labels);
|
|
155
|
+
const uid = $props.id();
|
|
156
|
+
const PAD = 12; // px around the page inside the stage
|
|
157
|
+
|
|
158
|
+
// ───── the document
|
|
159
|
+
let doc = $state.raw<PdfPages | null>(null);
|
|
160
|
+
let docId = $state(0);
|
|
161
|
+
let status = $state<'idle' | 'loading' | 'ready' | 'error'>('idle');
|
|
162
|
+
let loadError = $state('');
|
|
163
|
+
let retry = $state(0);
|
|
164
|
+
/** Resolves with the document being loaded (or null when it fails or is replaced), for `goTo` calls made before it is ready. */
|
|
165
|
+
let pending: Promise<PdfPages | null> = Promise.resolve(null);
|
|
166
|
+
/** An error's text without its class name (`InvalidPDFException: Invalid PDF structure.` → `Invalid PDF structure.`). */
|
|
167
|
+
const message = (e: unknown) => String(e).replace(/^[\w.]*(Error|Exception): /, '');
|
|
168
|
+
/** For failures that only cost an extra (a prefetched page, a text layer, links): the page image still shows. */
|
|
169
|
+
const ignore = () => undefined;
|
|
170
|
+
|
|
171
|
+
$effect(() => {
|
|
172
|
+
const s = src;
|
|
173
|
+
void retry;
|
|
174
|
+
let done!: (d: PdfPages | null) => void;
|
|
175
|
+
pending = new Promise((r) => (done = r));
|
|
176
|
+
let cancelled = false;
|
|
177
|
+
let task: PDFDocumentLoadingTask | undefined;
|
|
178
|
+
untrack(() => {
|
|
179
|
+
doc = null;
|
|
180
|
+
status = s ? 'loading' : 'idle';
|
|
181
|
+
loadError = '';
|
|
182
|
+
pageCount = 0;
|
|
183
|
+
});
|
|
184
|
+
if (s)
|
|
185
|
+
openPdf(s)
|
|
186
|
+
.then(async (t) => {
|
|
187
|
+
if (cancelled) return void t.destroy().catch(ignore); // a task destroyed while it starts rejects with "Loading aborted"
|
|
188
|
+
task = t;
|
|
189
|
+
const pdf = await t.promise;
|
|
190
|
+
if (cancelled) return;
|
|
191
|
+
const d = new PdfPages(t, pdf);
|
|
192
|
+
docId++;
|
|
193
|
+
doc = d;
|
|
194
|
+
pageCount = pdf.numPages;
|
|
195
|
+
page = Math.min(Math.max(1, Math.round(page)), pdf.numPages);
|
|
196
|
+
status = 'ready';
|
|
197
|
+
done(d);
|
|
198
|
+
})
|
|
199
|
+
.catch((e: unknown) => {
|
|
200
|
+
if (cancelled) return;
|
|
201
|
+
status = 'error';
|
|
202
|
+
loadError = message(e);
|
|
203
|
+
done(null);
|
|
204
|
+
});
|
|
205
|
+
else done(null);
|
|
206
|
+
return () => {
|
|
207
|
+
cancelled = true;
|
|
208
|
+
done(null);
|
|
209
|
+
task?.destroy().catch(ignore);
|
|
210
|
+
};
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
const total = $derived(doc ? doc.numPages : 0);
|
|
214
|
+
/** Identifies the page on screen of the document on screen. */
|
|
215
|
+
const curKey = $derived(`${docId}:${page}`);
|
|
216
|
+
|
|
217
|
+
// ───── paging
|
|
218
|
+
let stageEl = $state<HTMLDivElement>();
|
|
219
|
+
let pageEl = $state<HTMLDivElement>();
|
|
220
|
+
/** Where the scroll position goes after a page turn (a page taller than the stage). */
|
|
221
|
+
let enterAt: 'top' | 'bottom' = 'top';
|
|
222
|
+
let goSeq = 0;
|
|
223
|
+
|
|
224
|
+
function go(n: number, from: 'top' | 'bottom' = 'top') {
|
|
225
|
+
const next = Math.min(Math.max(1, Math.round(n)), total);
|
|
226
|
+
if (next === page) return;
|
|
227
|
+
enterAt = from;
|
|
228
|
+
page = next;
|
|
229
|
+
}
|
|
230
|
+
/** A page turn by the user: drops a pending jump so it cannot pull the view back. */
|
|
231
|
+
function turn(n: number, from: 'top' | 'bottom' = 'top') {
|
|
232
|
+
goSeq++;
|
|
233
|
+
reveal = null;
|
|
234
|
+
go(n, from);
|
|
235
|
+
}
|
|
236
|
+
const step = (dir: Step, fromEdge = false) => turn(page + dir, fromEdge && dir < 0 ? 'bottom' : 'top');
|
|
237
|
+
const scrolls = () => !!stageEl && stageEl.scrollHeight > stageEl.clientHeight + 1;
|
|
238
|
+
|
|
239
|
+
const pager = new WheelPager((dir) => step(dir, true));
|
|
240
|
+
const swiper = new SwipePager((dir) => step(dir));
|
|
241
|
+
|
|
242
|
+
$effect(() => {
|
|
243
|
+
const el = stageEl!;
|
|
244
|
+
const onWheel = (e: WheelEvent) => pager.handle(e, el);
|
|
245
|
+
el.addEventListener('wheel', onWheel, { passive: false });
|
|
246
|
+
return () => el.removeEventListener('wheel', onWheel);
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
// a new page starts at its top (or its bottom when reached by scrolling up), unless a jump is about to place it
|
|
250
|
+
$effect(() => {
|
|
251
|
+
void curKey;
|
|
252
|
+
const el = stageEl!;
|
|
253
|
+
void tick().then(() => {
|
|
254
|
+
if (reveal?.page !== page) el.scrollTop = enterAt === 'bottom' ? el.scrollHeight : 0;
|
|
255
|
+
enterAt = 'top';
|
|
256
|
+
});
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
let pageInput = $derived(String(page));
|
|
260
|
+
function commitPageInput() {
|
|
261
|
+
const n = Number.parseInt(pageInput, 10);
|
|
262
|
+
if (Number.isFinite(n)) turn(n);
|
|
263
|
+
pageInput = String(page);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function typing(t: EventTarget | null) {
|
|
267
|
+
return t instanceof HTMLElement && !!t.closest('input, textarea, select, [contenteditable="true"], [role="radiogroup"], [role="listbox"], [role="menu"]');
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function onKey(e: KeyboardEvent) {
|
|
271
|
+
if (e.key === 'Escape' && drawing) {
|
|
272
|
+
drawing = false;
|
|
273
|
+
draft = null;
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey || !total || typing(e.target)) return;
|
|
277
|
+
switch (e.key) {
|
|
278
|
+
case 'ArrowRight':
|
|
279
|
+
case 'PageDown':
|
|
280
|
+
step(1);
|
|
281
|
+
break;
|
|
282
|
+
case 'ArrowLeft':
|
|
283
|
+
case 'PageUp':
|
|
284
|
+
step(-1);
|
|
285
|
+
break;
|
|
286
|
+
case 'ArrowDown':
|
|
287
|
+
case 'ArrowUp':
|
|
288
|
+
if (scrolls()) return; // the arrows scroll a tall page; PgUp/PgDn still turn it
|
|
289
|
+
step(e.key === 'ArrowDown' ? 1 : -1);
|
|
290
|
+
break;
|
|
291
|
+
case 'Home':
|
|
292
|
+
turn(1);
|
|
293
|
+
break;
|
|
294
|
+
case 'End':
|
|
295
|
+
turn(total);
|
|
296
|
+
break;
|
|
297
|
+
default:
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
e.preventDefault();
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// ───── stage size → fit scale
|
|
304
|
+
let stageW = $state(0);
|
|
305
|
+
let stageH = $state(0);
|
|
306
|
+
/** Debounced copy of the stage size (and pixel ratio) the canvas is rendered for. */
|
|
307
|
+
let renderBox = $state({ w: 0, h: 0, dpr: 1 });
|
|
308
|
+
|
|
309
|
+
$effect(() => {
|
|
310
|
+
const el = stageEl!;
|
|
311
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
312
|
+
const measure = () => {
|
|
313
|
+
stageW = el.clientWidth;
|
|
314
|
+
stageH = el.clientHeight;
|
|
315
|
+
};
|
|
316
|
+
const commit = () => (renderBox = { w: el.clientWidth, h: el.clientHeight, dpr: window.devicePixelRatio });
|
|
317
|
+
measure();
|
|
318
|
+
commit();
|
|
319
|
+
const ro = new ResizeObserver(() => {
|
|
320
|
+
measure();
|
|
321
|
+
clearTimeout(timer);
|
|
322
|
+
timer = setTimeout(commit, 150);
|
|
323
|
+
});
|
|
324
|
+
ro.observe(el);
|
|
325
|
+
return () => {
|
|
326
|
+
ro.disconnect();
|
|
327
|
+
clearTimeout(timer);
|
|
328
|
+
};
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
function fitScale(d: PageSize, w: number, h: number, m: Mode) {
|
|
332
|
+
const aw = Math.max(40, w - 2 * PAD);
|
|
333
|
+
const ah = Math.max(40, h - 2 * PAD);
|
|
334
|
+
return m === 'page' ? Math.min(aw / d.w, ah / d.h) : aw / d.w;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// ───── the page: size and viewport, canvas, text layer
|
|
338
|
+
let vp1 = $state.raw<PageViewport | null>(null);
|
|
339
|
+
let vpKey = $state('');
|
|
340
|
+
let canvasHost = $state<HTMLDivElement>();
|
|
341
|
+
let textLayerEl = $state<HTMLDivElement>();
|
|
342
|
+
let rendering = $state(false);
|
|
343
|
+
let renderError = $state('');
|
|
344
|
+
|
|
345
|
+
$effect(() => {
|
|
346
|
+
const d = doc;
|
|
347
|
+
if (!d) return;
|
|
348
|
+
// a page set from outside is clamped to the document
|
|
349
|
+
const n = Math.min(Math.max(1, Math.round(page)), d.numPages);
|
|
350
|
+
if (n !== page) return void (page = n);
|
|
351
|
+
const key = curKey;
|
|
352
|
+
let stale = false;
|
|
353
|
+
d.viewport(n)
|
|
354
|
+
.then((vp) => {
|
|
355
|
+
if (stale) return;
|
|
356
|
+
vp1 = vp;
|
|
357
|
+
vpKey = key;
|
|
358
|
+
})
|
|
359
|
+
.catch(ignore);
|
|
360
|
+
return () => {
|
|
361
|
+
stale = true;
|
|
362
|
+
};
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
const pageReady = $derived(!!doc && !!vp1 && vpKey === curKey);
|
|
366
|
+
const dims = $derived<PageSize | null>(vp1 ? { w: vp1.width, h: vp1.height } : null);
|
|
367
|
+
// the stage is measured when it mounts, before any page size is known
|
|
368
|
+
const cssScale = $derived(dims ? fitScale(dims, stageW, stageH, mode) : 0);
|
|
369
|
+
const pageBox = $derived({ w: (dims?.w ?? 0) * cssScale, h: (dims?.h ?? 0) * cssScale });
|
|
370
|
+
const renderScale = $derived(dims ? Math.round(fitScale(dims, renderBox.w, renderBox.h, mode) * renderBox.dpr * 1000) / 1000 : 0);
|
|
371
|
+
|
|
372
|
+
// the canvas, rendered at the debounced size × devicePixelRatio; the neighbouring pages are rendered ahead
|
|
373
|
+
$effect(() => {
|
|
374
|
+
const n = page;
|
|
375
|
+
const s = renderScale;
|
|
376
|
+
const host = canvasHost;
|
|
377
|
+
const box = renderBox;
|
|
378
|
+
const m = mode;
|
|
379
|
+
if (!pageReady || !host) return;
|
|
380
|
+
const d = doc!;
|
|
381
|
+
let stale = false;
|
|
382
|
+
let shown = false;
|
|
383
|
+
renderError = '';
|
|
384
|
+
d.canvas(n, s).then(
|
|
385
|
+
(c) => {
|
|
386
|
+
if (stale) return;
|
|
387
|
+
shown = true;
|
|
388
|
+
rendering = false;
|
|
389
|
+
host.replaceChildren(c);
|
|
390
|
+
host.dataset.page = String(n);
|
|
391
|
+
for (const k of [n + 1, n - 1]) {
|
|
392
|
+
if (k < 1 || k > d.numPages) continue;
|
|
393
|
+
d.size(k)
|
|
394
|
+
.then((z) => (stale ? undefined : d.canvas(k, Math.round(fitScale(z, box.w, box.h, m) * box.dpr * 1000) / 1000)))
|
|
395
|
+
.catch(ignore);
|
|
396
|
+
}
|
|
397
|
+
},
|
|
398
|
+
(e: unknown) => {
|
|
399
|
+
if (stale) return;
|
|
400
|
+
rendering = false;
|
|
401
|
+
renderError = message(e);
|
|
402
|
+
}
|
|
403
|
+
);
|
|
404
|
+
// only show "rendering" (and blank a different page still on screen) when the render is not immediate
|
|
405
|
+
const t = setTimeout(() => {
|
|
406
|
+
if (shown) return;
|
|
407
|
+
rendering = true;
|
|
408
|
+
if (host.dataset.page !== String(n)) host.replaceChildren();
|
|
409
|
+
}, 60);
|
|
410
|
+
return () => {
|
|
411
|
+
stale = true;
|
|
412
|
+
clearTimeout(t);
|
|
413
|
+
};
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
// the text layer, rebuilt per page (it follows the page size through --total-scale-factor)
|
|
417
|
+
let layerKey = $state('');
|
|
418
|
+
let layerDivs: HTMLElement[] = [];
|
|
419
|
+
let layerStrs: string[] = [];
|
|
420
|
+
|
|
421
|
+
$effect(() => {
|
|
422
|
+
const n = page;
|
|
423
|
+
const el = textLayerEl;
|
|
424
|
+
const key = curKey;
|
|
425
|
+
if (!pageReady || !el) return;
|
|
426
|
+
const d = doc!;
|
|
427
|
+
let stale = false;
|
|
428
|
+
let layer: TextLayer | null = null;
|
|
429
|
+
el.replaceChildren();
|
|
430
|
+
layerKey = '';
|
|
431
|
+
Promise.all([loadPdfJs(), d.page(n), d.text(n)])
|
|
432
|
+
.then(async ([pdfjs, pg, tc]) => {
|
|
433
|
+
if (stale) return;
|
|
434
|
+
layer = new pdfjs.TextLayer({ textContentSource: tc, container: el, viewport: pg.getViewport({ scale: untrack(() => cssScale) }) });
|
|
435
|
+
await layer.render(); // cancel() makes it reject
|
|
436
|
+
layerDivs = layer.textDivs;
|
|
437
|
+
layerStrs = layer.textContentItemsStr;
|
|
438
|
+
layerKey = key;
|
|
439
|
+
})
|
|
440
|
+
.catch(ignore); // a cancelled or failed text layer only loses selection and highlights
|
|
441
|
+
return () => {
|
|
442
|
+
stale = true;
|
|
443
|
+
layer?.cancel();
|
|
444
|
+
};
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
// ───── geometry helpers
|
|
448
|
+
const pct = (v: number) => `${(v * 100).toFixed(4)}%`;
|
|
449
|
+
const clampFrac = (f: Frac): Frac => {
|
|
450
|
+
const l = Math.max(0, f.l);
|
|
451
|
+
const t = Math.max(0, f.t);
|
|
452
|
+
return { l, t, w: Math.max(0, Math.min(1, f.l + f.w) - l), h: Math.max(0, Math.min(1, f.t + f.h) - t) };
|
|
453
|
+
};
|
|
454
|
+
const rectCss = (f: Frac) => {
|
|
455
|
+
const c = clampFrac(f);
|
|
456
|
+
return `left: ${pct(c.l)}; top: ${pct(c.t)}; width: ${pct(c.w)}; height: ${pct(c.h)}`;
|
|
457
|
+
};
|
|
458
|
+
const union = (rs: Frac[]): Frac | undefined => {
|
|
459
|
+
if (!rs.length) return undefined;
|
|
460
|
+
const l = Math.min(...rs.map((r) => r.l));
|
|
461
|
+
const t = Math.min(...rs.map((r) => r.t));
|
|
462
|
+
return { l, t, w: Math.max(...rs.map((r) => r.l + r.w)) - l, h: Math.max(...rs.map((r) => r.t + r.h)) - t };
|
|
463
|
+
};
|
|
464
|
+
|
|
465
|
+
/** Client rects as page fractions, joined per line (a selection or a match yields one rect per text span). */
|
|
466
|
+
function toFracs(rects: Iterable<DOMRect>): Frac[] {
|
|
467
|
+
const base = pageEl!.getBoundingClientRect();
|
|
468
|
+
const fs = [...rects]
|
|
469
|
+
.filter((r) => r.width > 0 && r.height > 0)
|
|
470
|
+
.map((r) => ({ l: (r.left - base.left) / base.width, t: (r.top - base.top) / base.height, w: r.width / base.width, h: r.height / base.height }))
|
|
471
|
+
.sort((a, b) => a.t - b.t || a.l - b.l);
|
|
472
|
+
const out: Frac[] = [];
|
|
473
|
+
for (const f of fs) {
|
|
474
|
+
const last = out.at(-1);
|
|
475
|
+
if (last && Math.abs(f.t - last.t) < Math.min(f.h, last.h) / 2) {
|
|
476
|
+
const r = Math.max(last.l + last.w, f.l + f.w);
|
|
477
|
+
const b = Math.max(last.t + last.h, f.t + f.h);
|
|
478
|
+
last.l = Math.min(last.l, f.l);
|
|
479
|
+
last.t = Math.min(last.t, f.t);
|
|
480
|
+
last.w = r - last.l;
|
|
481
|
+
last.h = b - last.t;
|
|
482
|
+
} else out.push({ ...f });
|
|
483
|
+
}
|
|
484
|
+
return out;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/** Where a quote is on the page on screen (needs its text layer). */
|
|
488
|
+
function quoteRects(q: string): Frac[] {
|
|
489
|
+
const m = findQuote(layerStrs, q);
|
|
490
|
+
if (!m) return [];
|
|
491
|
+
const rects: DOMRect[] = [];
|
|
492
|
+
for (const [seg, ranges] of rangesBySegment(m)) {
|
|
493
|
+
const node = layerDivs[seg].firstChild!;
|
|
494
|
+
for (const [a, b] of ranges) {
|
|
495
|
+
const r = document.createRange();
|
|
496
|
+
r.setStart(node, a);
|
|
497
|
+
r.setEnd(node, b);
|
|
498
|
+
rects.push(...r.getClientRects());
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
return toFracs(rects);
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// ───── jumps
|
|
505
|
+
type Hl = { page: number; kind: 'region' | 'quote'; status: PdfGoToResult; rect?: Frac; quote?: string };
|
|
506
|
+
/** The outlined region or highlighted quote of the last jump. */
|
|
507
|
+
let hl = $state.raw<Hl | null>(null);
|
|
508
|
+
/** A place to scroll into view once its page is on screen: a rect, an annotation (by id) or the highlighted quote. */
|
|
509
|
+
let reveal = $state.raw<{ page: number; rect?: Frac; id?: string; quote?: boolean; focus?: boolean } | null>(null);
|
|
510
|
+
|
|
511
|
+
/** Shows a page and what to bring into view, unless a newer jump (or a page turn) came first. */
|
|
512
|
+
function show(seq: number, p: number, h: Hl | null, r: typeof reveal) {
|
|
513
|
+
if (seq !== goSeq) return;
|
|
514
|
+
hl = h;
|
|
515
|
+
reveal = r;
|
|
516
|
+
go(p);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
async function apply(d: PdfPages, t: PdfTarget, seq: number): Promise<PdfGoToResult> {
|
|
520
|
+
const n = d.numPages;
|
|
521
|
+
const valid = (p: unknown): p is number => typeof p === 'number' && Number.isInteger(p) && p >= 1 && p <= n;
|
|
522
|
+
if ('annotation' in t) {
|
|
523
|
+
const a = annotations.find((x) => x.id === t.annotation);
|
|
524
|
+
if (!a || !valid(a.page)) return 'missing';
|
|
525
|
+
let result: PdfGoToResult = 'found';
|
|
526
|
+
if ('quote' in a.target) {
|
|
527
|
+
const m = findQuote(await d.strings(a.page), a.target.quote);
|
|
528
|
+
if (!m) return 'missing';
|
|
529
|
+
result = m.exact ? 'found' : 'partial';
|
|
530
|
+
} else {
|
|
531
|
+
const vp = await d.viewport(a.page);
|
|
532
|
+
if (!a.target.boxes.some((b) => onPage(boxToFrac(vp, b)) !== 'out')) return 'missing';
|
|
533
|
+
}
|
|
534
|
+
show(seq, a.page, null, { page: a.page, id: a.id, focus: t.focus });
|
|
535
|
+
return result;
|
|
536
|
+
}
|
|
537
|
+
if ('dest' in t) {
|
|
538
|
+
const r = await d.resolveDest(t.dest);
|
|
539
|
+
if (!r) return 'missing';
|
|
540
|
+
show(seq, r.page, null, { page: r.page, rect: r.rect });
|
|
541
|
+
return 'found';
|
|
542
|
+
}
|
|
543
|
+
if ('quote' in t && typeof t.quote === 'string') {
|
|
544
|
+
const from = valid(t.page) ? t.page : page;
|
|
545
|
+
const order = t.strict && valid(t.page) ? [from] : [from, ...Array.from({ length: n }, (_, i) => i + 1).filter((k) => k !== from).sort((a, b) => Math.abs(a - from) - Math.abs(b - from) || a - b)];
|
|
546
|
+
let partial: number | null = null;
|
|
547
|
+
for (const k of order) {
|
|
548
|
+
const m = findQuote(await d.strings(k), t.quote);
|
|
549
|
+
if (m?.exact) {
|
|
550
|
+
show(seq, k, { page: k, kind: 'quote', status: 'found', quote: t.quote }, { page: k, quote: true });
|
|
551
|
+
return 'found';
|
|
552
|
+
}
|
|
553
|
+
partial ??= m ? k : null;
|
|
554
|
+
}
|
|
555
|
+
if (partial !== null) {
|
|
556
|
+
show(seq, partial, { page: partial, kind: 'quote', status: 'partial', quote: t.quote }, { page: partial, quote: true });
|
|
557
|
+
return 'partial';
|
|
558
|
+
}
|
|
559
|
+
show(seq, from, { page: from, kind: 'quote', status: 'missing' }, null);
|
|
560
|
+
return 'missing';
|
|
561
|
+
}
|
|
562
|
+
if (!valid(t.page)) return 'missing';
|
|
563
|
+
if (typeof t.x === 'number') {
|
|
564
|
+
const rect = boxToFrac(await d.viewport(t.page), t as PdfBox);
|
|
565
|
+
const where = onPage(rect);
|
|
566
|
+
const status: PdfGoToResult = where === 'in' ? 'found' : where === 'part' ? 'partial' : 'missing';
|
|
567
|
+
show(seq, t.page, { page: t.page, kind: 'region', status, rect }, where === 'out' ? null : { page: t.page, rect });
|
|
568
|
+
return status;
|
|
569
|
+
}
|
|
570
|
+
show(seq, t.page, null, null);
|
|
571
|
+
return 'found';
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* Goes to a page, a region, a quote, a destination or an annotation, and resolves with `found`, `partial` or `missing` once it is known
|
|
576
|
+
* (it waits for the document to load). A newer `goTo`, `target` or page turn by the user wins over one still in flight.
|
|
577
|
+
*/
|
|
578
|
+
export async function goTo(t: PdfTarget): Promise<PdfGoToResult> {
|
|
579
|
+
const seq = ++goSeq;
|
|
580
|
+
const d = doc ?? (await pending);
|
|
581
|
+
const result = d ? await apply(d, t, seq) : 'missing';
|
|
582
|
+
if (seq === goSeq) ontarget?.(result, t);
|
|
583
|
+
return result;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
// the declarative target: applied once the document is ready, and again when the target or its key changes
|
|
587
|
+
$effect(() => {
|
|
588
|
+
const t = target;
|
|
589
|
+
void targetKey;
|
|
590
|
+
if (!t || !doc) return;
|
|
591
|
+
untrack(() => void goTo(t));
|
|
592
|
+
});
|
|
593
|
+
|
|
594
|
+
// quote rects for the page on screen: quote annotations and the highlighted quote, once its text layer is in
|
|
595
|
+
let quoteHits = $state.raw<Record<string, Frac[]>>({});
|
|
596
|
+
const HL = '\u0000hl';
|
|
597
|
+
$effect(() => {
|
|
598
|
+
if (!layerKey || layerKey !== curKey) return;
|
|
599
|
+
const n = page;
|
|
600
|
+
const qs: [string, string][] = [];
|
|
601
|
+
for (const a of annotations) if (a.page === n && 'quote' in a.target) qs.push([a.id, a.target.quote]);
|
|
602
|
+
if (hl?.kind === 'quote' && hl.page === n && hl.quote) qs.push([HL, hl.quote]);
|
|
603
|
+
untrack(() => (quoteHits = Object.fromEntries(qs.map(([id, q]) => [id, quoteRects(q)]))));
|
|
604
|
+
});
|
|
605
|
+
|
|
606
|
+
/** The annotations of the page on screen, in reading order (the keyboard reaches them in this order). */
|
|
607
|
+
const shown = $derived.by(() => {
|
|
608
|
+
const vp = vp1;
|
|
609
|
+
if (!vp || vpKey !== curKey) return [];
|
|
610
|
+
return annotations
|
|
611
|
+
.filter((a) => a.page === page)
|
|
612
|
+
.map((a) => ({ a, rects: 'boxes' in a.target ? a.target.boxes.map((b) => boxToFrac(vp, b)).filter((f) => onPage(f) !== 'out') : (quoteHits[a.id] ?? []) }))
|
|
613
|
+
.filter((x) => x.rects.length > 0)
|
|
614
|
+
.sort((x, y) => Math.round((x.rects[0].t - y.rects[0].t) * 200) || x.rects[0].l - y.rects[0].l);
|
|
615
|
+
});
|
|
616
|
+
const hlRects = $derived(hl && hl.page === page && hl.status !== 'missing' ? (hl.kind === 'region' ? [hl.rect!] : (quoteHits[HL] ?? [])) : []);
|
|
617
|
+
|
|
618
|
+
// bring a jump's target into view (fit width: centred when it fits, else its top), and focus an annotation when asked
|
|
619
|
+
$effect(() => {
|
|
620
|
+
const h = pageBox.h;
|
|
621
|
+
const r = reveal;
|
|
622
|
+
const el = stageEl!;
|
|
623
|
+
const pg = pageEl;
|
|
624
|
+
if (!r || r.page !== page || !pageReady || !pg) return;
|
|
625
|
+
const rect = r.id ? union(shown.find((s) => s.a.id === r.id)?.rects ?? []) : r.quote ? union(hlRects) : r.rect;
|
|
626
|
+
if (!rect && (r.id || r.quote)) return; // waiting for the text layer
|
|
627
|
+
untrack(() => {
|
|
628
|
+
reveal = null;
|
|
629
|
+
void tick().then(() => {
|
|
630
|
+
if (rect) {
|
|
631
|
+
const top = pg.offsetTop + rect.t * h;
|
|
632
|
+
const tall = rect.h * h;
|
|
633
|
+
el.scrollTop = tall <= el.clientHeight ? top + tall / 2 - el.clientHeight / 2 : top - PAD;
|
|
634
|
+
}
|
|
635
|
+
if (r.focus) pg.querySelector<HTMLElement>(`[data-annotation-id="${CSS.escape(r.id!)}"] button`)?.focus({ preventScroll: true });
|
|
636
|
+
});
|
|
637
|
+
});
|
|
638
|
+
});
|
|
639
|
+
|
|
640
|
+
function choose(id: string) {
|
|
641
|
+
selected = id;
|
|
642
|
+
onselect?.(id);
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// ───── links of the document (its own annotation layer, with forms and actions, is never rendered)
|
|
646
|
+
let links = $state.raw<{ key: string; items: (PageLink & { to?: ResolvedDest })[] }>({ key: '', items: [] });
|
|
647
|
+
$effect(() => {
|
|
648
|
+
const n = page;
|
|
649
|
+
const key = curKey;
|
|
650
|
+
if (!pageReady) return;
|
|
651
|
+
const d = doc!;
|
|
652
|
+
let stale = false;
|
|
653
|
+
d.links(n)
|
|
654
|
+
.then(async (ls) => {
|
|
655
|
+
const items: (PageLink & { to?: ResolvedDest })[] = [];
|
|
656
|
+
for (const l of ls) {
|
|
657
|
+
if (l.url) items.push(l);
|
|
658
|
+
else {
|
|
659
|
+
const to = await d.resolveDest(l.dest!);
|
|
660
|
+
if (to) items.push({ ...l, to });
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
if (!stale) links = { key, items };
|
|
664
|
+
})
|
|
665
|
+
.catch(ignore);
|
|
666
|
+
return () => {
|
|
667
|
+
stale = true;
|
|
668
|
+
};
|
|
669
|
+
});
|
|
670
|
+
const pageLinks = $derived(links.key === curKey ? links.items : []);
|
|
671
|
+
function follow(to: ResolvedDest) {
|
|
672
|
+
goSeq++;
|
|
673
|
+
hl = null;
|
|
674
|
+
reveal = { page: to.page, rect: to.rect };
|
|
675
|
+
go(to.page);
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
// ───── creating annotations: a drawn box, or the selected text
|
|
679
|
+
let drawing = $state(false);
|
|
680
|
+
let draft = $state.raw<{ x: number; y: number; f: Frac } | null>(null);
|
|
681
|
+
let selRange = $state.raw<Range | null>(null);
|
|
682
|
+
|
|
683
|
+
function pointFrac(e: PointerEvent) {
|
|
684
|
+
const b = pageEl!.getBoundingClientRect();
|
|
685
|
+
return { x: Math.min(1, Math.max(0, (e.clientX - b.left) / b.width)), y: Math.min(1, Math.max(0, (e.clientY - b.top) / b.height)) };
|
|
686
|
+
}
|
|
687
|
+
function drawStart(e: PointerEvent) {
|
|
688
|
+
if (e.button !== 0) return;
|
|
689
|
+
const p = pointFrac(e);
|
|
690
|
+
(e.currentTarget as HTMLElement).setPointerCapture?.(e.pointerId);
|
|
691
|
+
draft = { ...p, f: { l: p.x, t: p.y, w: 0, h: 0 } };
|
|
692
|
+
e.preventDefault();
|
|
693
|
+
}
|
|
694
|
+
function drawMove(e: PointerEvent) {
|
|
695
|
+
if (!draft) return;
|
|
696
|
+
const p = pointFrac(e);
|
|
697
|
+
draft = { ...draft, f: { l: Math.min(p.x, draft.x), t: Math.min(p.y, draft.y), w: Math.abs(p.x - draft.x), h: Math.abs(p.y - draft.y) } };
|
|
698
|
+
}
|
|
699
|
+
function drawEnd() {
|
|
700
|
+
const d = draft;
|
|
701
|
+
draft = null;
|
|
702
|
+
if (!d || !vp1 || d.f.w < 0.005 || d.f.h < 0.005) return;
|
|
703
|
+
const base = pageEl!.getBoundingClientRect();
|
|
704
|
+
const inside = layerDivs.filter((s) => {
|
|
705
|
+
const r = s.getBoundingClientRect();
|
|
706
|
+
const cx = (r.left + r.width / 2 - base.left) / base.width;
|
|
707
|
+
const cy = (r.top + r.height / 2 - base.top) / base.height;
|
|
708
|
+
return r.width > 0 && cx >= d.f.l && cx <= d.f.l + d.f.w && cy >= d.f.t && cy <= d.f.t + d.f.h;
|
|
709
|
+
});
|
|
710
|
+
oncreate?.({ page, boxes: [fracToBox(vp1, d.f)], text: inside.map((s) => s.textContent).join(' ').replace(/\s+/g, ' ').trim() });
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
// track a text selection inside this page's text layer (only while creating is on)
|
|
714
|
+
$effect(() => {
|
|
715
|
+
const el = textLayerEl;
|
|
716
|
+
if (!oncreate || !el) return;
|
|
717
|
+
const update = () => {
|
|
718
|
+
const s = document.getSelection()!;
|
|
719
|
+
const r = s.rangeCount ? s.getRangeAt(0) : null;
|
|
720
|
+
selRange = r && !r.collapsed && el.contains(r.commonAncestorContainer) ? r.cloneRange() : null;
|
|
721
|
+
};
|
|
722
|
+
document.addEventListener('selectionchange', update);
|
|
723
|
+
return () => document.removeEventListener('selectionchange', update);
|
|
724
|
+
});
|
|
725
|
+
$effect(() => {
|
|
726
|
+
void curKey;
|
|
727
|
+
untrack(() => (selRange = null));
|
|
728
|
+
});
|
|
729
|
+
|
|
730
|
+
function createFromSelection() {
|
|
731
|
+
// the button is enabled only while there is a selection in the text layer, so the page is on screen
|
|
732
|
+
const r = selRange!;
|
|
733
|
+
const vp = vp1!;
|
|
734
|
+
const boxes = toFracs(r.getClientRects()).map((f) => fracToBox(vp, f));
|
|
735
|
+
const text = r.toString().replace(/\s+/g, ' ').trim();
|
|
736
|
+
document.getSelection()?.removeAllRanges();
|
|
737
|
+
selRange = null;
|
|
738
|
+
oncreate?.({ page, boxes, text });
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
// ───── labels
|
|
742
|
+
const announce = $derived(total ? L.pageStatus(page, total) : '');
|
|
743
|
+
const docName = $derived(isolate(title || L.document));
|
|
744
|
+
const hlStatus = $derived.by(() => {
|
|
745
|
+
if (!hl || hl.page !== page) return null;
|
|
746
|
+
const t = { quote: [L.quoteFound, L.quotePartial, L.quoteMissing], region: [L.regionFound, L.regionPartial, L.regionMissing] }[hl.kind];
|
|
747
|
+
const i = ['found', 'partial', 'missing'].indexOf(hl.status);
|
|
748
|
+
return { text: t[i], intent: (['success', 'warning', 'danger'] as const)[i] };
|
|
749
|
+
});
|
|
750
|
+
const cssLen = (v: number | string | undefined) => (typeof v === 'number' ? `${v}px` : v);
|
|
751
|
+
</script>
|
|
752
|
+
|
|
753
|
+
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
|
754
|
+
<div {...rest} class={['tr-pdf', klass]} data-mode={mode} onkeydown={onKey} {@attach cssvars(() => ({ '--pdf-h': cssLen(height) }))}>
|
|
755
|
+
{#if toolbar}
|
|
756
|
+
<div class="bar" role="group" aria-label={L.toolbar}>
|
|
757
|
+
<div class="grp">
|
|
758
|
+
<Button size="sm" variant="minimal" icon="chevron-left" aria-label={L.previous} disabled={!total || page <= 1} onclick={() => step(-1)} />
|
|
759
|
+
<label class="pageno">
|
|
760
|
+
<span class="sr">{L.pageNumber}</span>
|
|
761
|
+
<input type="text" inputmode="numeric" size="3" bind:value={pageInput} disabled={!total} onchange={commitPageInput} onkeydown={(e) => e.key === 'Enter' && commitPageInput()} onfocus={(e) => e.currentTarget.select()} aria-describedby="{uid}-total" />
|
|
762
|
+
<span id="{uid}-total" class="total">{total ? L.of(total) : ''}</span>
|
|
763
|
+
</label>
|
|
764
|
+
<Button size="sm" variant="minimal" icon="chevron-right" aria-label={L.next} disabled={!total || page >= total} onclick={() => step(1)} />
|
|
765
|
+
</div>
|
|
766
|
+
<SegmentedControl
|
|
767
|
+
size="sm"
|
|
768
|
+
label={L.zoom}
|
|
769
|
+
value={mode}
|
|
770
|
+
onchange={(v) => {
|
|
771
|
+
mode = v as Mode;
|
|
772
|
+
pager.reset();
|
|
773
|
+
}}
|
|
774
|
+
options={[
|
|
775
|
+
{ value: 'page', ariaLabel: L.fitPage, icon: 'minimize' },
|
|
776
|
+
{ value: 'fit-width', ariaLabel: L.fitWidth, icon: 'expand' }
|
|
777
|
+
]}
|
|
778
|
+
/>
|
|
779
|
+
{#if oncreate}
|
|
780
|
+
<div class="grp">
|
|
781
|
+
<Button size="sm" variant="minimal" icon="crop" aria-label={L.drawBox} disabled={!total} toggle bind:pressed={drawing} onpressedchange={() => (draft = null)} />
|
|
782
|
+
<Button size="sm" variant="minimal" icon="tag" aria-label={L.annotateSelection} disabled={!selRange} onpointerdown={(e: PointerEvent) => e.preventDefault()} onclick={createFromSelection} />
|
|
783
|
+
</div>
|
|
784
|
+
{/if}
|
|
785
|
+
<div class="grp status" aria-live="polite">
|
|
786
|
+
{#if hlStatus}<Tag size="sm" intent={hlStatus.intent}>{hlStatus.text}</Tag>{/if}
|
|
787
|
+
</div>
|
|
788
|
+
{#if actions}<div class="grp end">{@render actions()}</div>{/if}
|
|
789
|
+
</div>
|
|
790
|
+
{/if}
|
|
791
|
+
|
|
792
|
+
<div class="sr" aria-live="polite" aria-atomic="true">{announce}</div>
|
|
793
|
+
|
|
794
|
+
<!-- the page area takes the keys (and scrolls a tall page), so it is focusable -->
|
|
795
|
+
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
|
|
796
|
+
<div
|
|
797
|
+
class="stage"
|
|
798
|
+
data-scroll={mode === 'fit-width' || undefined}
|
|
799
|
+
bind:this={stageEl}
|
|
800
|
+
tabindex="0"
|
|
801
|
+
role="region"
|
|
802
|
+
aria-label={announce ? `${docName}, ${announce}` : docName}
|
|
803
|
+
aria-busy={status === 'loading' || undefined}
|
|
804
|
+
ontouchstart={(e) => swiper.start(e)}
|
|
805
|
+
ontouchend={(e) => swiper.end(e, !scrolls())}
|
|
806
|
+
>
|
|
807
|
+
{#if status === 'error'}
|
|
808
|
+
<div class="center">
|
|
809
|
+
<EmptyState intent="danger" icon="error" title={L.loadFailed} description={loadError}>
|
|
810
|
+
{#snippet actions()}<Button icon="refresh" onclick={() => retry++}>{L.retry}</Button>{/snippet}
|
|
811
|
+
</EmptyState>
|
|
812
|
+
</div>
|
|
813
|
+
{:else if doc && dims}
|
|
814
|
+
<div class="page" bind:this={pageEl} data-page={page} {@attach cssvars(() => ({ width: `${pageBox.w}px`, height: `${pageBox.h}px`, '--total-scale-factor': cssScale }))}>
|
|
815
|
+
<div class="canvas" bind:this={canvasHost}></div>
|
|
816
|
+
<div class="textLayer" bind:this={textLayerEl}></div>
|
|
817
|
+
<div class="layer">
|
|
818
|
+
{#each hlRects as r, i (i)}
|
|
819
|
+
<div class="hl" data-kind={hl?.kind} data-status={hl?.status} aria-hidden="true" {@attach csstext(() => rectCss(r))}></div>
|
|
820
|
+
{/each}
|
|
821
|
+
{#each shown as { a, rects }, i (a.id)}
|
|
822
|
+
{@const name = a.label ? isolate(a.label) : L.annotation(i + 1)}
|
|
823
|
+
<div class="ann" data-annotation-id={a.id} data-tone={a.tone ?? 'warning'} data-muted={a.muted || undefined} data-selected={a.id === selected || undefined}>
|
|
824
|
+
{#each rects as r, j (j)}
|
|
825
|
+
<div class="rect" {@attach csstext(() => rectCss(r))}>
|
|
826
|
+
{#if j === 0}
|
|
827
|
+
{#if a.label}
|
|
828
|
+
<Tooltip text={name}>{@render hit(a.id, name)}</Tooltip>
|
|
829
|
+
{:else}
|
|
830
|
+
{@render hit(a.id, name)}
|
|
831
|
+
{/if}
|
|
832
|
+
{:else}
|
|
833
|
+
<!-- the keyboard reaches the annotation through its first rect; the others are pointer targets only -->
|
|
834
|
+
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
|
835
|
+
<div class="more" aria-hidden="true" onclick={() => choose(a.id)}></div>
|
|
836
|
+
{/if}
|
|
837
|
+
</div>
|
|
838
|
+
{/each}
|
|
839
|
+
</div>
|
|
840
|
+
{/each}
|
|
841
|
+
{#each pageLinks as l, i (i)}
|
|
842
|
+
{#if l.to}
|
|
843
|
+
{@const to = l.to}
|
|
844
|
+
<button type="button" class="link" aria-label={L.goToPage(to.page)} onclick={() => follow(to)} {@attach csstext(() => rectCss(l.rect))}></button>
|
|
845
|
+
{:else if onlink}
|
|
846
|
+
<button type="button" class="link" aria-label={isolate(L.link(l.url!))} onclick={() => onlink(l.url!)} {@attach csstext(() => rectCss(l.rect))}></button>
|
|
847
|
+
{:else}
|
|
848
|
+
<a class="link" href={l.url} target="_blank" rel="noopener noreferrer nofollow" referrerpolicy="no-referrer" aria-label={isolate(L.link(l.url!))} {@attach csstext(() => rectCss(l.rect))}></a>
|
|
849
|
+
{/if}
|
|
850
|
+
{/each}
|
|
851
|
+
</div>
|
|
852
|
+
{#if drawing}
|
|
853
|
+
<div class="draw" onpointerdown={drawStart} onpointermove={drawMove} onpointerup={drawEnd} onpointercancel={() => (draft = null)} aria-hidden="true">
|
|
854
|
+
{#if draft}<div class="draft" {@attach csstext(() => rectCss(draft!.f))}></div>{/if}
|
|
855
|
+
</div>
|
|
856
|
+
{/if}
|
|
857
|
+
{#if rendering}<div class="overlay"><Spinner size={28} label={L.rendering} /></div>{/if}
|
|
858
|
+
</div>
|
|
859
|
+
{#if renderError}<div class="overlay error" role="alert">{L.renderFailed}: {renderError}</div>{/if}
|
|
860
|
+
{/if}
|
|
861
|
+
{#if status === 'loading'}<div class="overlay"><Spinner label={L.loading} /></div>{/if}
|
|
862
|
+
</div>
|
|
863
|
+
</div>
|
|
864
|
+
|
|
865
|
+
{#snippet hit(id: string, name: string)}
|
|
866
|
+
<button type="button" class="hit" aria-label={name} aria-current={id === selected || undefined} onclick={() => choose(id)}></button>
|
|
867
|
+
{/snippet}
|
|
868
|
+
|
|
869
|
+
<style>
|
|
870
|
+
.tr-pdf {
|
|
871
|
+
display: flex;
|
|
872
|
+
flex-direction: column;
|
|
873
|
+
height: var(--pdf-h, 32rem);
|
|
874
|
+
min-height: 12rem;
|
|
875
|
+
border: 1px solid var(--tr-outline-variant);
|
|
876
|
+
border-radius: var(--tr-radius-md, 8px);
|
|
877
|
+
overflow: hidden;
|
|
878
|
+
background: var(--tr-surface);
|
|
879
|
+
color: var(--tr-on-surface);
|
|
880
|
+
}
|
|
881
|
+
.bar {
|
|
882
|
+
display: flex;
|
|
883
|
+
flex-wrap: wrap;
|
|
884
|
+
align-items: center;
|
|
885
|
+
gap: var(--tr-space-1, 4px) var(--tr-space-3, 12px);
|
|
886
|
+
padding: var(--tr-space-1, 4px) var(--tr-space-3, 12px);
|
|
887
|
+
border-bottom: 1px solid var(--tr-outline-variant);
|
|
888
|
+
background: var(--tr-surface-container-low);
|
|
889
|
+
}
|
|
890
|
+
.grp {
|
|
891
|
+
display: flex;
|
|
892
|
+
align-items: center;
|
|
893
|
+
gap: var(--tr-space-1, 4px);
|
|
894
|
+
min-width: 0;
|
|
895
|
+
}
|
|
896
|
+
.status:empty {
|
|
897
|
+
display: none;
|
|
898
|
+
}
|
|
899
|
+
.end {
|
|
900
|
+
margin-left: auto;
|
|
901
|
+
}
|
|
902
|
+
.pageno {
|
|
903
|
+
display: inline-flex;
|
|
904
|
+
align-items: center;
|
|
905
|
+
gap: 0.35em;
|
|
906
|
+
font-size: var(--tr-text-sm);
|
|
907
|
+
font-variant-numeric: tabular-nums;
|
|
908
|
+
}
|
|
909
|
+
.pageno input {
|
|
910
|
+
width: 3.5em;
|
|
911
|
+
text-align: center;
|
|
912
|
+
font: inherit;
|
|
913
|
+
color: var(--tr-on-surface);
|
|
914
|
+
background: var(--tr-surface);
|
|
915
|
+
border: 1px solid var(--tr-outline);
|
|
916
|
+
border-radius: var(--tr-radius-sm, 4px);
|
|
917
|
+
padding: 2px 4px;
|
|
918
|
+
}
|
|
919
|
+
.pageno input:focus-visible {
|
|
920
|
+
outline: 2px solid var(--tr-focus-color, var(--tr-primary));
|
|
921
|
+
outline-offset: 1px;
|
|
922
|
+
}
|
|
923
|
+
.total {
|
|
924
|
+
color: var(--tr-on-surface-variant);
|
|
925
|
+
white-space: nowrap;
|
|
926
|
+
}
|
|
927
|
+
.sr {
|
|
928
|
+
position: absolute;
|
|
929
|
+
width: 1px;
|
|
930
|
+
height: 1px;
|
|
931
|
+
margin: -1px;
|
|
932
|
+
overflow: hidden;
|
|
933
|
+
clip-path: inset(50%);
|
|
934
|
+
white-space: nowrap;
|
|
935
|
+
}
|
|
936
|
+
.stage {
|
|
937
|
+
position: relative;
|
|
938
|
+
flex: 1;
|
|
939
|
+
min-height: 0;
|
|
940
|
+
overflow: hidden;
|
|
941
|
+
display: flex;
|
|
942
|
+
align-items: center;
|
|
943
|
+
justify-content: center;
|
|
944
|
+
padding: 12px;
|
|
945
|
+
background: var(--tr-surface-container-high, var(--tr-surface-container));
|
|
946
|
+
touch-action: none;
|
|
947
|
+
overscroll-behavior: contain;
|
|
948
|
+
}
|
|
949
|
+
.stage[data-scroll] {
|
|
950
|
+
overflow-y: auto;
|
|
951
|
+
align-items: flex-start;
|
|
952
|
+
scrollbar-gutter: stable;
|
|
953
|
+
touch-action: pan-y;
|
|
954
|
+
}
|
|
955
|
+
.stage:focus-visible {
|
|
956
|
+
outline: 2px solid var(--tr-focus-color, var(--tr-primary));
|
|
957
|
+
outline-offset: -2px;
|
|
958
|
+
}
|
|
959
|
+
.page {
|
|
960
|
+
position: relative;
|
|
961
|
+
flex: none;
|
|
962
|
+
margin: auto;
|
|
963
|
+
/* the paper: PDF content is drawn for a white page in both themes */
|
|
964
|
+
background: #fff;
|
|
965
|
+
box-shadow: var(--tr-elevation-2);
|
|
966
|
+
--scale-round-x: 1px;
|
|
967
|
+
--scale-round-y: 1px;
|
|
968
|
+
}
|
|
969
|
+
.canvas,
|
|
970
|
+
.canvas :global(canvas) {
|
|
971
|
+
position: absolute;
|
|
972
|
+
inset: 0;
|
|
973
|
+
width: 100%;
|
|
974
|
+
height: 100%;
|
|
975
|
+
display: block;
|
|
976
|
+
}
|
|
977
|
+
.overlay {
|
|
978
|
+
position: absolute;
|
|
979
|
+
inset: 0;
|
|
980
|
+
display: flex;
|
|
981
|
+
align-items: center;
|
|
982
|
+
justify-content: center;
|
|
983
|
+
pointer-events: none;
|
|
984
|
+
}
|
|
985
|
+
.overlay.error {
|
|
986
|
+
align-items: flex-end;
|
|
987
|
+
padding: var(--tr-space-3, 12px);
|
|
988
|
+
color: var(--tr-danger);
|
|
989
|
+
font-size: var(--tr-text-sm);
|
|
990
|
+
}
|
|
991
|
+
.center {
|
|
992
|
+
margin: auto;
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
/* pdf.js text layer (after pdfjs-dist/web/pdf_viewer.css): transparent, selectable text over the canvas */
|
|
996
|
+
.page :global(.textLayer) {
|
|
997
|
+
position: absolute;
|
|
998
|
+
inset: 0;
|
|
999
|
+
overflow: clip;
|
|
1000
|
+
opacity: 1;
|
|
1001
|
+
line-height: 1;
|
|
1002
|
+
text-align: initial;
|
|
1003
|
+
letter-spacing: normal;
|
|
1004
|
+
word-spacing: normal;
|
|
1005
|
+
text-size-adjust: none;
|
|
1006
|
+
forced-color-adjust: none;
|
|
1007
|
+
transform-origin: 0 0;
|
|
1008
|
+
caret-color: CanvasText;
|
|
1009
|
+
z-index: 0;
|
|
1010
|
+
--min-font-size: 1;
|
|
1011
|
+
--text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size));
|
|
1012
|
+
--min-font-size-inv: calc(1 / var(--min-font-size));
|
|
1013
|
+
}
|
|
1014
|
+
.page :global(.textLayer :is(span, br)) {
|
|
1015
|
+
color: transparent;
|
|
1016
|
+
position: absolute;
|
|
1017
|
+
white-space: pre;
|
|
1018
|
+
cursor: text;
|
|
1019
|
+
transform-origin: 0% 0%;
|
|
1020
|
+
user-select: text;
|
|
1021
|
+
}
|
|
1022
|
+
.page :global(.textLayer > :not(.markedContent)),
|
|
1023
|
+
.page :global(.textLayer .markedContent span:not(.markedContent)) {
|
|
1024
|
+
z-index: 1;
|
|
1025
|
+
--font-height: 0;
|
|
1026
|
+
font-size: calc(var(--text-scale-factor) * var(--font-height));
|
|
1027
|
+
--scale-x: 1;
|
|
1028
|
+
--rotate: 0deg;
|
|
1029
|
+
transform: rotate(var(--rotate)) scaleX(var(--scale-x)) scale(var(--min-font-size-inv));
|
|
1030
|
+
}
|
|
1031
|
+
/* the layer is laid out in unrotated page space and turned with the page's /Rotate */
|
|
1032
|
+
.page :global(.textLayer[data-main-rotation='90']) {
|
|
1033
|
+
transform: rotate(90deg) translateY(-100%);
|
|
1034
|
+
}
|
|
1035
|
+
.page :global(.textLayer[data-main-rotation='180']) {
|
|
1036
|
+
transform: rotate(180deg) translate(-100%, -100%);
|
|
1037
|
+
}
|
|
1038
|
+
.page :global(.textLayer[data-main-rotation='270']) {
|
|
1039
|
+
transform: rotate(270deg) translateX(-100%);
|
|
1040
|
+
}
|
|
1041
|
+
.page :global(.textLayer .markedContent) {
|
|
1042
|
+
display: contents;
|
|
1043
|
+
}
|
|
1044
|
+
.page :global(.textLayer span[role='img']) {
|
|
1045
|
+
user-select: none;
|
|
1046
|
+
cursor: default;
|
|
1047
|
+
}
|
|
1048
|
+
.page :global(.textLayer ::selection) {
|
|
1049
|
+
background: color-mix(in srgb, AccentColor, transparent 50%);
|
|
1050
|
+
color: transparent;
|
|
1051
|
+
}
|
|
1052
|
+
.page :global(.textLayer br::selection) {
|
|
1053
|
+
background: transparent;
|
|
1054
|
+
}
|
|
1055
|
+
.page :global(.textLayer .endOfContent) {
|
|
1056
|
+
display: block;
|
|
1057
|
+
position: absolute;
|
|
1058
|
+
inset: 100% 0 0;
|
|
1059
|
+
z-index: 0;
|
|
1060
|
+
cursor: default;
|
|
1061
|
+
user-select: none;
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
/* overlays above the text layer: the jump highlight, the annotations (first in the tab order, on top) and the links of the document */
|
|
1065
|
+
.layer {
|
|
1066
|
+
position: absolute;
|
|
1067
|
+
inset: 0;
|
|
1068
|
+
z-index: 2;
|
|
1069
|
+
pointer-events: none;
|
|
1070
|
+
}
|
|
1071
|
+
.link,
|
|
1072
|
+
.rect,
|
|
1073
|
+
.hl {
|
|
1074
|
+
position: absolute;
|
|
1075
|
+
box-sizing: border-box;
|
|
1076
|
+
}
|
|
1077
|
+
.link {
|
|
1078
|
+
z-index: 1;
|
|
1079
|
+
pointer-events: auto;
|
|
1080
|
+
padding: 0;
|
|
1081
|
+
margin: 0;
|
|
1082
|
+
border: 0;
|
|
1083
|
+
background: transparent;
|
|
1084
|
+
cursor: pointer;
|
|
1085
|
+
border-radius: 2px;
|
|
1086
|
+
}
|
|
1087
|
+
.link:hover {
|
|
1088
|
+
background: color-mix(in srgb, var(--tr-primary) 12%, transparent);
|
|
1089
|
+
}
|
|
1090
|
+
.link:focus-visible,
|
|
1091
|
+
.hit:focus-visible {
|
|
1092
|
+
outline: 2px solid var(--tr-focus-color, var(--tr-primary));
|
|
1093
|
+
outline-offset: 2px;
|
|
1094
|
+
}
|
|
1095
|
+
.hl {
|
|
1096
|
+
min-height: 2px;
|
|
1097
|
+
border-radius: 2px;
|
|
1098
|
+
background: color-mix(in srgb, var(--tr-warning) 35%, transparent);
|
|
1099
|
+
}
|
|
1100
|
+
.hl[data-kind='region'] {
|
|
1101
|
+
min-width: 6px;
|
|
1102
|
+
min-height: 6px;
|
|
1103
|
+
background: color-mix(in srgb, var(--tr-danger) 12%, transparent);
|
|
1104
|
+
border: 2px solid var(--tr-danger);
|
|
1105
|
+
animation: tr-pdf-pulse 1.2s ease-out 2;
|
|
1106
|
+
}
|
|
1107
|
+
@keyframes tr-pdf-pulse {
|
|
1108
|
+
0% {
|
|
1109
|
+
box-shadow: 0 0 0 0 color-mix(in srgb, var(--tr-danger) 60%, transparent);
|
|
1110
|
+
}
|
|
1111
|
+
100% {
|
|
1112
|
+
box-shadow: 0 0 0 12px transparent;
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
@media (prefers-reduced-motion: reduce) {
|
|
1116
|
+
.hl[data-kind='region'] {
|
|
1117
|
+
animation: none;
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
.ann {
|
|
1121
|
+
--c: var(--tr-warning);
|
|
1122
|
+
display: contents;
|
|
1123
|
+
}
|
|
1124
|
+
.ann[data-tone='danger'] {
|
|
1125
|
+
--c: var(--tr-danger);
|
|
1126
|
+
}
|
|
1127
|
+
.ann[data-tone='success'] {
|
|
1128
|
+
--c: var(--tr-success);
|
|
1129
|
+
}
|
|
1130
|
+
.ann[data-tone='info'],
|
|
1131
|
+
.ann[data-tone='primary'] {
|
|
1132
|
+
--c: var(--tr-primary);
|
|
1133
|
+
}
|
|
1134
|
+
.ann[data-tone='neutral'] {
|
|
1135
|
+
--c: var(--tr-outline);
|
|
1136
|
+
}
|
|
1137
|
+
.rect {
|
|
1138
|
+
z-index: 2;
|
|
1139
|
+
min-width: 4px;
|
|
1140
|
+
min-height: 4px;
|
|
1141
|
+
pointer-events: auto;
|
|
1142
|
+
border-radius: 2px;
|
|
1143
|
+
background: color-mix(in srgb, var(--c) 22%, transparent);
|
|
1144
|
+
box-shadow: inset 0 -2px 0 var(--c);
|
|
1145
|
+
}
|
|
1146
|
+
.ann[data-muted] .rect {
|
|
1147
|
+
background: color-mix(in srgb, var(--c) 8%, transparent);
|
|
1148
|
+
box-shadow: inset 0 -1px 0 color-mix(in srgb, var(--c) 50%, transparent);
|
|
1149
|
+
}
|
|
1150
|
+
.ann[data-selected] .rect {
|
|
1151
|
+
background: color-mix(in srgb, var(--c) 32%, transparent);
|
|
1152
|
+
box-shadow: 0 0 0 2px var(--c);
|
|
1153
|
+
}
|
|
1154
|
+
.rect > :global(span),
|
|
1155
|
+
.hit,
|
|
1156
|
+
.more {
|
|
1157
|
+
display: block;
|
|
1158
|
+
width: 100%;
|
|
1159
|
+
height: 100%;
|
|
1160
|
+
}
|
|
1161
|
+
.hit {
|
|
1162
|
+
padding: 0;
|
|
1163
|
+
margin: 0;
|
|
1164
|
+
border: 0;
|
|
1165
|
+
background: transparent;
|
|
1166
|
+
cursor: pointer;
|
|
1167
|
+
border-radius: inherit;
|
|
1168
|
+
}
|
|
1169
|
+
.more {
|
|
1170
|
+
cursor: pointer;
|
|
1171
|
+
}
|
|
1172
|
+
.draw {
|
|
1173
|
+
position: absolute;
|
|
1174
|
+
inset: 0;
|
|
1175
|
+
z-index: 3;
|
|
1176
|
+
cursor: crosshair;
|
|
1177
|
+
touch-action: none;
|
|
1178
|
+
}
|
|
1179
|
+
.draft {
|
|
1180
|
+
position: absolute;
|
|
1181
|
+
border: 2px dashed var(--tr-primary);
|
|
1182
|
+
background: color-mix(in srgb, var(--tr-primary) 10%, transparent);
|
|
1183
|
+
}
|
|
1184
|
+
</style>
|