feat(notifications): add navbar dropdown and sse client

This commit is contained in:
2026-04-25 11:29:53 +03:30
parent 441cc0c008
commit 2d903de97b
10 changed files with 1098 additions and 242 deletions

View File

@@ -4,6 +4,7 @@ import { LanguageProvider } from "./components/LanguageProvider"
import { Toaster } from "./components/ui/toaster"
import { Navbar } from "./components/Navbar"
import { Sidebar } from './components/Sidebar';
import { NotificationsProvider } from "./context/NotificationsContext"
import { WorkspaceProvider } from "./context/WorkspaceContext"
import Auth from "./pages/Auth"
import Profile from "./pages/Profile"
@@ -75,7 +76,9 @@ function App() {
return (
<ThemeProvider>
<LanguageProvider>
<RouterProvider router={router} />
<NotificationsProvider>
<RouterProvider router={router} />
</NotificationsProvider>
<Toaster />
</LanguageProvider>
</ThemeProvider>

View File

@@ -1,4 +1,10 @@
import { API_BASE_URL } from "../config/constants"
import {
clearSessionTokens,
emitSessionChanged,
getAccessToken,
getRefreshToken,
} from "../lib/session"
let refreshRequest: Promise<string | null> | null = null
@@ -40,8 +46,7 @@ const normalizeJsonResponse = (response: Response) => {
}
const clearSessionAndRedirect = () => {
localStorage.removeItem("accessToken")
localStorage.removeItem("refreshToken")
clearSessionTokens()
if (window.location.pathname !== "/auth") {
window.location.href = "/auth"
}
@@ -58,7 +63,7 @@ const shouldAttemptRefresh = (endpoint: string) => {
}
const refreshAccessToken = async () => {
const refreshToken = localStorage.getItem("refreshToken")
const refreshToken = getRefreshToken()
if (!refreshToken) return null
if (!refreshRequest) {
@@ -87,6 +92,7 @@ const refreshAccessToken = async () => {
if (nextRefreshToken) {
localStorage.setItem("refreshToken", nextRefreshToken)
}
emitSessionChanged()
return nextAccessToken
})().finally(() => {
@@ -98,7 +104,7 @@ const refreshAccessToken = async () => {
}
export const authFetch = async (endpoint: string, options: RequestInit = {}, allowRetry = true): Promise<Response> => {
const token = localStorage.getItem("accessToken")
const token = getAccessToken()
const isFormData = options.body instanceof FormData
const headers: HeadersInit = {

108
src/api/notifications.ts Normal file
View File

@@ -0,0 +1,108 @@
import { API_BASE_URL } from "../config/constants"
import { authFetch } from "./client"
export type NotificationLevel = "info" | "success" | "warning" | "error"
export interface NotificationItem {
id: string
type: string
title: string
message: string
level: NotificationLevel
created_at: string
is_seen: boolean
delete_on_seen: boolean
action_url?: string | null
entity_type?: string | null
entity_id?: string | null
meta?: Record<string, unknown>
}
export interface NotificationsResponse {
count: number
unread_count: number
notifications: NotificationItem[]
}
export interface NotificationStreamTokenResponse {
token: string
expires_in: number
}
export interface NotificationFilters {
limit?: number
offset?: number
type?: string
}
const buildSearchParams = (filters: NotificationFilters = {}) => {
const searchParams = new URLSearchParams()
if (typeof filters.limit === "number") {
searchParams.set("limit", String(filters.limit))
}
if (typeof filters.offset === "number") {
searchParams.set("offset", String(filters.offset))
}
if (filters.type) {
searchParams.set("type", filters.type)
}
const query = searchParams.toString()
return query ? `?${query}` : ""
}
export const getNotifications = async (
filters: NotificationFilters = {},
): Promise<NotificationsResponse> => {
const response = await authFetch(`/api/notifications/list/${buildSearchParams(filters)}`)
if (!response.ok) {
throw new Error("Failed to load notifications")
}
return response.json()
}
export const markNotificationSeen = async (id: string) => {
const response = await authFetch("/api/notifications/seen/", {
method: "POST",
body: JSON.stringify({ id }),
})
if (!response.ok) {
throw new Error("Failed to mark notification as read")
}
return response.json()
}
export const deleteNotification = async (id: string) => {
const response = await authFetch(`/api/notifications/${id}/`, {
method: "DELETE",
})
if (!response.ok) {
throw new Error("Failed to delete notification")
}
return response.json()
}
export const markAllNotificationsRead = async (type?: string) => {
const response = await authFetch(`/api/notifications/seen/all/${buildSearchParams({ type })}`, {
method: "POST",
body: JSON.stringify(type ? { type } : {}),
})
if (!response.ok) {
throw new Error("Failed to mark all notifications as read")
}
return response.json()
}
export const issueNotificationStreamToken = async (): Promise<NotificationStreamTokenResponse> => {
const response = await authFetch("/api/notifications/stream-token/", {
method: "POST",
})
if (!response.ok) {
throw new Error("Failed to issue notification stream token")
}
return response.json()
}
export const buildNotificationStreamUrl = (token: string) => {
const cleanBaseUrl = API_BASE_URL.replace(/\/+$/, "")
return `${cleanBaseUrl}/api/notifications/stream/?token=${encodeURIComponent(token)}`
}

View File

@@ -1,228 +1,244 @@
import { useState, useEffect, useRef } from "react"
import { useNavigate } from "react-router-dom"
import { useTranslation } from "../hooks/useTranslation"
import { Button } from "./ui/button"
import { SettingsMenu } from "./SettingsMenu"
import { LogOut, User, Moon, Sun, Globe, Command } from "lucide-react"
import { logoutUser, getUserProfile } from "../api/users"
import { WorkspaceSelector } from "./WorkspaceSelector"
import { toast } from "sonner"
export function Navbar() {
const { t, lang, setLanguage } = useTranslation()
const navigate = useNavigate()
const [showLogoutModal, setShowLogoutModal] = useState(false)
const [isDropdownOpen, setIsDropdownOpen] = useState(false)
const [user, setUser] = useState<any>(null)
const dropdownRef = useRef<HTMLDivElement>(null)
const isFa = lang === 'fa';
const [isDarkMode, setIsDarkMode] = useState(() => {
const savedTheme = localStorage.getItem('theme');
if (savedTheme) return savedTheme === 'dark';
return document.documentElement.classList.contains('dark');
});
useEffect(() => {
const handleProfileUpdated = ((e: CustomEvent) => {
if (e.detail) {
setUser((prev: any) => prev ? { ...prev, ...e.detail } : e.detail);
}
}) as EventListener;
window.addEventListener('profile_updated', handleProfileUpdated);
return () => window.removeEventListener('profile_updated', handleProfileUpdated);
}, []);
useEffect(() => {
if (isDarkMode) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
}, [isDarkMode]);
useEffect(() => {
const fetchUser = async () => {
const token = localStorage.getItem("accessToken")
if (!token) return
try {
const userData = await getUserProfile()
setUser(userData)
} catch (error) {
console.error("Failed to fetch user profile:", error)
}
}
fetchUser()
}, [])
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
setIsDropdownOpen(false)
}
}
document.addEventListener("mousedown", handleClickOutside)
return () => document.removeEventListener("mousedown", handleClickOutside)
}, [])
const handleLogout = async () => {
try {
const refreshToken = localStorage.getItem("refreshToken")
if (refreshToken) {
await logoutUser(refreshToken)
}
} catch (error) {
console.error("Logout API failed:", error)
} finally {
localStorage.removeItem("accessToken")
localStorage.removeItem("refreshToken")
setUser(null)
setShowLogoutModal(false)
toast.success(t.logoutToast || "Successfully logged out!")
navigate("/auth")
}
}
const toggleTheme = () => {
const newThemeState = !isDarkMode;
setIsDarkMode(newThemeState);
localStorage.setItem('theme', newThemeState ? 'dark' : 'light');
};
const toggleLanguage = () => {
const newLang = isFa ? 'en' : 'fa'
if (setLanguage) {
setLanguage(newLang)
} else {
localStorage.setItem('language', newLang)
window.location.reload()
}
}
return (
<>
<header className="sticky top-0 z-50 border-b border-slate-200/80 dark:border-slate-800/80 bg-white/70 dark:bg-slate-900/70 backdrop-blur-md px-8 py-6 flex items-center justify-between transition-colors">
<div
className="flex items-center gap-2 cursor-pointer"
onClick={() => navigate("/")}
>
<span className="relative z-20 flex items-center gap-2 font-bold text-xl tracking-tight text-slate-900 dark:text-slate-50">
<Command className="h-7 w-7" />
{t.title || "Qlockify"}
</span>
</div>
<div className="flex items-center gap-4">
{user && <WorkspaceSelector />}
{user ? (
<div className="relative" ref={dropdownRef}>
<button
onClick={() => setIsDropdownOpen(!isDropdownOpen)}
className="w-12 h-12 rounded-full overflow-hidden border-2 border-slate-200 dark:border-slate-700 hover:border-blue-500 dark:hover:border-blue-500 transition-all focus:outline-none"
>
{user.profile_picture ? (
<img
src={user.profile_picture}
alt="Profile"
className="w-full h-full object-cover"
/>
) : (
<div className="w-full h-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center text-sm font-bold text-slate-600 dark:text-slate-300 uppercase">
{user.first_name?.[0] || user.email?.[0] || "U"}
</div>
)}
</button>
{isDropdownOpen && (
<div dir='rtl' className={`absolute ${isFa ? 'left-0' : 'right-0'} mt-2 w-56 rounded-lg bg-white dark:bg-slate-900 shadow-lg ring-1 ring-black ring-opacity-5 border border-slate-200 dark:border-slate-800 z-50 py-2 overflow-hidden`}>
<div className="px-4 py-2 mb-2 border-b border-slate-100 dark:border-slate-800">
<p className="text-sm font-semibold text-slate-800 dark:text-slate-400 truncate">
{user.first_name || user.last_name
? `${user.first_name || ''} ${user.last_name || ''}`.trim()
: user.email}
</p>
</div>
<button
onClick={() => { navigate("/profile"); setIsDropdownOpen(false); }}
className="flex w-full items-center gap-3 px-4 py-2.5 text-sm text-slate-700 dark:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
>
<User className="h-4 w-4" />
<span>{t.profile?.title || "Profile"}</span>
</button>
<button
onClick={toggleTheme}
className="flex w-full items-center gap-3 px-4 py-2.5 text-sm text-slate-700 dark:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
>
{isDarkMode ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
<span>{isDarkMode ? (t.lightMode || "Light Mode") : (t.darkMode || "Dark Mode")}</span>
</button>
<button
onClick={toggleLanguage}
className="flex w-full items-center gap-3 px-4 py-2.5 text-sm text-slate-700 dark:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
>
<Globe className="h-4 w-4" />
<span>{isFa ? "English" : "فارسی"}</span>
</button>
<div className="h-px bg-slate-200 dark:bg-slate-800 my-1"></div>
<button
onClick={() => { setShowLogoutModal(true); setIsDropdownOpen(false); }}
className="flex w-full items-center gap-3 px-4 py-2.5 text-sm text-red-600 dark:text-red-500 hover:bg-red-50 dark:hover:bg-red-950/50 transition-colors font-medium"
>
<LogOut className="h-4 w-4" />
<span>{t.logout || "Logout"}</span>
</button>
</div>
)}
</div>
) : (
<>
<SettingsMenu />
<Button
onClick={() => navigate("/auth")}
className="bg-blue-600 text-white hover:bg-blue-700 dark:bg-blue-600 dark:hover:bg-blue-700"
>
{t.login?.signIn || "Login"}
</Button>
</>
)}
</div>
</header>
{showLogoutModal && (
<div className="fixed inset-0 z-60 flex items-center justify-center bg-black/50 px-4" onClick={() => setShowLogoutModal(false)}>
<div className="w-full max-w-sm rounded-lg bg-white p-6 shadow-lg dark:bg-slate-900 border dark:border-slate-800" onClick={(e) => e.stopPropagation()}>
<h2 className="mb-2 text-lg font-bold text-slate-900 dark:text-white">
{t.confirmLogoutTitle || "Confirm Logout"}
</h2>
<p className="mb-6 text-slate-600 dark:text-slate-400">
{t.confirmLogoutMessage || "Are you sure you want to log out of your account?"}
</p>
<div className="flex justify-end gap-3">
<Button
variant="outline"
onClick={() => setShowLogoutModal(false)}
className="dark:text-white"
>
{t.actions?.cancel || "Cancel"}
</Button>
<Button
variant="destructive"
onClick={handleLogout}
className="bg-red-500 text-white hover:bg-red-600 dark:bg-red-600 dark:hover:bg-red-700"
>
{t.logout || "Logout"}
</Button>
</div>
</div>
</div>
)}
</>
)
}
import { useState, useEffect, useRef } from "react"
import { useNavigate } from "react-router-dom"
import { useTranslation } from "../hooks/useTranslation"
import { Button } from "./ui/button"
import { SettingsMenu } from "./SettingsMenu"
import { LogOut, User, Moon, Sun, Globe, Command } from "lucide-react"
import { logoutUser, getUserProfile } from "../api/users"
import { WorkspaceSelector } from "./WorkspaceSelector"
import { toast } from "sonner"
import { NotificationBell } from "./notifications/NotificationBell"
import { clearSessionTokens, getAccessToken, getRefreshToken } from "../lib/session"
export function Navbar() {
const { t, lang, setLanguage } = useTranslation()
const navigate = useNavigate()
const [showLogoutModal, setShowLogoutModal] = useState(false)
const [isDropdownOpen, setIsDropdownOpen] = useState(false)
const [user, setUser] = useState<any>(null)
const dropdownRef = useRef<HTMLDivElement>(null)
const isFa = lang === "fa"
const [isDarkMode, setIsDarkMode] = useState(() => {
const savedTheme = localStorage.getItem("theme")
if (savedTheme) return savedTheme === "dark"
return document.documentElement.classList.contains("dark")
})
useEffect(() => {
const handleProfileUpdated = ((e: CustomEvent) => {
if (e.detail) {
setUser((prev: any) => (prev ? { ...prev, ...e.detail } : e.detail))
}
}) as EventListener
window.addEventListener("profile_updated", handleProfileUpdated)
return () => window.removeEventListener("profile_updated", handleProfileUpdated)
}, [])
useEffect(() => {
if (isDarkMode) {
document.documentElement.classList.add("dark")
} else {
document.documentElement.classList.remove("dark")
}
}, [isDarkMode])
useEffect(() => {
const fetchUser = async () => {
const token = getAccessToken()
if (!token) return
try {
const userData = await getUserProfile()
setUser(userData)
} catch (error) {
console.error("Failed to fetch user profile:", error)
}
}
void fetchUser()
}, [])
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
setIsDropdownOpen(false)
}
}
document.addEventListener("mousedown", handleClickOutside)
return () => document.removeEventListener("mousedown", handleClickOutside)
}, [])
const handleLogout = async () => {
try {
const refreshToken = getRefreshToken()
if (refreshToken) {
await logoutUser(refreshToken)
}
} catch (error) {
console.error("Logout API failed:", error)
} finally {
clearSessionTokens()
setUser(null)
setShowLogoutModal(false)
toast.success(t.logoutToast || "Successfully logged out!")
navigate("/auth")
}
}
const toggleTheme = () => {
const newThemeState = !isDarkMode
setIsDarkMode(newThemeState)
localStorage.setItem("theme", newThemeState ? "dark" : "light")
}
const toggleLanguage = () => {
const newLang = isFa ? "en" : "fa"
if (setLanguage) {
setLanguage(newLang)
} else {
localStorage.setItem("language", newLang)
window.location.reload()
}
}
return (
<>
<header className="sticky top-0 z-50 flex items-center justify-between border-b border-slate-200/80 bg-white/70 px-8 py-6 backdrop-blur-md transition-colors dark:border-slate-800/80 dark:bg-slate-900/70">
<div className="flex cursor-pointer items-center gap-2" onClick={() => navigate("/")}>
<span className="relative z-20 flex items-center gap-2 text-xl font-bold tracking-tight text-slate-900 dark:text-slate-50">
<Command className="h-7 w-7" />
{t.title || "Qlockify"}
</span>
</div>
<div className="flex items-center gap-4">
{user && <WorkspaceSelector />}
{user ? (
<>
<NotificationBell />
<div className="relative" ref={dropdownRef}>
<button
onClick={() => setIsDropdownOpen((current) => !current)}
className="h-12 w-12 overflow-hidden rounded-full border-2 border-slate-200 transition-all hover:border-blue-500 focus:outline-none dark:border-slate-700 dark:hover:border-blue-500"
>
{user.profile_picture ? (
<img
src={user.profile_picture}
alt="Profile"
className="h-full w-full object-cover"
/>
) : (
<div className="flex h-full w-full items-center justify-center bg-slate-100 text-sm font-bold uppercase text-slate-600 dark:bg-slate-800 dark:text-slate-300">
{user.first_name?.[0] || user.email?.[0] || "U"}
</div>
)}
</button>
{isDropdownOpen && (
<div
dir="rtl"
className={`absolute ${isFa ? "left-0" : "right-0"} z-50 mt-2 w-56 overflow-hidden rounded-lg border border-slate-200 bg-white py-2 shadow-lg ring-1 ring-black ring-opacity-5 dark:border-slate-800 dark:bg-slate-900`}
>
<div className="mb-2 border-b border-slate-100 px-4 py-2 dark:border-slate-800">
<p className="truncate text-sm font-semibold text-slate-800 dark:text-slate-400">
{user.first_name || user.last_name
? `${user.first_name || ""} ${user.last_name || ""}`.trim()
: user.email}
</p>
</div>
<button
onClick={() => {
navigate("/profile")
setIsDropdownOpen(false)
}}
className="flex w-full items-center gap-3 px-4 py-2.5 text-sm text-slate-700 transition-colors hover:bg-slate-100 dark:text-slate-200 dark:hover:bg-slate-800"
>
<User className="h-4 w-4" />
<span>{t.profile?.title || "Profile"}</span>
</button>
<button
onClick={toggleTheme}
className="flex w-full items-center gap-3 px-4 py-2.5 text-sm text-slate-700 transition-colors hover:bg-slate-100 dark:text-slate-200 dark:hover:bg-slate-800"
>
{isDarkMode ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
<span>{isDarkMode ? (t.lightMode || "Light Mode") : (t.darkMode || "Dark Mode")}</span>
</button>
<button
onClick={toggleLanguage}
className="flex w-full items-center gap-3 px-4 py-2.5 text-sm text-slate-700 transition-colors hover:bg-slate-100 dark:text-slate-200 dark:hover:bg-slate-800"
>
<Globe className="h-4 w-4" />
<span>{isFa ? "English" : "فارسی"}</span>
</button>
<div className="my-1 h-px bg-slate-200 dark:bg-slate-800"></div>
<button
onClick={() => {
setShowLogoutModal(true)
setIsDropdownOpen(false)
}}
className="flex w-full items-center gap-3 px-4 py-2.5 text-sm font-medium text-red-600 transition-colors hover:bg-red-50 dark:text-red-500 dark:hover:bg-red-950/50"
>
<LogOut className="h-4 w-4" />
<span>{t.logout || "Logout"}</span>
</button>
</div>
)}
</div>
</>
) : (
<>
<SettingsMenu />
<Button
onClick={() => navigate("/auth")}
className="bg-blue-600 text-white hover:bg-blue-700 dark:bg-blue-600 dark:hover:bg-blue-700"
>
{t.login?.signIn || "Login"}
</Button>
</>
)}
</div>
</header>
{showLogoutModal && (
<div
className="fixed inset-0 z-60 flex items-center justify-center bg-black/50 px-4"
onClick={() => setShowLogoutModal(false)}
>
<div
className="w-full max-w-sm rounded-lg border bg-white p-6 shadow-lg dark:border-slate-800 dark:bg-slate-900"
onClick={(e) => e.stopPropagation()}
>
<h2 className="mb-2 text-lg font-bold text-slate-900 dark:text-white">
{t.confirmLogoutTitle || "Confirm Logout"}
</h2>
<p className="mb-6 text-slate-600 dark:text-slate-400">
{t.confirmLogoutMessage || "Are you sure you want to log out of your account?"}
</p>
<div className="flex justify-end gap-3">
<Button
variant="outline"
onClick={() => setShowLogoutModal(false)}
className="dark:text-white"
>
{t.actions?.cancel || "Cancel"}
</Button>
<Button
variant="destructive"
onClick={handleLogout}
className="bg-red-500 text-white hover:bg-red-600 dark:bg-red-600 dark:hover:bg-red-700"
>
{t.logout || "Logout"}
</Button>
</div>
</div>
</div>
)}
</>
)
}

View File

@@ -0,0 +1,203 @@
import { useEffect, useMemo, useRef, useState } from "react"
import { Bell, CheckCheck, Loader2, Trash2 } from "lucide-react"
import { useTranslation } from "../../hooks/useTranslation"
import { cn } from "../../lib/utils"
import { useNotifications } from "../../context/NotificationsContext"
import type { NotificationItem } from "../../api/notifications"
import { Button } from "../ui/button"
const formatNotificationTimestamp = (value: string, locale: string) => {
const date = new Date(value)
if (Number.isNaN(date.getTime())) {
return value
}
return new Intl.DateTimeFormat(locale === "fa" ? "fa-IR" : "en-US", {
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
}).format(date)
}
function NotificationRow({
notification,
locale,
onClick,
onDelete,
}: {
notification: NotificationItem
locale: string
onClick: (notification: NotificationItem) => void
onDelete: (notification: NotificationItem) => void
}) {
return (
<div
className={cn(
"border-b border-slate-100 px-4 py-3 transition-colors dark:border-slate-800",
notification.is_seen
? "bg-white hover:bg-slate-50 dark:bg-slate-900 dark:hover:bg-slate-800/80"
: "bg-sky-50/70 hover:bg-sky-100/70 dark:bg-sky-500/10 dark:hover:bg-sky-500/15",
)}
>
<div className="flex items-start gap-3">
<button
type="button"
onClick={() => onClick(notification)}
className="flex min-w-0 flex-1 items-start gap-3 text-start"
>
<span
className={cn(
"mt-1 h-2.5 w-2.5 shrink-0 rounded-full",
notification.is_seen ? "bg-slate-300 dark:bg-slate-700" : "bg-sky-500",
)}
/>
<div className="min-w-0 flex-1">
<div className="flex items-center justify-between gap-3">
<p className="truncate text-sm font-semibold text-slate-900 dark:text-slate-100">
{notification.title || notification.type}
</p>
<span className="shrink-0 text-xs text-slate-500 dark:text-slate-400">
{formatNotificationTimestamp(notification.created_at, locale)}
</span>
</div>
{notification.message ? (
<p className="mt-1 line-clamp-2 text-sm text-slate-600 dark:text-slate-300">
{notification.message}
</p>
) : null}
</div>
</button>
<button
type="button"
onClick={(event) => {
event.stopPropagation()
void onDelete(notification)
}}
className="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-slate-400 transition-colors hover:bg-red-50 hover:text-red-600 dark:text-slate-500 dark:hover:bg-red-950/40 dark:hover:text-red-400"
aria-label="Delete notification"
title="Delete notification"
>
<Trash2 className="h-4 w-4" />
</button>
</div>
</div>
)
}
export function NotificationBell() {
const { t, lang } = useTranslation()
const {
notifications,
unreadCount,
totalCount,
hasMore,
isLoading,
isLoadingMore,
loadMore,
markAllAsSeen,
deleteOne,
handleNotificationClick,
} = useNotifications()
const [isOpen, setIsOpen] = useState(false)
const containerRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (
containerRef.current &&
!containerRef.current.contains(event.target as Node)
) {
setIsOpen(false)
}
}
document.addEventListener("mousedown", handleClickOutside)
return () => document.removeEventListener("mousedown", handleClickOutside)
}, [])
return (
<div className="relative" ref={containerRef}>
<button
type="button"
onClick={() => setIsOpen((current) => !current)}
className="relative inline-flex h-11 w-11 items-center justify-center rounded-full border border-slate-200 bg-white text-slate-600 transition-colors hover:border-sky-300 hover:text-sky-600 dark:border-slate-800 dark:bg-slate-900 dark:text-slate-300 dark:hover:border-sky-500/50 dark:hover:text-sky-300"
aria-label={t.notifications?.open || "Open notifications"}
>
<Bell className="h-5 w-5" />
{unreadCount > 0 ? (
<span className="absolute right-2 top-2 h-2.5 w-2.5 rounded-full bg-red-500" />
) : null}
</button>
{isOpen ? (
<div className="absolute end-0 top-full z-[80] mt-3 w-[22rem] max-w-[calc(100vw-2rem)] overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-2xl dark:border-slate-800 dark:bg-slate-900">
<div className="flex items-center justify-between border-b border-slate-100 px-4 py-3 dark:border-slate-800">
<div>
<p className="text-sm font-semibold text-slate-900 dark:text-slate-100">
{t.notifications?.title || "Notifications"}
</p>
<p className="text-xs text-slate-500 dark:text-slate-400">
{t.notifications?.summary?.(totalCount, unreadCount) ||
`${totalCount} total, ${unreadCount} unread`}
</p>
</div>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => void markAllAsSeen()}
className="h-8 px-2 text-slate-500 hover:text-sky-600 dark:text-slate-400 dark:hover:text-sky-300"
disabled={unreadCount === 0}
>
<CheckCheck className="h-4 w-4" />
<span className="sr-only">{t.notifications?.markAllRead || "Mark all as read"}</span>
</Button>
</div>
<div className="max-h-[26rem] overflow-y-auto">
{isLoading ? (
<div className="flex items-center justify-center px-4 py-12 text-sm text-slate-500 dark:text-slate-400">
<Loader2 className="me-2 h-4 w-4 animate-spin" />
{t.notifications?.loading || "Loading notifications..."}
</div>
) : notifications.length === 0 ? (
<div className="px-4 py-12 text-center text-sm text-slate-500 dark:text-slate-400">
{t.notifications?.empty || "No notifications yet."}
</div>
) : (
notifications.map((notification) => (
<NotificationRow
key={notification.id}
notification={notification}
locale={lang}
onClick={(item) => void handleNotificationClick(item)}
onDelete={(item) => void deleteOne(item)}
/>
))
)}
</div>
{hasMore ? (
<div className="border-t border-slate-100 p-3 dark:border-slate-800">
<Button
type="button"
variant="outline"
className="w-full"
onClick={() => void loadMore()}
disabled={isLoadingMore}
>
{isLoadingMore ? (
<>
<Loader2 className="me-2 h-4 w-4 animate-spin" />
{t.notifications?.loadingMore || "Loading more..."}
</>
) : (
t.notifications?.loadMore || "Load more"
)}
</Button>
</div>
) : null}
</div>
) : null}
</div>
)
}

