/
renderHtmlAst.js
64 lines (54 loc) · 1.38 KB
/
renderHtmlAst.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 React, { Fragment } from 'react';
import toH from 'hast-to-hyperscript';
const FRAGMENT_TAG_NAME = '__fragment';
function getReactElement(name, components) {
if (name === FRAGMENT_TAG_NAME) {
return Fragment;
}
if (
typeof name === 'string' &&
components &&
components.hasOwnProperty(name)
) {
return components[name];
}
return name;
}
function getReactChildren(name, children) {
if (['table', 'thead', 'tbody', 'tr', 'td'].indexOf(name) !== -1) {
// cleanup empty texts from children to prevent react warnings like
// "Whitespace text nodes cannot appear as a child of table/thead/..."
return (
children &&
children.filter(
element => typeof element !== 'string' || !!element.trim(),
)
);
}
return children;
}
/**
* Compile HAST to React.
* @param node
* @param components
*/
function renderHtmlAst(node, { components }) {
if (node.type === 'root') {
// NOTE: wrap children with React.Fragment, to avoid div wrapper from `hast-to-hyperscript`
node = {
type: 'element',
tagName: FRAGMENT_TAG_NAME,
properties: {},
children: node.children,
};
}
function h(name, props, children) {
return React.createElement(
getReactElement(name, components),
props,
getReactChildren(name, children),
);
}
return toH(h, node);
}
export default renderHtmlAst;