js/skooma.js

56 lines
1.8 KiB
JavaScript
Raw Normal View History

/*
A functional HTML generation library.
Example:
html.label(
html.span("Delete everything", {class: ["warning", "important"]}),
html.button("Click", {onClick: e => document.body.innerHTML=""}),
)
or
html.ul([1, 2, 3, 4, 5].map(x => html.li(x)), {class: "numbers"})
*/
2021-02-19 20:37:13 +00:00
const parseAttribute = (attribute) => {
2021-05-22 12:34:17 +00:00
if (typeof attribute == "string" || typeof attribute == "number")
2021-02-19 20:37:13 +00:00
return attribute
else if ("join" in attribute)
return attribute.join(" ")
else
return JSON.stringify(attribute)
}
2021-07-21 09:58:44 +00:00
const parseArgs = (element, ...args) => {
if (element.content) element = element.content
2021-03-05 12:29:21 +00:00
for (let arg of args)
2021-05-22 12:34:17 +00:00
if (typeof arg == "string" || typeof arg == "number")
element.appendChild(document.createTextNode(arg))
else if ("nodeName" in arg)
element.appendChild(arg)
else if ("length" in arg)
2021-07-21 09:58:44 +00:00
parseArgs(element, ...arg)
else
2021-05-17 15:19:32 +00:00
for (let key in arg)
2021-07-21 09:58:44 +00:00
if (key == "shadowRoot")
parseArgs((element.shadowRoot || element.attachShadow({mode: "open"})), arg[key])
else if (typeof arg[key] == "function")
element.addEventListener(key.replace(/^on[A-Z]/, x => x.charAt(x.length-1).toLowerCase()), e => e.preventDefault() || arg[key](e))
2021-05-26 09:26:44 +00:00
else
element.setAttribute(key, parseAttribute(arg[key]))
}
const node = (name, args, options) => {
2021-03-05 12:29:21 +00:00
let element
if (options.nameFilter) name = options.nameFilter(name)
if (options.xmlns)
element = document.createElementNS(options.xmlns, name)
else
element = document.createElement(name)
parseArgs(element, args)
return element
}
const nameSpacedProxy = (options={}) => new Proxy(Window, { get: (target, prop, receiver) => { return (...args) => node(prop, args, options) }})
export const html = nameSpacedProxy({nameFilter: name => name.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase()})
export const svg = nameSpacedProxy({xmlns: "http://www.w3.org/2000/svg"})