59 lines
2.1 KiB
TypeScript
59 lines
2.1 KiB
TypeScript
import { GefestElement } from "./element";
|
|
|
|
// For protecting the set of elements from direct access
|
|
const elements: Set<GefestElement> = new Set();
|
|
const elementsMapping: Record<string, GefestElement> = {};
|
|
export class GefestEngine {
|
|
static register (element: GefestElement) : string {
|
|
elements.add(element);
|
|
// Generate GefestID for the element
|
|
let gefestId : string;
|
|
do {
|
|
gefestId = `gefest-${Math.random().toString(36).substr(2, 9)}`;
|
|
} while(!!elementsMapping[gefestId]);
|
|
elementsMapping[gefestId] = element;
|
|
|
|
return gefestId;
|
|
}
|
|
|
|
static async activateOnClick(): Promise<void> {
|
|
for (let element of elements) {
|
|
const elementHTML = document.querySelectorAll(`[data-gefest-id="${element.gefestId}"]`);
|
|
if (elementHTML.length > 0) {
|
|
const htmlElement = elementHTML[0] as HTMLElement;
|
|
htmlElement.onclick = element.onClick;
|
|
}
|
|
}
|
|
}
|
|
|
|
static async main(main : () => Promise<void>): Promise<void> {
|
|
await main();
|
|
await GefestEngine.activateOnClick();
|
|
}
|
|
|
|
static render (gefestId: string | string[] | null = null) {
|
|
let gefestElements : string[] | null = null;
|
|
if (typeof gefestId === "string")
|
|
gefestId = [gefestId];
|
|
else if (gefestId === null) {
|
|
gefestId = Object.keys(elementsMapping);
|
|
gefestElements = gefestId;
|
|
}
|
|
//const gefestElement = elementsMapping.get(gefestId);
|
|
if (!gefestElements)
|
|
gefestElements = gefestId.filter(gid => !!elementsMapping[gid]);
|
|
if (gefestElements.length === 0) return;
|
|
const elementHTML = document.querySelectorAll('[data-gefest-id]');
|
|
|
|
if (elementHTML.length > 0) {
|
|
for (let htmlElement of elementHTML) {
|
|
const gid = htmlElement.getAttribute("data-gefest-id");
|
|
if (!gid || !elementsMapping[gid])
|
|
continue;
|
|
|
|
htmlElement.outerHTML = elementsMapping[gid].build();
|
|
}
|
|
GefestEngine.activateOnClick();
|
|
}
|
|
}
|
|
} |