0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2024-12-23 21:53:55 -05:00
astro/packages/integrations/react/vnode-children.js

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

36 lines
1.1 KiB
JavaScript
Raw Normal View History

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