/
placeholder.js
53 lines (48 loc) · 1.28 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
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}`,
})
})
parent.children.splice(index, 1, ...placeholders)
}
}
}
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
// do not override class of NcLink
const componentClass = component.name === 'NcLink' ? undefined : 'rich-text--component'
return h(component, {
props,
class: componentClass,
})
})
}
return text
}