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

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