View File

@@ -0,0 +1,467 @@
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react"
import { toast } from "sonner"
import {
buildNotificationStreamUrl,
deleteNotification,
getNotifications,
issueNotificationStreamToken,
markAllNotificationsRead,
markNotificationSeen,
type NotificationItem,
type NotificationLevel,
} from "../api/notifications"
import { useTranslation } from "../hooks/useTranslation"
import {
getAccessToken,
SESSION_CHANGED_EVENT,
} from "../lib/session"
type NotificationConnectionStatus =
| "idle"
| "connecting"
| "connected"
| "disconnected"
interface NotificationsContextValue {
notifications: NotificationItem[]
unreadCount: number
totalCount: number
hasMore: boolean
isLoading: boolean
isLoadingMore: boolean
connectionStatus: NotificationConnectionStatus
loadMore: () => Promise<void>
markAsSeen: (notification: NotificationItem) => Promise<void>
deleteOne: (notification: NotificationItem) => Promise<void>
markAllAsSeen: () => Promise<void>
handleNotificationClick: (notification: NotificationItem) => Promise<void>
refreshNotifications: () => Promise<void>
}
const NotificationsContext = createContext<NotificationsContextValue | undefined>(undefined)
const PAGE_SIZE = 20
const mergeNotifications = (
current: NotificationItem[],
incoming: NotificationItem[],
) => {
const notificationsById = new Map<string, NotificationItem>()
for (const notification of current) {
notificationsById.set(notification.id, notification)
}
for (const notification of incoming) {
const existing = notificationsById.get(notification.id)
notificationsById.set(notification.id, existing ? { ...existing, ...notification } : notification)
}
return Array.from(notificationsById.values()).sort((left, right) => {
return new Date(right.created_at).getTime() - new Date(left.created_at).getTime()
})
}
const getToastMethod = (level: NotificationLevel) => {
switch (level) {
case "success":
return toast.success
case "warning":
return toast.warning
case "error":
return toast.error
default:
return toast.info
}
}
export function NotificationsProvider({ children }: { children: ReactNode }) {
const { t } = useTranslation()
const [notifications, setNotifications] = useState<NotificationItem[]>([])
const [unreadCount, setUnreadCount] = useState(0)
const [totalCount, setTotalCount] = useState(0)
const [isLoading, setIsLoading] = useState(false)
const [isLoadingMore, setIsLoadingMore] = useState(false)
const [connectionStatus, setConnectionStatus] = useState<NotificationConnectionStatus>("idle")
const eventSourceRef = useRef<EventSource | null>(null)
const reconnectTimeoutRef = useRef<number | null>(null)
const reconnectAttemptRef = useRef(0)
const toastedNotificationIdsRef = useRef<Set<string>>(new Set())
const hasMore = notifications.length < totalCount
const closeEventSource = useCallback(() => {
if (reconnectTimeoutRef.current !== null) {
window.clearTimeout(reconnectTimeoutRef.current)
reconnectTimeoutRef.current = null
}
eventSourceRef.current?.close()
eventSourceRef.current = null
}, [])
const applyUnreadCount = useCallback((count: number | undefined) => {
if (typeof count === "number") {
setUnreadCount(count)
}
}, [])
const updateNotification = useCallback((notification: NotificationItem) => {
setNotifications((current) => mergeNotifications(current, [notification]))
}, [])
const removeNotification = useCallback((notificationId: string) => {
setNotifications((current) => current.filter((notification) => notification.id !== notificationId))
}, [])
const openNotificationTarget = useCallback((notification: NotificationItem) => {
if (!notification.action_url) {
return
}
window.location.assign(notification.action_url)
}, [])
const showIncomingToast = useCallback(
(notification: NotificationItem) => {
if (
notification.is_seen ||
toastedNotificationIdsRef.current.has(notification.id) ||
document.visibilityState !== "visible" ||
!document.hasFocus()
) {
return
}
toastedNotificationIdsRef.current.add(notification.id)
const notify = getToastMethod(notification.level)
notify(notification.title || (t.notifications?.newTitle || "New notification"), {
description: notification.message || undefined,
action: notification.action_url
? {
label: t.notifications?.openAction || "Open",
onClick: () => openNotificationTarget(notification),
}
: undefined,
})
},
[openNotificationTarget, t.notifications],
)
const refreshNotifications = useCallback(async () => {
if (!getAccessToken()) {
setNotifications([])
setUnreadCount(0)
setTotalCount(0)
setConnectionStatus("idle")
return
}
setIsLoading(true)
try {
const response = await getNotifications({ limit: PAGE_SIZE, offset: 0 })
setNotifications(response.notifications)
setUnreadCount(response.unread_count)
setTotalCount(response.count)
} catch {
toast.error(t.notifications?.loadError || "Failed to load notifications")
} finally {
setIsLoading(false)
}
}, [t.notifications])
const loadMore = useCallback(async () => {
if (isLoadingMore || !hasMore) {
return
}
setIsLoadingMore(true)
try {
const response = await getNotifications({
limit: PAGE_SIZE,
offset: notifications.length,
})
setNotifications((current) => mergeNotifications(current, response.notifications))
setUnreadCount(response.unread_count)
setTotalCount(response.count)
} catch {
toast.error(t.notifications?.loadError || "Failed to load notifications")
} finally {
setIsLoadingMore(false)
}
}, [hasMore, isLoadingMore, notifications.length, t.notifications])
const markAsSeen = useCallback(async (notification: NotificationItem) => {
if (notification.is_seen) {
return
}
try {
const response = await markNotificationSeen(notification.id)
setUnreadCount((current) => {
if (typeof response?.unread_count === "number") {
return response.unread_count
}
return Math.max(current - 1, 0)
})
if (response?.deleted) {
removeNotification(notification.id)
setTotalCount((current) => Math.max(current - 1, 0))
} else {
setNotifications((current) =>
current.map((item) =>
item.id === notification.id ? { ...item, is_seen: true } : item,
),
)
}
} catch {
toast.error(t.notifications?.markSeenError || "Failed to update notification")
}
}, [removeNotification, t.notifications])
const markAllAsSeen = useCallback(async () => {
try {
await markAllNotificationsRead()
setUnreadCount(0)
setNotifications((current) =>
current.map((notification) => ({ ...notification, is_seen: true })),
)
} catch {
toast.error(t.notifications?.markAllError || "Failed to update notifications")
}
}, [t.notifications])
const deleteOne = useCallback(async (notification: NotificationItem) => {
try {
const response = await deleteNotification(notification.id)
removeNotification(notification.id)
setTotalCount((current) => Math.max(current - 1, 0))
setUnreadCount((current) => {
if (typeof response?.unread_count === "number") {
return response.unread_count
}
return notification.is_seen ? current : Math.max(current - 1, 0)
})
} catch {
toast.error(t.notifications?.deleteError || "Failed to delete notification")
}
}, [removeNotification, t.notifications])
const handleNotificationClick = useCallback(async (notification: NotificationItem) => {
await markAsSeen(notification)
openNotificationTarget(notification)
}, [markAsSeen, openNotificationTarget])
const connectToStream = useCallback(async () => {
if (!getAccessToken()) {
closeEventSource()
setConnectionStatus("idle")
return
}
closeEventSource()
setConnectionStatus("connecting")
try {
const tokenResponse = await issueNotificationStreamToken()
const stream = new EventSource(buildNotificationStreamUrl(tokenResponse.token))
eventSourceRef.current = stream
stream.onopen = () => {
reconnectAttemptRef.current = 0
setConnectionStatus("connected")
}
stream.addEventListener("connected", (event) => {
const payload = JSON.parse((event as MessageEvent<string>).data) as {
notifications?: NotificationItem[]
unread_count?: number
}
if (Array.isArray(payload.notifications)) {
setNotifications((current) => mergeNotifications(current, payload.notifications || []))
setTotalCount((current) => Math.max(current, payload.notifications?.length || 0))
}
applyUnreadCount(payload.unread_count)
})
stream.addEventListener("notification", (event) => {
const payload = JSON.parse((event as MessageEvent<string>).data) as {
notification?: NotificationItem
unread_count?: number
}
if (!payload.notification) {
return
}
const incomingNotification = payload.notification
setNotifications((current) => {
const isExisting = current.some(
(notification) => notification.id === incomingNotification.id,
)
if (!isExisting) {
setTotalCount((count) => count + 1)
}
return mergeNotifications(current, [incomingNotification])
})
applyUnreadCount(payload.unread_count)
showIncomingToast(incomingNotification)
})
stream.addEventListener("notification_seen", (event) => {
const payload = JSON.parse((event as MessageEvent<string>).data) as {
notification_id?: string
deleted?: boolean
notification?: NotificationItem | null
unread_count?: number
}
if (payload.deleted && payload.notification_id) {
removeNotification(payload.notification_id)
setTotalCount((current) => Math.max(current - 1, 0))
} else if (payload.notification) {
updateNotification(payload.notification)
} else if (payload.notification_id) {
setNotifications((current) =>
current.map((notification) =>
notification.id === payload.notification_id
? { ...notification, is_seen: true }
: notification,
),
)
}
applyUnreadCount(payload.unread_count)
})
stream.addEventListener("notification_mark_all_read", (event) => {
const payload = JSON.parse((event as MessageEvent<string>).data) as {
type?: string | null
unread_count?: number
}
setNotifications((current) =>
current.map((notification) =>
payload.type && notification.type !== payload.type
? notification
: { ...notification, is_seen: true },
),
)
applyUnreadCount(payload.unread_count)
})
stream.addEventListener("unread_count", (event) => {
const payload = JSON.parse((event as MessageEvent<string>).data) as {
unread_count?: number
}
applyUnreadCount(payload.unread_count)
})
stream.onerror = async () => {
stream.close()
eventSourceRef.current = null
setConnectionStatus("disconnected")
reconnectAttemptRef.current += 1
const reconnectDelay = Math.min(
1000 * 2 ** reconnectAttemptRef.current,
30000,
)
reconnectTimeoutRef.current = window.setTimeout(async () => {
if (!getAccessToken()) {
return
}
try {
await connectToStream()
} catch {
setConnectionStatus("disconnected")
}
}, reconnectDelay)
}
} catch {
setConnectionStatus("disconnected")
}
}, [
applyUnreadCount,
closeEventSource,
showIncomingToast,
removeNotification,
updateNotification,
])
useEffect(() => {
const startNotifications = async () => {
if (!getAccessToken()) {
closeEventSource()
setNotifications([])
setUnreadCount(0)
setTotalCount(0)
setConnectionStatus("idle")
return
}
await refreshNotifications()
await connectToStream()
}
void startNotifications()
const handleSessionChange = () => {
void startNotifications()
}
window.addEventListener(SESSION_CHANGED_EVENT, handleSessionChange)
return () => {
window.removeEventListener(SESSION_CHANGED_EVENT, handleSessionChange)
closeEventSource()
}
}, [closeEventSource, connectToStream, refreshNotifications])
const value = useMemo<NotificationsContextValue>(() => {
return {
notifications,
unreadCount,
totalCount,
hasMore,
isLoading,
isLoadingMore,
connectionStatus,
loadMore,
markAsSeen,
deleteOne,
markAllAsSeen,
handleNotificationClick,
refreshNotifications,
}
}, [
connectionStatus,
handleNotificationClick,
hasMore,
isLoading,
isLoadingMore,
loadMore,
markAllAsSeen,
markAsSeen,
deleteOne,
notifications,
refreshNotifications,
totalCount,
unreadCount,
])
return (
<NotificationsContext.Provider value={value}>
{children}
</NotificationsContext.Provider>
)
}
export const useNotifications = () => {
const context = useContext(NotificationsContext)
if (!context) {
throw new Error("useNotifications must be used inside NotificationsProvider")
}
return context
}

