2024-02-27 06:15:27 -05:00
|
|
|
import { Fragment, createElement } from 'react';
|
|
|
|
import { DOCUMENT_NODE, ELEMENT_NODE, TEXT_NODE, parse } from 'ultrahtml';
|
2023-08-16 12:40:57 -05:00
|
|
|
|
2023-09-07 15:54:39 -05:00
|
|
|
let ids = 0;
|
2023-08-16 12:40:57 -05:00
|
|
|
export default function convert(children) {
|
2023-08-16 12:44:01 -05:00
|
|
|
let doc = parse(children.toString().trim());
|
2023-09-07 15:54:39 -05:00
|
|
|
let id = ids++;
|
|
|
|
let key = 0;
|
2023-08-16 12:40:57 -05:00
|
|
|
|
2023-10-24 07:05:19 -05:00
|
|
|
function createReactElementFromNode(node) {
|
2023-11-21 12:21:41 -05:00
|
|
|
const childVnodes =
|
|
|
|
Array.isArray(node.children) && node.children.length
|
|
|
|
? node.children.map((child) => createReactElementFromNode(child)).filter(Boolean)
|
|
|
|
: undefined;
|
2023-10-24 07:07:52 -05:00
|
|
|
|
|
|
|
if (node.type === DOCUMENT_NODE) {
|
2023-10-24 07:05:19 -05:00
|
|
|
return createElement(Fragment, {}, childVnodes);
|
2023-10-24 07:07:52 -05:00
|
|
|
} else if (node.type === ELEMENT_NODE) {
|
2023-10-24 07:05:19 -05:00
|
|
|
const { class: className, ...props } = node.attributes;
|
|
|
|
return createElement(node.name, { ...props, className, key: `${id}-${key++}` }, childVnodes);
|
2023-11-21 12:19:43 -05:00
|
|
|
} else if (node.type === TEXT_NODE) {
|
|
|
|
// 0-length text gets omitted in JSX
|
|
|
|
return node.value.trim() ? node.value : undefined;
|
2023-08-16 12:44:01 -05:00
|
|
|
}
|
2023-10-24 07:05:19 -05:00
|
|
|
}
|
2023-08-16 12:40:57 -05:00
|
|
|
|
2023-10-24 07:05:19 -05:00
|
|
|
const root = createReactElementFromNode(doc);
|
2023-08-16 12:44:01 -05:00
|
|
|
return root.props.children;
|
2023-08-16 12:40:57 -05:00
|
|
|
}
|