-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
62 lines (50 loc) · 1.35 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
const u = require('unist-builder');
const classNames = {
'hint tip': /^!>|!>\s/,
'hint warn': /^\?>|\?>\s/,
'hint error': /^x>|x>\s/,
};
// from github.com/syntax-tree/unist-util-map/blob/bb0567f651517b2d521af711d7376475b3d8446a/index.js
const map = (tree, iteratee) => {
const preorder = (node, index, parent) => {
const newNode = iteratee(node, index, parent);
if (Array.isArray(newNode.children)) {
newNode.children = newNode.children.map((child, index) => {
return preorder(child, index, node);
});
}
return newNode;
};
return preorder(tree, null, null);
};
module.exports = () => (tree) => {
return map(tree, (node) => {
const { children = [] } = node;
if (node.type !== 'paragraph') {
return node;
}
const [{ value, type }, ...siblings] = children;
if (type !== 'text') {
return node;
}
if (!Object.values(classNames).some((r) => r.test(value))) {
return node;
}
const [className, r] = Object.entries(classNames).find(([, r]) => {
return r.test(value);
});
const newChild = {
type,
value: value.replace(r, ''),
};
const props = {
data: {
class: className,
hProperties: {
class: className,
},
},
};
return u('paragraph', props, [newChild, ...siblings]);
});
};