57 lines
1.3 KiB
JavaScript
57 lines
1.3 KiB
JavaScript
// globals: mainDiv, crypto
|
|
class Elements {
|
|
elements = new Map(); // id -> Element
|
|
classes = [];
|
|
div = undefined;
|
|
|
|
constructor({classes} = {}) {
|
|
this.classes = classes;
|
|
this.div = document.createElement("div");
|
|
this.div.classList.add("elements");
|
|
this.div.classList.add("droptarget");
|
|
for (const className of (classes ?? [])) {
|
|
this.div.classList.add(className);
|
|
}
|
|
mainDiv.appendChild(this.div);
|
|
}
|
|
|
|
add(props) {
|
|
// Make sure we have a unique id
|
|
let id = props.id;
|
|
if (!id) {
|
|
if (crypto?.randomUUID) {
|
|
id = crypto.randomUUID();
|
|
} else {
|
|
id = 1;
|
|
while (this.elements.has(id)) {
|
|
id++;
|
|
}
|
|
}
|
|
}
|
|
// Create element
|
|
const element = new Element(this, {...props, id});
|
|
// Append to div
|
|
this.div.appendChild(element.el);
|
|
// Add to collection
|
|
this.elements.set(id, element);
|
|
return element;
|
|
}
|
|
|
|
remove(id) {
|
|
const element = this.elements.get(id);
|
|
if (element) {
|
|
this.div.removeChild(element.el);
|
|
this.elements.delete(id);
|
|
}
|
|
}
|
|
|
|
getElementFromDOM(target) {
|
|
return Array.from(this.elements.values()).find(({el}) => el === target);
|
|
}
|
|
|
|
renderAll() {
|
|
for (const element of this.elements.values()) {
|
|
element.render();
|
|
}
|
|
}
|
|
} |