-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathhighlighter.js
More file actions
622 lines (532 loc) · 22.7 KB
/
Copy pathhighlighter.js
File metadata and controls
622 lines (532 loc) · 22.7 KB
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
'use strict';
/**
* Create the Content Highlighter namespace. This component is injected into
* the page and is used to highlight occurrences of a regex in the page.
* */
Find.register('Content.Highlighter', function(self) {
const indexHighlight = 'find-ext-index-highlight';
const allHighlight = 'find-ext-all-highlight';
let scrollbarMaker = null;
/**
* Highlight all occurrences of a regex in the page, using an occurrence map and regex.
*
* @private
* @param {object} occurrenceMap - The occurrence map
* @param {string} regex - The regular expression
* @param {object} options - The search and highlight options
* */
self.highlightAll = function(occurrenceMap, regex, options) {
if (options && options.scroll_markers) {
scrollbarMaker?.destroy();
scrollbarMaker = new ScrollbarHighlightMaker(options);
}
const tags = {
occIndex: null,
maxIndex: null,
openingMarkup: '',
closingMarkup: '',
update: function (index) {
if (this.occIndex !== index) {
this.occIndex = index;
//If reached max number of occurrences to show, don't highlight text
if (this.maxIndex == null || this.occIndex <= this.maxIndex) {
let style = 'all: unset; background-color: ' + options.all_highlight_color.hexColor + '; color: black;';
let classList = 'find-ext-occr' + index + ' ' + allHighlight;
this.openingMarkup = '<span style="' + style + '" class="' + classList + '">';
this.closingMarkup = '</span>';
} else {
this.openingMarkup = '';
this.closingMarkup = '';
}
}
}
};
if (options && options.max_results !== 0) {
tags.maxIndex = options.max_results - 1;
} else {
tags.maxIndex = null;
}
regex = regex.replace(/ /g, '\\s');
if (!options || options.match_case) {
regex = new RegExp(regex, 'm');
} else {
regex = new RegExp(regex, 'mi');
}
//Iterate each text group
let occIndex = 0;
for (let index = 0; index < occurrenceMap.groups; index++) {
let uuids = occurrenceMap[index].uuids;
let groupText = '';
let charMap = {};
let charIndexMap = [];
//Build groupText, charMap and charIndexMap
let count = 0;
for (let uuidIndex = 0; uuidIndex < uuids.length; uuidIndex++) {
let el = document.getElementById(uuids[uuidIndex]);
let text = el.childNodes[0].nodeValue;
if (!text) {
continue;
}
text = decode(text);
groupText += text;
for (let stringIndex = 0; stringIndex < text.length; stringIndex++) {
charIndexMap.push(count);
charMap[count++] = {
char: text.charAt(stringIndex),
nodeUUID: uuids[uuidIndex],
nodeIndex: stringIndex,
ignorable: false,
matched: false,
boundary: false
};
}
}
charMap.length = count;
//Format text nodes (whitespaces) whilst keeping references to their nodes in the DOM, updating charMap ignorable characters
if (!occurrenceMap[index].preformatted) {
let info;
//Replace all whitespace characters (\t \n\r) with the space character
while (info = /[\t\n\r]/.exec(groupText)) {
charMap[charIndexMap[info.index]].ignorable = true;
groupText = groupText.replace(/[\t\n\r]/, ' ');
}
//Truncate consecutive whitespaces
while (info = / {2,}/.exec(groupText)) {
let len = info[0].length;
let offset = info.index;
for (let currIndex = 0; currIndex < len; currIndex++) {
charMap[charIndexMap[offset + currIndex]].ignorable = true;
}
for (let currIndex = 0; currIndex < len - 1; currIndex++) {
charIndexMap.splice(offset, 1);
}
groupText = groupText.replace(/ {2,}/, ' ');
}
//Collapse leading or trailing whitespaces
while (info = /^ | $/.exec(groupText)) {
let len = info[0].length;
let offset = info.index;
for (let currIndex = 0; currIndex < len; currIndex++) {
charMap[charIndexMap[offset + currIndex]].ignorable = true;
}
for (let currIndex = 0; currIndex < len; currIndex++) {
charIndexMap.splice(offset, 1);
}
groupText = groupText.replace(/^ | $/, '');
}
}
//Perform complex regex search, updating charMap matched characters
let info;
while (info = regex.exec(groupText)) {
let len = info[0].length;
let offset = info.index;
if (len === 0) {
break;
}
let first = charIndexMap[offset];
let last = charIndexMap[offset + len - 1];
for (let currIndex = first; currIndex <= last; currIndex++) {
charMap[currIndex].matched = true;
if (currIndex === last) {
charMap[currIndex].boundary = true;
}
}
for (let currIndex = 0; currIndex < offset + len; currIndex++) {
charIndexMap.splice(0, 1);
}
groupText = groupText.substring(offset + len);
}
//Wrap matched characters in an element with class indexHighlight and occurrenceIdentifier
let matchGroup = {text: '', groupUUID: charMap[0].nodeUUID};
let inMatch = false;
for (let key = 0; key < charMap.length; key++) {
tags.update(occIndex);
//If Transitioning Into New Text Group
if (matchGroup.groupUUID !== charMap[key].nodeUUID) {
if (inMatch) {
matchGroup.text += tags.closingMarkup;
}
document.getElementById(matchGroup.groupUUID).innerHTML = matchGroup.text;
matchGroup.text = '';
matchGroup.groupUUID = charMap[key].nodeUUID;
if (inMatch) {
matchGroup.text += tags.openingMarkup;
}
}
//If Current Character is Matched
if (charMap[key].matched) {
if (!inMatch) {
inMatch = charMap[key].matched;
matchGroup.text += tags.openingMarkup;
}
if (options && options.scroll_markers) {
scrollbarMaker.addOccurrence(occIndex, document.getElementById(matchGroup.groupUUID));
}
} else {
if (inMatch) {
inMatch = charMap[key].matched;
matchGroup.text += tags.closingMarkup;
if (key < charMap.length) {
occIndex++;
}
}
}
matchGroup.text += encode(charMap[key].char);
if (charMap[key].boundary) {
inMatch = false;
matchGroup.text += tags.closingMarkup;
if (key < charMap.length) {
occIndex++;
}
}
//If End of Map Reached
if (key === charMap.length - 1) {
if (inMatch) {
matchGroup.text += tags.closingMarkup;
occIndex++;
}
document.getElementById(matchGroup.groupUUID).innerHTML = matchGroup.text;
}
}
}
// Collect occurrence IDs from highlight spans
if (options && options.scroll_markers) {
scrollbarMaker.mount();
scrollbarMaker.createMarkers();
}
};
/**
* Seek the search to the given index.
*
* @private
* @param {number} index - The index to seek to
* @param {object} options - The search options
* */
self.seekHighlight = function(index, options) {
if (index === null || options == null) {
return;
}
let previousIndex = Array.from(document.querySelectorAll('.' + indexHighlight));
if (previousIndex && previousIndex.length) {
for (let elsIndex = 0; elsIndex < previousIndex.length; elsIndex++) {
let style = 'all: unset; background-color: ' + options.all_highlight_color.hexColor + '; color: black;';
previousIndex[elsIndex].classList.remove(indexHighlight);
previousIndex[elsIndex].setAttribute("style", style);
}
}
let els = Array.from(document.querySelectorAll('.find-ext-occr' + index));
if (els == null || els.length === 0) {
return;
}
for (let elsIndex = 0; elsIndex < els.length; elsIndex++) {
let style = 'all: unset; background-color: ' + options.index_highlight_color.hexColor + '; color: black;';
els[elsIndex].classList.add(indexHighlight);
els[elsIndex].setAttribute("style", style);
}
// only scroll if the element is not in the current viewport
if (!isElementInViewport(els[0])) {
els[0].scrollIntoView(true);
let docHeight = Math.max(document.documentElement.clientHeight, document.documentElement.offsetHeight, document.documentElement.scrollHeight);
let bottomScrollPos = window.pageYOffset + window.innerHeight;
if (bottomScrollPos + 100 < docHeight) {
window.scrollBy(0, -100);
}
}
if (options && options.scroll_markers) {
scrollbarMaker.setActive(index);
}
};
/**
* Replace a given occurrence of a regex with a given string.
*
* @private
* @param {number} index - The index of the occurrence that will be replaced
* @param {string} replaceWith - The text that will replace the given occurrence of the regex
* */
self.replace = function(index, replaceWith) {
let els = Array.from(document.querySelectorAll('.find-ext-occr' + index));
if (els.length === 0) {
return;
}
els.shift().innerText = replaceWith;
for (let elsIndex = 0; elsIndex < els.length; elsIndex++) {
els[elsIndex].innerText = '';
}
};
/**
* Replace all occurrences of a regex with a given string.
*
* @private
* @param {string} replaceWith - The text that will replace all occurrences of the regex
* */
self.replaceAll = function(replaceWith) {
let els = Array.from(document.querySelectorAll("[class*='find-ext-occr']"));
let currentOccurrence = null;
for (let index = 0; index < els.length; index++) {
let el = els[index];
let occrClassName = el.getAttribute('class').match(/find-ext-occr\d*/)[0];
let occurrenceFromClass = parseInt(occrClassName.replace('find-ext-occr', ''));
if (occurrenceFromClass !== currentOccurrence) {
currentOccurrence = occurrenceFromClass;
el.innerText = replaceWith
} else {
el.innerText = '';
}
}
};
/**
* Follow the link that is currently highlighted.
*
* @private
* */
self.followLinkUnderFocus = function() {
let els = document.getElementsByClassName(indexHighlight);
for (let index = 0; index < els.length; index++) {
let el = els[index];
while (el.parentElement) {
el = el.parentElement;
if (el.tagName.toLowerCase() === 'a') {
return el.click();
}
}
}
};
/**
* Restore the page by removing any highlighting markup.
*
* @private
* */
self.restore = function() {
scrollbarMaker?.destroy();
scrollbarMaker = null;
let classes = [indexHighlight, allHighlight];
for (let classIndex = 0; classIndex < classes.length; classIndex++) {
let els = Array.from(document.querySelectorAll('.' + classes[classIndex]));
for (let elsIndex = 0; elsIndex < els.length; elsIndex++) {
let el = els[elsIndex];
let parent = el.parentElement;
while (el.firstChild) {
parent.insertBefore(el.firstChild, el);
}
parent.removeChild(el);
parent.normalize();
}
}
};
class ScrollbarHighlightMaker {
scrollbarWidth = (function () {
const w = window.innerWidth - document.documentElement.clientWidth;
// Using OS-native overlay scrollbars produces w=0 here
return w > 0 ? w : 13;
})();
constructor(options) {
this.options = options;
this.globalStyle = null;
this.overlay = null;
this.track = null;
this.thumb = null;
this.markerContainer = null;
this.currentScrollY = 0;
this.docInvisibleHeight = 0;
this.scrollListener = null;
this.occTopPositionMap = new Map();
}
addComponents() {
// Suppress the native scrollbar
this.globalStyle = document.head.appendChild(document.createElement('style'));
this.globalStyle.textContent =
'::-webkit-scrollbar { width: 0px !important; height: 0px !important; }' +
'html { scrollbar-width: none !important; }';
this.overlay = document.body.appendChild(document.createElement('div'));
const shadowRoot = this.overlay.attachShadow({mode: 'open'});
shadowRoot.appendChild(document.createElement('style')).textContent = `
#find-ext-scrollbar-track {
position: fixed;
top: 0;
right: 0;
width: ${this.scrollbarWidth}px;
height: 100vh;
z-index: 2147483647;
pointer-events: auto;
background: #f1f1f1;
box-sizing: border-box;
overflow: hidden;
}
@media (prefers-color-scheme: dark) {
#find-ext-scrollbar-track {
background: #2b2b2b;
}
}
#find-ext-scroll-thumb {
position: absolute;
right: 0;
width: 100%;
min-height: 30px;
background: #aaaaaa;
border-radius: 3px;
cursor: pointer;
box-sizing: border-box;
transition: background 0.15s;
}
@media (prefers-color-scheme: dark) {
#find-ext-scroll-thumb {
background: #6b6b6b;
}
}
#find-ext-scroll-thumb:hover {
background: #888888;
}
[id^="find-ext-marker-"] {
display: block;
position: absolute;
left: 0;
right: 0;
width: 100%;
height: 4px;
min-height: 4px;
background-color: ${this.options.all_highlight_color.hexColor};
opacity: 0.85;
z-index: 2;
box-sizing: border-box;
pointer-events: none;
margin: 0;
padding: 0;
border: none;
border-radius: 1px;
}
[id^="find-ext-marker-"].index_highlight {
background-color: ${this.options.index_highlight_color.hexColor};
z-index: 3;
}
`;
// Scroll track, sits exactly where the native scrollbar was
this.track = shadowRoot.appendChild(document.createElement('div'));
this.track.id = 'find-ext-scrollbar-track';
// Scroll thumb
this.thumb = this.track.appendChild(document.createElement('div'));
this.thumb.id = 'find-ext-scroll-thumb';
// Highlight markers
this.markerContainer = this.track.appendChild(document.createElement('div'));
}
updateThumb() {
const scrollElement = document.scrollingElement;
const docHeight = scrollElement.scrollHeight;
const viewHeight = window.innerHeight;
if (docHeight <= viewHeight) {
this.thumb.style.display = 'none';
return;
}
this.thumb.style.display = 'block';
const thumbHeight = Math.max(30, (viewHeight / docHeight) * viewHeight);
const maxThumbTop = viewHeight - thumbHeight;
this.currentScrollY = window.scrollY || scrollElement.scrollTop;
this.docInvisibleHeight = docHeight - viewHeight;
const scrollRatio = this.currentScrollY / this.docInvisibleHeight;
this.thumb.style.height = thumbHeight + 'px';
this.thumb.style.top = Math.min(maxThumbTop, scrollRatio * maxThumbTop) + 'px';
}
bindScroll() {
// Throttle down here
// Do not use "requestAnimationFrame()", see MDN document for "scroll event"
this.ticking = false;
this.scrollListener = () => {
if (!this.ticking) {
this.ticking = true;
setTimeout(() => {
this.updateThumb();
this.ticking = false;
}, (1000 / 60) /* 60 FPS */);
}
};
window.addEventListener('scroll', this.scrollListener);
}
bindTrackClick() {
// Click on track to jump
this.track.addEventListener('click', (e) => {
if (e.target === this.thumb) return;
const ratio = (e.clientY - this.track.clientTop) / this.track.clientHeight;
const targetY = ratio * this.docInvisibleHeight;
window.scrollTo({ top: targetY, behavior: 'smooth' });
});
}
bindThumbDrag() {
this.thumb.addEventListener('mousedown', (e) => {
e.preventDefault();
const dragStartScrollY = this.currentScrollY;
const dragStartY = e.clientY;
const onMove = (e) => {
const ratio = (e.clientY - dragStartY) / (this.track.clientHeight - this.thumb.clientHeight /* exclude the thumb itself */);
const targetY = dragStartScrollY + ratio * this.docInvisibleHeight;
window.scrollTo(0, targetY);
};
const onUp = function () {
document.removeEventListener('mousemove', onMove);
document.removeEventListener('mouseup', onUp);
};
document.addEventListener('mousemove', onMove);
document.addEventListener('mouseup', onUp);
});
}
/**
* @private
* */
calculateMarkerPosition(el) {
const clientRect = el.getBoundingClientRect();
const docHeight = document.scrollingElement.scrollHeight;
const elementAbsoluteTop = window.scrollY + clientRect.top + (0.5 * clientRect.height);
const proportion = elementAbsoluteTop / docHeight;
const markerTop = proportion * window.innerHeight;
return Math.max(0, Math.min(window.innerHeight - 4, markerTop));
}
createMarker(occurrenceId, topPosition) {
const container = document.createDocumentFragment();
const marker = container.appendChild(document.createElement('div'));
marker.id = 'find-ext-marker-' + occurrenceId;
marker.style.top = topPosition + 'px';
return container;
}
setActive(occIndex) {
const markers = this.markerContainer.children;
Array.from(markers).forEach((el, index) => {
el.className = index === occIndex ? 'index_highlight' : '';
});
}
destroy() {
window.removeEventListener('scroll', this.scrollListener);
// Other event listeners will be removed by GC
this.overlay?.parentNode?.removeChild(this.overlay);
this.globalStyle?.parentNode?.removeChild(this.globalStyle);
}
createMarkers() {
this.occTopPositionMap.forEach((markerTop, occIndex) => {
this.markerContainer.appendChild(this.createMarker(occIndex, markerTop));
});
}
addOccurrence(occIndex, el) {
if (!this.occTopPositionMap.has(occIndex)) {
const markerTop = this.calculateMarkerPosition(el);
this.occTopPositionMap.set(occIndex, markerTop);
}
}
mount() {
this.addComponents();
this.bindTrackClick();
this.bindThumbDrag();
this.updateThumb();
this.bindScroll();
}
}
function isElementInViewport(element) {
let elementBoundingRect = element.getBoundingClientRect();
if (elementBoundingRect.top < 0 || elementBoundingRect.left < 0) {
return false;
}
if (elementBoundingRect.bottom > (window.innerHeight || document.documentElement.clientHeight)) {
return false;
}
if (elementBoundingRect.right > (window.innerWidth || document.documentElement.clientWidth)) {
return false;
}
return true;
}
});