21
src/lib/session.ts Normal file
View File

@@ -0,0 +1,21 @@
export const SESSION_CHANGED_EVENT = "auth_session_changed"
export const getAccessToken = () => localStorage.getItem("accessToken")
export const getRefreshToken = () => localStorage.getItem("refreshToken")
export const emitSessionChanged = () => {
window.dispatchEvent(new Event(SESSION_CHANGED_EVENT))
}
export const setSessionTokens = (accessToken: string, refreshToken: string) => {
localStorage.setItem("accessToken", accessToken)
localStorage.setItem("refreshToken", refreshToken)
emitSessionChanged()
}
export const clearSessionTokens = () => {
localStorage.removeItem("accessToken")
localStorage.removeItem("refreshToken")
emitSessionChanged()
}

View File

@@ -391,4 +391,20 @@ export const en = {
toFilterPrefix: "To",
},
notifications: {
title: "Notifications",
open: "Open notifications",
empty: "No notifications yet.",
loading: "Loading notifications...",
loadingMore: "Loading more...",
loadMore: "Load more",
markAllRead: "Mark all as read",
markSeenError: "Failed to update notification",
markAllError: "Failed to update notifications",
deleteError: "Failed to delete notification",
loadError: "Failed to load notifications",
newTitle: "New notification",
openAction: "Open",
summary: (total: number, unread: number) => `${total} total, ${unread} unread`,
},
}

View File

@@ -387,4 +387,20 @@ export const fa = {
fromFilterPrefix: "از",
toFilterPrefix: "تا",
},
notifications: {
title: "اعلان‌ها",
open: "باز کردن اعلان‌ها",
empty: "هنوز اعلانی وجود ندارد.",
loading: "در حال بارگذاری اعلان‌ها...",
loadingMore: "در حال بارگذاری بیشتر...",
loadMore: "بارگذاری بیشتر",
markAllRead: "خواندن همه",
markSeenError: "به‌روزرسانی اعلان با خطا مواجه شد.",
markAllError: "به‌روزرسانی اعلان‌ها با خطا مواجه شد.",
deleteError: "حذف اعلان با خطا مواجه شد.",
loadError: "دریافت اعلان‌ها با خطا مواجه شد.",
newTitle: "اعلان جدید",
openAction: "باز کردن",
summary: (total: number, unread: number) => `${total} کل، ${unread} خوانده‌نشده`,
},
}

View File

@@ -4,9 +4,10 @@ import { Button } from "../components/ui/button"
import { Input } from "../components/ui/input"
import { SettingsMenu } from "../components/SettingsMenu"
import { ArrowLeft, ArrowRight, Command, Loader2, Eye, EyeOff } from "lucide-react"
import { toast } from "sonner"
import { useTranslation } from "../hooks/useTranslation"
import { loginWithPassword, sendOtp, loginWithOtp } from "../api/users"
import { toast } from "sonner"
import { useTranslation } from "../hooks/useTranslation"
import { loginWithPassword, sendOtp, loginWithOtp } from "../api/users"
import { setSessionTokens } from "../lib/session"
type AuthStep = "mobile" | "password" | "otp"
type AuthMode = "login" | "register"
@@ -24,12 +25,11 @@ export default function Auth() {
const [loading, setLoading] = useState(false)
const [showPassword, setShowPassword] = useState(false) // Added state for password visibility
const handleTokenResponse = (access: string, refresh: string) => {
localStorage.setItem("accessToken", access)
localStorage.setItem("refreshToken", refresh)
toast.success(t.login.toasts.successLogin)
navigate("/profile")
}
const handleTokenResponse = (access: string, refresh: string) => {
setSessionTokens(access, refresh)
toast.success(t.login.toasts.successLogin)
navigate("/profile")
}
const handleSendOtp = async (selectedMode: AuthMode) => {
if (!mobile) return toast.error(t.login.toasts.enterMobile)