This is a sophisticated real-time notifications hub request. Let me break down what's needed:
- Web Push API - For native push notifications
- SSE (Server-Sent Events) Fallback - For browsers that don't support Web Push or when push fails
- Subscription Budgeting - Managing rate limits, quotas, and user preferences for notifications
Since this needs to be a single HTML file without external APIs, I'll create a comprehensive simulation that demonstrates:
- Web Push subscription flow (simulated with VAPID keys UI)
- SSE connection with fallback mechanism
- Subscription budget management (rate limiting, quotas, priority queues)
- Beautiful 3D UI with particles and animations
Key features to implement:
-
Notification Center UI
- Real-time notification feed
- Category filters
- Priority levels
- Read/unread states
-
Subscription Management
- Budget allocation per category
- Rate limiting visualization
- Quota tracking
- Burst handling
-
Connection Status
- Web Push status
- SSE fallback status
- Connection health indicator
-
Interactive Elements
- Send test notifications
- Adjust budgets
- Filter notifications
- Real-time stats
Design considerations:
- Dark theme with vibrant accents (avoiding purple!)
- Cyan/teal, orange, and white as accent colors
- 3D elements and particle effects
- Smooth animations
- High contrast for readability
Let me create this comprehensive system:
Real-Time Notifications Hub
This is a comprehensive notifications system featuring:
- Web Push API - Native browser push notifications with VAPID key management
- SSE Fallback - Server-Sent Events for real-time updates when Push unavailable
- Subscription Budgeting - Rate limiting, quota management, and priority queuing
Key Features:
- Real-time notification feed with categories and priorities
- Connection status monitoring (Push vs SSE fallback)
- Budget allocation per notification type
- Rate limiting visualization
- Interactive test controls
- 3D animated background with particles
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Real-Time Notifications Hub</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
:root {
--bg-primary: #0a0f1a;
--bg-secondary: #111827;
--bg-card: #1a2332;
--accent-cyan: #00d4ff;
--accent-orange: #ff6b35;
--accent-green: #10b981;
--accent-red: #ef4444;
--accent-yellow: #f59e0b;
--text-primary: #f1f5f9;
--text-secondary: #94a3b8;
--border-color: #2d3a4f;
}
body {
font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
background: var(--bg-primary);
color: var(--text-primary);
min-height: 100vh;
overflow-x: hidden;
}
#canvas-bg {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 0;
}
.app-container {
position: relative;
z-index: 1;
display: grid;
grid-template-columns: 320px 1fr 300px;
gap: 20px;
padding: 20px;
min-height: 100vh;
}
@media (max-width: 1200px) {
.app-container {
grid-template-columns: 1fr;
}
}
.panel {
background: linear-gradient(145deg, var(--bg-card), var(--bg-secondary));
border: 1px solid var(--border-color);
border-radius: 16px;
padding: 20px;
backdrop-filter: blur(10px);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}
.panel-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 20px;
padding-bottom: 15px;
border-bottom: 1px solid var(--border-color);
}
.panel-title {
font-size: 1.2rem;
font-weight: 600;
display: flex;
align-items: center;
gap: 10px;
}
.status-badge {
padding: 4px 12px;
border-radius: 20px;
font-size: 0.75rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.status-connected {
background: rgba(16, 185, 129, 0.2);
color: var(--accent-green);
border: 1px solid var(--accent-green);
}
.status-fallback {
background: rgba(245, 158, 11, 0.2);
color: var(--accent-yellow);
border: 1px solid var(--accent-yellow);
}
.status-disconnected {
background: rgba(239, 68, 68, 0.2);
color: var(--accent-red);
border: 1px solid var(--accent-red);
}
/* Connection Panel */
.connection-section {
margin-bottom: 20px;
}
.connection-card {
background: var(--bg-secondary);
border-radius: 12px;
padding: 15px;
margin-bottom: 12px;
border: 1px solid var(--border-color);
transition: all 0.3s ease;
}
.connection-card:hover {
border-color: var(--accent-cyan);
transform: translateX(5px);
}
.connection-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
}
.connection-name {
font-weight: 600;
display: flex;
align-items: center;
gap: 8px;
}
.connection-dot {
width: 8px;
height: 8px;
border-radius: 50%;
animation: pulse 2s infinite;
}
.dot-active { background: var(--accent-green); }
.dot-inactive { background: var(--accent-red); animation: none; }
.dot-fallback { background: var(--accent-yellow); }
@keyframes pulse {
0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.5; transform: scale(1.2); }
}
.connection-stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
font-size: 0.85rem;
}
.stat-item {
display: flex;
flex-direction: column;
}
.stat-label {
color: var(--text-secondary);
font-size: 0.75rem;
}
.stat-value {
font-weight: 600;
color: var(--accent-cyan);
}
/* Budget Section */
.budget-section {
margin-top: 20px;
}
.budget-item {
background: var(--bg-secondary);
border-radius: 10px;
padding: 12px;
margin-bottom: 10px;
}
.budget-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8px;
}
.budget-name {
font-size: 0.9rem;
font-weight: 500;
}
.budget-values {
font-size: 0.8rem;
color: var(--text-secondary);
}
.budget-bar {
height: 6px;
background: var(--bg-primary);
border-radius: 3px;
overflow: hidden;
}
.budget-fill {
height: 100%;
border-radius: 3px;
transition: width 0.5s ease;
}
.budget-fill.safe { background: var(--accent-green); }
.budget-fill.warning { background: var(--accent-yellow); }
.budget-fill.danger { background: var(--accent-red); }
/* Main Feed */
.feed-container {
display: flex;
flex-direction: column;
height: calc(100vh - 40px);
}
.feed-filters {
display: flex;
gap: 8px;
margin-bottom: 15px;
flex-wrap: wrap;
}
.filter-btn {
padding: 8px 16px;
border-radius: 20px;
border: 1px solid var(--border-color);
background: var(--bg-secondary);
color: var(--text-secondary);
cursor: pointer;
transition: all 0.3s ease;
font-size: 0.85rem;
}
.filter-btn:hover {
border-color: var(--accent-cyan);
color: var(--text-primary);
}
.filter-btn.active {
background: var(--accent-cyan);
color: var(--bg-primary);
border-color: var(--accent-cyan);
}
.feed-list {
flex: 1;
overflow-y: auto;
padding-right: 10px;
}
.feed-list::-webkit-scrollbar {
width: 6px;
}
.feed-list::-webkit-scrollbar-track {
background: var(--bg-secondary);
border-radius: 3px;
}
.feed-list::-webkit-scrollbar-thumb {
background: var(--border-color);
border-radius: 3px;
}
.notification-item {
background: var(--bg-secondary);
border-radius: 12px;
padding: 15px;
margin-bottom: 12px;
border-left: 4px solid transparent;
transition: all 0.3s ease;
animation: slideIn 0.4s ease;
cursor: pointer;
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateX(-20px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
.notification-item:hover {
background: var(--bg-card);
transform: translateX(5px);
}
.notification-item.unread {
border-left-color: var(--accent-cyan);
}
.notification-item.priority-high {
border-left-color: var(--accent-red);
}
.notification-item.priority-medium {
border-left-color: var(--accent-orange);
}
.notification-item.priority-low {
border-left-color: var(--accent-green);
}
.notification-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: 8px;
}
.notification-category {
display: flex;
align-items: center;
gap: 8px;
}
.category-icon {
width: 32px;
height: 32px;
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
font-size: 1rem;
}
.category-alert { background: rgba(239, 68, 68, 0.2); }
.category-message { background: rgba(0, 212, 255, 0.2); }
.category-update { background: rgba(16, 185, 129, 0.2); }
.category-system { background: rgba(245, 158, 11, 0.2); }
.notification-time {
font-size: 0.75rem;
color: var(--text-secondary);
}
.notification-title {
font-weight: 600;
margin-bottom: 5px;
}
.notification-body {
font-size: 0.9rem;
color: var(--text-secondary);
line-height: 1.5;
}
/* Right Panel */
.controls-section {
margin-bottom: 20px;
}
.control-btn {
width: 100%;
padding: 12px;
border-radius: 10px;
border: none;
cursor: pointer;
font-weight: 600;
font-size: 0.9rem;
transition: all 0.3s ease;
margin-bottom: 10px;
}
.btn-primary {
background: linear-gradient(135deg, var(--accent-cyan), #0099cc);
color: var(--bg-primary);
}
.btn-primary:hover {
transform: translateY(-2px);
box-shadow: 0 5px 20px rgba(0, 212, 255, 0.4);
}
.btn-secondary {
background: var(--bg-secondary);
color: var(--text-primary);
border: 1px solid var(--border-color);
}
.btn-secondary:hover {
border-color: var(--accent-cyan);
}
.btn-danger {
background: rgba(239, 68, 68, 0.2);
color: var(--accent-red);
border: 1px solid var(--accent-red);
}
/* Stats Grid */
.stats-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin-top: 20px;
}
.stat-card {
background: var(--bg-secondary);
border-radius: 10px;
padding: 15px;
text-align: center;
}
.stat-number {
font-size: 1.8rem;
font-weight: 700;
background: linear-gradient(135deg, var(--accent-cyan), var(--accent-orange));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.stat-desc {
font-size: 0.75rem;
color: var(--text-secondary);
margin-top: 5px;
}
/* Rate Limiter */
.rate-limiter {
margin-top: 20px;
padding: 15px;
background: var(--bg-secondary);
border-radius: 10px;
}
.rate-title {
font-size: 0.9rem;
font-weight: 600;
margin-bottom: 12px;
}
.token-bucket {
display: flex;
gap: 4px;
margin-bottom: 10px;
}
.token {
width: 12px;
height: 20px;
border-radius: 3px;
background: var(--accent-cyan);
transition: all 0.3s ease;
}
.token.empty {
background: var(--border-color);
}
.token.refilling {
animation: refill 0.5s ease;
}
@keyframes refill {
0% { transform: scaleY(0); }
100% { transform: scaleY(1); }
}
.rate-info {
font-size: 0.8rem;
color: var(--text-secondary);
}
/* Priority Queue */
.priority-queue {
margin-top: 20px;
}
.queue-item {
display: flex;
align-items: center;
gap: 10px;
padding: 10px;
background: var(--bg-secondary);
border-radius: 8px;
margin-bottom: 8px;
font-size: 0.85rem;
}
.queue-priority {
width: 8px;
height: 8px;
border-radius: 50%;
}
.queue-waiting {
margin-left: auto;
font-size: 0.75rem;
color: var(--text-secondary);
}
/* Empty State */
.empty-state {
text-align: center;
padding: 40px 20px;
color: var(--text-secondary);
}
.empty-icon {
font-size: 3rem;
margin-bottom: 15px;
opacity: 0.5;
}
</style>
</head>
<body>
<canvas id="canvas-bg"></canvas>
<div class="app-container">
<!-- Left Panel - Connections & Budget -->
<div class="panel" id="left-panel">
<div class="panel-header">
<h2 class="panel-title">Connection Hub</h2>
</div>
<div class="connection-section">
<div class="connection-card" id="push-connection">
<div class="connection-header">
<span class="connection-name">
<span class="connection-dot dot-inactive" id="push-dot"></span>
Web Push
</span>
<span class="status-badge status-disconnected" id="push-status">Disconnected</span>
</div>
<div class="connection-stats">
<div class="stat-item">
<span class="stat-label">Sent</span>
<span class="stat-value" id="push-sent">0</span>
</div>
<div class="stat-item">
<span class="stat-label">Failed</span>
<span class="stat-value" id="push-failed">0</span>
</div>
</div>
</div>
<div class="connection-card" id="sse-connection">
<div class="connection-header">
<span class="connection-name">
<span class="connection-dot dot-fallback" id="sse-dot"></span>
SSE Fallback
</span>
<span class="status-badge status-fallback" id="sse-status">Standby</span>
</div>
<div class="connection-stats">
<div class="stat-item">
<span class="stat-label">Received</span>
<span class="stat-value" id="sse-received">0</span>
</div>
<div class="stat-item">
<span class="stat-label">Reconnects</span>
<span class="stat-value" id="sse-reconnects">0</span>
</div>
</div>
</div>
</div>
<div class="budget-section">
<div class="panel-header" style="margin-bottom: 15px; padding-bottom: 10px;">
<h3 class="panel-title" style="font-size: 1rem;">Subscription Budget</h3>
</div>
<div class="budget-item">
<div class="budget-header">
<span class="budget-name">Alerts</span>
<span class="budget-values"><span id="alerts-used">12</span>/50/hr</span>
</div>
<div class="budget-bar">
<div class="budget-fill safe" id="alerts-bar" style="width: 24%"></div>
</div>
</div>
<div class="budget-item">
<div class="budget-header">
<span class="budget-name">Messages</span>
<span class="budget-values"><span id="messages-used">89</span>/100/hr</span>
</div>
<div class="budget-bar">
<div class="budget-fill warning" id="messages-bar" style="width: 89%"></div>
</div>
</div>
<div class="budget-item">
<div class="budget-header">
<span class="budget-name">Updates</span>
<span class="budget-values"><span id="updates-used">195</span>/200/hr</span>
</div>
<div class="budget-bar">
<div class="budget-fill danger" id="updates-bar" style="width: 97.5%"></div>
</div>
</div>
<div class="budget-item">
<div class="budget-header">
<span class="budget-name">System</span>
<span class="budget-values"><span id="system-used">5</span>/20/hr</span>
</div>
<div class="budget-bar">
<div class="budget-fill safe" id="system-bar" style="width: 25%"></div>
</div>
</div>
</div>
</div>
<!-- Main Panel - Notification Feed -->
<div class="panel feed-container">
<div class="panel-header">
<h2 class="panel-title">Notification Feed</h2>
<span class="status-badge status-connected" id="live-badge">LIVE</span>
</div>
<div class="feed-filters">
<button class="filter-btn active" data-filter="all">All</button>
<button class="filter-btn" data-filter="alert">Alerts</button>
<button class="filter-btn" data-filter="message">Messages</button>
<button class="filter-btn" data-filter="update">Updates</button>
<button class="filter-btn" data-filter="system">System</button>
</div>
<div class="feed-list" id="feed-list">
<div class="empty-state" id="empty-state">
<div class="empty-icon">📭</div>
<p>No notifications yet</p>
<p style="font-size: 0.85rem; margin-top: 5px;">Click "Send Test Notification" to start</p>
</div>
</div>
</div>
<!-- Right Panel - Controls -->
<div class="panel">
<div class="panel-header">
<h2 class="panel-title">Controls</h2>
</div>
<div class="controls-section">
<button class="control-btn btn-primary" id="enable-push">Enable Web Push</button>
<button class="control-btn btn-secondary" id="test-notification">Send Test Notification</button>
<button class="control-btn btn-secondary" id="test-burst">Simulate Burst (10)</button>
<button class="control-btn btn-danger" id="clear-all">Clear All</button>
</div>
<div class="stats-grid">
<div class="stat-card">
<div class="stat-number" id="total-sent">0</div>
<div class="stat-desc">Total Sent</div>
</div>
<div class="stat-card">
<div class="stat-number" id="total-queued">0</div>
<div class="stat-desc">Queued</div>
</div>
<div class="stat-card">
<div class="stat-number" id="total-dropped">0</div>
<div class="stat-desc">Dropped</div>
</div>
<div class="stat-card">
<div class="stat-number" id="avg-latency">0ms</div>
<div class="stat-desc">Avg Latency</div>
</div>
</div>
<div class="rate-limiter">
<div class="rate-title">Token Bucket Rate Limiter</div>
<div class="token-bucket" id="token-bucket"></div>
<div class="rate-info">
<span id="rate-current">10</span>/10 tokens |
<span id="rate-refill">1</span>/sec refill
</div>
</div>
<div class="priority-queue">
<div class="panel-header" style="margin-bottom: 10px; padding-bottom: 8px;">
<h3 class="panel-title" style="font-size: 0.95rem;">Priority Queue</h3>
</div>
<div id="queue-list">
<div class="queue-item">
<span class="queue-priority" style="background: var(--accent-red);"></span>
<span>Server Alert #1</span>
<span class="queue-waiting">Waiting: 2s</span>
</div>
<div class="queue-item">
<span class="queue-priority" style="background: var(--accent-orange);"></span>
<span>Message from User</span>
<span class="queue-waiting">Waiting: 5s</span>
</div>
<div class="queue-item">
<span class="queue-priority" style="background: var(--accent-green);"></span>
<span>System Update</span>
<span class="queue-warning">Waiting: 8s</span>
</div>
</div>
</div>
</div>
</div>
<script>
// ============ Background Animation ============
const canvas = document.getElementById('canvas-bg');
const ctx = canvas.getContext('2d');
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
class Particle {
constructor() {
this.reset();
}
reset() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.size = Math.random() * 2 + 0.5;
this.speedX = (Math.random() - 0.5) * 0.5;
this.speedY = (Math.random() - 0.5) * 0.5;
this.opacity = Math.random() * 0.5 + 0.2;
this.hue = Math.random() > 0.5 ? 190 : 25; // Cyan or Orange
}
update() {
this.x += this.speedX;
this.y += this.speedY;
if (this.x < 0 || this.x > canvas.width ||
this.y < 0 || this.y > canvas.height) {
this.reset();
}
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = `hsla(${this.hue}, 100%, 60%, ${this.opacity})`;
ctx.fill();
}
}
const particles = Array.from({ length: 100 }, () => new Particle());
let mouseX = 0, mouseY = 0;
document.addEventListener('mousemove', (e) => {
mouseX = e.clientX;
mouseY = e.clientY;
});
function animateBackground() {
ctx.fillStyle = 'rgba(10, 15, 26, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw connections
particles.forEach((p1, i) => {
particles.slice(i + 1).forEach(p2 => {
const dx = p1.x - p2.x;
const dy = p1.y - p2.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < 100) {
ctx.beginPath();
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
ctx.strokeStyle = `rgba(0, 212, 255, ${0.1 * (1 - dist / 100)})`;
ctx.stroke();
}
});
// Mouse attraction
const dx = mouseX - p1.x;
const dy = mouseY - p1.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < 200 && dist > 0) {
p1.x += dx / dist * 0.5;
p1.y += dy / dist * 0.5;
}
p1.update();
p1.draw();
});
requestAnimationFrame(animateBackground);
}
animateBackground();
// ============ Notifications Hub ============
const NotificationsHub = {
// State
notifications: [],
queue: [],
pushEnabled: false,
sseActive: false,
// Stats
stats: {
pushSent: 0,
pushFailed: 0,
sseReceived: 0,
sseReconnects: 0,
totalSent: 0,
totalQueued: 0,
totalDropped: 0,
latencies: []
},
// Budget
budget: {
alerts: { used: 12, limit: 50 },
messages: { used: 89, limit: 100 },
updates: { used: 195, limit: 200 },
system: { used: 5, limit: 20 }
},
// Token bucket rate limiter
tokens: 10,
maxTokens: 10,
refillRate: 1000, // ms per token
// Categories
categories: {
alert: { icon: '⚠️', class: 'category-alert', priority: 'high' },
message: { icon: '💬', class: 'category-message', priority: 'medium' },
update: { icon: '🔄', class: 'category-update', priority: 'low' },
system: { icon: '⚙️', class: 'category-system', priority: 'low' }
},
// Initialize
init() {
this.setupEventListeners();
this.initTokenBucket();
this.initSSE();
this.startQueueProcessor();
this.startBudgetRefill();
},
setupEventListeners() {
document.getElementById('enable-push').addEventListener('click', () => this.togglePush());
document.getElementById('test-notification').addEventListener('click', () => this.sendTestNotification());
document.getElementById('test-burst').addEventListener('click', () => this.sendBurst());
document.getElementById('clear-all').addEventListener('click', () => this.clearAll());
document.querySelectorAll('.filter-btn').forEach(btn => {
btn.addEventListener('click', (e) => this.setFilter(e.target.dataset.filter));
});
},
// Token Bucket Rate Limiter
initTokenBucket() {
this.renderTokens();
setInterval(() => {
if (this.tokens < this.maxTokens) {
this.tokens++;
this.renderTokens(true);
}
}, this.refillRate);
},
renderTokens(animate = false) {
const bucket = document.getElementById('token-bucket');
bucket.innerHTML = '';
for (let i = 0; i < this.maxTokens; i++) {
const token = document.createElement('div');
token.className = 'token' + (i >= this.tokens ? ' empty' : '') +
(animate && i === this.tokens - 1 ? ' refilling' : '');
bucket.appendChild(token);
}
document.getElementById('rate-current').textContent = this.tokens;
},
consumeToken() {
if (this.tokens > 0) {
this.tokens--;
this.renderTokens();
return true;
}
return false;
},
// Web Push
async togglePush() {
const btn = document.getElementById('enable-push');
if (!this.pushEnabled) {
// Simulate requesting permission
btn.textContent = 'Requesting...';
btn.disabled = true;
await new Promise(r => setTimeout(r, 1500));
// Simulate success (in real app, would use Push API)
if (Math.random() > 0.2) {
this.pushEnabled = true;
this.updatePushUI(true);
btn.textContent = 'Disable Web Push';
btn.disabled = false;
btn.classList.remove('btn-primary');
btn.classList.add('btn-secondary');
this.showSystemNotification('Web Push Enabled', 'You will now receive push notifications');
} else {
// Fallback to SSE
this.activateSSE();
btn.textContent = 'Push Denied - Using SSE';
btn.disabled = true;
}
} else {
this.pushEnabled = false;
this.updatePushUI(false);
btn.textContent = 'Enable Web Push';
btn.classList.add('btn-primary');
btn.classList.remove('btn-secondary');
}
},
updatePushUI(connected) {
const dot = document.getElementById('push-dot');
const status = document.getElementById('push-status');
if (connected) {
dot.className = 'connection-dot dot-active';
status.className = 'status-badge status-connected';
status.textContent = 'Connected';
} else {
dot.className = 'connection-dot dot-inactive';
status.className = 'status-badge status-disconnected';
status.textContent = 'Disconnected';
}
},
// SSE Fallback
initSSE() {
// Simulate SSE connection
this.sseActive = false;
this.updateSSEUI('standby');
},
activateSSE() {
this.sseActive = true;
this.updateSSEUI('active');
// Simulate SSE events
this.sseInterval = setInterval(() => {
if (this.sseActive && Math.random() > 0.7) {
this.stats.sseReceived++;
document.getElementById('sse-received').textContent = this.stats.sseReceived;
}
}, 2000);
},
updateSSEUI(state) {
const dot = document.getElementById('sse-dot');
const status = document.getElementById('sse-status');
if (state === 'active') {
dot.className = 'connection-dot dot-active';
status.className = 'status-badge status-connected';
status.textContent = 'Active';
} else if (state === 'standby') {
dot.className = 'connection-dot dot-fallback';
status.className = 'status-badge status-fallback';
status.textContent = 'Standby';
}
},
// Queue Processor
startQueueProcessor() {
setInterval(() => {
this.processQueue();
this.updateQueueUI();
}, 500);
},
processQueue() {
if (this.queue.length === 0) return;
if (this.consumeToken()) {
const notification = this.queue.shift();
this.deliverNotification(notification);
} else {
// Rate limited - check for drops
const now = Date.now();
this.queue = this.queue.filter(n => {
if (now - n.timestamp > 30000) { // 30s timeout
this.stats.totalDropped++;
document.getElementById('total-dropped').textContent = this.stats.totalDropped;
return false;
}
return true;
});
}
},
// Budget Management
checkBudget(category) {
const budget = this.budget[category];
if (!budget) return true;
const key = Object.keys(this.budget).find(k =>
k === category || (category.includes(k.slice(0, -1)))
);
if (budget.used >= budget.limit) {
return false;
}
return true;
},
incrementBudget(category) {
const mapping = {
'alert': 'alerts',
'message': 'messages',
'update': 'updates',
'system': 'system'
};
const key = mapping[category] || category;
if (this.budget[key]) {
this.budget[key].used++;
this.updateBudgetUI();
}
},
updateBudgetUI() {
Object.entries(this.budget).forEach(([key, data]) => {
const percent = (data.used / data.limit) * 100;
const bar = document.getElementById(`${key}-bar`);
const used = document.getElementById(`${key}-used`);
if (bar) {
bar.style.width = `${percent}%`;
bar.className = 'budget-fill ' +
(percent < 60 ? 'safe' : percent < 85 ? 'warning' : 'danger');
}
if (used) used.textContent = data.used;
});
},
startBudgetRefill() {
// Simulate hourly refill (every 10 seconds for demo)
setInterval(() => {
Object.keys(this.budget).forEach(key => {
this.budget[key].used = Math.max(0, this.budget[key].used - 5);
});
this.updateBudgetUI();
}, 10000);
},
// Send Notifications
sendTestNotification() {
const categories = ['alert', 'message', 'update', 'system'];
const category = categories[Math.floor(Math.random() * categories.length)];
const titles = {
alert: ['Server Down', 'High CPU Usage', 'Memory Warning', 'Security Alert'],
message: ['New Message', 'Mention', 'Direct Message', 'Group Chat'],
update: ['Update Available', 'Sync Complete', 'Backup Done', 'Cache Cleared'],
system: ['Maintenance', 'Scheduled Downtime', 'New Feature', 'Policy Update']
};
const bodies = {
alert: ['Server cluster-alpha is not responding', 'CPU usage exceeded 90% threshold',
'Memory usage is critically high', 'Unusual login activity detected'],
message: ['You have a new message from John', '@admin mentioned you in #general',
'Sarah sent you a direct message', 'New activity in Project Alpha'],
update: ['Version 2.5.1 is now available', 'All files have been synchronized',
'Daily backup completed successfully', 'Application cache has been cleared'],
system: ['Scheduled maintenance at 2:00 AM UTC', 'Service will be unavailable for 30 minutes',
'Introducing new dashboard features', 'Please review updated terms of service']
};
const tIdx = Math.floor(Math.random() * titles[category].length);
this.queueNotification({
id: Date.now(),
category,
title: titles[category][tIdx],
body: bodies[category][tIdx],
priority: this.categories[category].priority,
timestamp: Date.now()
});
},
sendBurst() {
for (let i = 0; i < 10; i++) {
setTimeout(() => this.sendTestNotification(), i * 100);
}
},
queueNotification(notification) {
// Check budget
const budgetKey = notification.category + 's';
if (!this.checkBudget(notification.category)) {
this.stats.totalDropped++;
document.getElementById('total-dropped').textContent = this.stats.totalDropped;
return;
}
this.queue.push(notification);
this.stats.totalQueued++;
document.getElementById('total-queued').textContent = this.stats.totalQueued;
// Sort by priority
const priorityOrder = { high: 0, medium: 1, low: 2 };
this.queue.sort((a, b) => priorityOrder[a.priority] - priorityOrder[b.priority]);
},
deliverNotification(notification) {
const start = performance.now();
// Simulate delivery
if (this.pushEnabled) {
this.stats.pushSent++;
document.getElementById('push-sent').textContent = this.stats.pushSent;
// Try actual browser notification
if (Notification.permission === 'granted') {
new Notification(notification.title, { body: notification.body });
}
} else if (this.sseActive) {
this.stats.sseReceived++;
document.getElementById('sse-received').textContent = this.stats.sseReceived;
}
// Add to feed
this.addNotificationToFeed(notification);
this.incrementBudget(notification.category);
this.stats.totalSent++;
document.getElementById('total-sent').textContent = this.stats.totalSent;
// Track latency
const latency = Math.round(performance.now() - start);
this.stats.latencies.push(latency);
if (this.stats.latencies.length > 100) this.stats.latencies.shift();
const avgLatency = Math.round(
this.stats.latencies.reduce((a, b) => a + b, 0) / this.stats.latencies.length
);
document.getElementById('avg-latency').textContent = avgLatency + 'ms';
},
addNotificationToFeed(notification) {
this.notifications.unshift(notification);
const feedList = document.getElementById('feed-list');
const emptyState = document.getElementById('empty-state');
if (emptyState) emptyState.remove();
const cat = this.categories[notification.category];
const timeAgo = 'Just now';
const item = document.createElement('div');
item.className = `notification-item unread priority-${notification.priority}`;
item.dataset.category = notification.category;
item.innerHTML = `
<div class="notification-header">
<div class="notification-category">
<div class="category-icon ${cat.class}">${cat.icon}</div>
<span style="font-size: 0.8rem; color: var(--text-secondary); text-transform: capitalize;">${notification.category}</span>
</div>
<span class="notification-time">${timeAgo}</span>
</div>
<div class="notification-title">${notification.title}</div>
<div class="notification-body">${notification.body}</div>
`;
item.addEventListener('click', () => {
item.classList.remove('unread');
});
feedList.insertBefore(item, feedList.firstChild);
// Limit feed size
while (feedList.children.length > 50) {
feedList.removeChild(feedList.lastChild);
}
},
updateQueueUI() {
const queueList = document.getElementById('queue-list');
if (this.queue.length === 0) {
queueList.innerHTML = `
<div class="queue-item" style="justify-content: center; color: var(--text-secondary);">
Queue empty
</div>
`;
return;
}
const colors = {
high: 'var(--accent-red)',
medium: 'var(--accent-orange)',
low: 'var(--accent-green)'
};
queueList.innerHTML = this.queue.slice(0, 5).map((n, i) => {
const waitTime = Math.round((Date.now() - n.timestamp) / 1000);
return `
<div class="queue-item">
<span class="queue-priority" style="background: ${colors[n.priority]};"></span>
<span>${n.title}</span>
<span class="queue-waiting">Waiting: ${waitTime}s</span>
</div>
`;
}).join('');
},
showSystemNotification(title, body) {
this.addNotificationToFeed({
id: Date.now(),
category: 'system',
title,
body,
priority: 'low',
timestamp: Date.now()
});
},
setFilter(filter) {
document.querySelectorAll('.filter-btn').forEach(btn => {
btn.classList.toggle('active', btn.dataset.filter === filter);
});
document.querySelectorAll('.notification-item').forEach(item => {
if (filter === 'all' || item.dataset.category === filter) {
item.style.display = 'block';
} else {
item.style.display = 'none';
}
});
},
clearAll() {
this.notifications = [];
this.queue = [];
document.getElementById('feed-list').innerHTML = `
<div class="empty-state" id="empty-state">
<div class="empty-icon">📭</div>
<p>No notifications yet</p>
<p style="font-size: 0.85rem; margin-top: 5px;">Click "Send Test Notification" to start</p>
</div>
`;
this.updateQueueUI();
}
};
// Initialize
NotificationsHub.init();
// Request notification permission
if ('Notification' in window && Notification.permission === 'default') {
Notification.requestPermission();
}
</script>
</body>
</html>
How It Works:
1. Web Push Integration
- Click "Enable Web Push" to simulate subscribing to push notifications
- If granted, native browser notifications will appear
- Tracks sent/failed counts in real-time
2. SSE Fallback
- Automatically activates when Web Push is denied
- Maintains persistent connection simulation
- Tracks received messages and reconnection attempts
3. Subscription Budgeting
- Each category has hourly limits (Alerts: 50, Messages: 100, Updates: 200, System: 20)
- Visual progress bars show usage with color-coded warnings
- Budgets auto-refill over time (simulated every 10 seconds)
4. Token Bucket Rate Limiter
- Visual representation of 10 tokens
- Tokens refill at 1/second
- Notifications queue when tokens depleted
- Dropped if waiting > 30 seconds
5. Priority Queue
- High priority (red): Alerts
- Medium priority (orange): Messages
- Low priority (green): Updates, System
- Queue automatically sorted by priority