UNPKG

tsx-dom

Version:

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

46 lines (45 loc) 1.96 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.setAttributes = setAttributes; const tsx_dom_types_1 = require("tsx-dom-types"); // eslint-disable-next-line @typescript-eslint/no-explicit-any function transferKnownProperties(source, target) { for (const key of Object.keys(source)) { if (key in target) target[key] = source[key]; } } /** "on" followed by an uppercase character. Not sure if there are any events with anything other than A-Z. Checking unicode just to be safe */ const eventAttributeName = /^on\p{Lu}/u; function setAttributes(element, attrs) { for (const name of Object.keys(attrs)) { // Ignore some debug props that might be added by bundlers if (name === "__source" || name === "__self" || name === "tsxTag") continue; const value = attrs[name]; if (name === "class") { const finalValue = (0, tsx_dom_types_1.classnames)(value); if (finalValue) element.setAttribute(name, finalValue); } else if (name === "ref") { value.current = element; } else if (eventAttributeName.test(name)) { 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 !== "string") { // 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 || value === "") element.setAttribute(name, value.toString()); } }