Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | // src/components/NotificationToastHandler.tsx
/**
* Global notification toast handler
* Listens for WebSocket notifications and displays them as toasts
* Should be rendered once at the app root level
*/
import { useCallback, useEffect } from 'react';
import { useWebSocket } from '../hooks/useWebSocket';
import { useEventBus } from '../hooks/useEventBus';
import toast from 'react-hot-toast';
import type { DealNotificationData, SystemMessageData } from '../types/websocket';
import { formatCurrency } from '../utils/formatUtils';
interface NotificationToastHandlerProps {
/**
* Whether to enable toast notifications
* @default true
*/
enabled?: boolean;
/**
* Whether to play a sound when notifications arrive
* @default false
*/
playSound?: boolean;
/**
* Custom sound URL (if playSound is true)
*/
soundUrl?: string;
}
export function NotificationToastHandler({
enabled = true,
playSound = false,
soundUrl = '/notification-sound.mp3',
}: NotificationToastHandlerProps) {
// Connect to WebSocket
const { isConnected, error } = useWebSocket({
autoConnect: true,
onConnect: () => {
if (enabled) {
toast.success('Connected to live notifications', {
duration: 2000,
icon: 'đĸ',
});
}
},
onDisconnect: () => {
if (enabled && error) {
toast.error('Disconnected from live notifications', {
duration: 3000,
icon: 'đ´',
});
}
},
});
// Play notification sound
const playNotificationSound = useCallback(() => {
if (!playSound) return;
try {
const audio = new Audio(soundUrl);
audio.volume = 0.3;
audio.play().catch((error) => {
console.warn('Failed to play notification sound:', error);
});
} catch (error) {
console.warn('Failed to play notification sound:', error);
}
}, [playSound, soundUrl]);
// Handle deal notifications
const handleDealNotification = useCallback(
(data?: DealNotificationData) => {
if (!enabled || !data) return;
playNotificationSound();
const dealsCount = data.deals.length;
const firstDeal = data.deals[0];
// Show toast with deal information
toast.success(
<div className="flex flex-col gap-1">
<div className="font-semibold">
{dealsCount === 1 ? 'New Deal Found!' : `${dealsCount} New Deals Found!`}
</div>
{dealsCount === 1 && firstDeal && (
<div className="text-sm text-gray-600 dark:text-gray-400">
{firstDeal.item_name} for {formatCurrency(firstDeal.best_price_in_cents)} at{' '}
{firstDeal.store_name}
</div>
)}
{dealsCount > 1 && (
<div className="text-sm text-gray-600 dark:text-gray-400">
Check your deals page to see all offers
</div>
)}
</div>,
{
duration: 5000,
icon: 'đ',
position: 'top-right',
},
);
},
[enabled, playNotificationSound],
);
// Handle system messages
const handleSystemMessage = useCallback(
(data?: SystemMessageData) => {
if (!enabled || !data) return;
const toastOptions = {
duration: data.severity === 'error' ? 6000 : 4000,
position: 'top-center' as const,
};
switch (data.severity) {
case 'error':
toast.error(data.message, { ...toastOptions, icon: 'â' });
break;
case 'warning':
toast(data.message, { ...toastOptions, icon: 'â ī¸' });
break;
case 'info':
default:
toast(data.message, { ...toastOptions, icon: 'âšī¸' });
break;
}
},
[enabled],
);
// Handle errors
const handleError = useCallback(
(data?: { message: string; code?: string }) => {
if (!enabled || !data) return;
toast.error(`Error: ${data.message}`, {
duration: 5000,
icon: 'đ¨',
});
},
[enabled],
);
// Subscribe to event bus
useEventBus('notification:deal', handleDealNotification);
useEventBus('notification:system', handleSystemMessage);
useEventBus('notification:error', handleError);
// Show connection error if persistent
useEffect(() => {
if (error && !isConnected) {
// Only show after a delay to avoid showing on initial connection
const timer = setTimeout(() => {
if (error && !isConnected && enabled) {
toast.error('Unable to connect to live notifications. Some features may be limited.', {
duration: 5000,
icon: 'â ī¸',
});
}
}, 5000);
return () => clearTimeout(timer);
}
}, [error, isConnected, enabled]);
// This component doesn't render anything - it just handles side effects
return null;
}
|