@salmonui/pdf-viewer 0.0.0-stage → 0.3.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.
Files changed (56) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +63 -2
  3. package/dist/PdfViewer.d.ts +6 -0
  4. package/dist/PdfViewer.d.ts.map +1 -0
  5. package/dist/PdfViewer.js +151 -0
  6. package/dist/PdfViewer.js.map +1 -0
  7. package/dist/core.d.ts +163 -0
  8. package/dist/core.d.ts.map +1 -0
  9. package/dist/core.js +939 -0
  10. package/dist/core.js.map +1 -0
  11. package/dist/engine/controller.d.ts +57 -0
  12. package/dist/engine/controller.d.ts.map +1 -0
  13. package/dist/engine/controller.js +418 -0
  14. package/dist/engine/controller.js.map +1 -0
  15. package/dist/engine/pdf-worker.d.ts +2 -0
  16. package/dist/engine/pdf-worker.d.ts.map +1 -0
  17. package/dist/engine/pdf-worker.js +23 -0
  18. package/dist/engine/pdf-worker.js.map +1 -0
  19. package/dist/icons.d.ts +5 -0
  20. package/dist/icons.d.ts.map +1 -0
  21. package/dist/icons.js +17 -0
  22. package/dist/icons.js.map +1 -0
  23. package/dist/index.d.ts +8 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +12 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/layout.d.ts +49 -0
  28. package/dist/layout.d.ts.map +1 -0
  29. package/dist/layout.js +115 -0
  30. package/dist/layout.js.map +1 -0
  31. package/dist/locale.d.ts +55 -0
  32. package/dist/locale.d.ts.map +1 -0
  33. package/dist/locale.js +50 -0
  34. package/dist/locale.js.map +1 -0
  35. package/dist/markup.d.ts +54 -0
  36. package/dist/markup.d.ts.map +1 -0
  37. package/dist/markup.js +175 -0
  38. package/dist/markup.js.map +1 -0
  39. package/dist/pdf-viewer.css +1523 -0
  40. package/dist/search.d.ts +36 -0
  41. package/dist/search.d.ts.map +1 -0
  42. package/dist/search.js +89 -0
  43. package/dist/search.js.map +1 -0
  44. package/dist/toolbar.d.ts +19 -0
  45. package/dist/toolbar.d.ts.map +1 -0
  46. package/dist/toolbar.js +128 -0
  47. package/dist/toolbar.js.map +1 -0
  48. package/dist/types.d.ts +227 -0
  49. package/dist/types.d.ts.map +1 -0
  50. package/dist/types.js +2 -0
  51. package/dist/types.js.map +1 -0
  52. package/dist/zoom.d.ts +35 -0
  53. package/dist/zoom.d.ts.map +1 -0
  54. package/dist/zoom.js +58 -0
  55. package/dist/zoom.js.map +1 -0
  56. package/package.json +44 -4
package/dist/core.js ADDED
@@ -0,0 +1,939 @@
1
+ // PdfViewer controller (initial chunk, no engine code). Owns the viewer
2
+ // state in an external store read through useSyncExternalStore: layout,
3
+ // visible pages, current page, zoom, search and the panels. Scroll, wheel
4
+ // and pinch transients stay here and reach React only when the rendered
5
+ // page set, the current page or the committed zoom changes. The pdf.js side
6
+ // (engine/controller.ts) loads with dynamic import() on the client.
7
+ import { computeRange, createVariableRowMetrics } from '@salmonui/core/virtual';
8
+ import { computeLayout, pageOffset, visiblePages } from './layout.js';
9
+ import { annotationId, cssRectToPdf, DEFAULT_MARKUP_COLORS, mergeLineRects } from './markup.js';
10
+ import { countByPage, findMatches, matchPieces } from './search.js';
11
+ import { PDF_TO_CSS, clampScale, pinchScale, resolveScale, stepScale, wheelFactor } from './zoom.js';
12
+ /** Layout assumed before the viewport is measured (server and first client render). */
13
+ export const INITIAL_VIEWPORT = Object.freeze({ width: 816, height: 1056 });
14
+ /** Thumbnail width in CSS px. */
15
+ export const THUMB_WIDTH = 120;
16
+ const THUMB_EXTRA = 36;
17
+ /** Widest viewer whose sidebar overlays the pages (`@container (max-width: 480px)` in pdf-viewer.css). */
18
+ const NARROW_WIDTH = 480;
19
+ const LETTER = { width: 612, height: 792 };
20
+ const sizesFrom = (props) => {
21
+ const s = props.pageSizes;
22
+ if (!s)
23
+ return [];
24
+ if (Array.isArray(s))
25
+ return s;
26
+ return Array.from({ length: Math.max(0, props.pageCount ?? 1) }, () => s);
27
+ };
28
+ const sameList = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
29
+ const isMac = () => /Mac|iPhone|iPad/.test(globalThis.navigator?.platform ?? '');
30
+ /** Cancellable event object. */
31
+ export function cancelable(fields) {
32
+ let prevented = false;
33
+ Object.defineProperty(fields, 'preventDefault', { value: () => void (prevented = true), enumerable: true });
34
+ Object.defineProperty(fields, 'defaultPrevented', { get: () => prevented, enumerable: true });
35
+ return fields;
36
+ }
37
+ export class ViewerCore {
38
+ props;
39
+ state;
40
+ listeners = new Set();
41
+ engine = null;
42
+ engineInfo = null;
43
+ loadId = 0;
44
+ passwordSubmit = null;
45
+ passwordCancel = null;
46
+ root = null;
47
+ viewportEl = null;
48
+ contentEl = null;
49
+ thumbsEl = null;
50
+ findInput = null;
51
+ cleanup = [];
52
+ mounted = new Map();
53
+ thumbCanvases = new Map();
54
+ frame = 0;
55
+ renderTimer;
56
+ lock = null;
57
+ anchor = null;
58
+ pageRow = 0;
59
+ matches = [];
60
+ texts = [];
61
+ searchRun = 0;
62
+ searchTimer;
63
+ scrollToMatch = false;
64
+ lastRange = null;
65
+ pinch = { factor: 1, timer: undefined, pointers: new Map(), startDist: 0 };
66
+ appliedForm;
67
+ printing = false;
68
+ actions;
69
+ constructor(props) {
70
+ this.props = props;
71
+ const sizes = sizesFrom(props);
72
+ const zoom = props.zoom ?? props.defaultZoom ?? 'auto';
73
+ const scale = this.scaleFor(zoom, sizes, INITIAL_VIEWPORT, props);
74
+ const layout = this.layoutFor(sizes, scale, INITIAL_VIEWPORT, props);
75
+ const page = Math.max(0, Math.min(sizes.length - 1, (props.page ?? props.defaultPage ?? 1) - 1));
76
+ this.pageRow = layout.rowOf[page] ?? 0;
77
+ this.state = {
78
+ status: props.src ? 'loading' : 'empty',
79
+ passwordReason: null,
80
+ error: null,
81
+ sizes,
82
+ geometry: null,
83
+ outline: [],
84
+ zoom,
85
+ scale,
86
+ layout,
87
+ visible: visiblePages(layout, pageOffset(layout, page), INITIAL_VIEWPORT.height, 0, this.pageRow).pages,
88
+ page,
89
+ viewport: INITIAL_VIEWPORT,
90
+ sidebar: props.sidebar !== undefined ? props.sidebar : (props.defaultSidebar ?? null),
91
+ findOpen: false,
92
+ find: { query: '', matchCase: false, wholeWord: false, highlightAll: true },
93
+ matchTotal: 0,
94
+ matchIndex: -1,
95
+ searching: false,
96
+ annotations: props.defaultAnnotations ?? [],
97
+ hasSelection: false,
98
+ thumbs: [],
99
+ pinching: false,
100
+ };
101
+ const self = this;
102
+ this.actions = Object.freeze({
103
+ goToPage: (page) => self.goToPage(page - 1, 'api'),
104
+ search: (query, options) => self.search(query, options),
105
+ findNext: () => self.stepMatch(1),
106
+ findPrevious: () => self.stepMatch(-1),
107
+ clearSearch: () => self.setQuery('', true),
108
+ setZoom: (zoom) => self.setZoom(zoom, 'api'),
109
+ print: () => self.print(),
110
+ save: () => self.save(),
111
+ download: (fileName) => self.download(fileName),
112
+ addTextMarkup: (kind, options) => self.addTextMarkup(kind, options),
113
+ removeAnnotation: (id) => self.removeAnnotation(id),
114
+ getState: () => self.publicState(),
115
+ openFind: (open = true) => self.openFind(open),
116
+ });
117
+ }
118
+ // Store -------------------------------------------------------------------
119
+ subscribe = (listener) => {
120
+ this.listeners.add(listener);
121
+ return () => this.listeners.delete(listener);
122
+ };
123
+ getSnapshot = () => this.state;
124
+ set(patch) {
125
+ let changed = false;
126
+ for (const key of Object.keys(patch))
127
+ if (this.state[key] !== patch[key])
128
+ changed = true;
129
+ if (!changed)
130
+ return;
131
+ this.state = { ...this.state, ...patch };
132
+ for (const l of this.listeners)
133
+ l();
134
+ }
135
+ publicState() {
136
+ const s = this.state;
137
+ return { status: s.status, page: this.currentPage(), pageCount: s.sizes.length, scale: s.scale, zoom: this.zoom() };
138
+ }
139
+ // Derived values ------------------------------------------------------------
140
+ zoom() {
141
+ return this.props.zoom ?? this.state.zoom;
142
+ }
143
+ annotations() {
144
+ return this.props.annotations ?? this.state.annotations;
145
+ }
146
+ annotationsFor(snapshotAnnotations) {
147
+ return this.props.annotations ?? snapshotAnnotations;
148
+ }
149
+ currentPage() {
150
+ return this.state.page + 1;
151
+ }
152
+ scaleFor(zoom, sizes, viewport, props) {
153
+ const ref = sizes[Math.max(0, Math.min(sizes.length - 1, this.state?.page ?? 0))] ?? sizes[0] ?? LETTER;
154
+ return resolveScale(zoom, { page: ref, viewport, scrollMode: props.scrollMode, spreadMode: props.spreadMode });
155
+ }
156
+ layoutFor(sizes, scale, viewport, props) {
157
+ return computeLayout({ sizes, scale, scrollMode: props.scrollMode ?? 'vertical', spreadMode: props.spreadMode ?? 'none', viewportWidth: viewport.width });
158
+ }
159
+ /** Recomputes scale and layout; keeps the reading position. */
160
+ relayout(patch = {}) {
161
+ const next = { ...this.state, ...patch };
162
+ const scale = this.scaleFor(this.props.zoom ?? next.zoom, next.sizes, next.viewport, this.props);
163
+ const layout = this.layoutFor(next.sizes, scale, next.viewport, this.props);
164
+ const old = this.state.layout;
165
+ if (this.viewportEl && old.boxes.length && !this.anchor) {
166
+ const box = old.boxes[this.state.page];
167
+ const offset = old.axis === 'x' ? Math.abs(this.viewportEl.scrollLeft) : this.viewportEl.scrollTop;
168
+ if (box)
169
+ this.anchor = { page: this.state.page, fraction: ((old.axis === 'x' ? offset - box.x : offset - box.y) + 0) / (old.axis === 'x' ? box.width : box.height), cross: 0 };
170
+ }
171
+ this.pageRow = layout.rowOf[Math.min(next.page, next.sizes.length - 1)] ?? 0;
172
+ this.set({ ...patch, scale, layout });
173
+ this.updateVisible();
174
+ this.updateThumbs();
175
+ if (scale !== this.renderedScale)
176
+ this.scheduleRender(120);
177
+ }
178
+ renderedScale = 0;
179
+ /** Called by the component after React committed a new layout. */
180
+ afterCommit() {
181
+ const el = this.viewportEl;
182
+ const a = this.anchor;
183
+ this.anchor = null;
184
+ if (!el || !a)
185
+ return;
186
+ const layout = this.state.layout;
187
+ const box = layout.boxes[a.page];
188
+ if (!box)
189
+ return;
190
+ if (layout.mode === 'page')
191
+ return;
192
+ const start = layout.axis === 'x' ? box.x : box.y;
193
+ const extent = layout.axis === 'x' ? box.width : box.height;
194
+ const target = Math.max(0, start + a.fraction * extent);
195
+ this.lock = { page: a.page, until: performance.now() + 200 };
196
+ if (layout.axis === 'x')
197
+ el.scrollLeft = this.rtl() ? -target : target;
198
+ else
199
+ el.scrollTop = target;
200
+ this.updateVisible();
201
+ }
202
+ // Props -----------------------------------------------------------------------
203
+ setProps(props) {
204
+ const prev = this.props;
205
+ this.props = props;
206
+ if (prev.pageSizes !== props.pageSizes && !this.engineInfo)
207
+ this.relayout({ sizes: sizesFrom(props) });
208
+ else if (prev.zoom !== props.zoom || prev.scrollMode !== props.scrollMode || prev.spreadMode !== props.spreadMode)
209
+ this.relayout();
210
+ if (props.page !== undefined && props.page !== prev.page && props.page - 1 !== this.state.page)
211
+ this.goToPage(props.page - 1, 'prop', false);
212
+ if (props.sidebar !== undefined && props.sidebar !== this.state.sidebar)
213
+ this.set({ sidebar: props.sidebar });
214
+ if (props.formValues !== undefined && props.formValues !== this.appliedForm && this.engine) {
215
+ this.appliedForm = props.formValues;
216
+ this.engine.setFormValues(props.formValues);
217
+ }
218
+ if (prev.annotations !== props.annotations)
219
+ this.set({ annotations: props.annotations ?? this.state.annotations });
220
+ }
221
+ // Loading -----------------------------------------------------------------------
222
+ async load(src) {
223
+ const id = ++this.loadId;
224
+ this.engine?.destroy();
225
+ this.engine = null;
226
+ this.engineInfo = null;
227
+ this.matches = [];
228
+ this.texts = [];
229
+ if (!src) {
230
+ this.set({ status: 'empty', error: null });
231
+ return;
232
+ }
233
+ this.set({ status: 'loading', error: null, passwordReason: null });
234
+ try {
235
+ const { openDocument } = await import('./engine/controller.js');
236
+ const engine = await openDocument({
237
+ src,
238
+ password: this.props.password,
239
+ workerSrc: this.props.workerSrc,
240
+ documentOptions: this.props.documentOptions,
241
+ onPassword: (reason, submit, cancel) => {
242
+ if (id !== this.loadId)
243
+ return cancel();
244
+ this.passwordSubmit = submit;
245
+ this.passwordCancel = cancel;
246
+ const request = { reason, submit: (pw) => this.submitPassword(pw), cancel: () => this.cancelPassword() };
247
+ this.set({ status: 'password', passwordReason: reason });
248
+ this.props.onPasswordRequired?.(request);
249
+ },
250
+ hooks: {
251
+ linkTarget: () => this.props.linkTarget ?? '_blank',
252
+ externalLink: (url) => {
253
+ const event = cancelable({ url, page: null });
254
+ this.props.onLinkClick?.(event);
255
+ return !event.defaultPrevented;
256
+ },
257
+ internalLink: (page) => {
258
+ const event = cancelable({ url: null, page });
259
+ this.props.onLinkClick?.(event);
260
+ if (!event.defaultPrevented && page)
261
+ this.goToPage(page - 1, 'link');
262
+ },
263
+ pageCount: () => this.state.sizes.length,
264
+ currentPage: () => this.currentPage(),
265
+ formInput: (name, value) => this.formInput(name, value),
266
+ },
267
+ });
268
+ if (id !== this.loadId)
269
+ return engine.destroy();
270
+ this.engine = engine;
271
+ this.engineInfo = engine.info;
272
+ const info = engine.info;
273
+ const form = this.props.formValues ?? this.props.defaultFormValues;
274
+ if (form) {
275
+ this.appliedForm = this.props.formValues;
276
+ engine.setFormValues(form);
277
+ }
278
+ const page = Math.max(0, Math.min(info.pageCount - 1, this.state.page));
279
+ this.renderedScale = 0;
280
+ this.relayout({ status: 'ready', sizes: info.sizes, geometry: info.geometry, outline: info.outline, page, passwordReason: null });
281
+ this.scheduleRender(0);
282
+ this.props.onLoad?.({ pageCount: info.pageCount, pageSizes: info.sizes, title: info.title, outline: info.outline, formFields: info.formFields });
283
+ if (this.state.find.query)
284
+ this.runSearch(false);
285
+ }
286
+ catch (error) {
287
+ if (id !== this.loadId)
288
+ return;
289
+ const err = error instanceof Error ? error : new Error(String(error));
290
+ this.set({ status: 'error', error: err, passwordReason: null });
291
+ this.props.onLoadError?.(err);
292
+ }
293
+ }
294
+ submitPassword(password) {
295
+ const submit = this.passwordSubmit;
296
+ this.passwordSubmit = null;
297
+ if (submit) {
298
+ this.set({ status: 'loading' });
299
+ submit(password);
300
+ }
301
+ }
302
+ cancelPassword() {
303
+ const cancel = this.passwordCancel;
304
+ this.passwordCancel = null;
305
+ this.passwordSubmit = null;
306
+ cancel?.();
307
+ }
308
+ destroy() {
309
+ this.loadId++;
310
+ this.engine?.destroy();
311
+ this.engine = null;
312
+ }
313
+ // DOM -------------------------------------------------------------------------------
314
+ attach(root, viewport, content) {
315
+ this.root = root;
316
+ this.viewportEl = viewport;
317
+ this.contentEl = content;
318
+ const on = (el, type, fn, opts) => {
319
+ el.addEventListener(type, fn, opts);
320
+ this.cleanup.push(() => el.removeEventListener(type, fn, opts));
321
+ };
322
+ const ro = new ResizeObserver(() => this.measure());
323
+ ro.observe(viewport);
324
+ this.cleanup.push(() => ro.disconnect());
325
+ on(viewport, 'scroll', () => this.onScroll(), { passive: true });
326
+ on(viewport, 'wheel', (e) => this.onWheel(e), { passive: false });
327
+ on(viewport, 'pointerdown', (e) => this.onPointer(e));
328
+ on(viewport, 'pointermove', (e) => this.onPointer(e));
329
+ on(viewport, 'pointerup', (e) => this.onPointerEnd(e));
330
+ on(viewport, 'pointercancel', (e) => this.onPointerEnd(e));
331
+ on(root, 'keydown', (e) => this.onKeyDown(e));
332
+ on(root, 'salmon-pdf-text', (e) => this.drawMatches(e.detail));
333
+ on(root.ownerDocument, 'selectionchange', () => this.onSelection());
334
+ this.measure();
335
+ }
336
+ detach() {
337
+ for (const c of this.cleanup.splice(0))
338
+ c();
339
+ cancelAnimationFrame(this.frame);
340
+ clearTimeout(this.renderTimer);
341
+ clearTimeout(this.searchTimer);
342
+ clearTimeout(this.pinch.timer);
343
+ this.root = this.viewportEl = this.contentEl = null;
344
+ }
345
+ setThumbsElement(el) {
346
+ this.thumbsEl = el;
347
+ if (!el)
348
+ return undefined;
349
+ const onScroll = () => this.updateThumbs();
350
+ el.addEventListener('scroll', onScroll, { passive: true });
351
+ const ro = new ResizeObserver(onScroll);
352
+ ro.observe(el);
353
+ this.updateThumbs();
354
+ return () => {
355
+ el.removeEventListener('scroll', onScroll);
356
+ ro.disconnect();
357
+ this.thumbsEl = null;
358
+ };
359
+ }
360
+ setFindInput(el) {
361
+ this.findInput = el;
362
+ }
363
+ rtl() {
364
+ return !!this.root && this.root.ownerDocument.defaultView?.getComputedStyle(this.root).direction === 'rtl';
365
+ }
366
+ measure() {
367
+ const el = this.viewportEl;
368
+ if (!el)
369
+ return;
370
+ const viewport = { width: el.clientWidth, height: el.clientHeight };
371
+ if (viewport.width === this.state.viewport.width && viewport.height === this.state.viewport.height)
372
+ return this.updateVisible();
373
+ if (!(viewport.width > 0))
374
+ return;
375
+ this.relayout({ viewport });
376
+ }
377
+ onScroll() {
378
+ cancelAnimationFrame(this.frame);
379
+ this.frame = requestAnimationFrame(() => this.updateVisible());
380
+ }
381
+ updateVisible() {
382
+ const el = this.viewportEl;
383
+ const layout = this.state.layout;
384
+ const offset = el ? (layout.axis === 'x' ? Math.abs(el.scrollLeft) : el.scrollTop) : pageOffset(layout, this.state.page);
385
+ const extent = el ? (layout.axis === 'x' ? el.clientWidth : el.clientHeight) : this.state.viewport.height;
386
+ const v = visiblePages(layout, offset, extent || this.state.viewport.height, 1, this.pageRow);
387
+ let page = layout.mode === 'page' ? this.state.page : v.current;
388
+ if (this.lock && performance.now() < this.lock.until)
389
+ page = this.lock.page;
390
+ else
391
+ this.lock = null;
392
+ const visible = sameList(v.pages, this.state.visible) ? this.state.visible : v.pages;
393
+ const pageChanged = page !== this.state.page && page < this.state.sizes.length;
394
+ this.set({ visible, ...(pageChanged ? { page } : {}) });
395
+ if (pageChanged)
396
+ this.props.onPageChange?.(page + 1, { source: 'scroll' });
397
+ }
398
+ // Pages ---------------------------------------------------------------------------------
399
+ mountPage(index, el) {
400
+ this.mounted.set(index, el);
401
+ this.scheduleRender(0);
402
+ }
403
+ unmountPage(index, el) {
404
+ if (this.mounted.get(index) !== el)
405
+ return;
406
+ this.mounted.delete(index);
407
+ this.engine?.releasePage(index);
408
+ }
409
+ scheduleRender(delay) {
410
+ clearTimeout(this.renderTimer);
411
+ this.renderTimer = setTimeout(() => this.renderMounted(), delay);
412
+ }
413
+ renderMounted() {
414
+ const engine = this.engine;
415
+ if (!engine)
416
+ return;
417
+ const css = this.state.scale * PDF_TO_CSS;
418
+ this.renderedScale = this.state.scale;
419
+ const order = [...this.mounted.keys()].sort((a, b) => Math.abs(a - this.state.page) - Math.abs(b - this.state.page));
420
+ for (const index of order) {
421
+ const page = this.mounted.get(index);
422
+ const layer = (name) => page.querySelector(`:scope > .salmon-pdf-viewer__${name}`);
423
+ const layers = { page, canvas: layer('canvas-layer'), text: layer('text-layer'), annotations: layer('annotation-layer') };
424
+ if (!layers.canvas)
425
+ continue;
426
+ void engine.renderPage(index, layers, css).then(() => this.drawMatches(index));
427
+ }
428
+ for (const [index, canvas] of this.thumbCanvases)
429
+ if (!canvas.width || canvas.dataset['rendered'] !== '1')
430
+ this.renderThumb(index, canvas);
431
+ }
432
+ // Thumbnails ----------------------------------------------------------------------------
433
+ thumbHeight(index) {
434
+ const size = this.state.sizes[index] ?? LETTER;
435
+ return Math.round((THUMB_WIDTH * size.height) / size.width) + THUMB_EXTRA;
436
+ }
437
+ thumbOffset(index) {
438
+ let y = 0;
439
+ for (let i = 0; i < index; i++)
440
+ y += this.thumbHeight(i);
441
+ return y;
442
+ }
443
+ updateThumbs() {
444
+ const el = this.thumbsEl;
445
+ if (!el)
446
+ return;
447
+ const n = this.state.sizes.length;
448
+ const metrics = createVariableRowMetrics(n, (i) => this.thumbHeight(i));
449
+ const range = computeRange(metrics, el.scrollTop, el.clientHeight || 600, 2);
450
+ const thumbs = [];
451
+ for (let i = range.overscanStart; i < range.overscanEnd; i++)
452
+ thumbs.push(i);
453
+ if (!sameList(thumbs, this.state.thumbs))
454
+ this.set({ thumbs });
455
+ }
456
+ mountThumb(index, canvas) {
457
+ if (!canvas) {
458
+ this.thumbCanvases.delete(index);
459
+ return;
460
+ }
461
+ this.thumbCanvases.set(index, canvas);
462
+ this.renderThumb(index, canvas);
463
+ }
464
+ renderThumb(index, canvas) {
465
+ if (!this.engine)
466
+ return;
467
+ canvas.dataset['rendered'] = '1';
468
+ void this.engine.renderThumbnail(index, canvas, THUMB_WIDTH);
469
+ }
470
+ // Navigation and zoom ------------------------------------------------------------------
471
+ goToPage(index, source, notify = true) {
472
+ const n = this.state.sizes.length;
473
+ if (!n)
474
+ return;
475
+ const page = Math.max(0, Math.min(n - 1, Math.round(index)));
476
+ const layout = this.state.layout;
477
+ this.lock = { page, until: performance.now() + 400 };
478
+ this.pageRow = layout.rowOf[page] ?? 0;
479
+ const changed = page !== this.state.page;
480
+ this.set({ page });
481
+ const el = this.viewportEl;
482
+ if (el) {
483
+ if (layout.mode === 'page')
484
+ el.scrollTop = 0;
485
+ else if (layout.axis === 'x')
486
+ el.scrollLeft = (this.rtl() ? -1 : 1) * pageOffset(layout, page);
487
+ else
488
+ el.scrollTop = pageOffset(layout, page);
489
+ }
490
+ this.updateVisible();
491
+ if (changed && notify)
492
+ this.props.onPageChange?.(page + 1, { source });
493
+ }
494
+ setZoom(zoom, source) {
495
+ const value = typeof zoom === 'number' ? clampScale(zoom) : zoom;
496
+ const scale = this.scaleFor(value, this.state.sizes, this.state.viewport, this.props);
497
+ if (this.props.zoom === undefined)
498
+ this.relayout({ zoom: value });
499
+ this.props.onZoomChange?.(value, { scale, source });
500
+ }
501
+ zoomBy(direction, source) {
502
+ this.setZoom(stepScale(this.state.scale, direction), source);
503
+ }
504
+ onWheel(event) {
505
+ if (event.ctrlKey || event.metaKey) {
506
+ event.preventDefault();
507
+ this.transientZoom(this.pinch.factor * wheelFactor(event.deltaY), event.clientX, event.clientY, 'wheel');
508
+ return;
509
+ }
510
+ // 'page' mode: the wheel turns pages at the scroll ends.
511
+ const el = this.viewportEl;
512
+ if (this.state.layout.mode === 'page' && el && Math.abs(event.deltaY) > 20) {
513
+ const atEnd = el.scrollTop + el.clientHeight >= el.scrollHeight - 1;
514
+ const atStart = el.scrollTop <= 0;
515
+ if (event.deltaY > 0 && atEnd)
516
+ this.stepPage(1, 'wheel');
517
+ else if (event.deltaY < 0 && atStart)
518
+ this.stepPage(-1, 'wheel');
519
+ }
520
+ }
521
+ /** Pinch and Ctrl+wheel: a CSS transform while the gesture runs; the zoom commits when it settles. */
522
+ transientZoom(factor, x, y, source, commitAfter = 150) {
523
+ const content = this.contentEl;
524
+ if (!content)
525
+ return;
526
+ const min = 0.1 / this.state.scale;
527
+ const max = 10 / this.state.scale;
528
+ this.pinch.factor = Math.min(max, Math.max(min, factor));
529
+ const rect = content.getBoundingClientRect();
530
+ content.style.transformOrigin = `${x - rect.left}px ${y - rect.top}px`;
531
+ content.style.transform = `scale(${this.pinch.factor})`;
532
+ if (!this.state.pinching)
533
+ this.set({ pinching: true });
534
+ clearTimeout(this.pinch.timer);
535
+ if (commitAfter >= 0)
536
+ this.pinch.timer = setTimeout(() => this.commitPinch(source), commitAfter);
537
+ }
538
+ commitPinch(source) {
539
+ const content = this.contentEl;
540
+ const factor = this.pinch.factor;
541
+ this.pinch.factor = 1;
542
+ if (content) {
543
+ content.style.transform = '';
544
+ content.style.transformOrigin = '';
545
+ }
546
+ this.set({ pinching: false });
547
+ if (Math.abs(factor - 1) > 0.01)
548
+ this.setZoom(pinchScale(this.state.scale, factor), source);
549
+ }
550
+ onPointer(event) {
551
+ if (event.pointerType !== 'touch')
552
+ return;
553
+ const p = this.pinch;
554
+ if (event.type === 'pointerdown')
555
+ p.pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
556
+ else if (p.pointers.has(event.pointerId))
557
+ p.pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
558
+ if (p.pointers.size !== 2)
559
+ return;
560
+ const [a, b] = [...p.pointers.values()];
561
+ const dist = Math.hypot(a.x - b.x, a.y - b.y);
562
+ if (event.type === 'pointerdown' || !p.startDist) {
563
+ p.startDist = dist;
564
+ return;
565
+ }
566
+ event.preventDefault();
567
+ this.transientZoom(dist / p.startDist, (a.x + b.x) / 2, (a.y + b.y) / 2, 'pinch', -1);
568
+ }
569
+ onPointerEnd(event) {
570
+ const p = this.pinch;
571
+ if (!p.pointers.delete(event.pointerId))
572
+ return;
573
+ if (p.startDist && p.pointers.size < 2) {
574
+ p.startDist = 0;
575
+ this.commitPinch('pinch');
576
+ }
577
+ }
578
+ stepPage(delta, source) {
579
+ const layout = this.state.layout;
580
+ // Spreads step by row.
581
+ const row = (layout.rowOf[this.state.page] ?? 0) + delta;
582
+ const target = layout.rows[Math.max(0, Math.min(layout.rows.length - 1, row))]?.pages[0];
583
+ if (target !== undefined)
584
+ this.goToPage(target, source);
585
+ }
586
+ onKeyDown(event) {
587
+ const mod = isMac() ? event.metaKey : event.ctrlKey;
588
+ const key = event.key;
589
+ if (mod && !event.altKey) {
590
+ if (key === 'f' || key === 'F') {
591
+ event.preventDefault();
592
+ this.openFind(true);
593
+ return;
594
+ }
595
+ if (key === '=' || key === '+') {
596
+ event.preventDefault();
597
+ return this.zoomBy(1, 'keyboard');
598
+ }
599
+ if (key === '-' || key === '_') {
600
+ event.preventDefault();
601
+ return this.zoomBy(-1, 'keyboard');
602
+ }
603
+ if (key === '0') {
604
+ event.preventDefault();
605
+ return this.setZoom('auto', 'keyboard');
606
+ }
607
+ if (key === 'p' || key === 'P') {
608
+ event.preventDefault();
609
+ void this.print();
610
+ return;
611
+ }
612
+ }
613
+ if (event.target !== this.viewportEl || mod || event.altKey)
614
+ return;
615
+ const mode = this.state.layout.mode;
616
+ const paged = mode === 'page' || mode === 'horizontal';
617
+ const next = paged ? ['PageDown', 'ArrowRight', 'ArrowDown', 'n', 'j'] : ['n', 'j'];
618
+ const prev = paged ? ['PageUp', 'ArrowLeft', 'ArrowUp', 'p', 'k'] : ['p', 'k'];
619
+ const rtl = this.rtl() && (key === 'ArrowRight' || key === 'ArrowLeft');
620
+ if (next.includes(key) && !(event.shiftKey && key === ' ')) {
621
+ event.preventDefault();
622
+ this.stepPage(rtl ? -1 : 1, 'keyboard');
623
+ }
624
+ else if (prev.includes(key)) {
625
+ event.preventDefault();
626
+ this.stepPage(rtl ? 1 : -1, 'keyboard');
627
+ }
628
+ else if (key === 'Home') {
629
+ event.preventDefault();
630
+ this.goToPage(0, 'keyboard');
631
+ }
632
+ else if (key === 'End') {
633
+ event.preventDefault();
634
+ this.goToPage(this.state.sizes.length - 1, 'keyboard');
635
+ }
636
+ }
637
+ followOutline(item) {
638
+ if (item.page)
639
+ this.goToPage(item.page - 1, 'outline');
640
+ else if (item.url) {
641
+ const event = cancelable({ url: item.url, page: null });
642
+ this.props.onLinkClick?.(event);
643
+ if (!event.defaultPrevented)
644
+ this.root?.ownerDocument.defaultView?.open(item.url, this.props.linkTarget ?? '_blank', 'noopener,noreferrer');
645
+ }
646
+ }
647
+ // Panels ------------------------------------------------------------------------------
648
+ /**
649
+ * Mount, before paint: a `defaultSidebar` stays closed when the viewer is
650
+ * at most 480px wide, where the sidebar overlays the pages (pdf-viewer.css)
651
+ * and would cover the document. A controlled `sidebar` is left alone; no
652
+ * `onSidebarChange` (nothing changed from the user's side).
653
+ */
654
+ applyNarrowDefault(width) {
655
+ if (this.props.sidebar === undefined && this.state.sidebar !== null && width > 0 && width <= NARROW_WIDTH)
656
+ this.set({ sidebar: null });
657
+ }
658
+ setSidebar(sidebar) {
659
+ if (this.props.sidebar === undefined)
660
+ this.set({ sidebar });
661
+ this.props.onSidebarChange?.(sidebar);
662
+ }
663
+ openFind(open) {
664
+ this.set({ findOpen: open });
665
+ if (open)
666
+ queueMicrotask(() => requestAnimationFrame(() => this.findInput?.select()));
667
+ else {
668
+ this.setQuery('', true);
669
+ this.viewportEl?.focus({ preventScroll: true });
670
+ }
671
+ }
672
+ // Search ------------------------------------------------------------------------------
673
+ setFindOption(patch) {
674
+ this.set({ find: { ...this.state.find, ...patch } });
675
+ if ('highlightAll' in patch && Object.keys(patch).length === 1)
676
+ return this.redrawMatches();
677
+ this.runSearch(false);
678
+ }
679
+ setQuery(query, immediate = false) {
680
+ this.set({ find: { ...this.state.find, query } });
681
+ clearTimeout(this.searchTimer);
682
+ if (immediate)
683
+ this.runSearch(true);
684
+ else
685
+ this.searchTimer = setTimeout(() => this.runSearch(true), 150);
686
+ }
687
+ async search(query, options = {}) {
688
+ clearTimeout(this.searchTimer);
689
+ this.set({
690
+ find: {
691
+ query,
692
+ matchCase: options.matchCase ?? this.state.find.matchCase,
693
+ wholeWord: options.wholeWord ?? this.state.find.wholeWord,
694
+ highlightAll: options.highlightAll ?? this.state.find.highlightAll,
695
+ },
696
+ });
697
+ return this.runSearch(true);
698
+ }
699
+ async runSearch(jump) {
700
+ const run = ++this.searchRun;
701
+ const { query, matchCase, wholeWord } = this.state.find;
702
+ const engine = this.engine;
703
+ if (!query.trim() || !engine) {
704
+ this.matches = [];
705
+ this.set({ matchTotal: 0, matchIndex: -1, searching: false });
706
+ this.redrawMatches();
707
+ return this.result(true);
708
+ }
709
+ this.set({ searching: true });
710
+ if (this.texts.length !== engine.info.pageCount) {
711
+ const texts = [];
712
+ for (let i = 0; i < engine.info.pageCount; i++)
713
+ texts.push(await engine.pageText(i));
714
+ if (run !== this.searchRun)
715
+ return this.result(false);
716
+ this.texts = texts;
717
+ }
718
+ this.matches = findMatches(this.texts, query, { matchCase, wholeWord });
719
+ // The current match: the first one at or after the current page.
720
+ const start = this.matches.findIndex((m) => m.page >= this.state.page);
721
+ const matchIndex = this.matches.length ? (start < 0 ? 0 : start) : -1;
722
+ this.set({ matchTotal: this.matches.length, matchIndex, searching: false });
723
+ this.scrollToMatch = jump;
724
+ if (jump && matchIndex >= 0)
725
+ this.showMatch();
726
+ this.redrawMatches();
727
+ return this.result(true);
728
+ }
729
+ result(notify) {
730
+ const m = this.matches[this.state.matchIndex];
731
+ const result = { query: this.state.find.query, total: this.matches.length, current: m ? this.state.matchIndex + 1 : 0, page: m ? m.page + 1 : 0, pages: countByPage(this.matches) };
732
+ if (notify)
733
+ this.props.onSearchResult?.(result);
734
+ return result;
735
+ }
736
+ stepMatch(delta) {
737
+ const n = this.matches.length;
738
+ if (!n)
739
+ return;
740
+ const matchIndex = (((this.state.matchIndex + delta) % n) + n) % n;
741
+ this.set({ matchIndex });
742
+ this.scrollToMatch = true;
743
+ this.showMatch();
744
+ this.redrawMatches();
745
+ this.result(true);
746
+ }
747
+ showMatch() {
748
+ const m = this.matches[this.state.matchIndex];
749
+ if (!m)
750
+ return;
751
+ if (!this.state.visible.includes(m.page) || m.page !== this.state.page)
752
+ this.goToPage(m.page, 'search');
753
+ }
754
+ redrawMatches() {
755
+ for (const index of this.mounted.keys())
756
+ this.drawMatches(index);
757
+ }
758
+ /** Find highlights of one rendered page, as percentages of the page box (zoom independent). */
759
+ drawMatches(index) {
760
+ const page = this.mounted.get(index);
761
+ const layer = page?.querySelector(':scope > .salmon-pdf-viewer__find-layer');
762
+ if (!page || !layer || !this.engine)
763
+ return;
764
+ layer.replaceChildren();
765
+ const text = this.texts[index];
766
+ const spans = this.engine.textSpans(index);
767
+ if (!text || !spans.length)
768
+ return;
769
+ const { highlightAll } = this.state.find;
770
+ const pageRect = page.getBoundingClientRect();
771
+ if (!pageRect.width)
772
+ return;
773
+ const doc = page.ownerDocument;
774
+ let current = null;
775
+ this.matches.forEach((m, i) => {
776
+ if (m.page !== index)
777
+ return;
778
+ const isCurrent = i === this.state.matchIndex;
779
+ if (!isCurrent && !highlightAll)
780
+ return;
781
+ for (const [item, from, to] of matchPieces(text, m.start, m.end)) {
782
+ const node = spans[item]?.firstChild;
783
+ if (!node)
784
+ continue;
785
+ const range = doc.createRange();
786
+ try {
787
+ range.setStart(node, Math.min(from, node.textContent?.length ?? 0));
788
+ range.setEnd(node, Math.min(to, node.textContent?.length ?? 0));
789
+ }
790
+ catch {
791
+ continue;
792
+ }
793
+ for (const r of range.getClientRects()) {
794
+ const mark = doc.createElement('div');
795
+ mark.className = 'salmon-pdf-viewer__find-match';
796
+ if (isCurrent)
797
+ mark.setAttribute('data-current', '');
798
+ mark.style.left = `${((r.left - pageRect.left) / pageRect.width) * 100}%`;
799
+ mark.style.top = `${((r.top - pageRect.top) / pageRect.height) * 100}%`;
800
+ mark.style.width = `${(r.width / pageRect.width) * 100}%`;
801
+ mark.style.height = `${(r.height / pageRect.height) * 100}%`;
802
+ layer.append(mark);
803
+ current ??= isCurrent ? mark : null;
804
+ }
805
+ }
806
+ });
807
+ if (current && this.scrollToMatch) {
808
+ this.scrollToMatch = false;
809
+ this.lock = { page: index, until: performance.now() + 300 };
810
+ current.scrollIntoView({ block: 'center', inline: 'center' });
811
+ }
812
+ }
813
+ // Selection and text markup -------------------------------------------------------------
814
+ onSelection() {
815
+ const sel = this.root?.ownerDocument.getSelection();
816
+ const range = sel && sel.rangeCount && !sel.isCollapsed ? sel.getRangeAt(0) : null;
817
+ const inside = !!range && !!this.contentEl?.contains(range.commonAncestorContainer);
818
+ if (inside)
819
+ this.lastRange = range.cloneRange();
820
+ this.set({ hasSelection: inside || (!!this.lastRange && !!sel && !sel.isCollapsed && !!this.root?.contains(sel.anchorNode)) });
821
+ }
822
+ addTextMarkup(kind, options = {}) {
823
+ const geometry = this.state.geometry;
824
+ const sel = this.root?.ownerDocument.getSelection();
825
+ const live = sel && sel.rangeCount && !sel.isCollapsed ? sel.getRangeAt(0) : null;
826
+ const range = live && this.contentEl?.contains(live.commonAncestorContainer) ? live : this.lastRange;
827
+ if (!range || !geometry)
828
+ return [];
829
+ const text = range.toString().replace(/\s+/g, ' ').trim();
830
+ const rects = [...range.getClientRects()];
831
+ const created = [];
832
+ const css = this.state.scale * PDF_TO_CSS;
833
+ for (const [index, el] of this.mounted) {
834
+ const box = el.getBoundingClientRect();
835
+ const local = rects
836
+ .filter((r) => {
837
+ const cx = r.left + r.width / 2;
838
+ const cy = r.top + r.height / 2;
839
+ return cx >= box.left && cx <= box.right && cy >= box.top && cy <= box.bottom;
840
+ })
841
+ .map((r) => ({ left: r.left - box.left, top: r.top - box.top, width: r.width, height: r.height }));
842
+ const lines = mergeLineRects(local);
843
+ if (!lines.length || !geometry[index])
844
+ continue;
845
+ created.push({
846
+ id: annotationId(),
847
+ kind,
848
+ page: index + 1,
849
+ rects: lines.map((r) => cssRectToPdf(geometry[index], css, r)),
850
+ color: options.color ?? this.props.annotationColors?.[kind] ?? DEFAULT_MARKUP_COLORS[kind],
851
+ ...(options.opacity !== undefined ? { opacity: options.opacity } : {}),
852
+ ...(this.props.annotationAuthor ? { author: this.props.annotationAuthor } : {}),
853
+ ...(options.comment ? { comment: options.comment } : {}),
854
+ ...(text ? { text } : {}),
855
+ createdAt: new Date().toISOString(),
856
+ });
857
+ }
858
+ created.sort((a, b) => a.page - b.page);
859
+ let list = this.annotations();
860
+ for (const annotation of created) {
861
+ list = [...list, annotation];
862
+ if (this.props.annotations === undefined)
863
+ this.set({ annotations: list });
864
+ this.props.onAnnotationsChange?.(list, { reason: 'create', annotation });
865
+ }
866
+ if (created.length) {
867
+ sel?.removeAllRanges();
868
+ this.lastRange = null;
869
+ this.set({ hasSelection: false });
870
+ }
871
+ return created;
872
+ }
873
+ removeAnnotation(id) {
874
+ const list = this.annotations();
875
+ const annotation = list.find((a) => a.id === id);
876
+ if (!annotation)
877
+ return;
878
+ const next = list.filter((a) => a.id !== id);
879
+ if (this.props.annotations === undefined)
880
+ this.set({ annotations: next });
881
+ this.props.onAnnotationsChange?.(next, { reason: 'remove', annotation });
882
+ }
883
+ // Forms --------------------------------------------------------------------------------
884
+ formInput(name, value) {
885
+ const engine = this.engine;
886
+ if (!engine)
887
+ return;
888
+ const values = { ...engine.formValues(), ...this.props.formValues, [name]: value };
889
+ this.props.onFormValuesChange?.(values, { name });
890
+ }
891
+ // Print and save ------------------------------------------------------------------------
892
+ async print() {
893
+ const event = cancelable({});
894
+ this.props.onBeforePrint?.(event);
895
+ if (event.defaultPrevented || !this.engine || this.printing)
896
+ return false;
897
+ this.printing = true;
898
+ const doc = this.root?.ownerDocument ?? document;
899
+ try {
900
+ const container = await this.engine.print(this.props.printResolution ?? 150, this.annotations());
901
+ doc.body.append(container);
902
+ await Promise.all([...container.querySelectorAll('img')].map((img) => img.decode().catch(() => { })));
903
+ const win = doc.defaultView ?? window;
904
+ const done = () => {
905
+ win.removeEventListener('afterprint', done);
906
+ for (const img of container.querySelectorAll('img'))
907
+ if (img.src.startsWith('blob:'))
908
+ URL.revokeObjectURL(img.src);
909
+ container.remove();
910
+ };
911
+ win.addEventListener('afterprint', done);
912
+ win.print();
913
+ setTimeout(done, 1000);
914
+ return true;
915
+ }
916
+ finally {
917
+ this.printing = false;
918
+ }
919
+ }
920
+ async save() {
921
+ if (!this.engine)
922
+ throw new Error('PdfViewer: no document is loaded.');
923
+ const bytes = await this.engine.save(this.annotations());
924
+ return new Blob([bytes], { type: 'application/pdf' });
925
+ }
926
+ async download(fileName) {
927
+ const blob = await this.save();
928
+ const doc = this.root?.ownerDocument ?? document;
929
+ const a = doc.createElement('a');
930
+ a.href = URL.createObjectURL(blob);
931
+ a.download = fileName ?? this.props.fileName ?? 'document.pdf';
932
+ a.style.display = 'none';
933
+ doc.body.append(a);
934
+ a.click();
935
+ a.remove();
936
+ setTimeout(() => URL.revokeObjectURL(a.href), 30_000);
937
+ }
938
+ }
939
+ //# sourceMappingURL=core.js.map