Created
May 27, 2022 22:27
-
-
Save iamtekeste/3fcab3cce3749334ae4f20b1a907f802 to your computer and use it in GitHub Desktop.
Craft.js renderer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// source: https://paste.zauberfisch.com/d/62871445eda3b/craftjs-frontend.js.txt | |
import React, {Fragment} from "react" | |
import Container from "./Container.jsx" | |
import Text from "./Text.jsx" | |
import Button from "./Button.jsx" | |
const contentElements = { | |
Container, | |
Text, | |
Button, | |
} | |
function createElementFromNode({key, id, type, childNodes, linkedNodes, children, linkedComponents, props}) { | |
if (contentElements[type] === undefined) { | |
throw `Component "${type}" does not exist` | |
} | |
return React.createElement(contentElements[type], { | |
key, | |
id, | |
linkedNodes, | |
childNodes, | |
children, | |
linkedComponents | |
...props, | |
}) | |
} | |
function getNode(nodes, id) { | |
const node = nodes[id] | |
const childNodes = node.nodes ? node.nodes.map((_id) => getNode(nodes, _id)) : [] | |
const linkedNodes = node.linkedNodes ? Object.fromEntries(Object.entries(node.linkedNodes).map(([linkId, _id]) => [linkId, getNode(nodes, _id)])) : {} | |
return { | |
id, | |
type: node.type.resolvedName, | |
props: node.props, | |
childNodes, | |
linkedNodes, | |
children: childNodes.map((node) => createElementFromNode({...node, key: node.id})), | |
linkedComponents: Object.fromEntries(Object.entries(linkedNodes).map(([linkId, node]) => createElementFromNode([linkId, {...node, key: linkId}]))), | |
} | |
} | |
export function FrontendFrame({json}) { | |
const content = JSON.parse(json) | |
if (content && content.ROOT) { | |
const root = getNode(content, "ROOT") | |
return <div>{root.children}</div> | |
} | |
return <div>no content</div> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment