forked from fkling/astexplorer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetFocusPath.js
More file actions
45 lines (42 loc) · 1.16 KB
/
getFocusPath.js
File metadata and controls
45 lines (42 loc) · 1.16 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
function isInRange(range, pos) {
return pos >= range[0] && pos <= range[1];
}
export function nodeToRange(parser, node) {
let range = parser.nodeToRange(node);
if (range) {
return range;
}
if (node.length > 0) {
// check first and last child
let rangeFirst = node[0] && parser.nodeToRange(node[0]);
let rangeLast = node[node.length - 1] &&
parser.nodeToRange(node[node.length - 1]);
if (rangeFirst && rangeLast) {
return [rangeFirst[0], rangeLast[1]];
}
}
}
export default function getFocusPath(node, pos, parser, seen = new Set()) {
seen.add(node);
let path = [];
let range = nodeToRange(parser, node);
if (range) {
if (isInRange(range, pos)) {
path.push(node);
} else {
return [];
}
}
for (let {value} of parser.forEachProperty(node)) {
if (value && typeof value === 'object' && !seen.has(value)) {
let childPath = getFocusPath(value, pos, parser, seen);
if (childPath.length > 0) {
// if current wasn't added, add it now
childPath = range ? childPath : [node].concat(childPath);
path = path.concat(childPath);
break;
}
}
}
return path;
}