generated from viktor-yakubiv/init
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
64 lines (50 loc) · 1.74 KB
/
index.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
import makeTemplate from 'lodash.template'
import { visitParents as visit } from 'unist-util-visit-parents'
const attach = (options = {}) => {
const {
values = {},
templateSettings,
} = options
const cache = new Map()
const template = str => {
if (!cache.has(str)) {
cache.set(str, makeTemplate(str, templateSettings))
}
return cache.get(str)
}
const substitute = str => {
const newString = template(str)(values)
// When the template matches one value completely, it's better to return
// original value so the compiler can process it in own way.
// This is helpful for boolean attributes like `hidden`
// and useful for nulish values to remove the attribute or text completely.
const valueEntry = Object.entries(values).find(([name, value]) =>
str.indexOf(name) >= 0 && newString === String(value))
return valueEntry?.[1] ?? newString
}
const visitor = (node, ancestors) => {
if (node.properties != null) {
const processedPropEntries = Object.entries(node.properties)
.map(([name, value]) =>
Array.isArray(value)
? [name, substitute(value.join(' ')).split(/\s+/)]
: [name, substitute(value)])
node.properties = Object.fromEntries(processedPropEntries)
}
if (node.value != null) {
node.value = substitute(node.value) ?? ''
if (node.value == null || node.value === '') {
const [parent] = ancestors.slice(-1)
const index = parent.children.indexOf(node)
parent.children.splice(index, 1)
} else if (typeof node.value != 'string') {
node.value = String(node.value)
}
}
}
const transform = tree => {
visit(tree, visitor)
}
return transform
}
export default attach