nopaque/app/static/js/resource-displays/index.js

69 lines
2.0 KiB
JavaScript

var ResourceDisplays = {};
ResourceDisplays.autoInit = () => {
console.log('ResourceDisplays.autoInit');
for (let propertyName in ResourceDisplays) {
let property = ResourceDisplays[propertyName];
// Call autoInit of all properties that are subclasses of `ResourceDisplays.BaseDisplay`.
// This does not include `ResourceDisplays.BaseDisplay` itself.
if (property.prototype instanceof ResourceDisplays.BaseDisplay) {
console.log(property);
// Check if the static `htmlClass` property is defined.
if (property.htmlClass === undefined) {return;}
// Gather all HTML elements that have the `this.htmlClass` class
// and do not have the `no-autoinit` class.
let displayElements = document.querySelectorAll(`.${property.htmlClass}:not(.no-autoinit)`);
console.log(displayElements);
// Create an instance of this class for each display element.
for (let displayElement of displayElements) {new property(displayElement);}
}
}
}
ResourceDisplays.BaseDisplay = class BaseDisplay {
static htmlClass;
constructor(displayElement) {
this.displayElement = displayElement;
this.userId = this.displayElement.dataset.userId;
this.isInitialized = false;
if (this.userId) {
app.subscribeUser(this.userId)
.then((response) => {
app.socket.on('PATCH', (patch) => {
if (this.isInitialized) {this.onPatch(patch);}
});
});
app.getUser(this.userId)
.then((user) => {
this.init(user);
this.isInitialized = true;
});
}
}
init(user) {throw 'Not implemented';}
onPatch(patch) {throw 'Not implemented';}
setElement(element, value) {
switch (element.tagName) {
case 'INPUT': {
element.value = value;
M.updateTextFields();
break;
}
default: {
element.innerText = value;
break;
}
}
}
setElements(elements, value) {
for (let element of elements) {
this.setElement(element, value);
}
}
};