core/factories/element.factory.ts
core/factories/element.factory.ts is a file in Bane's Lab Site. 54 lines of code and 9 definitions.
import type { ElementChild, ElementSpec, ElementTag } from "#types/element.types";
const applyAttributes = function applyAttributes(element: Element, attributes: Readonly<Record<string, string>>): 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<T extends ElementTag>(
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();
};
const VECTOR_NAMESPACE = "http://www.w3.org/2000/svg";
export const createVectorNode = function createVectorNode(name: string, spec: ElementSpec = {}): Element {
const element = document.createElementNS(VECTOR_NAMESPACE, name);
if (spec.className !== undefined) {
element.setAttribute("class", 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 createVectorElement = function createVectorElement(markup: string): Element {
const parsed = new DOMParser().parseFromString(markup, "image/svg+xml");
return document.importNode(parsed.documentElement, true);
};