Skip to content

Commit 066402a

Browse files
committed
Try using Range.surroundContents
1 parent 2a39e68 commit 066402a

1 file changed

Lines changed: 8 additions & 13 deletions

File tree

source/features/show-whitespace.tsx

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import getTextNodes from '../libs/get-text-nodes';
88

99
// `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>
1010
function showWhiteSpacesOn(line: Element): void {
11+
const range = new Range();
1112
for (const textNode of getTextNodes(line)) {
1213
// `textContent` reads must be cached #2737
1314
let text = textNode.textContent!;
@@ -21,29 +22,23 @@ function showWhiteSpacesOn(line: Element): void {
2122
continue;
2223
}
2324

24-
if (i < text.length - 1) {
25-
textNode.splitText(i + 1);
26-
}
25+
range.setEnd(textNode, i + 1);
2726

2827
// Find the same character so they can be wrapped together
2928
while (text[i - 1] === thisCharacter) {
3029
i--;
3130
}
3231

33-
textNode.splitText(i);
34-
35-
// Update cached variable here because it just changed
36-
text = textNode.textContent!;
32+
range.setStart(textNode, i);
3733

38-
const whitespace = textNode.nextSibling!.textContent!
34+
const whitespace = range.toString()
3935
.replace(/ /g, '·')
4036
.replace(/\t/g, '→');
4137

42-
textNode.after(
43-
<span data-rgh-whitespace={whitespace}>
44-
{textNode.nextSibling}
45-
</span>
46-
);
38+
range.surroundContents(<span data-rgh-whitespace={whitespace}/>);
39+
40+
// Update cached variable here because it just changed
41+
text = textNode.textContent!;
4742
}
4843
}
4944
}

0 commit comments

Comments
 (0)