html.ts
10 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import nodeUtil from 'util'
import NodeCache from 'node-cache'
import {
parse as umParse,
render as umRender,
transform as umTransform,
__unsafeHTML,
ELEMENT_NODE,
TEXT_NODE,
walkSync,
} from 'ultrahtml'
import {
parse as elParse,
specificity as getSpecificity,
specificityToNumber,
} from 'parsel-js'
import { parsedHtmlCache, selectorCache, findNodeCache } from './cache.js'
// TODO: implement a parent/child/element cache
const filterChildElements = (parent) => parent?.children?.filter(n => n.type === ELEMENT_NODE) || []
const nthChildPos = (node, parent) => filterChildElements(parent).findIndex((child) => child === node);
const makeNthChildPosMatcher = (ast) => {
const { argument } = ast
const n = Number(argument)
if (!Number.isNaN(n)) {
return (context, node, parent, i) => {
return i === n
}
}
switch (argument) {
case 'odd':
return (context, node, parent, i) => Math.abs(i % 2) === 1
case 'even':
return (context, node, parent, i) => i % 2 === 0
default: {
if (!argument) throw new Error(`Unsupported empty nth-child selector!`)
let [_, A = '1', B = '0'] = /^\s*(?:(-?(?:\d+)?)n)?\s*\+?\s*(\d+)?\s*$/gm.exec(argument) ?? []
if (A.length === 0) A = '1'
const a = Number.parseInt(A === '-' ? '-1' : A)
const b = Number.parseInt(B)
const nth = (index) => (a * n) + b
return (context, node, parent, i) => {
const elements = filterChildElements(parent)
for (let index = 0; index < elements.length; index++) {
const n = nth(index)
if (n > elements.length) return false
if (n === i) return true
}
return false
}
}
}
}
const getAttrValueMatch = (value, operator = '=', caseSenstive) => {
if (value === undefined) return (attrValue) => attrValue !== undefined
const isCaseInsenstive = caseSensitive === 'i'
if (isCaseInsensitive) value = value.toLowerCase()
const adjustMatcher = (matcher) => isCaseInsensitive ? (attrValue) => matcher(attrValue.toLowerCase()) : matcher
switch (operator) {
case '=': return (attrValue) => value === attrValue
case '~=': {
const keys = value.split(/\s+/g).reduce((keys, item) => {
keys[ item ] = true
return keys
}, {})
return adjustMatcher((attrValue) => keys[ attrValue ])
}
case '|=': return adjustMatcher((attrValue) => value.startsWith(attrValue + '-'))
case '*=': return adjustMatcher((attrValue) => value.indexOf(attrValue) > -1)
case '$=': return adjustMatcher((attrValue) => value.endsWith(attrValue))
case '^=': return adjustMatcher((attrValue) => value.startsWith(attrValue))
}
return (attrValue) => false
}
const compileMatcher = (ast, selector) => {
let counter = 0
const neededContext = []
const makeMatcher = (ast) => {
//console.log('makeMatcher', ast)
switch (ast.type) {
case 'list': {
const matchers = ast.list.map(s => makeMatcher(s))
return (context, node, parent, i, debug) => {
for (const matcher of matchers) {
if (!matcher(context, node, parent, i)) return false
}
return true
}
}
case 'compound': {
const matchers = ast.list.map(s => makeMatcher(s))
return (context, node, parent, i, debug) => {
for (const matcher of matchers) {
if (!matcher(context, node, parent, i)) return false
}
return true
}
}
case 'complex': {
const { left, right, combinator, pos } = ast
const leftMatcher = makeMatcher(left)
const rightMatcher = makeMatcher(right)
const setCounter = counter++
neededContext[ setCounter ] = () => new WeakSet()
return (context, node, parent, i, debug) => {
const seen = context[ setCounter ]
if (leftMatcher(context, node, parent, i, debug)) {
if (debug) console.log('matched on left', { left, right, combinator, pos, parent })
// TODO: Check seen.has(), and maybe skip calling leftMatcher?
seen.add(node)
} else if (parent && seen.has(parent) && combinator === ' ') {
seen.add(node)
}
if (!rightMatcher(context, node, parent, i, debug)) return false
seen.add(node)
if (debug) console.log('matched on right', { left, right, combinator, pos, node, parent })
switch (combinator) {
case ' ':
let parentPtr = parent
while (parentPtr) {
if (seen.has(parentPtr)) return true
parentPtr = parentPtr.parent
}
return false
case '>':
if (debug) console.log('seen parent', seen.has(parent))
return parent ? seen.has(parent) : false
case '+': {
if (!parent) return false
let prevSiblings = parent.children.slice(0, i).filter((el) => el.type === ELEMENT_NODE)
if (prevSiblings.length === 0) return false
const prev = prevSiblings[prevSiblings.length - 1]
if (!prev) return false
if (seen.has(prev)) return true
return false
}
case '~': {
if (!parent) return false
let prevSiblings = parent.children.slice(0, i).filter((el) => el.type === ELEMENT_NODE)
if (prevSiblings.length === 0) return false
for (const prev of prevSiblings) {
if (seen.has(prev)) return true
}
return false
}
default:
return false
}
}
}
case 'type': {
const { name, content } = ast
if (content === '*') return (context, node, parent, i) => true
return (context, node, parent, i, debug) => node.name === name
}
case 'class': {
const { name } = ast
return (context, node, parent, i, debug) => node.attributes?.['class']?.split(/\s+/g).includes(name)
}
case 'id': {
const { name } = ast
return (context, node, parent, i, debug) => node.attributes?.id === name
}
case 'pseudo-class':
switch (ast.name) {
case 'global':
return makeMatcher(elParse(ast.argument))
case 'not': {
const matcher = makeMatcher(ast.subtree)
return (...args) => !matcher(...args)
}
case 'is':
return makeMatcher(ast.subtree)
case 'where':
return makeMatcher(ast.subtree)
case 'root':
return (context, node, parent, i) => !node.parent
case 'empty':
return (context, node, parent, i, debug) => {
if (node.type !== ELEMENT_NODE) return false
const { children } = node
if (children.length === 0) return false
return children.every(child => child.type === TEXT_NODE && child.value.trim() === '')
}
case 'first-child':
return (context, node, parent, i, debug) => {
return parent?.children.findFirst(child => child.type === ELEMENT_NODE) === node
}
case 'last-child':
return (context, node, parent, i, debug) => {
return parent?.children.findLast(child => child.type === ELEMENT_NODE) === node
}
case 'only-child':
return (context, node, parent, i, debug) => {
// TODO: This can break-early after it finds the second element
return filterChildElements(parent).length === 1
}
case 'nth-child': {
const nthChildMatcher = makeNthChildPosMatcher(ast)
return (context, node, parent, i, debug) => {
const pos = nthChildPos(node, parent) + 1
return nthChildMatcher(context, node, parent, pos)
}
}
default:
throw new Error(`Unknown pseudo-class: ${ast.name}`)
}
case 'attribute':
const { caseSensitive, name, value, operator } = ast
const attrValueMatch = getAttrValueMatch(value, operator, caseSenstive)
return (context, node, parent, i, debug) => {
const { attributes: { [ name ]: attrValue } = {} } = node
return attrValueMatch(attrValue)
}
case 'universal':
return (context, node, parent, i, debug) => true
default:
throw new Error(`Unhandled ast: ${ast.type}`)
}
}
const matcher = makeMatcher(ast)
return () => {
const context = neededContext.map(item => item())
const nodeMatcher = (node, parent, i, debug) => {
//if (debug) console.log('starting to match', {node, context})
return matcher(context, node, parent, i, debug)
}
nodeMatcher.toString = () => {
return '[matcher:' + selector + ']'
}
return nodeMatcher
}
}
export const createMatcher = (selector) => {
const matcherCreater = selectorCache.get(selector)
if (false && matcher) return matcherCreater()
const ast = elParse(selector)
//console.log('createMatcher', nodeUtil.inspect({ selector, ast }, { depth: null, colors: true }))
const newMatcherCreater = compileMatcher(ast, selector)
selectorCache.set(selector, newMatcherCreater)
return newMatcherCreater()
}
export const parseHtml = (html) => {
const cached = parsedHtmlCache.get(html)
if (cached) return cached
const doc = umParse(html)
parsedHtmlCache.set(html, doc)
return doc
}
export const findNode = (doc, selector) => {
if (!selector) return doc
let docCache = findNodeCache.get(doc)
if (!docCache) {
docCache = new NodeCache({ stdTTL: 10*60, useClones: false })
findNodeCache.set(doc, docCache)
}
const found = docCache.get(selector)
if (found !== undefined) return found[0]
//console.log('cache miss', {selector})
const matcher = createMatcher(selector)
try {
walkSync(doc, (node, parent, index) => {
if (matcher(node, parent, index)) throw node
})
} catch (e) {
if (e instanceof Error) throw e
docCache.set(selector, [ e ])
return e
}
}