@10nm/tsx-dom
Version:
A simple way to use tsx syntax to create native dom elements using document.createElement.
72 lines • 2.87 kB
JavaScript
;
/* eslint-disable @typescript-eslint/no-unused-vars */
/**
* License: MIT
* @author Santo Pfingsten
* @see https://github.com/Lusito/tsx-dom
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.h = void 0;
function applyChild(element, child) {
if (child instanceof Element)
element.appendChild(child);
else if (typeof child === "string" || typeof child === "number")
element.appendChild(document.createTextNode(child.toString()));
else
console.warn("Unknown type to append: ", child);
}
function applyChildren(element, children) {
for (const child of children) {
if (!child && child !== 0)
continue;
if (Array.isArray(child))
applyChildren(element, child);
else
applyChild(element, child);
}
}
function transferKnownProperties(source, target) {
for (const key of Object.keys(source)) {
if (key in target)
target[key] = source[key];
}
}
function createElement(tag, attrs) {
const options = (attrs === null || attrs === void 0 ? void 0 : attrs.is) ? { is: attrs.is } : undefined;
if (attrs === null || attrs === void 0 ? void 0 : attrs.xmlns)
return document.createElementNS(attrs.xmlns, tag, options);
return document.createElement(tag, options);
}
function h(tag, attrs, ...children) {
if (typeof tag === "function")
return tag(Object.assign(Object.assign({}, attrs), { children }));
const element = createElement(tag, attrs);
if (attrs) {
for (const name of Object.keys(attrs)) {
// Ignore some debug props that might be added by bundlers
if (name === "__source" || name === "__self" || name === "is" || name === "xmlns")
continue;
const value = attrs[name];
if (name.startsWith("on")) {
const finalName = name.replace(/Capture$/, "");
const useCapture = name !== finalName;
const eventName = finalName.toLowerCase().substring(2);
element.addEventListener(eventName, value, useCapture);
}
else if (name === "style" && typeof value === "object") {
// Special handler for style with a value of type CSSStyleDeclaration
transferKnownProperties(value, element.style);
}
else if (name === "dangerouslySetInnerHTML")
element.innerHTML = value;
else if (value === true)
element.setAttribute(name, name);
else if (value || value === 0)
element.setAttribute(name, value.toString());
}
}
applyChildren(element, children);
return element;
}
exports.h = h;
//# sourceMappingURL=index.js.map