-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtinycfi.js
41 lines (36 loc) · 1.04 KB
/
tinycfi.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
function isWhitespaceNode(node) {
return !/[^\t\n\r ]/.test(node.textContent);
}
export function generateCfiSteps(target, root = this.window.document.documentElement) {
const window = this.window;
const treeWalker = window.document.createTreeWalker(
root,
window.NodeFilter.SHOW_ELEMENT + window.NodeFilter.SHOW_TEXT,
{
acceptNode: function (node) {
if (node.nodeType === window.Node.TEXT_NODE && isWhitespaceNode(node)) {
return window.NodeFilter.FILTER_REJECT;
}
return window.NodeFilter.FILTER_ACCEPT;
}
},
false
);
let currentNode;
if (target.nodeType === window.Node.TEXT_NODE) {
currentNode = target.parentNode;
} else {
currentNode = target;
}
treeWalker.currentNode = currentNode;
const path = [];
do {
let index = 1;
while (treeWalker.previousSibling()) {
index = index + 1;
}
path.push(index * 2);
currentNode = treeWalker.parentNode();
} while (currentNode && currentNode !== root);
return `/${path.reverse().join('/')}`;
}