blob: 4528c3896cae4358f8586239e9063663c701cb06 (
plain) (
blame)
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
|
import './show-whitespace.css';
import React from 'dom-chef';
import select from 'select-dom';
import * as pageDetect from 'github-url-detection';
import features from '.';
import getTextNodes from '../helpers/get-text-nodes';
import onPrFileLoad from '../github-events/on-pr-file-load';
import onNewComments from '../github-events/on-new-comments';
// `splitText` is used before and after each whitespace group so a new whitespace-only text node is created. This new node is then wrapped in a <span>
function showWhiteSpacesOn(line: Element): void {
const shouldAvoidSurroundingSpaces = Boolean(line.closest('.blob-wrapper-embedded')); // #2285
const textNodesOnThisLine = getTextNodes(line);
for (const [nodeIndex, textNode] of textNodesOnThisLine.entries()) {
// `textContent` reads must be cached #2737
let text = textNode.textContent!;
const startingCharacter = shouldAvoidSurroundingSpaces && nodeIndex === 0 ? 1 : 0;
const skipLastCharacter = shouldAvoidSurroundingSpaces && nodeIndex === textNodesOnThisLine.length - 1;
const endingCharacter = text.length - 1 - Number(skipLastCharacter);
// Loop goes in reverse otherwise `splitText`'s `index` parameter needs to keep track of the previous split
for (let i = endingCharacter; i >= startingCharacter; i--) {
const thisCharacter = text[i];
// Exclude irrelevant characters
if (thisCharacter !== ' ' && thisCharacter !== '\t') {
continue;
}
if (i < text.length - 1) {
textNode.splitText(i + 1);
}
// Find the same character so they can be wrapped together, but stop at `startingCharacter`
while (text[i - 1] === thisCharacter && !(i === startingCharacter)) {
i--;
}
textNode.splitText(i);
// Update cached variable here because it just changed
text = textNode.textContent!;
textNode.after(
<span data-rgh-whitespace={thisCharacter === '\t' ? 'tab' : 'space'}>
{textNode.nextSibling}
</span>
);
}
}
}
const viewportObserver = new IntersectionObserver(changes => {
for (const change of changes) {
if (change.isIntersecting) {
showWhiteSpacesOn(change.target);
viewportObserver.unobserve(change.target);
}
}
});
function init(): void {
for (const line of select.all('.blob-code-inner:not(.rgh-observing-whitespace)')) {
line.classList.add('rgh-observing-whitespace');
viewportObserver.observe(line);
}
}
void features.add(__filebasename, {
include: [
pageDetect.hasCode
],
additionalListeners: [
onNewComments,
onPrFileLoad
],
init
});
|