[ADD] Refresh notification icon script

Similar to what we have in AAv3 for the notification count
This commit is contained in:
Peter Pfeufer 2023-10-31 21:45:52 +01:00
parent ee41d62c13
commit 2c5972d0ab
No known key found for this signature in database
GPG Key ID: 6051D2C6AD4EBC27
3 changed files with 89 additions and 4 deletions

View File

@ -0,0 +1,81 @@
/* global notificationUpdateSettings */
/**
* This script refreshed the notification icon in the top menu
* on a regular basis so to keep the user apprised about newly arrived
* notifications without having to reload the page.
*
* The refresh rate can be changes via the Django setting NOTIFICATIONS_REFRESH_TIME.
* See documentation for details.
*/
$(() => {
'use strict';
const notificationsRefreshTime = notificationUpdateSettings.refreshTime;
const userNotificationsCountViewUrl = notificationUpdateSettings.userNotificationsCountViewUrl;
const elementNotificationIcon = $('#menu_item_notifications .fa-bell');
/**
* Update the notification icon in the top menu
*/
const updateNotificationIcon = () => {
fetch(userNotificationsCountViewUrl)
.then((response) => {
if (response.ok) {
return response.json();
}
throw new Error('Something went wrong');
})
.then((responseJson) => {
const unreadCount = responseJson.unread_count;
if (unreadCount > 0) {
elementNotificationIcon.addClass('text-danger');
} else {
elementNotificationIcon.removeClass('text-danger');
}
})
.catch((error) => {
console.log(`Failed to load HTMl to render notifications item. Error: ${error.message}`);
});
};
let myInterval;
/**
* Activate automatic refresh every x seconds
*/
const activateIconUpdate = () => {
if (notificationsRefreshTime > 0) {
myInterval = setInterval(
updateNotificationIcon, notificationsRefreshTime * 1000
);
}
};
/**
* Deactivate automatic refresh
*/
const deactivateIconUpdate = () => {
if ((notificationsRefreshTime > 0) && (typeof myInterval !== 'undefined')) {
clearInterval(myInterval);
}
};
/**
* Refresh only on active browser tabs
*/
$(window)
// Tab active
.focus(() => {
activateIconUpdate();
})
// Tab inactive
.blur(function() {
deactivateIconUpdate();
});
// Initial start of refreshing on script loading
activateIconUpdate();
});

View File

@ -122,13 +122,14 @@
{% theme_js %}
{% if user.is_authenticated %}
<script type="application/javascript">
let notificationUPdateSettings = {
notificationsListViewUrl: "{% url 'notifications:list' %}",
notificationsRefreshTime: "{% notifications_refresh_time %}",
<script>
const notificationUpdateSettings = {
refreshTime: "{% notifications_refresh_time %}",
userNotificationsCountViewUrl: "{% url 'notifications:user_notifications_count' request.user.pk %}"
};
</script>
{% include 'bundles/refresh-notification-icon-js.html' %}
{% endif %}
{% block extra_javascript %}

View File

@ -0,0 +1,3 @@
{% load static %}
<script src="{% static 'allianceauth/js/refresh-notification-icon.js' %}"></script>