StaticApps/src/app/Core/Notification.js

88 lines
2.8 KiB
JavaScript

class NotificationHandler {
constructor() {
this.outer = $('v-notification');
this.toast = $('v-toast');
this.notifications = [];
}
static get instance() {
if (NotificationHandler._instance === undefined) {
NotificationHandler._instance = new NotificationHandler();
}
return NotificationHandler._instance;
}
static createNotification(message, type, time, toast = false) {
time = parseInt(time || "3000");
let handler = NotificationHandler.instance,
notification = new NotificationItem(message, type, time, toast);
handler.notifications.push(notification);
notification.show();
return notification;
}
static createToast(message, type = 'info') {
let handler = NotificationHandler.instance,
notification = new NotificationItem(message, type, 2000, true);
handler.notifications.push(notification);
notification.show();
return notification;
}
}
class NotificationItem {
constructor(message, type, time, toast = false) {
this.outer = NotificationHandler.instance.outer;
this.toastCon = NotificationHandler.instance.toast;
this.message = message;
this.type = type;
this.time = time || 1000;
this.isRemoved = false;
this.toast = toast;
}
async show() {
let self = this,
endless = self.time === -1;
self.updateContent(self.message);
if (!endless) {
setTimeout(this.remove.bind(this), self.time)
}
}
async remove() {
if (this.isRemoved) {
return;
}
this.isRemoved = true;
const cont = this.toast ? this.toastCon : this.outer;
cont.removeChild($('#' + this.id));
let not = NotificationHandler.instance.notifications,
index = not.indexOf(this);
not.splice(index, 1);
}
updateContent(message) {
this.id = VUtils.tempId();
let self = this,
isEndless = self.time === -1,
data = {
message: message,
type: self.type,
id: self.id
};
if (isEndless && !self.toast) data.type += ' endless';
const tpl = self.toast ? 'gui/toast' : 'gui/notification';
const cont = self.toast ? self.toastCon : self.outer;
template.renderOn(tpl, data).then(html => {
cont.prepend(document.createRange().createContextualFragment(html));
if (!self.toast) $(`#${self.id} .fade-bar`).style.animationDuration = isEndless ? '1000ms' : `${self.time + 1}ms`;
});
}
updateMessageOnly(message) {
let item = $(`#${this.id} .message`);
if (item) item.innerHTML = message;
}
}