// DOM and formatting helpers. // // Everything here builds nodes and sets textContent rather than assembling // HTML strings. A stream title, a log line and an error message all come from // outside, and node building makes it impossible for them to become markup. /** * el("div.card", {title: "x"}, child, ...) -> HTMLElement * The tag accepts a CSS-like shorthand: "span.pill.ok" or "#id.cls". */ export function el(spec, attrs, ...children) { let tag = "div"; const classes = []; let id = ""; const m = String(spec).match(/^([a-zA-Z][a-zA-Z0-9-]*)?((?:[.#][^.#]+)*)$/); if (m) { if (m[1]) tag = m[1]; for (const part of (m[2] || "").match(/[.#][^.#]+/g) || []) { if (part[0] === ".") classes.push(part.slice(1)); else id = part.slice(1); } } const node = document.createElement(tag); if (classes.length) node.className = classes.join(" "); if (id) node.id = id; if (attrs && (typeof attrs !== "object" || attrs instanceof Node || Array.isArray(attrs))) { children.unshift(attrs); attrs = null; } for (const [k, v] of Object.entries(attrs || {})) { if (v === null || v === undefined || v === false) continue; if (k === "class") node.className = v; else if (k === "text") node.textContent = v; else if (k === "html") throw new Error("el(): raw html is not allowed"); else if (k === "dataset") Object.assign(node.dataset, v); else if (k === "style" && typeof v === "object") Object.assign(node.style, v); else if (k.startsWith("on") && typeof v === "function") node.addEventListener(k.slice(2), v); // Form controls: set the live property. setAttribute("value") does not fill //