feat: Enhance notification system with WebSocket support and auto-hide alerts

This commit is contained in:
bolade
2025-08-13 14:49:23 +01:00
parent 411f47e039
commit bd4a795a5a
5 changed files with 269 additions and 12 deletions
+103 -5
View File
@@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Email Alerts</title>
<link rel="stylesheet" href="/static/styles.css" />
<link rel="stylesheet" href="{{ url_for('static', path='/styles.css') }}" />
</head>
<body>
<header>
@@ -12,18 +12,116 @@
<h1>Email Alerts</h1>
<nav>
<a href="/">Threads</a>
<a href="/config">Config</a>
<form action="/sync_emails" method="post" style="display:inline-block; margin-left:12px;">
<button type="submit">Process Emails</button>
</form>
<a href="/config">Config</a>
<button id="processEmailsBtn" style="margin-left:12px;">Process Emails</button>
<form action="/process" method="post" style="display:inline-block; margin-left:12px;">
<button type="submit">Process Alerts</button>
</form>
</nav>
</div>
</header>
<!-- Notification banner -->
<div id="notify-root" class="notify-banner" aria-live="polite" aria-atomic="false"></div>
<main class="container">
{% block content %}{% endblock %}
</main>
</body>
<script>
const wsScheme = location.protocol === 'https:' ? 'wss' : 'ws';
const socket = new WebSocket(`${wsScheme}://${location.host}/ws`);
// One-time reload guard after successful sync
let reloadedAfterSync = false;
function maybeRefreshFromMessage(message) {
try {
const msg = String(message || '').toLowerCase();
if (!reloadedAfterSync && msg.includes('email synced successfully')) {
reloadedAfterSync = true;
// Give users a moment to read the success banner, then refresh
setTimeout(() => {
window.location.reload();
}, 800);
}
} catch (_) {
// no-op
}
}
// Simple single-banner notification system
function pushNotification(message, level = 'info') {
try {
const root = document.getElementById('notify-root');
if (!root) return;
const levels = new Set(['info', 'success', 'warn', 'danger']);
const cls = levels.has(String(level)) ? String(level) : 'info';
// Ensure only a single banner is visible at a time
root.innerHTML = '';
const item = document.createElement('div');
item.className = `notify ${cls}`;
item.setAttribute('role', 'status');
const content = document.createElement('div');
content.className = 'notify-content';
content.textContent = String(message ?? '');
const closeBtn = document.createElement('button');
closeBtn.className = 'notify-close';
closeBtn.setAttribute('aria-label', 'Close notification');
closeBtn.innerHTML = '&times;';
closeBtn.addEventListener('click', () => {
// Clear the banner on close
root.innerHTML = '';
});
item.appendChild(content);
item.appendChild(closeBtn);
root.appendChild(item);
} catch (e) {
console.error('Failed to render notification:', e);
}
}
socket.onmessage = function(event) {
try {
let data = null;
try { data = JSON.parse(event.data); } catch { /* may be plain text */ }
if (data && typeof data === 'object') {
const msg = data.message ?? data.msg ?? data.text ?? JSON.stringify(data);
const level = (data.level || data.type || data.status || 'info').toString().toLowerCase();
pushNotification(msg, level);
console.log('Received sync status update:', msg);
maybeRefreshFromMessage(msg);
} else {
const text = String(event.data);
pushNotification(text);
console.log('Received sync status update:', text);
maybeRefreshFromMessage(text);
}
} catch (err) {
console.error('Error handling websocket message:', err);
}
};
document.getElementById("processEmailsBtn").addEventListener("click", function () {
fetch("/sync_emails", { method: "POST" })
.then(response => response.json())
.then(data => {
const status = data?.status ?? 'ok';
pushNotification(`Email sync triggered (${status})`, status === 'ok' ? 'success' : 'info');
console.log("Sync triggered:", status);
})
.catch(err => {
pushNotification(`Error starting sync: ${err?.message || err}`, 'danger');
console.error("Error starting sync:", err)
});
});
</script>
</html>
+18 -1
View File
@@ -8,6 +8,23 @@
<div class="alert success" style="margin-bottom:12px;">
✓ Alerts processed! {{ alerts_processed }} thread(s) were checked for alerts.
</div>
<script>
// Auto-hide the success alert after a short delay with a smooth fade-out
(function() {
const alertEl = document.currentScript?.previousElementSibling;
if (!alertEl || !alertEl.classList || !alertEl.classList.contains('alert')) return;
const hideMs = 3000; // visible duration
const fadeMs = 350; // should match CSS transition
setTimeout(() => {
alertEl.classList.add('fade-out');
setTimeout(() => {
if (alertEl && alertEl.parentNode) {
alertEl.parentNode.removeChild(alertEl);
}
}, fadeMs + 25);
}, hideMs);
})();
</script>
{% endif %}
{% if status %}
<div class="muted" style="margin-top:6px;">
@@ -25,7 +42,7 @@
<span style="margin-left:8px;">Last Sync: {{ status.last_sync_at or 'never' }}</span>
<span style="margin-left:8px;">Items: {{ status.last_sync_count }}</span>
{% if status.last_sync_error %}
<div class="muted">Error: {{ status.last_sync_error }}</div>
<div class="muted" style="margin-top:2px;">Error: {{ status.last_sync_error }}</div>
{% endif %}
{% if status.auto_process %}
<div class="muted">Auto process enabled (every {{ status.interval }}m)</div>