| // components/notifications/NotificationDropdown.tsx | |
| "use client"; | |
| import { useNavigate } from "react-router-dom"; | |
| import { useState, useEffect, useRef, useCallback } from "react"; | |
| import api from "@/lib/api"; | |
| import { useToast } from "@/context/ToastContext"; | |
| import { useWebSocket } from "@/hooks/useWebSocket"; | |
| import { useAuth } from "@/context/AuthContext"; | |
| import { Notification } from "@/types"; | |
| const normalizeNotifications = (value: unknown): Notification[] => { | |
| if (Array.isArray(value)) return value as Notification[]; | |
| if (value && typeof value === "object") { | |
| const payload = value as { notifications?: unknown; items?: unknown; recentNotifications?: unknown }; | |
| if (Array.isArray(payload.notifications)) return payload.notifications as Notification[]; | |
| if (Array.isArray(payload.items)) return payload.items as Notification[]; | |
| if (Array.isArray(payload.recentNotifications)) return payload.recentNotifications as Notification[]; | |
| } | |
| return []; | |
| }; | |
| export function NotificationDropdown() { | |
| const { user } = useAuth(); | |
| const navigate = useNavigate(); | |
| const { addToast } = useToast(); | |
| const [open, setOpen] = useState(false); | |
| const [notifications, setNotifications] = useState<Notification[]>([]); | |
| const [unreadCount, setUnreadCount] = useState(0); | |
| const [loadingRecent, setLoadingRecent] = useState(false); | |
| const dropdownRef = useRef<HTMLDivElement>(null); | |
| const fetchUnreadCount = useCallback(async () => { | |
| if (!user) return; | |
| try { | |
| const res = await api.get("/notifications/unread-count"); | |
| setUnreadCount(res.data.unreadCount ?? res.data.count ?? res.data?.byType?.message ?? 0); | |
| } catch {} | |
| }, [user]); | |
| const fetchRecent = useCallback(async () => { | |
| if (!user) return; | |
| setLoadingRecent(true); | |
| try { | |
| const res = await api.get("/notifications", { params: { page: 0, size: 6 } }); | |
| const payload = res.data?.notifications ?? res.data?.recentNotifications ?? res.data; | |
| setNotifications(normalizeNotifications(payload)); | |
| } catch (err) { | |
| console.error(err); | |
| } finally { | |
| setLoadingRecent(false); | |
| } | |
| }, [user]); | |
| const handleWsMessage = useCallback((data: any) => { | |
| if (data.type === "new_notification") { | |
| fetchUnreadCount(); | |
| if (open) fetchRecent(); | |
| } | |
| }, [fetchUnreadCount, open, fetchRecent]); | |
| useWebSocket(handleWsMessage); | |
| useEffect(() => { | |
| fetchUnreadCount(); | |
| }, [user, fetchUnreadCount]); | |
| useEffect(() => { | |
| if (open) fetchRecent(); | |
| }, [open, fetchRecent]); | |
| useEffect(() => { | |
| const handler = (e: MouseEvent) => { | |
| if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) { | |
| setOpen(false); | |
| } | |
| }; | |
| document.addEventListener("mousedown", handler); | |
| return () => document.removeEventListener("mousedown", handler); | |
| }, []); | |
| const markRead = async (id: number) => { | |
| const notif = notifications.find(n => n.id === id); | |
| if (!notif || notif.read) return; | |
| try { | |
| await api.put(`/notifications/${id}/read`); | |
| setNotifications(prev => prev.map(n => n.id === id ? { ...n, read: true } : n)); | |
| setUnreadCount(c => Math.max(0, c - 1)); | |
| } catch (err) { | |
| console.error(err); | |
| } | |
| }; | |
| const handleNotificationClick = (notif: Notification) => { | |
| markRead(notif.id); | |
| setOpen(false); | |
| if (notif.type === "message" || notif.type === "group_message") { | |
| navigate("/messages"); | |
| } else if (notif.articleId) { | |
| navigate(`/articles/${notif.articleId}`); | |
| } else if (notif.type === "follow" && notif.fromUser) { | |
| navigate(`/users/${notif.fromUser}`); | |
| } else { | |
| navigate("/notifications"); | |
| } | |
| }; | |
| return ( | |
| <div className="relative" ref={dropdownRef}> | |
| <button | |
| onClick={() => setOpen(!open)} | |
| className="relative p-2 rounded-full hover:bg-white/10 text-slate-300 hover:text-white transition-all active:scale-95" | |
| aria-label="Notifications" | |
| > | |
| <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"> | |
| <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" /> | |
| </svg> | |
| {unreadCount > 0 && ( | |
| <span className="absolute -top-0.5 -right-0.5 bg-red-500 text-white text-[10px] font-bold rounded-full h-4 min-w-[16px] flex items-center justify-center px-1 animate-pulse"> | |
| {unreadCount > 9 ? "9+" : unreadCount} | |
| </span> | |
| )} | |
| </button> | |
| {open && ( | |
| <div className="absolute right-0 mt-2 w-80 rounded-2xl shadow-2xl z-50 border border-white/10 bg-slate-950/90 backdrop-blur-xl overflow-hidden animate-fadeIn text-slate-200"> | |
| <div className="p-4 border-b border-white/10 font-bold text-white flex justify-between items-center bg-slate-950/40"> | |
| <span className="text-sm tracking-wide">Notifications</span> | |
| {unreadCount > 0 && ( | |
| <span className="text-[10px] font-bold uppercase tracking-wider text-teal-400 bg-teal-400/15 px-2 py-0.5 rounded-md">{unreadCount} new</span> | |
| )} | |
| </div> | |
| <div className="max-h-80 overflow-y-auto scrollbar-thin"> | |
| {loadingRecent ? ( | |
| <div className="p-8 text-center text-slate-500 text-xs">Loading recent notifications...</div> | |
| ) : notifications.length === 0 ? ( | |
| <div className="p-8 text-center text-slate-500"> | |
| <div className="text-4xl mb-2 opacity-50">🔔</div> | |
| <p className="text-xs font-semibold text-slate-400">All caught up</p> | |
| <p className="mt-1 text-[10px] text-slate-500">Activity updates will appear here.</p> | |
| </div> | |
| ) : ( | |
| notifications.map(n => ( | |
| <div | |
| key={n.id} | |
| onClick={() => handleNotificationClick(n)} | |
| className={`p-3.5 cursor-pointer hover:bg-white/5 transition-all flex items-start gap-3 border-b border-white/5 ${ | |
| !n.read ? "bg-teal-500/5" : "" | |
| }`} | |
| > | |
| <div className="w-8 h-8 rounded-lg bg-slate-900 border border-white/5 flex items-center justify-center text-sm shrink-0"> | |
| {n.type === "message" || n.type === "group_message" ? "💬" : | |
| n.type === "follow" ? "👤" : | |
| n.type === "like" ? "❤️" : | |
| n.type === "comment" ? "💭" : "📣"} | |
| </div> | |
| <div className="flex-1 min-w-0"> | |
| <p className={`text-xs truncate ${!n.read ? "text-slate-100 font-semibold" : "text-slate-400"}`}> | |
| {(n as any).message || (n as any).title || (n as any).body} | |
| </p> | |
| <p className="text-[10px] text-slate-500 mt-1"> | |
| {new Date(n.createdAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })} | |
| </p> | |
| </div> | |
| {!n.read && ( | |
| <span className="w-1.5 h-1.5 bg-teal-400 rounded-full mt-2 shrink-0 animate-pulse"></span> | |
| )} | |
| </div> | |
| )) | |
| )} | |
| </div> | |
| <button | |
| onClick={() => { | |
| setOpen(false); | |
| navigate("/notifications"); | |
| }} | |
| className="block w-full text-center py-3 text-xs font-semibold text-teal-400 hover:text-teal-300 hover:bg-white/5 transition-all border-t border-white/10" | |
| > | |
| View all notifications | |
| </button> | |
| </div> | |
| )} | |
| </div> | |
| ); | |
| } | |
Xet Storage Details
- Size:
- 7.83 kB
- Xet hash:
- 400d3678444e39634db41d27752bd5fb67d4cfbd4a6773d79fed00616f843c8f
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.