-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhighlight-helper.js
executable file
·1199 lines (1076 loc) · 57.9 KB
/
highlight-helper.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
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
995
996
997
998
999
1000
/**
* Highlight Helper
* https://github.com/samuelbradshaw/highlight-helper-js
*/
function Highlighter(options = hhDefaultOptions) {
for (const key of Object.keys(hhDefaultOptions)) {
options[key] = options[key] ?? hhDefaultOptions[key];
}
this.annotatableContainer, this.annotatableParagraphs;
let generalStylesheet, appearanceStylesheet, highlightApiStylesheet, selectionStylesheet;
let annotatableParagraphIds, hyperlinkElements;
let svgBackground, svgActiveOverlay, selectionHandles;
let highlightsById, hyperlinksByPosition;
let controller;
const initializeHighlighter = (previousContainerSelector = null) => {
if (!options.paragraphSelector.includes(options.containerSelector)) {
const paragraphSelectorList = options.paragraphSelector.split(',').map(selector => `${options.containerSelector} ${selector}`);
options.paragraphSelector = paragraphSelectorList.join(',');
}
this.annotatableContainer = document.querySelector(options.containerSelector);
this.annotatableParagraphs = this.annotatableContainer.querySelectorAll(options.paragraphSelector);
annotatableParagraphIds = Array.from(this.annotatableParagraphs, paragraph => paragraph.id);
// Handle cases where a highlighter already exists for the container, or one of its children or ancestors
const previousContainer = document.querySelector(previousContainerSelector) ?? this.annotatableContainer;
if (previousContainer.highlighter) {
previousContainer.highlighter.removeHighlighter();
} else if (this.annotatableContainer.closest('[data-hh-container]') || this.annotatableContainer.querySelector('[data-hh-container]')) {
console.error(`Unable to create Highlighter with container selector “${options.containerSelector}” (annotatable container can’t be an child or ancestor of another annotatable container).`);
return false;
}
// Abort controller can be used to cancel event listeners if the highlighter is removed
controller = new AbortController;
// 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.
document.body.tabIndex = -1;
// Set up stylesheets
generalStylesheet = new CSSStyleSheet();
appearanceStylesheet = new CSSStyleSheet();
highlightApiStylesheet = new CSSStyleSheet();
selectionStylesheet = new CSSStyleSheet();
document.adoptedStyleSheets.push(generalStylesheet);
document.adoptedStyleSheets.push(appearanceStylesheet);
document.adoptedStyleSheets.push(highlightApiStylesheet);
document.adoptedStyleSheets.push(selectionStylesheet);
generalStylesheet.replaceSync(`
${options.containerSelector} {
position: relative;
-webkit-tap-highlight-color: transparent;
}
.hh-wrapper-start, .hh-wrapper-end {
-webkit-user-select: none;
user-select: none;
}
.hh-selection-handle {
position: absolute;
width: 0;
display: none;
}
.hh-selection-handle-content {
position: absolute;
height: 100%;
}
.hh-selection-handle [draggable] {
position: absolute;
top: 0;
width: 15px;
height: calc(100% + 10px);
background-color: transparent;
z-index: 1;
}
.hh-selection-handle [draggable]:hover,
.hh-selection-handle [draggable]:active { cursor: ew-resize; }
.hh-selection-handle[data-position="left"] [draggable] { right: 0; }
.hh-selection-handle[data-position="right"] [draggable] { left: 0; }
.hh-default-handle {
position: absolute;
width: 10px;
height: calc(100% + 5px);
background-color: hsl(from var(--hh-color) h 80% 50% / 1);
outline: 1px solid white;
outline-offset: -1px;
top: 0;
}
.hh-selection-handle[data-position="left"] .hh-default-handle {
right: 0;
border-radius: 20px 0 10px 10px;
}
.hh-selection-handle[data-position="right"] .hh-default-handle {
left: 0;
border-radius: 0 20px 10px 10px;
}
.hh-svg-background {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
}
.hh-svg-background g {
fill: transparent;
stroke: none;
}
span[data-highlight-id][data-style="fill"][data-start] {
border-top-left-radius: 0.25em;
border-bottom-left-radius: 0.25em;
margin-left: -0.13em; padding-left: 0.13em;
}
span[data-highlight-id][data-style="fill"][data-end] {
border-top-right-radius: 0.25em;
border-bottom-right-radius: 0.25em;
margin-right: -0.13em; padding-right: 0.13em;
}
`);
// Set up SVG background and selection handles
svgBackground = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svgActiveOverlay = document.createElementNS('http://www.w3.org/2000/svg', 'g');
svgActiveOverlay.dataset.activeOverlay = '';
svgBackground.appendChild(svgActiveOverlay);
svgBackground.classList.add('hh-svg-background');
this.annotatableContainer.appendChild(svgBackground);
this.annotatableContainer.insertAdjacentHTML('beforeend', `
<div class="hh-selection-handle" data-position="left"><div draggable="true"></div><div class="hh-selection-handle-content"></div></div>
<div class="hh-selection-handle" data-position="right"><div draggable="true"></div><div class="hh-selection-handle-content"></div></div>
`);
selectionHandles = this.annotatableContainer.getElementsByClassName('hh-selection-handle');
// Check for hyperlinks on the page
hyperlinkElements = this.annotatableContainer.getElementsByTagName('a');
hyperlinksByPosition = {}
for (let hyp = 0; hyp < hyperlinkElements.length; hyp++) {
hyperlinksByPosition[hyp] = {
'position': hyp,
'text': hyperlinkElements[hyp].innerHTML,
'url': hyperlinkElements[hyp].href,
'hyperlinkElement': hyperlinkElements[hyp],
}
}
highlightsById = {};
this.annotatableContainer.dataset.hhContainer = '';
this.annotatableContainer.highlighter = this;
hhHighlighters.push(this);
return true;
}
const isInitialized = initializeHighlighter();
if (!isInitialized) return;
let activeHighlightId, previousSelectionRange, activeSelectionHandle, isStylus, tapResult, longPressTimeoutId;
// -------- PUBLIC METHODS --------
// Load highlights
this.loadHighlights = (highlights) => {
// Don't load highlights until the document is ready (otherwise, highlights may be offset)
if (document.readyState !== 'complete') return setTimeout(this.loadHighlights, 10, highlights);
const startTimestamp = Date.now();
// Hide container (repeated DOM manipulations are faster if the container is hidden)
if (highlights.length > 1) (options.drawingMode === 'svg' ? svgBackground : this.annotatableContainer).style.display = 'none';
// Load read-only highlights first (read-only highlights change the DOM, affecting other highlights' ranges)
const sortedHighlights = highlights.sort((a,b) => a.readOnly === b.readOnly ? 0 : a.readOnly ? -1 : 1);
const knownHighlightIds = Object.keys(highlightsById);
let addedCount = 0, updatedCount = 0;
for (const highlight of sortedHighlights) {
const highlightInfo = diffHighlight(highlight, highlightsById[highlight.highlightId]);
highlightInfo.highlightId = highlight.highlightId;
const knownHighlightIndex = knownHighlightIds.indexOf(highlightInfo.highlightId);
if (knownHighlightIndex > -1) {
knownHighlightIds.splice(knownHighlightIndex, 1);
if (Object.keys(highlightInfo).length > 1) {
this.createOrUpdateHighlight(highlightInfo, false); updatedCount++;
}
} else {
this.createOrUpdateHighlight(highlightInfo, false); addedCount++;
}
}
if (knownHighlightIds.length > 0) this.removeHighlights(knownHighlightIds);
(options.drawingMode === 'svg' ? svgBackground : this.annotatableContainer).style.display = '';
this.annotatableContainer.dispatchEvent(new CustomEvent('hh:highlightsload', { detail: {
addedCount: addedCount, removedCount: knownHighlightIds.length, updatedCount: updatedCount,
totalCount: Object.keys(highlightsById).length,
timeToLoad: Date.now() - startTimestamp,
} }));
}
// Draw (or redraw) specified highlights, or all highlights on the page
this.drawHighlights = (highlightIds = Object.keys(highlightsById)) => {
// Hide container (repeated DOM manipulations is faster if the container is hidden)
if (highlightIds.length > 1) (options.drawingMode === 'svg' ? svgBackground : this.annotatableContainer).style.display = 'none';
for (const highlightId of highlightIds) {
const highlightInfo = highlightsById[highlightId];
let range = getCorrectedRangeObj(highlightId);
const rangeParagraphs = this.annotatableContainer.querySelectorAll(`#${highlightInfo.rangeParagraphIds.join(', #')}`);
const isReadOnly = (options.drawingMode === 'inserted-spans') || highlightInfo.readOnly;
const wasDrawnAsReadOnly = this.annotatableContainer.querySelector(`[data-highlight-id="${highlightId}"][data-read-only]`);
// Remove old highlight elements and styles
if (!wasDrawnAsReadOnly || (wasDrawnAsReadOnly && !isReadOnly)) undrawHighlight(highlightInfo);
if (isReadOnly) {
// Don't redraw a read-only highlight
if (wasDrawnAsReadOnly) continue;
// Inject HTML <span> elements
range.startContainer.splitText(range.startOffset);
range.endContainer.splitText(range.endOffset);
const textNodeIter = document.createNodeIterator(range.commonAncestorContainer, NodeFilter.SHOW_TEXT);
const relevantTextNodes = [];
while (node = textNodeIter.nextNode()) {
if (range.intersectsNode(node) && node !== range.startContainer && node.textContent !== '' && !node.parentElement.closest('rt')) relevantTextNodes.push(node);
if (node === range.endContainer) break;
}
for (let tn = 0; tn < relevantTextNodes.length; tn++) {
const textNode = relevantTextNodes[tn];
const styledSpan = document.createElement('span');
styledSpan.dataset.highlightId = highlightId;
styledSpan.dataset.readOnly = '';
styledSpan.dataset.color = highlightInfo.color;
styledSpan.dataset.style = highlightInfo.style;
if (tn === 0) styledSpan.dataset.start = '';
if (tn === relevantTextNodes.length - 1) styledSpan.dataset.end = '';
textNode.before(styledSpan);
styledSpan.appendChild(textNode);
}
rangeParagraphs.forEach(p => { p.normalize(); });
// Update the highlight's stored range object (because the DOM changed)
range = getCorrectedRangeObj(highlightId);
} else {
// Draw highlights with Custom Highlight API
if (options.drawingMode === 'highlight-api' && supportsHighlightApi) {
if (CSS.highlights.has(highlightId)) {
highlightObj = CSS.highlights.get(highlightId);
highlightObj.clear();
} else {
highlightObj = new Highlight();
CSS.highlights.set(highlightId, highlightObj);
}
highlightObj.add(range);
let styleTemplate = getStyleTemplate(highlightInfo.style, 'css', null).replaceAll('var(--hh-color)', options.colors[highlightInfo.color]);
highlightApiStylesheet.insertRule(`${options.containerSelector} ::highlight(${highlightInfo.escapedHighlightId}) { ${styleTemplate} }`);
highlightApiStylesheet.insertRule(`${options.containerSelector} rt::highlight(${highlightInfo.escapedHighlightId}) { color: inherit; background-color: transparent; }`);
highlightApiStylesheet.insertRule(`${options.containerSelector} img::highlight(${highlightInfo.escapedHighlightId}) { color: inherit; background-color: transparent; }`);
// Draw highlights with SVG shapes
} else if (options.drawingMode === 'svg') {
const clientRects = getMergedClientRects(range, rangeParagraphs);
let group = document.createElementNS('http://www.w3.org/2000/svg', 'g');
group.dataset.highlightId = highlightId;
group.dataset.color = highlightInfo.color;
group.dataset.style = highlightInfo.style;
let svgContent = '';
for (const clientRect of clientRects) {
svgContent += getStyleTemplate(highlightInfo.style, 'svg', clientRect);
}
group.innerHTML = svgContent;
svgBackground.appendChild(group);
}
}
// Update wrapper
// TODO: Enable wrappers for editable highlights
if (isReadOnly && !wasDrawnAsReadOnly) {
if (highlightInfo.wrapper && (options.wrappers[highlightInfo.wrapper]?.start || options.wrappers[highlightInfo.wrapper]?.end)) {
const addWrapper = (edge, range, htmlString) => {
htmlString = `<span class="hh-wrapper-${edge}" data-highlight-id="${highlightId}" data-color="${highlightInfo.color}" data-style="${highlightInfo.style}">${htmlString}</span>`
for (const key of Object.keys(highlightInfo.wrapperVariables)) {
htmlString = htmlString.replaceAll(`{${key}}`, highlightInfo.wrapperVariables[key]);
}
const template = document.createElement('template');
template.innerHTML = htmlString;
let htmlElement = template.content.firstChild;
const textNodeIter = document.createNodeIterator(htmlElement, NodeFilter.SHOW_TEXT);
while (node = textNodeIter.nextNode()) node.parentNode.removeChild(node);
range.insertNode(htmlElement);
}
const startRange = highlightInfo.rangeObj;
const endRange = document.createRange(); endRange.setStart(highlightInfo.rangeObj.endContainer, highlightInfo.rangeObj.endOffset);
const wrapperInfo = options.wrappers[highlightInfo.wrapper];
addWrapper('start', startRange, wrapperInfo.start);
addWrapper('end', endRange, wrapperInfo.end);
rangeParagraphs.forEach(p => { p.normalize(); });
}
}
}
// Show container
(options.drawingMode === 'svg' ? svgBackground : this.annotatableContainer).style.display = '';
}
// Create a new highlight, or update an existing highlight when it changes
this.createOrUpdateHighlight = (attributes = {}, triggeredByUserAction = true) => {
let highlightId = attributes.highlightId ?? activeHighlightId ?? options.highlightIdFunction();
appearanceChanges = [];
boundsChanges = [];
let isNewHighlight, oldHighlightInfo;
if (highlightsById.hasOwnProperty(highlightId)) {
oldHighlightInfo = highlightsById[highlightId];
} else {
isNewHighlight = true;
}
// If a different highlight is active, deactivate it
if (activeHighlightId && highlightId !== activeHighlightId) this.deactivateHighlights();
// Warn if color, style, or wrapper attributes are invalid
if (attributes.color && !options.colors.hasOwnProperty(attributes.color)) {
console.warn(`Highlight color "${attributes.color}" is not defined in options (highlightId: ${highlightId}).`);
}
if (attributes.style && !options.styles.hasOwnProperty(attributes.style)) {
console.warn(`Highlight style "${attributes.style}" is not defined in options (highlightId: ${highlightId}).`);
}
if (attributes.wrapper && !options.wrappers.hasOwnProperty(attributes.wrapper)) {
console.warn(`Highlight wrapper "${attributes.wrapper}" is not defined in options (highlightId: ${highlightId}).`);
}
// Update defaults
if (options.rememberStyle && triggeredByUserAction) {
if (attributes.color) options.defaultColor = attributes.color;
if (attributes.style) options.defaultStyle = attributes.style;
if (attributes.wrapper) options.defaultWrapper = attributes.wrapper;
}
// Check which appearance properties changed
for (const key of ['color', 'style', 'wrapper', 'wrapperVariables', 'readOnly']) {
if (isNewHighlight || (attributes[key] != null && attributes[key] !== oldHighlightInfo[key])) appearanceChanges.push(key);
}
// If the highlight was and still is read-only, return
if (oldHighlightInfo?.readOnly && (attributes.readOnly == null || attributes.readOnly === true)) return this.deactivateHighlights();
// Calculate the bounds of the highlight range, if it's changed
let adjustedSelectionRange, highlightRange;
let rangeText, rangeHtml, rangeParagraphIds;
let startParagraphId, startParagraphOffset, endParagraphId, endParagraphOffset;
const selection = window.getSelection();
if (selection.type === 'Range') adjustedSelectionRange = snapRangeToBoundaries(selection.getRangeAt(0));
if ((attributes.startParagraphId ?? attributes.startParagraphOffset ?? attributes.endParagraphId ?? attributes.endParagraphOffset != null) || adjustedSelectionRange) {
let startNode, startOffset, endNode, endOffset;
if (attributes.startParagraphId ?? attributes.startParagraphOffset ?? attributes.endParagraphId ?? attributes.endParagraphOffset != null) {
startParagraphId = attributes.startParagraphId ?? oldHighlightInfo?.startParagraphId;
startParagraphOffset = parseInt(attributes.startParagraphOffset ?? oldHighlightInfo?.startParagraphOffset);
endParagraphId = attributes.endParagraphId ?? oldHighlightInfo?.endParagraphId;
endParagraphOffset = parseInt(attributes.endParagraphOffset ?? oldHighlightInfo?.endParagraphOffset);
([ startNode, startOffset ] = getTextNodeAndOffset(document.getElementById(startParagraphId), startParagraphOffset));
([ endNode, endOffset ] = getTextNodeAndOffset(document.getElementById(endParagraphId), endParagraphOffset));
} else if (adjustedSelectionRange) {
startNode = adjustedSelectionRange.startContainer;
startOffset = adjustedSelectionRange.startOffset;
endNode = adjustedSelectionRange.endContainer;
endOffset = adjustedSelectionRange.endOffset;
([ startParagraphId, startParagraphOffset ] = getParagraphOffset(startNode, startOffset));
([ endParagraphId, endParagraphOffset ] = getParagraphOffset(endNode, endOffset));
}
// Create a new highlight range
highlightRange = document.createRange();
highlightRange.setStart(startNode, startOffset);
highlightRange.setEnd(endNode, endOffset);
// Check which bounds properties changed
for (const key of ['startParagraphId', 'startParagraphOffset', 'endParagraphId', 'endParagraphOffset']) {
if (isNewHighlight || eval(key) !== oldHighlightInfo[key]) boundsChanges.push(key);
}
// Set variables that depend on the range
const temporaryHtmlElement = document.createElement('div');
temporaryHtmlElement.appendChild(highlightRange.cloneContents());
for (const hyperlink of temporaryHtmlElement.querySelectorAll('a')) hyperlink.setAttribute('onclick', 'event.preventDefault();');
rangeText = highlightRange.toString();
rangeHtml = temporaryHtmlElement.innerHTML;
let startParagraphIndex = annotatableParagraphIds.indexOf(startParagraphId);
let endParagraphIndex = annotatableParagraphIds.indexOf(endParagraphId);
if (startParagraphIndex === -1) startParagraphIndex = 0;
if (endParagraphIndex === -1) endParagraphIndex = annotatableParagraphIds.length - 1;
rangeParagraphIds = annotatableParagraphIds.slice(startParagraphIndex, endParagraphIndex + 1);
}
// If there are no valid changes, return
if (!highlightRange || highlightRange.toString() === '' || appearanceChanges.length + boundsChanges.length === 0) return;
// Update saved highlight info
const newHighlightInfo = {
highlightId: highlightId,
color: attributes?.color ?? oldHighlightInfo?.color ?? options.defaultColor,
style: attributes?.style ?? oldHighlightInfo?.style ?? options.defaultStyle,
wrapper: attributes?.wrapper ?? oldHighlightInfo?.wrapper ?? options.defaultWrapper,
wrapperVariables: attributes?.wrapperVariables ?? oldHighlightInfo?.wrapperVariables ?? {},
readOnly: attributes?.readOnly ?? oldHighlightInfo?.readOnly ?? false,
startParagraphId: startParagraphId ?? oldHighlightInfo?.startParagraphId,
startParagraphOffset: startParagraphOffset ?? oldHighlightInfo?.startParagraphOffset,
endParagraphId: endParagraphId ?? oldHighlightInfo?.endParagraphId,
endParagraphOffset: endParagraphOffset ?? oldHighlightInfo?.endParagraphOffset,
// Read-only properties
escapedHighlightId: CSS.escape(highlightId),
rangeText: rangeText ?? oldHighlightInfo?.rangeText,
rangeHtml: rangeHtml ?? oldHighlightInfo?.rangeHtml,
rangeParagraphIds: rangeParagraphIds ?? oldHighlightInfo?.rangeParagraphIds,
rangeObj: highlightRange ?? oldHighlightInfo?.rangeObj,
};
highlightsById[highlightId] = newHighlightInfo;
const detail = {
highlight: newHighlightInfo,
changes: appearanceChanges.concat(boundsChanges),
}
this.drawHighlights([highlightId]);
if (highlightId === activeHighlightId && appearanceChanges.length > 0) {
updateSelectionUi('appearance');
} else if (triggeredByUserAction && highlightId !== activeHighlightId) {
this.activateHighlight(highlightId);
}
if (isNewHighlight) {
this.annotatableContainer.dispatchEvent(new CustomEvent('hh:highlightcreate', { detail: detail }));
} else {
this.annotatableContainer.dispatchEvent(new CustomEvent('hh:highlightupdate', { detail: detail }));
}
}
// Activate a highlight by ID
this.activateHighlight = (highlightId) => {
const highlightToActivate = highlightsById[highlightId];
if (options.drawingMode === 'inserted-spans' || highlightToActivate.readOnly) {
// If the highlight is read-only, return events, but don't actually activate it
this.annotatableContainer.dispatchEvent(new CustomEvent('hh:highlightactivate', { detail: { highlight: highlightToActivate } }));
this.annotatableContainer.dispatchEvent(new CustomEvent('hh:highlightdeactivate', { detail: { highlight: highlightToActivate } }));
return;
}
const selection = window.getSelection();
const highlightRange = highlightToActivate.rangeObj.cloneRange();
activeHighlightId = highlightId;
updateSelectionUi('appearance');
if (selection.type !== 'Range') {
selection.removeAllRanges();
selection.addRange(highlightRange);
}
this.annotatableContainer.dispatchEvent(new CustomEvent('hh:highlightactivate', { detail: { highlight: highlightToActivate } }));
}
// Activate a link by position
let allowHyperlinkClick = false;
this.activateHyperlink = (position) => {
this.deactivateHighlights();
allowHyperlinkClick = true;
hyperlinksByPosition[position].hyperlinkElement.click();
allowHyperlinkClick = false;
}
// Deactivate any highlights that are currently active/selected
this.deactivateHighlights = (removeSelectionRanges = true) => {
const deactivatedHighlight = highlightsById[activeHighlightId];
activeHighlightId = null;
updateSelectionUi('appearance');
previousSelectionRange = null;
const selection = window.getSelection();
if (removeSelectionRanges && selection.anchorNode && this.annotatableContainer.contains(selection.anchorNode)) {
selection.removeAllRanges();
}
if (deactivatedHighlight) {
this.annotatableContainer.dispatchEvent(new CustomEvent('hh:highlightdeactivate', { detail: {
highlight: deactivatedHighlight,
}}));
}
}
// Remove the specified highlights, or all highlights on the page
this.removeHighlights = (highlightIds = Object.keys(highlightsById)) => {
this.deactivateHighlights();
for (const highlightId of highlightIds) {
const highlightInfo = highlightsById[highlightId];
if (highlightInfo) {
delete highlightsById[highlightId];
this.annotatableContainer.dispatchEvent(new CustomEvent('hh:highlightremove', { detail: {
highlightId: highlightId,
}}));
undrawHighlight(highlightInfo);
}
}
}
// Get the active highlight ID (if there is one)
this.getActiveHighlightId = () => {
return activeHighlightId;
}
// Get info for specified highlights, or all highlights on the page
this.getHighlightInfo = (highlightIds = Object.keys(highlightsById), paragraphId = null) => {
let filteredHighlights = []
for (highlightId of highlightIds) {
const highlightInfo = highlightsById[highlightId];
if (!paragraphId || paragraphId === highlightInfo.startParagraphId) {
filteredHighlights.push(highlightInfo);
}
}
// Sort highlights based on their order on the page
if (filteredHighlights.length > 0) {
filteredHighlights.sort((a, b) => {
return (annotatableParagraphIds.indexOf(a.startParagraphId) - annotatableParagraphIds.indexOf(b.startParagraphId)) || (a.startParagraphOffset - b.startParagraphOffset);
});
}
return filteredHighlights;
}
// Update one of the initialized options
this.setOption = (key, value) => {
const containerSelector = options.containerSelector;
options[key] = value ?? options[key];
if (key === 'drawingMode' || key === 'styles') {
updateAppearanceStylesheet();
if (supportsHighlightApi) CSS.highlights.clear();
this.drawHighlights();
} else if (key === 'colors') {
updateAppearanceStylesheet();
} else if (key === 'containerSelector' || key === 'paragraphSelector') {
initializeHighlighter(containerSelector);
}
}
// Get all of the initialized options
this.getOptions = () => {
return options;
}
// Remove this Highlighter instance and its highlights
this.removeHighlighter = () => {
generalStylesheet.replaceSync('');
appearanceStylesheet.replaceSync('');
highlightApiStylesheet.replaceSync('');
selectionStylesheet.replaceSync('');
this.loadHighlights([]);
this.annotatableContainer.querySelectorAll('.hh-svg-background, .hh-selection-handle').forEach(el => el.remove())
controller.abort();
this.annotatableContainer.highlighter = undefined;
hhHighlighters = hhHighlighters.filter(hhHighlighter => hhHighlighter.annotatableContainer !== this.annotatableContainer);
delete hhHighlighters[options.containerSelector];
}
// -------- EVENT LISTENERS --------
// Selection change in document (new selection, change in selection range, or selection collapsing to a caret)
document.addEventListener('selectionchange', (event) => respondToSelectionChange(event), { signal: controller.signal });
const respondToSelectionChange = (event) => {
const selection = getRestoredSelectionOrCaret(window.getSelection());
const selectionRange = selection.type === 'None' ? null : selection.getRangeAt(0);
// Deactivate highlights when tapping or creating a selection outside of the previous selection range
if (!activeSelectionHandle && selectionRange && previousSelectionRange && (selection.type === 'Caret' || previousSelectionRange.comparePoint(selectionRange.startContainer, selectionRange.startOffset) === 1 || previousSelectionRange.comparePoint(selectionRange.endContainer, selectionRange.endOffset) === -1)) {
this.deactivateHighlights(false);
}
if (selection.type === 'Range') {
// Clear tap result (prevents hh:tap event from being sent when long-pressing or dragging to select text)
tapResult = null;
if (this.annotatableContainer.contains(selection.anchorNode)) {
if (activeHighlightId || (options.pointerMode === 'live' || (options.pointerMode === 'auto' && isStylus === true))) {
this.createOrUpdateHighlight({ highlightId: activeHighlightId, });
}
previousSelectionRange = selectionRange.cloneRange();
}
}
updateSelectionUi('bounds');
}
// Pointer down in annotatable container
this.annotatableContainer.addEventListener('pointerdown', (event) => respondToPointerDown(event), { signal: controller.signal });
const respondToPointerDown = (event) => {
isStylus = event.pointerType === 'pen';
// User is dragging a selection handle
if (event.target && event.target.parentElement.classList.contains('hh-selection-handle')) {
event.preventDefault();
activeSelectionHandle = event.target.parentElement;
this.annotatableContainer.addEventListener('pointermove', respondToSelectionHandleDrag, { signal: controller.signal });
}
// Return if it's not a regular click, or if the user is tapping away from an existing selection
if (previousSelectionRange || activeSelectionHandle || event.button !== 0 || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
// Trigger a long-press event if the user doesn't lift their finger within the specified time
if (options.longPressTimeout) longPressTimeoutId = setTimeout(() => respondToLongPress(event), options.longPressTimeout);
const tapRange = getRangeFromTapEvent(event);
tapResult = checkForTapTargets(tapRange);
}
// Selection handle drag (this function is added as an event listener on pointerdown, and removed on pointerup)
const respondToSelectionHandleDrag = (event) => {
const selection = window.getSelection();
const selectionRange = selection.getRangeAt(0);
const dragRange = getRangeFromTapEvent(event);
// TODO: While dragging, the selection startContainer or endContainer frequently gets set to the parent element. This causes the selection to flicker while dragging. The line below is a workaround, but it would be nice to figure out the root cause.
if (dragRange.startContainer.nodeType !== Node.TEXT_NODE || dragRange.endContainer.nodeType !== Node.TEXT_NODE) return;
const dragPositionRelativeToSelectionStart = dragRange.compareBoundaryPoints(Range.START_TO_START, selectionRange);
const dragPositionRelativeToSelectionEnd = dragRange.compareBoundaryPoints(Range.END_TO_END, selectionRange);
// TODO: Don't allow Caret (0-width) selections while dragging selection handles
if (activeSelectionHandle.dataset.position === 'left' && dragPositionRelativeToSelectionEnd === 1 || activeSelectionHandle.dataset.position === 'right' && dragPositionRelativeToSelectionStart === -1) {
for (const selectionHandle of selectionHandles) {
selectionHandle.dataset.position = selectionHandle.dataset.position === 'left' ? 'right' : 'left';
}
// TODO: Switch selection direction and don't deactivate the highlight
this.deactivateHighlights();
activeSelectionHandle = null;
this.annotatableContainer.removeEventListener('pointermove', respondToSelectionHandleDrag);
} else if (activeSelectionHandle.dataset.position === 'left' && dragPositionRelativeToSelectionStart !== 0) {
// Left selection handle is before or after the selection start
selectionRange.setStart(dragRange.startContainer, dragRange.startOffset);
} else if (activeSelectionHandle.dataset.position === 'right' && dragPositionRelativeToSelectionEnd !== 0) {
// Right selection handle is before or after the selection end
selectionRange.setEnd(dragRange.endContainer, dragRange.endOffset);
}
}
// Long press in annotatable container (triggered by setTimeout() in pointerdown event)
const respondToLongPress = (event) => {
respondToPointerUp(event, isLongPress = true);
tapResult = null;
}
// Pointer up in annotatable container
this.annotatableContainer.addEventListener('pointerup', (event) => respondToPointerUp(event), { signal: controller.signal });
const respondToPointerUp = (event, isLongPress = false) => {
if (tapResult) {
tapResult.pointerEvent = event;
tapResult.isLongPress = isLongPress;
this.annotatableContainer.dispatchEvent(new CustomEvent('hh:tap', { detail: tapResult, }));
if (options.autoTapToActivate && tapResult?.targetFound) {
if (tapResult.highlights.length === 1 && tapResult.hyperlinks.length === 0 && !isLongPress) {
return this.activateHighlight(tapResult.highlights[0].highlightId);
} else if (tapResult.highlights.length === 0 && tapResult.hyperlinks.length === 1 && !isLongPress) {
return this.activateHyperlink(tapResult.hyperlinks[0].position);
} else if (tapResult.highlights.length + tapResult.hyperlinks.length > 1) {
return this.annotatableContainer.dispatchEvent(new CustomEvent('hh:ambiguousaction', { detail: tapResult, }));
}
}
}
}
// Pointer up or cancel in window
window.addEventListener('pointerup', (event) => respondToWindowPointerUp(event), { signal: controller.signal });
window.addEventListener('pointercancel', (event) => respondToWindowPointerUp(event), { signal: controller.signal });
const respondToWindowPointerUp = (event) => {
const selection = window.getSelection();
if (selection.type === 'Range' && this.annotatableContainer.contains(selection.anchorNode)) {
const adjustedSelectionRange = snapRangeToBoundaries(selection.getRangeAt(0), selection.anchorNode);
selection.removeAllRanges();
selection.addRange(adjustedSelectionRange);
}
tapResult = null;
clearTimeout(longPressTimeoutId);
if (activeSelectionHandle) {
activeSelectionHandle = null;
this.annotatableContainer.removeEventListener('pointermove', respondToSelectionHandleDrag);
}
}
// Hyperlink click (for each hyperlink in annotatable container)
for (const hyperlinkElement of hyperlinkElements) {
hyperlinkElement.addEventListener('click', (event) => {
this.deactivateHighlights();
if (!allowHyperlinkClick) event.preventDefault();
}, { signal: controller.signal });
}
// Window resize
let previousWindowWidth = window.innerWidth;
const respondToWindowResize = () => {
// Only respond if the width changed (ignore height changes)
if (window.innerWidth === previousWindowWidth) return;
if (options.drawingMode === 'svg') {
this.drawHighlights();
if (previousSelectionRange) updateSelectionUi('bounds');
}
previousWindowWidth = window.innerWidth;
}
const debouncedRespondToWindowResize = debounce(() => respondToWindowResize(), Math.floor(Object.keys(highlightsById).length / 20));
window.addEventListener('resize', debouncedRespondToWindowResize, { signal: controller.signal });
// -------- UTILITY FUNCTIONS --------
// Check if the tap is in the range of an existing highlight or link
const checkForTapTargets = (tapRange) => {
if (!tapRange) return;
// Check for tapped highlights and hyperlinks
const tappedHighlights = [];
for (const highlightId of Object.keys(highlightsById)) {
const highlightInfo = highlightsById[highlightId];
const highlightRange = highlightInfo.rangeObj;
if (highlightRange.comparePoint(tapRange.startContainer, tapRange.startOffset) === 0) {
tappedHighlights.push(highlightInfo);
}
}
const tappedHyperlinks = [];
for (const hyperlinkPosition of Object.keys(hyperlinksByPosition)) {
const hyperlinkInfo = hyperlinksByPosition[hyperlinkPosition];
const hyperlinkRange = document.createRange()
hyperlinkRange.selectNodeContents(hyperlinkInfo.hyperlinkElement);
if (hyperlinkRange.comparePoint(tapRange.startContainer, tapRange.startOffset) === 0) {
tappedHyperlinks.push(hyperlinkInfo);
}
}
// Sort highlights (hyperlinks should already be sorted)
const tappedHyperlinkIds = [];
for (const highlightInfo of tappedHighlights) tappedHyperlinkIds.push(highlightInfo.highlightId);
const sortedTappedHighlights = this.getHighlightInfo(tappedHyperlinkIds);
return {
'targetFound': sortedTappedHighlights.length > 0 || tappedHyperlinks.length > 0,
'tapRange': tapRange,
'highlights': sortedTappedHighlights,
'hyperlinks': tappedHyperlinks,
}
}
// Compare new highlight information to old highlight information, returning an object with the properties that changed
const diffHighlight = (newHighlightInfo, oldHighlightInfo) => {
if (!oldHighlightInfo) return newHighlightInfo;
const changedHighlightInfo = {}
for (const key of Object.keys(newHighlightInfo)) {
if (oldHighlightInfo.hasOwnProperty(key) && oldHighlightInfo[key] !== newHighlightInfo[key]) {
changedHighlightInfo[key] = newHighlightInfo[key];
}
}
return changedHighlightInfo;
}
// Undraw the specified highlight
const undrawHighlight = (highlightInfo) => {
const highlightId = highlightInfo.highlightId;
// Remove HTML and SVG elements
if (document.querySelector('[data-highlight-id]')) {
this.annotatableContainer.querySelectorAll(`[data-highlight-id="${highlightId}"]`).forEach(element => {
if (element.hasAttribute('data-read-only')) {
element.outerHTML = element.innerHTML;
} else {
element.remove();
}
});
const rangeParagraphs = this.annotatableContainer.querySelectorAll(`#${highlightInfo.rangeParagraphIds.join(', #')}`);
rangeParagraphs.forEach(p => { p.normalize(); });
getCorrectedRangeObj(highlightId);
}
// Remove Highlight API highlights
if (supportsHighlightApi && CSS.highlights.has(highlightId)) {
const ruleIndexesToDelete = [];
for (let r = 0; r < highlightApiStylesheet.cssRules.length; r++) {
if (highlightApiStylesheet.cssRules[r].selectorText.includes(`::highlight(${highlightInfo.escapedHighlightId})`)) ruleIndexesToDelete.push(r);
}
for (const index of ruleIndexesToDelete.reverse()) highlightApiStylesheet.deleteRule(index);
CSS.highlights.delete(highlightId);
}
}
// Update selection background and handles
const updateSelectionUi = (changeType = 'appearance') => {
const selection = window.getSelection();
const selectionRange = selection.type === 'None' ? null : selection.getRangeAt(0);
if (selection.anchorNode && !this.annotatableContainer.contains(selection.anchorNode)) return;
const color = highlightsById[activeHighlightId]?.color;
const colorString = options.colors[color] ?? 'AccentColor';
const style = highlightsById[activeHighlightId]?.style;
// Update SVG shapes for the active highlight (bring shape group to front, and duplicate it to make the highlight darker)
svgActiveOverlay.innerHTML = '';
if (activeHighlightId && options.drawingMode === 'svg') {
const svgHighlight = svgBackground.querySelector(`g[data-highlight-id="${activeHighlightId}"]`);
svgActiveOverlay.dataset.color = color;
svgActiveOverlay.dataset.style = style;
svgActiveOverlay.innerHTML = svgHighlight.innerHTML;
svgBackground.appendChild(svgHighlight);
svgBackground.appendChild(svgActiveOverlay);
}
if (changeType === 'appearance') {
this.annotatableContainer.style = `--hh-color: ${colorString}`;
// Update selection background
if (activeHighlightId && options.drawingMode === 'svg') {
selectionStylesheet.replaceSync(`${options.containerSelector} ::selection { background-color: transparent; }`);
} else if (activeHighlightId) {
const styleTemplate = getStyleTemplate(style, 'css', null);
selectionStylesheet.replaceSync(`
${options.containerSelector} ::selection { ${styleTemplate} }
${options.containerSelector} rt::selection, ${options.containerSelector} img::selection { background-color: transparent; }
`);
} else {
selectionStylesheet.replaceSync(`
${options.containerSelector} ::selection { background-color: Highlight; color: HighlightText; }
${options.containerSelector} rt::selection, ${options.containerSelector} img::selection { background-color: transparent; }
`);
}
// Update selection handles
if (options.showSelectionHandles) {
selectionHandles[0].children[1].innerHTML = (options.selectionHandles.left ?? '');
selectionHandles[1].children[1].innerHTML = (options.selectionHandles.right ?? '');
}
// Send event
this.annotatableContainer.dispatchEvent(new CustomEvent('hh:selectionupdate', { detail: { color: color, style: style, }}));
} else if (changeType === 'bounds') {
// Update selection handle location and visibility
if (selection.type === 'Range' && options.showSelectionHandles) {
const selectionRangeRects = selectionRange.getClientRects();
const startRect = selectionRangeRects[0];
const endRect = selectionRangeRects[selectionRangeRects.length-1];
const annotatableContainerClientRect = this.annotatableContainer.getBoundingClientRect();
selectionHandles[0].dataset.position = 'left';
selectionHandles[0].style.display = 'block';
selectionHandles[0].style.height = startRect.height + 'px';
selectionHandles[0].style.left = startRect.left - annotatableContainerClientRect.left + 'px';
selectionHandles[0].style.top = startRect.top - annotatableContainerClientRect.top + 'px';
selectionHandles[1].dataset.position = 'right';
selectionHandles[1].style.display = 'block';
selectionHandles[1].style.height = endRect.height + 'px';
selectionHandles[1].style.left = endRect.right - annotatableContainerClientRect.left + 'px';
selectionHandles[1].style.top = endRect.top - annotatableContainerClientRect.top + 'px';
} else {
selectionHandles[0].style.display = 'none';
selectionHandles[1].style.display = 'none';
}
}
}
// Update the selection or highlight range to stay within the annotatable container
const snapRangeToBoundaries = (range, anchorNode = null) => {
let startNode = range.startContainer;
let endNode = range.endContainer;
let startOffset = range.startOffset;
let endOffset = range.endOffset;
// Prevent the range from going outside of the annotatable container
if (!this.annotatableContainer.contains(range.commonAncestorContainer)) {
if (anchorNode && !this.annotatableContainer.contains(anchorNode)) {
// Range is from a selection, and the selection anchor is outside of the container
window.getSelection().collapseToStart();
return window.getSelection().getRangeAt(0).cloneRange();
} else if (anchorNode === startNode || this.annotatableContainer.contains(startNode)) {
// Range starts in the container but ends outside
const lastParagraphTextNodeWalker = document.createTreeWalker(this.annotatableParagraphs[this.annotatableParagraphs.length - 1], NodeFilter.SHOW_TEXT);
let nextNode;
while (nextNode = lastParagraphTextNodeWalker.nextNode());
endNode = lastParagraphTextNodeWalker.previousNode();
endOffset = endNode.length;
} else if (anchorNode === endNode || this.annotatableContainer.contains(endNode)) {
// Range starts outside of the container but ends inside
const firstParagraphTextNodeWalker = document.createTreeWalker(this.annotatableParagraphs[0], NodeFilter.SHOW_TEXT);
startNode = firstParagraphTextNodeWalker.nextNode();
startOffset = 0;
}
}
// Snap to the nearest word
if (options.snapToWord) {
// 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.
if (startOffset === startNode.textContent.length) {
let parentElement = range.commonAncestorContainer;
let walker = document.createTreeWalker(parentElement, NodeFilter.SHOW_TEXT);
let nextTextNode = walker.nextNode();
while (nextTextNode !== startNode) nextTextNode = walker.nextNode();
nextTextNode = walker.nextNode();
if (nextTextNode) {
startNode = nextTextNode;
startOffset = 0;
}
}
// Trim whitespace and dashes at range start and end
while (/\s|\p{Pd}/u.test(startOffset < startNode.textContent.length && startNode.textContent[startOffset])) startOffset += 1;
while (endOffset - 1 >= 0 && /\s|\p{Pd}/u.test(endNode.textContent[endOffset - 1])) endOffset -= 1;
// Expand range to word boundaries
while (startOffset > 0 && /[^\s|\p{Pd}]/u.test(startNode.textContent[startOffset - 1])) startOffset -= 1;
while (endOffset + 1 <= endNode.textContent.length && /[^\s|\p{Pd}]/u.test(endNode.textContent[endOffset])) endOffset += 1;
}
let newRange = document.createRange();
newRange.setStart(startNode, startOffset);
newRange.setEnd(endNode, endOffset);
return newRange;
}
// Get the character offset relative to the annotatable paragraph
// Adapted from https://stackoverflow.com/a/4812022/1349044
const getParagraphOffset = (referenceTextNode, referenceTextNodeOffset) => {
const paragraph = referenceTextNode.parentElement.closest(options.paragraphSelector);
const referenceRange = document.createRange();
referenceRange.selectNodeContents(paragraph);
referenceRange.setEnd(referenceTextNode, referenceTextNodeOffset);
const paragraphOffset = referenceRange.toString().length;
return [ paragraph.id, paragraphOffset ];
}
// Get the character offset relative to the deepest relevant text node
const getTextNodeAndOffset = (parentElement, targetOffset) => {
let textNode, firstTextNode, currentOffset = 0;
const walker = document.createTreeWalker(parentElement, NodeFilter.SHOW_TEXT);
while (textNode = walker.nextNode()) {
if (!firstTextNode) firstTextNode = walker.currentNode;
currentOffset += textNode.textContent.length;
if (currentOffset >= targetOffset) {
const relativeOffset = textNode.textContent.length - currentOffset + targetOffset
return [ textNode, relativeOffset ];
}
}
// TODO: Direction isn't always accurate (maybe it resets when selection is cleared and set to a new range programmatically?)
const direction = window.getSelection().direction;
if (direction == 'backward') {
return [ firstTextNode, 0 ];
} else {
const lastTextNode = walker.previousNode();
return [ lastTextNode, lastTextNode.textContent.length ];
}
}
// Update appearance stylesheet (user-defined colors and styles)
const updateAppearanceStylesheet = () => {
appearanceStylesheet.replaceSync('');
for (const color of Object.keys(options.colors)) {
appearanceStylesheet.insertRule(`[data-color="${color}"] { --hh-color: ${options.colors[color]}; }`);
}
for (const style of Object.keys(options.styles)) {
const styleTemplate = getStyleTemplate(style, 'css', null);
appearanceStylesheet.insertRule(`span[data-highlight-id][data-style="${style}"] { ${styleTemplate} }`);
}
}
// Get style template for a given highlight style
const getStyleTemplate = (style, type, clientRect) => {
style = options.styles.hasOwnProperty(style) ? style : options.defaultStyle;
let styleTemplate = options.styles[style]?.[type] ?? '';
if (!styleTemplate) {
console.warn(`Highlight style "${style}" in options does not have a defined "${type}" value.`);
return;
}
if (type === 'svg' && clientRect) {
const annotatableContainerClientRect = this.annotatableContainer.getBoundingClientRect();
styleTemplate = styleTemplate
.replaceAll('{x}', clientRect.x - annotatableContainerClientRect.x)
.replaceAll('{y}', clientRect.y - annotatableContainerClientRect.y)
.replaceAll('{width}', clientRect.width)
.replaceAll('{height}', clientRect.height)
.replaceAll('{top}', clientRect.top - annotatableContainerClientRect.top)
.replaceAll('{right}', clientRect.right - annotatableContainerClientRect.right)
.replaceAll('{bottom}', clientRect.bottom - annotatableContainerClientRect.bottom)
.replaceAll('{left}', clientRect.left - annotatableContainerClientRect.left);
}
return styleTemplate;
}
// Restore the previous selection range in case the browser clears the selection
const getRestoredSelectionOrCaret = (selection, pointerEvent = null) => {
if (selection.type === 'None') {
if (previousSelectionRange) {
// iOS Safari deselects text when a button is tapped. This restores the selection.
selection.addRange(previousSelectionRange);
} else if (pointerEvent) {
// 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.
let range = getRangeFromTapEvent(pointerEvent);
selection.addRange(range);
}
}
return selection;
}
// Fix highlight range if the DOM changed and made the previous highlight range invalid
const getCorrectedRangeObj = (highlightId) => {
const highlightInfo = highlightsById[highlightId];