mydeate/js/element.js

68 lines
1.7 KiB
JavaScript

class Element {
elements = undefined;
id = undefined;
summary = () => "";
detail = () => "";
el = undefined;
classes = [];
constructor(elements, {id, summary, detail, classes, width, height, x, y}) {
this.elements = elements;
this.id = id;
this.summary = summary;
this.detail = detail;
// Create DOM element(s)
this.el = document.createElement("div");
this.el.id = id;
this.el.classList.add('element');
for (const className of (classes ?? [])) {
this.el.classList.add(className);
}
if (width !== undefined && height !== undefined) {
this.setSize(width, height);
}
if (x !== undefined && y !== undefined) {
this.setPosition({x, y});
}
if (summary) {
this.summaryEl = document.createElement("div");
this.summaryEl.classList.add("summary");
this.el.appendChild(this.summaryEl)
}
if (detail) {
this.detailEl = document.createElement("div");
this.detailEl.classList.add("detail");
this.el.appendChild(this.detailEl)
}
// Handle pointer down to initiate drag
this.el.addEventListener("pointerdown", (e) => {
e.preventDefault();
const {clientX: x, clientY: y} = e;
startDrag({element: this, x, y});
});
}
setPosition({x, y}) {
this.el.style.position = "absolute";
this.el.style.top = `${y}px`;
this.el.style.left = `${x}px`;
return this;
}
setSize(width, height) {
this.el.style.width = `${width}px`;
this.el.style.height = `${height}px`;
return this;
}
render() {
if (this.summary) {
this.summaryEl.innerHTML = this.summary();
}
if (this.detail) {
this.detailEl.innerHTML = this.detail();
}
}
}