Skip to content

Instantly share code, notes, and snippets.

@iamtekeste
Created May 27, 2022 22:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamtekeste/3fcab3cce3749334ae4f20b1a907f802 to your computer and use it in GitHub Desktop.
Save iamtekeste/3fcab3cce3749334ae4f20b1a907f802 to your computer and use it in GitHub Desktop.
Craft.js renderer
// 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