@repa/document-viewer 0.0.0-stage → 0.1.0-alpha.20

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/dist/index.js ADDED
@@ -0,0 +1,904 @@
1
+ import init, { DocumentViewerEngine, dsdx_font_requirements_json } from '../wasm/document_viewer_wasm.js';
2
+
3
+ // src/wasm-runtime.ts
4
+ var initialized = null;
5
+ async function loadViewerWasm() {
6
+ initialized ??= init().then(() => void 0);
7
+ await initialized;
8
+ }
9
+
10
+ // ../document-surface/src/page-surface.ts
11
+ var DocumentPageSurface = class {
12
+ #options;
13
+ #pages = /* @__PURE__ */ new Map();
14
+ #selectionLayers = /* @__PURE__ */ new Map();
15
+ #resizeObserver;
16
+ #fixedDpr;
17
+ #snapshot = null;
18
+ #selection = null;
19
+ #zoom;
20
+ #dpr;
21
+ #lastContainerSize = "";
22
+ #activePointer = null;
23
+ #lastSelectionTap = null;
24
+ #lastPointerInput = null;
25
+ #gestureMode;
26
+ #pendingTargetPointer = null;
27
+ constructor(options) {
28
+ this.#options = options;
29
+ this.#zoom = positive(options.initialZoom ?? 1, "initialZoom");
30
+ this.#gestureMode = options.initialGestureMode ?? "text";
31
+ this.#fixedDpr = options.devicePixelRatio !== void 0;
32
+ this.#dpr = positive(
33
+ options.devicePixelRatio ?? globalThis.devicePixelRatio ?? 1,
34
+ "devicePixelRatio"
35
+ );
36
+ options.container.replaceChildren();
37
+ options.container.dataset.repaDocumentViewer = "";
38
+ this.#resizeObserver = typeof globalThis.ResizeObserver === "function" ? new globalThis.ResizeObserver(() => this.#handleContainerResize()) : null;
39
+ this.#resizeObserver?.observe(options.container);
40
+ }
41
+ render(snapshot) {
42
+ this.#clearPointerTarget();
43
+ this.#snapshot = snapshot;
44
+ const fragment = document.createDocumentFragment();
45
+ this.#pages.clear();
46
+ this.#selectionLayers.clear();
47
+ for (const page of snapshot.pages) {
48
+ const shell = document.createElement("div");
49
+ const canvas = document.createElement("canvas");
50
+ const selectionLayer = document.createElement("div");
51
+ shell.dataset.repaDocumentPage = String(page.pageIndex);
52
+ shell.style.width = `${page.widthPt * this.#zoom}px`;
53
+ shell.style.height = `${page.heightPt * this.#zoom}px`;
54
+ shell.style.position = "relative";
55
+ canvas.style.display = "block";
56
+ canvas.style.width = "100%";
57
+ canvas.style.height = "100%";
58
+ canvas.style.touchAction = this.#touchAction();
59
+ selectionLayer.dataset.repaDocumentSelection = String(page.pageIndex);
60
+ selectionLayer.style.position = "absolute";
61
+ selectionLayer.style.inset = "0";
62
+ selectionLayer.style.pointerEvents = "none";
63
+ this.#bindPointerEvents(canvas, page.pageIndex);
64
+ shell.append(canvas, selectionLayer);
65
+ fragment.append(shell);
66
+ this.#pages.set(page.pageIndex, shell);
67
+ this.#selectionLayers.set(page.pageIndex, selectionLayer);
68
+ this.#options.engine.attach_page_canvas(
69
+ page.pageIndex,
70
+ canvas,
71
+ this.#zoom,
72
+ this.#dpr
73
+ );
74
+ }
75
+ this.#options.container.replaceChildren(fragment);
76
+ }
77
+ setZoom(zoom, snapshot, selection) {
78
+ this.#zoom = positive(zoom, "zoom");
79
+ if (!snapshot) return;
80
+ this.render(snapshot);
81
+ this.paintSelection(selection);
82
+ }
83
+ setDevicePixelRatio(devicePixelRatio, snapshot, selection) {
84
+ this.#dpr = positive(devicePixelRatio, "devicePixelRatio");
85
+ this.#fixedDpr = true;
86
+ if (!snapshot) return;
87
+ this.render(snapshot);
88
+ this.paintSelection(selection);
89
+ }
90
+ resize(snapshot, selection) {
91
+ if (!this.#fixedDpr) {
92
+ this.#dpr = positive(
93
+ globalThis.devicePixelRatio ?? 1,
94
+ "devicePixelRatio"
95
+ );
96
+ }
97
+ this.#lastContainerSize = containerSize(this.#options.container);
98
+ if (!snapshot) return;
99
+ this.render(snapshot);
100
+ this.paintSelection(selection);
101
+ }
102
+ scrollToPage(pageIndex) {
103
+ this.#pages.get(pageIndex)?.scrollIntoView({ block: "start" });
104
+ }
105
+ setGestureMode(mode) {
106
+ if (mode !== "text" && mode !== "target")
107
+ throw new Error(`Unsupported document gesture mode: ${String(mode)}`);
108
+ if (this.#gestureMode === mode) return;
109
+ this.#gestureMode = mode;
110
+ this.#activePointer = null;
111
+ this.#pendingTargetPointer = null;
112
+ this.#clearPointerTarget();
113
+ for (const shell of this.#pages.values()) {
114
+ const canvas = shell.querySelector("canvas");
115
+ if (canvas) canvas.style.touchAction = this.#touchAction();
116
+ }
117
+ }
118
+ paintSelection(selection) {
119
+ this.#selection = selection;
120
+ for (const layer of this.#selectionLayers.values()) layer.replaceChildren();
121
+ if (!selection) return;
122
+ for (const rect of selection.geometry.rects) {
123
+ const layer = this.#selectionLayers.get(rect.pageIndex);
124
+ if (!layer) continue;
125
+ const highlight = document.createElement("div");
126
+ highlight.style.position = "absolute";
127
+ highlight.style.left = `${rect.xPt * this.#zoom}px`;
128
+ highlight.style.top = `${rect.yPt * this.#zoom}px`;
129
+ highlight.style.width = `${rect.widthPt * this.#zoom}px`;
130
+ highlight.style.height = `${rect.heightPt * this.#zoom}px`;
131
+ highlight.style.background = "rgba(47, 111, 237, 0.24)";
132
+ layer.append(highlight);
133
+ }
134
+ }
135
+ dispose() {
136
+ this.#clearPointerTarget();
137
+ this.#resizeObserver?.disconnect();
138
+ this.#pages.clear();
139
+ this.#selectionLayers.clear();
140
+ this.#options.container.replaceChildren();
141
+ delete this.#options.container.dataset.repaDocumentViewer;
142
+ }
143
+ #handleContainerResize() {
144
+ const size = containerSize(this.#options.container);
145
+ const nextDpr = this.#fixedDpr ? this.#dpr : positive(globalThis.devicePixelRatio ?? 1, "devicePixelRatio");
146
+ if (size === this.#lastContainerSize && nextDpr === this.#dpr) return;
147
+ this.#lastContainerSize = size;
148
+ this.#dpr = nextDpr;
149
+ if (!this.#snapshot) return;
150
+ const selection = this.#selection;
151
+ this.render(this.#snapshot);
152
+ this.paintSelection(selection);
153
+ }
154
+ #bindPointerEvents(canvas, pageIndex) {
155
+ canvas.addEventListener("pointerdown", (event) => {
156
+ if (event.button !== void 0 && event.button !== 0 || event.isPrimary === false)
157
+ return;
158
+ const point = this.#pagePoint(canvas, pageIndex, event);
159
+ try {
160
+ if (this.#gestureMode === "target") {
161
+ this.#pendingTargetPointer = {
162
+ pointerId: event.pointerId,
163
+ clientX: event.clientX,
164
+ clientY: event.clientY,
165
+ moved: false
166
+ };
167
+ return;
168
+ }
169
+ event.preventDefault();
170
+ this.#clearPointerTarget(canvas);
171
+ canvas.style.cursor = "text";
172
+ canvas.setPointerCapture(event.pointerId);
173
+ this.#activePointer = event.pointerId;
174
+ const clickCount = this.#selectionClickCount(event, pageIndex);
175
+ this.#options.onSelection(
176
+ this.#options.engine.begin_pointer_gesture(
177
+ point.pageIndex,
178
+ point.xPt,
179
+ point.yPt,
180
+ clickCount
181
+ ),
182
+ pointerInput(event)
183
+ );
184
+ } catch (cause) {
185
+ this.#options.onError(
186
+ "selection-failed",
187
+ "Could not begin selection",
188
+ cause
189
+ );
190
+ }
191
+ });
192
+ canvas.addEventListener("pointermove", (event) => {
193
+ const point = this.#pagePoint(canvas, pageIndex, event);
194
+ try {
195
+ if (this.#pendingTargetPointer?.pointerId === event.pointerId) {
196
+ const dx = event.clientX - this.#pendingTargetPointer.clientX;
197
+ const dy = event.clientY - this.#pendingTargetPointer.clientY;
198
+ if (dx * dx + dy * dy > 16) this.#pendingTargetPointer.moved = true;
199
+ }
200
+ if (this.#activePointer === event.pointerId) {
201
+ if (this.#lastSelectionTap?.pointerId === event.pointerId && squaredDistance(event, this.#lastSelectionTap) > 64)
202
+ this.#lastSelectionTap = null;
203
+ this.#options.onSelection(
204
+ this.#options.engine.extend_pointer_selection(
205
+ point.pageIndex,
206
+ point.xPt,
207
+ point.yPt
208
+ ),
209
+ pointerInput(event)
210
+ );
211
+ } else {
212
+ const input = pointerInput(event);
213
+ this.#lastPointerInput = input;
214
+ canvas.style.cursor = this.#options.onPointerTarget(
215
+ point,
216
+ input,
217
+ this.#options.engine.hit_test_pointer_target(
218
+ point.pageIndex,
219
+ point.xPt,
220
+ point.yPt
221
+ )
222
+ );
223
+ }
224
+ } catch (cause) {
225
+ this.#options.onError(
226
+ "pointer-failed",
227
+ "Could not resolve pointer target",
228
+ cause
229
+ );
230
+ }
231
+ });
232
+ const end = (event) => {
233
+ if (this.#activePointer === event.pointerId) this.#activePointer = null;
234
+ if (this.#pendingTargetPointer?.pointerId === event.pointerId) {
235
+ const pending = this.#pendingTargetPointer;
236
+ this.#pendingTargetPointer = null;
237
+ if (!pending.moved && this.#gestureMode === "target") {
238
+ const point = this.#pagePoint(canvas, pageIndex, event);
239
+ try {
240
+ this.#options.onPointerActivate?.(
241
+ point,
242
+ pointerInput(event),
243
+ this.#options.engine.hit_test_pointer_target(
244
+ point.pageIndex,
245
+ point.xPt,
246
+ point.yPt
247
+ )
248
+ );
249
+ } catch (cause) {
250
+ this.#options.onError(
251
+ "pointer-activation-failed",
252
+ "Could not activate pointer target",
253
+ cause
254
+ );
255
+ }
256
+ }
257
+ }
258
+ };
259
+ canvas.addEventListener("pointerup", end);
260
+ canvas.addEventListener("pointercancel", (event) => {
261
+ if (this.#lastSelectionTap?.pointerId === event.pointerId)
262
+ this.#lastSelectionTap = null;
263
+ if (this.#pendingTargetPointer?.pointerId === event.pointerId)
264
+ this.#pendingTargetPointer = null;
265
+ end(event);
266
+ this.#clearPointerTarget(canvas, pointerInput(event));
267
+ });
268
+ canvas.addEventListener("lostpointercapture", (event) => {
269
+ if (this.#activePointer !== event.pointerId) return;
270
+ end(event);
271
+ this.#clearPointerTarget(canvas, pointerInput(event));
272
+ });
273
+ canvas.addEventListener("pointerleave", (event) => {
274
+ if (this.#activePointer !== null) return;
275
+ if (this.#pendingTargetPointer?.pointerId === event.pointerId)
276
+ this.#pendingTargetPointer = null;
277
+ this.#clearPointerTarget(canvas, pointerInput(event));
278
+ });
279
+ }
280
+ #selectionClickCount(event, pageIndex) {
281
+ const pointerType = pointerInput(event).pointerType;
282
+ const previous = this.#lastSelectionTap;
283
+ const repeated = previous !== null && previous.pageIndex === pageIndex && previous.pointerType === pointerType && event.timeStamp - previous.timeStamp >= 0 && event.timeStamp - previous.timeStamp <= 400 && squaredDistance(event, previous) <= 576;
284
+ const count = repeated ? Math.min(3, previous.count + 1) : 1;
285
+ this.#lastSelectionTap = {
286
+ pageIndex,
287
+ pointerId: event.pointerId,
288
+ pointerType,
289
+ clientX: event.clientX,
290
+ clientY: event.clientY,
291
+ timeStamp: event.timeStamp,
292
+ count
293
+ };
294
+ return Math.max(count, event.detail || 0);
295
+ }
296
+ #clearPointerTarget(canvas, fallbackInput) {
297
+ const input = this.#lastPointerInput ?? fallbackInput;
298
+ this.#lastPointerInput = null;
299
+ if (canvas) canvas.style.cursor = "default";
300
+ if (input) this.#options.onPointerTargetLeave(input);
301
+ }
302
+ #pagePoint(canvas, pageIndex, event) {
303
+ if (this.#activePointer !== null) {
304
+ return this.#pointAtClient(event.clientX, event.clientY, pageIndex);
305
+ }
306
+ return pagePoint(
307
+ pageIndex,
308
+ event.clientX,
309
+ event.clientY,
310
+ canvas.getBoundingClientRect(),
311
+ this.#zoom
312
+ );
313
+ }
314
+ #pointAtClient(clientX, clientY, fallbackPage) {
315
+ let best;
316
+ for (const [pageIndex, element] of this.#pages) {
317
+ const bounds = element.getBoundingClientRect();
318
+ const dx = axisDistance(clientX, bounds.left, bounds.right);
319
+ const dy = axisDistance(clientY, bounds.top, bounds.bottom);
320
+ const distance = dx * dx + dy * dy;
321
+ if (!best || distance < best.distance)
322
+ best = { pageIndex, bounds, distance };
323
+ }
324
+ const resolved = best ?? {
325
+ pageIndex: fallbackPage,
326
+ bounds: this.#pages.get(fallbackPage)?.getBoundingClientRect() ?? new DOMRect()};
327
+ const point = pagePoint(
328
+ resolved.pageIndex,
329
+ clientX,
330
+ clientY,
331
+ resolved.bounds,
332
+ this.#zoom
333
+ );
334
+ const page = this.#snapshot?.pages[resolved.pageIndex];
335
+ return {
336
+ pageIndex: point.pageIndex,
337
+ xPt: clamp(point.xPt, 0, page?.widthPt ?? point.xPt),
338
+ yPt: clamp(point.yPt, 0, page?.heightPt ?? point.yPt)
339
+ };
340
+ }
341
+ #touchAction() {
342
+ return this.#gestureMode === "text" ? "pinch-zoom" : "pan-x pan-y pinch-zoom";
343
+ }
344
+ };
345
+ function squaredDistance(event, point) {
346
+ const dx = event.clientX - point.clientX;
347
+ const dy = event.clientY - point.clientY;
348
+ return dx * dx + dy * dy;
349
+ }
350
+ function pointerInput(event) {
351
+ const pointerType = event.pointerType === "mouse" || event.pointerType === "pen" || event.pointerType === "touch" ? event.pointerType : "unknown";
352
+ return {
353
+ pointerType,
354
+ isPrimary: event.isPrimary !== false,
355
+ buttons: event.buttons ?? 0,
356
+ modifiers: {
357
+ alt: event.altKey ?? false,
358
+ control: event.ctrlKey ?? false,
359
+ meta: event.metaKey ?? false,
360
+ shift: event.shiftKey ?? false
361
+ }
362
+ };
363
+ }
364
+ function pagePoint(pageIndex, clientX, clientY, bounds, zoom) {
365
+ return {
366
+ pageIndex,
367
+ xPt: (clientX - bounds.left) / zoom,
368
+ yPt: (clientY - bounds.top) / zoom
369
+ };
370
+ }
371
+ function axisDistance(value, start, end) {
372
+ return value < start ? start - value : value > end ? value - end : 0;
373
+ }
374
+ function clamp(value, minimum, maximum) {
375
+ return Math.min(maximum, Math.max(minimum, value));
376
+ }
377
+ function positive(value, label) {
378
+ if (!Number.isFinite(value) || value <= 0) {
379
+ throw new RangeError(`${label} must be positive`);
380
+ }
381
+ return value;
382
+ }
383
+ function containerSize(container) {
384
+ const bounds = container.getBoundingClientRect();
385
+ return `${bounds.width}:${bounds.height}`;
386
+ }
387
+
388
+ // src/types.ts
389
+ var DocumentViewerError = class extends Error {
390
+ code;
391
+ cause;
392
+ constructor(code, message, cause) {
393
+ super(message);
394
+ this.name = "DocumentViewerError";
395
+ this.code = code;
396
+ this.cause = cause;
397
+ }
398
+ };
399
+
400
+ // src/font-delivery.ts
401
+ var MAX_ACTIVE_READS = 6;
402
+ var READS_PER_DOCUMENT = 3;
403
+ var FONT_READ_TIMEOUT_MS = 3e4;
404
+ var FONT_LOAD_TIMEOUT_MS = 12e4;
405
+ var active = 0;
406
+ var waiting = [];
407
+ function acquire(signal) {
408
+ signal.throwIfAborted();
409
+ return new Promise((resolve, reject) => {
410
+ const waiter = {
411
+ signal,
412
+ grant() {
413
+ signal.removeEventListener("abort", waiter.abort);
414
+ active++;
415
+ let released = false;
416
+ resolve(() => {
417
+ if (released) return;
418
+ released = true;
419
+ active--;
420
+ drain();
421
+ });
422
+ },
423
+ abort() {
424
+ const index = waiting.indexOf(waiter);
425
+ if (index !== -1) waiting.splice(index, 1);
426
+ signal.removeEventListener("abort", waiter.abort);
427
+ reject(signal.reason);
428
+ }
429
+ };
430
+ waiting.push(waiter);
431
+ signal.addEventListener("abort", waiter.abort, { once: true });
432
+ drain();
433
+ });
434
+ }
435
+ function drain() {
436
+ while (active < MAX_ACTIVE_READS && waiting.length) {
437
+ const waiter = waiting.shift();
438
+ if (waiter.signal.aborted) waiter.abort();
439
+ else waiter.grant();
440
+ }
441
+ }
442
+ async function readViewerFonts(requirements, source, controller) {
443
+ controller.signal.throwIfAborted();
444
+ const deadline = setTimeout(() => controller.abort(new DocumentViewerError(
445
+ "font-load-timeout",
446
+ "Font loading exceeded its 120 second deadline. Retry the document load."
447
+ )), FONT_LOAD_TIMEOUT_MS);
448
+ const files = new Array(requirements.files.length);
449
+ let next = 0;
450
+ const worker = async () => {
451
+ while (next < requirements.files.length) {
452
+ controller.signal.throwIfAborted();
453
+ const index = next++, requirement = requirements.files[index];
454
+ const release = await acquire(controller.signal);
455
+ try {
456
+ controller.signal.throwIfAborted();
457
+ const value = await readSource(() => source(requirement, {
458
+ packageFingerprint: requirements.packageFingerprint,
459
+ signal: controller.signal
460
+ }), controller);
461
+ if (!(value instanceof Uint8Array))
462
+ throw new DocumentViewerError("invalid-font-source", `Font source did not return Uint8Array for ${requirement.fileHash}`);
463
+ if (value.byteLength !== requirement.byteLength)
464
+ throw new DocumentViewerError("invalid-font-length", `Font ${requirement.fileHash} has ${value.byteLength} bytes; expected ${requirement.byteLength}`);
465
+ files[index] = value;
466
+ } finally {
467
+ release();
468
+ }
469
+ }
470
+ };
471
+ try {
472
+ await Promise.all(Array.from({ length: Math.min(READS_PER_DOCUMENT, files.length) }, worker));
473
+ controller.signal.throwIfAborted();
474
+ return files;
475
+ } catch (error) {
476
+ controller.abort(error);
477
+ throw error;
478
+ } finally {
479
+ clearTimeout(deadline);
480
+ }
481
+ }
482
+ function readSource(read, controller) {
483
+ const { signal } = controller;
484
+ signal.throwIfAborted();
485
+ return new Promise((resolve, reject) => {
486
+ const abort = () => {
487
+ cleanup();
488
+ reject(signal.reason);
489
+ };
490
+ const timeout = setTimeout(() => controller.abort(new DocumentViewerError(
491
+ "font-read-timeout",
492
+ "Font delivery exceeded its 30 second deadline. Retry the document load."
493
+ )), FONT_READ_TIMEOUT_MS);
494
+ const cleanup = () => {
495
+ clearTimeout(timeout);
496
+ signal.removeEventListener("abort", abort);
497
+ };
498
+ signal.addEventListener("abort", abort, { once: true });
499
+ Promise.resolve().then(() => {
500
+ signal.throwIfAborted();
501
+ return read();
502
+ }).then(
503
+ (value) => {
504
+ cleanup();
505
+ resolve(value);
506
+ },
507
+ (error) => {
508
+ cleanup();
509
+ reject(error);
510
+ }
511
+ );
512
+ });
513
+ }
514
+
515
+ // src/viewer.ts
516
+ async function createDocumentViewer(options) {
517
+ try {
518
+ await loadViewerWasm();
519
+ } catch (cause) {
520
+ throw asViewerError(
521
+ "runtime-init-failed",
522
+ "Document viewer runtime initialization failed",
523
+ cause
524
+ );
525
+ }
526
+ try {
527
+ return new BrowserDocumentViewer(options);
528
+ } catch (cause) {
529
+ throw asViewerError(
530
+ "invalid-option",
531
+ "Document viewer creation failed",
532
+ cause
533
+ );
534
+ }
535
+ }
536
+ var BrowserDocumentViewer = class {
537
+ #options;
538
+ #engine = new DocumentViewerEngine();
539
+ #surface;
540
+ #snapshot = null;
541
+ #loadController = null;
542
+ #disposed = false;
543
+ #selectionMode;
544
+ #structureSelection = null;
545
+ #zoom;
546
+ #minimumZoom;
547
+ #maximumZoom;
548
+ constructor(options) {
549
+ this.#options = options;
550
+ this.#minimumZoom = positiveZoom(options.minimumZoom ?? 0.25, "minimumZoom");
551
+ this.#maximumZoom = positiveZoom(options.maximumZoom ?? 4, "maximumZoom");
552
+ if (this.#minimumZoom > this.#maximumZoom)
553
+ throw new RangeError("minimumZoom must not exceed maximumZoom");
554
+ this.#zoom = boundedZoom(
555
+ options.initialZoom ?? 1,
556
+ this.#minimumZoom,
557
+ this.#maximumZoom
558
+ );
559
+ this.#selectionMode = selectionMode(options.initialSelectionMode ?? "text");
560
+ this.#surface = new DocumentPageSurface({
561
+ container: options.container,
562
+ engine: this.#engine,
563
+ initialZoom: this.#zoom,
564
+ devicePixelRatio: options.devicePixelRatio,
565
+ initialGestureMode: this.#selectionMode === "text" ? "text" : "target",
566
+ onSelection: (json, input) => this.#emitSelection(
567
+ parse(json, "pointer selection"),
568
+ input
569
+ ),
570
+ onPointerTarget: (point, input, json) => {
571
+ const target = pointerTarget(point, json);
572
+ const event = { target, input };
573
+ options.onPointerTargetChange?.(event);
574
+ return options.resolvePointerCursor?.(event) ?? (this.#selectionMode === "text" ? target.selectableText ? "text" : "default" : hasStructureTarget(this.#selectionMode, target) ? "pointer" : "default");
575
+ },
576
+ onPointerTargetLeave: (input) => options.onPointerTargetChange?.({ target: null, input }),
577
+ onPointerActivate: (point, input, json) => this.#activateStructure(pointerTarget(point, json), input),
578
+ onError: (code, message, cause) => this.#report(code, message, cause)
579
+ });
580
+ }
581
+ get snapshot() {
582
+ return this.#snapshot;
583
+ }
584
+ async load(bytes) {
585
+ this.#assertLive();
586
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0) {
587
+ throw new DocumentViewerError(
588
+ "invalid-dsdx",
589
+ "DSDX bytes must not be empty"
590
+ );
591
+ }
592
+ this.#loadController?.abort();
593
+ const controller = new AbortController();
594
+ this.#loadController = controller;
595
+ try {
596
+ const requirements = parse(
597
+ dsdx_font_requirements_json(bytes),
598
+ "font requirements"
599
+ );
600
+ const fontFiles = await readViewerFonts(requirements, this.#options.fontFiles, controller);
601
+ if (controller.signal.aborted) {
602
+ throw new DOMException("Document load was superseded", "AbortError");
603
+ }
604
+ const snapshot = parse(
605
+ this.#engine.load(bytes, fontFiles),
606
+ "viewer snapshot"
607
+ );
608
+ this.#snapshot = snapshot;
609
+ this.#structureSelection = null;
610
+ this.#surface.render(snapshot);
611
+ this.#surface.paintSelection(this.selection());
612
+ return snapshot;
613
+ } catch (cause) {
614
+ const error = asViewerError(
615
+ "load-failed",
616
+ "Document viewer load failed",
617
+ cause
618
+ );
619
+ this.#options.onError?.(error);
620
+ throw error;
621
+ } finally {
622
+ if (this.#loadController === controller) this.#loadController = null;
623
+ }
624
+ }
625
+ setZoom(zoom) {
626
+ const next = boundedZoom(zoom, this.#minimumZoom, this.#maximumZoom);
627
+ if (next === this.#zoom) return;
628
+ this.#zoom = next;
629
+ this.#surface.setZoom(
630
+ next,
631
+ this.#snapshot,
632
+ this.#snapshot ? this.selection() : null
633
+ );
634
+ }
635
+ zoom() {
636
+ return this.#zoom;
637
+ }
638
+ setDevicePixelRatio(devicePixelRatio) {
639
+ this.#surface.setDevicePixelRatio(
640
+ devicePixelRatio,
641
+ this.#snapshot,
642
+ this.#snapshot ? this.selection() : null
643
+ );
644
+ }
645
+ resize() {
646
+ this.#surface.resize(
647
+ this.#snapshot,
648
+ this.#snapshot ? this.selection() : null
649
+ );
650
+ }
651
+ scrollToPage(pageIndex) {
652
+ this.#surface.scrollToPage(pageIndex);
653
+ }
654
+ selectionMode() {
655
+ return this.#selectionMode;
656
+ }
657
+ setSelectionMode(mode) {
658
+ this.#assertLive();
659
+ const next = selectionMode(mode);
660
+ if (next === this.#selectionMode) return;
661
+ this.#selectionMode = next;
662
+ this.#surface.setGestureMode(next === "text" ? "text" : "target");
663
+ if (this.#snapshot) this.#clearSelections();
664
+ }
665
+ selection() {
666
+ this.#assertLoaded();
667
+ return parse(
668
+ this.#engine.selection(),
669
+ "selection"
670
+ );
671
+ }
672
+ structureSelection() {
673
+ this.#assertLive();
674
+ return this.#structureSelection;
675
+ }
676
+ selectRanges(target) {
677
+ this.#assertLoaded();
678
+ try {
679
+ const selected = parse(
680
+ this.#engine.select_ranges(
681
+ JSON.stringify({
682
+ ...target,
683
+ direction: target.direction ?? "forward"
684
+ })
685
+ ),
686
+ "programmatic selection"
687
+ );
688
+ this.#emitSelection(selected, null);
689
+ return selected;
690
+ } catch (cause) {
691
+ const message = cause instanceof Error ? cause.message : String(cause);
692
+ throw asViewerError(
693
+ message.includes("StaleSnapshot") ? "stale-snapshot" : "selection-failed",
694
+ "Canonical ranges could not be selected",
695
+ cause
696
+ );
697
+ }
698
+ }
699
+ restoreSelection(selection) {
700
+ this.#assertLoaded();
701
+ try {
702
+ const restored = parse(
703
+ this.#engine.restore_selection(JSON.stringify(selection)),
704
+ "restored selection"
705
+ );
706
+ this.#emitSelection(restored, null);
707
+ return restored;
708
+ } catch (cause) {
709
+ const message = cause instanceof Error ? cause.message : String(cause);
710
+ throw asViewerError(
711
+ message.includes("StaleSnapshot") ? "stale-snapshot" : "selection-restore-failed",
712
+ "Selection could not be restored",
713
+ cause
714
+ );
715
+ }
716
+ }
717
+ clearSelection() {
718
+ this.#assertLoaded();
719
+ this.#clearSelections();
720
+ }
721
+ structures() {
722
+ this.#assertLoaded();
723
+ return parse(
724
+ this.#engine.structure_index(),
725
+ "structure index"
726
+ );
727
+ }
728
+ hitTestPointerTarget(point) {
729
+ this.#assertLoaded();
730
+ return pointerTarget(
731
+ point,
732
+ this.#engine.hit_test_pointer_target(
733
+ point.pageIndex,
734
+ point.xPt,
735
+ point.yPt
736
+ )
737
+ );
738
+ }
739
+ hitTestStructures(point) {
740
+ this.#assertLoaded();
741
+ return parse(
742
+ this.#engine.hit_test_structures(point.pageIndex, point.xPt, point.yPt),
743
+ "structure hit test"
744
+ );
745
+ }
746
+ structuresForSelection() {
747
+ this.#assertLoaded();
748
+ return parse(
749
+ this.#engine.selection_structures(),
750
+ "selection structures"
751
+ );
752
+ }
753
+ dispose() {
754
+ if (this.#disposed) return;
755
+ this.#disposed = true;
756
+ this.#loadController?.abort();
757
+ this.#engine.dispose();
758
+ this.#engine.free();
759
+ this.#surface.dispose();
760
+ }
761
+ #emitSelection(selection, input) {
762
+ if (this.#structureSelection) {
763
+ this.#structureSelection = null;
764
+ this.#options.onStructureSelectionChange?.({
765
+ selection: null,
766
+ input
767
+ });
768
+ }
769
+ this.#surface.paintSelection(selection);
770
+ const structures = this.structuresForSelection();
771
+ this.#options.onSelectionChange?.({ selection, structures, input });
772
+ }
773
+ #activateStructure(target, input) {
774
+ if (this.#selectionMode === "text") return;
775
+ const selected = structureSelection(this.#selectionMode, target);
776
+ if (!selected) return;
777
+ this.#engine.clear_selection();
778
+ this.#structureSelection = selected;
779
+ this.#surface.paintSelection({ geometry: { rects: selected.geometry } });
780
+ this.#options.onSelectionChange?.({
781
+ selection: null,
782
+ structures: null,
783
+ input
784
+ });
785
+ this.#options.onStructureSelectionChange?.({ selection: selected, input });
786
+ }
787
+ #clearSelections() {
788
+ this.#engine.clear_selection();
789
+ const hadStructureSelection = this.#structureSelection !== null;
790
+ this.#structureSelection = null;
791
+ this.#surface.paintSelection(null);
792
+ this.#options.onSelectionChange?.({
793
+ selection: null,
794
+ structures: null,
795
+ input: null
796
+ });
797
+ if (hadStructureSelection)
798
+ this.#options.onStructureSelectionChange?.({
799
+ selection: null,
800
+ input: null
801
+ });
802
+ }
803
+ #report(code, message, cause) {
804
+ this.#options.onError?.(asViewerError(code, message, cause));
805
+ }
806
+ #assertLoaded() {
807
+ this.#assertLive();
808
+ if (!this.#snapshot) {
809
+ throw new DocumentViewerError("not-loaded", "Load a DSDX document first");
810
+ }
811
+ return this.#snapshot;
812
+ }
813
+ #assertLive() {
814
+ if (this.#disposed) {
815
+ throw new DocumentViewerError("disposed", "Document viewer is disposed");
816
+ }
817
+ }
818
+ };
819
+ function positiveZoom(value, label) {
820
+ if (!Number.isFinite(value) || value <= 0)
821
+ throw new RangeError(`${label} must be positive`);
822
+ return value;
823
+ }
824
+ function boundedZoom(value, minimum, maximum) {
825
+ return Math.min(maximum, Math.max(minimum, positiveZoom(value, "zoom")));
826
+ }
827
+ function selectionMode(value) {
828
+ if (value !== "text" && value !== "block" && value !== "table" && value !== "row" && value !== "cell")
829
+ throw new Error(`Unsupported document selection mode: ${String(value)}`);
830
+ return value;
831
+ }
832
+ function structureSelection(mode, pointer) {
833
+ const packageFingerprint = pointer.packageFingerprint;
834
+ if (mode === "block") {
835
+ const target2 = smallestByGeometry(
836
+ pointer.structures.blocks,
837
+ (block) => block.rects
838
+ );
839
+ return target2 ? { packageFingerprint, kind: "block", target: target2, geometry: target2.rects } : null;
840
+ }
841
+ if (mode === "table") {
842
+ const target2 = smallestByGeometry(
843
+ pointer.structures.tables,
844
+ (table) => table.occurrences.map((occurrence) => occurrence.rect)
845
+ );
846
+ return target2 ? {
847
+ packageFingerprint,
848
+ kind: "table",
849
+ target: target2,
850
+ geometry: target2.occurrences.map((occurrence) => occurrence.rect)
851
+ } : null;
852
+ }
853
+ if (mode === "row") {
854
+ const target2 = smallestByGeometry(pointer.structures.rows, (row) => [row.rect]);
855
+ return target2 ? { packageFingerprint, kind: "row", target: target2, geometry: [target2.rect] } : null;
856
+ }
857
+ const target = smallestByGeometry(pointer.structures.cells, (cell) => [cell.rect]);
858
+ return target ? { packageFingerprint, kind: "cell", target, geometry: [target.rect] } : null;
859
+ }
860
+ function hasStructureTarget(mode, pointer) {
861
+ if (mode === "block") return pointer.structures.blocks.length > 0;
862
+ if (mode === "table") return pointer.structures.tables.length > 0;
863
+ if (mode === "row") return pointer.structures.rows.length > 0;
864
+ return pointer.structures.cells.length > 0;
865
+ }
866
+ function smallestByGeometry(values, geometry) {
867
+ let selected = null;
868
+ let selectedArea = Number.POSITIVE_INFINITY;
869
+ for (const value of values) {
870
+ const area = geometry(value).reduce(
871
+ (total, rect) => total + rect.widthPt * rect.heightPt,
872
+ 0
873
+ );
874
+ if (area < selectedArea) {
875
+ selected = value;
876
+ selectedArea = area;
877
+ }
878
+ }
879
+ return selected;
880
+ }
881
+ function pointerTarget(point, json) {
882
+ const target = parse(json, "pointer target");
883
+ return { ...target, point };
884
+ }
885
+ function parse(json, label) {
886
+ try {
887
+ return JSON.parse(json);
888
+ } catch (cause) {
889
+ throw new DocumentViewerError(
890
+ "invalid-runtime-payload",
891
+ `Invalid ${label}`,
892
+ cause
893
+ );
894
+ }
895
+ }
896
+ function asViewerError(code, message, cause) {
897
+ return cause instanceof DocumentViewerError ? cause : new DocumentViewerError(
898
+ code,
899
+ cause instanceof Error ? cause.message : message,
900
+ cause
901
+ );
902
+ }
903
+
904
+ export { DocumentViewerError, createDocumentViewer };