@samuelbradshaw/highlight-helper-js 0.8.1 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/publish.yml +5 -5
- package/README.md +45 -28
- package/demo.html +96 -50
- package/highlight-helper.js +1394 -1247
- package/package.json +1 -1
package/highlight-helper.js
CHANGED
|
@@ -1,1408 +1,1531 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* HighlightHelper.js
|
|
3
3
|
* https://github.com/samuelbradshaw/highlight-helper-js
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
'use strict';
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
this.annotatableContainer, this.relativeAncestorElement, this.annotatableParagraphs, this.stylesheets;
|
|
14
|
-
let generalStylesheet, appearanceStylesheet, highlightApiStylesheet, selectionStylesheet;
|
|
15
|
-
let annotatableParagraphIds, hyperlinkElements;
|
|
16
|
-
let svgBackground, svgActiveOverlay, selectionHandles;
|
|
17
|
-
let highlightsById, hyperlinksByPosition;
|
|
18
|
-
let controller;
|
|
19
|
-
|
|
20
|
-
const initializeHighlighter = (previousContainerSelector = null) => {
|
|
21
|
-
if (!options.paragraphSelector.includes(options.containerSelector)) {
|
|
22
|
-
const paragraphSelectorList = options.paragraphSelector.split(',').map(selector => `${options.containerSelector} ${selector}`);
|
|
23
|
-
options.paragraphSelector = paragraphSelectorList.join(',');
|
|
24
|
-
}
|
|
25
|
-
this.annotatableContainer = document.querySelector(options.containerSelector);
|
|
26
|
-
this.annotatableParagraphs = this.annotatableContainer.querySelectorAll(options.paragraphSelector);
|
|
27
|
-
annotatableParagraphIds = Array.from(this.annotatableParagraphs, paragraph => paragraph.id);
|
|
28
|
-
|
|
29
|
-
// Handle cases where a highlighter already exists for the container, or one of its children or ancestors
|
|
30
|
-
const previousContainer = document.querySelector(previousContainerSelector) ?? this.annotatableContainer;
|
|
31
|
-
if (previousContainer.highlighter) {
|
|
32
|
-
previousContainer.highlighter.removeHighlighter();
|
|
33
|
-
} else if (this.annotatableContainer.closest('[data-hh-container]') || this.annotatableContainer.querySelector('[data-hh-container]')) {
|
|
34
|
-
console.error(`Unable to create Highlighter with container selector “${options.containerSelector}” (annotatable container can’t be an child or ancestor of another annotatable container).`);
|
|
35
|
-
return false;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
// Get the closest ancestor element with `position: relative`, or the root element (this is used to calculate the position of selection handles and SVG highlights)
|
|
39
|
-
let ancestorElement = this.annotatableContainer;
|
|
40
|
-
while (ancestorElement) {
|
|
41
|
-
if (ancestorElement === document.documentElement || window.getComputedStyle(ancestorElement).position === 'relative') {
|
|
42
|
-
this.relativeAncestorElement = ancestorElement;
|
|
43
|
-
break;
|
|
44
|
-
}
|
|
45
|
-
ancestorElement = ancestorElement.parentElement;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
// Abort controller can be used to cancel event listeners if the highlighter is removed
|
|
49
|
-
controller = new AbortController;
|
|
50
|
-
|
|
51
|
-
// Setting tabIndex -1 on <body> allows focus to be set programmatically (needed to initialize text selection in iOS Safari). It also prevents "tap to search" from interfering with text selection in Android Chrome.
|
|
52
|
-
document.body.tabIndex = -1;
|
|
53
|
-
|
|
54
|
-
// Set up stylesheets
|
|
55
|
-
this.stylesheets = {}
|
|
56
|
-
generalStylesheet = addStylesheet(this.stylesheets, 'general');
|
|
57
|
-
appearanceStylesheet = addStylesheet(this.stylesheets, 'appearance');
|
|
58
|
-
highlightApiStylesheet = addStylesheet(this.stylesheets, 'highlight-api');
|
|
59
|
-
selectionStylesheet = addStylesheet(this.stylesheets, 'selection');
|
|
60
|
-
generalStylesheet.replaceSync(`
|
|
61
|
-
${options.containerSelector} {
|
|
62
|
-
-webkit-tap-highlight-color: transparent;
|
|
63
|
-
}
|
|
64
|
-
.hh-wrapper-start, .hh-wrapper-end, .hh-selection-handle {
|
|
65
|
-
-webkit-user-select: none;
|
|
66
|
-
user-select: none;
|
|
67
|
-
}
|
|
68
|
-
.hh-selection-handle {
|
|
69
|
-
position: absolute;
|
|
70
|
-
width: 0px;
|
|
71
|
-
visibility: hidden;
|
|
72
|
-
}
|
|
73
|
-
[data-hh-pointer-down="true"] .hh-selection-handle {
|
|
74
|
-
visibility: hidden !important;
|
|
75
|
-
}
|
|
76
|
-
.hh-selection-handle-content {
|
|
77
|
-
position: absolute;
|
|
78
|
-
height: 100%;
|
|
79
|
-
}
|
|
80
|
-
.hh-selection-handle [draggable] {
|
|
81
|
-
position: absolute;
|
|
82
|
-
top: -0.3em;
|
|
83
|
-
width: 3.2em;
|
|
84
|
-
height: calc(100% + 1.3em);
|
|
85
|
-
background-color: transparent;
|
|
86
|
-
z-index: 1;
|
|
87
|
-
}
|
|
88
|
-
.hh-selection-handle[data-side="left"] [draggable] { right: -2em; }
|
|
89
|
-
.hh-selection-handle[data-side="right"] [draggable] { left: -2em; }
|
|
90
|
-
.hh-default-handle {
|
|
91
|
-
position: absolute;
|
|
92
|
-
width: 0.8em;
|
|
93
|
-
height: min(1.2em, 100%);
|
|
94
|
-
background-color: hsl(from var(--hh-color) h 80% 40% / 1);
|
|
95
|
-
outline: 0.1em solid hsla(0, 0%, 100%, 0.8);
|
|
96
|
-
outline-offset: -0.05em;
|
|
97
|
-
bottom: -0.2em;
|
|
98
|
-
}
|
|
99
|
-
.hh-selection-handle[data-side="left"] .hh-default-handle {
|
|
100
|
-
right: 0;
|
|
101
|
-
border-radius: 1em 0 0.6em 0.6em;
|
|
102
|
-
}
|
|
103
|
-
.hh-selection-handle[data-side="right"] .hh-default-handle {
|
|
104
|
-
left: 0;
|
|
105
|
-
border-radius: 0 1em 0.6em 0.6em;
|
|
106
|
-
}
|
|
107
|
-
.hh-svg-background {
|
|
108
|
-
position: absolute;
|
|
109
|
-
top: 0;
|
|
110
|
-
left: 0;
|
|
111
|
-
width: 100%;
|
|
112
|
-
overflow: visible;
|
|
113
|
-
z-index: -1;
|
|
114
|
-
}
|
|
115
|
-
.hh-svg-background g {
|
|
116
|
-
fill: transparent;
|
|
117
|
-
stroke: none;
|
|
118
|
-
}
|
|
119
|
-
mark[data-highlight-id] {
|
|
120
|
-
background-color: transparent;
|
|
121
|
-
color: inherit;
|
|
122
|
-
}
|
|
123
|
-
mark[data-highlight-id][data-style="fill"][data-start] {
|
|
124
|
-
border-top-left-radius: 0.25em;
|
|
125
|
-
border-bottom-left-radius: 0.25em;
|
|
126
|
-
margin-left: -0.13em; padding-left: 0.13em;
|
|
127
|
-
}
|
|
128
|
-
mark[data-highlight-id][data-style="fill"][data-end] {
|
|
129
|
-
border-top-right-radius: 0.25em;
|
|
130
|
-
border-bottom-right-radius: 0.25em;
|
|
131
|
-
margin-right: -0.13em; padding-right: 0.13em;
|
|
132
|
-
}
|
|
133
|
-
mark[data-highlight-id][data-style="fill"] + mark[data-highlight-id][data-style="fill"] {
|
|
134
|
-
margin-left: 0; padding-left: 0;
|
|
135
|
-
}
|
|
136
|
-
`);
|
|
137
|
-
|
|
138
|
-
// Set up SVG background and selection handles
|
|
139
|
-
svgBackground = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
|
|
140
|
-
svgActiveOverlay = document.createElementNS('http://www.w3.org/2000/svg', 'g');
|
|
141
|
-
svgActiveOverlay.dataset.activeOverlay = '';
|
|
142
|
-
svgBackground.appendChild(svgActiveOverlay);
|
|
143
|
-
svgBackground.classList.add('hh-svg-background');
|
|
144
|
-
this.annotatableContainer.appendChild(svgBackground);
|
|
145
|
-
this.annotatableContainer.insertAdjacentHTML('beforeend', `
|
|
146
|
-
<div class="hh-selection-handle" data-side="left" data-position="start"><div draggable="true"></div><div class="hh-selection-handle-content"></div></div>
|
|
147
|
-
<div class="hh-selection-handle" data-side="right" data-position="end"><div draggable="true"></div><div class="hh-selection-handle-content"></div></div>
|
|
148
|
-
`);
|
|
149
|
-
selectionHandles = this.annotatableContainer.getElementsByClassName('hh-selection-handle');
|
|
150
|
-
|
|
151
|
-
// Check for hyperlinks on the page
|
|
152
|
-
hyperlinkElements = this.annotatableContainer.getElementsByTagName('a');
|
|
153
|
-
hyperlinksByPosition = {}
|
|
154
|
-
for (let hyp = 0; hyp < hyperlinkElements.length; hyp++) {
|
|
155
|
-
hyperlinksByPosition[hyp] = {
|
|
156
|
-
'position': hyp,
|
|
157
|
-
'text': hyperlinkElements[hyp].innerHTML,
|
|
158
|
-
'url': hyperlinkElements[hyp].href,
|
|
159
|
-
'hyperlinkElement': hyperlinkElements[hyp],
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
highlightsById = {};
|
|
164
|
-
this.annotatableContainer.dataset.hhContainer = '';
|
|
165
|
-
this.annotatableContainer.highlighter = this;
|
|
166
|
-
hhHighlighters.push(this);
|
|
167
|
-
|
|
168
|
-
return true;
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
const isInitialized = initializeHighlighter();
|
|
172
|
-
if (!isInitialized) return;
|
|
173
|
-
|
|
174
|
-
let activeHighlightId, previousSelectionRange, activeSelectionHandle, dragAnchorNode, dragAnchorOffset, pointerType, tapResult, doubleTapTimeoutId, longPressTimeoutId;
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
// -------- PUBLIC METHODS --------
|
|
178
|
-
|
|
179
|
-
// Load highlights
|
|
180
|
-
this.loadHighlights = (highlights) => {
|
|
181
|
-
// Don't load highlights until the document is ready (otherwise, highlights may be offset)
|
|
182
|
-
if (document.readyState !== 'complete') return setTimeout(this.loadHighlights, 10, highlights);
|
|
183
|
-
const startTimestamp = Date.now();
|
|
184
|
-
|
|
185
|
-
// Hide container (repeated DOM manipulations are faster if the container is hidden)
|
|
186
|
-
if (highlights.length > 1) (options.drawingMode === 'svg' ? svgBackground : this.annotatableContainer).style.display = 'none';
|
|
187
|
-
|
|
188
|
-
// Load read-only highlights first (read-only highlights change the DOM, affecting other highlights' ranges)
|
|
189
|
-
const sortedHighlights = highlights.sort((a,b) => a.readOnly === b.readOnly ? 0 : a.readOnly ? -1 : 1);
|
|
190
|
-
|
|
191
|
-
const knownHighlightIds = Object.keys(highlightsById);
|
|
192
|
-
let addedCount = 0, updatedCount = 0;
|
|
193
|
-
for (const highlight of sortedHighlights) {
|
|
194
|
-
const highlightInfo = diffHighlight(highlight, highlightsById[highlight.highlightId]);
|
|
195
|
-
highlightInfo.highlightId = highlight.highlightId;
|
|
196
|
-
const knownHighlightIndex = knownHighlightIds.indexOf(highlightInfo.highlightId);
|
|
197
|
-
if (knownHighlightIndex > -1) {
|
|
198
|
-
knownHighlightIds.splice(knownHighlightIndex, 1);
|
|
199
|
-
if (Object.keys(highlightInfo).length > 1) {
|
|
200
|
-
this.createOrUpdateHighlight(highlightInfo, false); updatedCount++;
|
|
201
|
-
}
|
|
202
|
-
} else {
|
|
203
|
-
this.createOrUpdateHighlight(highlightInfo, false); addedCount++;
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
if (knownHighlightIds.length > 0) this.removeHighlights(knownHighlightIds);
|
|
207
|
-
|
|
208
|
-
(options.drawingMode === 'svg' ? svgBackground : this.annotatableContainer).style.display = '';
|
|
209
|
-
this.annotatableContainer.dispatchEvent(new CustomEvent('hh:highlightsload', { detail: {
|
|
210
|
-
addedCount: addedCount, removedCount: knownHighlightIds.length, updatedCount: updatedCount,
|
|
211
|
-
totalCount: Object.keys(highlightsById).length,
|
|
212
|
-
timeToLoad: Date.now() - startTimestamp,
|
|
213
|
-
} }));
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
// Draw (or redraw) specified highlights, or all highlights on the page
|
|
217
|
-
this.drawHighlights = (highlightIds = Object.keys(highlightsById)) => {
|
|
218
|
-
// Hide container (repeated DOM manipulations is faster if the container is hidden)
|
|
219
|
-
if (highlightIds.length > 1) (options.drawingMode === 'svg' ? svgBackground : this.annotatableContainer).style.display = 'none';
|
|
220
|
-
|
|
221
|
-
for (const highlightId of highlightIds) {
|
|
222
|
-
const highlightInfo = highlightsById[highlightId];
|
|
223
|
-
let range = getCorrectedRangeObj(highlightId);
|
|
224
|
-
const rangeParagraphs = this.annotatableContainer.querySelectorAll(`#${highlightInfo.rangeParagraphIds.join(', #')}`);
|
|
225
|
-
const wasDrawnAsReadOnly = this.annotatableContainer.querySelector(`[data-highlight-id="${highlightId}"][data-read-only]`);
|
|
226
|
-
|
|
227
|
-
// Remove old highlight elements and styles
|
|
228
|
-
if (!wasDrawnAsReadOnly || (wasDrawnAsReadOnly && !highlightInfo.readOnly)) undrawHighlight(highlightInfo);
|
|
229
|
-
|
|
230
|
-
if (highlightInfo.readOnly || options.drawingMode === 'mark-elements') {
|
|
231
|
-
// Don't redraw a read-only highlight
|
|
232
|
-
if (wasDrawnAsReadOnly) continue;
|
|
233
|
-
|
|
234
|
-
// Inject HTML <mark> elements
|
|
235
|
-
range.startContainer.splitText(range.startOffset);
|
|
236
|
-
range.endContainer.splitText(range.endOffset);
|
|
237
|
-
const textNodeIter = document.createNodeIterator(range.commonAncestorContainer, NodeFilter.SHOW_TEXT);
|
|
238
|
-
const relevantTextNodes = [];
|
|
239
|
-
let node;
|
|
240
|
-
while (node = textNodeIter.nextNode()) {
|
|
241
|
-
if (range.intersectsNode(node) && node !== range.startContainer && node.textContent !== '' && !node.parentElement.closest('rt') && node.parentElement.closest(options.paragraphSelector)) relevantTextNodes.push(node);
|
|
242
|
-
if (node === range.endContainer) break;
|
|
243
|
-
}
|
|
244
|
-
const overlappingHighlightIds = new Set();
|
|
245
|
-
for (let tn = 0; tn < relevantTextNodes.length; tn++) {
|
|
246
|
-
const textNode = relevantTextNodes[tn];
|
|
247
|
-
if (textNode.parentElement.dataset.highlightId) {
|
|
248
|
-
overlappingHighlightIds.add(textNode.parentElement.dataset.highlightId);
|
|
249
|
-
}
|
|
250
|
-
const styledMark = document.createElement('mark');
|
|
251
|
-
styledMark.dataset.highlightId = highlightId;
|
|
252
|
-
if (highlightInfo.readOnly) styledMark.dataset.readOnly = '';
|
|
253
|
-
styledMark.dataset.color = highlightInfo.color;
|
|
254
|
-
styledMark.dataset.style = highlightInfo.style;
|
|
255
|
-
if (tn === 0) styledMark.dataset.start = '';
|
|
256
|
-
if (tn === relevantTextNodes.length - 1) styledMark.dataset.end = '';
|
|
257
|
-
textNode.before(styledMark);
|
|
258
|
-
styledMark.appendChild(textNode);
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
// Update highlight ranges that were invalidated by the DOM change
|
|
262
|
-
range = getCorrectedRangeObj(highlightId);
|
|
263
|
-
for (const overlappingHighlightId of overlappingHighlightIds) {
|
|
264
|
-
getCorrectedRangeObj(overlappingHighlightId);
|
|
265
|
-
}
|
|
266
|
-
} else {
|
|
267
|
-
// Draw highlights with Custom Highlight API
|
|
268
|
-
if (options.drawingMode === 'highlight-api' && supportsHighlightApi) {
|
|
269
|
-
let highlightObj;
|
|
270
|
-
if (CSS.highlights.has(highlightId)) {
|
|
271
|
-
highlightObj = CSS.highlights.get(highlightId);
|
|
272
|
-
highlightObj.clear();
|
|
273
|
-
} else {
|
|
274
|
-
highlightObj = new Highlight();
|
|
275
|
-
CSS.highlights.set(highlightId, highlightObj);
|
|
276
|
-
}
|
|
277
|
-
highlightObj.add(range);
|
|
278
|
-
const styleTemplate = getStyleTemplate(highlightInfo.style, 'css', null);
|
|
279
|
-
const colorString = options.colors[highlightInfo.color];
|
|
280
|
-
highlightApiStylesheet.insertRule(`${options.containerSelector} ::highlight(${highlightInfo.escapedHighlightId}) { --hh-color: ${colorString}; ${styleTemplate} }`);
|
|
281
|
-
highlightApiStylesheet.insertRule(`${options.containerSelector} rt::highlight(${highlightInfo.escapedHighlightId}) { color: inherit; background-color: transparent; }`);
|
|
282
|
-
highlightApiStylesheet.insertRule(`${options.containerSelector} img::highlight(${highlightInfo.escapedHighlightId}) { color: inherit; background-color: transparent; }`);
|
|
283
|
-
|
|
284
|
-
// Draw highlights with SVG shapes
|
|
285
|
-
} else if (options.drawingMode === 'svg') {
|
|
286
|
-
const clientRects = getMergedClientRects(range, rangeParagraphs);
|
|
287
|
-
let group = document.createElementNS('http://www.w3.org/2000/svg', 'g');
|
|
288
|
-
group.dataset.highlightId = highlightId;
|
|
289
|
-
group.dataset.color = highlightInfo.color;
|
|
290
|
-
group.dataset.style = highlightInfo.style;
|
|
291
|
-
let svgContent = '';
|
|
292
|
-
for (const clientRect of clientRects) {
|
|
293
|
-
svgContent += getStyleTemplate(highlightInfo.style, 'svg', clientRect);
|
|
294
|
-
}
|
|
295
|
-
group.innerHTML = svgContent;
|
|
296
|
-
svgBackground.appendChild(group);
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
// Update wrapper (for read-only highlights only)
|
|
301
|
-
if (highlightInfo.readOnly && !wasDrawnAsReadOnly) {
|
|
302
|
-
if (highlightInfo.wrapper && (options.wrappers[highlightInfo.wrapper]?.start || options.wrappers[highlightInfo.wrapper]?.end)) {
|
|
303
|
-
const addWrapper = (edge, range, htmlString) => {
|
|
304
|
-
htmlString = `<span class="hh-wrapper-${edge}" data-highlight-id="${highlightId}" data-color="${highlightInfo.color}" data-style="${highlightInfo.style}">${htmlString}</span>`
|
|
305
|
-
for (const key of Object.keys(highlightInfo.wrapperVariables)) {
|
|
306
|
-
htmlString = htmlString.replaceAll(`{${key}}`, highlightInfo.wrapperVariables[key]);
|
|
307
|
-
}
|
|
308
|
-
const template = document.createElement('template');
|
|
309
|
-
template.innerHTML = htmlString;
|
|
310
|
-
let htmlElement = template.content.firstChild;
|
|
311
|
-
|
|
312
|
-
let node;
|
|
313
|
-
const textNodeIter = document.createNodeIterator(htmlElement, NodeFilter.SHOW_TEXT);
|
|
314
|
-
while (node = textNodeIter.nextNode()) node.parentNode.removeChild(node);
|
|
315
|
-
range.insertNode(htmlElement);
|
|
316
|
-
}
|
|
317
|
-
const startRange = highlightInfo.rangeObj;
|
|
318
|
-
const endRange = document.createRange(); endRange.setStart(highlightInfo.rangeObj.endContainer, highlightInfo.rangeObj.endOffset);
|
|
319
|
-
const wrapperInfo = options.wrappers[highlightInfo.wrapper];
|
|
320
|
-
addWrapper('start', startRange, wrapperInfo.start);
|
|
321
|
-
addWrapper('end', endRange, wrapperInfo.end);
|
|
322
|
-
rangeParagraphs.forEach(p => { p.normalize(); });
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
// Show container
|
|
328
|
-
(options.drawingMode === 'svg' ? svgBackground : this.annotatableContainer).style.display = '';
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
// Create a new highlight, or update an existing highlight when it changes
|
|
332
|
-
this.createOrUpdateHighlight = (attributes = {}, triggeredByUserAction = true) => {
|
|
333
|
-
let highlightId = attributes.highlightId ?? activeHighlightId ?? options.highlightIdFunction();
|
|
334
|
-
const appearanceChanges = [];
|
|
335
|
-
const boundsChanges = [];
|
|
336
|
-
|
|
337
|
-
let isNewHighlight, oldHighlightInfo;
|
|
338
|
-
if (highlightsById.hasOwnProperty(highlightId)) {
|
|
339
|
-
oldHighlightInfo = highlightsById[highlightId];
|
|
340
|
-
} else {
|
|
341
|
-
isNewHighlight = true;
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
// If a different highlight is active, deactivate it
|
|
345
|
-
if (activeHighlightId && highlightId !== activeHighlightId && triggeredByUserAction === true) {
|
|
346
|
-
this.deactivateHighlights();
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
// If the highlight is currently activate, ignore bounds changes that weren't initiated by the user
|
|
350
|
-
if (highlightId === activeHighlightId && triggeredByUserAction === false) {
|
|
351
|
-
attributes.startParagraphId = null;
|
|
352
|
-
attributes.startParagraphOffset = null;
|
|
353
|
-
attributes.endParagraphId = null;
|
|
354
|
-
attributes.endParagraphOffset = null;
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
// Warn if color, style, or wrapper attributes are invalid
|
|
358
|
-
if (attributes.color && !options.colors.hasOwnProperty(attributes.color)) {
|
|
359
|
-
console.warn(`Highlight color "${attributes.color}" is not defined in options (highlightId: ${highlightId}).`);
|
|
360
|
-
}
|
|
361
|
-
if (attributes.style && !options.styles.hasOwnProperty(attributes.style)) {
|
|
362
|
-
console.warn(`Highlight style "${attributes.style}" is not defined in options (highlightId: ${highlightId}).`);
|
|
363
|
-
}
|
|
364
|
-
if (attributes.wrapper && !options.wrappers.hasOwnProperty(attributes.wrapper)) {
|
|
365
|
-
console.warn(`Highlight wrapper "${attributes.wrapper}" is not defined in options (highlightId: ${highlightId}).`);
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
// Update defaults
|
|
369
|
-
if (options.rememberStyle && triggeredByUserAction) {
|
|
370
|
-
if (attributes.color) options.defaultColor = attributes.color;
|
|
371
|
-
if (attributes.style) options.defaultStyle = attributes.style;
|
|
372
|
-
if (attributes.wrapper) options.defaultWrapper = attributes.wrapper;
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
// Check which appearance properties changed
|
|
376
|
-
for (const key of ['color', 'style', 'wrapper', 'wrapperVariables', 'readOnly']) {
|
|
377
|
-
if (isNewHighlight || (attributes[key] != null && attributes[key] !== oldHighlightInfo[key])) appearanceChanges.push(key);
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
// If the highlight was and still is read-only, return
|
|
381
|
-
if (oldHighlightInfo?.readOnly && (attributes.readOnly == null || attributes.readOnly === true)) return this.deactivateHighlights();
|
|
382
|
-
|
|
383
|
-
// Calculate the bounds of the highlight range, if it's changed
|
|
384
|
-
let adjustedSelectionRange, highlightRange;
|
|
385
|
-
let rangeText, rangeHtml, rangeParagraphIds;
|
|
386
|
-
let startParagraphId, startParagraphOffset, endParagraphId, endParagraphOffset;
|
|
387
|
-
const selection = getRestoredSelectionOrCaret(window.getSelection());
|
|
388
|
-
if (selection.type === 'Range') adjustedSelectionRange = snapRangeToBoundaries(selection.getRangeAt(0));
|
|
389
|
-
if ((attributes.startParagraphId ?? attributes.startParagraphOffset ?? attributes.endParagraphId ?? attributes.endParagraphOffset != null) || (adjustedSelectionRange && !adjustedSelectionRange.collapsed)) {
|
|
390
|
-
let startNode, startOffset, endNode, endOffset;
|
|
391
|
-
if (attributes.startParagraphId ?? attributes.startParagraphOffset ?? attributes.endParagraphId ?? attributes.endParagraphOffset != null) {
|
|
392
|
-
startParagraphId = attributes.startParagraphId ?? oldHighlightInfo?.startParagraphId;
|
|
393
|
-
startParagraphOffset = parseInt(attributes.startParagraphOffset ?? oldHighlightInfo?.startParagraphOffset);
|
|
394
|
-
endParagraphId = attributes.endParagraphId ?? oldHighlightInfo?.endParagraphId;
|
|
395
|
-
endParagraphOffset = parseInt(attributes.endParagraphOffset ?? oldHighlightInfo?.endParagraphOffset);
|
|
396
|
-
([ startNode, startOffset ] = getTextNodeAndOffset(document.getElementById(startParagraphId), startParagraphOffset));
|
|
397
|
-
([ endNode, endOffset ] = getTextNodeAndOffset(document.getElementById(endParagraphId), endParagraphOffset));
|
|
398
|
-
} else if (adjustedSelectionRange) {
|
|
399
|
-
startNode = adjustedSelectionRange.startContainer;
|
|
400
|
-
startOffset = adjustedSelectionRange.startOffset;
|
|
401
|
-
endNode = adjustedSelectionRange.endContainer;
|
|
402
|
-
endOffset = adjustedSelectionRange.endOffset;
|
|
403
|
-
([ startParagraphId, startParagraphOffset ] = getParagraphOffset(startNode, startOffset));
|
|
404
|
-
([ endParagraphId, endParagraphOffset ] = getParagraphOffset(endNode, endOffset));
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
// Create a new highlight range
|
|
408
|
-
highlightRange = document.createRange();
|
|
409
|
-
highlightRange.setStart(startNode, startOffset);
|
|
410
|
-
highlightRange.setEnd(endNode, endOffset);
|
|
411
|
-
|
|
412
|
-
// Check which bounds properties changed
|
|
413
|
-
for (const key of ['startParagraphId', 'startParagraphOffset', 'endParagraphId', 'endParagraphOffset']) {
|
|
414
|
-
if (isNewHighlight || eval(key) !== oldHighlightInfo[key]) boundsChanges.push(key);
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
// Set variables that depend on the range
|
|
418
|
-
const temporaryHtmlElement = document.createElement('div');
|
|
419
|
-
temporaryHtmlElement.appendChild(highlightRange.cloneContents());
|
|
420
|
-
for (const element of temporaryHtmlElement.querySelectorAll(`a, [data-highlight-id]:not([data-highlight-id="${highlightId}"])`)) element.outerHTML = element.innerHTML;
|
|
421
|
-
rangeText = highlightRange.toString();
|
|
422
|
-
rangeHtml = temporaryHtmlElement.innerHTML;
|
|
423
|
-
let startParagraphIndex = annotatableParagraphIds.indexOf(startParagraphId);
|
|
424
|
-
let endParagraphIndex = annotatableParagraphIds.indexOf(endParagraphId);
|
|
425
|
-
if (startParagraphIndex === -1) startParagraphIndex = 0;
|
|
426
|
-
if (endParagraphIndex === -1) endParagraphIndex = annotatableParagraphIds.length - 1;
|
|
427
|
-
rangeParagraphIds = annotatableParagraphIds.slice(startParagraphIndex, endParagraphIndex + 1);
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
// If there are no valid changes, return
|
|
431
|
-
if (!highlightRange || highlightRange.toString() === '' || appearanceChanges.length + boundsChanges.length === 0) return;
|
|
432
|
-
|
|
433
|
-
// Update saved highlight info
|
|
434
|
-
const newHighlightInfo = {
|
|
435
|
-
highlightId: highlightId,
|
|
436
|
-
color: attributes?.color ?? oldHighlightInfo?.color ?? options.defaultColor,
|
|
437
|
-
style: attributes?.style ?? oldHighlightInfo?.style ?? options.defaultStyle,
|
|
438
|
-
wrapper: attributes?.wrapper ?? oldHighlightInfo?.wrapper ?? options.defaultWrapper,
|
|
439
|
-
wrapperVariables: attributes?.wrapperVariables ?? oldHighlightInfo?.wrapperVariables ?? {},
|
|
440
|
-
readOnly: attributes?.readOnly ?? oldHighlightInfo?.readOnly ?? false,
|
|
441
|
-
startParagraphId: startParagraphId ?? oldHighlightInfo?.startParagraphId,
|
|
442
|
-
startParagraphOffset: startParagraphOffset ?? oldHighlightInfo?.startParagraphOffset,
|
|
443
|
-
endParagraphId: endParagraphId ?? oldHighlightInfo?.endParagraphId,
|
|
444
|
-
endParagraphOffset: endParagraphOffset ?? oldHighlightInfo?.endParagraphOffset,
|
|
445
|
-
// Read-only properties
|
|
446
|
-
escapedHighlightId: CSS.escape(highlightId),
|
|
447
|
-
rangeText: rangeText ?? oldHighlightInfo?.rangeText,
|
|
448
|
-
rangeHtml: rangeHtml ?? oldHighlightInfo?.rangeHtml,
|
|
449
|
-
rangeParagraphIds: rangeParagraphIds ?? oldHighlightInfo?.rangeParagraphIds,
|
|
450
|
-
rangeObj: highlightRange ?? oldHighlightInfo?.rangeObj,
|
|
451
|
-
};
|
|
452
|
-
highlightsById[highlightId] = newHighlightInfo;
|
|
453
|
-
|
|
454
|
-
const detail = {
|
|
455
|
-
highlight: newHighlightInfo,
|
|
456
|
-
changes: appearanceChanges.concat(boundsChanges),
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
if (triggeredByUserAction && !activeHighlightId) {
|
|
460
|
-
this.activateHighlight(highlightId);
|
|
461
|
-
} else if (activeHighlightId && highlightId === activeHighlightId && appearanceChanges.length > 0) {
|
|
462
|
-
updateSelectionUi('appearance');
|
|
463
|
-
} else if (highlightId !== activeHighlightId) {
|
|
464
|
-
this.drawHighlights([highlightId]);
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
if (isNewHighlight) {
|
|
468
|
-
this.annotatableContainer.dispatchEvent(new CustomEvent('hh:highlightcreate', { detail: detail }));
|
|
469
|
-
} else {
|
|
470
|
-
this.annotatableContainer.dispatchEvent(new CustomEvent('hh:highlightupdate', { detail: detail }));
|
|
471
|
-
}
|
|
8
|
+
/********************** Highlighter Initialization **********************/
|
|
9
|
+
|
|
10
|
+
function Highlighter(options = _defaultOptions) {
|
|
11
|
+
for (const key of Object.keys(_defaultOptions)) {
|
|
12
|
+
options[key] = options[key] ?? _defaultOptions[key];
|
|
472
13
|
}
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
14
|
+
this._options = options;
|
|
15
|
+
|
|
16
|
+
// DOM references
|
|
17
|
+
this._annotatableContainer = null;
|
|
18
|
+
this._relativeAncestorElement = null;
|
|
19
|
+
this._annotatableParagraphs = null;
|
|
20
|
+
this._svgBackground = null;
|
|
21
|
+
this._svgActiveOverlay = null;
|
|
22
|
+
this._selectionHandles = null;
|
|
23
|
+
|
|
24
|
+
// Stylesheets
|
|
25
|
+
this._stylesheets = null;
|
|
26
|
+
this._generalStylesheet = null;
|
|
27
|
+
this._appearanceStylesheet = null;
|
|
28
|
+
this._highlightApiStylesheet = null;
|
|
29
|
+
this._selectionStylesheet = null;
|
|
30
|
+
|
|
31
|
+
// Data and state
|
|
32
|
+
this._annotatableParagraphIds = null;
|
|
33
|
+
this._hyperlinkElements = null;
|
|
34
|
+
this._hyperlinksByPosition = null;
|
|
35
|
+
this._highlightsById = null;
|
|
36
|
+
|
|
37
|
+
// Abort controller
|
|
38
|
+
this._controller = null;
|
|
39
|
+
|
|
40
|
+
const isInitialized = this._initializeHighlighter();
|
|
41
|
+
if (!isInitialized) return;
|
|
42
|
+
|
|
43
|
+
// Interaction state
|
|
44
|
+
this._activeHighlightId = undefined;
|
|
45
|
+
this._previousSelectionRange = undefined;
|
|
46
|
+
this._activeSelectionHandle = undefined;
|
|
47
|
+
this._dragAnchorNode = undefined;
|
|
48
|
+
this._dragAnchorOffset = undefined;
|
|
49
|
+
this._pointerType = undefined;
|
|
50
|
+
this._tapResult = undefined;
|
|
51
|
+
this._doubleTapTimeoutId = undefined;
|
|
52
|
+
this._longPressTimeoutId = undefined;
|
|
53
|
+
this._allowHyperlinkClick = false;
|
|
54
|
+
|
|
55
|
+
this._loadStyles();
|
|
56
|
+
this._loadEventListeners();
|
|
57
|
+
|
|
58
|
+
this._updateAppearanceStylesheet();
|
|
59
|
+
this._updateSelectionUi('appearance');
|
|
60
|
+
this.setOptions({ selectionHandles: this._options.selectionHandles });
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
Highlighter.prototype._initializeHighlighter = function (previousContainerSelector = null) {
|
|
64
|
+
const options = this._options;
|
|
65
|
+
if (!options.paragraphSelector.includes(options.containerSelector)) {
|
|
66
|
+
const paragraphSelectorList = options.paragraphSelector.split(',').map(selector => `${options.containerSelector} ${selector}`);
|
|
67
|
+
options.paragraphSelector = paragraphSelectorList.join(',');
|
|
502
68
|
}
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
this.deactivateHighlights = (removeSelectionRanges = true) => {
|
|
515
|
-
const deactivatedHighlight = highlightsById[activeHighlightId];
|
|
516
|
-
activeHighlightId = null;
|
|
517
|
-
previousSelectionRange = null;
|
|
518
|
-
const selection = window.getSelection();
|
|
519
|
-
if (removeSelectionRanges && selection.anchorNode && this.annotatableContainer.contains(selection.anchorNode)) {
|
|
520
|
-
selection.collapseToStart();
|
|
521
|
-
}
|
|
522
|
-
updateSelectionUi('appearance');
|
|
523
|
-
if (deactivatedHighlight) {
|
|
524
|
-
this.drawHighlights([deactivatedHighlight.highlightId]);
|
|
525
|
-
this.annotatableContainer.dispatchEvent(new CustomEvent('hh:highlightdeactivate', { detail: {
|
|
526
|
-
highlight: deactivatedHighlight,
|
|
527
|
-
}}));
|
|
528
|
-
}
|
|
69
|
+
this._annotatableContainer = document.querySelector(options.containerSelector);
|
|
70
|
+
this._annotatableParagraphs = this._annotatableContainer.querySelectorAll(options.paragraphSelector);
|
|
71
|
+
this._annotatableParagraphIds = Array.from(this._annotatableParagraphs, paragraph => paragraph.id);
|
|
72
|
+
|
|
73
|
+
// Handle cases where a highlighter already exists for the container, or one of its children or ancestors
|
|
74
|
+
const previousContainer = document.querySelector(previousContainerSelector) ?? this._annotatableContainer;
|
|
75
|
+
if (previousContainer.highlighter) {
|
|
76
|
+
previousContainer.highlighter.removeHighlighter();
|
|
77
|
+
} else if (this._annotatableContainer.closest('[data-hh-container]') || this._annotatableContainer.querySelector('[data-hh-container]')) {
|
|
78
|
+
console.error(`Unable to create Highlighter with container selector "${options.containerSelector}" (annotatable container can't be an child or ancestor of another annotatable container).`);
|
|
79
|
+
return false;
|
|
529
80
|
}
|
|
530
|
-
|
|
531
|
-
//
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
highlightId: highlightId,
|
|
540
|
-
}}));
|
|
541
|
-
undrawHighlight(highlightInfo);
|
|
542
|
-
}
|
|
543
|
-
}
|
|
81
|
+
|
|
82
|
+
// Get the closest ancestor element with `position: relative`, or the root element (this is used to calculate the position of selection handles and SVG highlights)
|
|
83
|
+
let ancestorElement = this._annotatableContainer;
|
|
84
|
+
while (ancestorElement) {
|
|
85
|
+
if (ancestorElement === document.documentElement || globalThis.getComputedStyle(ancestorElement).position === 'relative') {
|
|
86
|
+
this._relativeAncestorElement = ancestorElement;
|
|
87
|
+
break;
|
|
88
|
+
}
|
|
89
|
+
ancestorElement = ancestorElement.parentElement;
|
|
544
90
|
}
|
|
545
|
-
|
|
546
|
-
//
|
|
547
|
-
this.
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
}
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
this.drawHighlights();
|
|
577
|
-
} else if (key === 'colors') {
|
|
578
|
-
updateAppearanceStylesheet();
|
|
579
|
-
} else if (key === 'containerSelector') {
|
|
580
|
-
this.removeHighlighter();
|
|
581
|
-
initializeHighlighter();
|
|
582
|
-
} else if (key === 'paragraphSelector') {
|
|
583
|
-
initializeHighlighter();
|
|
584
|
-
} else if (key === 'selectionHandles') {
|
|
585
|
-
for (const selectionHandle of selectionHandles) {
|
|
586
|
-
selectionHandle.children[1].innerHTML = options.selectionHandles[selectionHandle.dataset.side] ?? '';
|
|
587
|
-
}
|
|
91
|
+
|
|
92
|
+
// Abort controller can be used to cancel event listeners if the highlighter is removed
|
|
93
|
+
this._controller = new AbortController;
|
|
94
|
+
|
|
95
|
+
// Setting tabIndex -1 on <body> allows focus to be set programmatically (needed to initialize text selection in iOS Safari). It also prevents "tap to search" from interfering with text selection in Android Chrome.
|
|
96
|
+
document.body.tabIndex = -1;
|
|
97
|
+
|
|
98
|
+
// Set up SVG background and selection handles
|
|
99
|
+
this._svgBackground = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
|
|
100
|
+
this._svgActiveOverlay = document.createElementNS('http://www.w3.org/2000/svg', 'g');
|
|
101
|
+
this._svgActiveOverlay.dataset.activeOverlay = '';
|
|
102
|
+
this._svgBackground.appendChild(this._svgActiveOverlay);
|
|
103
|
+
this._svgBackground.classList.add('hh-svg-background');
|
|
104
|
+
this._annotatableContainer.appendChild(this._svgBackground);
|
|
105
|
+
this._annotatableContainer.insertAdjacentHTML('beforeend', `
|
|
106
|
+
<div class="hh-selection-handle" data-side="left" data-position="start" data-hh-ignore=""><div draggable="true"></div><div class="hh-selection-handle-content"></div></div>
|
|
107
|
+
<div class="hh-selection-handle" data-side="right" data-position="end" data-hh-ignore=""><div draggable="true"></div><div class="hh-selection-handle-content"></div></div>
|
|
108
|
+
`);
|
|
109
|
+
this._selectionHandles = this._annotatableContainer.getElementsByClassName('hh-selection-handle');
|
|
110
|
+
|
|
111
|
+
// Check for hyperlinks on the page
|
|
112
|
+
this._hyperlinkElements = this._annotatableContainer.getElementsByTagName('a');
|
|
113
|
+
this._hyperlinksByPosition = {}
|
|
114
|
+
for (let hyp = 0; hyp < this._hyperlinkElements.length; hyp++) {
|
|
115
|
+
const hyperlink = this._hyperlinkElements[hyp];
|
|
116
|
+
hyperlink.dataset.hhPosition = hyp;
|
|
117
|
+
this._hyperlinksByPosition[hyp] = {
|
|
118
|
+
'position': hyp,
|
|
119
|
+
'text': hyperlink.innerHTML,
|
|
120
|
+
'url': hyperlink.href,
|
|
121
|
+
'hyperlinkElement': hyperlink,
|
|
588
122
|
}
|
|
589
123
|
}
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
this.
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
124
|
+
|
|
125
|
+
this._highlightsById = {};
|
|
126
|
+
this._annotatableContainer.dataset.hhContainer = '';
|
|
127
|
+
this._annotatableContainer.highlighter = this;
|
|
128
|
+
_highlighters.push(this);
|
|
129
|
+
|
|
130
|
+
return true;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
Highlighter.prototype._loadStyles = function () {
|
|
134
|
+
const options = this._options;
|
|
135
|
+
|
|
136
|
+
// Set up stylesheets
|
|
137
|
+
this._stylesheets = {}
|
|
138
|
+
this._generalStylesheet = addStylesheet(this._stylesheets, 'general');
|
|
139
|
+
this._appearanceStylesheet = addStylesheet(this._stylesheets, 'appearance');
|
|
140
|
+
this._highlightApiStylesheet = addStylesheet(this._stylesheets, 'highlight-api');
|
|
141
|
+
this._selectionStylesheet = addStylesheet(this._stylesheets, 'selection');
|
|
142
|
+
this._generalStylesheet.replaceSync(`
|
|
143
|
+
${options.containerSelector} {
|
|
144
|
+
-webkit-tap-highlight-color: transparent;
|
|
145
|
+
}
|
|
146
|
+
.hh-wrapper-start, .hh-wrapper-end, .hh-selection-handle {
|
|
147
|
+
-webkit-user-select: none;
|
|
148
|
+
user-select: none;
|
|
149
|
+
}
|
|
150
|
+
.hh-selection-handle {
|
|
151
|
+
position: absolute;
|
|
152
|
+
width: 0px;
|
|
153
|
+
visibility: hidden;
|
|
154
|
+
}
|
|
155
|
+
[data-hh-pointer-down="true"] .hh-selection-handle {
|
|
156
|
+
visibility: hidden !important;
|
|
157
|
+
}
|
|
158
|
+
.hh-selection-handle-content {
|
|
159
|
+
position: absolute;
|
|
160
|
+
height: 100%;
|
|
161
|
+
}
|
|
162
|
+
.hh-selection-handle [draggable] {
|
|
163
|
+
position: absolute;
|
|
164
|
+
top: -0.3em;
|
|
165
|
+
width: 3.2em;
|
|
166
|
+
height: calc(100% + 1.3em);
|
|
167
|
+
background-color: transparent;
|
|
168
|
+
z-index: 1;
|
|
169
|
+
}
|
|
170
|
+
.hh-selection-handle[data-side="left"] [draggable] { right: -2em; }
|
|
171
|
+
.hh-selection-handle[data-side="right"] [draggable] { left: -2em; }
|
|
172
|
+
.hh-default-handle {
|
|
173
|
+
position: absolute;
|
|
174
|
+
width: 0.8em;
|
|
175
|
+
height: min(1.2em, 100%);
|
|
176
|
+
background-color: hsl(from var(--hh-color) h 80% 40% / 1);
|
|
177
|
+
outline: 0.1em solid hsla(0, 0%, 100%, 0.8);
|
|
178
|
+
outline-offset: -0.05em;
|
|
179
|
+
bottom: -0.2em;
|
|
180
|
+
}
|
|
181
|
+
.hh-selection-handle[data-side="left"] .hh-default-handle {
|
|
182
|
+
right: 0;
|
|
183
|
+
border-radius: 1em 0 0.6em 0.6em;
|
|
184
|
+
}
|
|
185
|
+
.hh-selection-handle[data-side="right"] .hh-default-handle {
|
|
186
|
+
left: 0;
|
|
187
|
+
border-radius: 0 1em 0.6em 0.6em;
|
|
188
|
+
}
|
|
189
|
+
.hh-svg-background {
|
|
190
|
+
position: absolute;
|
|
191
|
+
top: 0;
|
|
192
|
+
left: 0;
|
|
193
|
+
width: 100%;
|
|
194
|
+
overflow: visible;
|
|
195
|
+
z-index: -1;
|
|
196
|
+
}
|
|
197
|
+
.hh-svg-background g {
|
|
198
|
+
fill: transparent;
|
|
199
|
+
stroke: none;
|
|
200
|
+
}
|
|
201
|
+
mark[data-highlight-id] {
|
|
202
|
+
background-color: transparent;
|
|
203
|
+
color: inherit;
|
|
204
|
+
}
|
|
205
|
+
`);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
Highlighter.prototype._loadEventListeners = function () {
|
|
209
|
+
const options = this._options;
|
|
210
|
+
|
|
611
211
|
// Selection change in document (new selection, change in selection range, or selection collapsing to a caret)
|
|
612
|
-
document.addEventListener('selectionchange', (event) => respondToSelectionChange(event), { signal: controller.signal });
|
|
613
212
|
const respondToSelectionChange = (event) => {
|
|
614
|
-
const selection =
|
|
213
|
+
const selection = this._getRestoredSelectionOrCaret(globalThis.getSelection());
|
|
615
214
|
const selectionRange = selection.type === 'None' ? null : selection.getRangeAt(0);
|
|
616
|
-
|
|
215
|
+
|
|
617
216
|
// In "Mac (Designed for iPad)" apps (iPad app running on macOS – most recently tested with macOS Sequoia 15.3.1), in-app webviews have several quirks related to text selection. One of these is text selection collapsing to a caret more often than expected. This code attempts to restore the previous selection range if it unexpectedly collapses to a caret in these scenarios:
|
|
618
217
|
// 1. While dragging custom selection handles (happens randomly). TODO: Dragging custom selection handles in this environment is still sometimes a little jumpy.
|
|
619
218
|
// 2. Just after clicking to activate a highlight (happens if it's the first click after the page loads).
|
|
620
|
-
if (isWKWebView && !isTouchDevice && selection.type !== 'Range' &&
|
|
621
|
-
selection.setBaseAndExtent(
|
|
219
|
+
if (isWKWebView && !isTouchDevice && selection.type !== 'Range' && this._previousSelectionRange && (this._activeSelectionHandle || (this._previousSelectionRange.compareBoundaryPoints(Range.END_TO_START, selectionRange) <= 0 && this._previousSelectionRange.compareBoundaryPoints(Range.END_TO_END, selectionRange) >= 0))) {
|
|
220
|
+
selection.setBaseAndExtent(this._previousSelectionRange.startContainer, this._previousSelectionRange.startOffset, this._previousSelectionRange.endContainer, this._previousSelectionRange.endOffset);
|
|
622
221
|
}
|
|
623
|
-
|
|
222
|
+
|
|
624
223
|
// Deactivate highlights when tapping or creating a selection outside of the previous selection range
|
|
625
|
-
if (!
|
|
224
|
+
if (!this._activeSelectionHandle && this._previousSelectionRange && (selection.type !== 'Range' || this._previousSelectionRange.comparePoint(selectionRange.startContainer, selectionRange.startOffset) === 1 || this._previousSelectionRange.comparePoint(selectionRange.endContainer, selectionRange.endOffset) === -1)) {
|
|
626
225
|
this.deactivateHighlights(false);
|
|
627
226
|
}
|
|
628
|
-
|
|
227
|
+
|
|
629
228
|
if (selection.type === 'Range') {
|
|
630
229
|
// Clear tap result (prevents hh:tap event from being sent when long-pressing or dragging to select text)
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
if (this.
|
|
634
|
-
if (
|
|
635
|
-
this.createOrUpdateHighlight({ highlightId:
|
|
230
|
+
this._tapResult = null;
|
|
231
|
+
|
|
232
|
+
if (this._annotatableContainer.contains(selection.anchorNode)) {
|
|
233
|
+
if (this._activeHighlightId || (options.pointerMode === 'live' || (options.pointerMode === 'auto' && this._pointerType === 'pen'))) {
|
|
234
|
+
this.createOrUpdateHighlight({ highlightId: this._activeHighlightId, });
|
|
636
235
|
}
|
|
637
|
-
|
|
236
|
+
this._previousSelectionRange = selectionRange.cloneRange();
|
|
638
237
|
}
|
|
639
238
|
}
|
|
640
|
-
|
|
641
|
-
|
|
239
|
+
|
|
240
|
+
this._updateSelectionUi('bounds');
|
|
642
241
|
}
|
|
643
|
-
|
|
242
|
+
document.addEventListener('selectionchange', (event) => respondToSelectionChange(event), { signal: this._controller.signal });
|
|
243
|
+
|
|
644
244
|
// Pointer down in annotatable container
|
|
645
|
-
this.annotatableContainer.addEventListener('pointerdown', (event) => respondToPointerDown(event), { signal: controller.signal });
|
|
646
245
|
const respondToPointerDown = (event) => {
|
|
647
246
|
const isSecondaryClick = (event.button !== 0 || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey);
|
|
648
|
-
if (!isSecondaryClick) this.
|
|
649
|
-
|
|
650
|
-
|
|
247
|
+
if (!isSecondaryClick) this._annotatableContainer.dataset.hhPointerDown = 'true';
|
|
248
|
+
this._pointerType = event.pointerType;
|
|
249
|
+
|
|
651
250
|
// Pointer down on a selection handle
|
|
652
251
|
if (event.target?.closest('.hh-selection-handle')) {
|
|
653
252
|
if (!isSecondaryClick) {
|
|
654
|
-
|
|
655
|
-
const selectionHandleClientRect =
|
|
253
|
+
this._activeSelectionHandle = event.target.parentElement.closest('.hh-selection-handle');
|
|
254
|
+
const selectionHandleClientRect = this._activeSelectionHandle.getBoundingClientRect();
|
|
656
255
|
const lineHeight = selectionHandleClientRect.bottom - selectionHandleClientRect.top;
|
|
657
|
-
|
|
658
|
-
const selectionRange =
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
this.
|
|
662
|
-
|
|
256
|
+
this._activeSelectionHandle.dataset.dragYOffset = Math.max(0, event.clientY - selectionHandleClientRect.bottom + (lineHeight / 6));
|
|
257
|
+
const selectionRange = globalThis.getSelection().getRangeAt(0);
|
|
258
|
+
this._dragAnchorNode = this._activeSelectionHandle.dataset.position === 'start' ? selectionRange.endContainer : selectionRange.startContainer;
|
|
259
|
+
this._dragAnchorOffset = this._activeSelectionHandle.dataset.position === 'start' ? selectionRange.endOffset : selectionRange.startOffset;
|
|
260
|
+
this._annotatableContainer.addEventListener('pointermove', respondToSelectionHandleDrag, { signal: this._controller.signal });
|
|
261
|
+
this._updateSelectionUi('bounds');
|
|
663
262
|
}
|
|
664
263
|
// Prevent default drag interaction (which would show a thumbnail and drag selected text)
|
|
665
264
|
return event.preventDefault();
|
|
666
265
|
}
|
|
667
|
-
|
|
266
|
+
|
|
668
267
|
// Deactivate highlights and return on double-tap. This fixes a bug where double-tapping and holding a word in a highlight in iOS Safari caused the highlight to activate then shrink to the selected word.
|
|
669
|
-
if (
|
|
268
|
+
if (this._doubleTapTimeoutId) {
|
|
670
269
|
return this.deactivateHighlights();
|
|
671
270
|
} else {
|
|
672
|
-
|
|
271
|
+
this._doubleTapTimeoutId = setTimeout(() => this._doubleTapTimeoutId = clearTimeout(this._doubleTapTimeoutId), 500);
|
|
673
272
|
}
|
|
674
|
-
|
|
273
|
+
|
|
675
274
|
// Return if it's not a regular click, or if the user is tapping away from an existing selection
|
|
676
|
-
if (
|
|
677
|
-
|
|
275
|
+
if (this._previousSelectionRange || isSecondaryClick) return;
|
|
276
|
+
|
|
678
277
|
// Trigger a long-press event if the user doesn't lift their finger within the specified time
|
|
679
|
-
if (options.longPressTimeout)
|
|
680
|
-
|
|
681
|
-
|
|
278
|
+
if (options.longPressTimeout) this._longPressTimeoutId = setTimeout(() => respondToLongPress(event), options.longPressTimeout);
|
|
279
|
+
|
|
280
|
+
this._tapResult = this._checkForTapTargets(event);
|
|
682
281
|
}
|
|
683
|
-
|
|
282
|
+
this._annotatableContainer.addEventListener('pointerdown', (event) => respondToPointerDown(event), { signal: this._controller.signal });
|
|
283
|
+
|
|
684
284
|
// Selection handle drag (this function is added as an event listener on pointerdown, and removed on pointerup)
|
|
685
285
|
const respondToSelectionHandleDrag = (event) => {
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
const selection =
|
|
286
|
+
this._activeSelectionHandle.dataset.pointerXPosition = event.clientX;
|
|
287
|
+
this._activeSelectionHandle.dataset.pointerYPosition = event.clientY;
|
|
288
|
+
const selection = globalThis.getSelection();
|
|
689
289
|
const selectionRange = selection.getRangeAt(0);
|
|
690
|
-
const dragCaret =
|
|
691
|
-
|
|
290
|
+
const dragCaret = this._getCaretFromCoordinates(event.clientX, event.clientY - this._activeSelectionHandle.dataset.dragYOffset, true, false, true);
|
|
291
|
+
|
|
692
292
|
// Return if there's no drag caret, if the drag caret is invalid, or if the drag caret and anchor caret have the same position
|
|
693
|
-
if (!dragCaret || dragCaret.startContainer.nodeType !== Node.TEXT_NODE || dragCaret.endContainer.nodeType !== Node.TEXT_NODE || (
|
|
694
|
-
|
|
293
|
+
if (!dragCaret || dragCaret.startContainer.nodeType !== Node.TEXT_NODE || dragCaret.endContainer.nodeType !== Node.TEXT_NODE || (this._dragAnchorNode === dragCaret.endContainer && this._dragAnchorOffset === dragCaret.endOffset)) return;
|
|
294
|
+
|
|
695
295
|
// Check if start and end selection handles switched positions
|
|
696
296
|
const dragPositionRelativeToSelectionStart = dragCaret.compareBoundaryPoints(Range.START_TO_END, selectionRange);
|
|
697
297
|
const dragPositionRelativeToSelectionEnd = dragCaret.compareBoundaryPoints(Range.END_TO_END, selectionRange);
|
|
698
|
-
if (
|
|
699
|
-
for (const selectionHandle of
|
|
298
|
+
if (this._activeSelectionHandle.dataset.position === 'start' && dragPositionRelativeToSelectionEnd === 1 || this._activeSelectionHandle.dataset.position === 'end' && dragPositionRelativeToSelectionStart === -1) {
|
|
299
|
+
for (const selectionHandle of this._selectionHandles) {
|
|
700
300
|
selectionHandle.dataset.position = selectionHandle.dataset.position === 'start' ? 'end' : 'start';
|
|
701
301
|
}
|
|
702
302
|
}
|
|
703
|
-
|
|
303
|
+
|
|
704
304
|
// Update selection
|
|
705
|
-
selection.setBaseAndExtent(
|
|
305
|
+
selection.setBaseAndExtent(this._dragAnchorNode, this._dragAnchorOffset, dragCaret.endContainer, dragCaret.endOffset);
|
|
706
306
|
}
|
|
707
|
-
|
|
307
|
+
|
|
708
308
|
// Long press in annotatable container (triggered by setTimeout() in pointerdown event)
|
|
709
309
|
const respondToLongPress = (event) => {
|
|
710
310
|
respondToPointerUp(event, true);
|
|
711
|
-
|
|
311
|
+
this._tapResult = null;
|
|
712
312
|
}
|
|
713
|
-
|
|
313
|
+
|
|
714
314
|
// Pointer up in annotatable container
|
|
715
|
-
this.annotatableContainer.addEventListener('pointerup', (event) => respondToPointerUp(event), { signal: controller.signal });
|
|
716
315
|
const respondToPointerUp = (event, isLongPress = false) => {
|
|
717
|
-
if (
|
|
718
|
-
|
|
719
|
-
this.
|
|
720
|
-
if (options.autoTapToActivate &&
|
|
721
|
-
if (
|
|
722
|
-
return this.
|
|
723
|
-
} else if (
|
|
724
|
-
return this.
|
|
725
|
-
} else if (
|
|
726
|
-
return this.
|
|
316
|
+
if (this._tapResult) {
|
|
317
|
+
this._tapResult.isLongPress = isLongPress;
|
|
318
|
+
this._annotatableContainer.dispatchEvent(new CustomEvent('hh:tap', { detail: this._tapResult, }));
|
|
319
|
+
if (options.autoTapToActivate && this._tapResult?.targetFound && !isLongPress) {
|
|
320
|
+
if (this._tapResult.targetCount > 1) {
|
|
321
|
+
return this._annotatableContainer.dispatchEvent(new CustomEvent('hh:ambiguousaction', { detail: this._tapResult, }));
|
|
322
|
+
} else if (this._tapResult.highlights.length === 1) {
|
|
323
|
+
return this.activateHighlight(this._tapResult.highlights[0].highlightId);
|
|
324
|
+
} else if (this._tapResult.hyperlinks.length === 1) {
|
|
325
|
+
return this.activateHyperlink(this._tapResult.hyperlinks[0].position);
|
|
727
326
|
}
|
|
728
327
|
}
|
|
729
328
|
}
|
|
730
329
|
}
|
|
731
|
-
|
|
330
|
+
this._annotatableContainer.addEventListener('pointerup', (event) => respondToPointerUp(event), { signal: this._controller.signal });
|
|
331
|
+
|
|
732
332
|
// Pointer up or cancel in window
|
|
733
|
-
window.addEventListener('pointerup', (event) => respondToWindowPointerUp(event), { signal: controller.signal });
|
|
734
|
-
window.addEventListener('pointercancel', (event) => respondToWindowPointerUp(event), { signal: controller.signal });
|
|
735
333
|
const respondToWindowPointerUp = (event) => {
|
|
736
|
-
const selection =
|
|
737
|
-
if (selection.type === 'Range' &&
|
|
738
|
-
const adjustedSelectionRange =
|
|
739
|
-
|
|
334
|
+
const selection = globalThis.getSelection();
|
|
335
|
+
if (selection.type === 'Range' && this._activeHighlightId && this._annotatableContainer.contains(selection.anchorNode)) {
|
|
336
|
+
const adjustedSelectionRange = this._snapRangeToBoundaries(selection.getRangeAt(0), selection.anchorNode);
|
|
337
|
+
|
|
740
338
|
// Update the selection range if needed
|
|
741
339
|
// In Android Chrome, sometimes selection handles don't show when a selection is updated programmatically, so it's best to only update the selection if needed.
|
|
742
340
|
const selectionRange = selection.getRangeAt(0);
|
|
743
341
|
if (!(
|
|
744
|
-
adjustedSelectionRange.startContainer === selectionRange.startContainer &&
|
|
745
|
-
adjustedSelectionRange.startOffset === selectionRange.startOffset &&
|
|
746
|
-
adjustedSelectionRange.endContainer === selectionRange.endContainer &&
|
|
342
|
+
adjustedSelectionRange.startContainer === selectionRange.startContainer &&
|
|
343
|
+
adjustedSelectionRange.startOffset === selectionRange.startOffset &&
|
|
344
|
+
adjustedSelectionRange.endContainer === selectionRange.endContainer &&
|
|
747
345
|
adjustedSelectionRange.endOffset === selectionRange.endOffset)
|
|
748
346
|
) {
|
|
749
347
|
selection.setBaseAndExtent(adjustedSelectionRange.startContainer, adjustedSelectionRange.startOffset, adjustedSelectionRange.endContainer, adjustedSelectionRange.endOffset);
|
|
750
348
|
}
|
|
751
349
|
}
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
this.
|
|
755
|
-
if (
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
this.
|
|
350
|
+
this._tapResult = null;
|
|
351
|
+
this._longPressTimeoutId = clearTimeout(this._longPressTimeoutId);
|
|
352
|
+
this._annotatableContainer.dataset.hhPointerDown = 'false';
|
|
353
|
+
if (this._activeSelectionHandle) {
|
|
354
|
+
this._activeSelectionHandle = null;
|
|
355
|
+
this._updateSelectionUi('bounds');
|
|
356
|
+
this._annotatableContainer.removeEventListener('pointermove', respondToSelectionHandleDrag);
|
|
759
357
|
}
|
|
760
358
|
}
|
|
761
|
-
|
|
359
|
+
globalThis.addEventListener('pointerup', (event) => respondToWindowPointerUp(event), { signal: this._controller.signal });
|
|
360
|
+
globalThis.addEventListener('pointercancel', (event) => respondToWindowPointerUp(event), { signal: this._controller.signal });
|
|
361
|
+
|
|
762
362
|
// Hyperlink click (for each hyperlink in annotatable container)
|
|
763
|
-
for (const hyperlinkElement of
|
|
363
|
+
for (const hyperlinkElement of this._hyperlinkElements) {
|
|
764
364
|
hyperlinkElement.addEventListener('click', (event) => {
|
|
765
365
|
this.deactivateHighlights();
|
|
766
|
-
if (!
|
|
767
|
-
}, { signal:
|
|
366
|
+
if (!this._allowHyperlinkClick) event.preventDefault();
|
|
367
|
+
}, { signal: this._controller.signal });
|
|
768
368
|
}
|
|
769
|
-
|
|
369
|
+
|
|
770
370
|
// Annotatable container resize (debounced)
|
|
771
|
-
let computedStyle =
|
|
772
|
-
let previousWidth = Math.round(this.
|
|
773
|
-
|
|
371
|
+
let computedStyle = globalThis.getComputedStyle(this._annotatableContainer);
|
|
372
|
+
let previousWidth = Math.round(this._annotatableContainer.clientWidth - Number.parseInt(computedStyle.getPropertyValue('padding-left')) - Number.parseInt(computedStyle.getPropertyValue('padding-right')));
|
|
373
|
+
this._resizeObserver = new ResizeObserver(debounce((entries) => {
|
|
774
374
|
for (const entry of entries) {
|
|
775
375
|
const width = Math.round(entry.contentBoxSize[0].inlineSize);
|
|
776
376
|
// Only respond if the annotatable content width changed
|
|
777
377
|
if (width !== previousWidth) {
|
|
778
378
|
if (options.drawingMode === 'svg') this.drawHighlights();
|
|
779
|
-
if (
|
|
379
|
+
if (this._previousSelectionRange) this._updateSelectionUi('bounds');
|
|
780
380
|
previousWidth = width;
|
|
781
381
|
}
|
|
782
382
|
}
|
|
783
|
-
}, Math.floor(Object.keys(
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
383
|
+
}, Math.floor(Object.keys(this._highlightsById).length / 20)));
|
|
384
|
+
this._resizeObserver.observe(this._annotatableContainer);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
/********************** Public Methods **********************/
|
|
389
|
+
|
|
390
|
+
// Load highlights
|
|
391
|
+
Highlighter.prototype.loadHighlights = function (highlights) {
|
|
392
|
+
// Don't load highlights until the document is ready (otherwise, highlights may be offset)
|
|
393
|
+
if (document.readyState !== 'complete') return setTimeout(this.loadHighlights.bind(this), 10, highlights);
|
|
394
|
+
const startTimestamp = Date.now();
|
|
395
|
+
|
|
396
|
+
// Hide container (repeated DOM manipulations are faster if the container is hidden)
|
|
397
|
+
if (highlights.length > 1) {
|
|
398
|
+
let containerToHide = this._options.drawingMode === 'svg' ? this._svgBackground : this._annotatableContainer;
|
|
399
|
+
containerToHide.style.display = 'none';
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// Load read-only highlights first (read-only highlights change the DOM, affecting other highlights' ranges)
|
|
403
|
+
const sortedHighlights = highlights.sort((a,b) => a.readOnly === b.readOnly ? 0 : a.readOnly ? -1 : 1);
|
|
404
|
+
|
|
405
|
+
const knownHighlightIds = Object.keys(this._highlightsById);
|
|
406
|
+
let addedCount = 0, updatedCount = 0;
|
|
407
|
+
for (const highlight of sortedHighlights) {
|
|
408
|
+
const highlightInfo = this._diffHighlight(highlight, this._highlightsById[highlight.highlightId]);
|
|
409
|
+
highlightInfo.highlightId = highlight.highlightId;
|
|
410
|
+
const knownHighlightIndex = knownHighlightIds.indexOf(highlightInfo.highlightId);
|
|
411
|
+
if (knownHighlightIndex > -1) {
|
|
412
|
+
knownHighlightIds.splice(knownHighlightIndex, 1);
|
|
413
|
+
if (Object.keys(highlightInfo).length > 1) {
|
|
414
|
+
this.createOrUpdateHighlight(highlightInfo, false); updatedCount++;
|
|
809
415
|
}
|
|
810
|
-
}
|
|
811
|
-
|
|
812
|
-
// Sort highlights (hyperlinks should already be sorted)
|
|
813
|
-
const tappedHighlightIds = [];
|
|
814
|
-
for (const highlightInfo of tappedHighlights) tappedHighlightIds.push(highlightInfo.highlightId);
|
|
815
|
-
const sortedTappedHighlights = this.getHighlightInfo(tappedHighlightIds);
|
|
816
|
-
|
|
817
|
-
return {
|
|
818
|
-
'targetFound': sortedTappedHighlights.length > 0 || tappedHyperlinks.length > 0,
|
|
819
|
-
'tapRange': getCaretFromCoordinates(pointerEvent.clientX, pointerEvent.clientY),
|
|
820
|
-
'pointerEvent': pointerEvent,
|
|
821
|
-
'highlights': sortedTappedHighlights,
|
|
822
|
-
'hyperlinks': tappedHyperlinks,
|
|
416
|
+
} else {
|
|
417
|
+
this.createOrUpdateHighlight(highlightInfo, false); addedCount++;
|
|
823
418
|
}
|
|
824
419
|
}
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
420
|
+
if (knownHighlightIds.length > 0) this.removeHighlights(knownHighlightIds);
|
|
421
|
+
|
|
422
|
+
(this._options.drawingMode === 'svg' ? this._svgBackground : this._annotatableContainer).style.display = '';
|
|
423
|
+
this._annotatableContainer.dispatchEvent(new CustomEvent('hh:highlightsload', { detail: {
|
|
424
|
+
addedCount: addedCount, removedCount: knownHighlightIds.length, updatedCount: updatedCount,
|
|
425
|
+
totalCount: Object.keys(this._highlightsById).length,
|
|
426
|
+
timeToLoad: Date.now() - startTimestamp,
|
|
427
|
+
} }));
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// Draw (or redraw) specified highlights, or all highlights on the page
|
|
431
|
+
Highlighter.prototype.drawHighlights = function (highlightIds = Object.keys(this._highlightsById)) {
|
|
432
|
+
const options = this._options;
|
|
433
|
+
|
|
434
|
+
// Hide container (repeated DOM manipulations is faster if the container is hidden)
|
|
435
|
+
if (highlightIds.length > 1) {
|
|
436
|
+
let containerToHide = options.drawingMode === 'svg' ? this._svgBackground : this._annotatableContainer;
|
|
437
|
+
containerToHide.style.display = 'none';
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
for (const highlightId of highlightIds) {
|
|
441
|
+
const highlightInfo = this._highlightsById[highlightId];
|
|
442
|
+
let range = this._getCorrectedRangeObj(highlightId);
|
|
443
|
+
const rangeParagraphs = this._annotatableContainer.querySelectorAll(`#${highlightInfo.rangeParagraphIds.join(', #')}`);
|
|
444
|
+
const wasDrawnAsReadOnly = this._annotatableContainer.querySelector(`[data-highlight-id="${highlightId}"][data-read-only]`);
|
|
445
|
+
|
|
446
|
+
// Remove old highlight elements and styles
|
|
447
|
+
if (!wasDrawnAsReadOnly || !highlightInfo.readOnly) this._undrawHighlight(highlightInfo);
|
|
448
|
+
// Don't redraw a read-only highlight that's already drawn
|
|
449
|
+
if (wasDrawnAsReadOnly) continue;
|
|
450
|
+
|
|
451
|
+
// Insert wrappers before drawing, so any layout shift from wrapper content is reflected in drawing positions
|
|
452
|
+
if (highlightInfo.wrapper && (options.wrappers[highlightInfo.wrapper]?.start || options.wrappers[highlightInfo.wrapper]?.end)) {
|
|
453
|
+
const addWrapper = (edge, range, htmlString) => {
|
|
454
|
+
htmlString = `<span class="hh-wrapper-${edge}" data-highlight-id="${highlightId}" data-color="${highlightInfo.color}" data-style="${highlightInfo.style}" data-hh-ignore="">${htmlString}</span>`
|
|
455
|
+
for (const key of Object.keys(highlightInfo.wrapperVariables)) {
|
|
456
|
+
htmlString = htmlString.replaceAll(`{${key}}`, highlightInfo.wrapperVariables[key]);
|
|
457
|
+
}
|
|
458
|
+
const template = document.createElement('template');
|
|
459
|
+
template.innerHTML = htmlString;
|
|
460
|
+
let htmlElement = template.content.firstChild;
|
|
461
|
+
range.insertNode(htmlElement);
|
|
462
|
+
}
|
|
463
|
+
const startRange = highlightInfo.rangeObj;
|
|
464
|
+
const endRange = document.createRange(); endRange.setStart(highlightInfo.rangeObj.endContainer, highlightInfo.rangeObj.endOffset);
|
|
465
|
+
const wrapperInfo = options.wrappers[highlightInfo.wrapper];
|
|
466
|
+
addWrapper('start', startRange, wrapperInfo.start);
|
|
467
|
+
addWrapper('end', endRange, wrapperInfo.end);
|
|
468
|
+
rangeParagraphs.forEach(p => { p.normalize(); });
|
|
469
|
+
range = this._getCorrectedRangeObj(highlightId);
|
|
470
|
+
if (!highlightInfo.readOnly && options.drawingMode === 'svg') {
|
|
471
|
+
const startWrapperEl = this._annotatableContainer.querySelector(`.hh-wrapper-start[data-highlight-id="${highlightId}"]`);
|
|
472
|
+
const endWrapperEl = this._annotatableContainer.querySelector(`.hh-wrapper-end[data-highlight-id="${highlightId}"]`);
|
|
473
|
+
range = document.createRange();
|
|
474
|
+
range.setStartAfter(startWrapperEl);
|
|
475
|
+
range.setEndBefore(endWrapperEl);
|
|
833
476
|
}
|
|
834
477
|
}
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
478
|
+
|
|
479
|
+
// Draw highlights with mark elements
|
|
480
|
+
if (highlightInfo.readOnly || options.drawingMode === 'mark-elements') {
|
|
481
|
+
// Inject HTML <mark> elements
|
|
482
|
+
if (range.startOffset < range.startContainer.length) range.startContainer.splitText(range.startOffset);
|
|
483
|
+
if (range.endOffset > 0 && range.endOffset < range.endContainer.length) range.endContainer.splitText(range.endOffset);
|
|
484
|
+
const walker = this._getTextNodeWalker(range.commonAncestorContainer);
|
|
485
|
+
walker.currentNode = range.startContainer;
|
|
486
|
+
const relevantTextNodes = [];
|
|
487
|
+
let node;
|
|
488
|
+
while (node = walker.nextNode()) {
|
|
489
|
+
if (!node.parentElement.closest('rt, rp')) relevantTextNodes.push(node);
|
|
490
|
+
if (node === range.endContainer) break;
|
|
491
|
+
}
|
|
844
492
|
const overlappingHighlightIds = new Set();
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
493
|
+
const createStyledMark = () => {
|
|
494
|
+
const mark = document.createElement('mark');
|
|
495
|
+
mark.dataset.highlightId = highlightId;
|
|
496
|
+
if (highlightInfo.readOnly) mark.dataset.readOnly = '';
|
|
497
|
+
mark.dataset.color = highlightInfo.color;
|
|
498
|
+
mark.dataset.style = highlightInfo.style;
|
|
499
|
+
return mark;
|
|
500
|
+
};
|
|
501
|
+
for (let tn = 0; tn < relevantTextNodes.length; tn++) {
|
|
502
|
+
const textNode = relevantTextNodes[tn];
|
|
503
|
+
if (textNode.parentElement.dataset.highlightId) overlappingHighlightIds.add(textNode.parentElement.dataset.highlightId);
|
|
504
|
+
const styledMark = createStyledMark();
|
|
505
|
+
if (tn === 0) styledMark.dataset.start = '';
|
|
506
|
+
if (tn === relevantTextNodes.length - 1) styledMark.dataset.end = '';
|
|
507
|
+
textNode.before(styledMark);
|
|
508
|
+
styledMark.appendChild(textNode);
|
|
509
|
+
// Absorb adjacent elements without text into the mark element. This prevents unstyled gaps around CSS-rendered pseudoelement content (such as superscript footnote markers).
|
|
510
|
+
let prev = styledMark.previousSibling;
|
|
511
|
+
while (prev && prev.nodeType === Node.ELEMENT_NODE && prev.textContent === '' && !prev.hasAttribute('data-hh-ignore')) {
|
|
512
|
+
const toAbsorb = prev; prev = prev.previousSibling;
|
|
513
|
+
styledMark.prepend(toAbsorb);
|
|
856
514
|
}
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
undrawHighlight(highlightsById[overlappingHighlightId]);
|
|
515
|
+
if (tn < relevantTextNodes.length - 1) {
|
|
516
|
+
let next = styledMark.nextSibling;
|
|
517
|
+
while (next && next.nodeType === Node.ELEMENT_NODE && next.textContent === '' && !next.hasAttribute('data-hh-ignore')) {
|
|
518
|
+
const toAbsorb = next; next = next.nextSibling;
|
|
519
|
+
styledMark.appendChild(toAbsorb);
|
|
520
|
+
}
|
|
864
521
|
}
|
|
865
|
-
this.drawHighlights(overlappingHighlightIds);
|
|
866
522
|
}
|
|
867
|
-
|
|
868
|
-
//
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
}
|
|
873
|
-
|
|
874
|
-
// Remove SVG highlights
|
|
875
|
-
if (svgBackground.querySelector(`g[data-highlight-id="${highlightId}"]`)) {
|
|
876
|
-
const overlappingHighlightIds = new Set();
|
|
877
|
-
svgBackground.querySelectorAll(`g[data-highlight-id="${highlightId}"]`).forEach(element => {
|
|
878
|
-
element.remove();
|
|
879
|
-
});
|
|
880
|
-
}
|
|
881
|
-
|
|
882
|
-
// Remove Highlight API highlights
|
|
883
|
-
if (supportsHighlightApi && CSS.highlights.has(highlightId)) {
|
|
884
|
-
const ruleIndexesToDelete = [];
|
|
885
|
-
for (let r = 0; r < highlightApiStylesheet.cssRules.length; r++) {
|
|
886
|
-
if (highlightApiStylesheet.cssRules[r].selectorText.includes(`::highlight(${highlightInfo.escapedHighlightId})`)) ruleIndexesToDelete.push(r);
|
|
523
|
+
|
|
524
|
+
// Update highlight ranges that were invalidated by the DOM change
|
|
525
|
+
this._getCorrectedRangeObj(highlightId);
|
|
526
|
+
for (const overlappingHighlightId of overlappingHighlightIds) {
|
|
527
|
+
this._getCorrectedRangeObj(overlappingHighlightId);
|
|
887
528
|
}
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
}
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
// Draw
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
let
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
svgActiveOverlay.dataset.style = style;
|
|
529
|
+
|
|
530
|
+
// Draw highlights with Custom Highlight API
|
|
531
|
+
} else if (options.drawingMode === 'highlight-api' && supportsHighlightApi) {
|
|
532
|
+
let highlightObj;
|
|
533
|
+
if (CSS.highlights.has(highlightId)) {
|
|
534
|
+
highlightObj = CSS.highlights.get(highlightId);
|
|
535
|
+
highlightObj.clear();
|
|
536
|
+
} else {
|
|
537
|
+
highlightObj = new Highlight();
|
|
538
|
+
CSS.highlights.set(highlightId, highlightObj);
|
|
539
|
+
}
|
|
540
|
+
highlightObj.add(range);
|
|
541
|
+
const styleTemplate = this._getStyleTemplate(highlightInfo.style, 'css', null);
|
|
542
|
+
const colorString = options.colors[highlightInfo.color];
|
|
543
|
+
this._highlightApiStylesheet.insertRule(`${options.containerSelector} ::highlight(${highlightInfo.escapedHighlightId}) { --hh-color: ${colorString}; ${styleTemplate} }`);
|
|
544
|
+
this._highlightApiStylesheet.insertRule(`${options.containerSelector} rt::highlight(${highlightInfo.escapedHighlightId}) { color: inherit; background-color: transparent; }`);
|
|
545
|
+
this._highlightApiStylesheet.insertRule(`${options.containerSelector} img::highlight(${highlightInfo.escapedHighlightId}) { color: inherit; background-color: transparent; }`);
|
|
546
|
+
|
|
547
|
+
// Draw highlights with SVG shapes
|
|
548
|
+
} else if (options.drawingMode === 'svg') {
|
|
549
|
+
const clientRects = this._getMergedClientRects(range, rangeParagraphs);
|
|
550
|
+
let group = document.createElementNS('http://www.w3.org/2000/svg', 'g');
|
|
551
|
+
group.dataset.highlightId = highlightId;
|
|
552
|
+
group.dataset.color = highlightInfo.color;
|
|
553
|
+
group.dataset.style = highlightInfo.style;
|
|
914
554
|
let svgContent = '';
|
|
915
555
|
for (const clientRect of clientRects) {
|
|
916
|
-
svgContent +=
|
|
556
|
+
svgContent += this._getStyleTemplate(highlightInfo.style, 'svg', clientRect);
|
|
917
557
|
}
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
// Bring active highlight to the front
|
|
921
|
-
const svgHighlight = svgBackground.querySelector(`g[data-highlight-id="${activeHighlightId}"]`);
|
|
922
|
-
if (svgHighlight) svgBackground.appendChild(svgHighlight);
|
|
923
|
-
svgBackground.appendChild(svgActiveOverlay);
|
|
558
|
+
group.innerHTML = svgContent;
|
|
559
|
+
this._svgBackground.appendChild(group);
|
|
924
560
|
}
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
// Show container
|
|
564
|
+
(options.drawingMode === 'svg' ? this._svgBackground : this._annotatableContainer).style.display = '';
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
// Create a new highlight, or update an existing highlight when it changes
|
|
568
|
+
Highlighter.prototype.createOrUpdateHighlight = function (attributes = {}, triggeredByUserAction = true) {
|
|
569
|
+
const options = this._options;
|
|
570
|
+
let highlightId = attributes.highlightId ?? this._activeHighlightId ?? options.highlightIdFunction();
|
|
571
|
+
const appearanceChanges = [];
|
|
572
|
+
const boundsChanges = [];
|
|
573
|
+
|
|
574
|
+
const oldHighlightInfo = this._highlightsById[highlightId];
|
|
575
|
+
const isNewHighlight = !oldHighlightInfo;
|
|
576
|
+
|
|
577
|
+
// If a different highlight is active, deactivate it
|
|
578
|
+
if (this._activeHighlightId && highlightId !== this._activeHighlightId && triggeredByUserAction) {
|
|
579
|
+
this.deactivateHighlights();
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
// If the highlight is currently activate, ignore bounds changes that weren't initiated by the user
|
|
583
|
+
if (highlightId === this._activeHighlightId && !triggeredByUserAction) {
|
|
584
|
+
attributes.startParagraphId = null;
|
|
585
|
+
attributes.startParagraphOffset = null;
|
|
586
|
+
attributes.endParagraphId = null;
|
|
587
|
+
attributes.endParagraphOffset = null;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
// Warn if color, style, or wrapper attributes are invalid
|
|
591
|
+
if (attributes.color && !Object.hasOwn(options.colors, attributes.color)) {
|
|
592
|
+
console.warn(`Highlight color "${attributes.color}" is not defined in options (highlightId: ${highlightId}).`);
|
|
593
|
+
}
|
|
594
|
+
if (attributes.style && !Object.hasOwn(options.styles, attributes.style)) {
|
|
595
|
+
console.warn(`Highlight style "${attributes.style}" is not defined in options (highlightId: ${highlightId}).`);
|
|
596
|
+
}
|
|
597
|
+
if (attributes.wrapper && !Object.hasOwn(options.wrappers, attributes.wrapper)) {
|
|
598
|
+
console.warn(`Highlight wrapper "${attributes.wrapper}" is not defined in options (highlightId: ${highlightId}).`);
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// Update defaults
|
|
602
|
+
if (options.rememberStyle && triggeredByUserAction) {
|
|
603
|
+
if (attributes.color) options.defaultColor = attributes.color;
|
|
604
|
+
if (attributes.style) options.defaultStyle = attributes.style;
|
|
605
|
+
if (attributes.wrapper) options.defaultWrapper = attributes.wrapper;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
// Check which appearance properties changed
|
|
609
|
+
for (const key of ['color', 'style', 'wrapper', 'wrapperVariables', 'readOnly']) {
|
|
610
|
+
if (isNewHighlight || (attributes[key] != null && attributes[key] !== oldHighlightInfo[key])) appearanceChanges.push(key);
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
// If the highlight was and still is read-only, return
|
|
614
|
+
if (oldHighlightInfo?.readOnly && (attributes.readOnly == null || attributes.readOnly === true)) return this.deactivateHighlights();
|
|
615
|
+
|
|
616
|
+
// Calculate the bounds of the highlight range, if it's changed
|
|
617
|
+
let adjustedSelectionRange, highlightRange;
|
|
618
|
+
let rangeText, rangeHtml, rangeParagraphIds;
|
|
619
|
+
let startParagraphId, startParagraphOffset, endParagraphId, endParagraphOffset;
|
|
620
|
+
const selection = this._getRestoredSelectionOrCaret(globalThis.getSelection());
|
|
621
|
+
if (selection.type === 'Range') adjustedSelectionRange = this._snapRangeToBoundaries(selection.getRangeAt(0));
|
|
622
|
+
if ((attributes.startParagraphId ?? attributes.startParagraphOffset ?? attributes.endParagraphId ?? attributes.endParagraphOffset != null) || (adjustedSelectionRange && !adjustedSelectionRange.collapsed)) {
|
|
623
|
+
let startNode, startOffset, endNode, endOffset;
|
|
624
|
+
if (attributes.startParagraphId ?? attributes.startParagraphOffset ?? attributes.endParagraphId ?? attributes.endParagraphOffset != null) {
|
|
625
|
+
startParagraphId = attributes.startParagraphId ?? oldHighlightInfo?.startParagraphId;
|
|
626
|
+
startParagraphOffset = Number.parseInt(attributes.startParagraphOffset ?? oldHighlightInfo?.startParagraphOffset);
|
|
627
|
+
endParagraphId = attributes.endParagraphId ?? oldHighlightInfo?.endParagraphId;
|
|
628
|
+
endParagraphOffset = Number.parseInt(attributes.endParagraphOffset ?? oldHighlightInfo?.endParagraphOffset);
|
|
629
|
+
([ startNode, startOffset ] = this._getTextNodeAndOffset(document.getElementById(startParagraphId), startParagraphOffset));
|
|
630
|
+
([ endNode, endOffset ] = this._getTextNodeAndOffset(document.getElementById(endParagraphId), endParagraphOffset));
|
|
631
|
+
} else if (adjustedSelectionRange) {
|
|
632
|
+
startNode = adjustedSelectionRange.startContainer;
|
|
633
|
+
startOffset = adjustedSelectionRange.startOffset;
|
|
634
|
+
endNode = adjustedSelectionRange.endContainer;
|
|
635
|
+
endOffset = adjustedSelectionRange.endOffset;
|
|
636
|
+
([ startParagraphId, startParagraphOffset ] = this._getParagraphOffset(startNode, startOffset));
|
|
637
|
+
([ endParagraphId, endParagraphOffset ] = this._getParagraphOffset(endNode, endOffset));
|
|
995
638
|
}
|
|
639
|
+
|
|
640
|
+
// Create a new highlight range
|
|
641
|
+
highlightRange = document.createRange();
|
|
642
|
+
highlightRange.setStart(startNode, startOffset);
|
|
643
|
+
highlightRange.setEnd(endNode, endOffset);
|
|
644
|
+
|
|
645
|
+
// Check which bounds properties changed
|
|
646
|
+
const boundsValues = { startParagraphId, startParagraphOffset, endParagraphId, endParagraphOffset };
|
|
647
|
+
for (const key of Object.keys(boundsValues)) {
|
|
648
|
+
if (isNewHighlight || boundsValues[key] !== oldHighlightInfo[key]) boundsChanges.push(key);
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// Set variables that depend on the range
|
|
652
|
+
const temporaryHtmlElement = document.createElement('div');
|
|
653
|
+
temporaryHtmlElement.appendChild(highlightRange.cloneContents());
|
|
654
|
+
for (const element of temporaryHtmlElement.querySelectorAll(`a, [data-highlight-id]:not([data-highlight-id="${highlightId}"])`)) element.outerHTML = element.innerHTML;
|
|
655
|
+
for (const element of temporaryHtmlElement.querySelectorAll(`[data-hh-ignore]`)) element.remove();
|
|
656
|
+
rangeText = temporaryHtmlElement.textContent;
|
|
657
|
+
rangeHtml = temporaryHtmlElement.innerHTML;
|
|
658
|
+
let startParagraphIndex = this._annotatableParagraphIds.indexOf(startParagraphId);
|
|
659
|
+
let endParagraphIndex = this._annotatableParagraphIds.indexOf(endParagraphId);
|
|
660
|
+
if (startParagraphIndex === -1) startParagraphIndex = 0;
|
|
661
|
+
if (endParagraphIndex === -1) endParagraphIndex = this._annotatableParagraphIds.length - 1;
|
|
662
|
+
rangeParagraphIds = this._annotatableParagraphIds.slice(startParagraphIndex, endParagraphIndex + 1);
|
|
996
663
|
}
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
664
|
+
|
|
665
|
+
// If there are no valid changes, return
|
|
666
|
+
if (!highlightRange || highlightRange.toString() === '' || appearanceChanges.length + boundsChanges.length === 0) return;
|
|
667
|
+
|
|
668
|
+
// Update saved highlight info
|
|
669
|
+
const newHighlightInfo = {
|
|
670
|
+
highlightId: highlightId,
|
|
671
|
+
color: attributes.color ?? oldHighlightInfo?.color ?? options.defaultColor,
|
|
672
|
+
style: attributes.style ?? oldHighlightInfo?.style ?? options.defaultStyle,
|
|
673
|
+
wrapper: attributes.wrapper ?? oldHighlightInfo?.wrapper ?? options.defaultWrapper,
|
|
674
|
+
wrapperVariables: attributes.wrapperVariables ?? oldHighlightInfo?.wrapperVariables ?? {},
|
|
675
|
+
readOnly: attributes.readOnly ?? oldHighlightInfo?.readOnly ?? false,
|
|
676
|
+
startParagraphId: startParagraphId ?? oldHighlightInfo?.startParagraphId,
|
|
677
|
+
startParagraphOffset: startParagraphOffset ?? oldHighlightInfo?.startParagraphOffset,
|
|
678
|
+
endParagraphId: endParagraphId ?? oldHighlightInfo?.endParagraphId,
|
|
679
|
+
endParagraphOffset: endParagraphOffset ?? oldHighlightInfo?.endParagraphOffset,
|
|
680
|
+
// Read-only properties
|
|
681
|
+
escapedHighlightId: CSS.escape(highlightId),
|
|
682
|
+
rangeText: rangeText ?? oldHighlightInfo?.rangeText,
|
|
683
|
+
rangeHtml: rangeHtml ?? oldHighlightInfo?.rangeHtml,
|
|
684
|
+
rangeParagraphIds: rangeParagraphIds ?? oldHighlightInfo?.rangeParagraphIds,
|
|
685
|
+
rangeObj: highlightRange ?? oldHighlightInfo?.rangeObj,
|
|
686
|
+
};
|
|
687
|
+
this._highlightsById[highlightId] = newHighlightInfo;
|
|
688
|
+
|
|
689
|
+
const detail = {
|
|
690
|
+
highlight: newHighlightInfo,
|
|
691
|
+
changes: appearanceChanges.concat(boundsChanges),
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
const wrapperChanged = appearanceChanges.some(k => k.startsWith('wrapper'));
|
|
695
|
+
if (triggeredByUserAction && !this._activeHighlightId) {
|
|
696
|
+
this.activateHighlight(highlightId);
|
|
697
|
+
} else if (this._activeHighlightId && highlightId === this._activeHighlightId && appearanceChanges.length > 0) {
|
|
698
|
+
this._updateSelectionUi('appearance');
|
|
699
|
+
}
|
|
700
|
+
if (highlightId !== this._activeHighlightId || wrapperChanged) {
|
|
701
|
+
this.drawHighlights([highlightId]);
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
// Redraw highlights after the current highlight if needed
|
|
705
|
+
if (wrapperChanged && options.drawingMode === 'svg') {
|
|
706
|
+
const highlights = this.getHighlightInfo();
|
|
707
|
+
const changedIndex = highlights.findIndex(h => h.highlightId === highlightId);
|
|
708
|
+
this.drawHighlights(highlights.slice(changedIndex + 1).map(h => h.highlightId));
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
if (isNewHighlight) {
|
|
712
|
+
this._annotatableContainer.dispatchEvent(new CustomEvent('hh:highlightcreate', { detail: detail }));
|
|
713
|
+
} else {
|
|
714
|
+
this._annotatableContainer.dispatchEvent(new CustomEvent('hh:highlightupdate', { detail: detail }));
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
// Activate a highlight by ID
|
|
719
|
+
Highlighter.prototype.activateHighlight = function (highlightId) {
|
|
720
|
+
const highlightToActivate = this._highlightsById[highlightId];
|
|
721
|
+
if (highlightToActivate.readOnly) {
|
|
722
|
+
// If the highlight is read-only, return events, but don't actually activate it
|
|
723
|
+
this._annotatableContainer.dispatchEvent(new CustomEvent('hh:highlightactivate', { detail: { highlight: highlightToActivate } }));
|
|
724
|
+
this._annotatableContainer.dispatchEvent(new CustomEvent('hh:highlightdeactivate', { detail: { highlight: highlightToActivate } }));
|
|
725
|
+
return;
|
|
726
|
+
}
|
|
727
|
+
const selection = globalThis.getSelection();
|
|
728
|
+
const highlightRange = highlightToActivate.rangeObj.cloneRange();
|
|
729
|
+
this._activeHighlightId = highlightId;
|
|
730
|
+
this._updateSelectionUi('appearance');
|
|
731
|
+
this._updateSelectionUi('bounds');
|
|
732
|
+
|
|
733
|
+
// Update the selection range if needed
|
|
734
|
+
// In Android Chrome, sometimes selection handles don't show when a selection is updated programmatically, so it's best to only update the selection if needed.
|
|
735
|
+
let selectionRange = selection.type === 'Range' ? selection.getRangeAt(0) : null;
|
|
736
|
+
if (!selectionRange || !(
|
|
737
|
+
selectionRange.startContainer === highlightRange.startContainer &&
|
|
738
|
+
selectionRange.startOffset === highlightRange.startOffset &&
|
|
739
|
+
selectionRange.endContainer === highlightRange.endContainer &&
|
|
740
|
+
selectionRange.endOffset === highlightRange.endOffset)
|
|
741
|
+
) {
|
|
742
|
+
selection.setBaseAndExtent(highlightRange.startContainer, highlightRange.startOffset, highlightRange.endContainer, highlightRange.endOffset);
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
this._annotatableContainer.dispatchEvent(new CustomEvent('hh:highlightactivate', { detail: { highlight: highlightToActivate } }));
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
// Activate a link by position
|
|
749
|
+
Highlighter.prototype.activateHyperlink = function (position) {
|
|
750
|
+
this.deactivateHighlights();
|
|
751
|
+
this._allowHyperlinkClick = true;
|
|
752
|
+
this._hyperlinksByPosition[position].hyperlinkElement.click();
|
|
753
|
+
this._allowHyperlinkClick = false;
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
// Deactivate any highlights that are currently active/selected
|
|
757
|
+
Highlighter.prototype.deactivateHighlights = function (removeSelectionRanges = true) {
|
|
758
|
+
const deactivatedHighlight = this._highlightsById[this._activeHighlightId];
|
|
759
|
+
this._activeHighlightId = null;
|
|
760
|
+
this._previousSelectionRange = null;
|
|
761
|
+
const selection = globalThis.getSelection();
|
|
762
|
+
if (removeSelectionRanges && selection.anchorNode && this._annotatableContainer.contains(selection.anchorNode)) {
|
|
763
|
+
selection.collapseToStart();
|
|
764
|
+
}
|
|
765
|
+
this._updateSelectionUi('appearance');
|
|
766
|
+
if (deactivatedHighlight) {
|
|
767
|
+
this.drawHighlights([deactivatedHighlight.highlightId]);
|
|
768
|
+
this._annotatableContainer.dispatchEvent(new CustomEvent('hh:highlightdeactivate', { detail: {
|
|
769
|
+
highlight: deactivatedHighlight,
|
|
770
|
+
}}));
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
// Remove the specified highlights, or all highlights on the page
|
|
775
|
+
Highlighter.prototype.removeHighlights = function (highlightIds = Object.keys(this._highlightsById)) {
|
|
776
|
+
this.deactivateHighlights();
|
|
777
|
+
for (const highlightId of highlightIds) {
|
|
778
|
+
const highlightInfo = this._highlightsById[highlightId];
|
|
779
|
+
if (highlightInfo) {
|
|
780
|
+
delete this._highlightsById[highlightId];
|
|
781
|
+
this._annotatableContainer.dispatchEvent(new CustomEvent('hh:highlightremove', { detail: {
|
|
782
|
+
highlightId: highlightId,
|
|
783
|
+
}}));
|
|
784
|
+
this._undrawHighlight(highlightInfo);
|
|
1001
785
|
}
|
|
1002
786
|
}
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
// Range starts in the container but ends outside
|
|
1018
|
-
endNode = getLastTextNode(this.annotatableParagraphs[this.annotatableParagraphs.length - 1]);
|
|
1019
|
-
endOffset = endNode.length;
|
|
1020
|
-
} else if (anchorNode === endNode || this.annotatableContainer.contains(endNode)) {
|
|
1021
|
-
// Range starts outside of the container but ends inside
|
|
1022
|
-
startNode = getFirstTextNode(this.annotatableParagraphs[0]);
|
|
1023
|
-
startOffset = 0;
|
|
1024
|
-
}
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
// Get the active highlight ID (if there is one)
|
|
790
|
+
Highlighter.prototype.getActiveHighlightId = function () {
|
|
791
|
+
return this._activeHighlightId;
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
// Get info for specified highlights, or all highlights on the page
|
|
795
|
+
Highlighter.prototype.getHighlightInfo = function (highlightIds = Object.keys(this._highlightsById), paragraphId = null) {
|
|
796
|
+
let filteredHighlights = []
|
|
797
|
+
for (const highlightId of highlightIds) {
|
|
798
|
+
const highlightInfo = this._highlightsById[highlightId];
|
|
799
|
+
if (!paragraphId || paragraphId === highlightInfo.startParagraphId) {
|
|
800
|
+
filteredHighlights.push(highlightInfo);
|
|
1025
801
|
}
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
802
|
+
}
|
|
803
|
+
// Sort highlights based on their order on the page
|
|
804
|
+
if (filteredHighlights.length > 0) {
|
|
805
|
+
filteredHighlights.sort((a, b) => {
|
|
806
|
+
return (this._annotatableParagraphIds.indexOf(a.startParagraphId) - this._annotatableParagraphIds.indexOf(b.startParagraphId)) || (a.startParagraphOffset - b.startParagraphOffset);
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
return filteredHighlights;
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
// Update initialized options
|
|
813
|
+
Highlighter.prototype.setOptions = function (optionsToUpdate) {
|
|
814
|
+
const options = this._options;
|
|
815
|
+
for (const key in optionsToUpdate) {
|
|
816
|
+
options[key] = optionsToUpdate[key] ?? options[key];
|
|
817
|
+
}
|
|
818
|
+
if ('containerSelector' in optionsToUpdate) {
|
|
819
|
+
this.removeHighlighter();
|
|
820
|
+
this._initializeHighlighter();
|
|
821
|
+
this._loadStyles();
|
|
822
|
+
this._loadEventListeners();
|
|
823
|
+
this._updateAppearanceStylesheet();
|
|
824
|
+
this._updateSelectionUi('appearance');
|
|
825
|
+
for (const selectionHandle of this._selectionHandles) {
|
|
826
|
+
selectionHandle.children[1].innerHTML = options.selectionHandles[selectionHandle.dataset.side] ?? '';
|
|
827
|
+
}
|
|
828
|
+
} else {
|
|
829
|
+
if ('paragraphSelector' in optionsToUpdate) {
|
|
830
|
+
this._initializeHighlighter();
|
|
831
|
+
}
|
|
832
|
+
if ('drawingMode' in optionsToUpdate || 'styles' in optionsToUpdate || 'colors' in optionsToUpdate) {
|
|
833
|
+
this._updateAppearanceStylesheet();
|
|
834
|
+
}
|
|
835
|
+
if ('drawingMode' in optionsToUpdate || 'styles' in optionsToUpdate) {
|
|
836
|
+
if (supportsHighlightApi) CSS.highlights.clear();
|
|
837
|
+
this.drawHighlights();
|
|
838
|
+
}
|
|
839
|
+
if ('selectionHandles' in optionsToUpdate) {
|
|
840
|
+
for (const selectionHandle of this._selectionHandles) {
|
|
841
|
+
selectionHandle.children[1].innerHTML = options.selectionHandles[selectionHandle.dataset.side] ?? '';
|
|
1044
842
|
}
|
|
1045
843
|
}
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
/** @deprecated Use setOptions({ key: value }) instead */
|
|
848
|
+
Highlighter.prototype.setOption = function (key, value) {
|
|
849
|
+
console.warn('setOption() is deprecated. Use setOptions({ key: value }) instead.');
|
|
850
|
+
this.setOptions({ [key]: value });
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
// Get all of the initialized options
|
|
854
|
+
Highlighter.prototype.getOptions = function () {
|
|
855
|
+
return this._options;
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
// Remove this Highlighter instance and its highlights
|
|
859
|
+
Highlighter.prototype.removeHighlighter = function () {
|
|
860
|
+
this.loadHighlights([]);
|
|
861
|
+
this._annotatableContainer.querySelectorAll('.hh-svg-background, .hh-selection-handle').forEach(el => el.remove())
|
|
862
|
+
removeStylesheets(this._stylesheets);
|
|
863
|
+
this._resizeObserver.disconnect();
|
|
864
|
+
this._controller.abort();
|
|
865
|
+
|
|
866
|
+
this._annotatableContainer.highlighter = undefined;
|
|
867
|
+
_highlighters = _highlighters.filter(h => h._annotatableContainer !== this._annotatableContainer);
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
|
|
871
|
+
/********************** Private Methods **********************/
|
|
872
|
+
|
|
873
|
+
// Check if the tap hits any highlights, wrappers, or links
|
|
874
|
+
Highlighter.prototype._checkForTapTargets = function (pointerEvent) {
|
|
875
|
+
if (!pointerEvent) return;
|
|
876
|
+
|
|
877
|
+
// Check for tapped highlights
|
|
878
|
+
const tappedHighlightIds = [];
|
|
879
|
+
if (!pointerEvent.target.closest('[data-hh-ignore]')) {
|
|
880
|
+
for (const highlightId of Object.keys(this._highlightsById)) {
|
|
881
|
+
const highlightInfo = this._highlightsById[highlightId];
|
|
882
|
+
const highlightRange = highlightInfo.rangeObj;
|
|
883
|
+
for (const rangeRect of highlightRange.getClientRects()) {
|
|
884
|
+
if (this._isPointInRect(pointerEvent.clientX, pointerEvent.clientY, rangeRect, 5)) {
|
|
885
|
+
tappedHighlightIds.push(highlightId);
|
|
886
|
+
break;
|
|
1059
887
|
}
|
|
1060
888
|
}
|
|
1061
|
-
|
|
1062
|
-
// Trim whitespace and dashes at range start and end
|
|
1063
|
-
while (/\s|\p{Pd}/u.test(startOffset < startNode.textContent.length && startNode.textContent[startOffset])) startOffset += 1;
|
|
1064
|
-
while (endOffset - 1 >= 0 && /\s|\p{Pd}/u.test(endNode.textContent[endOffset - 1])) endOffset -= 1;
|
|
1065
|
-
|
|
1066
|
-
// Expand range to word boundaries
|
|
1067
|
-
while (startOffset > 0 && /[^\s|\p{Pd}]/u.test(startNode.textContent[startOffset - 1])) startOffset -= 1;
|
|
1068
|
-
while (endOffset + 1 <= endNode.textContent.length && /[^\s|\p{Pd}]/u.test(endNode.textContent[endOffset])) endOffset += 1;
|
|
1069
889
|
}
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
// Get the character offset relative to the deepest relevant text node
|
|
1089
|
-
const getTextNodeAndOffset = (parentElement, targetOffset) => {
|
|
1090
|
-
let textNode, firstTextNode, currentOffset = 0;
|
|
1091
|
-
const walker = document.createTreeWalker(parentElement, NodeFilter.SHOW_TEXT);
|
|
1092
|
-
while (textNode = walker.nextNode()) {
|
|
1093
|
-
if (!firstTextNode) firstTextNode = walker.currentNode;
|
|
1094
|
-
currentOffset += textNode.textContent.length;
|
|
1095
|
-
if (currentOffset >= targetOffset) {
|
|
1096
|
-
const relativeOffset = textNode.textContent.length - currentOffset + targetOffset
|
|
1097
|
-
return [ textNode, relativeOffset ];
|
|
1098
|
-
}
|
|
890
|
+
}
|
|
891
|
+
const tappedHighlights = this.getHighlightInfo(tappedHighlightIds);
|
|
892
|
+
|
|
893
|
+
// Check for tapped wrappers and hyperlinks
|
|
894
|
+
const tappedWrappers = [];
|
|
895
|
+
const tappedHyperlinks = [];
|
|
896
|
+
const targetElements = document.elementsFromPoint(pointerEvent.clientX, pointerEvent.clientY);
|
|
897
|
+
for (const element of targetElements) {
|
|
898
|
+
const wrapper = element.closest('.hh-wrapper-start, .hh-wrapper-end');
|
|
899
|
+
if (wrapper) {
|
|
900
|
+
tappedWrappers.push({
|
|
901
|
+
position: wrapper.className.includes('hh-wrapper-start') ? 'start' : 'end',
|
|
902
|
+
highlightInfo: this._highlightsById[wrapper.dataset.highlightId],
|
|
903
|
+
});
|
|
904
|
+
} else if (element.matches('a') && element.dataset.hhPosition) {
|
|
905
|
+
const hyperlinkInfo = this._hyperlinksByPosition[element.dataset.hhPosition];
|
|
906
|
+
tappedHyperlinks.push(hyperlinkInfo);
|
|
1099
907
|
}
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
const targetCount = tappedHighlights.length + tappedWrappers.length + tappedHyperlinks.length;
|
|
911
|
+
return {
|
|
912
|
+
'targetCount': targetCount,
|
|
913
|
+
'targetFound': targetCount > 0,
|
|
914
|
+
'tapRange': this._getCaretFromCoordinates(pointerEvent.clientX, pointerEvent.clientY),
|
|
915
|
+
'pointerEvent': pointerEvent,
|
|
916
|
+
'highlights': tappedHighlights,
|
|
917
|
+
'wrappers': tappedWrappers,
|
|
918
|
+
'hyperlinks': tappedHyperlinks,
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
// Compare new highlight information to old highlight information, returning an object with the properties that changed
|
|
923
|
+
Highlighter.prototype._diffHighlight = function (newHighlightInfo, oldHighlightInfo) {
|
|
924
|
+
if (!oldHighlightInfo) return newHighlightInfo;
|
|
925
|
+
const changedHighlightInfo = {}
|
|
926
|
+
for (const key of Object.keys(newHighlightInfo)) {
|
|
927
|
+
if (Object.hasOwn(oldHighlightInfo, key) && oldHighlightInfo[key] !== newHighlightInfo[key]) {
|
|
928
|
+
changedHighlightInfo[key] = newHighlightInfo[key];
|
|
1107
929
|
}
|
|
1108
930
|
}
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
//
|
|
1117
|
-
const
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
return lastTextNodeWalker.currentNode;
|
|
1122
|
-
}
|
|
1123
|
-
|
|
1124
|
-
// Update appearance stylesheet (user-defined colors and styles)
|
|
1125
|
-
const updateAppearanceStylesheet = () => {
|
|
1126
|
-
appearanceStylesheet.replaceSync('');
|
|
1127
|
-
for (const color of Object.keys(options.colors)) {
|
|
1128
|
-
appearanceStylesheet.insertRule(`[data-color="${color}"] { --hh-color: ${options.colors[color]}; }`);
|
|
931
|
+
return changedHighlightInfo;
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
// Undraw the specified highlight
|
|
935
|
+
Highlighter.prototype._undrawHighlight = function (highlightInfo) {
|
|
936
|
+
const highlightId = highlightInfo.highlightId;
|
|
937
|
+
|
|
938
|
+
// Remove <mark> highlights and HTML wrappers
|
|
939
|
+
const overlappingHighlightIds = new Set();
|
|
940
|
+
this._annotatableContainer.querySelectorAll(`[data-highlight-id="${highlightId}"]:not(g)`).forEach(element => {
|
|
941
|
+
if (element.parentElement.dataset.highlightId) {
|
|
942
|
+
overlappingHighlightIds.add(element.parentElement.dataset.highlightId);
|
|
1129
943
|
}
|
|
1130
|
-
for (const
|
|
1131
|
-
|
|
1132
|
-
appearanceStylesheet.insertRule(`mark[data-highlight-id][data-style="${style}"] { ${styleTemplate} }`);
|
|
944
|
+
for (const childHighlight of element.querySelectorAll('[data-highlight-id]')) {
|
|
945
|
+
overlappingHighlightIds.add(childHighlight.dataset.highlightId);
|
|
1133
946
|
}
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
style = options.styles.hasOwnProperty(style) ? style : options.defaultStyle;
|
|
1139
|
-
let styleTemplate = options.styles[style]?.[type] ?? '';
|
|
1140
|
-
if (active) {
|
|
1141
|
-
styleTemplate = options.styles[style]?.[`${type}-active`] ?? styleTemplate;
|
|
947
|
+
if (element.matches('mark')) {
|
|
948
|
+
element.outerHTML = element.innerHTML;
|
|
949
|
+
} else {
|
|
950
|
+
element.remove();
|
|
1142
951
|
}
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
952
|
+
});
|
|
953
|
+
|
|
954
|
+
// Redraw overlapping highlights
|
|
955
|
+
overlappingHighlightIds.delete(highlightId);
|
|
956
|
+
if (overlappingHighlightIds.size > 0) {
|
|
957
|
+
for (const overlappingHighlightId of overlappingHighlightIds) {
|
|
958
|
+
this._undrawHighlight(this._highlightsById[overlappingHighlightId]);
|
|
1146
959
|
}
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
960
|
+
this.drawHighlights(overlappingHighlightIds);
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
// Normalize text nodes
|
|
964
|
+
const rangeParagraphs = this._annotatableContainer.querySelectorAll(`#${highlightInfo.startParagraphId}, #${highlightInfo.endParagraphId}`);
|
|
965
|
+
rangeParagraphs.forEach(p => p.normalize());
|
|
966
|
+
this._getCorrectedRangeObj(highlightId);
|
|
967
|
+
|
|
968
|
+
// Remove SVG highlights
|
|
969
|
+
this._svgBackground.querySelectorAll(`g[data-highlight-id="${highlightId}"]`).forEach(element => {
|
|
970
|
+
element.remove();
|
|
971
|
+
});
|
|
972
|
+
|
|
973
|
+
// Remove Highlight API highlights
|
|
974
|
+
if (supportsHighlightApi && CSS.highlights.has(highlightId)) {
|
|
975
|
+
const ruleIndexesToDelete = [];
|
|
976
|
+
for (let r = 0; r < this._highlightApiStylesheet.cssRules.length; r++) {
|
|
977
|
+
if (this._highlightApiStylesheet.cssRules[r].selectorText.includes(`::highlight(${highlightInfo.escapedHighlightId})`)) ruleIndexesToDelete.push(r);
|
|
978
|
+
}
|
|
979
|
+
for (const index of ruleIndexesToDelete.toReversed()) this._highlightApiStylesheet.deleteRule(index);
|
|
980
|
+
CSS.highlights.delete(highlightId);
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
// Update selection background and handles
|
|
985
|
+
Highlighter.prototype._updateSelectionUi = function (changeType = 'appearance') {
|
|
986
|
+
const options = this._options;
|
|
987
|
+
const selection = globalThis.getSelection();
|
|
988
|
+
const selectionRange = selection.type === 'None' ? null : selection.getRangeAt(0);
|
|
989
|
+
|
|
990
|
+
// If the selection starts in another annotatable container, let the other container handle it
|
|
991
|
+
if (selection.anchorNode?.parentElement?.closest('[data-hh-container]') && !this._annotatableContainer.contains(selection.anchorNode)) return;
|
|
992
|
+
|
|
993
|
+
const highlightInfo = this._highlightsById[this._activeHighlightId] ?? null;
|
|
994
|
+
const color = highlightInfo?.color ?? null;
|
|
995
|
+
const style = highlightInfo?.style ?? null;
|
|
996
|
+
const colorString = options.colors[color] ?? (CSS.supports('color', 'AccentColor') ? 'AccentColor' : 'dodgerblue');
|
|
997
|
+
|
|
998
|
+
// Draw SVG selection rects (SVG drawing mode only)
|
|
999
|
+
this._svgActiveOverlay.innerHTML = '';
|
|
1000
|
+
if (this._activeHighlightId && options.drawingMode === 'svg') {
|
|
1001
|
+
let range = this._getCorrectedRangeObj(this._activeHighlightId);
|
|
1002
|
+
range = this._snapRangeToBoundaries(range);
|
|
1003
|
+
const rangeParagraphs = this._annotatableContainer.querySelectorAll(`#${highlightInfo.rangeParagraphIds.join(', #')}`);
|
|
1004
|
+
const clientRects = this._getMergedClientRects(range, rangeParagraphs);
|
|
1005
|
+
this._svgActiveOverlay.dataset.color = color;
|
|
1006
|
+
this._svgActiveOverlay.dataset.style = style;
|
|
1007
|
+
let svgContent = '';
|
|
1008
|
+
for (const clientRect of clientRects) {
|
|
1009
|
+
svgContent += this._getStyleTemplate(highlightInfo.style, 'svg', clientRect, true);
|
|
1010
|
+
}
|
|
1011
|
+
this._svgActiveOverlay.innerHTML = svgContent;
|
|
1012
|
+
|
|
1013
|
+
// Bring active highlight to the front
|
|
1014
|
+
const svgHighlight = this._svgBackground.querySelector(`g[data-highlight-id="${this._activeHighlightId}"]`);
|
|
1015
|
+
if (svgHighlight) this._svgBackground.appendChild(svgHighlight);
|
|
1016
|
+
this._svgBackground.appendChild(this._svgActiveOverlay);
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
if (changeType === 'appearance') {
|
|
1020
|
+
this._annotatableContainer.style.setProperty('--hh-color', colorString);
|
|
1021
|
+
|
|
1022
|
+
// Hide the active highlight (and wrappers), and set a selection style that mimics the highlight. This avoids the need to redraw the highlight while actively editing it (especially important for <mark> highlights, because DOM manipulation around the selection can make the selection UI unstable).
|
|
1023
|
+
if (this._activeHighlightId && options.drawingMode === 'svg') {
|
|
1024
|
+
this._selectionStylesheet.replaceSync(`
|
|
1025
|
+
${options.containerSelector} g[data-highlight-id="${this._activeHighlightId}"][data-style] { display: none; }
|
|
1026
|
+
${options.containerSelector} .hh-wrapper-start[data-highlight-id="${this._activeHighlightId}"], .hh-wrapper-end[data-highlight-id="${this._activeHighlightId}"] { visibility: hidden; }
|
|
1027
|
+
${options.containerSelector} ::selection { background-color: transparent; }
|
|
1028
|
+
`);
|
|
1029
|
+
} else if (this._activeHighlightId) {
|
|
1030
|
+
const styleTemplate = this._getStyleTemplate(style, 'css', null, true);
|
|
1031
|
+
this._selectionStylesheet.replaceSync(`
|
|
1032
|
+
${options.containerSelector} ::highlight(${highlightInfo.escapedHighlightId}) { all: unset; }
|
|
1033
|
+
${options.containerSelector} mark[data-highlight-id="${this._activeHighlightId}"][data-style] { all: unset; }
|
|
1034
|
+
${options.containerSelector} .hh-wrapper-start[data-highlight-id="${this._activeHighlightId}"], .hh-wrapper-end[data-highlight-id="${this._activeHighlightId}"] { visibility: hidden; }
|
|
1035
|
+
${options.containerSelector} ::selection { --hh-color: ${colorString}; ${styleTemplate} }
|
|
1036
|
+
${options.containerSelector} rt::selection, ${options.containerSelector} img::selection { background-color: transparent; }
|
|
1037
|
+
`);
|
|
1038
|
+
|
|
1039
|
+
// No active highlight (show the regular selection UI)
|
|
1040
|
+
} else {
|
|
1041
|
+
this._selectionStylesheet.replaceSync(`
|
|
1042
|
+
${options.containerSelector} ::selection { background-color: Highlight; color: inherit; }
|
|
1043
|
+
${options.containerSelector} rt::selection, ${options.containerSelector} img::selection { background-color: transparent; }
|
|
1044
|
+
`);
|
|
1158
1045
|
}
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
if (
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1046
|
+
|
|
1047
|
+
// Send event
|
|
1048
|
+
this._annotatableContainer.dispatchEvent(new CustomEvent('hh:selectionupdate', { detail: { color: color, style: style, }}));
|
|
1049
|
+
|
|
1050
|
+
} else if (changeType === 'bounds') {
|
|
1051
|
+
// Update selection handle location and visibility
|
|
1052
|
+
if (selection.type === 'Range') {
|
|
1053
|
+
const selectionRangeRects = selectionRange.getClientRects();
|
|
1054
|
+
const startRect = selectionRangeRects[0];
|
|
1055
|
+
const endRect = selectionRangeRects[selectionRangeRects.length - 1];
|
|
1056
|
+
const relativeAncestorClientRect = this._relativeAncestorElement.getBoundingClientRect();
|
|
1057
|
+
const startNodeIsRtl = globalThis.getComputedStyle(selectionRange.startContainer.parentElement).direction === 'rtl';
|
|
1058
|
+
const endNodeIsRtl = globalThis.getComputedStyle(selectionRange.endContainer.parentElement).direction === 'rtl';
|
|
1059
|
+
|
|
1060
|
+
if (
|
|
1061
|
+
(options.showCustomSelectionHandlesOnTouch || this._pointerType === 'mouse')
|
|
1062
|
+
&& ((options.showCustomSelectionHandlesForActiveHighlights && this._activeHighlightId)
|
|
1063
|
+
|| (options.showCustomSelectionHandlesForTextSelection && !this._activeHighlightId))
|
|
1064
|
+
) {
|
|
1065
|
+
for (const selectionHandle of this._selectionHandles) {
|
|
1066
|
+
let side;
|
|
1067
|
+
if (selectionHandle.dataset.position === 'start') {
|
|
1068
|
+
side = startNodeIsRtl ? 'right' : 'left';
|
|
1069
|
+
selectionHandle.style.left = startRect[side] - relativeAncestorClientRect.left + 'px';
|
|
1070
|
+
selectionHandle.style.height = startRect.height + 'px';
|
|
1071
|
+
selectionHandle.style.top = startRect.top - relativeAncestorClientRect.top + 'px';
|
|
1072
|
+
} else {
|
|
1073
|
+
side = endNodeIsRtl ? 'left' : 'right';
|
|
1074
|
+
selectionHandle.style.left = endRect[side] - relativeAncestorClientRect.left + 'px';
|
|
1075
|
+
selectionHandle.style.height = endRect.height + 'px';
|
|
1076
|
+
selectionHandle.style.top = endRect.top - relativeAncestorClientRect.top + 'px';
|
|
1077
|
+
}
|
|
1078
|
+
if (selectionHandle.dataset.side !== side) {
|
|
1079
|
+
selectionHandle.dataset.side = side;
|
|
1080
|
+
this.setOptions({ selectionHandles: options.selectionHandles });
|
|
1081
|
+
}
|
|
1179
1082
|
}
|
|
1180
|
-
|
|
1083
|
+
this._setCustomSelectionHandleVisibility(true);
|
|
1181
1084
|
}
|
|
1182
|
-
|
|
1085
|
+
} else {
|
|
1086
|
+
this._setCustomSelectionHandleVisibility(false);
|
|
1183
1087
|
}
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
Highlighter.prototype._setCustomSelectionHandleVisibility = function (visible = this._selectionHandles[0].style.visibility === 'hidden') {
|
|
1092
|
+
for (const selectionHandle of this._selectionHandles) {
|
|
1093
|
+
selectionHandle.style.visibility = visible ? 'visible' : 'hidden';
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
// Update the selection or highlight range to stay within the annotatable container
|
|
1098
|
+
Highlighter.prototype._snapRangeToBoundaries = function (range, anchorNode = null) {
|
|
1099
|
+
const options = this._options;
|
|
1100
|
+
let startNode = range.startContainer;
|
|
1101
|
+
let endNode = range.endContainer;
|
|
1102
|
+
let startOffset = range.startOffset;
|
|
1103
|
+
let endOffset = range.endOffset;
|
|
1104
|
+
|
|
1105
|
+
// Prevent the range from going outside of the annotatable container
|
|
1106
|
+
if (!this._annotatableContainer.contains(range.commonAncestorContainer)) {
|
|
1107
|
+
if (anchorNode && !this._annotatableContainer.contains(anchorNode)) {
|
|
1108
|
+
// Range is from a selection, and the selection anchor is outside of the container
|
|
1109
|
+
return range.cloneRange().collapse(true);
|
|
1110
|
+
} else if (anchorNode === startNode || this._annotatableContainer.contains(startNode)) {
|
|
1111
|
+
// Range starts in the container but ends outside
|
|
1112
|
+
endNode = this._getLastTextNode(this._annotatableParagraphs[this._annotatableParagraphs.length - 1]);
|
|
1113
|
+
endOffset = endNode.length;
|
|
1114
|
+
} else if (anchorNode === endNode || this._annotatableContainer.contains(endNode)) {
|
|
1115
|
+
// Range starts outside of the container but ends inside
|
|
1116
|
+
startNode = this._getFirstTextNode(this._annotatableParagraphs[0]);
|
|
1117
|
+
startOffset = 0;
|
|
1196
1118
|
}
|
|
1197
1119
|
}
|
|
1198
|
-
|
|
1199
|
-
//
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1120
|
+
|
|
1121
|
+
// If the range starts at the end of a text node, move it to start at the beginning of the following text node. This prevents the range from jumping across the text node boundary and selecting an extra word.
|
|
1122
|
+
if (startOffset === startNode.textContent.length) {
|
|
1123
|
+
const walker = this._getTextNodeWalker(range.commonAncestorContainer);
|
|
1124
|
+
walker.currentNode = startNode;
|
|
1125
|
+
const nextTextNode = walker.nextNode();
|
|
1126
|
+
if (nextTextNode) {
|
|
1127
|
+
startNode = nextTextNode;
|
|
1128
|
+
startOffset = 0;
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
// Prevent the range from starting or ending in an invalid text node
|
|
1133
|
+
if (this._annotatableContainer.contains(range.commonAncestorContainer) && (this._shouldSkipTextNode(startNode) || this._shouldSkipTextNode(endNode))) {
|
|
1134
|
+
if (this._shouldSkipTextNode(startNode)) {
|
|
1135
|
+
startNode = this._getNextValidTextNode(startNode);
|
|
1136
|
+
startOffset = 0;
|
|
1210
1137
|
}
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
// Fix highlight range if the DOM changed and made the previous highlight range invalid
|
|
1215
|
-
const getCorrectedRangeObj = (highlightId) => {
|
|
1216
|
-
const highlightInfo = highlightsById[highlightId];
|
|
1217
|
-
const highlightRange = highlightInfo?.rangeObj;
|
|
1218
|
-
if (highlightRange && (
|
|
1219
|
-
highlightRange.startContainer.nodeType !== Node.TEXT_NODE || highlightRange.endContainer.nodeType !== Node.TEXT_NODE ||
|
|
1220
|
-
highlightRange.startOffset > highlightRange.startContainer.textContent.length - 1 ||
|
|
1221
|
-
highlightRange.endOffset > highlightRange.endContainer.textContent.length
|
|
1222
|
-
)) {
|
|
1223
|
-
const [ startNode, startOffset ] = getTextNodeAndOffset(document.getElementById(highlightInfo.startParagraphId), highlightInfo.startParagraphOffset);
|
|
1224
|
-
const [ endNode, endOffset ] = getTextNodeAndOffset(document.getElementById(highlightInfo.endParagraphId), highlightInfo.endParagraphOffset);
|
|
1225
|
-
highlightRange.setStart(startNode, startOffset);
|
|
1226
|
-
highlightRange.setEnd(endNode, endOffset);
|
|
1138
|
+
if (this._shouldSkipTextNode(endNode)) {
|
|
1139
|
+
endNode = this._getPreviousValidTextNode(endNode);
|
|
1140
|
+
endOffset = endNode.length;
|
|
1227
1141
|
}
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
// Adapted from https://stackoverflow.com/a/12924488/1349044
|
|
1233
|
-
const getCaretFromCoordinates = (clientX, clientY, checkAnnotatable = false, checkXDistance = false, checkYDistance = false) => {
|
|
1234
|
-
let range;
|
|
1235
|
-
if (supportsCaretPositionFromPoint) {
|
|
1236
|
-
let caretPosition = document.caretPositionFromPoint(clientX, clientY);
|
|
1237
|
-
range = document.createRange();
|
|
1238
|
-
range.setStart(caretPosition.offsetNode, caretPosition.offset);
|
|
1239
|
-
range.collapse(true);
|
|
1240
|
-
} else if (supportsCaretRangeFromPoint) {
|
|
1241
|
-
range = document.caretRangeFromPoint(clientX, clientY);
|
|
1142
|
+
if (!startNode || !endNode || (startNode === endNode && startOffset === endOffset)) {
|
|
1143
|
+
return range.cloneRange().collapse(true);
|
|
1144
|
+
} else if (startNode === endNode && endOffset < startOffset) {
|
|
1145
|
+
[startOffset, endOffset] = [endOffset, startOffset];
|
|
1242
1146
|
}
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
// Snap to the nearest word
|
|
1150
|
+
if (options.snapToWord) {
|
|
1151
|
+
// Trim whitespace and dashes at range start and end
|
|
1152
|
+
while (_reWhitespaceDash.test(startOffset < startNode.textContent.length && startNode.textContent[startOffset])) startOffset += 1;
|
|
1153
|
+
while (endOffset > 0 && _reWhitespaceDash.test(endNode.textContent[endOffset - 1])) endOffset -= 1;
|
|
1154
|
+
|
|
1155
|
+
// Expand range to word boundaries
|
|
1156
|
+
while (startOffset > 0 && _reNonWhitespaceDash.test(startNode.textContent[startOffset - 1])) startOffset -= 1;
|
|
1157
|
+
while (endOffset < endNode.textContent.length && _reNonWhitespaceDash.test(endNode.textContent[endOffset])) endOffset += 1;
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
const newRange = document.createRange();
|
|
1161
|
+
newRange.setStart(startNode, startOffset);
|
|
1162
|
+
newRange.setEnd(endNode, endOffset);
|
|
1163
|
+
return newRange;
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
// Get the character offset relative to the annotatable paragraph
|
|
1167
|
+
Highlighter.prototype._getParagraphOffset = function (referenceTextNode, referenceTextNodeOffset) {
|
|
1168
|
+
const paragraph = referenceTextNode.parentElement.closest(this._options.paragraphSelector);
|
|
1169
|
+
const walker = this._getTextNodeWalker(paragraph);
|
|
1170
|
+
let currentOffset = 0;
|
|
1171
|
+
let textNode;
|
|
1172
|
+
while (textNode = walker.nextNode()) {
|
|
1173
|
+
if (textNode === referenceTextNode) {
|
|
1174
|
+
currentOffset += referenceTextNodeOffset;
|
|
1175
|
+
break;
|
|
1176
|
+
}
|
|
1177
|
+
currentOffset += textNode.textContent.length;
|
|
1178
|
+
}
|
|
1179
|
+
return [ paragraph.id, currentOffset ];
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
// Get the character offset relative to the deepest relevant text node
|
|
1183
|
+
Highlighter.prototype._getTextNodeAndOffset = function (parentElement, targetOffset) {
|
|
1184
|
+
let textNode, firstTextNode, currentOffset = 0;
|
|
1185
|
+
const walker = this._getTextNodeWalker(parentElement);
|
|
1186
|
+
while (textNode = walker.nextNode()) {
|
|
1187
|
+
if (!firstTextNode) firstTextNode = walker.currentNode;
|
|
1188
|
+
currentOffset += textNode.textContent.length;
|
|
1189
|
+
if (currentOffset >= targetOffset) {
|
|
1190
|
+
const relativeOffset = textNode.textContent.length - currentOffset + targetOffset
|
|
1191
|
+
return [ textNode, relativeOffset ];
|
|
1249
1192
|
}
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
const
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1193
|
+
}
|
|
1194
|
+
// TODO: Direction isn't always accurate (maybe it resets when selection is cleared and set to a new range programmatically?)
|
|
1195
|
+
const direction = globalThis.getSelection().direction;
|
|
1196
|
+
if (direction == 'backward') {
|
|
1197
|
+
return [ firstTextNode, 0 ];
|
|
1198
|
+
} else {
|
|
1199
|
+
const lastTextNode = walker.currentNode;
|
|
1200
|
+
return [ lastTextNode, lastTextNode.textContent.length ];
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
// Get the first valid text node in an element
|
|
1205
|
+
Highlighter.prototype._getFirstTextNode = function (element) {
|
|
1206
|
+
const walker = this._getTextNodeWalker(element);
|
|
1207
|
+
return walker.nextNode();
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
// Get the last valid text node in an element
|
|
1211
|
+
Highlighter.prototype._getLastTextNode = function (element) {
|
|
1212
|
+
const walker = this._getTextNodeWalker(element);
|
|
1213
|
+
let lastNode = null, node;
|
|
1214
|
+
while (node = walker.nextNode()) lastNode = node;
|
|
1215
|
+
return lastNode;
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
// Get the previous valid text node in the annotatable container
|
|
1219
|
+
Highlighter.prototype._getNextValidTextNode = function (currentNode) {
|
|
1220
|
+
const walker = this._getTextNodeWalker(this._annotatableContainer);
|
|
1221
|
+
walker.currentNode = currentNode;
|
|
1222
|
+
return walker.nextNode();
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
// Get the next valid text node in the annotatable container
|
|
1226
|
+
Highlighter.prototype._getPreviousValidTextNode = function (currentNode) {
|
|
1227
|
+
const walker = this._getTextNodeWalker(this._annotatableContainer);
|
|
1228
|
+
walker.currentNode = currentNode;
|
|
1229
|
+
return walker.previousNode();
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
// Determine if text node should be skipped when snapping to word or calculating character offsets
|
|
1233
|
+
Highlighter.prototype._shouldSkipTextNode = function (textNode) {
|
|
1234
|
+
const parentParagraph = textNode.parentNode.closest(this._options.paragraphSelector);
|
|
1235
|
+
const hhIgnore = textNode.parentNode.closest('[data-hh-ignore]');
|
|
1236
|
+
if (!parentParagraph || hhIgnore || textNode.textContent === '') return true;
|
|
1237
|
+
return false;
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
// Get text node walker
|
|
1241
|
+
Highlighter.prototype._getTextNodeWalker = function (root) {
|
|
1242
|
+
return document.createTreeWalker(root, NodeFilter.SHOW_TEXT, (node) => this._shouldSkipTextNode(node) ? NodeFilter.FILTER_SKIP : NodeFilter.FILTER_ACCEPT);
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
// Update appearance stylesheet (user-defined colors and styles)
|
|
1246
|
+
Highlighter.prototype._updateAppearanceStylesheet = function () {
|
|
1247
|
+
const options = this._options;
|
|
1248
|
+
this._appearanceStylesheet.replaceSync('');
|
|
1249
|
+
for (const color of Object.keys(options.colors)) {
|
|
1250
|
+
this._appearanceStylesheet.insertRule(`[data-color="${color}"] { --hh-color: ${options.colors[color]}; }`);
|
|
1251
|
+
}
|
|
1252
|
+
for (const style of Object.keys(options.styles)) {
|
|
1253
|
+
const styleTemplate = this._getStyleTemplate(style, 'css', null);
|
|
1254
|
+
this._appearanceStylesheet.insertRule(`mark[data-highlight-id][data-style="${style}"] { ${styleTemplate} }`);
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
// Get style template for a given highlight style
|
|
1259
|
+
Highlighter.prototype._getStyleTemplate = function (style, type, clientRect = null, active = false) {
|
|
1260
|
+
const options = this._options;
|
|
1261
|
+
style = Object.hasOwn(options.styles, style) ? style : options.defaultStyle;
|
|
1262
|
+
let styleTemplate = options.styles[style]?.[type] ?? '';
|
|
1263
|
+
if (active) {
|
|
1264
|
+
styleTemplate = options.styles[style]?.[`${type}-active`] ?? styleTemplate;
|
|
1265
|
+
}
|
|
1266
|
+
if (!styleTemplate) {
|
|
1267
|
+
console.warn(`Highlight style "${style}" in options does not have a defined "${type}" value.`);
|
|
1268
|
+
return;
|
|
1269
|
+
}
|
|
1270
|
+
if (type === 'svg' && clientRect) {
|
|
1271
|
+
const relativeAncestorClientRect = this._relativeAncestorElement.getBoundingClientRect();
|
|
1272
|
+
styleTemplate = styleTemplate
|
|
1273
|
+
.replaceAll('{x}', clientRect.x - relativeAncestorClientRect.x)
|
|
1274
|
+
.replaceAll('{y}', clientRect.y - relativeAncestorClientRect.y)
|
|
1275
|
+
.replaceAll('{width}', clientRect.width)
|
|
1276
|
+
.replaceAll('{height}', clientRect.height)
|
|
1277
|
+
.replaceAll('{top}', clientRect.top - relativeAncestorClientRect.top)
|
|
1278
|
+
.replaceAll('{right}', clientRect.right - relativeAncestorClientRect.right)
|
|
1279
|
+
.replaceAll('{bottom}', clientRect.bottom - relativeAncestorClientRect.bottom)
|
|
1280
|
+
.replaceAll('{left}', clientRect.left - relativeAncestorClientRect.left);
|
|
1281
|
+
}
|
|
1282
|
+
return styleTemplate;
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
// Restore the previous selection range in case the browser clears the selection
|
|
1286
|
+
Highlighter.prototype._getRestoredSelectionOrCaret = function (selection, pointerEvent = null) {
|
|
1287
|
+
if (selection.type === 'None') {
|
|
1288
|
+
if (this._previousSelectionRange) {
|
|
1289
|
+
// iOS Safari deselects text when a button is tapped. This restores the selection.
|
|
1290
|
+
selection.addRange(this._previousSelectionRange);
|
|
1291
|
+
} else if (pointerEvent) {
|
|
1292
|
+
// In most browsers, tapping or clicking somewhere on the page creates a selection of 0 character length (selection.type === "Caret"). iOS Safari instead clears the selection (selection.type === "None"). This restores a Caret selection if the selection type is None.
|
|
1293
|
+
let range = this._getCaretFromCoordinates(pointerEvent.clientX, pointerEvent.clientY);
|
|
1294
|
+
selection.addRange(range);
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
return selection;
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
// Fix highlight range if the DOM changed and made the previous highlight range invalid
|
|
1301
|
+
Highlighter.prototype._getCorrectedRangeObj = function (highlightId) {
|
|
1302
|
+
const highlightInfo = this._highlightsById[highlightId];
|
|
1303
|
+
const highlightRange = highlightInfo?.rangeObj;
|
|
1304
|
+
if (highlightRange && (
|
|
1305
|
+
highlightRange.startContainer.nodeType !== Node.TEXT_NODE || highlightRange.endContainer.nodeType !== Node.TEXT_NODE ||
|
|
1306
|
+
highlightRange.startOffset > highlightRange.startContainer.textContent.length - 1 ||
|
|
1307
|
+
highlightRange.endOffset > highlightRange.endContainer.textContent.length
|
|
1308
|
+
)) {
|
|
1309
|
+
const [ startNode, startOffset ] = this._getTextNodeAndOffset(document.getElementById(highlightInfo.startParagraphId), highlightInfo.startParagraphOffset);
|
|
1310
|
+
const [ endNode, endOffset ] = this._getTextNodeAndOffset(document.getElementById(highlightInfo.endParagraphId), highlightInfo.endParagraphOffset);
|
|
1311
|
+
highlightRange.setStart(startNode, startOffset);
|
|
1312
|
+
highlightRange.setEnd(endNode, endOffset);
|
|
1313
|
+
}
|
|
1314
|
+
return highlightRange;
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
// Convert tap or click to a selection range
|
|
1318
|
+
// Adapted from https://stackoverflow.com/a/12924488/1349044
|
|
1319
|
+
Highlighter.prototype._getCaretFromCoordinates = function (clientX, clientY, checkAnnotatable = false, checkXDistance = false, checkYDistance = false) {
|
|
1320
|
+
let range;
|
|
1321
|
+
if (supportsCaretPositionFromPoint) {
|
|
1322
|
+
let caretPosition = document.caretPositionFromPoint(clientX, clientY);
|
|
1323
|
+
range = document.createRange();
|
|
1324
|
+
range.setStart(caretPosition.offsetNode, caretPosition.offset);
|
|
1325
|
+
range.collapse(true);
|
|
1326
|
+
} else if (supportsCaretRangeFromPoint) {
|
|
1327
|
+
range = document.caretRangeFromPoint(clientX, clientY);
|
|
1328
|
+
}
|
|
1329
|
+
if (!range) return;
|
|
1330
|
+
if (checkXDistance || checkYDistance) {
|
|
1331
|
+
const maxDistance = 30;
|
|
1332
|
+
const caretClientRect = range.getBoundingClientRect();
|
|
1333
|
+
if (checkXDistance && Math.abs(clientX - caretClientRect.x) > maxDistance) return;
|
|
1334
|
+
if (checkYDistance && Math.abs(clientY - caretClientRect.top) > maxDistance && Math.abs(clientY - caretClientRect.bottom) > maxDistance) return;
|
|
1335
|
+
}
|
|
1336
|
+
if (checkAnnotatable && !range.startContainer.parentElement.closest(this._options.paragraphSelector)) return;
|
|
1337
|
+
return range;
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1340
|
+
// Check if a point is in a DOMRect
|
|
1341
|
+
Highlighter.prototype._isPointInRect = function (x, y, rect, padding = 0) {
|
|
1342
|
+
return (
|
|
1343
|
+
x >= rect.x - padding && x <= rect.x + rect.width + padding &&
|
|
1344
|
+
y >= rect.y - padding && y <= rect.y + rect.height + padding
|
|
1345
|
+
)
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
// Get merged client rects from the highlight range
|
|
1349
|
+
Highlighter.prototype._getMergedClientRects = function (range, paragraphs) {
|
|
1350
|
+
const unmergedRects = Array.from(range.getClientRects());
|
|
1351
|
+
const mergedRects = [];
|
|
1352
|
+
|
|
1353
|
+
// Remove element rects (only text node rects are needed)
|
|
1354
|
+
const ancestorElementsInRange = new Set();
|
|
1355
|
+
for (const paragraph of paragraphs) {
|
|
1356
|
+
let element = paragraph;
|
|
1357
|
+
while (range.commonAncestorContainer.contains(element)) {
|
|
1358
|
+
ancestorElementsInRange.add(element);
|
|
1359
|
+
element = element.parentElement;
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
for (let ur = unmergedRects.length - 1; ur >= 0; ur--) {
|
|
1363
|
+
const rect = unmergedRects[ur];
|
|
1364
|
+
for (const element of ancestorElementsInRange) {
|
|
1365
|
+
const elementRect = element.getBoundingClientRect();
|
|
1366
|
+
if (Math.round(elementRect.width) === Math.round(rect.width) && Math.round(elementRect.height) === Math.round(rect.height) && Math.round(elementRect.top) === Math.round(rect.top) && Math.round(elementRect.left) === Math.round(rect.left)) {
|
|
1367
|
+
unmergedRects.splice(ur, 1);
|
|
1368
|
+
break;
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
// Loop through the highlight's paragraphs
|
|
1374
|
+
for (const paragraph of paragraphs) {
|
|
1375
|
+
const paragraphRect = paragraph.getBoundingClientRect();
|
|
1376
|
+
const paragraphStyle = getComputedStyle(paragraph);
|
|
1377
|
+
const snapTolerance = Math.max(Number.parseInt(paragraphStyle.fontSize) / 2, 4);
|
|
1378
|
+
const topPadding = Number.parseInt(paragraphStyle.paddingTop);
|
|
1379
|
+
const textIndent = Number.parseInt(paragraphStyle.textIndent);
|
|
1380
|
+
|
|
1381
|
+
// Build line positions from paragraph text nodes
|
|
1382
|
+
const linePositions = {};
|
|
1383
|
+
const lineBottomKeys = [];
|
|
1384
|
+
const walker = this._getTextNodeWalker(paragraph);
|
|
1385
|
+
const textNodeRange = document.createRange();
|
|
1386
|
+
let textNode;
|
|
1387
|
+
while (textNode = walker.nextNode()) {
|
|
1388
|
+
// Skip text nodes in elements that are higher or lower than surrounding text
|
|
1389
|
+
if (textNode.parentElement.closest('sup, sub, rt')) continue;
|
|
1390
|
+
textNodeRange.selectNode(textNode);
|
|
1391
|
+
for (const rect of textNodeRange.getClientRects()) {
|
|
1392
|
+
// Round to a nearby line position if close
|
|
1393
|
+
const lineBottom = lineBottomKeys.find(b => Math.abs(b - rect.bottom) < snapTolerance) ?? rect.bottom;
|
|
1394
|
+
if (!linePositions[lineBottom]) lineBottomKeys.push(lineBottom);
|
|
1395
|
+
const pos = linePositions[lineBottom] ??= {
|
|
1396
|
+
minLeft: rect.left, maxRight: rect.right,
|
|
1397
|
+
highlightLeft: null, highlightRight: null,
|
|
1398
|
+
};
|
|
1399
|
+
pos.minLeft = Math.min(pos.minLeft, rect.left);
|
|
1400
|
+
pos.maxRight = Math.max(pos.maxRight, rect.right);
|
|
1274
1401
|
}
|
|
1275
1402
|
}
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1403
|
+
|
|
1404
|
+
const lineBottoms = lineBottomKeys.sort((a, b) => a - b);
|
|
1405
|
+
|
|
1406
|
+
// Assign highlight range rects to matching line positions
|
|
1407
|
+
for (const rect of unmergedRects) {
|
|
1408
|
+
const centerY = rect.y + rect.height / 2;
|
|
1409
|
+
for (let i = 0; i < lineBottoms.length; i++) {
|
|
1410
|
+
const pos = linePositions[lineBottoms[i]];
|
|
1411
|
+
// Skip rects that extend outside the line of text (such as absolutely-positioned elements)
|
|
1412
|
+
if (rect.left >= pos.minLeft && rect.right <= pos.maxRight
|
|
1413
|
+
&& centerY > (lineBottoms[i - 1] ?? (paragraphRect.top + topPadding)) && centerY <= lineBottoms[i]) {
|
|
1414
|
+
pos.highlightLeft = Math.min(pos.highlightLeft ?? rect.left, rect.left);
|
|
1415
|
+
pos.highlightRight = Math.max(pos.highlightRight ?? rect.right, rect.right);
|
|
1282
1416
|
break;
|
|
1283
1417
|
}
|
|
1284
1418
|
}
|
|
1285
1419
|
}
|
|
1286
|
-
|
|
1287
|
-
//
|
|
1288
|
-
for (
|
|
1289
|
-
const
|
|
1290
|
-
const
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
let
|
|
1296
|
-
let
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1420
|
+
|
|
1421
|
+
// Create a merged rect for each relevant line
|
|
1422
|
+
for (let i = 0; i < lineBottoms.length; i++) {
|
|
1423
|
+
const bottom = lineBottoms[i];
|
|
1424
|
+
const pos = linePositions[bottom];
|
|
1425
|
+
if (pos.highlightLeft == null) continue;
|
|
1426
|
+
const nearbyBottom = lineBottoms[i - 1] ?? lineBottoms[i + 1] ?? (paragraphRect.top + topPadding);
|
|
1427
|
+
const height = Math.abs(bottom - nearbyBottom);
|
|
1428
|
+
const top = bottom - height;
|
|
1429
|
+
let left = Math.max(pos.minLeft, pos.highlightLeft);
|
|
1430
|
+
let right = Math.min(pos.maxRight, pos.highlightRight);
|
|
1431
|
+
|
|
1432
|
+
// Final adjustment to left and right bounds
|
|
1433
|
+
if (paragraphStyle.direction === 'ltr' && paragraphStyle.textAlign === 'start') {
|
|
1434
|
+
if (left - paragraphRect.left < snapTolerance) left = paragraphRect.left;
|
|
1435
|
+
if (textIndent < 0) left += textIndent;
|
|
1436
|
+
} else if (paragraphStyle.direction === 'rtl' && paragraphStyle.textAlign === 'start') {
|
|
1437
|
+
if (paragraphRect.right - right < snapTolerance) right = paragraphRect.right;
|
|
1438
|
+
if (textIndent < 0) right += textIndent;
|
|
1303
1439
|
}
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
}
|
|
1331
|
-
}
|
|
1332
|
-
if (mergedRect.width > 0) mergedRects.push(mergedRect);
|
|
1440
|
+
|
|
1441
|
+
const width = right - left;
|
|
1442
|
+
mergedRects.push(new DOMRect(left, top, width, height));
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
return mergedRects;
|
|
1447
|
+
}
|
|
1448
|
+
|
|
1449
|
+
|
|
1450
|
+
/********************** Utilities **********************/
|
|
1451
|
+
|
|
1452
|
+
// Add a CSS stylesheet to the document
|
|
1453
|
+
function addStylesheet(stylesheets, stylesheetKey) {
|
|
1454
|
+
let stylesheet = stylesheets[stylesheetKey];
|
|
1455
|
+
if (!stylesheet) {
|
|
1456
|
+
if (supportsCssStylesheetApi) {
|
|
1457
|
+
stylesheet = new CSSStyleSheet();
|
|
1458
|
+
document.adoptedStyleSheets.push(stylesheet);
|
|
1459
|
+
} else {
|
|
1460
|
+
// For browsers that don't fully support the CSSStyleSheet API, such as Safari < 16.4.
|
|
1461
|
+
// See https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet#browser_compatibility
|
|
1462
|
+
stylesheet = document.createElement('style');
|
|
1463
|
+
stylesheet.appendChild(document.createTextNode(''));
|
|
1464
|
+
stylesheet.replaceSync = (newContent) => {
|
|
1465
|
+
stylesheet.textContent = newContent;
|
|
1333
1466
|
}
|
|
1467
|
+
stylesheet.insertRule = (newContent) => {
|
|
1468
|
+
stylesheet.textContent += newContent;
|
|
1469
|
+
}
|
|
1470
|
+
document.head.appendChild(stylesheet);
|
|
1334
1471
|
}
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
const
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1472
|
+
stylesheets[stylesheetKey] = stylesheet;
|
|
1473
|
+
}
|
|
1474
|
+
return stylesheet;
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
// Remove CSS stylesheets (only those from the current Highlighter instance)
|
|
1478
|
+
function removeStylesheets(stylesheets) {
|
|
1479
|
+
for (const stylesheet of Object.values(stylesheets)) {
|
|
1480
|
+
if (supportsCssStylesheetApi) {
|
|
1481
|
+
const adoptedStylesheetIndex = document.adoptedStyleSheets.indexOf(stylesheet);
|
|
1482
|
+
document.adoptedStyleSheets.splice(adoptedStylesheetIndex, 1);
|
|
1483
|
+
} else {
|
|
1484
|
+
stylesheet.remove();
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
// Debounce a function to prevent it from being executed too frequently
|
|
1490
|
+
// Adapted from https://levelup.gitconnected.com/debounce-in-javascript-improve-your-applications-performance-5b01855e086
|
|
1491
|
+
function debounce(func, wait) {
|
|
1492
|
+
let timeout;
|
|
1493
|
+
return function executedFunction(...args) {
|
|
1494
|
+
const later = () => {
|
|
1348
1495
|
clearTimeout(timeout);
|
|
1349
|
-
|
|
1496
|
+
func(...args);
|
|
1350
1497
|
};
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
updateSelectionUi('appearance');
|
|
1355
|
-
this.setOption('selectionHandles', options.selectionHandles);
|
|
1498
|
+
clearTimeout(timeout);
|
|
1499
|
+
timeout = setTimeout(later, wait);
|
|
1500
|
+
};
|
|
1356
1501
|
}
|
|
1357
1502
|
|
|
1503
|
+
// Default function for generating a highlight ID
|
|
1504
|
+
const _getNewHighlightId = () => {
|
|
1505
|
+
return 'hh-' + Date.now().toString();
|
|
1506
|
+
}
|
|
1358
1507
|
|
|
1359
|
-
|
|
1508
|
+
|
|
1509
|
+
/********************** Constants **********************/
|
|
1360
1510
|
|
|
1361
1511
|
// Keep track of all Highlighter instances
|
|
1362
|
-
let
|
|
1512
|
+
let _highlighters = [];
|
|
1363
1513
|
|
|
1364
1514
|
// Check browser type
|
|
1365
1515
|
const isTouchDevice = navigator.maxTouchPoints > 0;
|
|
1366
1516
|
const isWebKit = /^((?!Chrome|Firefox|Android|Samsung).)*AppleWebKit/i.test(navigator.userAgent);
|
|
1367
|
-
const isWKWebView = isWebKit &&
|
|
1517
|
+
const isWKWebView = isWebKit && globalThis.webkit?.messageHandlers;
|
|
1368
1518
|
const supportsCaretPositionFromPoint = document.caretPositionFromPoint;
|
|
1369
1519
|
const supportsCaretRangeFromPoint = document.caretRangeFromPoint;
|
|
1370
1520
|
const supportsCssStylesheetApi = CSSStyleSheet?.prototype?.replaceSync;
|
|
1371
1521
|
const supportsHighlightApi = CSS.highlights;
|
|
1372
1522
|
|
|
1373
|
-
//
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
const tempInput = document.createElement('input');
|
|
1377
|
-
tempInput.style.position = 'fixed';
|
|
1378
|
-
tempInput.style.top = 0;
|
|
1379
|
-
tempInput.style.opacity = 0;
|
|
1380
|
-
tempInput.style.height = 0;
|
|
1381
|
-
tempInput.style.fontSize = '16px'; // Prevent page zoom on input focus
|
|
1382
|
-
tempInput.inputMode = 'none'; // Don't show keyboard
|
|
1383
|
-
tempInput.tabIndex = -1; // Prevent user from tabbing to input
|
|
1384
|
-
tempInput.ariaHidden = 'true'; // Hide from screen readers
|
|
1385
|
-
const initializeSelection = (event) => {
|
|
1386
|
-
if (document.readyState !== 'complete') return setTimeout(initializeSelection, 20);
|
|
1387
|
-
if (!tempInput.parentElement) document.body.append(tempInput);
|
|
1388
|
-
tempInput.focus();
|
|
1389
|
-
setTimeout(() => {
|
|
1390
|
-
tempInput.blur();
|
|
1391
|
-
}, 100);
|
|
1392
|
-
}
|
|
1393
|
-
initializeSelection();
|
|
1394
|
-
document.addEventListener('visibilitychange', (event) => {
|
|
1395
|
-
if (document.visibilityState === 'visible') initializeSelection();
|
|
1396
|
-
});
|
|
1397
|
-
}
|
|
1398
|
-
|
|
1399
|
-
// Default function for generating a highlight ID
|
|
1400
|
-
const hhGetNewHighlightId = () => {
|
|
1401
|
-
return 'hh-' + Date.now().toString();
|
|
1402
|
-
}
|
|
1523
|
+
// Regex patterns for word boundary detection
|
|
1524
|
+
const _reWhitespaceDash = /\s|\p{Pd}/u;
|
|
1525
|
+
const _reNonWhitespaceDash = /[^\s|\p{Pd}]/u;
|
|
1403
1526
|
|
|
1404
1527
|
// Default options
|
|
1405
|
-
|
|
1528
|
+
const _defaultOptions = {
|
|
1406
1529
|
containerSelector: 'body',
|
|
1407
1530
|
paragraphSelector: 'h1[id], h2[id], h3[id], h4[id], h5[id], h6[id], p[id], ol[id], ul[id], dl[id], tr[id]',
|
|
1408
1531
|
colors: {
|
|
@@ -1463,13 +1586,37 @@ let hhDefaultOptions = {
|
|
|
1463
1586
|
defaultColor: 'yellow',
|
|
1464
1587
|
defaultStyle: 'fill',
|
|
1465
1588
|
defaultWrapper: 'none',
|
|
1466
|
-
highlightIdFunction:
|
|
1589
|
+
highlightIdFunction: _getNewHighlightId,
|
|
1467
1590
|
showCustomSelectionHandlesForActiveHighlights: true,
|
|
1468
1591
|
showCustomSelectionHandlesForTextSelection: false,
|
|
1469
1592
|
showCustomSelectionHandlesOnTouch: false,
|
|
1470
1593
|
}
|
|
1471
1594
|
|
|
1472
|
-
|
|
1595
|
+
// Workaround to allow programmatic text selection on tap in iOS Safari
|
|
1596
|
+
// See https://stackoverflow.com/a/79261423/1349044
|
|
1597
|
+
if (isTouchDevice && isWebKit) {
|
|
1598
|
+
const tempInput = document.createElement('input');
|
|
1599
|
+
tempInput.style.position = 'fixed';
|
|
1600
|
+
tempInput.style.top = 0;
|
|
1601
|
+
tempInput.style.opacity = 0;
|
|
1602
|
+
tempInput.style.height = 0;
|
|
1603
|
+
tempInput.style.fontSize = '16px'; // Prevent page zoom on input focus
|
|
1604
|
+
tempInput.inputMode = 'none'; // Don't show keyboard
|
|
1605
|
+
tempInput.tabIndex = -1; // Prevent user from tabbing to input
|
|
1606
|
+
tempInput.ariaHidden = 'true'; // Hide from screen readers
|
|
1607
|
+
const initializeSelection = (event) => {
|
|
1608
|
+
if (document.readyState !== 'complete') return setTimeout(initializeSelection, 20);
|
|
1609
|
+
if (!tempInput.parentElement) document.body.append(tempInput);
|
|
1610
|
+
tempInput.focus();
|
|
1611
|
+
setTimeout(() => {
|
|
1612
|
+
tempInput.blur();
|
|
1613
|
+
}, 100);
|
|
1614
|
+
}
|
|
1615
|
+
initializeSelection();
|
|
1616
|
+
document.addEventListener('visibilitychange', (event) => {
|
|
1617
|
+
if (document.visibilityState === 'visible') initializeSelection();
|
|
1618
|
+
});
|
|
1619
|
+
}
|
|
1473
1620
|
|
|
1474
|
-
// Make Highlighter available to
|
|
1475
|
-
|
|
1621
|
+
// Make Highlighter available to JavaScript module (highlight-helper.mjs)
|
|
1622
|
+
globalThis.Highlighter = Highlighter;
|