Last active
October 14, 2023 12:50
-
-
Save cxmeel/ca26412961e5d0b991ecd3f27c1a3f21 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(namespace) { | |
function Create(className = "span", attributes = {}, ...children) { | |
const node = document.createElement(className) | |
let onInit = null | |
const events = { | |
event: {}, | |
} | |
for (const [attributeName, attributeValue] of Object.entries(attributes)) { | |
if (attributeName.startsWith("$on:")) { | |
const eventName = attributeName.split(":")?.[1] | |
events.event[eventName] = attributeValue | |
continue | |
} | |
if (attributeName === "className" || attributeName === "class") { | |
let classList = attributeValue | |
if (typeof attributeValue === "string") { | |
const classStringSplit = attributeValue.split(" ") | |
if (classStringSplit.length > 0) { | |
classList = classStringSplit | |
} else { | |
classList = [ attributeValue ] | |
} | |
} | |
node.classList.add(...classList) | |
continue | |
} | |
if (attributeName === "style") { | |
let styleList = typeof attributeValue === "string" ? [ attributeValue ] : attributeValue | |
if (attributeValue instanceof Object) { | |
styleList = Object.entries(attributeValue).reduce( | |
(acc, [ key, value ]) => [...acc, `${key.replace(/([A-Z])/g, "-$1").toLowerCase()}: ${value}`], | |
[] | |
) | |
} | |
if (Array.isArray(styleList)) { | |
node.setAttribute("style", styleList.join("; ")) | |
} else { | |
throw new Error(`Key "style" expected a string, Array or Dictionary`) | |
} | |
continue | |
} | |
if (attributeName === "$html") { | |
node.innerHTML = attributeValue | |
continue | |
} | |
if (attributeName === "$init") { | |
onInit = attributeValue | |
continue | |
} | |
node.setAttribute(attributeName, attributeValue) | |
} | |
for (const childNode of children.flat(1).filter((value) => !!value)) { | |
node.append(childNode) | |
} | |
if (onInit) { | |
onInit(node) | |
} | |
for (const [eventName, callback] of Object.entries(events.event)) { | |
node.addEventListener(eventName, function() { | |
callback(node, ...arguments) | |
}) | |
} | |
return node | |
} | |
namespace.Create = Create | |
})(globalThis ?? window) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment