DOM to JSON and back
Here we will create two simple but powerful JavaScript functions.
The first, jsToDom, takes a JavaScript object that describes an element and builds a DOM node. The second, domToJs, reads a DOM node and returns a JavaScript description.
JSON.parse turns JSON text into a value the renderer can use. JSON.stringify turns the description back into text for storage or transfer.
Now we can stringify it and persist it in our database. And rehydrate it at will.
As you may know, JSON does not recognize functions. So we will need a way to deal with our event listeners. Don’t worry! We’ve got it covered.
Check out our example of DOM to JSON and back in action. We will explain it below.
Our reasoning
A key axiom of Craft Code is less is more. (external site) This influences several of the Craft Code methods (external site), such as code just in time (external site) and keep it simple. (external site)
This means that we don’t rush to load up dozens of frameworks, libraries, and other dependencies. Instead, we start with nothing: zero dependencies.
We build the site structure with semantically-correct and accessible HTML. Then we add just enough CSS to make it attractive, user-friendly, and responsive.
Finally, we add JavaScript to progressively enhance the user experience. But only if we need it.
This vanilla approach works very well. One goal of the Craft Code effort is to see how far we can go before we have to add a dependency on someone else’s code.
The code
For the impatient, let’s take a look at the final code. Then we’ll explain it.
The demo checks the description before constructing any elements. It accepts a small set of elements and attributes, and uses a fixed list of handler names. The same renderer works for both examples.
// ./modules/js-to-dom.js
export default async function jsToDom(js) {
const { attributes, children, events, tagName } = js
const elem = document.createElement(tagName)
for (const attr in attributes) {
elem.setAttribute(attr, attributes[attr])
}
if (Array.isArray(children)) {
for (const child of children) {
const node =
typeof child === "object"
? await jsToDom(child)
: document.createTextNode(child)
elem.appendChild(node)
}
}
if (events) {
for (const key in events) {
if (!events[key]) {
continue
}
const handler =
typeof events[key] === "function"
? events[key]
: (await import(`./${events[key]}.js`)).default
handler && elem.addEventListener(key, handler)
}
setDataEvents(elem, js.events)
}
return elem
}
function setDataEvents(elem, obj = {}) {
const eventString = Object.keys(obj)
.reduce((out, key) => {
if (typeof obj[key] === "string") {
out.push(`${key}:${obj[key]}`)
}
return out
}, [])
.join(",")
if (eventString) {
elem.setAttribute("data-events", eventString)
}
}
We grab the tagName from the description and create a DOM element of that type. Then we add the attributes to that element. Then we apply jsToDom recursively on the children, appending them to the element.
An events entry names a handler the demo already knows. The renderer attaches it and records the name in the element’s data-events attribute so the serializer can recover it later. JSON never has to carry the function itself.
// ./modules/dom-to-js.js
export default function domToJs(dom) {
const { attributes, childNodes, tagName } = dom
const eventList = dom.getAttribute("data-events")
const events = eventList?.split(",").reduce((out, evt) => {
const [key, value] = evt.split(":")
if (key) {
out[key] = value
}
return out
}, {})
const attrs = Object.values(attributes)
.map((v) => v.localName)
.filter((name) => name !== "data-events")
const children =
tagName === "TEXTAREA"
? [dom.value]
: Array.from(childNodes).map((_, idx) => {
const child = childNodes[idx]
return child.nodeType === Node.TEXT_NODE
? child.nodeValue
: domToJs(child)
})
return {
tagName,
attributes: attrs.reduce((out, attr) => {
out[attr] = dom.getAttribute(attr)
return out
}, {}),
events,
children,
}
}
The serializer reads the element’s tag, attributes, and child elements or text. For a textarea it records the current .value as a text child. Password values are excluded, even after the user reveals the password.
What can we do with this?
Ooo. All sorts of cool things.
Easy element creation
Suppose I wanted to inject a password field with a show/hide button. First, we create a toggle handler such as this:
// ./modules/toggle-visibility.js
export default function (event) {
const button = event.target
const div = button.closest(".form-field")
const input = div?.querySelector("input")
if (input) {
if (input.type === "password") {
input.type = "text"
button.innerText = "hide"
button.setAttribute("aria-label", "Hide password.")
return
}
input.type = "password"
button.innerText = "show"
button.setAttribute("aria-label", "Show password.")
}
}
Next we assign the event.target to a button variable. (The target is a button.) We use closest to find the closest element to the button with class “form-field”. This will be the div wrapper.
Then, using that wrapper, we can use querySelector to get the password input.
Try pasting this JSON into the example editor, then choose Render JSON.
{
"tagName": "div",
"attributes": {
"class": "form-field"
},
"children": [
{
"tagName": "label",
"children": [
"Password (demo only)",
{
"tagName": "input",
"attributes": {
"type": "password"
}
}
]
},
{
"tagName": "button",
"attributes": {
"type": "button"
},
"events": {
"click": "toggle-visibility"
},
"children": [
"Show password"
]
}
]
}
Easy element persistence
What if I want to save current UI state?
Edit the textarea, then choose Round-trip this edit. The text you typed is what goes into the new control. You can inspect the serialized description under Saved editor JSON.
demo.querySelector("[data-dom-restore]").addEventListener(
"click",
async () => {
const editor = demo.querySelector("#dom-demo-editor")
const saved = JSON.stringify(domToJs(editor), null, 2)
const restored = await jsToDom(JSON.parse(saved))
editor.replaceWith(restored)
showJson(
demo.querySelector("[data-dom-snapshot-code]"),
saved
)
demo.querySelector("[data-dom-snapshot]").hidden = false
status.textContent =
"Rebuilt the editor with your current text."
}
)
The click handler puts the fresh textarea on the page and displays the saved JSON. A real application could store that text and parse it when the user returns.
Build a page from data
The same renderer can use a separate HTML document as the destination. The example creates a document with a title and character encoding, then renders the description into its body. It displays both the result and the complete HTML source.
async function buildPage(description) {
const page = document.implementation.createHTMLDocument(
"A page from data",
)
page.documentElement.lang = "en"
const charset = page.createElement("meta")
charset.setAttribute("charset", "utf-8")
page.head.prepend(charset)
page.body.append(await jsToDom(describeElement(description)))
return page
}
Try the generated-page example.
Data-driven user interfaces
One idea that we have been promoting for several years now is that of a data-driven interface. We’ve got an article on that, Data-driven UIs. But we can give a quick overview here.
The idea is quite simple. The easiest example to visualize is automated form rendering.
Forms collect data. Typically, that data is then persisted in a database.
Databases have schemas. That means that the database already knows the types it expects. If we have defined our schema well, then it knows those types precisely.
Particular data use particular interface widgets. For example, an email address would use an input element of type “email”. An integer might use an input element of type “number” with its step attribute set to “1”.
An enum might use a select or radio buttons or a checkbox group.
From this schema we should be able to determine how to both display and validate that data. After all, there is only a small number of widgets.
So what if the response to our database query for the data included the schema? Some GraphQL queries already make this possible. From that schema, we can generate validation functions. And we know which widgets to display.
So we can generate our form and our validators automatically.
Best of all, we have a single source of truth: our database schema.
(There is an advanced version of this that uses a SHACL (external site) ontology and a triple store (external site) such as Fuseki. (external site) We then use SPARQL (external site) queries to generate the HTML, CSS, and JS straight from the database. Wee ha! We’ll get to that sometime soon, too. Promise.)
If anyone requests it, we’ll give a detailed explanation of the above code in a separate article. This one is long enough.
A reader’s comment on this article led to The proximity principle, part 2.