-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.js
89 lines (83 loc) · 1.95 KB
/
search.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
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
/**
* @param {string} text
* @returns {{ token: string | null, index: number } last token
*/
function parseLastToken(text) {
const matches = text.trim().match(/^[\#\.]?[\w\-\_]+$/);
return {
token: matches ? matches[0] : null,
index: matches ? matches.index : 0
};
}
/**
* @param {{
selected?: boolean;
opened: boolean;
tagName: string;
state: number;
attributes: { name: string, value: string }[];
children: (object | string)[]
}[]} contentTree
* @param {string} token
@returns {boolean} found
*/
function findAllByToken(contentTree, token) {
let found = false;
contentTree.forEach(node => {
if (typeof node === "string") {
return;
}
node.selected = undefined;
if (node.tagName === token) {
found = true;
node.selected = true;
}
if (node.attributes.length > 0) {
node.attributes.forEach(a => {
if (a.name === "id" && `#${a.value}` === token || a.name === "class" && `.${a.value}` === token) {
found = true;
node.selected = true;
}
});
}
if (findAllByToken(node.children, token)) {
found = true;
node.opened = true;
}
});
return found;
}
function clearSelected(contentTree) {
contentTree.forEach(node => {
if (typeof node === "string") {
return;
}
node.selected = undefined;
clearSelected(node.children);
});
}
/**
* search the selector in the contentTree
* @param {{
selected?: boolean;
opened: boolean;
tagName: string;
state: number;
attributes: { name: string, value: string }[];
children: (object | string)[]
}[]} contentTree
* @param {string} selector
*/
function findAllBySelector(contentTree, selector) {
let text = selector;
do {
const { token, index } = parseLastToken(text);
if (!token) {
clearSelected(contentTree);
return;
}
findAllByToken(contentTree, token);
text = text.slice(0, index);
}
while (text);
}