-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery-selector-lite.js
More file actions
87 lines (77 loc) · 2.03 KB
/
query-selector-lite.js
File metadata and controls
87 lines (77 loc) · 2.03 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
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
const { ASTLite } = require('./ast-lite');
function searchForTagName(tagName, tag) {
return tag.name === tagName;
}
function searchForId(id, tag) {
return tag.attributes.id && tag.attributes.id.toLowerCase() === id.substring(1).toLowerCase();
}
function searchForClass(desiredClassName, tag) {
return tag.attributes.class
&& tag.attributes.class.split(' ').some((className) => className.toLowerCase() === desiredClassName.substring(1).toLowerCase());
}
function interpretSubquery(query) {
const operator = query[0];
switch (operator) {
case '.':
return (tag) => searchForClass(query, tag);
case '#':
return (tag) => searchForId(query, tag);
default:
return (tag) => searchForTagName(query, tag);
}
}
function createSubQueryMap(subQuery) {
const subQueryMap = [];
const combinators = {
descendant: ' ',
};
for (const matchers of Object.values(combinators)) {
}
}
/**
* Query Interpret Logic:
* Go through each character
* 1. Determine basic selectors
* 2. Determine Combinator
* 3. Create a list of query actions
* [
* {
* combinator: null,
* basicSelector: '.test',
* nodes: []
* },
* {
* combinator: 'descendant',
* basicSelector: 'div',
*
* }
* ]
*
*/
class Document {
constructor(htmlString = null) {
// Create AST from htmlString if provided
if (htmlString) {
this.ast = new ASTLite();
this.ast.createAST(htmlString);
}
}
async loadFile(filePath) {
this.ast = new ASTLite();
await this.ast.loadFile(filePath);
}
querySelector(query) {
return this.querySelectorAll(query)[0];
}
querySelectorAll(query) {
const subQueries = query.split(',').map((q) => q.trim());
const tags = new Set();
for (const subQuery of subQueries) {
const subQueryMap = createSubQueryMap(subQuery);
const selectorFn = interpretSubquery(subQuery);
this.ast.getTagArray().filter(selectorFn).forEach((item) => tags.add(item));
}
return Array.from(tags);
}
}
module.exports = Document;