2023-08-16 17:44:01 +00:00
|
|
|
import { parse, walkSync, DOCUMENT_NODE, ELEMENT_NODE, TEXT_NODE } from 'ultrahtml';
|
2023-08-16 17:40:57 +00:00
|
|
|
import { createElement, Fragment } from 'react';
|
|
|
|
|
2023-09-07 20:54:39 +00:00
|
|
|
let ids = 0;
|
2023-08-16 17:40:57 +00:00
|
|
|
export default function convert(children) {
|
2023-08-16 17:44:01 +00:00
|
|
|
const nodeMap = new WeakMap();
|
|
|
|
let doc = parse(children.toString().trim());
|
2023-09-07 20:54:39 +00:00
|
|
|
let id = ids++;
|
|
|
|
let key = 0;
|
2023-08-16 17:44:01 +00:00
|
|
|
let root = createElement(Fragment, { children: [] });
|
2023-08-16 17:40:57 +00:00
|
|
|
|
2023-08-16 17:44:01 +00:00
|
|
|
walkSync(doc, (node, parent, index) => {
|
|
|
|
let newNode = {};
|
|
|
|
if (node.type === DOCUMENT_NODE) {
|
|
|
|
nodeMap.set(node, root);
|
|
|
|
} else if (node.type === ELEMENT_NODE) {
|
|
|
|
const { class: className, ...props } = node.attributes;
|
2023-09-07 20:54:39 +00:00
|
|
|
// NOTE: do not manually pass `children`, React handles this internally
|
|
|
|
newNode = createElement(node.name, { ...props, className, key: `${id}-${key++}` });
|
2023-08-16 17:44:01 +00:00
|
|
|
nodeMap.set(node, newNode);
|
|
|
|
if (parent) {
|
|
|
|
const newParent = nodeMap.get(parent);
|
|
|
|
newParent.props.children[index] = newNode;
|
|
|
|
}
|
|
|
|
} else if (node.type === TEXT_NODE) {
|
2023-09-07 20:54:39 +00:00
|
|
|
newNode = node.value;
|
|
|
|
if (newNode.trim() && parent) {
|
|
|
|
const newParent = nodeMap.get(parent);
|
|
|
|
newParent.props.children[index] = newNode;
|
2023-08-16 17:44:01 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
2023-08-16 17:40:57 +00:00
|
|
|
|
2023-08-16 17:44:01 +00:00
|
|
|
return root.props.children;
|
2023-08-16 17:40:57 +00:00
|
|
|
}
|