-
-
Notifications
You must be signed in to change notification settings - Fork 96
/
finder.ts
373 lines (335 loc) · 9 KB
/
finder.ts
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
// License: MIT
// Author: Anton Medvedev <[email protected]>
// Source: https://github.com/antonmedv/finder
type Knot = {
name: string
penalty: number
level?: number
}
const acceptedAttrNames = new Set(['role', 'name', 'aria-label', 'rel', 'href'])
/** Check if attribute name and value are word-like. */
export function attr(name: string, value: string): boolean {
let nameIsOk = acceptedAttrNames.has(name)
nameIsOk ||= name.startsWith('data-') && wordLike(name)
let valueIsOk = wordLike(value) && value.length < 100
valueIsOk ||= value.startsWith('#') && wordLike(value.slice(1))
return nameIsOk && valueIsOk
}
/** Check if id name is word-like. */
export function idName(name: string): boolean {
return wordLike(name)
}
/** Check if class name is word-like. */
export function className(name: string): boolean {
return wordLike(name)
}
/** Check if tag name is word-like. */
export function tagName(name: string): boolean {
return true
}
/** Configuration options for the finder. */
export type Options = {
/** The root element to start the search from. */
root: Element
/** Function that determines if an id name may be used in a selector. */
idName: (name: string) => boolean
/** Function that determines if a class name may be used in a selector. */
className: (name: string) => boolean
/** Function that determines if a tag name may be used in a selector. */
tagName: (name: string) => boolean
/** Function that determines if an attribute may be used in a selector. */
attr: (name: string, value: string) => boolean
/** Timeout to search for a selector. */
timeoutMs: number
/** Minimum length of levels in fining selector. */
seedMinLength: number
/** Minimum length for optimising selector. */
optimizedMinLength: number
/** Maximum number of path checks. */
maxNumberOfPathChecks: number
}
/** Finds unique CSS selectors for the given element. */
export function finder(input: Element, options?: Partial<Options>): string {
if (input.nodeType !== Node.ELEMENT_NODE) {
throw new Error(`Can't generate CSS selector for non-element node type.`)
}
if (input.tagName.toLowerCase() === 'html') {
return 'html'
}
const defaults: Options = {
root: document.body,
idName: idName,
className: className,
tagName: tagName,
attr: attr,
timeoutMs: 1000,
seedMinLength: 3,
optimizedMinLength: 2,
maxNumberOfPathChecks: Infinity,
}
const startTime = new Date()
const config = { ...defaults, ...options }
const rootDocument = findRootDocument(config.root, defaults)
let foundPath: Knot[] | undefined
let count = 0
for (const candidate of search(input, config, rootDocument)) {
const elapsedTimeMs = new Date().getTime() - startTime.getTime()
if (
elapsedTimeMs > config.timeoutMs ||
count >= config.maxNumberOfPathChecks
) {
const fPath = fallback(input, rootDocument)
if (!fPath) {
throw new Error(
`Timeout: Can't find a unique selector after ${config.timeoutMs}ms`,
)
}
return selector(fPath)
}
count++
if (unique(candidate, rootDocument)) {
foundPath = candidate
break
}
}
if (!foundPath) {
throw new Error(`Selector was not found.`)
}
const optimized = [
...optimize(foundPath, input, config, rootDocument, startTime),
]
optimized.sort(byPenalty)
if (optimized.length > 0) {
return selector(optimized[0])
}
return selector(foundPath)
}
function* search(
input: Element,
config: Options,
rootDocument: Element | Document,
): Generator<Knot[]> {
const stack: Knot[][] = []
let paths: Knot[][] = []
let current: Element | null = input
let i = 0
while (current && current !== rootDocument) {
const level = tie(current, config)
for (const node of level) {
node.level = i
}
stack.push(level)
current = current.parentElement
i++
paths.push(...combinations(stack))
if (i >= config.seedMinLength) {
paths.sort(byPenalty)
for (const candidate of paths) {
yield candidate
}
paths = []
}
}
paths.sort(byPenalty)
for (const candidate of paths) {
yield candidate
}
}
function wordLike(name: string): boolean {
if (/^[a-z\-]{3,}$/i.test(name)) {
const words = name.split(/-|[A-Z]/)
for (const word of words) {
if (word.length <= 2) {
return false
}
if (/[^aeiou]{4,}/i.test(word)) {
return false
}
}
return true
}
return false
}
function tie(element: Element, config: Options): Knot[] {
const level: Knot[] = []
const elementId = element.getAttribute('id')
if (elementId && config.idName(elementId)) {
level.push({
name: '#' + CSS.escape(elementId),
penalty: 0,
})
}
for (let i = 0; i < element.classList.length; i++) {
const name = element.classList[i]
if (config.className(name)) {
level.push({
name: '.' + CSS.escape(name),
penalty: 1,
})
}
}
for (let i = 0; i < element.attributes.length; i++) {
const attr = element.attributes[i]
if (config.attr(attr.name, attr.value)) {
level.push({
name: `[${CSS.escape(attr.name)}="${CSS.escape(attr.value)}"]`,
penalty: 2,
})
}
}
const tagName = element.tagName.toLowerCase()
if (config.tagName(tagName)) {
level.push({
name: tagName,
penalty: 5,
})
const index = indexOf(element, tagName)
if (index !== undefined) {
level.push({
name: nthOfType(tagName, index),
penalty: 10,
})
}
}
const nth = indexOf(element)
if (nth !== undefined) {
level.push({
name: nthChild(tagName, nth),
penalty: 50,
})
}
return level
}
function selector(path: Knot[]): string {
let node = path[0]
let query = node.name
for (let i = 1; i < path.length; i++) {
const level = path[i].level || 0
if (node.level === level - 1) {
query = `${path[i].name} > ${query}`
} else {
query = `${path[i].name} ${query}`
}
node = path[i]
}
return query
}
function penalty(path: Knot[]): number {
return path.map((node) => node.penalty).reduce((acc, i) => acc + i, 0)
}
function byPenalty(a: Knot[], b: Knot[]) {
return penalty(a) - penalty(b)
}
function indexOf(input: Element, tagName?: string): number | undefined {
const parent = input.parentNode
if (!parent) {
return undefined
}
let child = parent.firstChild
if (!child) {
return undefined
}
let i = 0
while (child) {
if (
child.nodeType === Node.ELEMENT_NODE &&
(tagName === undefined ||
(child as Element).tagName.toLowerCase() === tagName)
) {
i++
}
if (child === input) {
break
}
child = child.nextSibling
}
return i
}
function fallback(input: Element, rootDocument: Element | Document) {
let i = 0
let current: Element | null = input
const path: Knot[] = []
while (current && current !== rootDocument) {
const tagName = current.tagName.toLowerCase()
const index = indexOf(current, tagName)
if (index === undefined) {
return
}
path.push({
name: nthOfType(tagName, index),
penalty: NaN,
level: i,
})
current = current.parentElement
i++
}
if (unique(path, rootDocument)) {
return path
}
}
function nthChild(tagName: string, index: number) {
if (tagName === 'html') {
return 'html'
}
return `${tagName}:nth-child(${index})`
}
function nthOfType(tagName: string, index: number) {
if (tagName === 'html') {
return 'html'
}
return `${tagName}:nth-of-type(${index})`
}
function* combinations(stack: Knot[][], path: Knot[] = []): Generator<Knot[]> {
if (stack.length > 0) {
for (let node of stack[0]) {
yield* combinations(stack.slice(1, stack.length), path.concat(node))
}
} else {
yield path
}
}
function findRootDocument(rootNode: Element | Document, defaults: Options) {
if (rootNode.nodeType === Node.DOCUMENT_NODE) {
return rootNode
}
if (rootNode === defaults.root) {
return rootNode.ownerDocument as Document
}
return rootNode
}
function unique(path: Knot[], rootDocument: Element | Document) {
const css = selector(path)
switch (rootDocument.querySelectorAll(css).length) {
case 0:
throw new Error(`Can't select any node with this selector: ${css}`)
case 1:
return true
default:
return false
}
}
function* optimize(
path: Knot[],
input: Element,
config: Options,
rootDocument: Element | Document,
startTime: Date,
): Generator<Knot[]> {
if (path.length > 2 && path.length > config.optimizedMinLength) {
for (let i = 1; i < path.length - 1; i++) {
const elapsedTimeMs = new Date().getTime() - startTime.getTime()
if (elapsedTimeMs > config.timeoutMs) {
return
}
const newPath = [...path]
newPath.splice(i, 1)
if (
unique(newPath, rootDocument) &&
rootDocument.querySelector(selector(newPath)) === input
) {
yield newPath
yield* optimize(newPath, input, config, rootDocument, startTime)
}
}
}
}