UNPKG

cary-tsx-dom

Version:

A simple way to use tsx syntax to create native dom elements using document.createElement.

80 lines 2.99 kB
"use strict"; /* eslint-disable @typescript-eslint/no-unused-vars */ /** * License: MIT * @author Santo Pfingsten * @see https://github.com/Lusito/tsx-dom */ var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.h = void 0; function applyChild(element, child) { if (child instanceof HTMLElement) 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 (var _i = 0, children_1 = children; _i < children_1.length; _i++) { var child = children_1[_i]; if (!child && child !== 0) continue; if (Array.isArray(child)) applyChildren(element, child); else applyChild(element, child); } } function transferKnownProperties(source, target) { for (var _i = 0, _a = Object.keys(source); _i < _a.length; _i++) { var key = _a[_i]; if (Object.prototype.hasOwnProperty.call(target, key)) target[key] = source[key]; } } function h(tag, attrs) { var children = []; for (var _i = 2; _i < arguments.length; _i++) { children[_i - 2] = arguments[_i]; } if (typeof tag === "function") return tag(__assign(__assign({}, attrs), { children: children })); var element = document.createElement(tag); if (attrs) { // Special handler for style with a value of type JSX.StyleAttributes if (attrs.style && typeof attrs.style !== "string") { transferKnownProperties(attrs.style, element.style); delete attrs.style; } for (var _a = 0, _b = Object.keys(attrs); _a < _b.length; _a++) { var name_1 = _b[_a]; var value = attrs[name_1]; if (name_1.match(/^on/)) { var finalName = name_1.replace(/Capture$/, ""); var useCapture = name_1 !== finalName; var eventName = finalName.toLowerCase().substring(2); element.addEventListener(eventName, value, useCapture); } else if (value === true) element.setAttribute(name_1, name_1); else if (value || value === 0) element.setAttribute(name_1, value.toString()); } } applyChildren(element, children); return element; } exports.h = h; //# sourceMappingURL=index.js.map