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