Skip to content

Instantly share code, notes, and snippets.

@mcsf
Last active September 3, 2021 09:43
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 mcsf/d23c700e98d561be15702591c4b8deb1 to your computer and use it in GitHub Desktop.
Save mcsf/d23c700e98d561be15702591c4b8deb1 to your computer and use it in GitHub Desktop.
A very simple HTM-based prototype to generate Gutenberg block code. See https://github.com/youknowriad/blocky for the real deal.
const htm = require('htm')
const h = (type, props, ...children) => ({type, props, children})
const html = htm.bind(h)
const API = {
"wp.rich": "wp.blockEditor.RichText",
"wp.plain": "wp.blockEditor.PlainText",
}
const toComponent = type =>
API.hasOwnProperty(type) ?
API[type] :
`"${type}"`
const toCode = ({ type, props, children }) =>
`el(${toComponent(type)}, ${JSON.stringify(Object(props))}, ${
children.map(
c => typeof c === 'string' ? JSON.stringify(c) : toCode(c)
).join(', ')
})`
const trees = [
html`<h1 id=hello>Hello</h1>`,
html`<wp.plain value={content} tagName="pre" />`,
html`<wp.rich value={content} tagName="div" />`,
html`<p className="red">Hello</p>`,
html`<div><div><strong>Level: {{level}}</strong></div><wp.rich value={content} tagName="div" /></div>`,
]
for (const t of trees) {
console.log()
console.dir(t, {depth:null})
console.log('-->')
console.log(toCode(t))
}
// OUTPUT:
// { type: 'h1', props: { id: 'hello' }, children: [ 'Hello' ] }
// -->
// el("h1", {"id":"hello"}, "Hello")
// {
// type: 'wp.plain',
// props: { value: '{content}', tagName: 'pre' },
// children: []
// }
// -->
// el(wp.blockEditor.PlainText, {"value":"{content}","tagName":"pre"}, )
// {
// type: 'wp.rich',
// props: { value: '{content}', tagName: 'div' },
// children: []
// }
// -->
// el(wp.blockEditor.RichText, {"value":"{content}","tagName":"div"}, )
// { type: 'p', props: { className: 'red' }, children: [ 'Hello' ] }
// -->
// el("p", {"className":"red"}, "Hello")
// {
// type: 'div',
// props: null,
// children: [
// {
// type: 'div',
// props: null,
// children: [
// {
// type: 'strong',
// props: null,
// children: [ 'Level: {{level}}' ]
// }
// ]
// },
// {
// type: 'wp.rich',
// props: { value: '{content}', tagName: 'div' },
// children: []
// }
// ]
// }
// -->
// el("div", {}, el("div", {}, el("strong", {}, "Level: {{level}}")), el(wp.blockEditor.RichText, {"value":"{content}","tagName":"div"}, ))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment