30 lines
686 B
JavaScript
30 lines
686 B
JavaScript
function use_as_array (val) {
|
|
return Array.isArray(val) ? val : [val];
|
|
}
|
|
|
|
export function json_as_html (json, state = new Map()) {
|
|
if (json instanceof Node) {
|
|
return json;
|
|
}
|
|
|
|
if (typeof json === "string") {
|
|
return document.createTextNode(json);
|
|
}
|
|
|
|
if (typeof json === "function") {
|
|
return json_as_html(json(state), state);
|
|
}
|
|
|
|
const [type, attributes, children] = json;
|
|
|
|
const elem = document.createElement(type);
|
|
|
|
attributes.forEach(([key, value]) =>
|
|
elem[key] = value);
|
|
// elem.setAttribute(key, value));
|
|
|
|
const child_nodes = use_as_array(children).map(child => json_as_html(child, state))
|
|
child_nodes.forEach(child => elem.appendChild(child));
|
|
|
|
return elem;
|
|
}
|