2021-05-07 22:23:52 +01:00
|
|
|
import { getObjectKeys } from "./utils";
|
|
|
|
|
|
|
|
type optionsFunctionsObject = {
|
|
|
|
[key: string]: (e: any, arg: any) => void
|
|
|
|
}
|
|
|
|
|
|
|
|
const optionsFunctions: optionsFunctionsObject = {
|
|
|
|
"class": (e: Element, arg: string | string[]) => {
|
|
|
|
if (Array.isArray(arg)) {
|
|
|
|
e.classList.add(...arg);
|
|
|
|
} else {
|
|
|
|
e.classList.add(arg);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
"id": (e: Element, arg: string) => e.id = arg,
|
|
|
|
"html": (e: Element, arg: string) => e.innerHTML = arg,
|
|
|
|
"onclick": (e: HTMLButtonElement, arg: any) => e.onclick = arg,
|
|
|
|
"attributes": setElementAttributes,
|
|
|
|
"text": (e: HTMLParagraphElement, arg: string) => e.innerText = arg,
|
2021-05-08 00:38:02 +01:00
|
|
|
"children": (e: Element, arg: Element | Element[]) => {
|
2021-05-07 22:23:52 +01:00
|
|
|
if (Array.isArray(arg)) {
|
|
|
|
arg.forEach(child => {
|
|
|
|
if (child != null) e.appendChild(child);
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
if (arg != null) e.appendChild(arg);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
"thenRun": (e: Element, arg: (e: Element) => void) => arg(e),
|
|
|
|
}
|
|
|
|
|
|
|
|
interface ElementInfo {
|
2021-05-07 23:08:02 +01:00
|
|
|
condition?: boolean;
|
2021-05-07 22:23:52 +01:00
|
|
|
tag: string;
|
|
|
|
class?: string | string[];
|
|
|
|
id?: string;
|
|
|
|
html?: string;
|
|
|
|
attributes?: {
|
|
|
|
[propName: string]: any
|
|
|
|
};
|
2021-05-08 00:38:02 +01:00
|
|
|
children?: Element | Element[];
|
2021-05-07 22:23:52 +01:00
|
|
|
text?: string;
|
|
|
|
thenRun?: (e: Element) => void;
|
|
|
|
[propName: string]: any;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function makeElement(elementInfo: ElementInfo) {
|
|
|
|
if ("condition" in elementInfo) { if (!elementInfo.condition) { return null; } }
|
2021-05-07 23:08:02 +01:00
|
|
|
const element = document.createElement(elementInfo.tag);
|
2021-05-07 22:23:52 +01:00
|
|
|
|
2021-05-07 23:08:02 +01:00
|
|
|
for (const key of Object.getOwnPropertyNames(elementInfo)) {
|
2021-05-07 22:23:52 +01:00
|
|
|
if (getObjectKeys(optionsFunctions).includes(key)) {
|
|
|
|
(optionsFunctions as any)[key](element, elementInfo[key]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return element;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function setElementAttributes(element: Element, attributes: {[propName: string]: any}) {
|
2021-05-07 23:08:02 +01:00
|
|
|
for (const key of Object.getOwnPropertyNames(attributes)) {
|
2021-05-07 22:23:52 +01:00
|
|
|
element.setAttribute(key, attributes[key]);
|
|
|
|
}
|
|
|
|
}
|