-
Notifications
You must be signed in to change notification settings - Fork 88
/
placeholder.js
54 lines (49 loc) · 1.21 KB
/
placeholder.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
import { parseUrl } from './autolink.js'
import { visit } from 'unist-util-visit'
import { u } from 'unist-builder'
export const remarkPlaceholder = function() {
return function(ast) {
visit(ast, (node) => node.type === 'text', visitor)
/**
*
* @param {object} node The node
* @param {number} index The index of the node
* @param {object} parent The parent node
*/
function visitor(node, index, parent) {
const placeholders = node.value.split(/(\{[a-z\-_.0-9]+\})/ig)
.map((entry, index, list) => {
const matches = entry.match(/^\{([a-z\-_.0-9]+)\}$/i)
if (!matches) {
return u('text', entry)
}
const [, component] = matches
return u('element', {
tagName: `#${component}`,
})
})
node = u('element', { tagName: 'span' }, [
...placeholders,
])
parent.children[index] = node
}
}
}
export const prepareTextNode = ({ h, context }, text) => {
if (context.autolink) {
text = parseUrl(text)
}
if (Array.isArray(text)) {
return text.map((entry) => {
if (typeof entry === 'string') {
return entry
}
const { component, props } = entry
return h(component, {
props,
class: 'rich-text--component',
})
})
}
return text
}