Compare commits
2 Commits
ac75e69f53
...
690cd76d85
Author | SHA1 | Date |
---|---|---|
trans_soup | 690cd76d85 | |
trans_soup | 6f33791a0b |
35
export.mjs
35
export.mjs
|
@ -1,34 +1 @@
|
|||
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]) => {
|
||||
// from testing: class only works with the former, onclick only work with the latter. so both are used here :)
|
||||
// also from testing: this only works in this specific order.
|
||||
// TODO: learn how element attribute setting works and create something more reliable.
|
||||
elem.setAttribute(key, value);
|
||||
elem[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;
|
||||
}
|
||||
export { json_as_html } from "/src/core.mjs";
|
||||
|
|
|
@ -0,0 +1,34 @@
|
|||
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]) => {
|
||||
// from testing: class only works with the former, onclick only work with the latter. so both are used here :)
|
||||
// also from testing: this only works in this specific order.
|
||||
// TODO: learn how element attribute setting works and create something more reliable.
|
||||
elem.setAttribute(key, value);
|
||||
elem[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;
|
||||
}
|
Loading…
Reference in New Issue