eduproj2/stories/articles/ConvertNode.tsx
Michael Zhang ebcce28d5b wtf
2023-08-01 22:20:15 -04:00

59 lines
1.4 KiB
TypeScript

import { createElement } from "react";
import Exercise from "./Exercise";
import { parse } from "yaml";
interface ConvertNodeProps {
node: ChildNode;
}
/**
*/
export default function ConvertNode({ node }: ConvertNodeProps): JSX.Element {
switch (node.nodeType) {
// ELEMENT_NODE
case 1: {
const element = node as Element;
const tagName = element.tagName.toLowerCase();
switch (tagName) {
case "script": {
const scriptType = element.attributes.getNamedItem("type")?.value;
console.log("script type", scriptType);
switch (scriptType) {
case "eduproj/exercise": {
console.log(element.textContent);
const data = parse(element.textContent);
console.log(data);
return <Exercise data={data} />;
}
default:
break;
}
break;
}
default: {
const props = {};
const children = [...node.childNodes].map((child) => (
<ConvertNode node={child} />
));
return createElement(tagName, props, children);
}
}
break;
}
// TEXT_NODE
case 3:
return <>{node.textContent}</>;
default:
console.log("unknown node type", node.nodeType);
return <></>;
}
throw new Error("Something not handled");
}