// Tiny DOM builder. Listing content comes from strangers, so it is only ever // inserted as text nodes or attribute values, never as HTML. export type Child = Node | string | number | null | undefined | false; export type Props = Record void) | undefined>; export function h( tag: K, props: Props | null = null, ...children: Child[] ): HTMLElementTagNameMap[K] { const el = document.createElement(tag); for (const [key, value] of Object.entries(props ?? {})) { if (value === undefined || value === false) continue; if (typeof value === "function") { el.addEventListener(key.replace(/^on/, "").toLowerCase(), value); } else if (value === true) { el.setAttribute(key, ""); } else { el.setAttribute(key, String(value)); } } append(el, children); return el; } export function append(parent: Node, children: Child[]): void { for (const c of children) { if (c === null || c === undefined || c === false) continue; parent.appendChild(typeof c === "object" ? c : document.createTextNode(String(c))); } } export function clear(el: Element): void { while (el.firstChild) el.removeChild(el.firstChild); } /** Lets Ctrl+Enter (Cmd+Enter on a Mac) send the form a text box belongs to, like its Send button. */ export function sendOnCtrlEnter(area: HTMLTextAreaElement): void { area.addEventListener("keydown", (ev) => { if (ev.key !== "Enter" || !(ev.ctrlKey || ev.metaKey) || ev.isComposing || area.disabled) return; ev.preventDefault(); area.form?.requestSubmit(); }); }