1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
/**
* Notifications
*/
import { fetchJson, handleError } from './utils/requests';
import { $, $$, hideEl, toggleEl } from './utils/dom';
import store from './utils/store';
const NOTIFICATION_INTERVAL = 600000,
NOTIFICATION_EXPIRES = 300000;
function makeRequest(verb, action, body) {
return fetchJson(verb, `${window.booru.apiEndpoint}notifications/${action}.json`, body).then(handleError);
}
function toggleSubscription(data) {
const { subscriptionId, subscriptionType } = data.el.dataset;
const subscriptionElements = $$(`.js-notification-${subscriptionType + subscriptionId}`);
makeRequest('PUT', data.value, { id: subscriptionId, actor_class: subscriptionType }) // eslint-disable-line camelcase
.then(() => toggleEl(subscriptionElements))
.catch(() => data.el.textContent = 'Error!');
}
function markRead(data) {
const notificationId = data.value;
const notification = $(`.js-notification-id-${notificationId}`);
makeRequest('PUT', 'mark_read', { id: notificationId })
.then(() => hideEl(notification))
.catch(() => data.el.textContent = 'Error!');
}
function getNewNotifications() {
if (document.hidden || !store.hasExpired('notificationCount')) {
return;
}
makeRequest('GET', 'unread').then(response => response.json()).then(json => {
updateNotificationTicker(json.count);
storeNotificationCount(json.count);
});
}
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
setInterval(getNewNotifications, NOTIFICATION_INTERVAL);
// Update the current number of notifications based on the latest page load
storeNotificationCount($('.js-notification-ticker').dataset.notificationCount);
// Update ticker when the stored value changes - this will occur in all open tabs
store.watch('notificationCount', updateNotificationTicker);
}
export { setupNotifications, toggleSubscription, markRead };
|