@soomo/text-annotator 3.1.0-staging.24 → 3.1.0-staging.25

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.
@@ -1,1433 +1,3 @@
1
- (function(global, factory) {
2
- typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("debounce"), require("colord"), require("dequal/lite"), require("uuid"), require("@annotorious/core"), require("rbush"), require("nanoevents"), require("hotkeys-js"), require("poll")) : typeof define === "function" && define.amd ? define(["exports", "debounce", "colord", "dequal/lite", "uuid", "@annotorious/core", "rbush", "nanoevents", "hotkeys-js", "poll"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.RecogitoJS = {}, global.debounce, global.Colord, global.DequalLite, global.UUID, global.AnnotoriousCore, global.RBush, global.nanoevents, global.HotkeysJs, global.poll));
3
- })(this, function(exports2, debounce, colord, lite, uuid, core, RBush, nanoevents, hotkeys, poll) {
4
- "use strict";
5
- const NOT_ANNOTATABLE_CLASS = "not-annotatable";
6
- const NOT_ANNOTATABLE_SELECTOR = `.${NOT_ANNOTATABLE_CLASS}`;
7
- const isNotAnnotatable = (node) => {
8
- var _a;
9
- const closestNotAnnotatable = node instanceof HTMLElement ? node.closest(NOT_ANNOTATABLE_SELECTOR) : (_a = node.parentElement) == null ? void 0 : _a.closest(NOT_ANNOTATABLE_SELECTOR);
10
- return Boolean(closestNotAnnotatable);
11
- };
12
- const isRangeAnnotatable = (range) => {
13
- const ancestor = range.commonAncestorContainer;
14
- return !isNotAnnotatable(ancestor);
15
- };
16
- const cancelSingleClickEvents = (container) => container.addEventListener("click", (event) => {
17
- const targetElement = event.target;
18
- const shouldPrevent = (
19
- // Allow clicks within not-annotatable elements
20
- !targetElement.closest(NOT_ANNOTATABLE_SELECTOR) && !event.target.closest("a")
21
- );
22
- if (shouldPrevent)
23
- event.preventDefault();
24
- });
25
- const isMac = /mac/i.test(navigator.userAgentData ? navigator.userAgentData.platform : navigator.platform);
26
- const programmaticallyFocusable = (container) => {
27
- if (!container.hasAttribute("tabindex") && container.tabIndex < 0) {
28
- container.setAttribute("tabindex", "-1");
29
- }
30
- container.classList.add("no-focus-outline");
31
- };
32
- const iterateNotAnnotatableElements = function* (range) {
33
- const notAnnotatableIterator = document.createNodeIterator(
34
- range.commonAncestorContainer,
35
- NodeFilter.SHOW_ELEMENT,
36
- (node) => node instanceof HTMLElement && node.classList.contains(NOT_ANNOTATABLE_CLASS) && !node.parentElement.closest(NOT_ANNOTATABLE_SELECTOR) && range.intersectsNode(node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP
37
- );
38
- let notAnnotatableNode;
39
- while (notAnnotatableNode = notAnnotatableIterator.nextNode()) {
40
- if (notAnnotatableNode instanceof HTMLElement) {
41
- yield notAnnotatableNode;
42
- }
43
- }
44
- };
45
- const splitAnnotatableRanges = (range) => {
46
- if (!isRangeAnnotatable(range)) return [];
47
- const annotatableRanges = [];
48
- let prevNotAnnotatable = null;
49
- for (const notAnnotatable of iterateNotAnnotatableElements(range)) {
50
- let subRange;
51
- if (!prevNotAnnotatable) {
52
- subRange = range.cloneRange();
53
- subRange.setEndBefore(notAnnotatable);
54
- } else {
55
- subRange = document.createRange();
56
- subRange.setStartAfter(prevNotAnnotatable);
57
- subRange.setEndBefore(notAnnotatable);
58
- }
59
- if (!subRange.collapsed)
60
- annotatableRanges.push(subRange);
61
- prevNotAnnotatable = notAnnotatable;
62
- }
63
- if (prevNotAnnotatable) {
64
- const lastRange = range.cloneRange();
65
- lastRange.setStartAfter(prevNotAnnotatable);
66
- if (!lastRange.collapsed) {
67
- annotatableRanges.push(lastRange);
68
- }
69
- }
70
- return annotatableRanges.length > 0 ? annotatableRanges : [range];
71
- };
72
- const getRangeAnnotatableContents = (range) => {
73
- const contents = range.cloneContents();
74
- contents.querySelectorAll(NOT_ANNOTATABLE_SELECTOR).forEach((el) => el.remove());
75
- return contents;
76
- };
77
- const getQuoteContext = (range, container, length = 10, offsetReferenceSelector) => {
78
- const offsetReference = offsetReferenceSelector ? range.startContainer.parentElement.closest(offsetReferenceSelector) : container;
79
- const rangeBefore = document.createRange();
80
- rangeBefore.setStart(offsetReference, 0);
81
- rangeBefore.setEnd(range.startContainer, range.startOffset);
82
- const before = getRangeAnnotatableContents(rangeBefore).textContent;
83
- const rangeAfter = document.createRange();
84
- rangeAfter.setStart(range.endContainer, range.endOffset);
85
- if (offsetReference === document.body)
86
- rangeAfter.setEnd(offsetReference, offsetReference.childNodes.length);
87
- else
88
- rangeAfter.setEndAfter(offsetReference);
89
- const after = getRangeAnnotatableContents(rangeAfter).textContent;
90
- return {
91
- prefix: before.substring(before.length - length),
92
- suffix: after.substring(0, length)
93
- };
94
- };
95
- const isRevived = (selector) => selector.every((s) => s.range instanceof Range && !s.range.collapsed);
96
- const whitespaceOrEmptyRegex = /^\s*$/;
97
- const isWhitespaceOrEmpty = (range) => whitespaceOrEmptyRegex.test(range.toString());
98
- const getRelation = (rectA, rectB) => {
99
- const round = (num) => Math.round(num * 10) / 10;
100
- const a = {
101
- top: round(rectA.top),
102
- bottom: round(rectA.bottom),
103
- left: round(rectA.left),
104
- right: round(rectA.right)
105
- };
106
- const b = {
107
- top: round(rectB.top),
108
- bottom: round(rectB.bottom),
109
- left: round(rectB.left),
110
- right: round(rectB.right)
111
- };
112
- if (Math.abs(a.top - b.top) < 0.5 && Math.abs(a.bottom - b.bottom) < 0.5) {
113
- if (Math.abs(a.left - b.right) < 0.5 || Math.abs(a.right - b.left) < 0.5)
114
- return "inline-adjacent";
115
- if (a.left >= b.left && a.right <= b.right)
116
- return "inline-is-contained";
117
- if (a.left <= b.left && a.right >= b.right)
118
- return "inline-contains";
119
- } else {
120
- if (a.top <= b.top && a.bottom >= b.bottom) {
121
- if (a.left <= b.left && a.right >= b.right) {
122
- return "block-contains";
123
- }
124
- } else if (a.top >= b.top && a.bottom <= b.bottom) {
125
- if (a.left >= b.left && a.right <= b.right) {
126
- return "block-is-contained";
127
- }
128
- }
129
- }
130
- };
131
- const union = (a, b) => {
132
- const left = Math.min(a.left, b.left);
133
- const right = Math.max(a.right, b.right);
134
- const top = Math.min(a.top, b.top);
135
- const bottom = Math.max(a.bottom, b.bottom);
136
- return new DOMRect(left, top, right - left, bottom - top);
137
- };
138
- const mergeClientRects = (rects) => rects.reduce((merged, rectA) => {
139
- if (rectA.width === 0 || rectA.height === 0)
140
- return merged;
141
- let next = [...merged];
142
- let wasMerged = false;
143
- for (const rectB of merged) {
144
- const relation = getRelation(rectA, rectB);
145
- if (relation === "inline-adjacent") {
146
- next = next.map((r) => r === rectB ? union(rectA, rectB) : r);
147
- wasMerged = true;
148
- break;
149
- } else if (relation === "inline-contains") {
150
- next = next.map((r) => r === rectB ? rectA : r);
151
- wasMerged = true;
152
- break;
153
- } else if (relation === "inline-is-contained") {
154
- wasMerged = true;
155
- break;
156
- } else if (relation === "block-contains" || relation === "block-is-contained") {
157
- if (rectA.width < rectB.width) {
158
- next = next.map((r) => r === rectB ? rectA : r);
159
- }
160
- wasMerged = true;
161
- break;
162
- }
163
- }
164
- return wasMerged ? next : [...next, rectA];
165
- }, []);
166
- const toDomRectList = (rects) => ({
167
- length: rects.length,
168
- item: (index) => rects[index],
169
- [Symbol.iterator]: function* () {
170
- for (let i = 0; i < this.length; i++)
171
- yield this.item(i);
172
- }
173
- });
174
- const rangeToSelector = (range, container, offsetReferenceSelector) => {
175
- const rangeBefore = document.createRange();
176
- const offsetReference = offsetReferenceSelector ? range.startContainer.parentElement.closest(offsetReferenceSelector) : container;
177
- rangeBefore.setStart(offsetReference, 0);
178
- rangeBefore.setEnd(range.startContainer, range.startOffset);
179
- const before = getRangeAnnotatableContents(rangeBefore).textContent;
180
- const quote = range.toString();
181
- const start = before.length || 0;
182
- const end = start + quote.length;
183
- return offsetReferenceSelector ? { quote, start, end, range, offsetReference } : { quote, start, end, range };
184
- };
185
- const reviveSelector = (selector, container) => {
186
- var _a, _b;
187
- const { start, end } = selector;
188
- const offsetReference = selector.offsetReference || container;
189
- const iterator = document.createNodeIterator(
190
- container,
191
- NodeFilter.SHOW_TEXT,
192
- (node) => {
193
- var _a2;
194
- return ((_a2 = node.parentElement) == null ? void 0 : _a2.closest(NOT_ANNOTATABLE_SELECTOR)) ? NodeFilter.FILTER_SKIP : NodeFilter.FILTER_ACCEPT;
195
- }
196
- );
197
- let runningOffset = 0;
198
- const range = document.createRange();
199
- let n = iterator.nextNode();
200
- if (n === null) console.error("Could not revive annotation target. Content missing.");
201
- let startCounting = !offsetReference;
202
- while (n !== null) {
203
- startCounting || (startCounting = offsetReference == null ? void 0 : offsetReference.contains(n));
204
- if (startCounting) {
205
- const len = ((_a = n.textContent) == null ? void 0 : _a.length) || 0;
206
- if (runningOffset + len > start) {
207
- range.setStart(n, start - runningOffset);
208
- break;
209
- }
210
- runningOffset += len;
211
- }
212
- n = iterator.nextNode();
213
- }
214
- while (n !== null) {
215
- const len = ((_b = n.textContent) == null ? void 0 : _b.length) || 0;
216
- if (runningOffset + len >= end) {
217
- range.setEnd(n, end - runningOffset);
218
- break;
219
- }
220
- runningOffset += len;
221
- n = iterator.nextNode();
222
- }
223
- return {
224
- ...selector,
225
- range
226
- };
227
- };
228
- const reviveTarget = (target, container) => isRevived(target.selector) ? target : {
229
- ...target,
230
- selector: target.selector.map((s) => s.range instanceof Range && !s.range.collapsed ? s : reviveSelector(s, container))
231
- };
232
- const reviveAnnotation = (annotation, container) => isRevived(annotation.target.selector) ? annotation : { ...annotation, target: reviveTarget(annotation.target, container) };
233
- const clonedNodeContains = (clonedNode, targetNode) => {
234
- if (clonedNode.isEqualNode(targetNode)) {
235
- return true;
236
- }
237
- for (let child of clonedNode.childNodes) {
238
- if (clonedNodeContains(child, targetNode)) {
239
- return true;
240
- }
241
- }
242
- return false;
243
- };
244
- const rangeContains = (range, node) => {
245
- const rangeContents = range.cloneContents();
246
- return clonedNodeContains(rangeContents, node);
247
- };
248
- const trimRangeToContainer = (range, container) => {
249
- const trimmedRange = range.cloneRange();
250
- const containsRangeStart = container.contains(trimmedRange.startContainer);
251
- const containsRangeEnd = container.contains(trimmedRange.endContainer);
252
- if (!containsRangeStart && !containsRangeEnd) {
253
- const containedWithinRange = rangeContains(trimmedRange, container);
254
- if (!containedWithinRange) {
255
- trimmedRange.collapse();
256
- return trimmedRange;
257
- }
258
- }
259
- if (!containsRangeStart) {
260
- trimmedRange.setStart(container, 0);
261
- }
262
- if (!containsRangeEnd) {
263
- trimmedRange.setEnd(container, container.childNodes.length);
264
- }
265
- return trimmedRange;
266
- };
267
- const clonePointerEvent = (event) => ({
268
- ...event,
269
- type: event.type,
270
- x: event.x,
271
- y: event.y,
272
- clientX: event.clientX,
273
- clientY: event.clientY,
274
- offsetX: event.offsetX,
275
- offsetY: event.offsetY,
276
- screenX: event.screenX,
277
- screenY: event.screenY,
278
- isPrimary: event.isPrimary,
279
- altKey: event.altKey,
280
- ctrlKey: event.ctrlKey,
281
- metaKey: event.metaKey,
282
- shiftKey: event.shiftKey,
283
- button: event.button,
284
- buttons: event.buttons,
285
- currentTarget: event.currentTarget,
286
- target: event.target,
287
- defaultPrevented: event.defaultPrevented,
288
- detail: event.detail,
289
- eventPhase: event.eventPhase,
290
- pointerId: event.pointerId,
291
- pointerType: event.pointerType,
292
- timeStamp: event.timeStamp
293
- });
294
- const cloneKeyboardEvent = (event) => ({
295
- ...event,
296
- type: event.type,
297
- key: event.key,
298
- code: event.code,
299
- location: event.location,
300
- repeat: event.repeat,
301
- altKey: event.altKey,
302
- ctrlKey: event.ctrlKey,
303
- metaKey: event.metaKey,
304
- shiftKey: event.shiftKey,
305
- currentTarget: event.currentTarget,
306
- target: event.target,
307
- defaultPrevented: event.defaultPrevented,
308
- detail: event.detail,
309
- timeStamp: event.timeStamp
310
- });
311
- const toParentBounds = (rect, offset) => {
312
- const { left, top, right, bottom } = rect;
313
- return new DOMRect(left - offset.left, top - offset.top, right - left, bottom - top);
314
- };
315
- const toViewportBounds = (rect, offset) => {
316
- const { left, top, right, bottom } = rect;
317
- return new DOMRect(left + offset.left, top + offset.top, right - left, bottom - top);
318
- };
319
- const getScrollParent = (el) => {
320
- if (el === null)
321
- return document.scrollingElement;
322
- const { overflowY } = window.getComputedStyle(el);
323
- const isScrollable = overflowY !== "visible" && overflowY !== "hidden";
324
- if (isScrollable && el.scrollHeight > el.clientHeight)
325
- return el;
326
- else
327
- return getScrollParent(el.parentElement);
328
- };
329
- const scrollIntoView = (container, store) => (annotationOrId) => {
330
- const id = typeof annotationOrId === "string" ? annotationOrId : annotationOrId.id;
331
- const scroll = (target) => {
332
- const parentBounds = scrollParent.getBoundingClientRect();
333
- const parentHeight = scrollParent.clientHeight;
334
- const parentWidth = scrollParent.clientWidth;
335
- const annotationBounds = target.selector[0].range.getBoundingClientRect();
336
- const { width, height } = store.getAnnotationBounds(id);
337
- const offsetTop = annotationBounds.top - parentBounds.top;
338
- const offsetLeft = annotationBounds.left - parentBounds.left;
339
- const scrollTop = scrollParent.parentElement ? scrollParent.scrollTop : 0;
340
- const scrollLeft = scrollParent.parentElement ? scrollParent.scrollLeft : 0;
341
- const top = offsetTop + scrollTop - (parentHeight - height) / 2;
342
- const left = offsetLeft + scrollLeft - (parentWidth - width) / 2;
343
- scrollParent.scroll({ top, left, behavior: "smooth" });
344
- };
345
- const scrollParent = getScrollParent(container);
346
- if (scrollParent) {
347
- const current = store.getAnnotation(id);
348
- const { range } = current.target.selector[0];
349
- if (range && !range.collapsed) {
350
- scroll(current.target);
351
- return true;
352
- } else {
353
- const revived = reviveTarget(current.target, container);
354
- const { range: range2 } = revived.selector[0];
355
- if (range2 && !range2.collapsed) {
356
- scroll(revived);
357
- return true;
358
- }
359
- }
360
- }
361
- return false;
362
- };
363
- const DEFAULT_STYLE = {
364
- fill: "rgb(0, 128, 255)",
365
- fillOpacity: 0.18
366
- };
367
- const DEFAULT_SELECTED_STYLE = {
368
- fill: "rgb(0, 128, 255)",
369
- fillOpacity: 0.45
370
- };
371
- const paint = (highlight, viewportBounds, style, painter, zIndex) => {
372
- var _a, _b;
373
- const base = style ? typeof style === "function" ? style(highlight.annotation, highlight.state, zIndex) || (((_a = highlight.state) == null ? void 0 : _a.selected) ? DEFAULT_SELECTED_STYLE : DEFAULT_STYLE) : style : ((_b = highlight.state) == null ? void 0 : _b.selected) ? DEFAULT_SELECTED_STYLE : DEFAULT_STYLE;
374
- return painter ? painter.paint(highlight, viewportBounds) || base : base;
375
- };
376
- const getViewportBounds = (container) => {
377
- const { top, left } = container.getBoundingClientRect();
378
- const { innerWidth, innerHeight } = window;
379
- const minX = -left;
380
- const minY = -top;
381
- const maxX = innerWidth - left;
382
- const maxY = innerHeight - top;
383
- return { top, left, minX, minY, maxX, maxY };
384
- };
385
- const trackViewport = (viewport) => {
386
- let visible = /* @__PURE__ */ new Set();
387
- const onDraw = (annotations) => {
388
- const ids = annotations.map((a) => a.id);
389
- if (visible.size !== ids.length || ids.some((id) => !visible.has(id))) {
390
- viewport.set(ids);
391
- }
392
- visible = new Set(ids);
393
- };
394
- return onDraw;
395
- };
396
- const createBaseRenderer = (container, state, viewport, renderer) => {
397
- const { store, selection, hover } = state;
398
- let currentStyle;
399
- let currentFilter;
400
- let currentPainter;
401
- const onDraw = trackViewport(viewport);
402
- const onPointerMove = (event) => {
403
- const { x, y } = container.getBoundingClientRect();
404
- const hit = store.getAt(event.clientX - x, event.clientY - y, false, currentFilter);
405
- if (hit) {
406
- if (hover.current !== hit.id) {
407
- container.classList.add("hovered");
408
- hover.set(hit.id);
409
- }
410
- } else {
411
- if (hover.current) {
412
- container.classList.remove("hovered");
413
- hover.set(null);
414
- }
415
- }
416
- };
417
- container.addEventListener("pointermove", onPointerMove);
418
- const redraw = (lazy = false) => {
419
- if (currentPainter)
420
- currentPainter.clear();
421
- const bounds = getViewportBounds(container);
422
- const { minX, minY, maxX, maxY } = bounds;
423
- const annotationsInView = currentFilter ? store.getIntersecting(minX, minY, maxX, maxY).filter(({ annotation }) => currentFilter(annotation)) : store.getIntersecting(minX, minY, maxX, maxY);
424
- const selectedIds = selection.selected.map(({ id }) => id);
425
- const highlights = annotationsInView.map(({ annotation, rects }) => {
426
- const selected = selectedIds.includes(annotation.id);
427
- const hovered = annotation.id === hover.current;
428
- return { annotation, rects, state: { selected, hover: hovered } };
429
- });
430
- renderer.redraw(highlights, bounds, currentStyle, currentPainter, lazy);
431
- setTimeout(() => onDraw(annotationsInView.map(({ annotation }) => annotation)), 1);
432
- };
433
- const setPainter = (painter) => {
434
- currentPainter = painter;
435
- redraw();
436
- };
437
- const setStyle = (style) => {
438
- currentStyle = style;
439
- redraw();
440
- };
441
- const setFilter = (filter) => {
442
- currentFilter = filter;
443
- redraw(false);
444
- };
445
- const onStoreChange = () => redraw();
446
- store.observe(onStoreChange);
447
- const unsubscribeSelection = selection.subscribe(() => redraw());
448
- const onScroll = () => redraw(true);
449
- document.addEventListener("scroll", onScroll, { capture: true, passive: true });
450
- const onResize = debounce(() => {
451
- store.recalculatePositions();
452
- currentPainter == null ? void 0 : currentPainter.reset();
453
- redraw();
454
- }, 10);
455
- window.addEventListener("resize", onResize);
456
- const resizeObserver = new ResizeObserver(onResize);
457
- resizeObserver.observe(container);
458
- const config = { attributes: true, childList: true, subtree: true };
459
- const mutationObserver = new MutationObserver((records) => {
460
- const isInternal = records.every((record) => record.target === container || container.contains(record.target));
461
- if (!isInternal) redraw(true);
462
- });
463
- mutationObserver.observe(document.body, config);
464
- const destroy = () => {
465
- container.removeEventListener("pointermove", onPointerMove);
466
- renderer.destroy();
467
- store.unobserve(onStoreChange);
468
- unsubscribeSelection();
469
- document.removeEventListener("scroll", onScroll);
470
- onResize.clear();
471
- window.removeEventListener("resize", onResize);
472
- resizeObserver.disconnect();
473
- mutationObserver.disconnect();
474
- };
475
- return {
476
- destroy,
477
- redraw,
478
- setStyle,
479
- setFilter,
480
- setPainter,
481
- setVisible: renderer.setVisible
482
- };
483
- };
484
- const createCanvas$1 = () => {
485
- const canvas = document.createElement("canvas");
486
- canvas.width = window.innerWidth;
487
- canvas.height = window.innerHeight;
488
- canvas.className = "r6o-canvas-highlight-layer bg";
489
- return canvas;
490
- };
491
- const resetCanvas = (canvas, highres) => {
492
- canvas.width = window.innerWidth;
493
- canvas.height = window.innerHeight;
494
- };
495
- const createRenderer$2 = (container) => {
496
- container.classList.add("r6o-annotatable");
497
- const canvas = createCanvas$1();
498
- const ctx = canvas.getContext("2d");
499
- document.body.appendChild(canvas);
500
- const redraw = (highlights, viewportBounds, currentStyle, currentPainter) => requestAnimationFrame(() => {
501
- const { width, height } = canvas;
502
- ctx.clearRect(-0.5, -0.5, width + 1, height + 1);
503
- if (currentPainter)
504
- currentPainter.clear();
505
- const { top, left } = viewportBounds;
506
- const highlightsByCreation = [...highlights].sort((highlightA, highlightB) => {
507
- const { annotation: { target: { created: createdA } } } = highlightA;
508
- const { annotation: { target: { created: createdB } } } = highlightB;
509
- return createdA.getTime() - createdB.getTime();
510
- });
511
- highlightsByCreation.forEach((h) => {
512
- var _a;
513
- const base = currentStyle ? typeof currentStyle === "function" ? currentStyle(h.annotation, h.state) : currentStyle : ((_a = h.state) == null ? void 0 : _a.selected) ? DEFAULT_SELECTED_STYLE : DEFAULT_STYLE;
514
- const style = currentPainter ? currentPainter.paint(h, viewportBounds) || base : base;
515
- const offsetRects = h.rects.map(({ x, y, width: width2, height: height2 }) => ({
516
- x: x + left,
517
- y: y + top,
518
- width: width2,
519
- height: height2
520
- }));
521
- ctx.fillStyle = style.fill;
522
- ctx.globalAlpha = style.fillOpacity || 1;
523
- offsetRects.forEach(
524
- ({ x, y, width: width2, height: height2 }) => ctx.fillRect(x, y, width2, height2)
525
- );
526
- if (style.underlineColor) {
527
- ctx.globalAlpha = 1;
528
- ctx.strokeStyle = style.underlineColor;
529
- ctx.lineWidth = style.underlineThickness ?? 1;
530
- const underlineOffset = style.underlineOffset ?? 0;
531
- offsetRects.forEach(({ x, y, width: width2, height: height2 }) => {
532
- ctx.beginPath();
533
- ctx.moveTo(x, y + height2 + underlineOffset);
534
- ctx.lineTo(x + width2, y + height2 + underlineOffset);
535
- ctx.stroke();
536
- });
537
- }
538
- });
539
- });
540
- const onResize = debounce(() => resetCanvas(canvas), 10);
541
- window.addEventListener("resize", onResize);
542
- const setVisible = (visible) => {
543
- console.log("setVisible not implemented on Canvas renderer");
544
- };
545
- const destroy = () => {
546
- canvas.remove();
547
- onResize.clear();
548
- window.removeEventListener("resize", onResize);
549
- };
550
- return {
551
- destroy,
552
- setVisible,
553
- redraw
554
- };
555
- };
556
- const createCanvasRenderer = (container, state, viewport) => createBaseRenderer(container, state, viewport, createRenderer$2(container));
557
- const toCSS = (s) => {
558
- const backgroundColor = colord.colord((s == null ? void 0 : s.fill) || DEFAULT_STYLE.fill).alpha((s == null ? void 0 : s.fillOpacity) === void 0 ? DEFAULT_STYLE.fillOpacity : s.fillOpacity).toHex();
559
- const rules = [
560
- `background-color:${backgroundColor}`,
561
- (s == null ? void 0 : s.underlineThickness) ? `text-decoration:underline` : void 0,
562
- (s == null ? void 0 : s.underlineColor) ? `text-decoration-color:${s.underlineColor}` : void 0,
563
- (s == null ? void 0 : s.underlineOffset) ? `text-underline-offset:${s.underlineOffset}px` : void 0,
564
- (s == null ? void 0 : s.underlineThickness) ? `text-decoration-thickness:${s.underlineThickness}px` : void 0
565
- ].filter(Boolean);
566
- return rules.join(";");
567
- };
568
- const createRenderer$1 = () => {
569
- const elem = document.createElement("style");
570
- document.getElementsByTagName("head")[0].appendChild(elem);
571
- let currentRendered = /* @__PURE__ */ new Set();
572
- const redraw = (highlights, viewportBounds, currentStyle, painter) => {
573
- if (painter)
574
- painter.clear();
575
- const nextRendered = new Set(highlights.map((h) => h.annotation.id));
576
- Array.from(currentRendered).filter((id) => !nextRendered.has(id));
577
- const updatedCSS = highlights.map((h) => {
578
- var _a;
579
- const base = currentStyle ? typeof currentStyle === "function" ? currentStyle(h.annotation, h.state) : currentStyle : ((_a = h.state) == null ? void 0 : _a.selected) ? DEFAULT_SELECTED_STYLE : DEFAULT_STYLE;
580
- const style = painter ? painter.paint(h, viewportBounds) || base : base;
581
- return `::highlight(_${h.annotation.id}) { ${toCSS(style)} }`;
582
- });
583
- elem.innerHTML = updatedCSS.join("\n");
584
- CSS.highlights.clear();
585
- highlights.forEach(({ annotation }) => {
586
- const ranges = annotation.target.selector.map((s) => s.range);
587
- const highlights2 = new Highlight(...ranges);
588
- CSS.highlights.set(`_${annotation.id}`, highlights2);
589
- });
590
- currentRendered = nextRendered;
591
- };
592
- const setVisible = (visible) => {
593
- console.log("setVisible not implemented on CSS Custom Highlights renderer");
594
- };
595
- const destroy = () => {
596
- CSS.highlights.clear();
597
- elem.remove();
598
- };
599
- return {
600
- destroy,
601
- setVisible,
602
- redraw
603
- };
604
- };
605
- const createHighlightsRenderer = (container, state, viewport) => createBaseRenderer(container, state, viewport, createRenderer$1());
606
- const computeZIndex = (rect, all) => {
607
- const intersects = (a, b) => a.x <= b.x + b.width && a.x + a.width >= b.x && a.y <= b.y + b.height && a.y + a.height >= b.y;
608
- const getLength = (h) => h.rects.reduce((total, rect2) => total + rect2.width, 0);
609
- const intersecting = all.filter(({ rects }) => rects.some((r) => intersects(rect, r)));
610
- intersecting.sort((a, b) => getLength(b) - getLength(a));
611
- return intersecting.findIndex((h) => h.rects.includes(rect));
612
- };
613
- const createRenderer = (container) => {
614
- container.classList.add("r6o-annotatable");
615
- const highlightLayer = document.createElement("div");
616
- highlightLayer.className = "r6o-span-highlight-layer";
617
- container.insertBefore(highlightLayer, container.firstChild);
618
- let currentRendered = [];
619
- const redraw = (highlights, viewportBounds, currentStyle, painter, lazy) => {
620
- const noChanges = lite.dequal(currentRendered, highlights);
621
- const shouldRedraw = !(noChanges && lazy);
622
- if (!painter && !shouldRedraw) return;
623
- if (shouldRedraw)
624
- highlightLayer.innerHTML = "";
625
- const sorted = [...highlights].sort((highlightA, highlightB) => {
626
- const { annotation: { target: { created: createdA } } } = highlightA;
627
- const { annotation: { target: { created: createdB } } } = highlightB;
628
- return createdA && createdB ? createdA.getTime() - createdB.getTime() : 0;
629
- });
630
- sorted.forEach((highlight) => {
631
- highlight.rects.map((rect) => {
632
- const zIndex = computeZIndex(rect, highlights);
633
- const style = paint(highlight, viewportBounds, currentStyle, painter, zIndex);
634
- if (shouldRedraw) {
635
- const span = document.createElement("span");
636
- span.className = "r6o-annotation";
637
- span.dataset.annotation = highlight.annotation.id;
638
- span.style.left = `${rect.x}px`;
639
- span.style.top = `${rect.y}px`;
640
- span.style.width = `${rect.width}px`;
641
- span.style.height = `${rect.height}px`;
642
- span.style.backgroundColor = colord.colord((style == null ? void 0 : style.fill) || DEFAULT_STYLE.fill).alpha((style == null ? void 0 : style.fillOpacity) === void 0 ? DEFAULT_STYLE.fillOpacity : style.fillOpacity).toHex();
643
- if (style.underlineStyle)
644
- span.style.borderStyle = style.underlineStyle;
645
- if (style.underlineColor)
646
- span.style.borderColor = style.underlineColor;
647
- if (style.underlineThickness)
648
- span.style.borderBottomWidth = `${style.underlineThickness}px`;
649
- if (style.underlineOffset)
650
- span.style.paddingBottom = `${style.underlineOffset}px`;
651
- highlightLayer.appendChild(span);
652
- }
653
- });
654
- });
655
- currentRendered = highlights;
656
- };
657
- const setVisible = (visible) => {
658
- if (visible)
659
- highlightLayer.classList.remove("hidden");
660
- else
661
- highlightLayer.classList.add("hidden");
662
- };
663
- const destroy = () => {
664
- highlightLayer.remove();
665
- };
666
- return {
667
- destroy,
668
- redraw,
669
- setVisible
670
- };
671
- };
672
- const createSpansRenderer = (container, state, viewport) => createBaseRenderer(container, state, viewport, createRenderer(container));
673
- const W3CTextFormat = (source, container) => ({
674
- parse: (serialized) => parseW3CTextAnnotation(serialized),
675
- serialize: (annotation) => serializeW3CTextAnnotation(annotation, source, container)
676
- });
677
- const isTextSelector = (selector) => selector.quote !== void 0 && selector.start !== void 0 && selector.end !== void 0;
678
- const parseW3CTextTargets = (annotation) => {
679
- const {
680
- id: annotationId,
681
- creator,
682
- created,
683
- modified,
684
- target
685
- } = annotation;
686
- const w3cTargets = Array.isArray(target) ? target : [target];
687
- if (w3cTargets.length === 0) {
688
- return { error: Error(`No targets found for annotation: ${annotation.id}`) };
689
- }
690
- const parsed = {
691
- creator: core.parseW3CUser(creator),
692
- created: created ? new Date(created) : void 0,
693
- updated: modified ? new Date(modified) : void 0,
694
- annotation: annotationId,
695
- selector: [],
696
- // @ts-expect-error: `styleClass` is not part of the core `TextAnnotationTarget` type
697
- styleClass: "styleClass" in w3cTargets[0] ? w3cTargets[0].styleClass : void 0
698
- };
699
- for (const w3cTarget of w3cTargets) {
700
- const w3cSelectors = Array.isArray(w3cTarget.selector) ? w3cTarget.selector : [w3cTarget.selector];
701
- const selector = w3cSelectors.reduce((s, w3cSelector) => {
702
- switch (w3cSelector.type) {
703
- case "TextQuoteSelector":
704
- s.quote = w3cSelector.exact;
705
- break;
706
- case "TextPositionSelector":
707
- s.start = w3cSelector.start;
708
- s.end = w3cSelector.end;
709
- break;
710
- }
711
- return s;
712
- }, {});
713
- if (isTextSelector(selector)) {
714
- parsed.selector.push(
715
- {
716
- ...selector,
717
- id: w3cTarget.id,
718
- // @ts-expect-error: `scope` is not part of the core `TextSelector` type
719
- scope: w3cTarget.scope
720
- }
721
- );
722
- } else {
723
- const missingTypes = [
724
- !selector.start ? "TextPositionSelector" : void 0,
725
- !selector.quote ? "TextQuoteSelector" : void 0
726
- ].filter(Boolean);
727
- return { error: Error(`Missing selector types: ${missingTypes.join(" and ")} for annotation: ${annotation.id}`) };
728
- }
729
- }
730
- return { parsed };
731
- };
732
- const parseW3CTextAnnotation = (annotation) => {
733
- const annotationId = annotation.id || uuid.v4();
734
- const {
735
- creator,
736
- created,
737
- modified,
738
- body,
739
- ...rest
740
- } = annotation;
741
- const bodies = core.parseW3CBodies(body, annotationId);
742
- const target = parseW3CTextTargets(annotation);
743
- const parseResult = "error" in target ? { error: target.error } : {
744
- parsed: {
745
- ...rest,
746
- id: annotationId,
747
- bodies,
748
- target: target.parsed
749
- }
750
- };
751
- return parseResult;
752
- };
753
- const serializeW3CTextAnnotation = (annotation, source, container) => {
754
- const { bodies, target, ...rest } = annotation;
755
- const {
756
- selector,
757
- creator,
758
- created,
759
- updated,
760
- ...targetRest
761
- } = target;
762
- const w3cTargets = selector.map((s) => {
763
- const { id, quote, start, end, range } = s;
764
- const { prefix, suffix } = getQuoteContext(range, container);
765
- const w3cSelectors = [{
766
- type: "TextQuoteSelector",
767
- exact: quote,
768
- prefix,
769
- suffix
770
- }, {
771
- type: "TextPositionSelector",
772
- start,
773
- end
774
- }];
775
- return {
776
- ...targetRest,
777
- id,
778
- // @ts-expect-error: `scope` is not part of the core `TextSelector` type
779
- scope: "scope" in s ? s.scope : void 0,
780
- source,
781
- selector: w3cSelectors
782
- };
783
- });
784
- return {
785
- ...rest,
786
- "@context": "http://www.w3.org/ns/anno.jsonld",
787
- id: annotation.id,
788
- type: "Annotation",
789
- body: core.serializeW3CBodies(annotation.bodies),
790
- creator,
791
- created: created == null ? void 0 : created.toISOString(),
792
- modified: updated == null ? void 0 : updated.toISOString(),
793
- target: w3cTargets
794
- };
795
- };
796
- const createSpatialTree = (store, container) => {
797
- const tree = new RBush();
798
- const index = /* @__PURE__ */ new Map();
799
- const emitter = nanoevents.createNanoEvents();
800
- const toItems = (target, offset) => {
801
- const rects = target.selector.flatMap((s) => {
802
- const revivedRange = isRevived([s]) ? s.range : reviveSelector(s, container).range;
803
- return Array.from(revivedRange.getClientRects());
804
- });
805
- const merged = mergeClientRects(rects).map((rect) => toParentBounds(rect, offset));
806
- return merged.map((rect) => {
807
- const { x, y, width, height } = rect;
808
- return {
809
- minX: x,
810
- minY: y,
811
- maxX: x + width,
812
- maxY: y + height,
813
- annotation: {
814
- id: target.annotation,
815
- rects: merged
816
- }
817
- };
818
- });
819
- };
820
- const all = () => [...index.values()];
821
- const clear = () => {
822
- tree.clear();
823
- index.clear();
824
- };
825
- const insert = (target) => {
826
- const rects = toItems(target, container.getBoundingClientRect());
827
- if (rects.length === 0) return;
828
- rects.forEach((rect) => tree.insert(rect));
829
- index.set(target.annotation, rects);
830
- };
831
- const remove = (target) => {
832
- const rects = index.get(target.annotation);
833
- if (rects) {
834
- rects.forEach((rect) => tree.remove(rect));
835
- index.delete(target.annotation);
836
- }
837
- };
838
- const update = (target) => {
839
- remove(target);
840
- insert(target);
841
- };
842
- const set = (targets, replace = true) => {
843
- if (replace)
844
- clear();
845
- const offset = container.getBoundingClientRect();
846
- const rectsByTarget = targets.map((target) => ({ target, rects: toItems(target, offset) }));
847
- rectsByTarget.forEach(({ target, rects }) => {
848
- if (rects.length > 0)
849
- index.set(target.annotation, rects);
850
- });
851
- const allRects = rectsByTarget.flatMap(({ rects }) => rects);
852
- tree.load(allRects);
853
- };
854
- const getAt = (x, y, all2 = false) => {
855
- const hits = tree.search({
856
- minX: x,
857
- minY: y,
858
- maxX: x,
859
- maxY: y
860
- });
861
- const area = (rect) => rect.annotation.rects.reduce((area2, r) => area2 + r.width * r.height, 0);
862
- if (hits.length > 0) {
863
- hits.sort((a, b) => area(a) - area(b));
864
- return all2 ? hits.map((h) => h.annotation.id) : [hits[0].annotation.id];
865
- } else {
866
- return [];
867
- }
868
- };
869
- const getAnnotationBounds = (id) => {
870
- const rects = getAnnotationRects(id);
871
- if (rects.length === 0)
872
- return void 0;
873
- let left = rects[0].left;
874
- let top = rects[0].top;
875
- let right = rects[0].right;
876
- let bottom = rects[0].bottom;
877
- for (let i = 1; i < rects.length; i++) {
878
- const rect = rects[i];
879
- left = Math.min(left, rect.left);
880
- top = Math.min(top, rect.top);
881
- right = Math.max(right, rect.right);
882
- bottom = Math.max(bottom, rect.bottom);
883
- }
884
- return new DOMRect(left, top, right - left, bottom - top);
885
- };
886
- const getAnnotationRects = (id) => {
887
- const indexed = index.get(id);
888
- if (indexed) {
889
- return indexed[0].annotation.rects;
890
- } else {
891
- return [];
892
- }
893
- };
894
- const getIntersecting = (minX, minY, maxX, maxY) => {
895
- const rects = tree.search({ minX, minY, maxX, maxY });
896
- const annotationIds = new Set(rects.map((rect) => rect.annotation.id));
897
- return Array.from(annotationIds).map((annotationId) => ({
898
- annotation: store.getAnnotation(annotationId),
899
- rects: getAnnotationRects(annotationId)
900
- })).filter((t) => Boolean(t.annotation));
901
- };
902
- const size = () => tree.all().length;
903
- const recalculate = () => {
904
- set(store.all().map((a) => a.target), true);
905
- emitter.emit("recalculate");
906
- };
907
- const on = (event, callback) => emitter.on(event, callback);
908
- return {
909
- all,
910
- clear,
911
- getAt,
912
- getAnnotationBounds,
913
- getAnnotationRects,
914
- getIntersecting,
915
- insert,
916
- recalculate,
917
- remove,
918
- set,
919
- size,
920
- update,
921
- on
922
- };
923
- };
924
- const createTextAnnotatorState = (container, opts) => {
925
- const store = core.createStore();
926
- const tree = createSpatialTree(store, container);
927
- const selection = core.createSelectionState(store, opts.userSelectAction, opts.adapter);
928
- const hover = core.createHoverState(store);
929
- const viewport = core.createViewportState();
930
- const addAnnotation = (annotation, origin = core.Origin.LOCAL) => {
931
- const revived = reviveAnnotation(annotation, container);
932
- const isValid = isRevived(revived.target.selector);
933
- if (isValid)
934
- store.addAnnotation(revived, origin);
935
- return isValid;
936
- };
937
- const bulkAddAnnotation = (annotations, replace = true, origin = core.Origin.LOCAL) => {
938
- const revived = annotations.map((a) => reviveAnnotation(a, container));
939
- const couldNotRevive = revived.filter((a) => !isRevived(a.target.selector));
940
- store.bulkAddAnnotation(revived, replace, origin);
941
- return couldNotRevive;
942
- };
943
- const bulkUpsertAnnotations = (annotations, origin = core.Origin.LOCAL) => {
944
- const revived = annotations.map((a) => reviveAnnotation(a, container));
945
- const couldNotRevive = revived.filter((a) => !isRevived(a.target.selector));
946
- revived.forEach((a) => {
947
- if (store.getAnnotation(a.id))
948
- store.updateAnnotation(a, origin);
949
- else
950
- store.addAnnotation(a, origin);
951
- });
952
- return couldNotRevive;
953
- };
954
- const updateTarget = (target, origin = core.Origin.LOCAL) => {
955
- const revived = reviveTarget(target, container);
956
- store.updateTarget(revived, origin);
957
- };
958
- const bulkUpdateTargets = (targets, origin = core.Origin.LOCAL) => {
959
- const revived = targets.map((t) => reviveTarget(t, container));
960
- store.bulkUpdateTargets(revived, origin);
961
- };
962
- function getAt(x, y, all, filter) {
963
- const getAll = all || Boolean(filter);
964
- const annotations = tree.getAt(x, y, getAll).map((id) => store.getAnnotation(id));
965
- const filtered = filter ? annotations.filter(filter) : annotations;
966
- if (filtered.length === 0)
967
- return void 0;
968
- return all ? filtered : filtered[0];
969
- }
970
- const getAnnotationBounds = (id) => {
971
- const rects = tree.getAnnotationRects(id);
972
- return rects.length > 0 ? tree.getAnnotationBounds(id) : void 0;
973
- };
974
- const getIntersecting = (minX, minY, maxX, maxY) => tree.getIntersecting(minX, minY, maxX, maxY);
975
- const getAnnotationRects = (id) => tree.getAnnotationRects(id);
976
- const recalculatePositions = () => tree.recalculate();
977
- const onRecalculatePositions = (callback) => tree.on("recalculate", callback);
978
- store.observe(({ changes }) => {
979
- const deleted = (changes.deleted || []).filter((a) => isRevived(a.target.selector));
980
- const created = (changes.created || []).filter((a) => isRevived(a.target.selector));
981
- const updated = (changes.updated || []).filter((u) => isRevived(u.newValue.target.selector));
982
- if ((deleted == null ? void 0 : deleted.length) > 0)
983
- deleted.forEach((a) => tree.remove(a.target));
984
- if (created.length > 0)
985
- tree.set(created.map((a) => a.target), false);
986
- if ((updated == null ? void 0 : updated.length) > 0)
987
- updated.forEach(({ newValue }) => tree.update(newValue.target));
988
- });
989
- return {
990
- store: {
991
- ...store,
992
- addAnnotation,
993
- bulkAddAnnotation,
994
- bulkUpdateTargets,
995
- bulkUpsertAnnotations,
996
- getAnnotationBounds,
997
- getAnnotationRects,
998
- getIntersecting,
999
- getAt,
1000
- recalculatePositions,
1001
- onRecalculatePositions,
1002
- updateTarget
1003
- },
1004
- selection,
1005
- hover,
1006
- viewport
1007
- };
1008
- };
1009
- const createCanvas = () => {
1010
- const canvas = document.createElement("canvas");
1011
- canvas.width = 2 * window.innerWidth;
1012
- canvas.height = 2 * window.innerHeight;
1013
- canvas.className = "r6o-presence-layer";
1014
- const context = canvas.getContext("2d");
1015
- context.scale(2, 2);
1016
- context.translate(0.5, 0.5);
1017
- return canvas;
1018
- };
1019
- const createPresencePainter = (provider, opts = {}) => {
1020
- const canvas = createCanvas();
1021
- const ctx = canvas.getContext("2d");
1022
- document.body.appendChild(canvas);
1023
- const trackedAnnotations = /* @__PURE__ */ new Map();
1024
- const getAnnotationsForUser = (p) => Array.from(trackedAnnotations.entries()).filter(([id, user]) => user.presenceKey === p.presenceKey).map(([id, _]) => id);
1025
- provider.on("selectionChange", (p, selection) => {
1026
- const currentIds = getAnnotationsForUser(p);
1027
- currentIds.forEach((id) => trackedAnnotations.delete(id));
1028
- if (selection)
1029
- selection.forEach((id) => trackedAnnotations.set(id, p));
1030
- });
1031
- const clear = () => {
1032
- const { width, height } = canvas;
1033
- ctx.clearRect(-0.5, -0.5, width + 1, height + 1);
1034
- };
1035
- const paint2 = (highlight, viewportBounds, isSelected) => {
1036
- if (opts.font)
1037
- ctx.font = opts.font;
1038
- const user = trackedAnnotations.get(highlight.annotation.id);
1039
- if (user) {
1040
- const { height } = highlight.rects[0];
1041
- const x = highlight.rects[0].x + viewportBounds.left;
1042
- const y = highlight.rects[0].y + viewportBounds.top;
1043
- ctx.fillStyle = user.appearance.color;
1044
- ctx.fillRect(x - 2, y - 2.5, 2, height + 5);
1045
- const metrics = ctx.measureText(user.appearance.label);
1046
- const labelWidth = metrics.width + 6;
1047
- const labelHeight = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent + 8;
1048
- const paddingBottom = metrics.fontBoundingBoxAscent ? 8 : 6.5;
1049
- ctx.fillRect(x - 2, y - 2.5 - labelHeight, labelWidth, labelHeight);
1050
- ctx.fillStyle = "#fff";
1051
- ctx.fillText(user.appearance.label, x + 1, y - paddingBottom);
1052
- return {
1053
- fill: user.appearance.color,
1054
- fillOpacity: isSelected ? 0.45 : 0.18
1055
- };
1056
- }
1057
- };
1058
- const reset = () => {
1059
- canvas.width = 2 * window.innerWidth;
1060
- canvas.height = 2 * window.innerHeight;
1061
- const context = canvas.getContext("2d");
1062
- context.scale(2, 2);
1063
- context.translate(0.5, 0.5);
1064
- };
1065
- const destroy = () => {
1066
- canvas.remove();
1067
- };
1068
- return {
1069
- clear,
1070
- destroy,
1071
- paint: paint2,
1072
- reset
1073
- };
1074
- };
1075
- const CLICK_TIMEOUT = 300;
1076
- const ARROW_KEYS = ["up", "down", "left", "right"];
1077
- const SELECT_ALL = isMac ? "⌘+a" : "ctrl+a";
1078
- const SELECTION_KEYS = [
1079
- ...ARROW_KEYS.map((key) => `shift+${key}`),
1080
- SELECT_ALL
1081
- ];
1082
- const createSelectionHandler = (container, state, options) => {
1083
- const { store, selection } = state;
1084
- let currentUser;
1085
- const { annotatingEnabled, offsetReferenceSelector, selectionMode } = options;
1086
- const setUser = (user) => currentUser = user;
1087
- let currentFilter;
1088
- const setFilter = (filter) => currentFilter = filter;
1089
- let currentTarget;
1090
- let isLeftClick;
1091
- let lastDownEvent;
1092
- let currentAnnotatingEnabled = annotatingEnabled;
1093
- const setAnnotatingEnabled = (enabled) => {
1094
- currentAnnotatingEnabled = enabled;
1095
- onSelectionChange.clear();
1096
- if (!enabled) {
1097
- currentTarget = void 0;
1098
- isLeftClick = void 0;
1099
- lastDownEvent = void 0;
1100
- }
1101
- };
1102
- const onSelectStart = (evt) => {
1103
- if (!currentAnnotatingEnabled) return;
1104
- if (isLeftClick === false) return;
1105
- currentTarget = isNotAnnotatable(evt.target) ? void 0 : {
1106
- annotation: uuid.v4(),
1107
- selector: [],
1108
- creator: currentUser,
1109
- created: /* @__PURE__ */ new Date()
1110
- };
1111
- };
1112
- const onSelectionChange = debounce((evt) => {
1113
- if (!currentAnnotatingEnabled) return;
1114
- const sel = document.getSelection();
1115
- if (!(sel == null ? void 0 : sel.anchorNode)) {
1116
- return;
1117
- }
1118
- if (isNotAnnotatable(sel.anchorNode)) {
1119
- currentTarget = void 0;
1120
- return;
1121
- }
1122
- const timeDifference = evt.timeStamp - ((lastDownEvent == null ? void 0 : lastDownEvent.timeStamp) || evt.timeStamp);
1123
- if ((lastDownEvent == null ? void 0 : lastDownEvent.type) === "pointerdown") {
1124
- if (timeDifference < 1e3 && !currentTarget) {
1125
- onSelectStart(lastDownEvent || evt);
1126
- } else if (sel.isCollapsed && timeDifference < CLICK_TIMEOUT) {
1127
- onSelectStart(lastDownEvent || evt);
1128
- }
1129
- }
1130
- if (!currentTarget) return;
1131
- if (sel.isCollapsed) {
1132
- if (store.getAnnotation(currentTarget.annotation)) {
1133
- selection.clear();
1134
- store.deleteAnnotation(currentTarget.annotation);
1135
- }
1136
- return;
1137
- }
1138
- const selectionRange = sel.getRangeAt(0);
1139
- const containedRange = trimRangeToContainer(selectionRange, container);
1140
- if (isWhitespaceOrEmpty(containedRange)) return;
1141
- const annotatableRanges = splitAnnotatableRanges(containedRange.cloneRange());
1142
- const hasChanged = annotatableRanges.length !== currentTarget.selector.length || annotatableRanges.some((r, i) => {
1143
- var _a;
1144
- return r.toString() !== ((_a = currentTarget.selector[i]) == null ? void 0 : _a.quote);
1145
- });
1146
- if (!hasChanged) return;
1147
- currentTarget = {
1148
- ...currentTarget,
1149
- selector: annotatableRanges.map((r) => rangeToSelector(r, container, offsetReferenceSelector)),
1150
- updated: /* @__PURE__ */ new Date()
1151
- };
1152
- if (store.getAnnotation(currentTarget.annotation)) {
1153
- store.updateTarget(currentTarget, core.Origin.LOCAL);
1154
- } else {
1155
- selection.clear();
1156
- }
1157
- }, 10);
1158
- const onPointerDown = (evt) => {
1159
- if (isNotAnnotatable(evt.target)) return;
1160
- lastDownEvent = clonePointerEvent(evt);
1161
- isLeftClick = lastDownEvent.button === 0;
1162
- };
1163
- const onPointerUp = async (evt) => {
1164
- if (isNotAnnotatable(evt.target) || !isLeftClick) return;
1165
- const clickSelect = () => {
1166
- const { x, y } = container.getBoundingClientRect();
1167
- const hovered = evt.target instanceof Node && container.contains(evt.target) && store.getAt(evt.clientX - x, evt.clientY - y, selectionMode === "all", currentFilter);
1168
- if (hovered) {
1169
- const { selected } = selection;
1170
- const currentIds = new Set(selected.map((s) => s.id));
1171
- const nextIds = Array.isArray(hovered) ? hovered.map((a) => a.id) : [hovered.id];
1172
- const hasChanged = currentIds.size !== nextIds.length || !nextIds.every((id) => currentIds.has(id));
1173
- if (hasChanged)
1174
- selection.userSelect(nextIds, evt);
1175
- } else {
1176
- selection.clear();
1177
- }
1178
- };
1179
- const timeDifference = evt.timeStamp - lastDownEvent.timeStamp;
1180
- if (timeDifference < CLICK_TIMEOUT) {
1181
- await pollSelectionCollapsed();
1182
- const sel = document.getSelection();
1183
- if (sel == null ? void 0 : sel.isCollapsed) {
1184
- currentTarget = void 0;
1185
- clickSelect();
1186
- return;
1187
- }
1188
- }
1189
- if (currentTarget && currentTarget.selector.length > 0) {
1190
- upsertCurrentTarget();
1191
- selection.userSelect(currentTarget.annotation, clonePointerEvent(evt));
1192
- }
1193
- };
1194
- const pollSelectionCollapsed = async () => {
1195
- const sel = document.getSelection();
1196
- let stopPolling = false;
1197
- let isCollapsed = sel == null ? void 0 : sel.isCollapsed;
1198
- const shouldStopPolling = () => isCollapsed || stopPolling;
1199
- const pollingDelayMs = 1;
1200
- const stopPollingInMs = 50;
1201
- setTimeout(() => stopPolling = true, stopPollingInMs);
1202
- return poll.poll(() => isCollapsed = sel == null ? void 0 : sel.isCollapsed, pollingDelayMs, shouldStopPolling);
1203
- };
1204
- const onContextMenu = (evt) => {
1205
- const sel = document.getSelection();
1206
- if (sel == null ? void 0 : sel.isCollapsed) return;
1207
- if (!currentTarget || currentTarget.selector.length === 0) {
1208
- onSelectionChange(evt);
1209
- }
1210
- upsertCurrentTarget();
1211
- selection.userSelect(currentTarget.annotation, clonePointerEvent(evt));
1212
- };
1213
- const onKeyup = (evt) => {
1214
- if (!currentAnnotatingEnabled) return;
1215
- if (evt.key === "Shift" && currentTarget) {
1216
- const sel = document.getSelection();
1217
- if (!sel.isCollapsed) {
1218
- upsertCurrentTarget();
1219
- selection.userSelect(currentTarget.annotation, cloneKeyboardEvent(evt));
1220
- }
1221
- }
1222
- };
1223
- const onSelectAll = (evt) => {
1224
- const onSelected = () => setTimeout(() => {
1225
- if ((currentTarget == null ? void 0 : currentTarget.selector.length) > 0) {
1226
- selection.clear();
1227
- store.addAnnotation({
1228
- id: currentTarget.annotation,
1229
- bodies: [],
1230
- target: currentTarget
1231
- });
1232
- selection.userSelect(currentTarget.annotation, cloneKeyboardEvent(evt));
1233
- }
1234
- document.removeEventListener("selectionchange", onSelected);
1235
- }, 100);
1236
- document.addEventListener("selectionchange", onSelected);
1237
- onSelectStart(evt);
1238
- };
1239
- hotkeys(SELECTION_KEYS.join(","), { element: container, keydown: true, keyup: false }, (evt) => {
1240
- if (!evt.repeat)
1241
- lastDownEvent = cloneKeyboardEvent(evt);
1242
- });
1243
- hotkeys(SELECT_ALL, { keydown: true, keyup: false }, (evt) => {
1244
- lastDownEvent = cloneKeyboardEvent(evt);
1245
- onSelectAll(evt);
1246
- });
1247
- const handleArrowKeyPress = (evt) => {
1248
- if (evt.repeat || evt.target !== container && evt.target !== document.body) {
1249
- return;
1250
- }
1251
- currentTarget = void 0;
1252
- selection.clear();
1253
- };
1254
- hotkeys(ARROW_KEYS.join(","), { keydown: true, keyup: false }, handleArrowKeyPress);
1255
- const upsertCurrentTarget = () => {
1256
- const existingAnnotation = store.getAnnotation(currentTarget.annotation);
1257
- if (!existingAnnotation) {
1258
- store.addAnnotation({
1259
- id: currentTarget.annotation,
1260
- bodies: [],
1261
- target: currentTarget
1262
- });
1263
- return;
1264
- }
1265
- const { target: { updated: existingTargetUpdated } } = existingAnnotation;
1266
- const { updated: currentTargetUpdated } = currentTarget;
1267
- if (!existingTargetUpdated || !currentTargetUpdated || existingTargetUpdated < currentTargetUpdated) {
1268
- store.updateTarget(currentTarget);
1269
- }
1270
- };
1271
- document.addEventListener("pointerdown", onPointerDown);
1272
- document.addEventListener("pointerup", onPointerUp);
1273
- document.addEventListener("contextmenu", onContextMenu);
1274
- container.addEventListener("keyup", onKeyup);
1275
- container.addEventListener("selectstart", onSelectStart);
1276
- document.addEventListener("selectionchange", onSelectionChange);
1277
- const destroy = () => {
1278
- currentTarget = void 0;
1279
- isLeftClick = void 0;
1280
- lastDownEvent = void 0;
1281
- onSelectionChange.clear();
1282
- document.removeEventListener("pointerdown", onPointerDown);
1283
- document.removeEventListener("pointerup", onPointerUp);
1284
- document.removeEventListener("contextmenu", onContextMenu);
1285
- container.removeEventListener("keyup", onKeyup);
1286
- container.removeEventListener("selectstart", onSelectStart);
1287
- document.removeEventListener("selectionchange", onSelectionChange);
1288
- hotkeys.unbind();
1289
- };
1290
- return {
1291
- destroy,
1292
- setFilter,
1293
- setUser,
1294
- setAnnotatingEnabled
1295
- };
1296
- };
1297
- const fillDefaults = (opts, defaults) => ({
1298
- ...opts,
1299
- annotatingEnabled: opts.annotatingEnabled ?? defaults.annotatingEnabled,
1300
- user: opts.user || defaults.user
1301
- });
1302
- const USE_DEFAULT_RENDERER = "SPANS";
1303
- const createTextAnnotator = (container, options = {}) => {
1304
- cancelSingleClickEvents(container);
1305
- programmaticallyFocusable(container);
1306
- const opts = fillDefaults(options, {
1307
- annotatingEnabled: true,
1308
- user: core.createAnonymousGuest()
1309
- });
1310
- const state = createTextAnnotatorState(container, opts);
1311
- const { selection, viewport } = state;
1312
- const store = state.store;
1313
- const undoStack = core.createUndoStack(store);
1314
- const lifecycle = core.createLifecycleObserver(state, undoStack, opts.adapter);
1315
- let currentUser = opts.user;
1316
- const useRenderer = opts.renderer === "CSS_HIGHLIGHTS" ? Boolean(CSS.highlights) ? "CSS_HIGHLIGHTS" : USE_DEFAULT_RENDERER : opts.renderer || USE_DEFAULT_RENDERER;
1317
- const highlightRenderer = useRenderer === "SPANS" ? createSpansRenderer(container, state, viewport) : useRenderer === "CSS_HIGHLIGHTS" ? createHighlightsRenderer(container, state, viewport) : useRenderer === "CANVAS" ? createCanvasRenderer(container, state, viewport) : void 0;
1318
- if (!highlightRenderer)
1319
- throw `Unknown renderer implementation: ${useRenderer}`;
1320
- console.debug(`Using ${useRenderer} renderer`);
1321
- if (opts.style)
1322
- highlightRenderer.setStyle(opts.style);
1323
- const selectionHandler = createSelectionHandler(container, state, opts);
1324
- selectionHandler.setUser(currentUser);
1325
- selectionHandler.setAnnotatingEnabled(opts.annotatingEnabled);
1326
- const base = core.createBaseAnnotator(state, undoStack, opts.adapter);
1327
- const getUser = () => currentUser;
1328
- const setAnnotatingEnabled = (enabled) => {
1329
- selectionHandler.setAnnotatingEnabled(
1330
- enabled === void 0 ? true : enabled
1331
- );
1332
- };
1333
- const setFilter = (filter) => {
1334
- highlightRenderer.setFilter(filter);
1335
- selectionHandler.setFilter(filter);
1336
- };
1337
- const setUser = (user) => {
1338
- currentUser = user;
1339
- selectionHandler.setUser(user);
1340
- };
1341
- const setPresenceProvider = (provider) => {
1342
- if (provider) {
1343
- highlightRenderer.setPainter(createPresencePainter(provider, opts.presence));
1344
- provider.on("selectionChange", () => highlightRenderer.redraw());
1345
- }
1346
- };
1347
- const setSelected = (arg) => {
1348
- if (arg) {
1349
- selection.setSelected(arg);
1350
- } else {
1351
- selection.clear();
1352
- }
1353
- };
1354
- const destroy = () => {
1355
- highlightRenderer.destroy();
1356
- selectionHandler.destroy();
1357
- undoStack.destroy();
1358
- };
1359
- return {
1360
- ...base,
1361
- destroy,
1362
- element: container,
1363
- getUser,
1364
- setAnnotatingEnabled,
1365
- setFilter,
1366
- setStyle: highlightRenderer.setStyle.bind(highlightRenderer),
1367
- redraw: highlightRenderer.redraw.bind(highlightRenderer),
1368
- setUser,
1369
- setSelected,
1370
- setPresenceProvider,
1371
- setVisible: highlightRenderer.setVisible.bind(highlightRenderer),
1372
- on: lifecycle.on,
1373
- off: lifecycle.off,
1374
- scrollIntoView: scrollIntoView(container, store),
1375
- state
1376
- };
1377
- };
1378
- Object.defineProperty(exports2, "Origin", {
1379
- enumerable: true,
1380
- get: () => core.Origin
1381
- });
1382
- Object.defineProperty(exports2, "UserSelectAction", {
1383
- enumerable: true,
1384
- get: () => core.UserSelectAction
1385
- });
1386
- Object.defineProperty(exports2, "createBody", {
1387
- enumerable: true,
1388
- get: () => core.createBody
1389
- });
1390
- exports2.DEFAULT_SELECTED_STYLE = DEFAULT_SELECTED_STYLE;
1391
- exports2.DEFAULT_STYLE = DEFAULT_STYLE;
1392
- exports2.NOT_ANNOTATABLE_CLASS = NOT_ANNOTATABLE_CLASS;
1393
- exports2.NOT_ANNOTATABLE_SELECTOR = NOT_ANNOTATABLE_SELECTOR;
1394
- exports2.W3CTextFormat = W3CTextFormat;
1395
- exports2.cancelSingleClickEvents = cancelSingleClickEvents;
1396
- exports2.cloneKeyboardEvent = cloneKeyboardEvent;
1397
- exports2.clonePointerEvent = clonePointerEvent;
1398
- exports2.createCanvasRenderer = createCanvasRenderer;
1399
- exports2.createHighlightsRenderer = createHighlightsRenderer;
1400
- exports2.createPresencePainter = createPresencePainter;
1401
- exports2.createRenderer = createRenderer$1;
1402
- exports2.createSelectionHandler = createSelectionHandler;
1403
- exports2.createSpansRenderer = createSpansRenderer;
1404
- exports2.createTextAnnotator = createTextAnnotator;
1405
- exports2.createTextAnnotatorState = createTextAnnotatorState;
1406
- exports2.fillDefaults = fillDefaults;
1407
- exports2.getQuoteContext = getQuoteContext;
1408
- exports2.getRangeAnnotatableContents = getRangeAnnotatableContents;
1409
- exports2.isMac = isMac;
1410
- exports2.isNotAnnotatable = isNotAnnotatable;
1411
- exports2.isRangeAnnotatable = isRangeAnnotatable;
1412
- exports2.isRevived = isRevived;
1413
- exports2.isWhitespaceOrEmpty = isWhitespaceOrEmpty;
1414
- exports2.mergeClientRects = mergeClientRects;
1415
- exports2.paint = paint;
1416
- exports2.parseW3CTextAnnotation = parseW3CTextAnnotation;
1417
- exports2.programmaticallyFocusable = programmaticallyFocusable;
1418
- exports2.rangeContains = rangeContains;
1419
- exports2.rangeToSelector = rangeToSelector;
1420
- exports2.reviveAnnotation = reviveAnnotation;
1421
- exports2.reviveSelector = reviveSelector;
1422
- exports2.reviveTarget = reviveTarget;
1423
- exports2.scrollIntoView = scrollIntoView;
1424
- exports2.serializeW3CTextAnnotation = serializeW3CTextAnnotation;
1425
- exports2.splitAnnotatableRanges = splitAnnotatableRanges;
1426
- exports2.toDomRectList = toDomRectList;
1427
- exports2.toParentBounds = toParentBounds;
1428
- exports2.toViewportBounds = toViewportBounds;
1429
- exports2.trimRangeToContainer = trimRangeToContainer;
1430
- exports2.whitespaceOrEmptyRegex = whitespaceOrEmptyRegex;
1431
- Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
1432
- });
1
+ (function(O,Q){typeof exports=="object"&&typeof module<"u"?Q(exports):typeof define=="function"&&define.amd?define(["exports"],Q):(O=typeof globalThis<"u"?globalThis:O||self,Q(O.RecogitoJS={}))})(this,function(O){"use strict";const Q="not-annotatable",J=`.${Q}`,et=t=>{var n;return!!(t instanceof HTMLElement?t.closest(J):(n=t.parentElement)==null?void 0:n.closest(J))},qt=t=>{const e=t.commonAncestorContainer;return!et(e)},Gt=t=>t.addEventListener("click",e=>{!e.target.closest(J)&&!e.target.closest("a")&&e.preventDefault()}),Qt=/mac/i.test(navigator.userAgentData?navigator.userAgentData.platform:navigator.platform),Jt=t=>{!t.hasAttribute("tabindex")&&t.tabIndex<0&&t.setAttribute("tabindex","-1"),t.classList.add("no-focus-outline")},on=function*(t){const e=document.createNodeIterator(t.commonAncestorContainer,NodeFilter.SHOW_ELEMENT,o=>o instanceof HTMLElement&&o.classList.contains(Q)&&!o.parentElement.closest(J)&&t.intersectsNode(o)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP);let n;for(;n=e.nextNode();)n instanceof HTMLElement&&(yield n)},Zt=t=>{if(!qt(t))return[];const e=[];let n=null;for(const o of on(t)){let i;n?(i=document.createRange(),i.setStartAfter(n),i.setEndBefore(o)):(i=t.cloneRange(),i.setEndBefore(o)),i.collapsed||e.push(i),n=o}if(n){const o=t.cloneRange();o.setStartAfter(n),o.collapsed||e.push(o)}return e.length>0?e:[t]},bt=t=>{const e=t.cloneContents();return e.querySelectorAll(J).forEach(n=>n.remove()),e},te=(t,e,n=10,o)=>{const i=o?t.startContainer.parentElement.closest(o):e,s=document.createRange();s.setStart(i,0),s.setEnd(t.startContainer,t.startOffset);const a=bt(s).textContent,r=document.createRange();r.setStart(t.endContainer,t.endOffset),i===document.body?r.setEnd(i,i.childNodes.length):r.setEndAfter(i);const l=bt(r).textContent;return{prefix:a.substring(a.length-n),suffix:l.substring(0,n)}},j=t=>t.every(e=>e.range instanceof Range&&!e.range.collapsed),ee=/^\s*$/,ne=t=>ee.test(t.toString()),sn=(t,e)=>{const n=s=>Math.round(s*10)/10,o={top:n(t.top),bottom:n(t.bottom),left:n(t.left),right:n(t.right)},i={top:n(e.top),bottom:n(e.bottom),left:n(e.left),right:n(e.right)};if(Math.abs(o.top-i.top)<.5&&Math.abs(o.bottom-i.bottom)<.5){if(Math.abs(o.left-i.right)<.5||Math.abs(o.right-i.left)<.5)return"inline-adjacent";if(o.left>=i.left&&o.right<=i.right)return"inline-is-contained";if(o.left<=i.left&&o.right>=i.right)return"inline-contains"}else if(o.top<=i.top&&o.bottom>=i.bottom){if(o.left<=i.left&&o.right>=i.right)return"block-contains"}else if(o.top>=i.top&&o.bottom<=i.bottom&&o.left>=i.left&&o.right<=i.right)return"block-is-contained"},rn=(t,e)=>{const n=Math.min(t.left,e.left),o=Math.max(t.right,e.right),i=Math.min(t.top,e.top),s=Math.max(t.bottom,e.bottom);return new DOMRect(n,i,o-n,s-i)},oe=t=>t.reduce((e,n)=>{if(n.width===0||n.height===0)return e;let o=[...e],i=!1;for(const s of e){const a=sn(n,s);if(a==="inline-adjacent"){o=o.map(r=>r===s?rn(n,s):r),i=!0;break}else if(a==="inline-contains"){o=o.map(r=>r===s?n:r),i=!0;break}else if(a==="inline-is-contained"){i=!0;break}else if(a==="block-contains"||a==="block-is-contained"){n.width<s.width&&(o=o.map(r=>r===s?n:r)),i=!0;break}}return i?o:[...o,n]},[]),an=t=>({length:t.length,item:e=>t[e],[Symbol.iterator]:function*(){for(let e=0;e<this.length;e++)yield this.item(e)}}),ie=(t,e,n)=>{const o=document.createRange(),i=n?t.startContainer.parentElement.closest(n):e;o.setStart(i,0),o.setEnd(t.startContainer,t.startOffset);const s=bt(o).textContent,a=t.toString(),r=s.length||0,l=r+a.length;return n?{quote:a,start:r,end:l,range:t,offsetReference:i}:{quote:a,start:r,end:l,range:t}},Rt=(t,e)=>{var p,u;const{start:n,end:o}=t,i=t.offsetReference||e,s=document.createNodeIterator(e,NodeFilter.SHOW_TEXT,f=>{var A;return(A=f.parentElement)!=null&&A.closest(J)?NodeFilter.FILTER_SKIP:NodeFilter.FILTER_ACCEPT});let a=0;const r=document.createRange();let l=s.nextNode();l===null&&console.error("Could not revive annotation target. Content missing.");let d=!i;for(;l!==null;){if(d||(d=i==null?void 0:i.contains(l)),d){const f=((p=l.textContent)==null?void 0:p.length)||0;if(a+f>n){r.setStart(l,n-a);break}a+=f}l=s.nextNode()}for(;l!==null;){const f=((u=l.textContent)==null?void 0:u.length)||0;if(a+f>=o){r.setEnd(l,o-a);break}a+=f,l=s.nextNode()}return{...t,range:r}},st=(t,e)=>j(t.selector)?t:{...t,selector:t.selector.map(n=>n.range instanceof Range&&!n.range.collapsed?n:Rt(n,e))},wt=(t,e)=>j(t.target.selector)?t:{...t,target:st(t.target,e)},se=(t,e)=>{if(t.isEqualNode(e))return!0;for(let n of t.childNodes)if(se(n,e))return!0;return!1},re=(t,e)=>{const n=t.cloneContents();return se(n,e)},ae=(t,e)=>{const n=t.cloneRange(),o=e.contains(n.startContainer),i=e.contains(n.endContainer);return!o&&!i&&!re(n,e)?(n.collapse(),n):(o||n.setStart(e,0),i||n.setEnd(e,e.childNodes.length),n)},At=t=>({...t,type:t.type,x:t.x,y:t.y,clientX:t.clientX,clientY:t.clientY,offsetX:t.offsetX,offsetY:t.offsetY,screenX:t.screenX,screenY:t.screenY,isPrimary:t.isPrimary,altKey:t.altKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,shiftKey:t.shiftKey,button:t.button,buttons:t.buttons,currentTarget:t.currentTarget,target:t.target,defaultPrevented:t.defaultPrevented,detail:t.detail,eventPhase:t.eventPhase,pointerId:t.pointerId,pointerType:t.pointerType,timeStamp:t.timeStamp}),rt=t=>({...t,type:t.type,key:t.key,code:t.code,location:t.location,repeat:t.repeat,altKey:t.altKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,shiftKey:t.shiftKey,currentTarget:t.currentTarget,target:t.target,defaultPrevented:t.defaultPrevented,detail:t.detail,timeStamp:t.timeStamp}),ce=(t,e)=>{const{left:n,top:o,right:i,bottom:s}=t;return new DOMRect(n-e.left,o-e.top,i-n,s-o)},cn=(t,e)=>{const{left:n,top:o,right:i,bottom:s}=t;return new DOMRect(n+e.left,o+e.top,i-n,s-o)},le=t=>{if(t===null)return document.scrollingElement;const{overflowY:e}=window.getComputedStyle(t);return e!=="visible"&&e!=="hidden"&&t.scrollHeight>t.clientHeight?t:le(t.parentElement)},de=(t,e)=>n=>{const o=typeof n=="string"?n:n.id,i=a=>{const r=s.getBoundingClientRect(),l=s.clientHeight,d=s.clientWidth,p=a.selector[0].range.getBoundingClientRect(),{width:u,height:f}=e.getAnnotationBounds(o),A=p.top-r.top,g=p.left-r.left,b=s.parentElement?s.scrollTop:0,v=s.parentElement?s.scrollLeft:0,m=A+b-(l-f)/2,c=g+v-(d-u)/2;s.scroll({top:m,left:c,behavior:"smooth"})},s=le(t);if(s){const a=e.getAnnotation(o),{range:r}=a.target.selector[0];if(r&&!r.collapsed)return i(a.target),!0;{const l=st(a.target,t),{range:d}=l.selector[0];if(d&&!d.collapsed)return i(l),!0}}return!1},z={fill:"rgb(0, 128, 255)",fillOpacity:.18},at={fill:"rgb(0, 128, 255)",fillOpacity:.45},ue=(t,e,n,o,i)=>{var a,r;const s=n?typeof n=="function"?n(t.annotation,t.state,i)||((a=t.state)!=null&&a.selected?at:z):n:(r=t.state)!=null&&r.selected?at:z;return o&&o.paint(t,e)||s};function ln(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var vt={exports:{}},fe;function dn(){if(fe)return vt.exports;fe=1;function t(e,n=100,o={}){if(typeof e!="function")throw new TypeError(`Expected the first parameter to be a function, got \`${typeof e}\`.`);if(n<0)throw new RangeError("`wait` must not be negative.");const{immediate:i}=typeof o=="boolean"?{immediate:o}:o;let s,a,r,l,d;function p(){const A=s,g=a;return s=void 0,a=void 0,d=e.apply(A,g),d}function u(){const A=Date.now()-l;A<n&&A>=0?r=setTimeout(u,n-A):(r=void 0,i||(d=p()))}const f=function(...A){if(s&&this!==s&&Object.getPrototypeOf(this)===Object.getPrototypeOf(s))throw new Error("Debounced method called with different contexts of the same prototype.");s=this,a=A,l=Date.now();const g=i&&!r;return r||(r=setTimeout(u,n)),g&&(d=p()),d};return Object.defineProperty(f,"isPending",{get(){return r!==void 0}}),f.clear=()=>{r&&(clearTimeout(r),r=void 0)},f.flush=()=>{r&&f.trigger()},f.trigger=()=>{d=p(),f.clear()},f}return vt.exports.debounce=t,vt.exports=t,vt.exports}var un=dn();const Bt=ln(un),fn=t=>{const{top:e,left:n}=t.getBoundingClientRect(),{innerWidth:o,innerHeight:i}=window,s=-n,a=-e,r=o-n,l=i-e;return{top:e,left:n,minX:s,minY:a,maxX:r,maxY:l}},hn=t=>{let e=new Set;return o=>{const i=o.map(s=>s.id);(e.size!==i.length||i.some(s=>!e.has(s)))&&t.set(i),e=new Set(i)}},Mt=(t,e,n,o)=>{const{store:i,selection:s,hover:a}=e;let r,l,d;const p=hn(n),u=T=>{const{x:M,y:w}=t.getBoundingClientRect(),E=i.getAt(T.clientX-M,T.clientY-w,!1,l);E?a.current!==E.id&&(t.classList.add("hovered"),a.set(E.id)):a.current&&(t.classList.remove("hovered"),a.set(null))};t.addEventListener("pointermove",u);const f=(T=!1)=>{d&&d.clear();const M=fn(t),{minX:w,minY:E,maxX:h,maxY:S}=M,k=l?i.getIntersecting(w,E,h,S).filter(({annotation:D})=>l(D)):i.getIntersecting(w,E,h,S),R=s.selected.map(({id:D})=>D),U=k.map(({annotation:D,rects:Ot})=>{const G=R.includes(D.id),tt=D.id===a.current;return{annotation:D,rects:Ot,state:{selected:G,hover:tt}}});o.redraw(U,M,r,d,T),setTimeout(()=>p(k.map(({annotation:D})=>D)),1)},A=T=>{d=T,f()},g=T=>{r=T,f()},b=T=>{l=T,f(!1)},v=()=>f();i.observe(v);const m=s.subscribe(()=>f()),c=()=>f(!0);document.addEventListener("scroll",c,{capture:!0,passive:!0});const y=Bt(()=>{i.recalculatePositions(),d==null||d.reset(),f()},10);window.addEventListener("resize",y);const C=new ResizeObserver(y);C.observe(t);const x={attributes:!0,childList:!0,subtree:!0},L=new MutationObserver(T=>{T.every(w=>w.target===t||t.contains(w.target))||f(!0)});return L.observe(document.body,x),{destroy:()=>{t.removeEventListener("pointermove",u),o.destroy(),i.unobserve(v),m(),document.removeEventListener("scroll",c),y.clear(),window.removeEventListener("resize",y),C.disconnect(),L.disconnect()},redraw:f,setStyle:g,setFilter:b,setPainter:A,setVisible:o.setVisible}},gn=()=>{const t=document.createElement("canvas");return t.width=window.innerWidth,t.height=window.innerHeight,t.className="r6o-canvas-highlight-layer bg",t},pn=(t,e)=>{t.width=window.innerWidth,t.height=window.innerHeight},mn=t=>{t.classList.add("r6o-annotatable");const e=gn(),n=e.getContext("2d");document.body.appendChild(e);const o=(r,l,d,p)=>requestAnimationFrame(()=>{const{width:u,height:f}=e;n.clearRect(-.5,-.5,u+1,f+1),p&&p.clear();const{top:A,left:g}=l;[...r].sort((v,m)=>{const{annotation:{target:{created:c}}}=v,{annotation:{target:{created:y}}}=m;return c.getTime()-y.getTime()}).forEach(v=>{var C;const m=d?typeof d=="function"?d(v.annotation,v.state):d:(C=v.state)!=null&&C.selected?at:z,c=p&&p.paint(v,l)||m,y=v.rects.map(({x,y:L,width:B,height:T})=>({x:x+g,y:L+A,width:B,height:T}));if(n.fillStyle=c.fill,n.globalAlpha=c.fillOpacity||1,y.forEach(({x,y:L,width:B,height:T})=>n.fillRect(x,L,B,T)),c.underlineColor){n.globalAlpha=1,n.strokeStyle=c.underlineColor,n.lineWidth=c.underlineThickness??1;const x=c.underlineOffset??0;y.forEach(({x:L,y:B,width:T,height:M})=>{n.beginPath(),n.moveTo(L,B+M+x),n.lineTo(L+T,B+M+x),n.stroke()})}})}),i=Bt(()=>pn(e),10);return window.addEventListener("resize",i),{destroy:()=>{e.remove(),i.clear(),window.removeEventListener("resize",i)},setVisible:r=>{console.log("setVisible not implemented on Canvas renderer")},redraw:o}},he=(t,e,n)=>Mt(t,e,n,mn(t));var yn={grad:.9,turn:360,rad:360/(2*Math.PI)},W=function(t){return typeof t=="string"?t.length>0:typeof t=="number"},V=function(t,e,n){return e===void 0&&(e=0),n===void 0&&(n=Math.pow(10,e)),Math.round(n*t)/n+0},X=function(t,e,n){return e===void 0&&(e=0),n===void 0&&(n=1),t>n?n:t>e?t:e},ge=function(t){return(t=isFinite(t)?t%360:0)>0?t:t+360},pe=function(t){return{r:X(t.r,0,255),g:X(t.g,0,255),b:X(t.b,0,255),a:X(t.a)}},kt=function(t){return{r:V(t.r),g:V(t.g),b:V(t.b),a:V(t.a,3)}},bn=/^#([0-9a-f]{3,8})$/i,Et=function(t){var e=t.toString(16);return e.length<2?"0"+e:e},me=function(t){var e=t.r,n=t.g,o=t.b,i=t.a,s=Math.max(e,n,o),a=s-Math.min(e,n,o),r=a?s===e?(n-o)/a:s===n?2+(o-e)/a:4+(e-n)/a:0;return{h:60*(r<0?r+6:r),s:s?a/s*100:0,v:s/255*100,a:i}},ye=function(t){var e=t.h,n=t.s,o=t.v,i=t.a;e=e/360*6,n/=100,o/=100;var s=Math.floor(e),a=o*(1-n),r=o*(1-(e-s)*n),l=o*(1-(1-e+s)*n),d=s%6;return{r:255*[o,r,a,a,l,o][d],g:255*[l,o,o,r,a,a][d],b:255*[a,a,l,o,o,r][d],a:i}},be=function(t){return{h:ge(t.h),s:X(t.s,0,100),l:X(t.l,0,100),a:X(t.a)}},we=function(t){return{h:V(t.h),s:V(t.s),l:V(t.l),a:V(t.a,3)}},Ae=function(t){return ye((n=(e=t).s,{h:e.h,s:(n*=((o=e.l)<50?o:100-o)/100)>0?2*n/(o+n)*100:0,v:o+n,a:e.a}));var e,n,o},ct=function(t){return{h:(e=me(t)).h,s:(i=(200-(n=e.s))*(o=e.v)/100)>0&&i<200?n*o/100/(i<=100?i:200-i)*100:0,l:i/2,a:e.a};var e,n,o,i},wn=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,An=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,vn=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,En=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,ve={string:[[function(t){var e=bn.exec(t);return e?(t=e[1]).length<=4?{r:parseInt(t[0]+t[0],16),g:parseInt(t[1]+t[1],16),b:parseInt(t[2]+t[2],16),a:t.length===4?V(parseInt(t[3]+t[3],16)/255,2):1}:t.length===6||t.length===8?{r:parseInt(t.substr(0,2),16),g:parseInt(t.substr(2,2),16),b:parseInt(t.substr(4,2),16),a:t.length===8?V(parseInt(t.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(t){var e=vn.exec(t)||En.exec(t);return e?e[2]!==e[4]||e[4]!==e[6]?null:pe({r:Number(e[1])/(e[2]?100/255:1),g:Number(e[3])/(e[4]?100/255:1),b:Number(e[5])/(e[6]?100/255:1),a:e[7]===void 0?1:Number(e[7])/(e[8]?100:1)}):null},"rgb"],[function(t){var e=wn.exec(t)||An.exec(t);if(!e)return null;var n,o,i=be({h:(n=e[1],o=e[2],o===void 0&&(o="deg"),Number(n)*(yn[o]||1)),s:Number(e[3]),l:Number(e[4]),a:e[5]===void 0?1:Number(e[5])/(e[6]?100:1)});return Ae(i)},"hsl"]],object:[[function(t){var e=t.r,n=t.g,o=t.b,i=t.a,s=i===void 0?1:i;return W(e)&&W(n)&&W(o)?pe({r:Number(e),g:Number(n),b:Number(o),a:Number(s)}):null},"rgb"],[function(t){var e=t.h,n=t.s,o=t.l,i=t.a,s=i===void 0?1:i;if(!W(e)||!W(n)||!W(o))return null;var a=be({h:Number(e),s:Number(n),l:Number(o),a:Number(s)});return Ae(a)},"hsl"],[function(t){var e=t.h,n=t.s,o=t.v,i=t.a,s=i===void 0?1:i;if(!W(e)||!W(n)||!W(o))return null;var a=function(r){return{h:ge(r.h),s:X(r.s,0,100),v:X(r.v,0,100),a:X(r.a)}}({h:Number(e),s:Number(n),v:Number(o),a:Number(s)});return ye(a)},"hsv"]]},Ee=function(t,e){for(var n=0;n<e.length;n++){var o=e[n][0](t);if(o)return[o,e[n][1]]}return[null,void 0]},Sn=function(t){return typeof t=="string"?Ee(t.trim(),ve.string):typeof t=="object"&&t!==null?Ee(t,ve.object):[null,void 0]},It=function(t,e){var n=ct(t);return{h:n.h,s:X(n.s+100*e,0,100),l:n.l,a:n.a}},Nt=function(t){return(299*t.r+587*t.g+114*t.b)/1e3/255},Se=function(t,e){var n=ct(t);return{h:n.h,s:n.s,l:X(n.l+100*e,0,100),a:n.a}},xe=function(){function t(e){this.parsed=Sn(e)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return t.prototype.isValid=function(){return this.parsed!==null},t.prototype.brightness=function(){return V(Nt(this.rgba),2)},t.prototype.isDark=function(){return Nt(this.rgba)<.5},t.prototype.isLight=function(){return Nt(this.rgba)>=.5},t.prototype.toHex=function(){return e=kt(this.rgba),n=e.r,o=e.g,i=e.b,a=(s=e.a)<1?Et(V(255*s)):"","#"+Et(n)+Et(o)+Et(i)+a;var e,n,o,i,s,a},t.prototype.toRgb=function(){return kt(this.rgba)},t.prototype.toRgbString=function(){return e=kt(this.rgba),n=e.r,o=e.g,i=e.b,(s=e.a)<1?"rgba("+n+", "+o+", "+i+", "+s+")":"rgb("+n+", "+o+", "+i+")";var e,n,o,i,s},t.prototype.toHsl=function(){return we(ct(this.rgba))},t.prototype.toHslString=function(){return e=we(ct(this.rgba)),n=e.h,o=e.s,i=e.l,(s=e.a)<1?"hsla("+n+", "+o+"%, "+i+"%, "+s+")":"hsl("+n+", "+o+"%, "+i+"%)";var e,n,o,i,s},t.prototype.toHsv=function(){return e=me(this.rgba),{h:V(e.h),s:V(e.s),v:V(e.v),a:V(e.a,3)};var e},t.prototype.invert=function(){return H({r:255-(e=this.rgba).r,g:255-e.g,b:255-e.b,a:e.a});var e},t.prototype.saturate=function(e){return e===void 0&&(e=.1),H(It(this.rgba,e))},t.prototype.desaturate=function(e){return e===void 0&&(e=.1),H(It(this.rgba,-e))},t.prototype.grayscale=function(){return H(It(this.rgba,-1))},t.prototype.lighten=function(e){return e===void 0&&(e=.1),H(Se(this.rgba,e))},t.prototype.darken=function(e){return e===void 0&&(e=.1),H(Se(this.rgba,-e))},t.prototype.rotate=function(e){return e===void 0&&(e=15),this.hue(this.hue()+e)},t.prototype.alpha=function(e){return typeof e=="number"?H({r:(n=this.rgba).r,g:n.g,b:n.b,a:e}):V(this.rgba.a,3);var n},t.prototype.hue=function(e){var n=ct(this.rgba);return typeof e=="number"?H({h:e,s:n.s,l:n.l,a:n.a}):V(n.h)},t.prototype.isEqual=function(e){return this.toHex()===H(e).toHex()},t}(),H=function(t){return t instanceof xe?t:new xe(t)};const xn=t=>[`background-color:${H((t==null?void 0:t.fill)||z.fill).alpha((t==null?void 0:t.fillOpacity)===void 0?z.fillOpacity:t.fillOpacity).toHex()}`,t!=null&&t.underlineThickness?"text-decoration:underline":void 0,t!=null&&t.underlineColor?`text-decoration-color:${t.underlineColor}`:void 0,t!=null&&t.underlineOffset?`text-underline-offset:${t.underlineOffset}px`:void 0,t!=null&&t.underlineThickness?`text-decoration-thickness:${t.underlineThickness}px`:void 0].filter(Boolean).join(";"),Ce=()=>{const t=document.createElement("style");document.getElementsByTagName("head")[0].appendChild(t);let e=new Set;return{destroy:()=>{CSS.highlights.clear(),t.remove()},setVisible:s=>{console.log("setVisible not implemented on CSS Custom Highlights renderer")},redraw:(s,a,r,l)=>{l&&l.clear();const d=new Set(s.map(u=>u.annotation.id));Array.from(e).filter(u=>!d.has(u));const p=s.map(u=>{var g;const f=r?typeof r=="function"?r(u.annotation,u.state):r:(g=u.state)!=null&&g.selected?at:z,A=l&&l.paint(u,a)||f;return`::highlight(_${u.annotation.id}) { ${xn(A)} }`});t.innerHTML=p.join(`
2
+ `),CSS.highlights.clear(),s.forEach(({annotation:u})=>{const f=u.target.selector.map(g=>g.range),A=new Highlight(...f);CSS.highlights.set(`_${u.id}`,A)}),e=d}}},Le=(t,e,n)=>Mt(t,e,n,Ce());var Te=Object.prototype.hasOwnProperty;function _t(t,e){var n,o;if(t===e)return!0;if(t&&e&&(n=t.constructor)===e.constructor){if(n===Date)return t.getTime()===e.getTime();if(n===RegExp)return t.toString()===e.toString();if(n===Array){if((o=t.length)===e.length)for(;o--&&_t(t[o],e[o]););return o===-1}if(!n||typeof t=="object"){o=0;for(n in t)if(Te.call(t,n)&&++o&&!Te.call(e,n)||!(n in e)||!_t(t[n],e[n]))return!1;return Object.keys(e).length===o}}return t!==t&&e!==e}const Cn=(t,e)=>{const n=(s,a)=>s.x<=a.x+a.width&&s.x+s.width>=a.x&&s.y<=a.y+a.height&&s.y+s.height>=a.y,o=s=>s.rects.reduce((a,r)=>a+r.width,0),i=e.filter(({rects:s})=>s.some(a=>n(t,a)));return i.sort((s,a)=>o(a)-o(s)),i.findIndex(s=>s.rects.includes(t))},Ln=t=>{t.classList.add("r6o-annotatable");const e=document.createElement("div");e.className="r6o-span-highlight-layer",t.insertBefore(e,t.firstChild);let n=[];return{destroy:()=>{e.remove()},redraw:(a,r,l,d,p)=>{const f=!(_t(n,a)&&p);if(!d&&!f)return;f&&(e.innerHTML=""),[...a].sort((g,b)=>{const{annotation:{target:{created:v}}}=g,{annotation:{target:{created:m}}}=b;return v&&m?v.getTime()-m.getTime():0}).forEach(g=>{g.rects.map(b=>{const v=Cn(b,a),m=ue(g,r,l,d,v);if(f){const c=document.createElement("span");c.className="r6o-annotation",c.dataset.annotation=g.annotation.id,c.style.left=`${b.x}px`,c.style.top=`${b.y}px`,c.style.width=`${b.width}px`,c.style.height=`${b.height}px`,c.style.backgroundColor=H((m==null?void 0:m.fill)||z.fill).alpha((m==null?void 0:m.fillOpacity)===void 0?z.fillOpacity:m.fillOpacity).toHex(),m.underlineStyle&&(c.style.borderStyle=m.underlineStyle),m.underlineColor&&(c.style.borderColor=m.underlineColor),m.underlineThickness&&(c.style.borderBottomWidth=`${m.underlineThickness}px`),m.underlineOffset&&(c.style.paddingBottom=`${m.underlineOffset}px`),e.appendChild(c)}})}),n=a},setVisible:a=>{a?e.classList.remove("hidden"):e.classList.add("hidden")}}},Oe=(t,e,n)=>Mt(t,e,n,Ln(t)),Y=[];for(let t=0;t<256;++t)Y.push((t+256).toString(16).slice(1));function Tn(t,e=0){return(Y[t[e+0]]+Y[t[e+1]]+Y[t[e+2]]+Y[t[e+3]]+"-"+Y[t[e+4]]+Y[t[e+5]]+"-"+Y[t[e+6]]+Y[t[e+7]]+"-"+Y[t[e+8]]+Y[t[e+9]]+"-"+Y[t[e+10]]+Y[t[e+11]]+Y[t[e+12]]+Y[t[e+13]]+Y[t[e+14]]+Y[t[e+15]]).toLowerCase()}let Dt;const On=new Uint8Array(16);function Rn(){if(!Dt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Dt=crypto.getRandomValues.bind(crypto)}return Dt(On)}const Re={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Be(t,e,n){if(Re.randomUUID&&!e&&!t)return Re.randomUUID();t=t||{};const o=t.random||(t.rng||Rn)();return o[6]=o[6]&15|64,o[8]=o[8]&63|128,Tn(o)}var Me=Object.prototype.hasOwnProperty;function Z(t,e){var n,o;if(t===e)return!0;if(t&&e&&(n=t.constructor)===e.constructor){if(n===Date)return t.getTime()===e.getTime();if(n===RegExp)return t.toString()===e.toString();if(n===Array){if((o=t.length)===e.length)for(;o--&&Z(t[o],e[o]););return o===-1}if(!n||typeof t=="object"){o=0;for(n in t)if(Me.call(t,n)&&++o&&!Me.call(e,n)||!(n in e)||!Z(t[n],e[n]))return!1;return Object.keys(e).length===o}}return t!==t&&e!==e}function Ut(){}function Bn(t,e){return t!=t?e==e:t!==e||t&&typeof t=="object"||typeof t=="function"}const nt=[];function Vt(t,e=Ut){let n;const o=new Set;function i(r){if(Bn(t,r)&&(t=r,n)){const l=!nt.length;for(const d of o)d[1](),nt.push(d,t);if(l){for(let d=0;d<nt.length;d+=2)nt[d][0](nt[d+1]);nt.length=0}}}function s(r){i(r(t))}function a(r,l=Ut){const d=[r,l];return o.add(d),o.size===1&&(n=e(i,s)||Ut),r(t),()=>{o.delete(d),o.size===0&&n&&(n(),n=null)}}return{set:i,update:s,subscribe:a}}const Mn=t=>{const{subscribe:e,set:n}=Vt();let o;return e(i=>o=i),t.observe(({changes:i})=>{if(o){(i.deleted||[]).some(a=>a.id===o)&&n(void 0);const s=(i.updated||[]).find(({oldValue:a})=>a.id===o);s&&n(s.newValue.id)}}),{get current(){return o},subscribe:e,set:n}};var ke=(t=>(t.EDIT="EDIT",t.SELECT="SELECT",t.NONE="NONE",t))(ke||{});const St={selected:[]},kn=(t,e,n)=>{const{subscribe:o,set:i}=Vt(St);let s=e,a=St;o(g=>a=g);const r=()=>{Z(a,St)||i(St)},l=()=>{var g;return((g=a.selected)==null?void 0:g.length)===0},d=g=>{if(l())return!1;const b=typeof g=="string"?g:g.id;return a.selected.some(v=>v.id===b)},p=(g,b)=>{let v;if(Array.isArray(g)){if(v=g.map(c=>t.getAnnotation(c)).filter(Boolean),v.length<g.length){console.warn("Invalid selection: "+g.filter(c=>!v.some(y=>y.id===c)));return}}else{const c=t.getAnnotation(g);if(!c){console.warn("Invalid selection: "+g);return}v=[c]}const m=v.reduce((c,y)=>{const C=Ie(y,s,n);return C==="EDIT"?[...c,{id:y.id,editable:!0}]:C==="SELECT"?[...c,{id:y.id}]:c},[]);i({selected:m,event:b})},u=(g,b)=>{const v=Array.isArray(g)?g:[g],m=v.map(c=>t.getAnnotation(c)).filter(c=>!!c);i({selected:m.map(c=>{const y=b===void 0?Ie(c,s,n)==="EDIT":b;return{id:c.id,editable:y}})}),m.length!==v.length&&console.warn("Invalid selection",g)},f=g=>{if(l())return!1;const{selected:b}=a;b.some(({id:v})=>g.includes(v))&&i({selected:b.filter(({id:v})=>!g.includes(v))})},A=g=>s=g;return t.observe(({changes:g})=>f((g.deleted||[]).map(b=>b.id))),{get event(){return a?a.event:null},get selected(){return a?[...a.selected]:null},get userSelectAction(){return s},clear:r,isEmpty:l,isSelected:d,setSelected:u,setUserSelectAction:A,subscribe:o,userSelect:p}},Ie=(t,e,n)=>{const o=n?n.serialize(t):t;return typeof e=="function"?e(o):e||"EDIT"},P=[];for(let t=0;t<256;++t)P.push((t+256).toString(16).slice(1));function In(t,e=0){return(P[t[e+0]]+P[t[e+1]]+P[t[e+2]]+P[t[e+3]]+"-"+P[t[e+4]]+P[t[e+5]]+"-"+P[t[e+6]]+P[t[e+7]]+"-"+P[t[e+8]]+P[t[e+9]]+"-"+P[t[e+10]]+P[t[e+11]]+P[t[e+12]]+P[t[e+13]]+P[t[e+14]]+P[t[e+15]]).toLowerCase()}let Yt;const Nn=new Uint8Array(16);function _n(){if(!Yt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Yt=crypto.getRandomValues.bind(crypto)}return Yt(Nn)}const Dn=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Ne={randomUUID:Dn};function _e(t,e,n){if(Ne.randomUUID&&!e&&!t)return Ne.randomUUID();t=t||{};const o=t.random||(t.rng||_n)();return o[6]=o[6]&15|64,o[8]=o[8]&63|128,In(o)}const Pt=t=>{const e=n=>{const o={...n};return n.created&&typeof n.created=="string"&&(o.created=new Date(n.created)),n.updated&&typeof n.updated=="string"&&(o.updated=new Date(n.updated)),o};return{...t,bodies:(t.bodies||[]).map(e),target:e(t.target)}},Un=(t,e,n,o)=>({id:_e(),annotation:typeof t=="string"?t:t.id,created:n||new Date,creator:o,...e}),Vn=(t,e)=>{const n=new Set(t.bodies.map(o=>o.id));return e.bodies.filter(o=>!n.has(o.id))},Yn=(t,e)=>{const n=new Set(e.bodies.map(o=>o.id));return t.bodies.filter(o=>!n.has(o.id))},Pn=(t,e)=>e.bodies.map(n=>{const o=t.bodies.find(i=>i.id===n.id);return{newBody:n,oldBody:o&&!Z(o,n)?o:void 0}}).filter(({oldBody:n})=>n).map(({oldBody:n,newBody:o})=>({oldBody:n,newBody:o})),Kn=(t,e)=>!Z(t.target,e.target),De=(t,e)=>{const n=Vn(t,e),o=Yn(t,e),i=Pn(t,e);return{oldValue:t,newValue:e,bodiesCreated:n.length>0?n:void 0,bodiesDeleted:o.length>0?o:void 0,bodiesUpdated:i.length>0?i:void 0,targetUpdated:Kn(t,e)?{oldTarget:t.target,newTarget:e.target}:void 0}};var I=(t=>(t.LOCAL="LOCAL",t.REMOTE="REMOTE",t.SILENT="SILENT",t))(I||{});const Xn=(t,e)=>{var n,o;const{changes:i,origin:s}=e;if(!(t.options.origin?t.options.origin===s:s!=="SILENT"))return!1;if(t.options.ignore){const{ignore:a}=t.options,r=l=>l&&l.length>0;if(!(r(i.created)||r(i.deleted))){const l=(n=i.updated)==null?void 0:n.some(p=>r(p.bodiesCreated)||r(p.bodiesDeleted)||r(p.bodiesUpdated)),d=(o=i.updated)==null?void 0:o.some(p=>p.targetUpdated);if(a==="BODY_ONLY"&&l&&!d||a==="TARGET_ONLY"&&d&&!l)return!1}}if(t.options.annotations){const a=new Set([...(i.created||[]).map(r=>r.id),...(i.deleted||[]).map(r=>r.id),...(i.updated||[]).map(({oldValue:r})=>r.id)]);return!!(Array.isArray(t.options.annotations)?t.options.annotations:[t.options.annotations]).find(r=>a.has(r))}else return!0},$n=(t,e)=>{const n=new Set((t.created||[]).map(u=>u.id)),o=new Set((t.updated||[]).map(({newValue:u})=>u.id)),i=new Set((e.created||[]).map(u=>u.id)),s=new Set((e.deleted||[]).map(u=>u.id)),a=new Set((e.updated||[]).map(({oldValue:u})=>u.id)),r=new Set((e.updated||[]).filter(({oldValue:u})=>n.has(u.id)||o.has(u.id)).map(({oldValue:u})=>u.id)),l=[...(t.created||[]).filter(u=>!s.has(u.id)).map(u=>a.has(u.id)?e.updated.find(({oldValue:f})=>f.id===u.id).newValue:u),...e.created||[]],d=[...(t.deleted||[]).filter(u=>!i.has(u.id)),...(e.deleted||[]).filter(u=>!n.has(u.id))],p=[...(t.updated||[]).filter(({newValue:u})=>!s.has(u.id)).map(u=>{const{oldValue:f,newValue:A}=u;if(a.has(A.id)){const g=e.updated.find(b=>b.oldValue.id===A.id).newValue;return De(f,g)}else return u}),...(e.updated||[]).filter(({oldValue:u})=>!r.has(u.id))];return{created:l,deleted:d,updated:p}},Kt=t=>{const e=t.id===void 0?_e():t.id;return{...t,id:e,bodies:t.bodies===void 0?[]:t.bodies.map(n=>({...n,annotation:e})),target:{...t.target,annotation:e}}},Hn=t=>t.id!==void 0,jn=()=>{const t=new Map,e=new Map,n=[],o=(w,E={})=>{n.push({onChange:w,options:E})},i=w=>{const E=n.findIndex(h=>h.onChange==w);E>-1&&n.splice(E,1)},s=(w,E)=>{const h={origin:w,changes:{created:E.created||[],updated:E.updated||[],deleted:E.deleted||[]},state:[...t.values()]};n.forEach(S=>{Xn(S,h)&&S.onChange(h)})},a=(w,E=I.LOCAL)=>{if(w.id&&t.get(w.id))throw Error(`Cannot add annotation ${w.id} - exists already`);{const h=Kt(w);t.set(h.id,h),h.bodies.forEach(S=>e.set(S.id,h.id)),s(E,{created:[h]})}},r=(w,E)=>{const h=Kt(typeof w=="string"?E:w),S=typeof w=="string"?w:w.id,k=S&&t.get(S);if(k){const R=De(k,h);return S===h.id?t.set(S,h):(t.delete(S),t.set(h.id,h)),k.bodies.forEach(U=>e.delete(U.id)),h.bodies.forEach(U=>e.set(U.id,h.id)),R}else console.warn(`Cannot update annotation ${S} - does not exist`)},l=(w,E=I.LOCAL,h=I.LOCAL)=>{const S=Hn(E)?h:E,k=r(w,E);k&&s(S,{updated:[k]})},d=(w,E=I.LOCAL)=>{const h=w.reduce((S,k)=>{const R=r(k);return R?[...S,R]:S},[]);h.length>0&&s(E,{updated:h})},p=(w,E=I.LOCAL)=>{const h=t.get(w.annotation);if(h){const S={...h,bodies:[...h.bodies,w]};t.set(h.id,S),e.set(w.id,S.id),s(E,{updated:[{oldValue:h,newValue:S,bodiesCreated:[w]}]})}else console.warn(`Attempt to add body to missing annotation: ${w.annotation}`)},u=()=>[...t.values()],f=(w=I.LOCAL)=>{const E=[...t.values()];t.clear(),e.clear(),s(w,{deleted:E})},A=(w,E=!0,h=I.LOCAL)=>{const S=w.map(Kt);if(E){const k=[...t.values()];t.clear(),e.clear(),S.forEach(R=>{t.set(R.id,R),R.bodies.forEach(U=>e.set(U.id,R.id))}),s(h,{created:S,deleted:k})}else{const k=w.reduce((R,U)=>{const D=U.id&&t.get(U.id);return D?[...R,D]:R},[]);if(k.length>0)throw Error(`Bulk insert would overwrite the following annotations: ${k.map(R=>R.id).join(", ")}`);S.forEach(R=>{t.set(R.id,R),R.bodies.forEach(U=>e.set(U.id,R.id))}),s(h,{created:S})}},g=w=>{const E=typeof w=="string"?w:w.id,h=t.get(E);if(h)return t.delete(E),h.bodies.forEach(S=>e.delete(S.id)),h;console.warn(`Attempt to delete missing annotation: ${E}`)},b=(w,E=I.LOCAL)=>{const h=g(w);h&&s(E,{deleted:[h]})},v=(w,E=I.LOCAL)=>{const h=w.reduce((S,k)=>{const R=g(k);return R?[...S,R]:S},[]);h.length>0&&s(E,{deleted:h})},m=w=>{const E=t.get(w.annotation);if(E){const h=E.bodies.find(S=>S.id===w.id);if(h){e.delete(h.id);const S={...E,bodies:E.bodies.filter(k=>k.id!==w.id)};return t.set(E.id,S),{oldValue:E,newValue:S,bodiesDeleted:[h]}}else console.warn(`Attempt to delete missing body ${w.id} from annotation ${w.annotation}`)}else console.warn(`Attempt to delete body from missing annotation ${w.annotation}`)},c=(w,E=I.LOCAL)=>{const h=m(w);h&&s(E,{updated:[h]})},y=(w,E=I.LOCAL)=>{const h=w.map(S=>m(S)).filter(Boolean);h.length>0&&s(E,{updated:h})},C=w=>{const E=t.get(w);return E?{...E}:void 0},x=w=>{const E=e.get(w);if(E){const h=C(E).bodies.find(S=>S.id===w);if(h)return h;console.error(`Store integrity error: body ${w} in index, but not in annotation`)}else console.warn(`Attempt to retrieve missing body: ${w}`)},L=(w,E)=>{if(w.annotation!==E.annotation)throw"Annotation integrity violation: annotation ID must be the same when updating bodies";const h=t.get(w.annotation);if(h){const S=h.bodies.find(R=>R.id===w.id),k={...h,bodies:h.bodies.map(R=>R.id===S.id?E:R)};return t.set(h.id,k),S.id!==E.id&&(e.delete(S.id),e.set(E.id,k.id)),{oldValue:h,newValue:k,bodiesUpdated:[{oldBody:S,newBody:E}]}}else console.warn(`Attempt to add body to missing annotation ${w.annotation}`)},B=(w,E,h=I.LOCAL)=>{const S=L(w,E);S&&s(h,{updated:[S]})},T=(w,E=I.LOCAL)=>{const h=w.map(S=>L({id:S.id,annotation:S.annotation},S)).filter(Boolean);s(E,{updated:h})},M=w=>{const E=t.get(w.annotation);if(E){const h={...E,target:{...E.target,...w}};return t.set(E.id,h),{oldValue:E,newValue:h,targetUpdated:{oldTarget:E.target,newTarget:w}}}else console.warn(`Attempt to update target on missing annotation: ${w.annotation}`)};return{addAnnotation:a,addBody:p,all:u,bulkAddAnnotation:A,bulkDeleteAnnotation:v,bulkDeleteBodies:y,bulkUpdateAnnotation:d,bulkUpdateBodies:T,bulkUpdateTargets:(w,E=I.LOCAL)=>{const h=w.map(S=>M(S)).filter(Boolean);h.length>0&&s(E,{updated:h})},clear:f,deleteAnnotation:b,deleteBody:c,getAnnotation:C,getBody:x,observe:o,unobserve:i,updateAnnotation:l,updateBody:B,updateTarget:(w,E=I.LOCAL)=>{const h=M(w);h&&s(E,{updated:[h]})}}};let Fn=()=>({emit(t,...e){for(let n=this.events[t]||[],o=0,i=n.length;o<i;o++)n[o](...e)},events:{},on(t,e){var n;return((n=this.events)[t]||(n[t]=[])).push(e),()=>{var o;this.events[t]=(o=this.events[t])==null?void 0:o.filter(i=>e!==i)}}});const zn=250,Wn=(t,e)=>{const n=Fn(),o=[];let i=-1,s=!1,a=0;const r=g=>{if(!s){const{changes:b}=g,v=performance.now();if(v-a>zn)o.splice(i+1),o.push(b),i=o.length-1;else{const m=o.length-1;o[m]=$n(o[m],b)}a=v}s=!1};t.observe(r,{origin:I.LOCAL});const l=g=>g&&g.length>0&&t.bulkDeleteAnnotation(g),d=g=>g&&g.length>0&&t.bulkAddAnnotation(g,!1),p=g=>g&&g.length>0&&t.bulkUpdateAnnotation(g.map(({oldValue:b})=>b)),u=g=>g&&g.length>0&&t.bulkUpdateAnnotation(g.map(({newValue:b})=>b)),f=g=>g&&g.length>0&&t.bulkAddAnnotation(g,!1),A=g=>g&&g.length>0&&t.bulkDeleteAnnotation(g);return{canRedo:()=>o.length-1>i,canUndo:()=>i>-1,destroy:()=>t.unobserve(r),getHistory:()=>({changes:[...o],pointer:i}),on:(g,b)=>n.on(g,b),redo:()=>{if(o.length-1>i){s=!0;const{created:g,updated:b,deleted:v}=o[i+1];d(g),u(b),A(v),n.emit("redo",o[i+1]),i+=1}},undo:()=>{if(i>-1){s=!0;const{created:g,updated:b,deleted:v}=o[i];l(g),p(b),f(v),n.emit("undo",o[i]),i-=1}}}},qn=()=>{const{subscribe:t,set:e}=Vt([]);return{subscribe:t,set:e}},Gn=(t,e,n,o)=>{const{hover:i,selection:s,store:a,viewport:r}=t,l=new Map;let d=[],p;const u=(b,v)=>{l.has(b)?l.get(b).push(v):l.set(b,[v])},f=(b,v)=>{const m=l.get(b);if(m){const c=m.indexOf(v);c!==-1&&m.splice(c,1)}},A=(b,v,m)=>{l.has(b)&&setTimeout(()=>{l.get(b).forEach(c=>{if(n){const y=Array.isArray(v)?v.map(x=>n.serialize(x)):n.serialize(v),C=m?m instanceof PointerEvent?m:n.serialize(m):void 0;c(y,C)}else c(v,m)})},1)};s.subscribe(({selected:b})=>{if(!(d.length===0&&b.length===0)){if(d.length===0&&b.length>0)d=b.map(({id:v})=>a.getAnnotation(v));else if(d.length>0&&b.length===0)d.forEach(v=>{const m=a.getAnnotation(v.id);m&&!Z(m,v)&&A("updateAnnotation",m,v)}),d=[];else{const v=new Set(d.map(c=>c.id)),m=new Set(b.map(({id:c})=>c));d.filter(c=>!m.has(c.id)).forEach(c=>{const y=a.getAnnotation(c.id);y&&!Z(y,c)&&A("updateAnnotation",y,c)}),d=[...d.filter(c=>m.has(c.id)),...b.filter(({id:c})=>!v.has(c)).map(({id:c})=>a.getAnnotation(c))]}A("selectionChanged",d)}}),i.subscribe(b=>{!p&&b?A("mouseEnterAnnotation",a.getAnnotation(b)):p&&!b?A("mouseLeaveAnnotation",a.getAnnotation(p)):p&&b&&(A("mouseLeaveAnnotation",a.getAnnotation(p)),A("mouseEnterAnnotation",a.getAnnotation(b))),p=b}),r==null||r.subscribe(b=>A("viewportIntersect",b.map(v=>a.getAnnotation(v)))),a.observe(b=>{const{created:v,deleted:m}=b.changes;(v||[]).forEach(c=>A("createAnnotation",c)),(m||[]).forEach(c=>A("deleteAnnotation",c)),(b.changes.updated||[]).filter(c=>[...c.bodiesCreated||[],...c.bodiesDeleted||[],...c.bodiesUpdated||[]].length>0).forEach(({oldValue:c,newValue:y})=>{const C=d.find(x=>x.id===c.id)||c;d=d.map(x=>x.id===c.id?y:x),A("updateAnnotation",y,C)})},{origin:I.LOCAL}),a.observe(b=>{if(d){const v=new Set(d.map(c=>c.id)),m=(b.changes.updated||[]).filter(({newValue:c})=>v.has(c.id)).map(({newValue:c})=>c);m.length>0&&(d=d.map(c=>m.find(C=>C.id===c.id)||c))}},{origin:I.REMOTE});const g=b=>v=>{const{updated:m}=v;b?(m||[]).forEach(c=>A("updateAnnotation",c.oldValue,c.newValue)):(m||[]).forEach(c=>A("updateAnnotation",c.newValue,c.oldValue))};return e.on("undo",g(!0)),e.on("redo",g(!1)),{on:u,off:f,emit:A}},Qn=t=>e=>e.reduce((n,o)=>{const{parsed:i,error:s}=t.parse(o);return s?{parsed:n.parsed,failed:[...n.failed,o]}:i?{parsed:[...n.parsed,i],failed:n.failed}:{...n}},{parsed:[],failed:[]}),Jn=(t,e,n)=>{const{store:o,selection:i}=t,s=m=>{if(n){const{parsed:c,error:y}=n.parse(m);c?o.addAnnotation(c,I.REMOTE):console.error(y)}else o.addAnnotation(Pt(m),I.REMOTE)},a=()=>i.clear(),r=()=>o.clear(),l=m=>{const c=o.getAnnotation(m);return n&&c?n.serialize(c):c},d=()=>n?o.all().map(n.serialize):o.all(),p=()=>{var m;const c=(((m=i.selected)==null?void 0:m.map(y=>y.id))||[]).map(y=>o.getAnnotation(y)).filter(Boolean);return n?c.map(n.serialize):c},u=(m,c=!0)=>fetch(m).then(y=>y.json()).then(y=>(A(y,c),y)),f=m=>{if(typeof m=="string"){const c=o.getAnnotation(m);if(o.deleteAnnotation(m),c)return n?n.serialize(c):c}else{const c=n?n.parse(m).parsed:m;if(c)return o.deleteAnnotation(c),m}},A=(m,c=!0)=>{if(n){const y=n.parseAll||Qn(n),{parsed:C,failed:x}=y(m);x.length>0&&console.warn(`Discarded ${x.length} invalid annotations`,x),o.bulkAddAnnotation(C,c,I.REMOTE)}else o.bulkAddAnnotation(m.map(Pt),c,I.REMOTE)},g=(m,c)=>{m?i.setSelected(m,c):i.clear()},b=m=>{i.clear(),i.setUserSelectAction(m)},v=m=>{if(n){const c=n.parse(m).parsed,y=n.serialize(o.getAnnotation(c.id));return o.updateAnnotation(c),y}else{const c=o.getAnnotation(m.id);return o.updateAnnotation(Pt(m)),c}};return{addAnnotation:s,cancelSelected:a,canRedo:e.canRedo,canUndo:e.canUndo,clearAnnotations:r,getAnnotationById:l,getAnnotations:d,getHistory:e.getHistory,getSelected:p,loadAnnotations:u,redo:e.redo,removeAnnotation:f,setAnnotations:A,setSelected:g,setUserSelectAction:b,undo:e.undo,updateAnnotation:v}},Zn="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let to=t=>crypto.getRandomValues(new Uint8Array(t)),eo=(t,e,n)=>{let o=(2<<Math.log2(t.length-1))-1,i=-~(1.6*o*e/t.length);return(s=e)=>{let a="";for(;;){let r=n(i),l=i|0;for(;l--;)if(a+=t[r[l]&o]||"",a.length>=s)return a}}},no=(t,e=21)=>eo(t,e|0,to),oo=(t=21)=>{let e="",n=crypto.getRandomValues(new Uint8Array(t|=0));for(;t--;)e+=Zn[n[t]&63];return e};const io=()=>({isGuest:!0,id:no("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_",20)()}),so=t=>{const e=JSON.stringify(t);let n=0;for(let o=0,i=e.length;o<i;o++){let s=e.charCodeAt(o);n=(n<<5)-n+s,n|=0}return`${n}`},Ue=t=>t?typeof t=="object"?{...t}:t:void 0,ro=(t,e)=>(Array.isArray(t)?t:[t]).map(n=>{const{id:o,type:i,purpose:s,value:a,created:r,modified:l,creator:d,...p}=n;return{id:o||`temp-${so(n)}`,annotation:e,type:i,purpose:s,value:a,creator:Ue(d),created:r?new Date(r):void 0,updated:l?new Date(l):void 0,...p}}),ao=t=>t.map(e=>{var n;const{annotation:o,created:i,updated:s,...a}=e,r={...a,created:i==null?void 0:i.toISOString(),modified:s==null?void 0:s.toISOString()};return(n=r.id)!=null&&n.startsWith("temp-")&&delete r.id,r});oo();const co=(t,e)=>({parse:n=>Ve(n),serialize:n=>Ye(n,t,e)}),lo=t=>t.quote!==void 0&&t.start!==void 0&&t.end!==void 0,uo=t=>{const{id:e,creator:n,created:o,modified:i,target:s}=t,a=Array.isArray(s)?s:[s];if(a.length===0)return{error:Error(`No targets found for annotation: ${t.id}`)};const r={creator:Ue(n),created:o?new Date(o):void 0,updated:i?new Date(i):void 0,annotation:e,selector:[],styleClass:"styleClass"in a[0]?a[0].styleClass:void 0};for(const l of a){const p=(Array.isArray(l.selector)?l.selector:[l.selector]).reduce((u,f)=>{switch(f.type){case"TextQuoteSelector":u.quote=f.exact;break;case"TextPositionSelector":u.start=f.start,u.end=f.end;break}return u},{});if(lo(p))"outdated"in l&&l.outdated,r.selector.push({...p,id:l.id,scope:l.scope});else{const u=[p.start?void 0:"TextPositionSelector",p.quote?void 0:"TextQuoteSelector"].filter(Boolean);return{error:Error(`Missing selector types: ${u.join(" and ")} for annotation: ${t.id}`)}}}return{parsed:r}},Ve=t=>{const e=t.id||Be(),{creator:n,created:o,modified:i,body:s,...a}=t,r=ro(s,e),l=uo(t);return"error"in l?{error:l.error}:{parsed:{...a,id:e,bodies:r,target:l.parsed}}},Ye=(t,e,n)=>{const{bodies:o,target:i,...s}=t,{selector:a,creator:r,created:l,updated:d,...p}=i,u=a.map(f=>{const{id:A,quote:g,start:b,end:v,range:m}=f,{prefix:c,suffix:y}=te(m,n),C=[{type:"TextQuoteSelector",exact:g,prefix:c,suffix:y},{type:"TextPositionSelector",start:b,end:v}];return{...p,id:A,outdated:"outdated"in f?f.outdated:void 0,scope:"scope"in f?f.scope:void 0,source:e,selector:C}});return{...s,"@context":"http://www.w3.org/ns/anno.jsonld",id:t.id,type:"Annotation",body:ao(t.bodies),creator:r,created:l==null?void 0:l.toISOString(),modified:d==null?void 0:d.toISOString(),target:u}};function Pe(t,e,n=0,o=t.length-1,i=fo){for(;o>n;){if(o-n>600){const l=o-n+1,d=e-n+1,p=Math.log(l),u=.5*Math.exp(2*p/3),f=.5*Math.sqrt(p*u*(l-u)/l)*(d-l/2<0?-1:1),A=Math.max(n,Math.floor(e-d*u/l+f)),g=Math.min(o,Math.floor(e+(l-d)*u/l+f));Pe(t,e,A,g,i)}const s=t[e];let a=n,r=o;for(lt(t,n,e),i(t[o],s)>0&&lt(t,n,o);a<r;){for(lt(t,a,r),a++,r--;i(t[a],s)<0;)a++;for(;i(t[r],s)>0;)r--}i(t[n],s)===0?lt(t,n,r):(r++,lt(t,r,o)),r<=e&&(n=r+1),e<=r&&(o=r-1)}}function lt(t,e,n){const o=t[e];t[e]=t[n],t[n]=o}function fo(t,e){return t<e?-1:t>e?1:0}class ho{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(this._maxEntries*.4)),this.clear()}all(){return this._all(this.data,[])}search(e){let n=this.data;const o=[];if(!Ct(e,n))return o;const i=this.toBBox,s=[];for(;n;){for(let a=0;a<n.children.length;a++){const r=n.children[a],l=n.leaf?i(r):r;Ct(e,l)&&(n.leaf?o.push(r):$t(e,l)?this._all(r,o):s.push(r))}n=s.pop()}return o}collides(e){let n=this.data;if(!Ct(e,n))return!1;const o=[];for(;n;){for(let i=0;i<n.children.length;i++){const s=n.children[i],a=n.leaf?this.toBBox(s):s;if(Ct(e,a)){if(n.leaf||$t(e,a))return!0;o.push(s)}}n=o.pop()}return!1}load(e){if(!(e&&e.length))return this;if(e.length<this._minEntries){for(let o=0;o<e.length;o++)this.insert(e[o]);return this}let n=this._build(e.slice(),0,e.length-1,0);if(!this.data.children.length)this.data=n;else if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){const o=this.data;this.data=n,n=o}this._insert(n,this.data.height-n.height-1,!0)}return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=it([]),this}remove(e,n){if(!e)return this;let o=this.data;const i=this.toBBox(e),s=[],a=[];let r,l,d;for(;o||s.length;){if(o||(o=s.pop(),l=s[s.length-1],r=a.pop(),d=!0),o.leaf){const p=go(e,o.children,n);if(p!==-1)return o.children.splice(p,1),s.push(o),this._condense(s),this}!d&&!o.leaf&&$t(o,i)?(s.push(o),a.push(r),r=0,l=o,o=o.children[0]):l?(r++,o=l.children[r],d=!1):o=null}return this}toBBox(e){return e}compareMinX(e,n){return e.minX-n.minX}compareMinY(e,n){return e.minY-n.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,n){const o=[];for(;e;)e.leaf?n.push(...e.children):o.push(...e.children),e=o.pop();return n}_build(e,n,o,i){const s=o-n+1;let a=this._maxEntries,r;if(s<=a)return r=it(e.slice(n,o+1)),ot(r,this.toBBox),r;i||(i=Math.ceil(Math.log(s)/Math.log(a)),a=Math.ceil(s/Math.pow(a,i-1))),r=it([]),r.leaf=!1,r.height=i;const l=Math.ceil(s/a),d=l*Math.ceil(Math.sqrt(a));Ke(e,n,o,d,this.compareMinX);for(let p=n;p<=o;p+=d){const u=Math.min(p+d-1,o);Ke(e,p,u,l,this.compareMinY);for(let f=p;f<=u;f+=l){const A=Math.min(f+l-1,u);r.children.push(this._build(e,f,A,i-1))}}return ot(r,this.toBBox),r}_chooseSubtree(e,n,o,i){for(;i.push(n),!(n.leaf||i.length-1===o);){let s=1/0,a=1/0,r;for(let l=0;l<n.children.length;l++){const d=n.children[l],p=Xt(d),u=yo(e,d)-p;u<a?(a=u,s=p<s?p:s,r=d):u===a&&p<s&&(s=p,r=d)}n=r||n.children[0]}return n}_insert(e,n,o){const i=o?e:this.toBBox(e),s=[],a=this._chooseSubtree(i,this.data,n,s);for(a.children.push(e),ut(a,i);n>=0&&s[n].children.length>this._maxEntries;)this._split(s,n),n--;this._adjustParentBBoxes(i,s,n)}_split(e,n){const o=e[n],i=o.children.length,s=this._minEntries;this._chooseSplitAxis(o,s,i);const a=this._chooseSplitIndex(o,s,i),r=it(o.children.splice(a,o.children.length-a));r.height=o.height,r.leaf=o.leaf,ot(o,this.toBBox),ot(r,this.toBBox),n?e[n-1].children.push(r):this._splitRoot(o,r)}_splitRoot(e,n){this.data=it([e,n]),this.data.height=e.height+1,this.data.leaf=!1,ot(this.data,this.toBBox)}_chooseSplitIndex(e,n,o){let i,s=1/0,a=1/0;for(let r=n;r<=o-n;r++){const l=dt(e,0,r,this.toBBox),d=dt(e,r,o,this.toBBox),p=bo(l,d),u=Xt(l)+Xt(d);p<s?(s=p,i=r,a=u<a?u:a):p===s&&u<a&&(a=u,i=r)}return i||o-n}_chooseSplitAxis(e,n,o){const i=e.leaf?this.compareMinX:po,s=e.leaf?this.compareMinY:mo,a=this._allDistMargin(e,n,o,i),r=this._allDistMargin(e,n,o,s);a<r&&e.children.sort(i)}_allDistMargin(e,n,o,i){e.children.sort(i);const s=this.toBBox,a=dt(e,0,n,s),r=dt(e,o-n,o,s);let l=xt(a)+xt(r);for(let d=n;d<o-n;d++){const p=e.children[d];ut(a,e.leaf?s(p):p),l+=xt(a)}for(let d=o-n-1;d>=n;d--){const p=e.children[d];ut(r,e.leaf?s(p):p),l+=xt(r)}return l}_adjustParentBBoxes(e,n,o){for(let i=o;i>=0;i--)ut(n[i],e)}_condense(e){for(let n=e.length-1,o;n>=0;n--)e[n].children.length===0?n>0?(o=e[n-1].children,o.splice(o.indexOf(e[n]),1)):this.clear():ot(e[n],this.toBBox)}}function go(t,e,n){if(!n)return e.indexOf(t);for(let o=0;o<e.length;o++)if(n(t,e[o]))return o;return-1}function ot(t,e){dt(t,0,t.children.length,e,t)}function dt(t,e,n,o,i){i||(i=it(null)),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(let s=e;s<n;s++){const a=t.children[s];ut(i,t.leaf?o(a):a)}return i}function ut(t,e){return t.minX=Math.min(t.minX,e.minX),t.minY=Math.min(t.minY,e.minY),t.maxX=Math.max(t.maxX,e.maxX),t.maxY=Math.max(t.maxY,e.maxY),t}function po(t,e){return t.minX-e.minX}function mo(t,e){return t.minY-e.minY}function Xt(t){return(t.maxX-t.minX)*(t.maxY-t.minY)}function xt(t){return t.maxX-t.minX+(t.maxY-t.minY)}function yo(t,e){return(Math.max(e.maxX,t.maxX)-Math.min(e.minX,t.minX))*(Math.max(e.maxY,t.maxY)-Math.min(e.minY,t.minY))}function bo(t,e){const n=Math.max(t.minX,e.minX),o=Math.max(t.minY,e.minY),i=Math.min(t.maxX,e.maxX),s=Math.min(t.maxY,e.maxY);return Math.max(0,i-n)*Math.max(0,s-o)}function $t(t,e){return t.minX<=e.minX&&t.minY<=e.minY&&e.maxX<=t.maxX&&e.maxY<=t.maxY}function Ct(t,e){return e.minX<=t.maxX&&e.minY<=t.maxY&&e.maxX>=t.minX&&e.maxY>=t.minY}function it(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function Ke(t,e,n,o,i){const s=[e,n];for(;s.length;){if(n=s.pop(),e=s.pop(),n-e<=o)continue;const a=e+Math.ceil((n-e)/o/2)*o;Pe(t,a,e,n,i),s.push(e,a,a,n)}}let wo=()=>({emit(t,...e){for(let n=this.events[t]||[],o=0,i=n.length;o<i;o++)n[o](...e)},events:{},on(t,e){var n;return((n=this.events)[t]||(n[t]=[])).push(e),()=>{var o;this.events[t]=(o=this.events[t])==null?void 0:o.filter(i=>e!==i)}}});const Ao=(t,e)=>{const n=new ho,o=new Map,i=wo(),s=(y,C)=>{const x=y.selector.flatMap(B=>{const T=j([B])?B.range:Rt(B,e).range;return Array.from(T.getClientRects())}),L=oe(x).map(B=>ce(B,C));return L.map(B=>{const{x:T,y:M,width:w,height:E}=B;return{minX:T,minY:M,maxX:T+w,maxY:M+E,annotation:{id:y.annotation,rects:L}}})},a=()=>[...o.values()],r=()=>{n.clear(),o.clear()},l=y=>{const C=s(y,e.getBoundingClientRect());C.length!==0&&(C.forEach(x=>n.insert(x)),o.set(y.annotation,C))},d=y=>{const C=o.get(y.annotation);C&&(C.forEach(x=>n.remove(x)),o.delete(y.annotation))},p=y=>{d(y),l(y)},u=(y,C=!0)=>{C&&r();const x=e.getBoundingClientRect(),L=y.map(T=>({target:T,rects:s(T,x)}));L.forEach(({target:T,rects:M})=>{M.length>0&&o.set(T.annotation,M)});const B=L.flatMap(({rects:T})=>T);n.load(B)},f=(y,C,x=!1)=>{const L=n.search({minX:y,minY:C,maxX:y,maxY:C}),B=T=>T.annotation.rects.reduce((M,w)=>M+w.width*w.height,0);return L.length>0?(L.sort((T,M)=>B(T)-B(M)),x?L.map(T=>T.annotation.id):[L[0].annotation.id]):[]},A=y=>{const C=g(y);if(C.length===0)return;let x=C[0].left,L=C[0].top,B=C[0].right,T=C[0].bottom;for(let M=1;M<C.length;M++){const w=C[M];x=Math.min(x,w.left),L=Math.min(L,w.top),B=Math.max(B,w.right),T=Math.max(T,w.bottom)}return new DOMRect(x,L,B-x,T-L)},g=y=>{const C=o.get(y);return C?C[0].annotation.rects:[]};return{all:a,clear:r,getAt:f,getAnnotationBounds:A,getAnnotationRects:g,getIntersecting:(y,C,x,L)=>{const B=n.search({minX:y,minY:C,maxX:x,maxY:L}),T=new Set(B.map(M=>M.annotation.id));return Array.from(T).map(M=>({annotation:t.getAnnotation(M),rects:g(M)})).filter(M=>!!M.annotation)},insert:l,recalculate:()=>{u(t.all().map(y=>y.target),!0),i.emit("recalculate")},remove:d,set:u,size:()=>n.all().length,update:p,on:(y,C)=>i.on(y,C)}},Xe=(t,e)=>{const n=jn(),o=Ao(n,t),i=kn(n,e.userSelectAction,e.adapter),s=Mn(n),a=qn(),r=(c,y=I.LOCAL)=>{const C=wt(c,t),x=j(C.target.selector);return x&&n.addAnnotation(C,y),x},l=(c,y=!0,C=I.LOCAL)=>{const x=c.map(B=>wt(B,t)),L=x.filter(B=>!j(B.target.selector));return n.bulkAddAnnotation(x,y,C),L},d=(c,y=I.LOCAL)=>{const C=c.map(L=>wt(L,t)),x=C.filter(L=>!j(L.target.selector));return C.forEach(L=>{n.getAnnotation(L.id)?n.updateAnnotation(L,y):n.addAnnotation(L,y)}),x},p=(c,y=I.LOCAL)=>{const C=st(c,t);n.updateTarget(C,y)},u=(c,y=I.LOCAL)=>{const C=c.map(x=>st(x,t));n.bulkUpdateTargets(C,y)};function f(c,y,C,x){const L=C||!!x,B=o.getAt(c,y,L).map(M=>n.getAnnotation(M)),T=x?B.filter(x):B;if(T.length!==0)return C?T:T[0]}const A=c=>o.getAnnotationRects(c).length>0?o.getAnnotationBounds(c):void 0,g=(c,y,C,x)=>o.getIntersecting(c,y,C,x),b=c=>o.getAnnotationRects(c),v=()=>o.recalculate(),m=c=>o.on("recalculate",c);return n.observe(({changes:c})=>{const y=(c.deleted||[]).filter(L=>j(L.target.selector)),C=(c.created||[]).filter(L=>j(L.target.selector)),x=(c.updated||[]).filter(L=>j(L.newValue.target.selector));(y==null?void 0:y.length)>0&&y.forEach(L=>o.remove(L.target)),C.length>0&&o.set(C.map(L=>L.target),!1),(x==null?void 0:x.length)>0&&x.forEach(({newValue:L})=>o.update(L.target))}),{store:{...n,addAnnotation:r,bulkAddAnnotation:l,bulkUpdateTargets:u,bulkUpsertAnnotations:d,getAnnotationBounds:A,getAnnotationRects:b,getIntersecting:g,getAt:f,recalculatePositions:v,onRecalculatePositions:m,updateTarget:p},selection:i,hover:s,viewport:a}},vo=()=>{const t=document.createElement("canvas");t.width=2*window.innerWidth,t.height=2*window.innerHeight,t.className="r6o-presence-layer";const e=t.getContext("2d");return e.scale(2,2),e.translate(.5,.5),t},$e=(t,e={})=>{const n=vo(),o=n.getContext("2d");document.body.appendChild(n);const i=new Map,s=p=>Array.from(i.entries()).filter(([u,f])=>f.presenceKey===p.presenceKey).map(([u,f])=>u);return t.on("selectionChange",(p,u)=>{s(p).forEach(A=>i.delete(A)),u&&u.forEach(A=>i.set(A,p))}),{clear:()=>{const{width:p,height:u}=n;o.clearRect(-.5,-.5,p+1,u+1)},destroy:()=>{n.remove()},paint:(p,u,f)=>{e.font&&(o.font=e.font);const A=i.get(p.annotation.id);if(A){const{height:g}=p.rects[0],b=p.rects[0].x+u.left,v=p.rects[0].y+u.top;o.fillStyle=A.appearance.color,o.fillRect(b-2,v-2.5,2,g+5);const m=o.measureText(A.appearance.label),c=m.width+6,y=m.actualBoundingBoxAscent+m.actualBoundingBoxDescent+8,C=m.fontBoundingBoxAscent?8:6.5;return o.fillRect(b-2,v-2.5-y,c,y),o.fillStyle="#fff",o.fillText(A.appearance.label,b+1,v-C),{fill:A.appearance.color,fillOpacity:f?.45:.18}}},reset:()=>{n.width=2*window.innerWidth,n.height=2*window.innerHeight;const p=n.getContext("2d");p.scale(2,2),p.translate(.5,.5)}}},Ht=typeof navigator<"u"?navigator.userAgent.toLowerCase().indexOf("firefox")>0:!1;function jt(t,e,n,o){t.addEventListener?t.addEventListener(e,n,o):t.attachEvent&&t.attachEvent("on".concat(e),n)}function ft(t,e,n,o){t.removeEventListener?t.removeEventListener(e,n,o):t.detachEvent&&t.detachEvent("on".concat(e),n)}function He(t,e){const n=e.slice(0,e.length-1);for(let o=0;o<n.length;o++)n[o]=t[n[o].toLowerCase()];return n}function je(t){typeof t!="string"&&(t=""),t=t.replace(/\s/g,"");const e=t.split(",");let n=e.lastIndexOf("");for(;n>=0;)e[n-1]+=",",e.splice(n,1),n=e.lastIndexOf("");return e}function Eo(t,e){const n=t.length>=e.length?t:e,o=t.length>=e.length?e:t;let i=!0;for(let s=0;s<n.length;s++)o.indexOf(n[s])===-1&&(i=!1);return i}const ht={backspace:8,"⌫":8,tab:9,clear:12,enter:13,"↩":13,return:13,esc:27,escape:27,space:32,left:37,up:38,right:39,down:40,del:46,delete:46,ins:45,insert:45,home:36,end:35,pageup:33,pagedown:34,capslock:20,num_0:96,num_1:97,num_2:98,num_3:99,num_4:100,num_5:101,num_6:102,num_7:103,num_8:104,num_9:105,num_multiply:106,num_add:107,num_enter:108,num_subtract:109,num_decimal:110,num_divide:111,"⇪":20,",":188,".":190,"/":191,"`":192,"-":Ht?173:189,"=":Ht?61:187,";":Ht?59:186,"'":222,"[":219,"]":221,"\\":220},F={"⇧":16,shift:16,"⌥":18,alt:18,option:18,"⌃":17,ctrl:17,control:17,"⌘":91,cmd:91,command:91},Lt={16:"shiftKey",18:"altKey",17:"ctrlKey",91:"metaKey",shiftKey:16,ctrlKey:17,altKey:18,metaKey:91},K={16:!1,18:!1,17:!1,91:!1},_={};for(let t=1;t<20;t++)ht["f".concat(t)]=111+t;let N=[],gt=null,Fe="all";const q=new Map,pt=t=>ht[t.toLowerCase()]||F[t.toLowerCase()]||t.toUpperCase().charCodeAt(0),So=t=>Object.keys(ht).find(e=>ht[e]===t),xo=t=>Object.keys(F).find(e=>F[e]===t);function ze(t){Fe=t||"all"}function mt(){return Fe||"all"}function Co(){return N.slice(0)}function Lo(){return N.map(t=>So(t)||xo(t)||String.fromCharCode(t))}function To(){const t=[];return Object.keys(_).forEach(e=>{_[e].forEach(n=>{let{key:o,scope:i,mods:s,shortcut:a}=n;t.push({scope:i,shortcut:a,mods:s,keys:o.split("+").map(r=>pt(r))})})}),t}function Oo(t){const e=t.target||t.srcElement,{tagName:n}=e;let o=!0;const i=n==="INPUT"&&!["checkbox","radio","range","button","file","reset","submit","color"].includes(e.type);return(e.isContentEditable||(i||n==="TEXTAREA"||n==="SELECT")&&!e.readOnly)&&(o=!1),o}function Ro(t){return typeof t=="string"&&(t=pt(t)),N.indexOf(t)!==-1}function Bo(t,e){let n,o;t||(t=mt());for(const i in _)if(Object.prototype.hasOwnProperty.call(_,i))for(n=_[i],o=0;o<n.length;)n[o].scope===t?n.splice(o,1).forEach(a=>{let{element:r}=a;return Ft(r)}):o++;mt()===t&&ze(e||"all")}function Mo(t){let e=t.keyCode||t.which||t.charCode;const n=N.indexOf(e);if(n>=0&&N.splice(n,1),t.key&&t.key.toLowerCase()==="meta"&&N.splice(0,N.length),(e===93||e===224)&&(e=91),e in K){K[e]=!1;for(const o in F)F[o]===e&&($[o]=!1)}}function We(t){if(typeof t>"u")Object.keys(_).forEach(i=>{Array.isArray(_[i])&&_[i].forEach(s=>Tt(s)),delete _[i]}),Ft(null);else if(Array.isArray(t))t.forEach(i=>{i.key&&Tt(i)});else if(typeof t=="object")t.key&&Tt(t);else if(typeof t=="string"){for(var e=arguments.length,n=new Array(e>1?e-1:0),o=1;o<e;o++)n[o-1]=arguments[o];let[i,s]=n;typeof i=="function"&&(s=i,i=""),Tt({key:t,scope:i,method:s,splitKey:"+"})}}const Tt=t=>{let{key:e,scope:n,method:o,splitKey:i="+"}=t;je(e).forEach(a=>{const r=a.split(i),l=r.length,d=r[l-1],p=d==="*"?"*":pt(d);if(!_[p])return;n||(n=mt());const u=l>1?He(F,r):[],f=[];_[p]=_[p].filter(A=>{const b=(o?A.method===o:!0)&&A.scope===n&&Eo(A.mods,u);return b&&f.push(A.element),!b}),f.forEach(A=>Ft(A))})};function qe(t,e,n,o){if(e.element!==o)return;let i;if(e.scope===n||e.scope==="all"){i=e.mods.length>0;for(const s in K)Object.prototype.hasOwnProperty.call(K,s)&&(!K[s]&&e.mods.indexOf(+s)>-1||K[s]&&e.mods.indexOf(+s)===-1)&&(i=!1);(e.mods.length===0&&!K[16]&&!K[18]&&!K[17]&&!K[91]||i||e.shortcut==="*")&&(e.keys=[],e.keys=e.keys.concat(N),e.method(t,e)===!1&&(t.preventDefault?t.preventDefault():t.returnValue=!1,t.stopPropagation&&t.stopPropagation(),t.cancelBubble&&(t.cancelBubble=!0)))}}function Ge(t,e){const n=_["*"];let o=t.keyCode||t.which||t.charCode;if(!$.filter.call(this,t))return;if((o===93||o===224)&&(o=91),N.indexOf(o)===-1&&o!==229&&N.push(o),["metaKey","ctrlKey","altKey","shiftKey"].forEach(r=>{const l=Lt[r];t[r]&&N.indexOf(l)===-1?N.push(l):!t[r]&&N.indexOf(l)>-1?N.splice(N.indexOf(l),1):r==="metaKey"&&t[r]&&(N=N.filter(d=>d in Lt||d===o))}),o in K){K[o]=!0;for(const r in F)F[r]===o&&($[r]=!0);if(!n)return}for(const r in K)Object.prototype.hasOwnProperty.call(K,r)&&(K[r]=t[Lt[r]]);t.getModifierState&&!(t.altKey&&!t.ctrlKey)&&t.getModifierState("AltGraph")&&(N.indexOf(17)===-1&&N.push(17),N.indexOf(18)===-1&&N.push(18),K[17]=!0,K[18]=!0);const i=mt();if(n)for(let r=0;r<n.length;r++)n[r].scope===i&&(t.type==="keydown"&&n[r].keydown||t.type==="keyup"&&n[r].keyup)&&qe(t,n[r],i,e);if(!(o in _))return;const s=_[o],a=s.length;for(let r=0;r<a;r++)if((t.type==="keydown"&&s[r].keydown||t.type==="keyup"&&s[r].keyup)&&s[r].key){const l=s[r],{splitKey:d}=l,p=l.key.split(d),u=[];for(let f=0;f<p.length;f++)u.push(pt(p[f]));u.sort().join("")===N.sort().join("")&&qe(t,l,i,e)}}function $(t,e,n){N=[];const o=je(t);let i=[],s="all",a=document,r=0,l=!1,d=!0,p="+",u=!1,f=!1;for(n===void 0&&typeof e=="function"&&(n=e),Object.prototype.toString.call(e)==="[object Object]"&&(e.scope&&(s=e.scope),e.element&&(a=e.element),e.keyup&&(l=e.keyup),e.keydown!==void 0&&(d=e.keydown),e.capture!==void 0&&(u=e.capture),typeof e.splitKey=="string"&&(p=e.splitKey),e.single===!0&&(f=!0)),typeof e=="string"&&(s=e),f&&We(t,s);r<o.length;r++)t=o[r].split(p),i=[],t.length>1&&(i=He(F,t)),t=t[t.length-1],t=t==="*"?"*":pt(t),t in _||(_[t]=[]),_[t].push({keyup:l,keydown:d,scope:s,mods:i,shortcut:o[r],method:n,key:o[r],splitKey:p,element:a});if(typeof a<"u"&&window){if(!q.has(a)){const A=function(){let b=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.event;return Ge(b,a)},g=function(){let b=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.event;Ge(b,a),Mo(b)};q.set(a,{keydownListener:A,keyupListenr:g,capture:u}),jt(a,"keydown",A,u),jt(a,"keyup",g,u)}if(!gt){const A=()=>{N=[]};gt={listener:A,capture:u},jt(window,"focus",A,u)}}}function ko(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"all";Object.keys(_).forEach(n=>{_[n].filter(i=>i.scope===e&&i.shortcut===t).forEach(i=>{i&&i.method&&i.method()})})}function Ft(t){const e=Object.values(_).flat();if(e.findIndex(o=>{let{element:i}=o;return i===t})<0){const{keydownListener:o,keyupListenr:i,capture:s}=q.get(t)||{};o&&i&&(ft(t,"keyup",i,s),ft(t,"keydown",o,s),q.delete(t))}if((e.length<=0||q.size<=0)&&(Object.keys(q).forEach(i=>{const{keydownListener:s,keyupListenr:a,capture:r}=q.get(i)||{};s&&a&&(ft(i,"keyup",a,r),ft(i,"keydown",s,r),q.delete(i))}),q.clear(),Object.keys(_).forEach(i=>delete _[i]),gt)){const{listener:i,capture:s}=gt;ft(window,"focus",i,s),gt=null}}const zt={getPressedKeyString:Lo,setScope:ze,getScope:mt,deleteScope:Bo,getPressedKeyCodes:Co,getAllKeyCodes:To,isPressed:Ro,filter:Oo,trigger:ko,unbind:We,keyMap:ht,modifier:F,modifierMap:Lt};for(const t in zt)Object.prototype.hasOwnProperty.call(zt,t)&&($[t]=zt[t]);if(typeof window<"u"){const t=window.hotkeys;$.noConflict=e=>(e&&window.hotkeys===$&&(window.hotkeys=t),$),window.hotkeys=$}async function Io(t,e,n=()=>!1){do{if(await t(),await n())break;const o=e;await new Promise(i=>setTimeout(i,Math.max(0,o)))}while(!await n())}const Qe=300,Je=["up","down","left","right"],Ze=Qt?"⌘+a":"ctrl+a",No=[...Je.map(t=>`shift+${t}`),Ze],tn=(t,e,n)=>{const{store:o,selection:i}=e;let s;const{annotatingEnabled:a,offsetReferenceSelector:r,selectionMode:l}=n,d=h=>s=h;let p;const u=h=>p=h;let f,A,g,b=a;const v=h=>{b=h,c.clear(),h||(f=void 0,A=void 0,g=void 0)},m=h=>{b&&A!==!1&&(f=et(h.target)?void 0:{annotation:Be(),selector:[],creator:s,created:new Date})},c=Bt(h=>{if(!b)return;const S=document.getSelection();if(!(S!=null&&S.anchorNode))return;if(et(S.anchorNode)){f=void 0;return}const k=h.timeStamp-((g==null?void 0:g.timeStamp)||h.timeStamp);if((g==null?void 0:g.type)==="pointerdown"&&(k<1e3&&!f||S.isCollapsed&&k<Qe)&&m(g||h),!f)return;if(S.isCollapsed){o.getAnnotation(f.annotation)&&(i.clear(),o.deleteAnnotation(f.annotation));return}const R=S.getRangeAt(0),U=ae(R,t);if(ne(U))return;const D=Zt(U.cloneRange());(D.length!==f.selector.length||D.some((G,tt)=>{var Wt;return G.toString()!==((Wt=f.selector[tt])==null?void 0:Wt.quote)}))&&(f={...f,selector:D.map(G=>ie(G,t,r)),updated:new Date},o.getAnnotation(f.annotation)?o.updateTarget(f,I.LOCAL):i.clear())},10),y=h=>{et(h.target)||(g=At(h),A=g.button===0)},C=async h=>{if(et(h.target)||!A)return;const S=()=>{const{x:R,y:U}=t.getBoundingClientRect(),D=h.target instanceof Node&&t.contains(h.target)&&o.getAt(h.clientX-R,h.clientY-U,l==="all",p);if(D){const{selected:Ot}=i,G=new Set(Ot.map(yt=>yt.id)),tt=Array.isArray(D)?D.map(yt=>yt.id):[D.id];(G.size!==tt.length||!tt.every(yt=>G.has(yt)))&&i.userSelect(tt,h)}else i.clear()};if(h.timeStamp-g.timeStamp<Qe){await x();const R=document.getSelection();if(R!=null&&R.isCollapsed){f=void 0,S();return}}f&&f.selector.length>0&&(w(),i.userSelect(f.annotation,At(h)))},x=async()=>{const h=document.getSelection();let S=!1,k=h==null?void 0:h.isCollapsed;const R=()=>k||S,U=1;return setTimeout(()=>S=!0,50),Io(()=>k=h==null?void 0:h.isCollapsed,U,R)},L=h=>{const S=document.getSelection();S!=null&&S.isCollapsed||((!f||f.selector.length===0)&&c(h),w(),i.userSelect(f.annotation,At(h)))},B=h=>{b&&h.key==="Shift"&&f&&(document.getSelection().isCollapsed||(w(),i.userSelect(f.annotation,rt(h))))},T=h=>{const S=()=>setTimeout(()=>{(f==null?void 0:f.selector.length)>0&&(i.clear(),o.addAnnotation({id:f.annotation,bodies:[],target:f}),i.userSelect(f.annotation,rt(h))),document.removeEventListener("selectionchange",S)},100);document.addEventListener("selectionchange",S),m(h)};$(No.join(","),{element:t,keydown:!0,keyup:!1},h=>{h.repeat||(g=rt(h))}),$(Ze,{keydown:!0,keyup:!1},h=>{g=rt(h),T(h)});const M=h=>{h.repeat||h.target!==t&&h.target!==document.body||(f=void 0,i.clear())};$(Je.join(","),{keydown:!0,keyup:!1},M);const w=()=>{const h=o.getAnnotation(f.annotation);if(!h){o.addAnnotation({id:f.annotation,bodies:[],target:f});return}const{target:{updated:S}}=h,{updated:k}=f;(!S||!k||S<k)&&o.updateTarget(f)};return document.addEventListener("pointerdown",y),document.addEventListener("pointerup",C),document.addEventListener("contextmenu",L),t.addEventListener("keyup",B),t.addEventListener("selectstart",m),document.addEventListener("selectionchange",c),{destroy:()=>{f=void 0,A=void 0,g=void 0,c.clear(),document.removeEventListener("pointerdown",y),document.removeEventListener("pointerup",C),document.removeEventListener("contextmenu",L),t.removeEventListener("keyup",B),t.removeEventListener("selectstart",m),document.removeEventListener("selectionchange",c),$.unbind()},setFilter:u,setUser:d,setAnnotatingEnabled:v}},en=(t,e)=>({...t,annotatingEnabled:t.annotatingEnabled??e.annotatingEnabled,user:t.user||e.user}),nn="SPANS",_o=(t,e={})=>{Gt(t),Jt(t);const n=en(e,{annotatingEnabled:!0,user:io()}),o=Xe(t,n),{selection:i,viewport:s}=o,a=o.store,r=Wn(a),l=Gn(o,r,n.adapter);let d=n.user;const p=n.renderer==="CSS_HIGHLIGHTS"?CSS.highlights?"CSS_HIGHLIGHTS":nn:n.renderer||nn,u=p==="SPANS"?Oe(t,o,s):p==="CSS_HIGHLIGHTS"?Le(t,o,s):p==="CANVAS"?he(t,o,s):void 0;if(!u)throw`Unknown renderer implementation: ${p}`;console.debug(`Using ${p} renderer`),n.style&&u.setStyle(n.style);const f=tn(t,o,n);f.setUser(d),f.setAnnotatingEnabled(n.annotatingEnabled);const A=Jn(o,r,n.adapter),g=()=>d,b=x=>{f.setAnnotatingEnabled(x===void 0?!0:x)},v=x=>{u.setFilter(x),f.setFilter(x)},m=x=>{d=x,f.setUser(x)},c=x=>{x&&(u.setPainter($e(x,n.presence)),x.on("selectionChange",()=>u.redraw()))},y=x=>{x?i.setSelected(x):i.clear()};return{...A,destroy:()=>{u.destroy(),f.destroy(),r.destroy()},element:t,getUser:g,setAnnotatingEnabled:b,setFilter:v,setStyle:u.setStyle.bind(u),redraw:u.redraw.bind(u),setUser:m,setSelected:y,setPresenceProvider:c,setVisible:u.setVisible.bind(u),on:l.on,off:l.off,scrollIntoView:de(t,a),state:o}};O.DEFAULT_SELECTED_STYLE=at,O.DEFAULT_STYLE=z,O.NOT_ANNOTATABLE_CLASS=Q,O.NOT_ANNOTATABLE_SELECTOR=J,O.Origin=I,O.UserSelectAction=ke,O.W3CTextFormat=co,O.cancelSingleClickEvents=Gt,O.cloneKeyboardEvent=rt,O.clonePointerEvent=At,O.createBody=Un,O.createCanvasRenderer=he,O.createHighlightsRenderer=Le,O.createPresencePainter=$e,O.createRenderer=Ce,O.createSelectionHandler=tn,O.createSpansRenderer=Oe,O.createTextAnnotator=_o,O.createTextAnnotatorState=Xe,O.fillDefaults=en,O.getQuoteContext=te,O.getRangeAnnotatableContents=bt,O.isMac=Qt,O.isNotAnnotatable=et,O.isRangeAnnotatable=qt,O.isRevived=j,O.isWhitespaceOrEmpty=ne,O.mergeClientRects=oe,O.paint=ue,O.parseW3CTextAnnotation=Ve,O.programmaticallyFocusable=Jt,O.rangeContains=re,O.rangeToSelector=ie,O.reviveAnnotation=wt,O.reviveSelector=Rt,O.reviveTarget=st,O.scrollIntoView=de,O.serializeW3CTextAnnotation=Ye,O.splitAnnotatableRanges=Zt,O.toDomRectList=an,O.toParentBounds=ce,O.toViewportBounds=cn,O.trimRangeToContainer=ae,O.whitespaceOrEmptyRegex=ee,Object.defineProperty(O,Symbol.toStringTag,{value:"Module"})});
1433
3
  //# sourceMappingURL=text-annotator.umd.js.map