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

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,2468 +1,1430 @@
1
- const ue = "not-annotatable", et = `.${ue}`, st = (t) => {
2
- var n;
3
- return !!(t instanceof HTMLElement ? t.closest(et) : (n = t.parentElement) == null ? void 0 : n.closest(et));
4
- }, Re = (t) => {
5
- const e = t.commonAncestorContainer;
6
- return !st(e);
7
- }, Me = (t) => t.addEventListener("click", (e) => {
8
- // Allow clicks within not-annotatable elements
9
- !e.target.closest(et) && !e.target.closest("a") && e.preventDefault();
10
- }), ke = /mac/i.test(navigator.userAgentData ? navigator.userAgentData.platform : navigator.platform), Ie = (t) => {
11
- !t.hasAttribute("tabindex") && t.tabIndex < 0 && t.setAttribute("tabindex", "-1"), t.classList.add("no-focus-outline");
12
- }, Ne = function* (t) {
13
- const e = document.createNodeIterator(
14
- t.commonAncestorContainer,
1
+ import debounce from "debounce";
2
+ import { colord } from "colord";
3
+ import { dequal } from "dequal/lite";
4
+ import { v4 } from "uuid";
5
+ import { serializeW3CBodies, parseW3CBodies, parseW3CUser, createStore, createSelectionState, createHoverState, createViewportState, Origin, createAnonymousGuest, createUndoStack, createLifecycleObserver, createBaseAnnotator } from "@annotorious/core";
6
+ import { Origin as Origin2, UserSelectAction, createBody } from "@annotorious/core";
7
+ import RBush from "rbush";
8
+ import { createNanoEvents } from "nanoevents";
9
+ import hotkeys from "hotkeys-js";
10
+ import { poll } from "poll";
11
+ const NOT_ANNOTATABLE_CLASS = "not-annotatable";
12
+ const NOT_ANNOTATABLE_SELECTOR = `.${NOT_ANNOTATABLE_CLASS}`;
13
+ const isNotAnnotatable = (node) => {
14
+ var _a;
15
+ const closestNotAnnotatable = node instanceof HTMLElement ? node.closest(NOT_ANNOTATABLE_SELECTOR) : (_a = node.parentElement) == null ? void 0 : _a.closest(NOT_ANNOTATABLE_SELECTOR);
16
+ return Boolean(closestNotAnnotatable);
17
+ };
18
+ const isRangeAnnotatable = (range) => {
19
+ const ancestor = range.commonAncestorContainer;
20
+ return !isNotAnnotatable(ancestor);
21
+ };
22
+ const cancelSingleClickEvents = (container) => container.addEventListener("click", (event) => {
23
+ const targetElement = event.target;
24
+ const shouldPrevent = (
25
+ // Allow clicks within not-annotatable elements
26
+ !targetElement.closest(NOT_ANNOTATABLE_SELECTOR) && !event.target.closest("a")
27
+ );
28
+ if (shouldPrevent)
29
+ event.preventDefault();
30
+ });
31
+ const isMac = /mac/i.test(navigator.userAgentData ? navigator.userAgentData.platform : navigator.platform);
32
+ const programmaticallyFocusable = (container) => {
33
+ if (!container.hasAttribute("tabindex") && container.tabIndex < 0) {
34
+ container.setAttribute("tabindex", "-1");
35
+ }
36
+ container.classList.add("no-focus-outline");
37
+ };
38
+ const iterateNotAnnotatableElements = function* (range) {
39
+ const notAnnotatableIterator = document.createNodeIterator(
40
+ range.commonAncestorContainer,
15
41
  NodeFilter.SHOW_ELEMENT,
16
- (o) => o instanceof HTMLElement && o.classList.contains(ue) && !o.parentElement.closest(et) && t.intersectsNode(o) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP
42
+ (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
17
43
  );
18
- let n;
19
- for (; n = e.nextNode(); )
20
- n instanceof HTMLElement && (yield n);
21
- }, _e = (t) => {
22
- if (!Re(t)) return [];
23
- const e = [];
24
- let n = null;
25
- for (const o of Ne(t)) {
26
- let i;
27
- n ? (i = document.createRange(), i.setStartAfter(n), i.setEndBefore(o)) : (i = t.cloneRange(), i.setEndBefore(o)), i.collapsed || e.push(i), n = o;
44
+ let notAnnotatableNode;
45
+ while (notAnnotatableNode = notAnnotatableIterator.nextNode()) {
46
+ if (notAnnotatableNode instanceof HTMLElement) {
47
+ yield notAnnotatableNode;
48
+ }
28
49
  }
29
- if (n) {
30
- const o = t.cloneRange();
31
- o.setStartAfter(n), o.collapsed || e.push(o);
50
+ };
51
+ const splitAnnotatableRanges = (range) => {
52
+ if (!isRangeAnnotatable(range)) return [];
53
+ const annotatableRanges = [];
54
+ let prevNotAnnotatable = null;
55
+ for (const notAnnotatable of iterateNotAnnotatableElements(range)) {
56
+ let subRange;
57
+ if (!prevNotAnnotatable) {
58
+ subRange = range.cloneRange();
59
+ subRange.setEndBefore(notAnnotatable);
60
+ } else {
61
+ subRange = document.createRange();
62
+ subRange.setStartAfter(prevNotAnnotatable);
63
+ subRange.setEndBefore(notAnnotatable);
64
+ }
65
+ if (!subRange.collapsed)
66
+ annotatableRanges.push(subRange);
67
+ prevNotAnnotatable = notAnnotatable;
32
68
  }
33
- return e.length > 0 ? e : [t];
34
- }, Kt = (t) => {
35
- const e = t.cloneContents();
36
- return e.querySelectorAll(et).forEach((n) => n.remove()), e;
37
- }, Ue = (t, e, n = 10, o) => {
38
- const i = o ? t.startContainer.parentElement.closest(o) : e, s = document.createRange();
39
- s.setStart(i, 0), s.setEnd(t.startContainer, t.startOffset);
40
- const a = Kt(s).textContent, r = document.createRange();
41
- r.setStart(t.endContainer, t.endOffset), i === document.body ? r.setEnd(i, i.childNodes.length) : r.setEndAfter(i);
42
- const l = Kt(r).textContent;
69
+ if (prevNotAnnotatable) {
70
+ const lastRange = range.cloneRange();
71
+ lastRange.setStartAfter(prevNotAnnotatable);
72
+ if (!lastRange.collapsed) {
73
+ annotatableRanges.push(lastRange);
74
+ }
75
+ }
76
+ return annotatableRanges.length > 0 ? annotatableRanges : [range];
77
+ };
78
+ const getRangeAnnotatableContents = (range) => {
79
+ const contents = range.cloneContents();
80
+ contents.querySelectorAll(NOT_ANNOTATABLE_SELECTOR).forEach((el) => el.remove());
81
+ return contents;
82
+ };
83
+ const getQuoteContext = (range, container, length = 10, offsetReferenceSelector) => {
84
+ const offsetReference = offsetReferenceSelector ? range.startContainer.parentElement.closest(offsetReferenceSelector) : container;
85
+ const rangeBefore = document.createRange();
86
+ rangeBefore.setStart(offsetReference, 0);
87
+ rangeBefore.setEnd(range.startContainer, range.startOffset);
88
+ const before = getRangeAnnotatableContents(rangeBefore).textContent;
89
+ const rangeAfter = document.createRange();
90
+ rangeAfter.setStart(range.endContainer, range.endOffset);
91
+ if (offsetReference === document.body)
92
+ rangeAfter.setEnd(offsetReference, offsetReference.childNodes.length);
93
+ else
94
+ rangeAfter.setEndAfter(offsetReference);
95
+ const after = getRangeAnnotatableContents(rangeAfter).textContent;
43
96
  return {
44
- prefix: a.substring(a.length - n),
45
- suffix: l.substring(0, n)
46
- };
47
- }, F = (t) => t.every((e) => e.range instanceof Range && !e.range.collapsed), De = /^\s*$/, Ve = (t) => De.test(t.toString()), Ye = (t, e) => {
48
- const n = (s) => Math.round(s * 10) / 10, o = {
49
- top: n(t.top),
50
- bottom: n(t.bottom),
51
- left: n(t.left),
52
- right: n(t.right)
53
- }, i = {
54
- top: n(e.top),
55
- bottom: n(e.bottom),
56
- left: n(e.left),
57
- right: n(e.right)
58
- };
59
- if (Math.abs(o.top - i.top) < 0.5 && Math.abs(o.bottom - i.bottom) < 0.5) {
60
- if (Math.abs(o.left - i.right) < 0.5 || Math.abs(o.right - i.left) < 0.5)
97
+ prefix: before.substring(before.length - length),
98
+ suffix: after.substring(0, length)
99
+ };
100
+ };
101
+ const isRevived = (selector) => selector.every((s) => s.range instanceof Range && !s.range.collapsed);
102
+ const whitespaceOrEmptyRegex = /^\s*$/;
103
+ const isWhitespaceOrEmpty = (range) => whitespaceOrEmptyRegex.test(range.toString());
104
+ const getRelation = (rectA, rectB) => {
105
+ const round = (num) => Math.round(num * 10) / 10;
106
+ const a = {
107
+ top: round(rectA.top),
108
+ bottom: round(rectA.bottom),
109
+ left: round(rectA.left),
110
+ right: round(rectA.right)
111
+ };
112
+ const b = {
113
+ top: round(rectB.top),
114
+ bottom: round(rectB.bottom),
115
+ left: round(rectB.left),
116
+ right: round(rectB.right)
117
+ };
118
+ if (Math.abs(a.top - b.top) < 0.5 && Math.abs(a.bottom - b.bottom) < 0.5) {
119
+ if (Math.abs(a.left - b.right) < 0.5 || Math.abs(a.right - b.left) < 0.5)
61
120
  return "inline-adjacent";
62
- if (o.left >= i.left && o.right <= i.right)
121
+ if (a.left >= b.left && a.right <= b.right)
63
122
  return "inline-is-contained";
64
- if (o.left <= i.left && o.right >= i.right)
123
+ if (a.left <= b.left && a.right >= b.right)
65
124
  return "inline-contains";
66
- } else if (o.top <= i.top && o.bottom >= i.bottom) {
67
- if (o.left <= i.left && o.right >= i.right)
68
- return "block-contains";
69
- } else if (o.top >= i.top && o.bottom <= i.bottom && o.left >= i.left && o.right <= i.right)
70
- return "block-is-contained";
71
- }, Ke = (t, e) => {
72
- 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);
73
- return new DOMRect(n, i, o - n, s - i);
74
- }, Pe = (t) => t.reduce((e, n) => {
75
- if (n.width === 0 || n.height === 0)
76
- return e;
77
- let o = [...e], i = !1;
78
- for (const s of e) {
79
- const a = Ye(n, s);
80
- if (a === "inline-adjacent") {
81
- o = o.map((r) => r === s ? Ke(n, s) : r), i = !0;
125
+ } else {
126
+ if (a.top <= b.top && a.bottom >= b.bottom) {
127
+ if (a.left <= b.left && a.right >= b.right) {
128
+ return "block-contains";
129
+ }
130
+ } else if (a.top >= b.top && a.bottom <= b.bottom) {
131
+ if (a.left >= b.left && a.right <= b.right) {
132
+ return "block-is-contained";
133
+ }
134
+ }
135
+ }
136
+ };
137
+ const union = (a, b) => {
138
+ const left = Math.min(a.left, b.left);
139
+ const right = Math.max(a.right, b.right);
140
+ const top = Math.min(a.top, b.top);
141
+ const bottom = Math.max(a.bottom, b.bottom);
142
+ return new DOMRect(left, top, right - left, bottom - top);
143
+ };
144
+ const mergeClientRects = (rects) => rects.reduce((merged, rectA) => {
145
+ if (rectA.width === 0 || rectA.height === 0)
146
+ return merged;
147
+ let next = [...merged];
148
+ let wasMerged = false;
149
+ for (const rectB of merged) {
150
+ const relation = getRelation(rectA, rectB);
151
+ if (relation === "inline-adjacent") {
152
+ next = next.map((r) => r === rectB ? union(rectA, rectB) : r);
153
+ wasMerged = true;
82
154
  break;
83
- } else if (a === "inline-contains") {
84
- o = o.map((r) => r === s ? n : r), i = !0;
155
+ } else if (relation === "inline-contains") {
156
+ next = next.map((r) => r === rectB ? rectA : r);
157
+ wasMerged = true;
85
158
  break;
86
- } else if (a === "inline-is-contained") {
87
- i = !0;
159
+ } else if (relation === "inline-is-contained") {
160
+ wasMerged = true;
88
161
  break;
89
- } else if (a === "block-contains" || a === "block-is-contained") {
90
- n.width < s.width && (o = o.map((r) => r === s ? n : r)), i = !0;
162
+ } else if (relation === "block-contains" || relation === "block-is-contained") {
163
+ if (rectA.width < rectB.width) {
164
+ next = next.map((r) => r === rectB ? rectA : r);
165
+ }
166
+ wasMerged = true;
91
167
  break;
92
168
  }
93
169
  }
94
- return i ? o : [...o, n];
95
- }, []), Mo = (t) => ({
96
- length: t.length,
97
- item: (e) => t[e],
170
+ return wasMerged ? next : [...next, rectA];
171
+ }, []);
172
+ const toDomRectList = (rects) => ({
173
+ length: rects.length,
174
+ item: (index) => rects[index],
98
175
  [Symbol.iterator]: function* () {
99
- for (let e = 0; e < this.length; e++)
100
- yield this.item(e);
176
+ for (let i = 0; i < this.length; i++)
177
+ yield this.item(i);
101
178
  }
102
- }), Xe = (t, e, n) => {
103
- const o = document.createRange(), i = n ? t.startContainer.parentElement.closest(n) : e;
104
- o.setStart(i, 0), o.setEnd(t.startContainer, t.startOffset);
105
- const s = Kt(o).textContent, a = t.toString(), r = s.length || 0, l = r + a.length;
106
- return n ? { quote: a, start: r, end: l, range: t, offsetReference: i } : { quote: a, start: r, end: l, range: t };
107
- }, fe = (t, e) => {
108
- var g, u;
109
- const { start: n, end: o } = t, i = t.offsetReference || e, s = document.createNodeIterator(
110
- e,
179
+ });
180
+ const rangeToSelector = (range, container, offsetReferenceSelector) => {
181
+ const rangeBefore = document.createRange();
182
+ const offsetReference = offsetReferenceSelector ? range.startContainer.parentElement.closest(offsetReferenceSelector) : container;
183
+ rangeBefore.setStart(offsetReference, 0);
184
+ rangeBefore.setEnd(range.startContainer, range.startOffset);
185
+ const before = getRangeAnnotatableContents(rangeBefore).textContent;
186
+ const quote = range.toString();
187
+ const start = before.length || 0;
188
+ const end = start + quote.length;
189
+ return offsetReferenceSelector ? { quote, start, end, range, offsetReference } : { quote, start, end, range };
190
+ };
191
+ const reviveSelector = (selector, container) => {
192
+ var _a, _b;
193
+ const { start, end } = selector;
194
+ const offsetReference = selector.offsetReference || container;
195
+ const iterator = document.createNodeIterator(
196
+ container,
111
197
  NodeFilter.SHOW_TEXT,
112
- (h) => {
113
- var A;
114
- return (A = h.parentElement) != null && A.closest(et) ? NodeFilter.FILTER_SKIP : NodeFilter.FILTER_ACCEPT;
198
+ (node) => {
199
+ var _a2;
200
+ return ((_a2 = node.parentElement) == null ? void 0 : _a2.closest(NOT_ANNOTATABLE_SELECTOR)) ? NodeFilter.FILTER_SKIP : NodeFilter.FILTER_ACCEPT;
115
201
  }
116
202
  );
117
- let a = 0;
118
- const r = document.createRange();
119
- let l = s.nextNode();
120
- l === null && console.error("Could not revive annotation target. Content missing.");
121
- let d = !i;
122
- for (; l !== null; ) {
123
- if (d || (d = i == null ? void 0 : i.contains(l)), d) {
124
- const h = ((g = l.textContent) == null ? void 0 : g.length) || 0;
125
- if (a + h > n) {
126
- r.setStart(l, n - a);
203
+ let runningOffset = 0;
204
+ const range = document.createRange();
205
+ let n = iterator.nextNode();
206
+ if (n === null) console.error("Could not revive annotation target. Content missing.");
207
+ let startCounting = !offsetReference;
208
+ while (n !== null) {
209
+ startCounting || (startCounting = offsetReference == null ? void 0 : offsetReference.contains(n));
210
+ if (startCounting) {
211
+ const len = ((_a = n.textContent) == null ? void 0 : _a.length) || 0;
212
+ if (runningOffset + len > start) {
213
+ range.setStart(n, start - runningOffset);
127
214
  break;
128
215
  }
129
- a += h;
216
+ runningOffset += len;
130
217
  }
131
- l = s.nextNode();
218
+ n = iterator.nextNode();
132
219
  }
133
- for (; l !== null; ) {
134
- const h = ((u = l.textContent) == null ? void 0 : u.length) || 0;
135
- if (a + h >= o) {
136
- r.setEnd(l, o - a);
220
+ while (n !== null) {
221
+ const len = ((_b = n.textContent) == null ? void 0 : _b.length) || 0;
222
+ if (runningOffset + len >= end) {
223
+ range.setEnd(n, end - runningOffset);
137
224
  break;
138
225
  }
139
- a += h, l = s.nextNode();
226
+ runningOffset += len;
227
+ n = iterator.nextNode();
140
228
  }
141
229
  return {
142
- ...t,
143
- range: r
144
- };
145
- }, vt = (t, e) => F(t.selector) ? t : {
146
- ...t,
147
- selector: t.selector.map((n) => n.range instanceof Range && !n.range.collapsed ? n : fe(n, e))
148
- }, Ct = (t, e) => F(t.target.selector) ? t : { ...t, target: vt(t.target, e) }, he = (t, e) => {
149
- if (t.isEqualNode(e))
150
- return !0;
151
- for (let n of t.childNodes)
152
- if (he(n, e))
153
- return !0;
154
- return !1;
155
- }, $e = (t, e) => {
156
- const n = t.cloneContents();
157
- return he(n, e);
158
- }, He = (t, e) => {
159
- const n = t.cloneRange(), o = e.contains(n.startContainer), i = e.contains(n.endContainer);
160
- return !o && !i && !$e(n, e) ? (n.collapse(), n) : (o || n.setStart(e, 0), i || n.setEnd(e, e.childNodes.length), n);
161
- }, Lt = (t) => ({
162
- ...t,
163
- type: t.type,
164
- x: t.x,
165
- y: t.y,
166
- clientX: t.clientX,
167
- clientY: t.clientY,
168
- offsetX: t.offsetX,
169
- offsetY: t.offsetY,
170
- screenX: t.screenX,
171
- screenY: t.screenY,
172
- isPrimary: t.isPrimary,
173
- altKey: t.altKey,
174
- ctrlKey: t.ctrlKey,
175
- metaKey: t.metaKey,
176
- shiftKey: t.shiftKey,
177
- button: t.button,
178
- buttons: t.buttons,
179
- currentTarget: t.currentTarget,
180
- target: t.target,
181
- defaultPrevented: t.defaultPrevented,
182
- detail: t.detail,
183
- eventPhase: t.eventPhase,
184
- pointerId: t.pointerId,
185
- pointerType: t.pointerType,
186
- timeStamp: t.timeStamp
187
- }), pt = (t) => ({
188
- ...t,
189
- type: t.type,
190
- key: t.key,
191
- code: t.code,
192
- location: t.location,
193
- repeat: t.repeat,
194
- altKey: t.altKey,
195
- ctrlKey: t.ctrlKey,
196
- metaKey: t.metaKey,
197
- shiftKey: t.shiftKey,
198
- currentTarget: t.currentTarget,
199
- target: t.target,
200
- defaultPrevented: t.defaultPrevented,
201
- detail: t.detail,
202
- timeStamp: t.timeStamp
203
- }), je = (t, e) => {
204
- const { left: n, top: o, right: i, bottom: s } = t;
205
- return new DOMRect(n - e.left, o - e.top, i - n, s - o);
206
- }, ko = (t, e) => {
207
- const { left: n, top: o, right: i, bottom: s } = t;
208
- return new DOMRect(n + e.left, o + e.top, i - n, s - o);
209
- }, pe = (t) => {
210
- if (t === null)
211
- return document.scrollingElement;
212
- const { overflowY: e } = window.getComputedStyle(t);
213
- return e !== "visible" && e !== "hidden" && t.scrollHeight > t.clientHeight ? t : pe(t.parentElement);
214
- }, ze = (t, e) => (n) => {
215
- const o = typeof n == "string" ? n : n.id, i = (a) => {
216
- const r = s.getBoundingClientRect(), l = s.clientHeight, d = s.clientWidth, g = a.selector[0].range.getBoundingClientRect(), { width: u, height: h } = e.getAnnotationBounds(o), A = g.top - r.top, p = g.left - r.left, b = s.parentElement ? s.scrollTop : 0, x = s.parentElement ? s.scrollLeft : 0, m = A + b - (l - h) / 2, c = p + x - (d - u) / 2;
217
- s.scroll({ top: m, left: c, behavior: "smooth" });
218
- }, s = pe(t);
219
- if (s) {
220
- const a = e.getAnnotation(o), { range: r } = a.target.selector[0];
221
- if (r && !r.collapsed)
222
- return i(a.target), !0;
223
- {
224
- const l = vt(a.target, t), { range: d } = l.selector[0];
225
- if (d && !d.collapsed)
226
- return i(l), !0;
230
+ ...selector,
231
+ range
232
+ };
233
+ };
234
+ const reviveTarget = (target, container) => isRevived(target.selector) ? target : {
235
+ ...target,
236
+ selector: target.selector.map((s) => s.range instanceof Range && !s.range.collapsed ? s : reviveSelector(s, container))
237
+ };
238
+ const reviveAnnotation = (annotation, container) => isRevived(annotation.target.selector) ? annotation : { ...annotation, target: reviveTarget(annotation.target, container) };
239
+ const clonedNodeContains = (clonedNode, targetNode) => {
240
+ if (clonedNode.isEqualNode(targetNode)) {
241
+ return true;
242
+ }
243
+ for (let child of clonedNode.childNodes) {
244
+ if (clonedNodeContains(child, targetNode)) {
245
+ return true;
227
246
  }
228
247
  }
229
- return !1;
230
- }, q = {
231
- fill: "rgb(0, 128, 255)",
232
- fillOpacity: 0.18
233
- }, Et = {
234
- fill: "rgb(0, 128, 255)",
235
- fillOpacity: 0.45
236
- }, Fe = (t, e, n, o, i) => {
237
- var a, r;
238
- const s = n ? typeof n == "function" ? n(t.annotation, t.state, i) || ((a = t.state) != null && a.selected ? Et : q) : n : (r = t.state) != null && r.selected ? Et : q;
239
- return o && o.paint(t, e) || s;
248
+ return false;
240
249
  };
241
- function We(t) {
242
- return t && t.__esModule && Object.prototype.hasOwnProperty.call(t, "default") ? t.default : t;
243
- }
244
- var gt = { exports: {} }, zt;
245
- function qe() {
246
- if (zt) return gt.exports;
247
- zt = 1;
248
- function t(e, n = 100, o = {}) {
249
- if (typeof e != "function")
250
- throw new TypeError(`Expected the first parameter to be a function, got \`${typeof e}\`.`);
251
- if (n < 0)
252
- throw new RangeError("`wait` must not be negative.");
253
- const { immediate: i } = typeof o == "boolean" ? { immediate: o } : o;
254
- let s, a, r, l, d;
255
- function g() {
256
- const A = s, p = a;
257
- return s = void 0, a = void 0, d = e.apply(A, p), d;
258
- }
259
- function u() {
260
- const A = Date.now() - l;
261
- A < n && A >= 0 ? r = setTimeout(u, n - A) : (r = void 0, i || (d = g()));
250
+ const rangeContains = (range, node) => {
251
+ const rangeContents = range.cloneContents();
252
+ return clonedNodeContains(rangeContents, node);
253
+ };
254
+ const trimRangeToContainer = (range, container) => {
255
+ const trimmedRange = range.cloneRange();
256
+ const containsRangeStart = container.contains(trimmedRange.startContainer);
257
+ const containsRangeEnd = container.contains(trimmedRange.endContainer);
258
+ if (!containsRangeStart && !containsRangeEnd) {
259
+ const containedWithinRange = rangeContains(trimmedRange, container);
260
+ if (!containedWithinRange) {
261
+ trimmedRange.collapse();
262
+ return trimmedRange;
262
263
  }
263
- const h = function(...A) {
264
- if (s && this !== s && Object.getPrototypeOf(this) === Object.getPrototypeOf(s))
265
- throw new Error("Debounced method called with different contexts of the same prototype.");
266
- s = this, a = A, l = Date.now();
267
- const p = i && !r;
268
- return r || (r = setTimeout(u, n)), p && (d = g()), d;
269
- };
270
- return Object.defineProperty(h, "isPending", {
271
- get() {
272
- return r !== void 0;
273
- }
274
- }), h.clear = () => {
275
- r && (clearTimeout(r), r = void 0);
276
- }, h.flush = () => {
277
- r && h.trigger();
278
- }, h.trigger = () => {
279
- d = g(), h.clear();
280
- }, h;
281
264
  }
282
- return gt.exports.debounce = t, gt.exports = t, gt.exports;
283
- }
284
- var Ge = /* @__PURE__ */ qe();
285
- const Xt = /* @__PURE__ */ We(Ge), Qe = (t) => {
286
- const { top: e, left: n } = t.getBoundingClientRect(), { innerWidth: o, innerHeight: i } = window, s = -n, a = -e, r = o - n, l = i - e;
287
- return { top: e, left: n, minX: s, minY: a, maxX: r, maxY: l };
288
- }, Je = (t) => {
289
- let e = /* @__PURE__ */ new Set();
290
- return (o) => {
291
- const i = o.map((s) => s.id);
292
- (e.size !== i.length || i.some((s) => !e.has(s))) && t.set(i), e = new Set(i);
293
- };
294
- }, $t = (t, e, n, o) => {
295
- const { store: i, selection: s, hover: a } = e;
296
- let r, l, d;
297
- const g = Je(n), u = (T) => {
298
- const { x: R, y: w } = t.getBoundingClientRect(), v = i.getAt(T.clientX - R, T.clientY - w, !1, l);
299
- v ? a.current !== v.id && (t.classList.add("hovered"), a.set(v.id)) : a.current && (t.classList.remove("hovered"), a.set(null));
300
- };
301
- t.addEventListener("pointermove", u);
302
- const h = (T = !1) => {
303
- d && d.clear();
304
- const R = Qe(t), { minX: w, minY: v, maxX: f, maxY: E } = R, M = l ? i.getIntersecting(w, v, f, E).filter(({ annotation: _ }) => l(_)) : i.getIntersecting(w, v, f, E), O = s.selected.map(({ id: _ }) => _), U = M.map(({ annotation: _, rects: ht }) => {
305
- const W = O.includes(_.id), G = _.id === a.current;
306
- return { annotation: _, rects: ht, state: { selected: W, hover: G } };
307
- });
308
- o.redraw(U, R, r, d, T), setTimeout(() => g(M.map(({ annotation: _ }) => _)), 1);
309
- }, A = (T) => {
310
- d = T, h();
311
- }, p = (T) => {
312
- r = T, h();
313
- }, b = (T) => {
314
- l = T, h(!1);
315
- }, x = () => h();
316
- i.observe(x);
317
- const m = s.subscribe(() => h()), c = () => h(!0);
318
- document.addEventListener("scroll", c, { capture: !0, passive: !0 });
319
- const y = Xt(() => {
320
- i.recalculatePositions(), d == null || d.reset(), h();
321
- }, 10);
322
- window.addEventListener("resize", y);
323
- const C = new ResizeObserver(y);
324
- C.observe(t);
325
- const S = { attributes: !0, childList: !0, subtree: !0 }, L = new MutationObserver((T) => {
326
- T.every((w) => w.target === t || t.contains(w.target)) || h(!0);
327
- });
328
- return L.observe(document.body, S), {
329
- destroy: () => {
330
- t.removeEventListener("pointermove", u), o.destroy(), i.unobserve(x), m(), document.removeEventListener("scroll", c), y.clear(), window.removeEventListener("resize", y), C.disconnect(), L.disconnect();
331
- },
332
- redraw: h,
333
- setStyle: p,
334
- setFilter: b,
335
- setPainter: A,
336
- setVisible: o.setVisible
337
- };
338
- }, Ze = () => {
339
- const t = document.createElement("canvas");
340
- return t.width = window.innerWidth, t.height = window.innerHeight, t.className = "r6o-canvas-highlight-layer bg", t;
341
- }, tn = (t, e) => {
342
- t.width = window.innerWidth, t.height = window.innerHeight;
343
- }, en = (t) => {
344
- t.classList.add("r6o-annotatable");
345
- const e = Ze(), n = e.getContext("2d");
346
- document.body.appendChild(e);
347
- const o = (r, l, d, g) => requestAnimationFrame(() => {
348
- const { width: u, height: h } = e;
349
- n.clearRect(-0.5, -0.5, u + 1, h + 1), g && g.clear();
350
- const { top: A, left: p } = l;
351
- [...r].sort((x, m) => {
352
- const { annotation: { target: { created: c } } } = x, { annotation: { target: { created: y } } } = m;
353
- return c.getTime() - y.getTime();
354
- }).forEach((x) => {
355
- var C;
356
- const m = d ? typeof d == "function" ? d(x.annotation, x.state) : d : (C = x.state) != null && C.selected ? Et : q, c = g && g.paint(x, l) || m, y = x.rects.map(({ x: S, y: L, width: B, height: T }) => ({
357
- x: S + p,
358
- y: L + A,
359
- width: B,
360
- height: T
361
- }));
362
- if (n.fillStyle = c.fill, n.globalAlpha = c.fillOpacity || 1, y.forEach(
363
- ({ x: S, y: L, width: B, height: T }) => n.fillRect(S, L, B, T)
364
- ), c.underlineColor) {
365
- n.globalAlpha = 1, n.strokeStyle = c.underlineColor, n.lineWidth = c.underlineThickness ?? 1;
366
- const S = c.underlineOffset ?? 0;
367
- y.forEach(({ x: L, y: B, width: T, height: R }) => {
368
- n.beginPath(), n.moveTo(L, B + R + S), n.lineTo(L + T, B + R + S), n.stroke();
369
- });
370
- }
371
- });
372
- }), i = Xt(() => tn(e), 10);
373
- return window.addEventListener("resize", i), {
374
- destroy: () => {
375
- e.remove(), i.clear(), window.removeEventListener("resize", i);
376
- },
377
- setVisible: (r) => {
378
- console.log("setVisible not implemented on Canvas renderer");
379
- },
380
- redraw: o
381
- };
382
- }, nn = (t, e, n) => $t(t, e, n, en(t));
383
- var on = { grad: 0.9, turn: 360, rad: 360 / (2 * Math.PI) }, j = function(t) {
384
- return typeof t == "string" ? t.length > 0 : typeof t == "number";
385
- }, D = function(t, e, n) {
386
- return e === void 0 && (e = 0), n === void 0 && (n = Math.pow(10, e)), Math.round(n * t) / n + 0;
387
- }, P = function(t, e, n) {
388
- return e === void 0 && (e = 0), n === void 0 && (n = 1), t > n ? n : t > e ? t : e;
389
- }, ge = function(t) {
390
- return (t = isFinite(t) ? t % 360 : 0) > 0 ? t : t + 360;
391
- }, Ft = function(t) {
392
- return { r: P(t.r, 0, 255), g: P(t.g, 0, 255), b: P(t.b, 0, 255), a: P(t.a) };
393
- }, Tt = function(t) {
394
- return { r: D(t.r), g: D(t.g), b: D(t.b), a: D(t.a, 3) };
395
- }, sn = /^#([0-9a-f]{3,8})$/i, mt = function(t) {
396
- var e = t.toString(16);
397
- return e.length < 2 ? "0" + e : e;
398
- }, me = function(t) {
399
- 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;
400
- return { h: 60 * (r < 0 ? r + 6 : r), s: s ? a / s * 100 : 0, v: s / 255 * 100, a: i };
401
- }, ye = function(t) {
402
- var e = t.h, n = t.s, o = t.v, i = t.a;
403
- e = e / 360 * 6, n /= 100, o /= 100;
404
- 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;
405
- 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 };
406
- }, Wt = function(t) {
407
- return { h: ge(t.h), s: P(t.s, 0, 100), l: P(t.l, 0, 100), a: P(t.a) };
408
- }, qt = function(t) {
409
- return { h: D(t.h), s: D(t.s), l: D(t.l), a: D(t.a, 3) };
410
- }, Gt = function(t) {
411
- 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 }));
412
- var e, n, o;
413
- }, ct = function(t) {
414
- 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 };
415
- var e, n, o, i;
416
- }, rn = /^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, cn = /^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i, ln = /^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i, Qt = { string: [[function(t) {
417
- var e = sn.exec(t);
418
- 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 ? D(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 ? D(parseInt(t.substr(6, 2), 16) / 255, 2) : 1 } : null : null;
419
- }, "hex"], [function(t) {
420
- var e = cn.exec(t) || ln.exec(t);
421
- return e ? e[2] !== e[4] || e[4] !== e[6] ? null : Ft({ 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;
422
- }, "rgb"], [function(t) {
423
- var e = rn.exec(t) || an.exec(t);
424
- if (!e) return null;
425
- var n, o, i = Wt({ h: (n = e[1], o = e[2], o === void 0 && (o = "deg"), Number(n) * (on[o] || 1)), s: Number(e[3]), l: Number(e[4]), a: e[5] === void 0 ? 1 : Number(e[5]) / (e[6] ? 100 : 1) });
426
- return Gt(i);
427
- }, "hsl"]], object: [[function(t) {
428
- var e = t.r, n = t.g, o = t.b, i = t.a, s = i === void 0 ? 1 : i;
429
- return j(e) && j(n) && j(o) ? Ft({ r: Number(e), g: Number(n), b: Number(o), a: Number(s) }) : null;
430
- }, "rgb"], [function(t) {
431
- var e = t.h, n = t.s, o = t.l, i = t.a, s = i === void 0 ? 1 : i;
432
- if (!j(e) || !j(n) || !j(o)) return null;
433
- var a = Wt({ h: Number(e), s: Number(n), l: Number(o), a: Number(s) });
434
- return Gt(a);
435
- }, "hsl"], [function(t) {
436
- var e = t.h, n = t.s, o = t.v, i = t.a, s = i === void 0 ? 1 : i;
437
- if (!j(e) || !j(n) || !j(o)) return null;
438
- var a = function(r) {
439
- return { h: ge(r.h), s: P(r.s, 0, 100), v: P(r.v, 0, 100), a: P(r.a) };
440
- }({ h: Number(e), s: Number(n), v: Number(o), a: Number(s) });
441
- return ye(a);
442
- }, "hsv"]] }, Jt = function(t, e) {
443
- for (var n = 0; n < e.length; n++) {
444
- var o = e[n][0](t);
445
- if (o) return [o, e[n][1]];
265
+ if (!containsRangeStart) {
266
+ trimmedRange.setStart(container, 0);
446
267
  }
447
- return [null, void 0];
448
- }, dn = function(t) {
449
- return typeof t == "string" ? Jt(t.trim(), Qt.string) : typeof t == "object" && t !== null ? Jt(t, Qt.object) : [null, void 0];
450
- }, Ot = function(t, e) {
451
- var n = ct(t);
452
- return { h: n.h, s: P(n.s + 100 * e, 0, 100), l: n.l, a: n.a };
453
- }, Bt = function(t) {
454
- return (299 * t.r + 587 * t.g + 114 * t.b) / 1e3 / 255;
455
- }, Zt = function(t, e) {
456
- var n = ct(t);
457
- return { h: n.h, s: n.s, l: P(n.l + 100 * e, 0, 100), a: n.a };
458
- }, te = function() {
459
- function t(e) {
460
- this.parsed = dn(e)[0], this.rgba = this.parsed || { r: 0, g: 0, b: 0, a: 1 };
268
+ if (!containsRangeEnd) {
269
+ trimmedRange.setEnd(container, container.childNodes.length);
461
270
  }
462
- return t.prototype.isValid = function() {
463
- return this.parsed !== null;
464
- }, t.prototype.brightness = function() {
465
- return D(Bt(this.rgba), 2);
466
- }, t.prototype.isDark = function() {
467
- return Bt(this.rgba) < 0.5;
468
- }, t.prototype.isLight = function() {
469
- return Bt(this.rgba) >= 0.5;
470
- }, t.prototype.toHex = function() {
471
- return e = Tt(this.rgba), n = e.r, o = e.g, i = e.b, a = (s = e.a) < 1 ? mt(D(255 * s)) : "", "#" + mt(n) + mt(o) + mt(i) + a;
472
- var e, n, o, i, s, a;
473
- }, t.prototype.toRgb = function() {
474
- return Tt(this.rgba);
475
- }, t.prototype.toRgbString = function() {
476
- return e = Tt(this.rgba), n = e.r, o = e.g, i = e.b, (s = e.a) < 1 ? "rgba(" + n + ", " + o + ", " + i + ", " + s + ")" : "rgb(" + n + ", " + o + ", " + i + ")";
477
- var e, n, o, i, s;
478
- }, t.prototype.toHsl = function() {
479
- return qt(ct(this.rgba));
480
- }, t.prototype.toHslString = function() {
481
- return e = qt(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 + "%)";
482
- var e, n, o, i, s;
483
- }, t.prototype.toHsv = function() {
484
- return e = me(this.rgba), { h: D(e.h), s: D(e.s), v: D(e.v), a: D(e.a, 3) };
485
- var e;
486
- }, t.prototype.invert = function() {
487
- return $({ r: 255 - (e = this.rgba).r, g: 255 - e.g, b: 255 - e.b, a: e.a });
488
- var e;
489
- }, t.prototype.saturate = function(e) {
490
- return e === void 0 && (e = 0.1), $(Ot(this.rgba, e));
491
- }, t.prototype.desaturate = function(e) {
492
- return e === void 0 && (e = 0.1), $(Ot(this.rgba, -e));
493
- }, t.prototype.grayscale = function() {
494
- return $(Ot(this.rgba, -1));
495
- }, t.prototype.lighten = function(e) {
496
- return e === void 0 && (e = 0.1), $(Zt(this.rgba, e));
497
- }, t.prototype.darken = function(e) {
498
- return e === void 0 && (e = 0.1), $(Zt(this.rgba, -e));
499
- }, t.prototype.rotate = function(e) {
500
- return e === void 0 && (e = 15), this.hue(this.hue() + e);
501
- }, t.prototype.alpha = function(e) {
502
- return typeof e == "number" ? $({ r: (n = this.rgba).r, g: n.g, b: n.b, a: e }) : D(this.rgba.a, 3);
503
- var n;
504
- }, t.prototype.hue = function(e) {
505
- var n = ct(this.rgba);
506
- return typeof e == "number" ? $({ h: e, s: n.s, l: n.l, a: n.a }) : D(n.h);
507
- }, t.prototype.isEqual = function(e) {
508
- return this.toHex() === $(e).toHex();
509
- }, t;
510
- }(), $ = function(t) {
511
- return t instanceof te ? t : new te(t);
271
+ return trimmedRange;
512
272
  };
513
- const un = (t) => [
514
- `background-color:${$((t == null ? void 0 : t.fill) || q.fill).alpha((t == null ? void 0 : t.fillOpacity) === void 0 ? q.fillOpacity : t.fillOpacity).toHex()}`,
515
- t != null && t.underlineThickness ? "text-decoration:underline" : void 0,
516
- t != null && t.underlineColor ? `text-decoration-color:${t.underlineColor}` : void 0,
517
- t != null && t.underlineOffset ? `text-underline-offset:${t.underlineOffset}px` : void 0,
518
- t != null && t.underlineThickness ? `text-decoration-thickness:${t.underlineThickness}px` : void 0
519
- ].filter(Boolean).join(";"), fn = () => {
520
- const t = document.createElement("style");
521
- document.getElementsByTagName("head")[0].appendChild(t);
522
- let e = /* @__PURE__ */ new Set();
523
- return {
524
- destroy: () => {
525
- CSS.highlights.clear(), t.remove();
526
- },
527
- setVisible: (s) => {
528
- console.log("setVisible not implemented on CSS Custom Highlights renderer");
529
- },
530
- redraw: (s, a, r, l) => {
531
- l && l.clear();
532
- const d = new Set(s.map((u) => u.annotation.id));
533
- Array.from(e).filter((u) => !d.has(u));
534
- const g = s.map((u) => {
535
- var p;
536
- const h = r ? typeof r == "function" ? r(u.annotation, u.state) : r : (p = u.state) != null && p.selected ? Et : q, A = l && l.paint(u, a) || h;
537
- return `::highlight(_${u.annotation.id}) { ${un(A)} }`;
538
- });
539
- t.innerHTML = g.join(`
540
- `), CSS.highlights.clear(), s.forEach(({ annotation: u }) => {
541
- const h = u.target.selector.map((p) => p.range), A = new Highlight(...h);
542
- CSS.highlights.set(`_${u.id}`, A);
543
- }), e = d;
544
- }
545
- };
546
- }, hn = (t, e, n) => $t(t, e, n, fn());
547
- var ee = Object.prototype.hasOwnProperty;
548
- function Pt(t, e) {
549
- var n, o;
550
- if (t === e) return !0;
551
- if (t && e && (n = t.constructor) === e.constructor) {
552
- if (n === Date) return t.getTime() === e.getTime();
553
- if (n === RegExp) return t.toString() === e.toString();
554
- if (n === Array) {
555
- if ((o = t.length) === e.length)
556
- for (; o-- && Pt(t[o], e[o]); ) ;
557
- return o === -1;
558
- }
559
- if (!n || typeof t == "object") {
560
- o = 0;
561
- for (n in t)
562
- if (ee.call(t, n) && ++o && !ee.call(e, n) || !(n in e) || !Pt(t[n], e[n])) return !1;
563
- return Object.keys(e).length === o;
564
- }
565
- }
566
- return t !== t && e !== e;
567
- }
568
- const pn = (t, e) => {
569
- 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)));
570
- return i.sort((s, a) => o(a) - o(s)), i.findIndex((s) => s.rects.includes(t));
571
- }, gn = (t) => {
572
- t.classList.add("r6o-annotatable");
573
- const e = document.createElement("div");
574
- e.className = "r6o-span-highlight-layer", t.insertBefore(e, t.firstChild);
575
- let n = [];
576
- return {
577
- destroy: () => {
578
- e.remove();
579
- },
580
- redraw: (a, r, l, d, g) => {
581
- const h = !(Pt(n, a) && g);
582
- if (!d && !h) return;
583
- h && (e.innerHTML = ""), [...a].sort((p, b) => {
584
- const { annotation: { target: { created: x } } } = p, { annotation: { target: { created: m } } } = b;
585
- return x && m ? x.getTime() - m.getTime() : 0;
586
- }).forEach((p) => {
587
- p.rects.map((b) => {
588
- const x = pn(b, a), m = Fe(p, r, l, d, x);
589
- if (h) {
590
- const c = document.createElement("span");
591
- c.className = "r6o-annotation", c.dataset.annotation = p.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 = $((m == null ? void 0 : m.fill) || q.fill).alpha((m == null ? void 0 : m.fillOpacity) === void 0 ? q.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);
592
- }
593
- });
594
- }), n = a;
595
- },
596
- setVisible: (a) => {
597
- a ? e.classList.remove("hidden") : e.classList.add("hidden");
598
- }
273
+ const clonePointerEvent = (event) => ({
274
+ ...event,
275
+ type: event.type,
276
+ x: event.x,
277
+ y: event.y,
278
+ clientX: event.clientX,
279
+ clientY: event.clientY,
280
+ offsetX: event.offsetX,
281
+ offsetY: event.offsetY,
282
+ screenX: event.screenX,
283
+ screenY: event.screenY,
284
+ isPrimary: event.isPrimary,
285
+ altKey: event.altKey,
286
+ ctrlKey: event.ctrlKey,
287
+ metaKey: event.metaKey,
288
+ shiftKey: event.shiftKey,
289
+ button: event.button,
290
+ buttons: event.buttons,
291
+ currentTarget: event.currentTarget,
292
+ target: event.target,
293
+ defaultPrevented: event.defaultPrevented,
294
+ detail: event.detail,
295
+ eventPhase: event.eventPhase,
296
+ pointerId: event.pointerId,
297
+ pointerType: event.pointerType,
298
+ timeStamp: event.timeStamp
299
+ });
300
+ const cloneKeyboardEvent = (event) => ({
301
+ ...event,
302
+ type: event.type,
303
+ key: event.key,
304
+ code: event.code,
305
+ location: event.location,
306
+ repeat: event.repeat,
307
+ altKey: event.altKey,
308
+ ctrlKey: event.ctrlKey,
309
+ metaKey: event.metaKey,
310
+ shiftKey: event.shiftKey,
311
+ currentTarget: event.currentTarget,
312
+ target: event.target,
313
+ defaultPrevented: event.defaultPrevented,
314
+ detail: event.detail,
315
+ timeStamp: event.timeStamp
316
+ });
317
+ const toParentBounds = (rect, offset) => {
318
+ const { left, top, right, bottom } = rect;
319
+ return new DOMRect(left - offset.left, top - offset.top, right - left, bottom - top);
320
+ };
321
+ const toViewportBounds = (rect, offset) => {
322
+ const { left, top, right, bottom } = rect;
323
+ return new DOMRect(left + offset.left, top + offset.top, right - left, bottom - top);
324
+ };
325
+ const getScrollParent = (el) => {
326
+ if (el === null)
327
+ return document.scrollingElement;
328
+ const { overflowY } = window.getComputedStyle(el);
329
+ const isScrollable = overflowY !== "visible" && overflowY !== "hidden";
330
+ if (isScrollable && el.scrollHeight > el.clientHeight)
331
+ return el;
332
+ else
333
+ return getScrollParent(el.parentElement);
334
+ };
335
+ const scrollIntoView = (container, store) => (annotationOrId) => {
336
+ const id = typeof annotationOrId === "string" ? annotationOrId : annotationOrId.id;
337
+ const scroll = (target) => {
338
+ const parentBounds = scrollParent.getBoundingClientRect();
339
+ const parentHeight = scrollParent.clientHeight;
340
+ const parentWidth = scrollParent.clientWidth;
341
+ const annotationBounds = target.selector[0].range.getBoundingClientRect();
342
+ const { width, height } = store.getAnnotationBounds(id);
343
+ const offsetTop = annotationBounds.top - parentBounds.top;
344
+ const offsetLeft = annotationBounds.left - parentBounds.left;
345
+ const scrollTop = scrollParent.parentElement ? scrollParent.scrollTop : 0;
346
+ const scrollLeft = scrollParent.parentElement ? scrollParent.scrollLeft : 0;
347
+ const top = offsetTop + scrollTop - (parentHeight - height) / 2;
348
+ const left = offsetLeft + scrollLeft - (parentWidth - width) / 2;
349
+ scrollParent.scroll({ top, left, behavior: "smooth" });
599
350
  };
600
- }, mn = (t, e, n) => $t(t, e, n, gn(t)), V = [];
601
- for (let t = 0; t < 256; ++t)
602
- V.push((t + 256).toString(16).slice(1));
603
- function yn(t, e = 0) {
604
- return (V[t[e + 0]] + V[t[e + 1]] + V[t[e + 2]] + V[t[e + 3]] + "-" + V[t[e + 4]] + V[t[e + 5]] + "-" + V[t[e + 6]] + V[t[e + 7]] + "-" + V[t[e + 8]] + V[t[e + 9]] + "-" + V[t[e + 10]] + V[t[e + 11]] + V[t[e + 12]] + V[t[e + 13]] + V[t[e + 14]] + V[t[e + 15]]).toLowerCase();
605
- }
606
- let Rt;
607
- const bn = new Uint8Array(16);
608
- function wn() {
609
- if (!Rt) {
610
- if (typeof crypto > "u" || !crypto.getRandomValues)
611
- throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
612
- Rt = crypto.getRandomValues.bind(crypto);
613
- }
614
- return Rt(bn);
615
- }
616
- const An = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), ne = { randomUUID: An };
617
- function be(t, e, n) {
618
- if (ne.randomUUID && !e && !t)
619
- return ne.randomUUID();
620
- t = t || {};
621
- const o = t.random || (t.rng || wn)();
622
- return o[6] = o[6] & 15 | 64, o[8] = o[8] & 63 | 128, yn(o);
623
- }
624
- var oe = Object.prototype.hasOwnProperty;
625
- function Q(t, e) {
626
- var n, o;
627
- if (t === e) return !0;
628
- if (t && e && (n = t.constructor) === e.constructor) {
629
- if (n === Date) return t.getTime() === e.getTime();
630
- if (n === RegExp) return t.toString() === e.toString();
631
- if (n === Array) {
632
- if ((o = t.length) === e.length)
633
- for (; o-- && Q(t[o], e[o]); ) ;
634
- return o === -1;
635
- }
636
- if (!n || typeof t == "object") {
637
- o = 0;
638
- for (n in t)
639
- if (oe.call(t, n) && ++o && !oe.call(e, n) || !(n in e) || !Q(t[n], e[n])) return !1;
640
- return Object.keys(e).length === o;
641
- }
642
- }
643
- return t !== t && e !== e;
644
- }
645
- function Mt() {
646
- }
647
- function xn(t, e) {
648
- return t != t ? e == e : t !== e || t && typeof t == "object" || typeof t == "function";
649
- }
650
- const J = [];
651
- function Ht(t, e = Mt) {
652
- let n;
653
- const o = /* @__PURE__ */ new Set();
654
- function i(r) {
655
- if (xn(t, r) && (t = r, n)) {
656
- const l = !J.length;
657
- for (const d of o)
658
- d[1](), J.push(d, t);
659
- if (l) {
660
- for (let d = 0; d < J.length; d += 2)
661
- J[d][0](J[d + 1]);
662
- J.length = 0;
351
+ const scrollParent = getScrollParent(container);
352
+ if (scrollParent) {
353
+ const current = store.getAnnotation(id);
354
+ const { range } = current.target.selector[0];
355
+ if (range && !range.collapsed) {
356
+ scroll(current.target);
357
+ return true;
358
+ } else {
359
+ const revived = reviveTarget(current.target, container);
360
+ const { range: range2 } = revived.selector[0];
361
+ if (range2 && !range2.collapsed) {
362
+ scroll(revived);
363
+ return true;
663
364
  }
664
365
  }
665
366
  }
666
- function s(r) {
667
- i(r(t));
668
- }
669
- function a(r, l = Mt) {
670
- const d = [r, l];
671
- return o.add(d), o.size === 1 && (n = e(i, s) || Mt), r(t), () => {
672
- o.delete(d), o.size === 0 && n && (n(), n = null);
673
- };
674
- }
675
- return { set: i, update: s, subscribe: a };
676
- }
677
- const vn = (t) => {
678
- const { subscribe: e, set: n } = Ht();
679
- let o;
680
- return e((i) => o = i), t.observe(({ changes: i }) => {
681
- if (o) {
682
- (i.deleted || []).some((a) => a.id === o) && n(void 0);
683
- const s = (i.updated || []).find(({ oldValue: a }) => a.id === o);
684
- s && n(s.newValue.id);
367
+ return false;
368
+ };
369
+ const DEFAULT_STYLE = {
370
+ fill: "rgb(0, 128, 255)",
371
+ fillOpacity: 0.18
372
+ };
373
+ const DEFAULT_SELECTED_STYLE = {
374
+ fill: "rgb(0, 128, 255)",
375
+ fillOpacity: 0.45
376
+ };
377
+ const paint = (highlight, viewportBounds, style, painter, zIndex) => {
378
+ var _a, _b;
379
+ 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;
380
+ return painter ? painter.paint(highlight, viewportBounds) || base : base;
381
+ };
382
+ const getViewportBounds = (container) => {
383
+ const { top, left } = container.getBoundingClientRect();
384
+ const { innerWidth, innerHeight } = window;
385
+ const minX = -left;
386
+ const minY = -top;
387
+ const maxX = innerWidth - left;
388
+ const maxY = innerHeight - top;
389
+ return { top, left, minX, minY, maxX, maxY };
390
+ };
391
+ const trackViewport = (viewport) => {
392
+ let visible = /* @__PURE__ */ new Set();
393
+ const onDraw = (annotations) => {
394
+ const ids = annotations.map((a) => a.id);
395
+ if (visible.size !== ids.length || ids.some((id) => !visible.has(id))) {
396
+ viewport.set(ids);
685
397
  }
686
- }), {
687
- get current() {
688
- return o;
689
- },
690
- subscribe: e,
691
- set: n
398
+ visible = new Set(ids);
692
399
  };
400
+ return onDraw;
693
401
  };
694
- var En = /* @__PURE__ */ ((t) => (t.EDIT = "EDIT", t.SELECT = "SELECT", t.NONE = "NONE", t))(En || {});
695
- const yt = { selected: [] }, Sn = (t, e, n) => {
696
- const { subscribe: o, set: i } = Ht(yt);
697
- let s = e, a = yt;
698
- o((p) => a = p);
699
- const r = () => {
700
- Q(a, yt) || i(yt);
701
- }, l = () => {
702
- var p;
703
- return ((p = a.selected) == null ? void 0 : p.length) === 0;
704
- }, d = (p) => {
705
- if (l())
706
- return !1;
707
- const b = typeof p == "string" ? p : p.id;
708
- return a.selected.some((x) => x.id === b);
709
- }, g = (p, b) => {
710
- let x;
711
- if (Array.isArray(p)) {
712
- if (x = p.map((c) => t.getAnnotation(c)).filter(Boolean), x.length < p.length) {
713
- console.warn("Invalid selection: " + p.filter((c) => !x.some((y) => y.id === c)));
714
- return;
402
+ const createBaseRenderer = (container, state, viewport, renderer) => {
403
+ const { store, selection, hover } = state;
404
+ let currentStyle;
405
+ let currentFilter;
406
+ let currentPainter;
407
+ const onDraw = trackViewport(viewport);
408
+ const onPointerMove = (event) => {
409
+ const { x, y } = container.getBoundingClientRect();
410
+ const hit = store.getAt(event.clientX - x, event.clientY - y, false, currentFilter);
411
+ if (hit) {
412
+ if (hover.current !== hit.id) {
413
+ container.classList.add("hovered");
414
+ hover.set(hit.id);
715
415
  }
716
416
  } else {
717
- const c = t.getAnnotation(p);
718
- if (!c) {
719
- console.warn("Invalid selection: " + p);
720
- return;
417
+ if (hover.current) {
418
+ container.classList.remove("hovered");
419
+ hover.set(null);
721
420
  }
722
- x = [c];
723
421
  }
724
- const m = x.reduce((c, y) => {
725
- const C = ie(y, s, n);
726
- return C === "EDIT" ? [...c, { id: y.id, editable: !0 }] : C === "SELECT" ? [...c, { id: y.id }] : c;
727
- }, []);
728
- i({ selected: m, event: b });
729
- }, u = (p, b) => {
730
- const x = Array.isArray(p) ? p : [p], m = x.map((c) => t.getAnnotation(c)).filter((c) => !!c);
731
- i({
732
- selected: m.map((c) => {
733
- const y = b === void 0 ? ie(c, s, n) === "EDIT" : b;
734
- return { id: c.id, editable: y };
735
- })
736
- }), m.length !== x.length && console.warn("Invalid selection", p);
737
- }, h = (p) => {
738
- if (l())
739
- return !1;
740
- const { selected: b } = a;
741
- b.some(({ id: x }) => p.includes(x)) && i({ selected: b.filter(({ id: x }) => !p.includes(x)) });
742
- }, A = (p) => s = p;
743
- return t.observe(
744
- ({ changes: p }) => h((p.deleted || []).map((b) => b.id))
745
- ), {
746
- get event() {
747
- return a ? a.event : null;
748
- },
749
- get selected() {
750
- return a ? [...a.selected] : null;
751
- },
752
- get userSelectAction() {
753
- return s;
754
- },
755
- clear: r,
756
- isEmpty: l,
757
- isSelected: d,
758
- setSelected: u,
759
- setUserSelectAction: A,
760
- subscribe: o,
761
- userSelect: g
762
- };
763
- }, ie = (t, e, n) => {
764
- const o = n ? n.serialize(t) : t;
765
- return typeof e == "function" ? e(o) : e || "EDIT";
766
- }, Y = [];
767
- for (let t = 0; t < 256; ++t)
768
- Y.push((t + 256).toString(16).slice(1));
769
- function Cn(t, e = 0) {
770
- 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();
771
- }
772
- let kt;
773
- const Ln = new Uint8Array(16);
774
- function Tn() {
775
- if (!kt) {
776
- if (typeof crypto > "u" || !crypto.getRandomValues)
777
- throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
778
- kt = crypto.getRandomValues.bind(crypto);
779
- }
780
- return kt(Ln);
781
- }
782
- const On = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), se = { randomUUID: On };
783
- function we(t, e, n) {
784
- if (se.randomUUID && !e && !t)
785
- return se.randomUUID();
786
- t = t || {};
787
- const o = t.random || (t.rng || Tn)();
788
- return o[6] = o[6] & 15 | 64, o[8] = o[8] & 63 | 128, Cn(o);
789
- }
790
- const It = (t) => {
791
- const e = (n) => {
792
- const o = { ...n };
793
- 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;
794
422
  };
795
- return {
796
- ...t,
797
- bodies: (t.bodies || []).map(e),
798
- target: e(t.target)
799
- };
800
- }, Io = (t, e, n, o) => ({
801
- id: we(),
802
- annotation: typeof t == "string" ? t : t.id,
803
- created: n || /* @__PURE__ */ new Date(),
804
- creator: o,
805
- ...e
806
- }), Bn = (t, e) => {
807
- const n = new Set(t.bodies.map((o) => o.id));
808
- return e.bodies.filter((o) => !n.has(o.id));
809
- }, Rn = (t, e) => {
810
- const n = new Set(e.bodies.map((o) => o.id));
811
- return t.bodies.filter((o) => !n.has(o.id));
812
- }, Mn = (t, e) => e.bodies.map((n) => {
813
- const o = t.bodies.find((i) => i.id === n.id);
814
- return { newBody: n, oldBody: o && !Q(o, n) ? o : void 0 };
815
- }).filter(({ oldBody: n }) => n).map(({ oldBody: n, newBody: o }) => ({ oldBody: n, newBody: o })), kn = (t, e) => !Q(t.target, e.target), Ae = (t, e) => {
816
- const n = Bn(t, e), o = Rn(t, e), i = Mn(t, e);
817
- return {
818
- oldValue: t,
819
- newValue: e,
820
- bodiesCreated: n.length > 0 ? n : void 0,
821
- bodiesDeleted: o.length > 0 ? o : void 0,
822
- bodiesUpdated: i.length > 0 ? i : void 0,
823
- targetUpdated: kn(t, e) ? { oldTarget: t.target, newTarget: e.target } : void 0
423
+ container.addEventListener("pointermove", onPointerMove);
424
+ const redraw = (lazy = false) => {
425
+ if (currentPainter)
426
+ currentPainter.clear();
427
+ const bounds = getViewportBounds(container);
428
+ const { minX, minY, maxX, maxY } = bounds;
429
+ const annotationsInView = currentFilter ? store.getIntersecting(minX, minY, maxX, maxY).filter(({ annotation }) => currentFilter(annotation)) : store.getIntersecting(minX, minY, maxX, maxY);
430
+ const selectedIds = selection.selected.map(({ id }) => id);
431
+ const highlights = annotationsInView.map(({ annotation, rects }) => {
432
+ const selected = selectedIds.includes(annotation.id);
433
+ const hovered = annotation.id === hover.current;
434
+ return { annotation, rects, state: { selected, hover: hovered } };
435
+ });
436
+ renderer.redraw(highlights, bounds, currentStyle, currentPainter, lazy);
437
+ setTimeout(() => onDraw(annotationsInView.map(({ annotation }) => annotation)), 1);
824
438
  };
825
- };
826
- var k = /* @__PURE__ */ ((t) => (t.LOCAL = "LOCAL", t.REMOTE = "REMOTE", t.SILENT = "SILENT", t))(k || {});
827
- const In = (t, e) => {
828
- var n, o;
829
- const { changes: i, origin: s } = e;
830
- if (!(t.options.origin ? t.options.origin === s : s !== "SILENT"))
831
- return !1;
832
- if (t.options.ignore) {
833
- const { ignore: a } = t.options, r = (l) => l && l.length > 0;
834
- if (!(r(i.created) || r(i.deleted))) {
835
- const l = (n = i.updated) == null ? void 0 : n.some((g) => r(g.bodiesCreated) || r(g.bodiesDeleted) || r(g.bodiesUpdated)), d = (o = i.updated) == null ? void 0 : o.some((g) => g.targetUpdated);
836
- if (a === "BODY_ONLY" && l && !d || a === "TARGET_ONLY" && d && !l)
837
- return !1;
838
- }
839
- }
840
- if (t.options.annotations) {
841
- const a = /* @__PURE__ */ new Set([
842
- ...(i.created || []).map((r) => r.id),
843
- ...(i.deleted || []).map((r) => r.id),
844
- ...(i.updated || []).map(({ oldValue: r }) => r.id)
845
- ]);
846
- return !!(Array.isArray(t.options.annotations) ? t.options.annotations : [t.options.annotations]).find((r) => a.has(r));
847
- } else
848
- return !0;
849
- }, Nn = (t, e) => {
850
- 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 = [
851
- ...(t.created || []).filter((u) => !s.has(u.id)).map((u) => a.has(u.id) ? e.updated.find(({ oldValue: h }) => h.id === u.id).newValue : u),
852
- ...e.created || []
853
- ], d = [
854
- ...(t.deleted || []).filter((u) => !i.has(u.id)),
855
- ...(e.deleted || []).filter((u) => !n.has(u.id))
856
- ], g = [
857
- ...(t.updated || []).filter(({ newValue: u }) => !s.has(u.id)).map((u) => {
858
- const { oldValue: h, newValue: A } = u;
859
- if (a.has(A.id)) {
860
- const p = e.updated.find((b) => b.oldValue.id === A.id).newValue;
861
- return Ae(h, p);
862
- } else
863
- return u;
864
- }),
865
- ...(e.updated || []).filter(({ oldValue: u }) => !r.has(u.id))
866
- ];
867
- return { created: l, deleted: d, updated: g };
868
- }, Nt = (t) => {
869
- const e = t.id === void 0 ? we() : t.id;
870
- return {
871
- ...t,
872
- id: e,
873
- bodies: t.bodies === void 0 ? [] : t.bodies.map((n) => ({
874
- ...n,
875
- annotation: e
876
- })),
877
- target: {
878
- ...t.target,
879
- annotation: e
880
- }
439
+ const setPainter = (painter) => {
440
+ currentPainter = painter;
441
+ redraw();
881
442
  };
882
- }, _n = (t) => t.id !== void 0, Un = () => {
883
- const t = /* @__PURE__ */ new Map(), e = /* @__PURE__ */ new Map(), n = [], o = (w, v = {}) => {
884
- n.push({ onChange: w, options: v });
885
- }, i = (w) => {
886
- const v = n.findIndex((f) => f.onChange == w);
887
- v > -1 && n.splice(v, 1);
888
- }, s = (w, v) => {
889
- const f = {
890
- origin: w,
891
- changes: {
892
- created: v.created || [],
893
- updated: v.updated || [],
894
- deleted: v.deleted || []
895
- },
896
- state: [...t.values()]
897
- };
898
- n.forEach((E) => {
899
- In(E, f) && E.onChange(f);
900
- });
901
- }, a = (w, v = k.LOCAL) => {
902
- if (w.id && t.get(w.id))
903
- throw Error(`Cannot add annotation ${w.id} - exists already`);
904
- {
905
- const f = Nt(w);
906
- t.set(f.id, f), f.bodies.forEach((E) => e.set(E.id, f.id)), s(v, { created: [f] });
907
- }
908
- }, r = (w, v) => {
909
- const f = Nt(typeof w == "string" ? v : w), E = typeof w == "string" ? w : w.id, M = E && t.get(E);
910
- if (M) {
911
- const O = Ae(M, f);
912
- return E === f.id ? t.set(E, f) : (t.delete(E), t.set(f.id, f)), M.bodies.forEach((U) => e.delete(U.id)), f.bodies.forEach((U) => e.set(U.id, f.id)), O;
913
- } else
914
- console.warn(`Cannot update annotation ${E} - does not exist`);
915
- }, l = (w, v = k.LOCAL, f = k.LOCAL) => {
916
- const E = _n(v) ? f : v, M = r(w, v);
917
- M && s(E, { updated: [M] });
918
- }, d = (w, v = k.LOCAL) => {
919
- const f = w.reduce((E, M) => {
920
- const O = r(M);
921
- return O ? [...E, O] : E;
922
- }, []);
923
- f.length > 0 && s(v, { updated: f });
924
- }, g = (w, v = k.LOCAL) => {
925
- const f = t.get(w.annotation);
926
- if (f) {
927
- const E = {
928
- ...f,
929
- bodies: [...f.bodies, w]
930
- };
931
- t.set(f.id, E), e.set(w.id, E.id), s(v, { updated: [{
932
- oldValue: f,
933
- newValue: E,
934
- bodiesCreated: [w]
935
- }] });
936
- } else
937
- console.warn(`Attempt to add body to missing annotation: ${w.annotation}`);
938
- }, u = () => [...t.values()], h = (w = k.LOCAL) => {
939
- const v = [...t.values()];
940
- t.clear(), e.clear(), s(w, { deleted: v });
941
- }, A = (w, v = !0, f = k.LOCAL) => {
942
- const E = w.map(Nt);
943
- if (v) {
944
- const M = [...t.values()];
945
- t.clear(), e.clear(), E.forEach((O) => {
946
- t.set(O.id, O), O.bodies.forEach((U) => e.set(U.id, O.id));
947
- }), s(f, { created: E, deleted: M });
948
- } else {
949
- const M = w.reduce((O, U) => {
950
- const _ = U.id && t.get(U.id);
951
- return _ ? [...O, _] : O;
952
- }, []);
953
- if (M.length > 0)
954
- throw Error(`Bulk insert would overwrite the following annotations: ${M.map((O) => O.id).join(", ")}`);
955
- E.forEach((O) => {
956
- t.set(O.id, O), O.bodies.forEach((U) => e.set(U.id, O.id));
957
- }), s(f, { created: E });
958
- }
959
- }, p = (w) => {
960
- const v = typeof w == "string" ? w : w.id, f = t.get(v);
961
- if (f)
962
- return t.delete(v), f.bodies.forEach((E) => e.delete(E.id)), f;
963
- console.warn(`Attempt to delete missing annotation: ${v}`);
964
- }, b = (w, v = k.LOCAL) => {
965
- const f = p(w);
966
- f && s(v, { deleted: [f] });
967
- }, x = (w, v = k.LOCAL) => {
968
- const f = w.reduce((E, M) => {
969
- const O = p(M);
970
- return O ? [...E, O] : E;
971
- }, []);
972
- f.length > 0 && s(v, { deleted: f });
973
- }, m = (w) => {
974
- const v = t.get(w.annotation);
975
- if (v) {
976
- const f = v.bodies.find((E) => E.id === w.id);
977
- if (f) {
978
- e.delete(f.id);
979
- const E = {
980
- ...v,
981
- bodies: v.bodies.filter((M) => M.id !== w.id)
982
- };
983
- return t.set(v.id, E), {
984
- oldValue: v,
985
- newValue: E,
986
- bodiesDeleted: [f]
987
- };
988
- } else
989
- console.warn(`Attempt to delete missing body ${w.id} from annotation ${w.annotation}`);
990
- } else
991
- console.warn(`Attempt to delete body from missing annotation ${w.annotation}`);
992
- }, c = (w, v = k.LOCAL) => {
993
- const f = m(w);
994
- f && s(v, { updated: [f] });
995
- }, y = (w, v = k.LOCAL) => {
996
- const f = w.map((E) => m(E)).filter(Boolean);
997
- f.length > 0 && s(v, { updated: f });
998
- }, C = (w) => {
999
- const v = t.get(w);
1000
- return v ? { ...v } : void 0;
1001
- }, S = (w) => {
1002
- const v = e.get(w);
1003
- if (v) {
1004
- const f = C(v).bodies.find((E) => E.id === w);
1005
- if (f)
1006
- return f;
1007
- console.error(`Store integrity error: body ${w} in index, but not in annotation`);
1008
- } else
1009
- console.warn(`Attempt to retrieve missing body: ${w}`);
1010
- }, L = (w, v) => {
1011
- if (w.annotation !== v.annotation)
1012
- throw "Annotation integrity violation: annotation ID must be the same when updating bodies";
1013
- const f = t.get(w.annotation);
1014
- if (f) {
1015
- const E = f.bodies.find((O) => O.id === w.id), M = {
1016
- ...f,
1017
- bodies: f.bodies.map((O) => O.id === E.id ? v : O)
1018
- };
1019
- return t.set(f.id, M), E.id !== v.id && (e.delete(E.id), e.set(v.id, M.id)), {
1020
- oldValue: f,
1021
- newValue: M,
1022
- bodiesUpdated: [{ oldBody: E, newBody: v }]
1023
- };
1024
- } else
1025
- console.warn(`Attempt to add body to missing annotation ${w.annotation}`);
1026
- }, B = (w, v, f = k.LOCAL) => {
1027
- const E = L(w, v);
1028
- E && s(f, { updated: [E] });
1029
- }, T = (w, v = k.LOCAL) => {
1030
- const f = w.map((E) => L({ id: E.id, annotation: E.annotation }, E)).filter(Boolean);
1031
- s(v, { updated: f });
1032
- }, R = (w) => {
1033
- const v = t.get(w.annotation);
1034
- if (v) {
1035
- const f = {
1036
- ...v,
1037
- target: {
1038
- ...v.target,
1039
- ...w
1040
- }
1041
- };
1042
- return t.set(v.id, f), {
1043
- oldValue: v,
1044
- newValue: f,
1045
- targetUpdated: {
1046
- oldTarget: v.target,
1047
- newTarget: w
1048
- }
1049
- };
1050
- } else
1051
- console.warn(`Attempt to update target on missing annotation: ${w.annotation}`);
443
+ const setStyle = (style) => {
444
+ currentStyle = style;
445
+ redraw();
446
+ };
447
+ const setFilter = (filter) => {
448
+ currentFilter = filter;
449
+ redraw(false);
450
+ };
451
+ const onStoreChange = () => redraw();
452
+ store.observe(onStoreChange);
453
+ const unsubscribeSelection = selection.subscribe(() => redraw());
454
+ const onScroll = () => redraw(true);
455
+ document.addEventListener("scroll", onScroll, { capture: true, passive: true });
456
+ const onResize = debounce(() => {
457
+ store.recalculatePositions();
458
+ currentPainter == null ? void 0 : currentPainter.reset();
459
+ redraw();
460
+ }, 10);
461
+ window.addEventListener("resize", onResize);
462
+ const resizeObserver = new ResizeObserver(onResize);
463
+ resizeObserver.observe(container);
464
+ const config = { attributes: true, childList: true, subtree: true };
465
+ const mutationObserver = new MutationObserver((records) => {
466
+ const isInternal = records.every((record) => record.target === container || container.contains(record.target));
467
+ if (!isInternal) redraw(true);
468
+ });
469
+ mutationObserver.observe(document.body, config);
470
+ const destroy = () => {
471
+ container.removeEventListener("pointermove", onPointerMove);
472
+ renderer.destroy();
473
+ store.unobserve(onStoreChange);
474
+ unsubscribeSelection();
475
+ document.removeEventListener("scroll", onScroll);
476
+ onResize.clear();
477
+ window.removeEventListener("resize", onResize);
478
+ resizeObserver.disconnect();
479
+ mutationObserver.disconnect();
1052
480
  };
1053
481
  return {
1054
- addAnnotation: a,
1055
- addBody: g,
1056
- all: u,
1057
- bulkAddAnnotation: A,
1058
- bulkDeleteAnnotation: x,
1059
- bulkDeleteBodies: y,
1060
- bulkUpdateAnnotation: d,
1061
- bulkUpdateBodies: T,
1062
- bulkUpdateTargets: (w, v = k.LOCAL) => {
1063
- const f = w.map((E) => R(E)).filter(Boolean);
1064
- f.length > 0 && s(v, { updated: f });
1065
- },
1066
- clear: h,
1067
- deleteAnnotation: b,
1068
- deleteBody: c,
1069
- getAnnotation: C,
1070
- getBody: S,
1071
- observe: o,
1072
- unobserve: i,
1073
- updateAnnotation: l,
1074
- updateBody: B,
1075
- updateTarget: (w, v = k.LOCAL) => {
1076
- const f = R(w);
1077
- f && s(v, { updated: [f] });
1078
- }
482
+ destroy,
483
+ redraw,
484
+ setStyle,
485
+ setFilter,
486
+ setPainter,
487
+ setVisible: renderer.setVisible
1079
488
  };
1080
489
  };
1081
- let Dn = () => ({
1082
- emit(t, ...e) {
1083
- for (let n = this.events[t] || [], o = 0, i = n.length; o < i; o++)
1084
- n[o](...e);
1085
- },
1086
- events: {},
1087
- on(t, e) {
1088
- var n;
1089
- return ((n = this.events)[t] || (n[t] = [])).push(e), () => {
1090
- var o;
1091
- this.events[t] = (o = this.events[t]) == null ? void 0 : o.filter((i) => e !== i);
1092
- };
1093
- }
1094
- });
1095
- const Vn = 250, Yn = (t, e) => {
1096
- const n = Dn(), o = [];
1097
- let i = -1, s = !1, a = 0;
1098
- const r = (p) => {
1099
- if (!s) {
1100
- const { changes: b } = p, x = performance.now();
1101
- if (x - a > Vn)
1102
- o.splice(i + 1), o.push(b), i = o.length - 1;
1103
- else {
1104
- const m = o.length - 1;
1105
- o[m] = Nn(o[m], b);
490
+ const createCanvas$1 = () => {
491
+ const canvas = document.createElement("canvas");
492
+ canvas.width = window.innerWidth;
493
+ canvas.height = window.innerHeight;
494
+ canvas.className = "r6o-canvas-highlight-layer bg";
495
+ return canvas;
496
+ };
497
+ const resetCanvas = (canvas, highres) => {
498
+ canvas.width = window.innerWidth;
499
+ canvas.height = window.innerHeight;
500
+ };
501
+ const createRenderer$2 = (container) => {
502
+ container.classList.add("r6o-annotatable");
503
+ const canvas = createCanvas$1();
504
+ const ctx = canvas.getContext("2d");
505
+ document.body.appendChild(canvas);
506
+ const redraw = (highlights, viewportBounds, currentStyle, currentPainter) => requestAnimationFrame(() => {
507
+ const { width, height } = canvas;
508
+ ctx.clearRect(-0.5, -0.5, width + 1, height + 1);
509
+ if (currentPainter)
510
+ currentPainter.clear();
511
+ const { top, left } = viewportBounds;
512
+ const highlightsByCreation = [...highlights].sort((highlightA, highlightB) => {
513
+ const { annotation: { target: { created: createdA } } } = highlightA;
514
+ const { annotation: { target: { created: createdB } } } = highlightB;
515
+ return createdA.getTime() - createdB.getTime();
516
+ });
517
+ highlightsByCreation.forEach((h) => {
518
+ var _a;
519
+ 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;
520
+ const style = currentPainter ? currentPainter.paint(h, viewportBounds) || base : base;
521
+ const offsetRects = h.rects.map(({ x, y, width: width2, height: height2 }) => ({
522
+ x: x + left,
523
+ y: y + top,
524
+ width: width2,
525
+ height: height2
526
+ }));
527
+ ctx.fillStyle = style.fill;
528
+ ctx.globalAlpha = style.fillOpacity || 1;
529
+ offsetRects.forEach(
530
+ ({ x, y, width: width2, height: height2 }) => ctx.fillRect(x, y, width2, height2)
531
+ );
532
+ if (style.underlineColor) {
533
+ ctx.globalAlpha = 1;
534
+ ctx.strokeStyle = style.underlineColor;
535
+ ctx.lineWidth = style.underlineThickness ?? 1;
536
+ const underlineOffset = style.underlineOffset ?? 0;
537
+ offsetRects.forEach(({ x, y, width: width2, height: height2 }) => {
538
+ ctx.beginPath();
539
+ ctx.moveTo(x, y + height2 + underlineOffset);
540
+ ctx.lineTo(x + width2, y + height2 + underlineOffset);
541
+ ctx.stroke();
542
+ });
1106
543
  }
1107
- a = x;
1108
- }
1109
- s = !1;
544
+ });
545
+ });
546
+ const onResize = debounce(() => resetCanvas(canvas), 10);
547
+ window.addEventListener("resize", onResize);
548
+ const setVisible = (visible) => {
549
+ console.log("setVisible not implemented on Canvas renderer");
550
+ };
551
+ const destroy = () => {
552
+ canvas.remove();
553
+ onResize.clear();
554
+ window.removeEventListener("resize", onResize);
1110
555
  };
1111
- t.observe(r, { origin: k.LOCAL });
1112
- const l = (p) => p && p.length > 0 && t.bulkDeleteAnnotation(p), d = (p) => p && p.length > 0 && t.bulkAddAnnotation(p, !1), g = (p) => p && p.length > 0 && t.bulkUpdateAnnotation(p.map(({ oldValue: b }) => b)), u = (p) => p && p.length > 0 && t.bulkUpdateAnnotation(p.map(({ newValue: b }) => b)), h = (p) => p && p.length > 0 && t.bulkAddAnnotation(p, !1), A = (p) => p && p.length > 0 && t.bulkDeleteAnnotation(p);
1113
556
  return {
1114
- canRedo: () => o.length - 1 > i,
1115
- canUndo: () => i > -1,
1116
- destroy: () => t.unobserve(r),
1117
- getHistory: () => ({ changes: [...o], pointer: i }),
1118
- on: (p, b) => n.on(p, b),
1119
- redo: () => {
1120
- if (o.length - 1 > i) {
1121
- s = !0;
1122
- const { created: p, updated: b, deleted: x } = o[i + 1];
1123
- d(p), u(b), A(x), n.emit("redo", o[i + 1]), i += 1;
1124
- }
1125
- },
1126
- undo: () => {
1127
- if (i > -1) {
1128
- s = !0;
1129
- const { created: p, updated: b, deleted: x } = o[i];
1130
- l(p), g(b), h(x), n.emit("undo", o[i]), i -= 1;
1131
- }
1132
- }
557
+ destroy,
558
+ setVisible,
559
+ redraw
560
+ };
561
+ };
562
+ const createCanvasRenderer = (container, state, viewport) => createBaseRenderer(container, state, viewport, createRenderer$2(container));
563
+ const toCSS = (s) => {
564
+ const backgroundColor = 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();
565
+ const rules = [
566
+ `background-color:${backgroundColor}`,
567
+ (s == null ? void 0 : s.underlineThickness) ? `text-decoration:underline` : void 0,
568
+ (s == null ? void 0 : s.underlineColor) ? `text-decoration-color:${s.underlineColor}` : void 0,
569
+ (s == null ? void 0 : s.underlineOffset) ? `text-underline-offset:${s.underlineOffset}px` : void 0,
570
+ (s == null ? void 0 : s.underlineThickness) ? `text-decoration-thickness:${s.underlineThickness}px` : void 0
571
+ ].filter(Boolean);
572
+ return rules.join(";");
573
+ };
574
+ const createRenderer$1 = () => {
575
+ const elem = document.createElement("style");
576
+ document.getElementsByTagName("head")[0].appendChild(elem);
577
+ let currentRendered = /* @__PURE__ */ new Set();
578
+ const redraw = (highlights, viewportBounds, currentStyle, painter) => {
579
+ if (painter)
580
+ painter.clear();
581
+ const nextRendered = new Set(highlights.map((h) => h.annotation.id));
582
+ Array.from(currentRendered).filter((id) => !nextRendered.has(id));
583
+ const updatedCSS = highlights.map((h) => {
584
+ var _a;
585
+ 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;
586
+ const style = painter ? painter.paint(h, viewportBounds) || base : base;
587
+ return `::highlight(_${h.annotation.id}) { ${toCSS(style)} }`;
588
+ });
589
+ elem.innerHTML = updatedCSS.join("\n");
590
+ CSS.highlights.clear();
591
+ highlights.forEach(({ annotation }) => {
592
+ const ranges = annotation.target.selector.map((s) => s.range);
593
+ const highlights2 = new Highlight(...ranges);
594
+ CSS.highlights.set(`_${annotation.id}`, highlights2);
595
+ });
596
+ currentRendered = nextRendered;
597
+ };
598
+ const setVisible = (visible) => {
599
+ console.log("setVisible not implemented on CSS Custom Highlights renderer");
600
+ };
601
+ const destroy = () => {
602
+ CSS.highlights.clear();
603
+ elem.remove();
1133
604
  };
1134
- }, Kn = () => {
1135
- const { subscribe: t, set: e } = Ht([]);
1136
605
  return {
1137
- subscribe: t,
1138
- set: e
1139
- };
1140
- }, Pn = (t, e, n, o) => {
1141
- const { hover: i, selection: s, store: a, viewport: r } = t, l = /* @__PURE__ */ new Map();
1142
- let d = [], g;
1143
- const u = (b, x) => {
1144
- l.has(b) ? l.get(b).push(x) : l.set(b, [x]);
1145
- }, h = (b, x) => {
1146
- const m = l.get(b);
1147
- if (m) {
1148
- const c = m.indexOf(x);
1149
- c !== -1 && m.splice(c, 1);
1150
- }
1151
- }, A = (b, x, m) => {
1152
- l.has(b) && setTimeout(() => {
1153
- l.get(b).forEach((c) => {
1154
- if (n) {
1155
- const y = Array.isArray(x) ? x.map((S) => n.serialize(S)) : n.serialize(x), C = m ? m instanceof PointerEvent ? m : n.serialize(m) : void 0;
1156
- c(y, C);
1157
- } else
1158
- c(x, m);
606
+ destroy,
607
+ setVisible,
608
+ redraw
609
+ };
610
+ };
611
+ const createHighlightsRenderer = (container, state, viewport) => createBaseRenderer(container, state, viewport, createRenderer$1());
612
+ const computeZIndex = (rect, all) => {
613
+ 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;
614
+ const getLength = (h) => h.rects.reduce((total, rect2) => total + rect2.width, 0);
615
+ const intersecting = all.filter(({ rects }) => rects.some((r) => intersects(rect, r)));
616
+ intersecting.sort((a, b) => getLength(b) - getLength(a));
617
+ return intersecting.findIndex((h) => h.rects.includes(rect));
618
+ };
619
+ const createRenderer = (container) => {
620
+ container.classList.add("r6o-annotatable");
621
+ const highlightLayer = document.createElement("div");
622
+ highlightLayer.className = "r6o-span-highlight-layer";
623
+ container.insertBefore(highlightLayer, container.firstChild);
624
+ let currentRendered = [];
625
+ const redraw = (highlights, viewportBounds, currentStyle, painter, lazy) => {
626
+ const noChanges = dequal(currentRendered, highlights);
627
+ const shouldRedraw = !(noChanges && lazy);
628
+ if (!painter && !shouldRedraw) return;
629
+ if (shouldRedraw)
630
+ highlightLayer.innerHTML = "";
631
+ const sorted = [...highlights].sort((highlightA, highlightB) => {
632
+ const { annotation: { target: { created: createdA } } } = highlightA;
633
+ const { annotation: { target: { created: createdB } } } = highlightB;
634
+ return createdA && createdB ? createdA.getTime() - createdB.getTime() : 0;
635
+ });
636
+ sorted.forEach((highlight) => {
637
+ highlight.rects.map((rect) => {
638
+ const zIndex = computeZIndex(rect, highlights);
639
+ const style = paint(highlight, viewportBounds, currentStyle, painter, zIndex);
640
+ if (shouldRedraw) {
641
+ const span = document.createElement("span");
642
+ span.className = "r6o-annotation";
643
+ span.dataset.annotation = highlight.annotation.id;
644
+ span.style.left = `${rect.x}px`;
645
+ span.style.top = `${rect.y}px`;
646
+ span.style.width = `${rect.width}px`;
647
+ span.style.height = `${rect.height}px`;
648
+ span.style.backgroundColor = 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();
649
+ if (style.underlineStyle)
650
+ span.style.borderStyle = style.underlineStyle;
651
+ if (style.underlineColor)
652
+ span.style.borderColor = style.underlineColor;
653
+ if (style.underlineThickness)
654
+ span.style.borderBottomWidth = `${style.underlineThickness}px`;
655
+ if (style.underlineOffset)
656
+ span.style.paddingBottom = `${style.underlineOffset}px`;
657
+ highlightLayer.appendChild(span);
658
+ }
1159
659
  });
1160
- }, 1);
1161
- };
1162
- s.subscribe(({ selected: b }) => {
1163
- if (!(d.length === 0 && b.length === 0)) {
1164
- if (d.length === 0 && b.length > 0)
1165
- d = b.map(({ id: x }) => a.getAnnotation(x));
1166
- else if (d.length > 0 && b.length === 0)
1167
- d.forEach((x) => {
1168
- const m = a.getAnnotation(x.id);
1169
- m && !Q(m, x) && A("updateAnnotation", m, x);
1170
- }), d = [];
1171
- else {
1172
- const x = new Set(d.map((c) => c.id)), m = new Set(b.map(({ id: c }) => c));
1173
- d.filter((c) => !m.has(c.id)).forEach((c) => {
1174
- const y = a.getAnnotation(c.id);
1175
- y && !Q(y, c) && A("updateAnnotation", y, c);
1176
- }), d = [
1177
- // Remove annotations that were deselected
1178
- ...d.filter((c) => m.has(c.id)),
1179
- // Add editable annotations that were selected
1180
- ...b.filter(({ id: c }) => !x.has(c)).map(({ id: c }) => a.getAnnotation(c))
1181
- ];
1182
- }
1183
- A("selectionChanged", d);
1184
- }
1185
- }), i.subscribe((b) => {
1186
- !g && b ? A("mouseEnterAnnotation", a.getAnnotation(b)) : g && !b ? A("mouseLeaveAnnotation", a.getAnnotation(g)) : g && b && (A("mouseLeaveAnnotation", a.getAnnotation(g)), A("mouseEnterAnnotation", a.getAnnotation(b))), g = b;
1187
- }), r == null || r.subscribe((b) => A("viewportIntersect", b.map((x) => a.getAnnotation(x)))), a.observe((b) => {
1188
- const { created: x, deleted: m } = b.changes;
1189
- (x || []).forEach((c) => A("createAnnotation", c)), (m || []).forEach((c) => A("deleteAnnotation", c)), (b.changes.updated || []).filter((c) => [
1190
- ...c.bodiesCreated || [],
1191
- ...c.bodiesDeleted || [],
1192
- ...c.bodiesUpdated || []
1193
- ].length > 0).forEach(({ oldValue: c, newValue: y }) => {
1194
- const C = d.find((S) => S.id === c.id) || c;
1195
- d = d.map((S) => S.id === c.id ? y : S), A("updateAnnotation", y, C);
1196
660
  });
1197
- }, { origin: k.LOCAL }), a.observe((b) => {
1198
- if (d) {
1199
- const x = new Set(d.map((c) => c.id)), m = (b.changes.updated || []).filter(({ newValue: c }) => x.has(c.id)).map(({ newValue: c }) => c);
1200
- m.length > 0 && (d = d.map((c) => m.find((C) => C.id === c.id) || c));
1201
- }
1202
- }, { origin: k.REMOTE });
1203
- const p = (b) => (x) => {
1204
- const { updated: m } = x;
1205
- b ? (m || []).forEach((c) => A("updateAnnotation", c.oldValue, c.newValue)) : (m || []).forEach((c) => A("updateAnnotation", c.newValue, c.oldValue));
1206
- };
1207
- return e.on("undo", p(!0)), e.on("redo", p(!1)), { on: u, off: h, emit: A };
1208
- }, Xn = (t) => (e) => e.reduce((n, o) => {
1209
- const { parsed: i, error: s } = t.parse(o);
1210
- return s ? {
1211
- parsed: n.parsed,
1212
- failed: [...n.failed, o]
1213
- } : i ? {
1214
- parsed: [...n.parsed, i],
1215
- failed: n.failed
1216
- } : {
1217
- ...n
1218
- };
1219
- }, { parsed: [], failed: [] }), $n = (t, e, n) => {
1220
- const { store: o, selection: i } = t, s = (m) => {
1221
- if (n) {
1222
- const { parsed: c, error: y } = n.parse(m);
1223
- c ? o.addAnnotation(c, k.REMOTE) : console.error(y);
1224
- } else
1225
- o.addAnnotation(It(m), k.REMOTE);
1226
- }, a = () => i.clear(), r = () => o.clear(), l = (m) => {
1227
- const c = o.getAnnotation(m);
1228
- return n && c ? n.serialize(c) : c;
1229
- }, d = () => n ? o.all().map(n.serialize) : o.all(), g = () => {
1230
- var m;
1231
- const c = (((m = i.selected) == null ? void 0 : m.map((y) => y.id)) || []).map((y) => o.getAnnotation(y)).filter(Boolean);
1232
- return n ? c.map(n.serialize) : c;
1233
- }, u = (m, c = !0) => fetch(m).then((y) => y.json()).then((y) => (A(y, c), y)), h = (m) => {
1234
- if (typeof m == "string") {
1235
- const c = o.getAnnotation(m);
1236
- if (o.deleteAnnotation(m), c)
1237
- return n ? n.serialize(c) : c;
1238
- } else {
1239
- const c = n ? n.parse(m).parsed : m;
1240
- if (c)
1241
- return o.deleteAnnotation(c), m;
1242
- }
1243
- }, A = (m, c = !0) => {
1244
- if (n) {
1245
- const y = n.parseAll || Xn(n), { parsed: C, failed: S } = y(m);
1246
- S.length > 0 && console.warn(`Discarded ${S.length} invalid annotations`, S), o.bulkAddAnnotation(C, c, k.REMOTE);
1247
- } else
1248
- o.bulkAddAnnotation(m.map(It), c, k.REMOTE);
1249
- }, p = (m, c) => {
1250
- m ? i.setSelected(m, c) : i.clear();
1251
- }, b = (m) => {
1252
- i.clear(), i.setUserSelectAction(m);
1253
- }, x = (m) => {
1254
- if (n) {
1255
- const c = n.parse(m).parsed, y = n.serialize(o.getAnnotation(c.id));
1256
- return o.updateAnnotation(c), y;
1257
- } else {
1258
- const c = o.getAnnotation(m.id);
1259
- return o.updateAnnotation(It(m)), c;
1260
- }
661
+ currentRendered = highlights;
662
+ };
663
+ const setVisible = (visible) => {
664
+ if (visible)
665
+ highlightLayer.classList.remove("hidden");
666
+ else
667
+ highlightLayer.classList.add("hidden");
668
+ };
669
+ const destroy = () => {
670
+ highlightLayer.remove();
1261
671
  };
1262
672
  return {
1263
- addAnnotation: s,
1264
- cancelSelected: a,
1265
- canRedo: e.canRedo,
1266
- canUndo: e.canUndo,
1267
- clearAnnotations: r,
1268
- getAnnotationById: l,
1269
- getAnnotations: d,
1270
- getHistory: e.getHistory,
1271
- getSelected: g,
1272
- loadAnnotations: u,
1273
- redo: e.redo,
1274
- removeAnnotation: h,
1275
- setAnnotations: A,
1276
- setSelected: p,
1277
- setUserSelectAction: b,
1278
- undo: e.undo,
1279
- updateAnnotation: x
1280
- };
1281
- }, Hn = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
1282
- let jn = (t) => crypto.getRandomValues(new Uint8Array(t)), zn = (t, e, n) => {
1283
- let o = (2 << Math.log2(t.length - 1)) - 1, i = -~(1.6 * o * e / t.length);
1284
- return (s = e) => {
1285
- let a = "";
1286
- for (; ; ) {
1287
- let r = n(i), l = i | 0;
1288
- for (; l--; )
1289
- if (a += t[r[l] & o] || "", a.length >= s) return a;
1290
- }
673
+ destroy,
674
+ redraw,
675
+ setVisible
1291
676
  };
1292
- }, Fn = (t, e = 21) => zn(t, e | 0, jn), Wn = (t = 21) => {
1293
- let e = "", n = crypto.getRandomValues(new Uint8Array(t |= 0));
1294
- for (; t--; )
1295
- e += Hn[n[t] & 63];
1296
- return e;
1297
677
  };
1298
- const qn = () => ({ isGuest: !0, id: Fn("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_", 20)() }), Gn = (t) => {
1299
- const e = JSON.stringify(t);
1300
- let n = 0;
1301
- for (let o = 0, i = e.length; o < i; o++) {
1302
- let s = e.charCodeAt(o);
1303
- n = (n << 5) - n + s, n |= 0;
1304
- }
1305
- return `${n}`;
1306
- }, xe = (t) => t ? typeof t == "object" ? { ...t } : t : void 0, Qn = (t, e) => (Array.isArray(t) ? t : [t]).map((n) => {
1307
- const { id: o, type: i, purpose: s, value: a, created: r, modified: l, creator: d, ...g } = n;
1308
- return {
1309
- id: o || `temp-${Gn(n)}`,
1310
- annotation: e,
1311
- type: i,
1312
- purpose: s,
1313
- value: a,
1314
- creator: xe(d),
1315
- created: r ? new Date(r) : void 0,
1316
- updated: l ? new Date(l) : void 0,
1317
- ...g
1318
- };
1319
- }), Jn = (t) => t.map((e) => {
1320
- var n;
1321
- const { annotation: o, created: i, updated: s, ...a } = e, r = {
1322
- ...a,
1323
- created: i == null ? void 0 : i.toISOString(),
1324
- modified: s == null ? void 0 : s.toISOString()
1325
- };
1326
- return (n = r.id) != null && n.startsWith("temp-") && delete r.id, r;
678
+ const createSpansRenderer = (container, state, viewport) => createBaseRenderer(container, state, viewport, createRenderer(container));
679
+ const W3CTextFormat = (source, container) => ({
680
+ parse: (serialized) => parseW3CTextAnnotation(serialized),
681
+ serialize: (annotation) => serializeW3CTextAnnotation(annotation, source, container)
1327
682
  });
1328
- Wn();
1329
- const No = (t, e) => ({
1330
- parse: (n) => eo(n),
1331
- serialize: (n) => no(n, t, e)
1332
- }), Zn = (t) => t.quote !== void 0 && t.start !== void 0 && t.end !== void 0, to = (t) => {
683
+ const isTextSelector = (selector) => selector.quote !== void 0 && selector.start !== void 0 && selector.end !== void 0;
684
+ const parseW3CTextTargets = (annotation) => {
1333
685
  const {
1334
- id: e,
1335
- creator: n,
1336
- created: o,
1337
- modified: i,
1338
- target: s
1339
- } = t, a = Array.isArray(s) ? s : [s];
1340
- if (a.length === 0)
1341
- return { error: Error(`No targets found for annotation: ${t.id}`) };
1342
- const r = {
1343
- creator: xe(n),
1344
- created: o ? new Date(o) : void 0,
1345
- updated: i ? new Date(i) : void 0,
1346
- annotation: e,
686
+ id: annotationId,
687
+ creator,
688
+ created,
689
+ modified,
690
+ target
691
+ } = annotation;
692
+ const w3cTargets = Array.isArray(target) ? target : [target];
693
+ if (w3cTargets.length === 0) {
694
+ return { error: Error(`No targets found for annotation: ${annotation.id}`) };
695
+ }
696
+ const parsed = {
697
+ creator: parseW3CUser(creator),
698
+ created: created ? new Date(created) : void 0,
699
+ updated: modified ? new Date(modified) : void 0,
700
+ annotation: annotationId,
1347
701
  selector: [],
1348
702
  // @ts-expect-error: `styleClass` is not part of the core `TextAnnotationTarget` type
1349
- styleClass: "styleClass" in a[0] ? a[0].styleClass : void 0
703
+ styleClass: "styleClass" in w3cTargets[0] ? w3cTargets[0].styleClass : void 0
1350
704
  };
1351
- for (const l of a) {
1352
- const g = (Array.isArray(l.selector) ? l.selector : [l.selector]).reduce((u, h) => {
1353
- switch (h.type) {
705
+ for (const w3cTarget of w3cTargets) {
706
+ const w3cSelectors = Array.isArray(w3cTarget.selector) ? w3cTarget.selector : [w3cTarget.selector];
707
+ const selector = w3cSelectors.reduce((s, w3cSelector) => {
708
+ switch (w3cSelector.type) {
1354
709
  case "TextQuoteSelector":
1355
- u.quote = h.exact;
710
+ s.quote = w3cSelector.exact;
1356
711
  break;
1357
712
  case "TextPositionSelector":
1358
- u.start = h.start, u.end = h.end;
713
+ s.start = w3cSelector.start;
714
+ s.end = w3cSelector.end;
1359
715
  break;
1360
716
  }
1361
- return u;
717
+ return s;
1362
718
  }, {});
1363
- if (Zn(g))
1364
- r.selector.push(
719
+ if (isTextSelector(selector)) {
720
+ parsed.selector.push(
1365
721
  {
1366
- ...g,
1367
- id: l.id,
722
+ ...selector,
723
+ id: w3cTarget.id,
1368
724
  // @ts-expect-error: `scope` is not part of the core `TextSelector` type
1369
- scope: l.scope
725
+ scope: w3cTarget.scope
1370
726
  }
1371
727
  );
1372
- else {
1373
- const u = [
1374
- g.start ? void 0 : "TextPositionSelector",
1375
- g.quote ? void 0 : "TextQuoteSelector"
728
+ } else {
729
+ const missingTypes = [
730
+ !selector.start ? "TextPositionSelector" : void 0,
731
+ !selector.quote ? "TextQuoteSelector" : void 0
1376
732
  ].filter(Boolean);
1377
- return { error: Error(`Missing selector types: ${u.join(" and ")} for annotation: ${t.id}`) };
733
+ return { error: Error(`Missing selector types: ${missingTypes.join(" and ")} for annotation: ${annotation.id}`) };
1378
734
  }
1379
735
  }
1380
- return { parsed: r };
1381
- }, eo = (t) => {
1382
- const e = t.id || be(), {
1383
- creator: n,
1384
- created: o,
1385
- modified: i,
1386
- body: s,
1387
- ...a
1388
- } = t, r = Qn(s, e), l = to(t);
1389
- return "error" in l ? { error: l.error } : {
736
+ return { parsed };
737
+ };
738
+ const parseW3CTextAnnotation = (annotation) => {
739
+ const annotationId = annotation.id || v4();
740
+ const {
741
+ creator,
742
+ created,
743
+ modified,
744
+ body,
745
+ ...rest
746
+ } = annotation;
747
+ const bodies = parseW3CBodies(body, annotationId);
748
+ const target = parseW3CTextTargets(annotation);
749
+ const parseResult = "error" in target ? { error: target.error } : {
1390
750
  parsed: {
1391
- ...a,
1392
- id: e,
1393
- bodies: r,
1394
- target: l.parsed
751
+ ...rest,
752
+ id: annotationId,
753
+ bodies,
754
+ target: target.parsed
1395
755
  }
1396
756
  };
1397
- }, no = (t, e, n) => {
1398
- const { bodies: o, target: i, ...s } = t, {
1399
- selector: a,
1400
- creator: r,
1401
- created: l,
1402
- updated: d,
1403
- ...g
1404
- } = i, u = a.map((h) => {
1405
- const { id: A, quote: p, start: b, end: x, range: m } = h, { prefix: c, suffix: y } = Ue(m, n), C = [{
757
+ return parseResult;
758
+ };
759
+ const serializeW3CTextAnnotation = (annotation, source, container) => {
760
+ const { bodies, target, ...rest } = annotation;
761
+ const {
762
+ selector,
763
+ creator,
764
+ created,
765
+ updated,
766
+ ...targetRest
767
+ } = target;
768
+ const w3cTargets = selector.map((s) => {
769
+ const { id, quote, start, end, range } = s;
770
+ const { prefix, suffix } = getQuoteContext(range, container);
771
+ const w3cSelectors = [{
1406
772
  type: "TextQuoteSelector",
1407
- exact: p,
1408
- prefix: c,
1409
- suffix: y
773
+ exact: quote,
774
+ prefix,
775
+ suffix
1410
776
  }, {
1411
777
  type: "TextPositionSelector",
1412
- start: b,
1413
- end: x
778
+ start,
779
+ end
1414
780
  }];
1415
781
  return {
1416
- ...g,
1417
- id: A,
782
+ ...targetRest,
783
+ id,
1418
784
  // @ts-expect-error: `scope` is not part of the core `TextSelector` type
1419
- scope: "scope" in h ? h.scope : void 0,
1420
- source: e,
1421
- selector: C
785
+ scope: "scope" in s ? s.scope : void 0,
786
+ source,
787
+ selector: w3cSelectors
1422
788
  };
1423
789
  });
1424
790
  return {
1425
- ...s,
791
+ ...rest,
1426
792
  "@context": "http://www.w3.org/ns/anno.jsonld",
1427
- id: t.id,
793
+ id: annotation.id,
1428
794
  type: "Annotation",
1429
- body: Jn(t.bodies),
1430
- creator: r,
1431
- created: l == null ? void 0 : l.toISOString(),
1432
- modified: d == null ? void 0 : d.toISOString(),
1433
- target: u
795
+ body: serializeW3CBodies(annotation.bodies),
796
+ creator,
797
+ created: created == null ? void 0 : created.toISOString(),
798
+ modified: updated == null ? void 0 : updated.toISOString(),
799
+ target: w3cTargets
1434
800
  };
1435
801
  };
1436
- function ve(t, e, n = 0, o = t.length - 1, i = oo) {
1437
- for (; o > n; ) {
1438
- if (o - n > 600) {
1439
- const l = o - n + 1, d = e - n + 1, g = Math.log(l), u = 0.5 * Math.exp(2 * g / 3), h = 0.5 * Math.sqrt(g * u * (l - u) / l) * (d - l / 2 < 0 ? -1 : 1), A = Math.max(n, Math.floor(e - d * u / l + h)), p = Math.min(o, Math.floor(e + (l - d) * u / l + h));
1440
- ve(t, e, A, p, i);
1441
- }
1442
- const s = t[e];
1443
- let a = n, r = o;
1444
- for (ot(t, n, e), i(t[o], s) > 0 && ot(t, n, o); a < r; ) {
1445
- for (ot(t, a, r), a++, r--; i(t[a], s) < 0; ) a++;
1446
- for (; i(t[r], s) > 0; ) r--;
1447
- }
1448
- i(t[n], s) === 0 ? ot(t, n, r) : (r++, ot(t, r, o)), r <= e && (n = r + 1), e <= r && (o = r - 1);
1449
- }
1450
- }
1451
- function ot(t, e, n) {
1452
- const o = t[e];
1453
- t[e] = t[n], t[n] = o;
1454
- }
1455
- function oo(t, e) {
1456
- return t < e ? -1 : t > e ? 1 : 0;
1457
- }
1458
- class io {
1459
- constructor(e = 9) {
1460
- this._maxEntries = Math.max(4, e), this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4)), this.clear();
1461
- }
1462
- all() {
1463
- return this._all(this.data, []);
1464
- }
1465
- search(e) {
1466
- let n = this.data;
1467
- const o = [];
1468
- if (!wt(e, n)) return o;
1469
- const i = this.toBBox, s = [];
1470
- for (; n; ) {
1471
- for (let a = 0; a < n.children.length; a++) {
1472
- const r = n.children[a], l = n.leaf ? i(r) : r;
1473
- wt(e, l) && (n.leaf ? o.push(r) : Ut(e, l) ? this._all(r, o) : s.push(r));
1474
- }
1475
- n = s.pop();
1476
- }
1477
- return o;
1478
- }
1479
- collides(e) {
1480
- let n = this.data;
1481
- if (!wt(e, n)) return !1;
1482
- const o = [];
1483
- for (; n; ) {
1484
- for (let i = 0; i < n.children.length; i++) {
1485
- const s = n.children[i], a = n.leaf ? this.toBBox(s) : s;
1486
- if (wt(e, a)) {
1487
- if (n.leaf || Ut(e, a)) return !0;
1488
- o.push(s);
1489
- }
1490
- }
1491
- n = o.pop();
1492
- }
1493
- return !1;
1494
- }
1495
- load(e) {
1496
- if (!(e && e.length)) return this;
1497
- if (e.length < this._minEntries) {
1498
- for (let o = 0; o < e.length; o++)
1499
- this.insert(e[o]);
1500
- return this;
1501
- }
1502
- let n = this._build(e.slice(), 0, e.length - 1, 0);
1503
- if (!this.data.children.length)
1504
- this.data = n;
1505
- else if (this.data.height === n.height)
1506
- this._splitRoot(this.data, n);
1507
- else {
1508
- if (this.data.height < n.height) {
1509
- const o = this.data;
1510
- this.data = n, n = o;
1511
- }
1512
- this._insert(n, this.data.height - n.height - 1, !0);
1513
- }
1514
- return this;
1515
- }
1516
- insert(e) {
1517
- return e && this._insert(e, this.data.height - 1), this;
1518
- }
1519
- clear() {
1520
- return this.data = tt([]), this;
1521
- }
1522
- remove(e, n) {
1523
- if (!e) return this;
1524
- let o = this.data;
1525
- const i = this.toBBox(e), s = [], a = [];
1526
- let r, l, d;
1527
- for (; o || s.length; ) {
1528
- if (o || (o = s.pop(), l = s[s.length - 1], r = a.pop(), d = !0), o.leaf) {
1529
- const g = so(e, o.children, n);
1530
- if (g !== -1)
1531
- return o.children.splice(g, 1), s.push(o), this._condense(s), this;
1532
- }
1533
- !d && !o.leaf && Ut(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;
1534
- }
1535
- return this;
1536
- }
1537
- toBBox(e) {
1538
- return e;
1539
- }
1540
- compareMinX(e, n) {
1541
- return e.minX - n.minX;
1542
- }
1543
- compareMinY(e, n) {
1544
- return e.minY - n.minY;
1545
- }
1546
- toJSON() {
1547
- return this.data;
1548
- }
1549
- fromJSON(e) {
1550
- return this.data = e, this;
1551
- }
1552
- _all(e, n) {
1553
- const o = [];
1554
- for (; e; )
1555
- e.leaf ? n.push(...e.children) : o.push(...e.children), e = o.pop();
1556
- return n;
1557
- }
1558
- _build(e, n, o, i) {
1559
- const s = o - n + 1;
1560
- let a = this._maxEntries, r;
1561
- if (s <= a)
1562
- return r = tt(e.slice(n, o + 1)), Z(r, this.toBBox), r;
1563
- i || (i = Math.ceil(Math.log(s) / Math.log(a)), a = Math.ceil(s / Math.pow(a, i - 1))), r = tt([]), r.leaf = !1, r.height = i;
1564
- const l = Math.ceil(s / a), d = l * Math.ceil(Math.sqrt(a));
1565
- re(e, n, o, d, this.compareMinX);
1566
- for (let g = n; g <= o; g += d) {
1567
- const u = Math.min(g + d - 1, o);
1568
- re(e, g, u, l, this.compareMinY);
1569
- for (let h = g; h <= u; h += l) {
1570
- const A = Math.min(h + l - 1, u);
1571
- r.children.push(this._build(e, h, A, i - 1));
1572
- }
1573
- }
1574
- return Z(r, this.toBBox), r;
1575
- }
1576
- _chooseSubtree(e, n, o, i) {
1577
- for (; i.push(n), !(n.leaf || i.length - 1 === o); ) {
1578
- let s = 1 / 0, a = 1 / 0, r;
1579
- for (let l = 0; l < n.children.length; l++) {
1580
- const d = n.children[l], g = _t(d), u = co(e, d) - g;
1581
- u < a ? (a = u, s = g < s ? g : s, r = d) : u === a && g < s && (s = g, r = d);
1582
- }
1583
- n = r || n.children[0];
1584
- }
1585
- return n;
1586
- }
1587
- _insert(e, n, o) {
1588
- const i = o ? e : this.toBBox(e), s = [], a = this._chooseSubtree(i, this.data, n, s);
1589
- for (a.children.push(e), at(a, i); n >= 0 && s[n].children.length > this._maxEntries; )
1590
- this._split(s, n), n--;
1591
- this._adjustParentBBoxes(i, s, n);
1592
- }
1593
- // split overflowed node into two
1594
- _split(e, n) {
1595
- const o = e[n], i = o.children.length, s = this._minEntries;
1596
- this._chooseSplitAxis(o, s, i);
1597
- const a = this._chooseSplitIndex(o, s, i), r = tt(o.children.splice(a, o.children.length - a));
1598
- r.height = o.height, r.leaf = o.leaf, Z(o, this.toBBox), Z(r, this.toBBox), n ? e[n - 1].children.push(r) : this._splitRoot(o, r);
1599
- }
1600
- _splitRoot(e, n) {
1601
- this.data = tt([e, n]), this.data.height = e.height + 1, this.data.leaf = !1, Z(this.data, this.toBBox);
1602
- }
1603
- _chooseSplitIndex(e, n, o) {
1604
- let i, s = 1 / 0, a = 1 / 0;
1605
- for (let r = n; r <= o - n; r++) {
1606
- const l = rt(e, 0, r, this.toBBox), d = rt(e, r, o, this.toBBox), g = lo(l, d), u = _t(l) + _t(d);
1607
- g < s ? (s = g, i = r, a = u < a ? u : a) : g === s && u < a && (a = u, i = r);
1608
- }
1609
- return i || o - n;
1610
- }
1611
- // sorts node children by the best axis for split
1612
- _chooseSplitAxis(e, n, o) {
1613
- const i = e.leaf ? this.compareMinX : ro, s = e.leaf ? this.compareMinY : ao, a = this._allDistMargin(e, n, o, i), r = this._allDistMargin(e, n, o, s);
1614
- a < r && e.children.sort(i);
1615
- }
1616
- // total margin of all possible split distributions where each node is at least m full
1617
- _allDistMargin(e, n, o, i) {
1618
- e.children.sort(i);
1619
- const s = this.toBBox, a = rt(e, 0, n, s), r = rt(e, o - n, o, s);
1620
- let l = bt(a) + bt(r);
1621
- for (let d = n; d < o - n; d++) {
1622
- const g = e.children[d];
1623
- at(a, e.leaf ? s(g) : g), l += bt(a);
1624
- }
1625
- for (let d = o - n - 1; d >= n; d--) {
1626
- const g = e.children[d];
1627
- at(r, e.leaf ? s(g) : g), l += bt(r);
1628
- }
1629
- return l;
1630
- }
1631
- _adjustParentBBoxes(e, n, o) {
1632
- for (let i = o; i >= 0; i--)
1633
- at(n[i], e);
1634
- }
1635
- _condense(e) {
1636
- for (let n = e.length - 1, o; n >= 0; n--)
1637
- e[n].children.length === 0 ? n > 0 ? (o = e[n - 1].children, o.splice(o.indexOf(e[n]), 1)) : this.clear() : Z(e[n], this.toBBox);
1638
- }
1639
- }
1640
- function so(t, e, n) {
1641
- if (!n) return e.indexOf(t);
1642
- for (let o = 0; o < e.length; o++)
1643
- if (n(t, e[o])) return o;
1644
- return -1;
1645
- }
1646
- function Z(t, e) {
1647
- rt(t, 0, t.children.length, e, t);
1648
- }
1649
- function rt(t, e, n, o, i) {
1650
- i || (i = tt(null)), i.minX = 1 / 0, i.minY = 1 / 0, i.maxX = -1 / 0, i.maxY = -1 / 0;
1651
- for (let s = e; s < n; s++) {
1652
- const a = t.children[s];
1653
- at(i, t.leaf ? o(a) : a);
1654
- }
1655
- return i;
1656
- }
1657
- function at(t, e) {
1658
- 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;
1659
- }
1660
- function ro(t, e) {
1661
- return t.minX - e.minX;
1662
- }
1663
- function ao(t, e) {
1664
- return t.minY - e.minY;
1665
- }
1666
- function _t(t) {
1667
- return (t.maxX - t.minX) * (t.maxY - t.minY);
1668
- }
1669
- function bt(t) {
1670
- return t.maxX - t.minX + (t.maxY - t.minY);
1671
- }
1672
- function co(t, e) {
1673
- 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));
1674
- }
1675
- function lo(t, e) {
1676
- 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);
1677
- return Math.max(0, i - n) * Math.max(0, s - o);
1678
- }
1679
- function Ut(t, e) {
1680
- return t.minX <= e.minX && t.minY <= e.minY && e.maxX <= t.maxX && e.maxY <= t.maxY;
1681
- }
1682
- function wt(t, e) {
1683
- return e.minX <= t.maxX && e.minY <= t.maxY && e.maxX >= t.minX && e.maxY >= t.minY;
1684
- }
1685
- function tt(t) {
1686
- return {
1687
- children: t,
1688
- height: 1,
1689
- leaf: !0,
1690
- minX: 1 / 0,
1691
- minY: 1 / 0,
1692
- maxX: -1 / 0,
1693
- maxY: -1 / 0
1694
- };
1695
- }
1696
- function re(t, e, n, o, i) {
1697
- const s = [e, n];
1698
- for (; s.length; ) {
1699
- if (n = s.pop(), e = s.pop(), n - e <= o) continue;
1700
- const a = e + Math.ceil((n - e) / o / 2) * o;
1701
- ve(t, a, e, n, i), s.push(e, a, a, n);
1702
- }
1703
- }
1704
- let uo = () => ({
1705
- emit(t, ...e) {
1706
- for (let n = this.events[t] || [], o = 0, i = n.length; o < i; o++)
1707
- n[o](...e);
1708
- },
1709
- events: {},
1710
- on(t, e) {
1711
- var n;
1712
- return ((n = this.events)[t] || (n[t] = [])).push(e), () => {
1713
- var o;
1714
- this.events[t] = (o = this.events[t]) == null ? void 0 : o.filter((i) => e !== i);
1715
- };
1716
- }
1717
- });
1718
- const fo = (t, e) => {
1719
- const n = new io(), o = /* @__PURE__ */ new Map(), i = uo(), s = (y, C) => {
1720
- const S = y.selector.flatMap((B) => {
1721
- const T = F([B]) ? B.range : fe(B, e).range;
1722
- return Array.from(T.getClientRects());
1723
- }), L = Pe(S).map((B) => je(B, C));
1724
- return L.map((B) => {
1725
- const { x: T, y: R, width: w, height: v } = B;
802
+ const createSpatialTree = (store, container) => {
803
+ const tree = new RBush();
804
+ const index = /* @__PURE__ */ new Map();
805
+ const emitter = createNanoEvents();
806
+ const toItems = (target, offset) => {
807
+ const rects = target.selector.flatMap((s) => {
808
+ const revivedRange = isRevived([s]) ? s.range : reviveSelector(s, container).range;
809
+ return Array.from(revivedRange.getClientRects());
810
+ });
811
+ const merged = mergeClientRects(rects).map((rect) => toParentBounds(rect, offset));
812
+ return merged.map((rect) => {
813
+ const { x, y, width, height } = rect;
1726
814
  return {
1727
- minX: T,
1728
- minY: R,
1729
- maxX: T + w,
1730
- maxY: R + v,
815
+ minX: x,
816
+ minY: y,
817
+ maxX: x + width,
818
+ maxY: y + height,
1731
819
  annotation: {
1732
- id: y.annotation,
1733
- rects: L
820
+ id: target.annotation,
821
+ rects: merged
1734
822
  }
1735
823
  };
1736
824
  });
1737
- }, a = () => [...o.values()], r = () => {
1738
- n.clear(), o.clear();
1739
- }, l = (y) => {
1740
- const C = s(y, e.getBoundingClientRect());
1741
- C.length !== 0 && (C.forEach((S) => n.insert(S)), o.set(y.annotation, C));
1742
- }, d = (y) => {
1743
- const C = o.get(y.annotation);
1744
- C && (C.forEach((S) => n.remove(S)), o.delete(y.annotation));
1745
- }, g = (y) => {
1746
- d(y), l(y);
1747
- }, u = (y, C = !0) => {
1748
- C && r();
1749
- const S = e.getBoundingClientRect(), L = y.map((T) => ({ target: T, rects: s(T, S) }));
1750
- L.forEach(({ target: T, rects: R }) => {
1751
- R.length > 0 && o.set(T.annotation, R);
1752
- });
1753
- const B = L.flatMap(({ rects: T }) => T);
1754
- n.load(B);
1755
- }, h = (y, C, S = !1) => {
1756
- const L = n.search({
1757
- minX: y,
1758
- minY: C,
1759
- maxX: y,
1760
- maxY: C
1761
- }), B = (T) => T.annotation.rects.reduce((R, w) => R + w.width * w.height, 0);
1762
- return L.length > 0 ? (L.sort((T, R) => B(T) - B(R)), S ? L.map((T) => T.annotation.id) : [L[0].annotation.id]) : [];
1763
- }, A = (y) => {
1764
- const C = p(y);
1765
- if (C.length === 0)
1766
- return;
1767
- let S = C[0].left, L = C[0].top, B = C[0].right, T = C[0].bottom;
1768
- for (let R = 1; R < C.length; R++) {
1769
- const w = C[R];
1770
- S = Math.min(S, w.left), L = Math.min(L, w.top), B = Math.max(B, w.right), T = Math.max(T, w.bottom);
1771
- }
1772
- return new DOMRect(S, L, B - S, T - L);
1773
- }, p = (y) => {
1774
- const C = o.get(y);
1775
- return C ? C[0].annotation.rects : [];
1776
825
  };
1777
- return {
1778
- all: a,
1779
- clear: r,
1780
- getAt: h,
1781
- getAnnotationBounds: A,
1782
- getAnnotationRects: p,
1783
- getIntersecting: (y, C, S, L) => {
1784
- const B = n.search({ minX: y, minY: C, maxX: S, maxY: L }), T = new Set(B.map((R) => R.annotation.id));
1785
- return Array.from(T).map((R) => ({
1786
- annotation: t.getAnnotation(R),
1787
- rects: p(R)
1788
- })).filter((R) => !!R.annotation);
1789
- },
1790
- insert: l,
1791
- recalculate: () => {
1792
- u(t.all().map((y) => y.target), !0), i.emit("recalculate");
1793
- },
1794
- remove: d,
1795
- set: u,
1796
- size: () => n.all().length,
1797
- update: g,
1798
- on: (y, C) => i.on(y, C)
1799
- };
1800
- }, ho = (t, e) => {
1801
- const n = Un(), o = fo(n, t), i = Sn(n, e.userSelectAction, e.adapter), s = vn(n), a = Kn(), r = (c, y = k.LOCAL) => {
1802
- const C = Ct(c, t), S = F(C.target.selector);
1803
- return S && n.addAnnotation(C, y), S;
1804
- }, l = (c, y = !0, C = k.LOCAL) => {
1805
- const S = c.map((B) => Ct(B, t)), L = S.filter((B) => !F(B.target.selector));
1806
- return n.bulkAddAnnotation(S, y, C), L;
1807
- }, d = (c, y = k.LOCAL) => {
1808
- const C = c.map((L) => Ct(L, t)), S = C.filter((L) => !F(L.target.selector));
1809
- return C.forEach((L) => {
1810
- n.getAnnotation(L.id) ? n.updateAnnotation(L, y) : n.addAnnotation(L, y);
1811
- }), S;
1812
- }, g = (c, y = k.LOCAL) => {
1813
- const C = vt(c, t);
1814
- n.updateTarget(C, y);
1815
- }, u = (c, y = k.LOCAL) => {
1816
- const C = c.map((S) => vt(S, t));
1817
- n.bulkUpdateTargets(C, y);
1818
- };
1819
- function h(c, y, C, S) {
1820
- const L = C || !!S, B = o.getAt(c, y, L).map((R) => n.getAnnotation(R)), T = S ? B.filter(S) : B;
1821
- if (T.length !== 0)
1822
- return C ? T : T[0];
1823
- }
1824
- const A = (c) => o.getAnnotationRects(c).length > 0 ? o.getAnnotationBounds(c) : void 0, p = (c, y, C, S) => o.getIntersecting(c, y, C, S), b = (c) => o.getAnnotationRects(c), x = () => o.recalculate(), m = (c) => o.on("recalculate", c);
1825
- return n.observe(({ changes: c }) => {
1826
- const y = (c.deleted || []).filter((L) => F(L.target.selector)), C = (c.created || []).filter((L) => F(L.target.selector)), S = (c.updated || []).filter((L) => F(L.newValue.target.selector));
1827
- (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), (S == null ? void 0 : S.length) > 0 && S.forEach(({ newValue: L }) => o.update(L.target));
1828
- }), {
1829
- store: {
1830
- ...n,
1831
- addAnnotation: r,
1832
- bulkAddAnnotation: l,
1833
- bulkUpdateTargets: u,
1834
- bulkUpsertAnnotations: d,
1835
- getAnnotationBounds: A,
1836
- getAnnotationRects: b,
1837
- getIntersecting: p,
1838
- getAt: h,
1839
- recalculatePositions: x,
1840
- onRecalculatePositions: m,
1841
- updateTarget: g
1842
- },
1843
- selection: i,
1844
- hover: s,
1845
- viewport: a
1846
- };
1847
- }, po = () => {
1848
- const t = document.createElement("canvas");
1849
- t.width = 2 * window.innerWidth, t.height = 2 * window.innerHeight, t.className = "r6o-presence-layer";
1850
- const e = t.getContext("2d");
1851
- return e.scale(2, 2), e.translate(0.5, 0.5), t;
1852
- }, go = (t, e = {}) => {
1853
- const n = po(), o = n.getContext("2d");
1854
- document.body.appendChild(n);
1855
- const i = /* @__PURE__ */ new Map(), s = (g) => Array.from(i.entries()).filter(([u, h]) => h.presenceKey === g.presenceKey).map(([u, h]) => u);
1856
- return t.on("selectionChange", (g, u) => {
1857
- s(g).forEach((A) => i.delete(A)), u && u.forEach((A) => i.set(A, g));
1858
- }), {
1859
- clear: () => {
1860
- const { width: g, height: u } = n;
1861
- o.clearRect(-0.5, -0.5, g + 1, u + 1);
1862
- },
1863
- destroy: () => {
1864
- n.remove();
1865
- },
1866
- paint: (g, u, h) => {
1867
- e.font && (o.font = e.font);
1868
- const A = i.get(g.annotation.id);
1869
- if (A) {
1870
- const { height: p } = g.rects[0], b = g.rects[0].x + u.left, x = g.rects[0].y + u.top;
1871
- o.fillStyle = A.appearance.color, o.fillRect(b - 2, x - 2.5, 2, p + 5);
1872
- const m = o.measureText(A.appearance.label), c = m.width + 6, y = m.actualBoundingBoxAscent + m.actualBoundingBoxDescent + 8, C = m.fontBoundingBoxAscent ? 8 : 6.5;
1873
- return o.fillRect(b - 2, x - 2.5 - y, c, y), o.fillStyle = "#fff", o.fillText(A.appearance.label, b + 1, x - C), {
1874
- fill: A.appearance.color,
1875
- fillOpacity: h ? 0.45 : 0.18
1876
- };
1877
- }
1878
- },
1879
- reset: () => {
1880
- n.width = 2 * window.innerWidth, n.height = 2 * window.innerHeight;
1881
- const g = n.getContext("2d");
1882
- g.scale(2, 2), g.translate(0.5, 0.5);
826
+ const all = () => [...index.values()];
827
+ const clear = () => {
828
+ tree.clear();
829
+ index.clear();
830
+ };
831
+ const insert = (target) => {
832
+ const rects = toItems(target, container.getBoundingClientRect());
833
+ if (rects.length === 0) return;
834
+ rects.forEach((rect) => tree.insert(rect));
835
+ index.set(target.annotation, rects);
836
+ };
837
+ const remove = (target) => {
838
+ const rects = index.get(target.annotation);
839
+ if (rects) {
840
+ rects.forEach((rect) => tree.remove(rect));
841
+ index.delete(target.annotation);
1883
842
  }
1884
843
  };
1885
- }, Dt = typeof navigator < "u" ? navigator.userAgent.toLowerCase().indexOf("firefox") > 0 : !1;
1886
- function Vt(t, e, n, o) {
1887
- t.addEventListener ? t.addEventListener(e, n, o) : t.attachEvent && t.attachEvent("on".concat(e), n);
1888
- }
1889
- function it(t, e, n, o) {
1890
- t.removeEventListener ? t.removeEventListener(e, n, o) : t.detachEvent && t.detachEvent("on".concat(e), n);
1891
- }
1892
- function Ee(t, e) {
1893
- const n = e.slice(0, e.length - 1);
1894
- for (let o = 0; o < n.length; o++) n[o] = t[n[o].toLowerCase()];
1895
- return n;
1896
- }
1897
- function Se(t) {
1898
- typeof t != "string" && (t = ""), t = t.replace(/\s/g, "");
1899
- const e = t.split(",");
1900
- let n = e.lastIndexOf("");
1901
- for (; n >= 0; )
1902
- e[n - 1] += ",", e.splice(n, 1), n = e.lastIndexOf("");
1903
- return e;
1904
- }
1905
- function mo(t, e) {
1906
- const n = t.length >= e.length ? t : e, o = t.length >= e.length ? e : t;
1907
- let i = !0;
1908
- for (let s = 0; s < n.length; s++)
1909
- o.indexOf(n[s]) === -1 && (i = !1);
1910
- return i;
1911
- }
1912
- const dt = {
1913
- backspace: 8,
1914
- "⌫": 8,
1915
- tab: 9,
1916
- clear: 12,
1917
- enter: 13,
1918
- "↩": 13,
1919
- return: 13,
1920
- esc: 27,
1921
- escape: 27,
1922
- space: 32,
1923
- left: 37,
1924
- up: 38,
1925
- right: 39,
1926
- down: 40,
1927
- del: 46,
1928
- delete: 46,
1929
- ins: 45,
1930
- insert: 45,
1931
- home: 36,
1932
- end: 35,
1933
- pageup: 33,
1934
- pagedown: 34,
1935
- capslock: 20,
1936
- num_0: 96,
1937
- num_1: 97,
1938
- num_2: 98,
1939
- num_3: 99,
1940
- num_4: 100,
1941
- num_5: 101,
1942
- num_6: 102,
1943
- num_7: 103,
1944
- num_8: 104,
1945
- num_9: 105,
1946
- num_multiply: 106,
1947
- num_add: 107,
1948
- num_enter: 108,
1949
- num_subtract: 109,
1950
- num_decimal: 110,
1951
- num_divide: 111,
1952
- "⇪": 20,
1953
- ",": 188,
1954
- ".": 190,
1955
- "/": 191,
1956
- "`": 192,
1957
- "-": Dt ? 173 : 189,
1958
- "=": Dt ? 61 : 187,
1959
- ";": Dt ? 59 : 186,
1960
- "'": 222,
1961
- "[": 219,
1962
- "]": 221,
1963
- "\\": 220
1964
- }, H = {
1965
- // shiftKey
1966
- "⇧": 16,
1967
- shift: 16,
1968
- // altKey
1969
- "⌥": 18,
1970
- alt: 18,
1971
- option: 18,
1972
- // ctrlKey
1973
- "⌃": 17,
1974
- ctrl: 17,
1975
- control: 17,
1976
- // metaKey
1977
- "⌘": 91,
1978
- cmd: 91,
1979
- command: 91
1980
- }, xt = {
1981
- 16: "shiftKey",
1982
- 18: "altKey",
1983
- 17: "ctrlKey",
1984
- 91: "metaKey",
1985
- shiftKey: 16,
1986
- ctrlKey: 17,
1987
- altKey: 18,
1988
- metaKey: 91
1989
- }, K = {
1990
- 16: !1,
1991
- 18: !1,
1992
- 17: !1,
1993
- 91: !1
1994
- }, N = {};
1995
- for (let t = 1; t < 20; t++)
1996
- dt["f".concat(t)] = 111 + t;
1997
- let I = [], lt = null, Ce = "all";
1998
- const z = /* @__PURE__ */ new Map(), ft = (t) => dt[t.toLowerCase()] || H[t.toLowerCase()] || t.toUpperCase().charCodeAt(0), yo = (t) => Object.keys(dt).find((e) => dt[e] === t), bo = (t) => Object.keys(H).find((e) => H[e] === t);
1999
- function Le(t) {
2000
- Ce = t || "all";
2001
- }
2002
- function ut() {
2003
- return Ce || "all";
2004
- }
2005
- function wo() {
2006
- return I.slice(0);
2007
- }
2008
- function Ao() {
2009
- return I.map((t) => yo(t) || bo(t) || String.fromCharCode(t));
2010
- }
2011
- function xo() {
2012
- const t = [];
2013
- return Object.keys(N).forEach((e) => {
2014
- N[e].forEach((n) => {
2015
- let {
2016
- key: o,
2017
- scope: i,
2018
- mods: s,
2019
- shortcut: a
2020
- } = n;
2021
- t.push({
2022
- scope: i,
2023
- shortcut: a,
2024
- mods: s,
2025
- keys: o.split("+").map((r) => ft(r))
2026
- });
844
+ const update = (target) => {
845
+ remove(target);
846
+ insert(target);
847
+ };
848
+ const set = (targets, replace = true) => {
849
+ if (replace)
850
+ clear();
851
+ const offset = container.getBoundingClientRect();
852
+ const rectsByTarget = targets.map((target) => ({ target, rects: toItems(target, offset) }));
853
+ rectsByTarget.forEach(({ target, rects }) => {
854
+ if (rects.length > 0)
855
+ index.set(target.annotation, rects);
2027
856
  });
2028
- }), t;
2029
- }
2030
- function vo(t) {
2031
- const e = t.target || t.srcElement, {
2032
- tagName: n
2033
- } = e;
2034
- let o = !0;
2035
- const i = n === "INPUT" && !["checkbox", "radio", "range", "button", "file", "reset", "submit", "color"].includes(e.type);
2036
- return (e.isContentEditable || (i || n === "TEXTAREA" || n === "SELECT") && !e.readOnly) && (o = !1), o;
2037
- }
2038
- function Eo(t) {
2039
- return typeof t == "string" && (t = ft(t)), I.indexOf(t) !== -1;
2040
- }
2041
- function So(t, e) {
2042
- let n, o;
2043
- t || (t = ut());
2044
- for (const i in N)
2045
- if (Object.prototype.hasOwnProperty.call(N, i))
2046
- for (n = N[i], o = 0; o < n.length; )
2047
- n[o].scope === t ? n.splice(o, 1).forEach((a) => {
2048
- let {
2049
- element: r
2050
- } = a;
2051
- return jt(r);
2052
- }) : o++;
2053
- ut() === t && Le(e || "all");
2054
- }
2055
- function Co(t) {
2056
- let e = t.keyCode || t.which || t.charCode;
2057
- const n = I.indexOf(e);
2058
- if (n >= 0 && I.splice(n, 1), t.key && t.key.toLowerCase() === "meta" && I.splice(0, I.length), (e === 93 || e === 224) && (e = 91), e in K) {
2059
- K[e] = !1;
2060
- for (const o in H) H[o] === e && (X[o] = !1);
2061
- }
2062
- }
2063
- function Te(t) {
2064
- if (typeof t > "u")
2065
- Object.keys(N).forEach((i) => {
2066
- Array.isArray(N[i]) && N[i].forEach((s) => At(s)), delete N[i];
2067
- }), jt(null);
2068
- else if (Array.isArray(t))
2069
- t.forEach((i) => {
2070
- i.key && At(i);
857
+ const allRects = rectsByTarget.flatMap(({ rects }) => rects);
858
+ tree.load(allRects);
859
+ };
860
+ const getAt = (x, y, all2 = false) => {
861
+ const hits = tree.search({
862
+ minX: x,
863
+ minY: y,
864
+ maxX: x,
865
+ maxY: y
2071
866
  });
2072
- else if (typeof t == "object")
2073
- t.key && At(t);
2074
- else if (typeof t == "string") {
2075
- for (var e = arguments.length, n = new Array(e > 1 ? e - 1 : 0), o = 1; o < e; o++)
2076
- n[o - 1] = arguments[o];
2077
- let [i, s] = n;
2078
- typeof i == "function" && (s = i, i = ""), At({
2079
- key: t,
2080
- scope: i,
2081
- method: s,
2082
- splitKey: "+"
867
+ const area = (rect) => rect.annotation.rects.reduce((area2, r) => area2 + r.width * r.height, 0);
868
+ if (hits.length > 0) {
869
+ hits.sort((a, b) => area(a) - area(b));
870
+ return all2 ? hits.map((h) => h.annotation.id) : [hits[0].annotation.id];
871
+ } else {
872
+ return [];
873
+ }
874
+ };
875
+ const getAnnotationBounds = (id) => {
876
+ const rects = getAnnotationRects(id);
877
+ if (rects.length === 0)
878
+ return void 0;
879
+ let left = rects[0].left;
880
+ let top = rects[0].top;
881
+ let right = rects[0].right;
882
+ let bottom = rects[0].bottom;
883
+ for (let i = 1; i < rects.length; i++) {
884
+ const rect = rects[i];
885
+ left = Math.min(left, rect.left);
886
+ top = Math.min(top, rect.top);
887
+ right = Math.max(right, rect.right);
888
+ bottom = Math.max(bottom, rect.bottom);
889
+ }
890
+ return new DOMRect(left, top, right - left, bottom - top);
891
+ };
892
+ const getAnnotationRects = (id) => {
893
+ const indexed = index.get(id);
894
+ if (indexed) {
895
+ return indexed[0].annotation.rects;
896
+ } else {
897
+ return [];
898
+ }
899
+ };
900
+ const getIntersecting = (minX, minY, maxX, maxY) => {
901
+ const rects = tree.search({ minX, minY, maxX, maxY });
902
+ const annotationIds = new Set(rects.map((rect) => rect.annotation.id));
903
+ return Array.from(annotationIds).map((annotationId) => ({
904
+ annotation: store.getAnnotation(annotationId),
905
+ rects: getAnnotationRects(annotationId)
906
+ })).filter((t) => Boolean(t.annotation));
907
+ };
908
+ const size = () => tree.all().length;
909
+ const recalculate = () => {
910
+ set(store.all().map((a) => a.target), true);
911
+ emitter.emit("recalculate");
912
+ };
913
+ const on = (event, callback) => emitter.on(event, callback);
914
+ return {
915
+ all,
916
+ clear,
917
+ getAt,
918
+ getAnnotationBounds,
919
+ getAnnotationRects,
920
+ getIntersecting,
921
+ insert,
922
+ recalculate,
923
+ remove,
924
+ set,
925
+ size,
926
+ update,
927
+ on
928
+ };
929
+ };
930
+ const createTextAnnotatorState = (container, opts) => {
931
+ const store = createStore();
932
+ const tree = createSpatialTree(store, container);
933
+ const selection = createSelectionState(store, opts.userSelectAction, opts.adapter);
934
+ const hover = createHoverState(store);
935
+ const viewport = createViewportState();
936
+ const addAnnotation = (annotation, origin = Origin.LOCAL) => {
937
+ const revived = reviveAnnotation(annotation, container);
938
+ const isValid = isRevived(revived.target.selector);
939
+ if (isValid)
940
+ store.addAnnotation(revived, origin);
941
+ return isValid;
942
+ };
943
+ const bulkAddAnnotation = (annotations, replace = true, origin = Origin.LOCAL) => {
944
+ const revived = annotations.map((a) => reviveAnnotation(a, container));
945
+ const couldNotRevive = revived.filter((a) => !isRevived(a.target.selector));
946
+ store.bulkAddAnnotation(revived, replace, origin);
947
+ return couldNotRevive;
948
+ };
949
+ const bulkUpsertAnnotations = (annotations, origin = Origin.LOCAL) => {
950
+ const revived = annotations.map((a) => reviveAnnotation(a, container));
951
+ const couldNotRevive = revived.filter((a) => !isRevived(a.target.selector));
952
+ revived.forEach((a) => {
953
+ if (store.getAnnotation(a.id))
954
+ store.updateAnnotation(a, origin);
955
+ else
956
+ store.addAnnotation(a, origin);
2083
957
  });
958
+ return couldNotRevive;
959
+ };
960
+ const updateTarget = (target, origin = Origin.LOCAL) => {
961
+ const revived = reviveTarget(target, container);
962
+ store.updateTarget(revived, origin);
963
+ };
964
+ const bulkUpdateTargets = (targets, origin = Origin.LOCAL) => {
965
+ const revived = targets.map((t) => reviveTarget(t, container));
966
+ store.bulkUpdateTargets(revived, origin);
967
+ };
968
+ function getAt(x, y, all, filter) {
969
+ const getAll = all || Boolean(filter);
970
+ const annotations = tree.getAt(x, y, getAll).map((id) => store.getAnnotation(id));
971
+ const filtered = filter ? annotations.filter(filter) : annotations;
972
+ if (filtered.length === 0)
973
+ return void 0;
974
+ return all ? filtered : filtered[0];
2084
975
  }
2085
- }
2086
- const At = (t) => {
2087
- let {
2088
- key: e,
2089
- scope: n,
2090
- method: o,
2091
- splitKey: i = "+"
2092
- } = t;
2093
- Se(e).forEach((a) => {
2094
- const r = a.split(i), l = r.length, d = r[l - 1], g = d === "*" ? "*" : ft(d);
2095
- if (!N[g]) return;
2096
- n || (n = ut());
2097
- const u = l > 1 ? Ee(H, r) : [], h = [];
2098
- N[g] = N[g].filter((A) => {
2099
- const b = (o ? A.method === o : !0) && A.scope === n && mo(A.mods, u);
2100
- return b && h.push(A.element), !b;
2101
- }), h.forEach((A) => jt(A));
976
+ const getAnnotationBounds = (id) => {
977
+ const rects = tree.getAnnotationRects(id);
978
+ return rects.length > 0 ? tree.getAnnotationBounds(id) : void 0;
979
+ };
980
+ const getIntersecting = (minX, minY, maxX, maxY) => tree.getIntersecting(minX, minY, maxX, maxY);
981
+ const getAnnotationRects = (id) => tree.getAnnotationRects(id);
982
+ const recalculatePositions = () => tree.recalculate();
983
+ const onRecalculatePositions = (callback) => tree.on("recalculate", callback);
984
+ store.observe(({ changes }) => {
985
+ const deleted = (changes.deleted || []).filter((a) => isRevived(a.target.selector));
986
+ const created = (changes.created || []).filter((a) => isRevived(a.target.selector));
987
+ const updated = (changes.updated || []).filter((u) => isRevived(u.newValue.target.selector));
988
+ if ((deleted == null ? void 0 : deleted.length) > 0)
989
+ deleted.forEach((a) => tree.remove(a.target));
990
+ if (created.length > 0)
991
+ tree.set(created.map((a) => a.target), false);
992
+ if ((updated == null ? void 0 : updated.length) > 0)
993
+ updated.forEach(({ newValue }) => tree.update(newValue.target));
2102
994
  });
995
+ return {
996
+ store: {
997
+ ...store,
998
+ addAnnotation,
999
+ bulkAddAnnotation,
1000
+ bulkUpdateTargets,
1001
+ bulkUpsertAnnotations,
1002
+ getAnnotationBounds,
1003
+ getAnnotationRects,
1004
+ getIntersecting,
1005
+ getAt,
1006
+ recalculatePositions,
1007
+ onRecalculatePositions,
1008
+ updateTarget
1009
+ },
1010
+ selection,
1011
+ hover,
1012
+ viewport
1013
+ };
2103
1014
  };
2104
- function ae(t, e, n, o) {
2105
- if (e.element !== o)
2106
- return;
2107
- let i;
2108
- if (e.scope === n || e.scope === "all") {
2109
- i = e.mods.length > 0;
2110
- for (const s in K)
2111
- Object.prototype.hasOwnProperty.call(K, s) && (!K[s] && e.mods.indexOf(+s) > -1 || K[s] && e.mods.indexOf(+s) === -1) && (i = !1);
2112
- (e.mods.length === 0 && !K[16] && !K[18] && !K[17] && !K[91] || i || e.shortcut === "*") && (e.keys = [], e.keys = e.keys.concat(I), e.method(t, e) === !1 && (t.preventDefault ? t.preventDefault() : t.returnValue = !1, t.stopPropagation && t.stopPropagation(), t.cancelBubble && (t.cancelBubble = !0)));
2113
- }
2114
- }
2115
- function ce(t, e) {
2116
- const n = N["*"];
2117
- let o = t.keyCode || t.which || t.charCode;
2118
- if (!X.filter.call(this, t)) return;
2119
- if ((o === 93 || o === 224) && (o = 91), I.indexOf(o) === -1 && o !== 229 && I.push(o), ["metaKey", "ctrlKey", "altKey", "shiftKey"].forEach((r) => {
2120
- const l = xt[r];
2121
- t[r] && I.indexOf(l) === -1 ? I.push(l) : !t[r] && I.indexOf(l) > -1 ? I.splice(I.indexOf(l), 1) : r === "metaKey" && t[r] && (I = I.filter((d) => d in xt || d === o));
2122
- }), o in K) {
2123
- K[o] = !0;
2124
- for (const r in H)
2125
- H[r] === o && (X[r] = !0);
2126
- if (!n) return;
2127
- }
2128
- for (const r in K)
2129
- Object.prototype.hasOwnProperty.call(K, r) && (K[r] = t[xt[r]]);
2130
- t.getModifierState && !(t.altKey && !t.ctrlKey) && t.getModifierState("AltGraph") && (I.indexOf(17) === -1 && I.push(17), I.indexOf(18) === -1 && I.push(18), K[17] = !0, K[18] = !0);
2131
- const i = ut();
2132
- if (n)
2133
- for (let r = 0; r < n.length; r++)
2134
- n[r].scope === i && (t.type === "keydown" && n[r].keydown || t.type === "keyup" && n[r].keyup) && ae(t, n[r], i, e);
2135
- if (!(o in N)) return;
2136
- const s = N[o], a = s.length;
2137
- for (let r = 0; r < a; r++)
2138
- if ((t.type === "keydown" && s[r].keydown || t.type === "keyup" && s[r].keyup) && s[r].key) {
2139
- const l = s[r], {
2140
- splitKey: d
2141
- } = l, g = l.key.split(d), u = [];
2142
- for (let h = 0; h < g.length; h++)
2143
- u.push(ft(g[h]));
2144
- u.sort().join("") === I.sort().join("") && ae(t, l, i, e);
2145
- }
2146
- }
2147
- function X(t, e, n) {
2148
- I = [];
2149
- const o = Se(t);
2150
- let i = [], s = "all", a = document, r = 0, l = !1, d = !0, g = "+", u = !1, h = !1;
2151
- 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" && (g = e.splitKey), e.single === !0 && (h = !0)), typeof e == "string" && (s = e), h && Te(t, s); r < o.length; r++)
2152
- t = o[r].split(g), i = [], t.length > 1 && (i = Ee(H, t)), t = t[t.length - 1], t = t === "*" ? "*" : ft(t), t in N || (N[t] = []), N[t].push({
2153
- keyup: l,
2154
- keydown: d,
2155
- scope: s,
2156
- mods: i,
2157
- shortcut: o[r],
2158
- method: n,
2159
- key: o[r],
2160
- splitKey: g,
2161
- element: a
2162
- });
2163
- if (typeof a < "u" && window) {
2164
- if (!z.has(a)) {
2165
- const A = function() {
2166
- let b = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : window.event;
2167
- return ce(b, a);
2168
- }, p = function() {
2169
- let b = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : window.event;
2170
- ce(b, a), Co(b);
2171
- };
2172
- z.set(a, {
2173
- keydownListener: A,
2174
- keyupListenr: p,
2175
- capture: u
2176
- }), Vt(a, "keydown", A, u), Vt(a, "keyup", p, u);
2177
- }
2178
- if (!lt) {
2179
- const A = () => {
2180
- I = [];
1015
+ const createCanvas = () => {
1016
+ const canvas = document.createElement("canvas");
1017
+ canvas.width = 2 * window.innerWidth;
1018
+ canvas.height = 2 * window.innerHeight;
1019
+ canvas.className = "r6o-presence-layer";
1020
+ const context = canvas.getContext("2d");
1021
+ context.scale(2, 2);
1022
+ context.translate(0.5, 0.5);
1023
+ return canvas;
1024
+ };
1025
+ const createPresencePainter = (provider, opts = {}) => {
1026
+ const canvas = createCanvas();
1027
+ const ctx = canvas.getContext("2d");
1028
+ document.body.appendChild(canvas);
1029
+ const trackedAnnotations = /* @__PURE__ */ new Map();
1030
+ const getAnnotationsForUser = (p) => Array.from(trackedAnnotations.entries()).filter(([id, user]) => user.presenceKey === p.presenceKey).map(([id, _]) => id);
1031
+ provider.on("selectionChange", (p, selection) => {
1032
+ const currentIds = getAnnotationsForUser(p);
1033
+ currentIds.forEach((id) => trackedAnnotations.delete(id));
1034
+ if (selection)
1035
+ selection.forEach((id) => trackedAnnotations.set(id, p));
1036
+ });
1037
+ const clear = () => {
1038
+ const { width, height } = canvas;
1039
+ ctx.clearRect(-0.5, -0.5, width + 1, height + 1);
1040
+ };
1041
+ const paint2 = (highlight, viewportBounds, isSelected) => {
1042
+ if (opts.font)
1043
+ ctx.font = opts.font;
1044
+ const user = trackedAnnotations.get(highlight.annotation.id);
1045
+ if (user) {
1046
+ const { height } = highlight.rects[0];
1047
+ const x = highlight.rects[0].x + viewportBounds.left;
1048
+ const y = highlight.rects[0].y + viewportBounds.top;
1049
+ ctx.fillStyle = user.appearance.color;
1050
+ ctx.fillRect(x - 2, y - 2.5, 2, height + 5);
1051
+ const metrics = ctx.measureText(user.appearance.label);
1052
+ const labelWidth = metrics.width + 6;
1053
+ const labelHeight = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent + 8;
1054
+ const paddingBottom = metrics.fontBoundingBoxAscent ? 8 : 6.5;
1055
+ ctx.fillRect(x - 2, y - 2.5 - labelHeight, labelWidth, labelHeight);
1056
+ ctx.fillStyle = "#fff";
1057
+ ctx.fillText(user.appearance.label, x + 1, y - paddingBottom);
1058
+ return {
1059
+ fill: user.appearance.color,
1060
+ fillOpacity: isSelected ? 0.45 : 0.18
2181
1061
  };
2182
- lt = {
2183
- listener: A,
2184
- capture: u
2185
- }, Vt(window, "focus", A, u);
2186
1062
  }
2187
- }
2188
- }
2189
- function Lo(t) {
2190
- let e = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "all";
2191
- Object.keys(N).forEach((n) => {
2192
- N[n].filter((i) => i.scope === e && i.shortcut === t).forEach((i) => {
2193
- i && i.method && i.method();
2194
- });
2195
- });
2196
- }
2197
- function jt(t) {
2198
- const e = Object.values(N).flat();
2199
- if (e.findIndex((o) => {
2200
- let {
2201
- element: i
2202
- } = o;
2203
- return i === t;
2204
- }) < 0) {
2205
- const {
2206
- keydownListener: o,
2207
- keyupListenr: i,
2208
- capture: s
2209
- } = z.get(t) || {};
2210
- o && i && (it(t, "keyup", i, s), it(t, "keydown", o, s), z.delete(t));
2211
- }
2212
- if ((e.length <= 0 || z.size <= 0) && (Object.keys(z).forEach((i) => {
2213
- const {
2214
- keydownListener: s,
2215
- keyupListenr: a,
2216
- capture: r
2217
- } = z.get(i) || {};
2218
- s && a && (it(i, "keyup", a, r), it(i, "keydown", s, r), z.delete(i));
2219
- }), z.clear(), Object.keys(N).forEach((i) => delete N[i]), lt)) {
2220
- const {
2221
- listener: i,
2222
- capture: s
2223
- } = lt;
2224
- it(window, "focus", i, s), lt = null;
2225
- }
2226
- }
2227
- const Yt = {
2228
- getPressedKeyString: Ao,
2229
- setScope: Le,
2230
- getScope: ut,
2231
- deleteScope: So,
2232
- getPressedKeyCodes: wo,
2233
- getAllKeyCodes: xo,
2234
- isPressed: Eo,
2235
- filter: vo,
2236
- trigger: Lo,
2237
- unbind: Te,
2238
- keyMap: dt,
2239
- modifier: H,
2240
- modifierMap: xt
1063
+ };
1064
+ const reset = () => {
1065
+ canvas.width = 2 * window.innerWidth;
1066
+ canvas.height = 2 * window.innerHeight;
1067
+ const context = canvas.getContext("2d");
1068
+ context.scale(2, 2);
1069
+ context.translate(0.5, 0.5);
1070
+ };
1071
+ const destroy = () => {
1072
+ canvas.remove();
1073
+ };
1074
+ return {
1075
+ clear,
1076
+ destroy,
1077
+ paint: paint2,
1078
+ reset
1079
+ };
2241
1080
  };
2242
- for (const t in Yt)
2243
- Object.prototype.hasOwnProperty.call(Yt, t) && (X[t] = Yt[t]);
2244
- if (typeof window < "u") {
2245
- const t = window.hotkeys;
2246
- X.noConflict = (e) => (e && window.hotkeys === X && (window.hotkeys = t), X), window.hotkeys = X;
2247
- }
2248
- async function To(t, e, n = () => !1) {
2249
- do {
2250
- if (await t(), await n()) break;
2251
- const o = e;
2252
- await new Promise((i) => setTimeout(i, Math.max(0, o)));
2253
- } while (!await n());
2254
- }
2255
- const le = 300, Oe = ["up", "down", "left", "right"], Be = ke ? "⌘+a" : "ctrl+a", Oo = [
2256
- ...Oe.map((t) => `shift+${t}`),
2257
- Be
2258
- ], Bo = (t, e, n) => {
2259
- const { store: o, selection: i } = e;
2260
- let s;
2261
- const { annotatingEnabled: a, offsetReferenceSelector: r, selectionMode: l } = n, d = (f) => s = f;
2262
- let g;
2263
- const u = (f) => g = f;
2264
- let h, A, p, b = a;
2265
- const x = (f) => {
2266
- b = f, c.clear(), f || (h = void 0, A = void 0, p = void 0);
2267
- }, m = (f) => {
2268
- b && A !== !1 && (h = st(f.target) ? void 0 : {
2269
- annotation: be(),
1081
+ const CLICK_TIMEOUT = 300;
1082
+ const ARROW_KEYS = ["up", "down", "left", "right"];
1083
+ const SELECT_ALL = isMac ? "⌘+a" : "ctrl+a";
1084
+ const SELECTION_KEYS = [
1085
+ ...ARROW_KEYS.map((key) => `shift+${key}`),
1086
+ SELECT_ALL
1087
+ ];
1088
+ const createSelectionHandler = (container, state, options) => {
1089
+ const { store, selection } = state;
1090
+ let currentUser;
1091
+ const { annotatingEnabled, offsetReferenceSelector, selectionMode } = options;
1092
+ const setUser = (user) => currentUser = user;
1093
+ let currentFilter;
1094
+ const setFilter = (filter) => currentFilter = filter;
1095
+ let currentTarget;
1096
+ let isLeftClick;
1097
+ let lastDownEvent;
1098
+ let currentAnnotatingEnabled = annotatingEnabled;
1099
+ const setAnnotatingEnabled = (enabled) => {
1100
+ currentAnnotatingEnabled = enabled;
1101
+ onSelectionChange.clear();
1102
+ if (!enabled) {
1103
+ currentTarget = void 0;
1104
+ isLeftClick = void 0;
1105
+ lastDownEvent = void 0;
1106
+ }
1107
+ };
1108
+ const onSelectStart = (evt) => {
1109
+ if (!currentAnnotatingEnabled) return;
1110
+ if (isLeftClick === false) return;
1111
+ currentTarget = isNotAnnotatable(evt.target) ? void 0 : {
1112
+ annotation: v4(),
2270
1113
  selector: [],
2271
- creator: s,
1114
+ creator: currentUser,
2272
1115
  created: /* @__PURE__ */ new Date()
2273
- });
2274
- }, c = Xt((f) => {
2275
- if (!b) return;
2276
- const E = document.getSelection();
2277
- if (!(E != null && E.anchorNode))
1116
+ };
1117
+ };
1118
+ const onSelectionChange = debounce((evt) => {
1119
+ if (!currentAnnotatingEnabled) return;
1120
+ const sel = document.getSelection();
1121
+ if (!(sel == null ? void 0 : sel.anchorNode)) {
2278
1122
  return;
2279
- if (st(E.anchorNode)) {
2280
- h = void 0;
1123
+ }
1124
+ if (isNotAnnotatable(sel.anchorNode)) {
1125
+ currentTarget = void 0;
2281
1126
  return;
2282
1127
  }
2283
- const M = f.timeStamp - ((p == null ? void 0 : p.timeStamp) || f.timeStamp);
2284
- if ((p == null ? void 0 : p.type) === "pointerdown" && (M < 1e3 && !h || E.isCollapsed && M < le) && m(p || f), !h) return;
2285
- if (E.isCollapsed) {
2286
- o.getAnnotation(h.annotation) && (i.clear(), o.deleteAnnotation(h.annotation));
1128
+ const timeDifference = evt.timeStamp - ((lastDownEvent == null ? void 0 : lastDownEvent.timeStamp) || evt.timeStamp);
1129
+ if ((lastDownEvent == null ? void 0 : lastDownEvent.type) === "pointerdown") {
1130
+ if (timeDifference < 1e3 && !currentTarget) {
1131
+ onSelectStart(lastDownEvent || evt);
1132
+ } else if (sel.isCollapsed && timeDifference < CLICK_TIMEOUT) {
1133
+ onSelectStart(lastDownEvent || evt);
1134
+ }
1135
+ }
1136
+ if (!currentTarget) return;
1137
+ if (sel.isCollapsed) {
1138
+ if (store.getAnnotation(currentTarget.annotation)) {
1139
+ selection.clear();
1140
+ store.deleteAnnotation(currentTarget.annotation);
1141
+ }
2287
1142
  return;
2288
1143
  }
2289
- const O = E.getRangeAt(0), U = He(O, t);
2290
- if (Ve(U)) return;
2291
- const _ = _e(U.cloneRange());
2292
- (_.length !== h.selector.length || _.some((W, G) => {
2293
- var St;
2294
- return W.toString() !== ((St = h.selector[G]) == null ? void 0 : St.quote);
2295
- })) && (h = {
2296
- ...h,
2297
- selector: _.map((W) => Xe(W, t, r)),
1144
+ const selectionRange = sel.getRangeAt(0);
1145
+ const containedRange = trimRangeToContainer(selectionRange, container);
1146
+ if (isWhitespaceOrEmpty(containedRange)) return;
1147
+ const annotatableRanges = splitAnnotatableRanges(containedRange.cloneRange());
1148
+ const hasChanged = annotatableRanges.length !== currentTarget.selector.length || annotatableRanges.some((r, i) => {
1149
+ var _a;
1150
+ return r.toString() !== ((_a = currentTarget.selector[i]) == null ? void 0 : _a.quote);
1151
+ });
1152
+ if (!hasChanged) return;
1153
+ currentTarget = {
1154
+ ...currentTarget,
1155
+ selector: annotatableRanges.map((r) => rangeToSelector(r, container, offsetReferenceSelector)),
2298
1156
  updated: /* @__PURE__ */ new Date()
2299
- }, o.getAnnotation(h.annotation) ? o.updateTarget(h, k.LOCAL) : i.clear());
2300
- }, 10), y = (f) => {
2301
- st(f.target) || (p = Lt(f), A = p.button === 0);
2302
- }, C = async (f) => {
2303
- if (st(f.target) || !A) return;
2304
- const E = () => {
2305
- const { x: O, y: U } = t.getBoundingClientRect(), _ = f.target instanceof Node && t.contains(f.target) && o.getAt(f.clientX - O, f.clientY - U, l === "all", g);
2306
- if (_) {
2307
- const { selected: ht } = i, W = new Set(ht.map((nt) => nt.id)), G = Array.isArray(_) ? _.map((nt) => nt.id) : [_.id];
2308
- (W.size !== G.length || !G.every((nt) => W.has(nt))) && i.userSelect(G, f);
2309
- } else
2310
- i.clear();
2311
1157
  };
2312
- if (f.timeStamp - p.timeStamp < le) {
2313
- await S();
2314
- const O = document.getSelection();
2315
- if (O != null && O.isCollapsed) {
2316
- h = void 0, E();
1158
+ if (store.getAnnotation(currentTarget.annotation)) {
1159
+ store.updateTarget(currentTarget, Origin.LOCAL);
1160
+ } else {
1161
+ selection.clear();
1162
+ }
1163
+ }, 10);
1164
+ const onPointerDown = (evt) => {
1165
+ if (isNotAnnotatable(evt.target)) return;
1166
+ lastDownEvent = clonePointerEvent(evt);
1167
+ isLeftClick = lastDownEvent.button === 0;
1168
+ };
1169
+ const onPointerUp = async (evt) => {
1170
+ if (isNotAnnotatable(evt.target) || !isLeftClick) return;
1171
+ const clickSelect = () => {
1172
+ const { x, y } = container.getBoundingClientRect();
1173
+ const hovered = evt.target instanceof Node && container.contains(evt.target) && store.getAt(evt.clientX - x, evt.clientY - y, selectionMode === "all", currentFilter);
1174
+ if (hovered) {
1175
+ const { selected } = selection;
1176
+ const currentIds = new Set(selected.map((s) => s.id));
1177
+ const nextIds = Array.isArray(hovered) ? hovered.map((a) => a.id) : [hovered.id];
1178
+ const hasChanged = currentIds.size !== nextIds.length || !nextIds.every((id) => currentIds.has(id));
1179
+ if (hasChanged)
1180
+ selection.userSelect(nextIds, evt);
1181
+ } else {
1182
+ selection.clear();
1183
+ }
1184
+ };
1185
+ const timeDifference = evt.timeStamp - lastDownEvent.timeStamp;
1186
+ if (timeDifference < CLICK_TIMEOUT) {
1187
+ await pollSelectionCollapsed();
1188
+ const sel = document.getSelection();
1189
+ if (sel == null ? void 0 : sel.isCollapsed) {
1190
+ currentTarget = void 0;
1191
+ clickSelect();
2317
1192
  return;
2318
1193
  }
2319
1194
  }
2320
- h && h.selector.length > 0 && (w(), i.userSelect(h.annotation, Lt(f)));
2321
- }, S = async () => {
2322
- const f = document.getSelection();
2323
- let E = !1, M = f == null ? void 0 : f.isCollapsed;
2324
- const O = () => M || E, U = 1;
2325
- return setTimeout(() => E = !0, 50), To(() => M = f == null ? void 0 : f.isCollapsed, U, O);
2326
- }, L = (f) => {
2327
- const E = document.getSelection();
2328
- E != null && E.isCollapsed || ((!h || h.selector.length === 0) && c(f), w(), i.userSelect(h.annotation, Lt(f)));
2329
- }, B = (f) => {
2330
- b && f.key === "Shift" && h && (document.getSelection().isCollapsed || (w(), i.userSelect(h.annotation, pt(f))));
2331
- }, T = (f) => {
2332
- const E = () => setTimeout(() => {
2333
- (h == null ? void 0 : h.selector.length) > 0 && (i.clear(), o.addAnnotation({
2334
- id: h.annotation,
2335
- bodies: [],
2336
- target: h
2337
- }), i.userSelect(h.annotation, pt(f))), document.removeEventListener("selectionchange", E);
1195
+ if (currentTarget && currentTarget.selector.length > 0) {
1196
+ upsertCurrentTarget();
1197
+ selection.userSelect(currentTarget.annotation, clonePointerEvent(evt));
1198
+ }
1199
+ };
1200
+ const pollSelectionCollapsed = async () => {
1201
+ const sel = document.getSelection();
1202
+ let stopPolling = false;
1203
+ let isCollapsed = sel == null ? void 0 : sel.isCollapsed;
1204
+ const shouldStopPolling = () => isCollapsed || stopPolling;
1205
+ const pollingDelayMs = 1;
1206
+ const stopPollingInMs = 50;
1207
+ setTimeout(() => stopPolling = true, stopPollingInMs);
1208
+ return poll(() => isCollapsed = sel == null ? void 0 : sel.isCollapsed, pollingDelayMs, shouldStopPolling);
1209
+ };
1210
+ const onContextMenu = (evt) => {
1211
+ const sel = document.getSelection();
1212
+ if (sel == null ? void 0 : sel.isCollapsed) return;
1213
+ if (!currentTarget || currentTarget.selector.length === 0) {
1214
+ onSelectionChange(evt);
1215
+ }
1216
+ upsertCurrentTarget();
1217
+ selection.userSelect(currentTarget.annotation, clonePointerEvent(evt));
1218
+ };
1219
+ const onKeyup = (evt) => {
1220
+ if (!currentAnnotatingEnabled) return;
1221
+ if (evt.key === "Shift" && currentTarget) {
1222
+ const sel = document.getSelection();
1223
+ if (!sel.isCollapsed) {
1224
+ upsertCurrentTarget();
1225
+ selection.userSelect(currentTarget.annotation, cloneKeyboardEvent(evt));
1226
+ }
1227
+ }
1228
+ };
1229
+ const onSelectAll = (evt) => {
1230
+ const onSelected = () => setTimeout(() => {
1231
+ if ((currentTarget == null ? void 0 : currentTarget.selector.length) > 0) {
1232
+ selection.clear();
1233
+ store.addAnnotation({
1234
+ id: currentTarget.annotation,
1235
+ bodies: [],
1236
+ target: currentTarget
1237
+ });
1238
+ selection.userSelect(currentTarget.annotation, cloneKeyboardEvent(evt));
1239
+ }
1240
+ document.removeEventListener("selectionchange", onSelected);
2338
1241
  }, 100);
2339
- document.addEventListener("selectionchange", E), m(f);
1242
+ document.addEventListener("selectionchange", onSelected);
1243
+ onSelectStart(evt);
2340
1244
  };
2341
- X(Oo.join(","), { element: t, keydown: !0, keyup: !1 }, (f) => {
2342
- f.repeat || (p = pt(f));
2343
- }), X(Be, { keydown: !0, keyup: !1 }, (f) => {
2344
- p = pt(f), T(f);
1245
+ hotkeys(SELECTION_KEYS.join(","), { element: container, keydown: true, keyup: false }, (evt) => {
1246
+ if (!evt.repeat)
1247
+ lastDownEvent = cloneKeyboardEvent(evt);
1248
+ });
1249
+ hotkeys(SELECT_ALL, { keydown: true, keyup: false }, (evt) => {
1250
+ lastDownEvent = cloneKeyboardEvent(evt);
1251
+ onSelectAll(evt);
2345
1252
  });
2346
- const R = (f) => {
2347
- f.repeat || f.target !== t && f.target !== document.body || (h = void 0, i.clear());
2348
- };
2349
- X(Oe.join(","), { keydown: !0, keyup: !1 }, R);
2350
- const w = () => {
2351
- const f = o.getAnnotation(h.annotation);
2352
- if (!f) {
2353
- o.addAnnotation({
2354
- id: h.annotation,
1253
+ const handleArrowKeyPress = (evt) => {
1254
+ if (evt.repeat || evt.target !== container && evt.target !== document.body) {
1255
+ return;
1256
+ }
1257
+ currentTarget = void 0;
1258
+ selection.clear();
1259
+ };
1260
+ hotkeys(ARROW_KEYS.join(","), { keydown: true, keyup: false }, handleArrowKeyPress);
1261
+ const upsertCurrentTarget = () => {
1262
+ const existingAnnotation = store.getAnnotation(currentTarget.annotation);
1263
+ if (!existingAnnotation) {
1264
+ store.addAnnotation({
1265
+ id: currentTarget.annotation,
2355
1266
  bodies: [],
2356
- target: h
1267
+ target: currentTarget
2357
1268
  });
2358
1269
  return;
2359
1270
  }
2360
- const { target: { updated: E } } = f, { updated: M } = h;
2361
- (!E || !M || E < M) && o.updateTarget(h);
1271
+ const { target: { updated: existingTargetUpdated } } = existingAnnotation;
1272
+ const { updated: currentTargetUpdated } = currentTarget;
1273
+ if (!existingTargetUpdated || !currentTargetUpdated || existingTargetUpdated < currentTargetUpdated) {
1274
+ store.updateTarget(currentTarget);
1275
+ }
2362
1276
  };
2363
- 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), {
2364
- destroy: () => {
2365
- h = void 0, A = void 0, p = 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), X.unbind();
2366
- },
2367
- setFilter: u,
2368
- setUser: d,
2369
- setAnnotatingEnabled: x
2370
- };
2371
- }, Ro = (t, e) => ({
2372
- ...t,
2373
- annotatingEnabled: t.annotatingEnabled ?? e.annotatingEnabled,
2374
- user: t.user || e.user
2375
- }), de = "SPANS", _o = (t, e = {}) => {
2376
- Me(t), Ie(t);
2377
- const n = Ro(e, {
2378
- annotatingEnabled: !0,
2379
- user: qn()
2380
- }), o = ho(t, n), { selection: i, viewport: s } = o, a = o.store, r = Yn(a), l = Pn(o, r, n.adapter);
2381
- let d = n.user;
2382
- const g = n.renderer === "CSS_HIGHLIGHTS" ? CSS.highlights ? "CSS_HIGHLIGHTS" : de : n.renderer || de, u = g === "SPANS" ? mn(t, o, s) : g === "CSS_HIGHLIGHTS" ? hn(t, o, s) : g === "CANVAS" ? nn(t, o, s) : void 0;
2383
- if (!u)
2384
- throw `Unknown renderer implementation: ${g}`;
2385
- console.debug(`Using ${g} renderer`), n.style && u.setStyle(n.style);
2386
- const h = Bo(t, o, n);
2387
- h.setUser(d), h.setAnnotatingEnabled(n.annotatingEnabled);
2388
- const A = $n(o, r, n.adapter), p = () => d, b = (S) => {
2389
- h.setAnnotatingEnabled(
2390
- S === void 0 ? !0 : S
1277
+ document.addEventListener("pointerdown", onPointerDown);
1278
+ document.addEventListener("pointerup", onPointerUp);
1279
+ document.addEventListener("contextmenu", onContextMenu);
1280
+ container.addEventListener("keyup", onKeyup);
1281
+ container.addEventListener("selectstart", onSelectStart);
1282
+ document.addEventListener("selectionchange", onSelectionChange);
1283
+ const destroy = () => {
1284
+ currentTarget = void 0;
1285
+ isLeftClick = void 0;
1286
+ lastDownEvent = void 0;
1287
+ onSelectionChange.clear();
1288
+ document.removeEventListener("pointerdown", onPointerDown);
1289
+ document.removeEventListener("pointerup", onPointerUp);
1290
+ document.removeEventListener("contextmenu", onContextMenu);
1291
+ container.removeEventListener("keyup", onKeyup);
1292
+ container.removeEventListener("selectstart", onSelectStart);
1293
+ document.removeEventListener("selectionchange", onSelectionChange);
1294
+ hotkeys.unbind();
1295
+ };
1296
+ return {
1297
+ destroy,
1298
+ setFilter,
1299
+ setUser,
1300
+ setAnnotatingEnabled
1301
+ };
1302
+ };
1303
+ const fillDefaults = (opts, defaults) => ({
1304
+ ...opts,
1305
+ annotatingEnabled: opts.annotatingEnabled ?? defaults.annotatingEnabled,
1306
+ user: opts.user || defaults.user
1307
+ });
1308
+ const USE_DEFAULT_RENDERER = "SPANS";
1309
+ const createTextAnnotator = (container, options = {}) => {
1310
+ cancelSingleClickEvents(container);
1311
+ programmaticallyFocusable(container);
1312
+ const opts = fillDefaults(options, {
1313
+ annotatingEnabled: true,
1314
+ user: createAnonymousGuest()
1315
+ });
1316
+ const state = createTextAnnotatorState(container, opts);
1317
+ const { selection, viewport } = state;
1318
+ const store = state.store;
1319
+ const undoStack = createUndoStack(store);
1320
+ const lifecycle = createLifecycleObserver(state, undoStack, opts.adapter);
1321
+ let currentUser = opts.user;
1322
+ const useRenderer = opts.renderer === "CSS_HIGHLIGHTS" ? Boolean(CSS.highlights) ? "CSS_HIGHLIGHTS" : USE_DEFAULT_RENDERER : opts.renderer || USE_DEFAULT_RENDERER;
1323
+ const highlightRenderer = useRenderer === "SPANS" ? createSpansRenderer(container, state, viewport) : useRenderer === "CSS_HIGHLIGHTS" ? createHighlightsRenderer(container, state, viewport) : useRenderer === "CANVAS" ? createCanvasRenderer(container, state, viewport) : void 0;
1324
+ if (!highlightRenderer)
1325
+ throw `Unknown renderer implementation: ${useRenderer}`;
1326
+ console.debug(`Using ${useRenderer} renderer`);
1327
+ if (opts.style)
1328
+ highlightRenderer.setStyle(opts.style);
1329
+ const selectionHandler = createSelectionHandler(container, state, opts);
1330
+ selectionHandler.setUser(currentUser);
1331
+ selectionHandler.setAnnotatingEnabled(opts.annotatingEnabled);
1332
+ const base = createBaseAnnotator(state, undoStack, opts.adapter);
1333
+ const getUser = () => currentUser;
1334
+ const setAnnotatingEnabled = (enabled) => {
1335
+ selectionHandler.setAnnotatingEnabled(
1336
+ enabled === void 0 ? true : enabled
2391
1337
  );
2392
- }, x = (S) => {
2393
- u.setFilter(S), h.setFilter(S);
2394
- }, m = (S) => {
2395
- d = S, h.setUser(S);
2396
- }, c = (S) => {
2397
- S && (u.setPainter(go(S, n.presence)), S.on("selectionChange", () => u.redraw()));
2398
- }, y = (S) => {
2399
- S ? i.setSelected(S) : i.clear();
1338
+ };
1339
+ const setFilter = (filter) => {
1340
+ highlightRenderer.setFilter(filter);
1341
+ selectionHandler.setFilter(filter);
1342
+ };
1343
+ const setUser = (user) => {
1344
+ currentUser = user;
1345
+ selectionHandler.setUser(user);
1346
+ };
1347
+ const setPresenceProvider = (provider) => {
1348
+ if (provider) {
1349
+ highlightRenderer.setPainter(createPresencePainter(provider, opts.presence));
1350
+ provider.on("selectionChange", () => highlightRenderer.redraw());
1351
+ }
1352
+ };
1353
+ const setSelected = (arg) => {
1354
+ if (arg) {
1355
+ selection.setSelected(arg);
1356
+ } else {
1357
+ selection.clear();
1358
+ }
1359
+ };
1360
+ const destroy = () => {
1361
+ highlightRenderer.destroy();
1362
+ selectionHandler.destroy();
1363
+ undoStack.destroy();
2400
1364
  };
2401
1365
  return {
2402
- ...A,
2403
- destroy: () => {
2404
- u.destroy(), h.destroy(), r.destroy();
2405
- },
2406
- element: t,
2407
- getUser: p,
2408
- setAnnotatingEnabled: b,
2409
- setFilter: x,
2410
- setStyle: u.setStyle.bind(u),
2411
- redraw: u.redraw.bind(u),
2412
- setUser: m,
2413
- setSelected: y,
2414
- setPresenceProvider: c,
2415
- setVisible: u.setVisible.bind(u),
2416
- on: l.on,
2417
- off: l.off,
2418
- scrollIntoView: ze(t, a),
2419
- state: o
1366
+ ...base,
1367
+ destroy,
1368
+ element: container,
1369
+ getUser,
1370
+ setAnnotatingEnabled,
1371
+ setFilter,
1372
+ setStyle: highlightRenderer.setStyle.bind(highlightRenderer),
1373
+ redraw: highlightRenderer.redraw.bind(highlightRenderer),
1374
+ setUser,
1375
+ setSelected,
1376
+ setPresenceProvider,
1377
+ setVisible: highlightRenderer.setVisible.bind(highlightRenderer),
1378
+ on: lifecycle.on,
1379
+ off: lifecycle.off,
1380
+ scrollIntoView: scrollIntoView(container, store),
1381
+ state
2420
1382
  };
2421
1383
  };
2422
1384
  export {
2423
- Et as DEFAULT_SELECTED_STYLE,
2424
- q as DEFAULT_STYLE,
2425
- ue as NOT_ANNOTATABLE_CLASS,
2426
- et as NOT_ANNOTATABLE_SELECTOR,
2427
- k as Origin,
2428
- En as UserSelectAction,
2429
- No as W3CTextFormat,
2430
- Me as cancelSingleClickEvents,
2431
- pt as cloneKeyboardEvent,
2432
- Lt as clonePointerEvent,
2433
- Io as createBody,
2434
- nn as createCanvasRenderer,
2435
- hn as createHighlightsRenderer,
2436
- go as createPresencePainter,
2437
- fn as createRenderer,
2438
- Bo as createSelectionHandler,
2439
- mn as createSpansRenderer,
2440
- _o as createTextAnnotator,
2441
- ho as createTextAnnotatorState,
2442
- Ro as fillDefaults,
2443
- Ue as getQuoteContext,
2444
- Kt as getRangeAnnotatableContents,
2445
- ke as isMac,
2446
- st as isNotAnnotatable,
2447
- Re as isRangeAnnotatable,
2448
- F as isRevived,
2449
- Ve as isWhitespaceOrEmpty,
2450
- Pe as mergeClientRects,
2451
- Fe as paint,
2452
- eo as parseW3CTextAnnotation,
2453
- Ie as programmaticallyFocusable,
2454
- $e as rangeContains,
2455
- Xe as rangeToSelector,
2456
- Ct as reviveAnnotation,
2457
- fe as reviveSelector,
2458
- vt as reviveTarget,
2459
- ze as scrollIntoView,
2460
- no as serializeW3CTextAnnotation,
2461
- _e as splitAnnotatableRanges,
2462
- Mo as toDomRectList,
2463
- je as toParentBounds,
2464
- ko as toViewportBounds,
2465
- He as trimRangeToContainer,
2466
- De as whitespaceOrEmptyRegex
1385
+ DEFAULT_SELECTED_STYLE,
1386
+ DEFAULT_STYLE,
1387
+ NOT_ANNOTATABLE_CLASS,
1388
+ NOT_ANNOTATABLE_SELECTOR,
1389
+ Origin2 as Origin,
1390
+ UserSelectAction,
1391
+ W3CTextFormat,
1392
+ cancelSingleClickEvents,
1393
+ cloneKeyboardEvent,
1394
+ clonePointerEvent,
1395
+ createBody,
1396
+ createCanvasRenderer,
1397
+ createHighlightsRenderer,
1398
+ createPresencePainter,
1399
+ createRenderer$1 as createRenderer,
1400
+ createSelectionHandler,
1401
+ createSpansRenderer,
1402
+ createTextAnnotator,
1403
+ createTextAnnotatorState,
1404
+ fillDefaults,
1405
+ getQuoteContext,
1406
+ getRangeAnnotatableContents,
1407
+ isMac,
1408
+ isNotAnnotatable,
1409
+ isRangeAnnotatable,
1410
+ isRevived,
1411
+ isWhitespaceOrEmpty,
1412
+ mergeClientRects,
1413
+ paint,
1414
+ parseW3CTextAnnotation,
1415
+ programmaticallyFocusable,
1416
+ rangeContains,
1417
+ rangeToSelector,
1418
+ reviveAnnotation,
1419
+ reviveSelector,
1420
+ reviveTarget,
1421
+ scrollIntoView,
1422
+ serializeW3CTextAnnotation,
1423
+ splitAnnotatableRanges,
1424
+ toDomRectList,
1425
+ toParentBounds,
1426
+ toViewportBounds,
1427
+ trimRangeToContainer,
1428
+ whitespaceOrEmptyRegex
2467
1429
  };
2468
1430
  //# sourceMappingURL=text-annotator.es.js.map