nopaque/app/static/js/App.js

86 lines
2.4 KiB
JavaScript

class App {
constructor() {
this.data = {
promises: {getUser: {}, subscribeUser: {}},
users: {},
};
this.socket = io({transports: ['websocket'], upgrade: false});
this.socket.on('PATCH', (patch) => {
const re = new RegExp(`^/users/(${Object.keys(this.data.users).join('|')})`);
const filteredPatch = patch.filter(operation => re.test(operation.path));
jsonpatch.applyPatch(this.data, filteredPatch);
});
}
getUser(userId) {
if (userId in this.data.promises.getUser) {
return this.data.promises.getUser[userId];
}
this.data.promises.getUser[userId] = new Promise((resolve, reject) => {
this.socket.emit('GET /users/<user_id>', userId, (response) => {
if (response.code === 200) {
this.data.users[userId] = response.payload;
resolve(this.data.users[userId]);
} else {
reject(response);
}
});
});
return this.data.promises.getUser[userId];
}
subscribeUser(userId) {
if (userId in this.data.promises.subscribeUser) {
return this.data.promises.subscribeUser[userId];
}
this.data.promises.subscribeUser[userId] = new Promise((resolve, reject) => {
this.socket.emit('SUBSCRIBE /users/<user_id>', userId, (response) => {
if (response.code === 200) {
resolve(response);
} else {
reject(response);
}
});
});
return this.data.promises.subscribeUser[userId];
}
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-icons">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();});
}
}