import type { ElementChild, ElementSpec, ElementTag } from "#types/element.types"; const applyAttributes = function applyAttributes(element: Element, attributes: Readonly>): void { for (const [name, value] of Object.entries(attributes)) { element.setAttribute(name, value); } }; export const appendChildren = function appendChildren(parent: Element, children: readonly ElementChild[]): void { for (const child of children) { parent.append(child); } }; export const createElement = function createElement( tag: T, spec: ElementSpec = {}, ): HTMLElementTagNameMap[T] { const element = document.createElement(tag); if (spec.className !== undefined) { element.className = spec.className; } if (spec.text !== undefined) { element.textContent = spec.text; } if (spec.attributes !== undefined) { applyAttributes(element, spec.attributes); } if (spec.children !== undefined) { appendChildren(element, spec.children); } return element; }; export const clearChildren = function clearChildren(parent: Element): void { parent.replaceChildren(); }; export const createVectorElement = function createVectorElement(markup: string): Element { const parsed = new DOMParser().parseFromString(markup, "image/svg+xml"); return document.importNode(parsed.documentElement, true); };