src | ||
export.mjs | ||
README.md |
small utility for creating DOM trees from javascript arrays.
note that this doesn't actually take a json string, but rather an actual array, as input. array_as_html
would be a bit inaccurate though, since it also handles some other things such as functions and strings in ways that make sense.
to use, clone/submodule/subtree/whatever the main
branch, and import json_as_html
from export.mjs
.
to see a demo, or contribute, clone the dev
branch.
example
here's the demo array being used at the time of writing this:
[
"div",
[
["id", "wrapper"],
["class", "demo_div"],
],
[
["h1", [], "header :)"],
["p", [], "paragraph! meow"],
["p", [], "another paragraph!! this is so cool"],
state => ["button", [
["onclick", _ => {
state.set("clicked", true);
render();
}]
], "it can even do buttons!"],
state => ["p", [], state.get("clicked") ? "clicked" : "not clicked"],
],
]
it assumes a function render
which replaces the contents of the <body>
with the result of calling json_as_html
with this array as argument. it also assumes a Map
called state
.
how to use
the json_as_html
function takes two arguments:
- a required
json
argument that gets transformed into a tree ofNode
s. - an optional
state
argument which defaults to an emptyMap
.
this is how the function returns, given certain types of json
input:
Node
object: return it as it is.- string: return a text node containing the string.
- function: evaluate the function, with
state
as argument, and recursively calljson_as_html
on the result. return what that recursive call returns. - array: see below.
when given an array as json
input, the function treats its elements as the tag name, attributes, and children, of the Node
to create, in that order. call these type
, attributes
, and children
:
type
is expected to be a string.attributes
is expected to be an array, where each element is a key-value pair.children
is expected to be an array containing valid inputs forjson_as_html
. if it's not an array, it's treated as an array containing a single element.
both attributes
and children
default to empty arrays, and may thus be omitted.