nopaque/app/static/js/App.js

79 lines
2.2 KiB
JavaScript

class App {
constructor() {
this.data = {users: {}};
this.eventListeners = {'users.patch': []};
this.promises = {users: {}};
this.socket = io({transports: ['websocket'], upgrade: false});
this.socket.on('users.patch', patch => this.usersPatchHandler(patch));
}
get users() {
return this.data.users;
}
addEventListener(type, listener) {
if (!(type in this.eventListeners)) {
throw `Unknown event type: ${type}`;
}
this.eventListeners[type].push(listener);
}
flash(message, category) {
let iconPrefix;
let toast;
let toastCloseActionElement;
switch (category) {
case 'corpus':
iconPrefix = '<i class="left material-icons">book</i>';
break;
case 'error':
iconPrefix = '<i class="error-color-text left material-icons">error</i>';
break;
case 'job':
iconPrefix = '<i class="left nopaque-icon">J</i>';
break;
default:
iconPrefix = '<i class="left material-icons">notifications</i>';
break;
}
toast = M.toast(
{
html: `
<span>${iconPrefix}${message}</span>
<button class="btn-flat toast-action white-text" data-action="close">
<i class="material-icons">close</i>
</button>
`.trim()
}
);
toastCloseActionElement = toast.el.querySelector('.toast-action[data-action="close"]');
toastCloseActionElement.addEventListener('click', () => {toast.dismiss();});
}
getUserById(userId) {
if (userId in this.promises.users) {
return this.promises.users[userId];
}
this.promises.users[userId] = new Promise((resolve, reject) => {
this.socket.emit('users.user.get', userId, response => {
if (response.code === 200) {
this.data.users[userId] = response.payload;
resolve(this.data.users[userId]);
} else {
reject(response);
}
});
});
return this.promises.users[userId];
}
usersPatchHandler(patch) {
let listener;
this.data = jsonpatch.applyPatch(this.data, patch).newDocument;
//this.data = jsonpatch.apply_patch(this.data, patch);
for (listener of this.eventListeners['users.patch']) {listener(patch);}
}
}