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.

30 lines
995 B
JavaScript
Raw Normal View History

import { Fragment, createElement } from 'react';
import { DOCUMENT_NODE, ELEMENT_NODE, TEXT_NODE, parse } from 'ultrahtml';
let ids = 0;
export default function convert(children) {
2023-08-16 12:44:01 -05:00
let doc = parse(children.toString().trim());
let id = ids++;
let key = 0;
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) {
return createElement(Fragment, {}, childVnodes);
2023-10-24 07:07:52 -05:00
} else if (node.type === ELEMENT_NODE) {
const { class: className, ...props } = node.attributes;
return createElement(node.name, { ...props, className, key: `${id}-${key++}` }, childVnodes);
} 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
}
}
const root = createReactElementFromNode(doc);
2023-08-16 12:44:01 -05:00
return root.props.children;
}