Skip to content

Commit

Permalink
feat: implement singleton SSE manager for improved notification handling
Browse files Browse the repository at this point in the history
- Added a singleton SSEManager to manage server-sent events (SSE) for real-time notifications.
- Implemented methods for subscribing and unsubscribing notification callbacks.
- Enhanced the initialization process to ensure a single event source is used and cleaned up on page unload.
- Updated the component initialization to utilize the new SSEManager for handling notifications.
  • Loading branch information
tphakala committed Jan 8, 2025
1 parent 6b768e5 commit ab0483a
Showing 1 changed file with 51 additions and 5 deletions.
56 changes: 51 additions & 5 deletions views/settings/settingsBase.html
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,43 @@
}, 50); // Small delay to ensure Alpine has finished rendering
});
});

// Create a singleton SSE manager
window.SSEManager = window.SSEManager || {
eventSource: null,
notificationCallbacks: new Set(),

init() {
if (this.eventSource) {
return; // Already initialized
}

this.eventSource = new EventSource('/sse');
this.eventSource.onmessage = (event) => {
const notification = JSON.parse(event.data);
this.notificationCallbacks.forEach(callback => callback(notification));
};

// Clean up on page unload
window.addEventListener('unload', () => this.cleanup());
},

cleanup() {
if (this.eventSource) {
this.eventSource.close();
this.eventSource = null;
}
this.notificationCallbacks.clear();
},

subscribe(callback) {
this.notificationCallbacks.add(callback);
},

unsubscribe(callback) {
this.notificationCallbacks.delete(callback);
}
};
</script>
<style>
[x-cloak] {
Expand Down Expand Up @@ -68,13 +105,22 @@
notifications: [],
hasChanges: false,
saving: false,
initSSE() {
const eventSource = new EventSource('/sse');
eventSource.onmessage = (event) => {
const notification = JSON.parse(event.data);
init() {
// Subscribe to notifications using the singleton SSE manager
const handleNotification = (notification) => {
this.addNotification(notification.message, notification.type);
};
window.SSEManager.subscribe(handleNotification);
window.SSEManager.init(); // Initialize if not already done
// Cleanup on component destroy
this.$cleanup(() => {
window.SSEManager.unsubscribe(handleNotification);
});
},
addNotification(message, type) {
const id = Date.now();
this.notifications.push({ id, message, type });
Expand Down Expand Up @@ -144,7 +190,7 @@
}
});
}
}" x-init="initSSE()" x-bind:class="$store.pageLoaded.loaded ? 'page-loaded' : ''">
}" x-init="init()" x-bind:class="$store.pageLoaded.loaded ? 'page-loaded' : ''">
<form id="settingsForm" @submit.prevent="saveSettings()">
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2">
<!-- Settings content rendered here -->
Expand Down

0 comments on commit ab0483a

Please sign in to comment.