nopaque/app/static/js/App.js

86 lines
2.4 KiB
JavaScript
Raw Normal View History

2021-11-30 15:22:16 +00:00
class App {
constructor() {
this.data = {
promises: {getUser: {}, subscribeUser: {}},
users: {},
};
2021-11-30 15:22:16 +00:00
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);
});
2021-11-30 15:22:16 +00:00
}
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];
2021-12-01 13:15:20 +00:00
}
2021-11-30 15:22:16 +00:00
2022-07-04 12:09:17 +00:00
subscribeUser(userId) {
if (userId in this.data.promises.subscribeUser) {
return this.data.promises.subscribeUser[userId];
2021-12-01 13:15:20 +00:00
}
this.data.promises.subscribeUser[userId] = new Promise((resolve, reject) => {
this.socket.emit('SUBSCRIBE /users/<user_id>', userId, (response) => {
2022-07-04 12:09:17 +00:00
if (response.code === 200) {
resolve(response);
2022-07-04 12:09:17 +00:00
} else {
reject(response);
}
});
});
return this.data.promises.subscribeUser[userId];
2021-11-30 15:22:16 +00:00
}
flash(message, category) {
2021-12-01 13:15:20 +00:00
let iconPrefix;
let toast;
let toastCloseActionElement;
2021-11-30 15:22:16 +00:00
switch (category) {
2021-12-01 13:15:20 +00:00
case 'corpus':
iconPrefix = '<i class="left material-icons">book</i>';
2021-11-30 15:22:16 +00:00
break;
2021-12-01 13:15:20 +00:00
case 'error':
iconPrefix = '<i class="error-color-text left material-icons">error</i>';
2021-11-30 15:22:16 +00:00
break;
2021-12-01 13:15:20 +00:00
case 'job':
iconPrefix = '<i class="left nopaque-icons">J</i>';
2021-11-30 15:22:16 +00:00
break;
default:
2021-12-01 13:15:20 +00:00
iconPrefix = '<i class="left material-icons">notifications</i>';
break;
2021-11-30 15:22:16 +00:00
}
2021-12-01 13:15:20 +00:00
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()
}
);
2021-11-30 15:22:16 +00:00
toastCloseActionElement = toast.el.querySelector('.toast-action[data-action="close"]');
toastCloseActionElement.addEventListener('click', () => {toast.dismiss();});
}
}