/
extractor.ts
66 lines (56 loc) · 2.17 KB
/
extractor.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
import type { Extractor } from '@unocss/core'
import { isValidSelector } from '@unocss/core'
import type { AttributifyOptions } from '.'
const strippedPrefixes = [
'v-bind:',
':',
]
const splitterRE = /[\s'"`;]+/g
const elementRE = /<\w(?=.*>)[\w:\.$-]*\s((?:['"`\{].*?['"`\}]|.*?)*?)>/gs
const valuedAttributeRE = /([?]|(?!\d|-{2}|-\d)[a-zA-Z0-9\u00A0-\uFFFF-_:!%-.]+)=?(?:["]([^"]*)["]|[']([^']*)[']|[{]([^}]*)[}])?/gms
export const defaultIgnoreAttributes = ['placeholder']
export const extractorAttributify = (options?: AttributifyOptions): Extractor => {
const ignoreAttributes = options?.ignoreAttributes ?? defaultIgnoreAttributes
const nonValuedAttribute = options?.nonValuedAttribute ?? true
const trueToNonValued = options?.trueToNonValued ?? false
return {
name: 'attributify',
extract({ code }) {
const result = Array.from(code.matchAll(elementRE))
.flatMap(match => Array.from((match[1] || '').matchAll(valuedAttributeRE)))
.flatMap(([, name, ...contents]) => {
const content = contents.filter(Boolean).join('')
if (ignoreAttributes.includes(name))
return []
for (const prefix of strippedPrefixes) {
if (name.startsWith(prefix)) {
name = name.slice(prefix.length)
break
}
}
if (!content) {
if (isValidSelector(name) && nonValuedAttribute !== false) {
const result = [`[${name}=""]`]
if (trueToNonValued)
result.push(`[${name}="true"]`)
return result
}
return []
}
if (['class', 'className'].includes(name)) {
return content
.split(splitterRE)
.filter(isValidSelector)
}
else {
const extractTernary = Array.from(content.matchAll(/(?:[\?:].*?)(["'])([^\1]*?)\1/gms))
.map(([,,v]) => v.split(splitterRE)).flat()
return (extractTernary.length ? extractTernary : content.split(splitterRE))
.filter(Boolean)
.map(v => `[${name}~="${v}"]`)
}
})
return new Set(result)
},
}
}