philomena/assets/js/notifications.js

76 lines
2.1 KiB
JavaScript
Raw Normal View History

2019-10-05 02:09:52 +02:00
/**
* Notifications
*/
import { fetchJson, handleError } from './utils/requests';
2019-12-02 15:55:48 +01:00
import { $ } from './utils/dom';
2019-11-17 18:50:42 +01:00
import { delegate } from './utils/events';
2019-10-05 02:09:52 +02:00
import store from './utils/store';
const NOTIFICATION_INTERVAL = 600000,
NOTIFICATION_EXPIRES = 300000;
2019-10-05 02:09:52 +02:00
2019-12-02 15:55:48 +01:00
function makeRequest(verb) {
return fetchJson(verb, '/notifications/unread').then(handleError);
2019-10-05 02:09:52 +02:00
}
2019-11-17 18:50:42 +01:00
function bindSubscriptionLinks() {
delegate(document, 'fetchcomplete', {
'.js-subscription-link': event => {
2024-03-03 06:31:06 +01:00
const target = event.target.closest('.js-subscription-target');
2019-11-17 18:50:42 +01:00
event.detail.text().then(text => {
target.outerHTML = text;
});
}
});
2019-10-05 02:09:52 +02:00
}
function getNewNotifications() {
if (document.hidden || !store.hasExpired('notificationCount')) {
return;
}
2019-12-02 15:55:48 +01:00
makeRequest('GET').then(response => response.json()).then(({ notifications }) => {
updateNotificationTicker(notifications);
storeNotificationCount(notifications);
setTimeout(getNewNotifications, NOTIFICATION_INTERVAL);
2019-10-05 02:09:52 +02:00
});
}
function updateNotificationTicker(notificationCount) {
const ticker = $('.js-notification-ticker');
const parsedNotificationCount = Number(notificationCount);
ticker.dataset.notificationCount = parsedNotificationCount;
ticker.textContent = parsedNotificationCount;
}
function storeNotificationCount(notificationCount) {
// The current number of notifications are stored along with the time when the data expires
store.setWithExpireTime('notificationCount', notificationCount, NOTIFICATION_EXPIRES);
}
function setupNotifications() {
if (!window.booru.userIsSignedIn) return;
// Fetch notifications from the server at a regular interval
setTimeout(getNewNotifications, NOTIFICATION_INTERVAL);
2019-10-05 02:09:52 +02:00
// Update the current number of notifications based on the latest page load
2024-05-31 20:14:32 +02:00
const ticker = $('.js-notification-ticker');
if (ticker) {
storeNotificationCount(ticker.dataset.notificationCount);
}
2019-10-05 02:09:52 +02:00
// Update ticker when the stored value changes - this will occur in all open tabs
store.watch('notificationCount', updateNotificationTicker);
2019-11-17 18:50:42 +01:00
bindSubscriptionLinks();
2019-10-05 02:09:52 +02:00
}
export { setupNotifications };