refactor(announcements,messaging,notifications): V1+V2 审计重构 — i18n 命名空间独立 + 通知标题 i18n 化 + 服务端过滤 + 编排下沉 + 表单错误展示 + 架构图同步
V1 改进(已完成): - P0-4/P1-4/P1-5: 通知组件和 CRUD Action 从 messaging 迁移至 notifications 模块 - P1-5: 新增 getMessagesPageData / getAdminAnnouncementsPageData 编排函数 - P1-6: announcements schema 添加 superRefine 条件校验 - P1-7: 新增 useMessageSearch hook(防抖 + 请求竞态取消)+ 客户端分页 UI - P1-9: deleteMessage 事务化 - P2-11: 全模块 trackEvent 埋点 - 全模块 i18n 接入 + Error Boundary + a11y 改进 V2 改进(本次完成): - V2-P0-1: 通知 i18n 命名空间独立(notifications.json),useTranslations 从 "messages" 切换到 "notifications" - V2-P0-2: 公告/消息通知标题 i18n 化,Server Action 中使用 getTranslations 生成通知标题 - V2-P1-1: AnnouncementList 纯服务端过滤,移除客户端 useState/useMemo - V2-P1-2: MessageList 客户端过滤仅在初始数据时执行,搜索结果由服务端按 tab 过滤 - V2-P1-3: 消息详情页编排下沉,新增 getMessageDetailPageData 编排函数 - V2-P1-4: 表单服务端校验错误展示(fieldErrors + aria-invalid) - V2-P2-1: 轮询间隔常量化(POLL_INTERVAL_MS) - V2-P2-2: 架构图同步(004 + 005)
This commit is contained in:
@@ -23,6 +23,8 @@ import {
|
||||
import { sendMessageAction } from "../actions"
|
||||
import type { RecipientOption } from "../types"
|
||||
|
||||
type FieldErrors = Record<string, string[]>
|
||||
|
||||
export function MessageCompose({
|
||||
recipients,
|
||||
parentMessageId,
|
||||
@@ -40,10 +42,16 @@ export function MessageCompose({
|
||||
const router = useRouter()
|
||||
const [isWorking, setIsWorking] = useState(false)
|
||||
const [receiverId, setReceiverId] = useState(defaultReceiverId ?? "")
|
||||
const [fieldErrors, setFieldErrors] = useState<FieldErrors>({})
|
||||
|
||||
const getFieldError = (field: string): string | null => {
|
||||
const errs = fieldErrors[field]
|
||||
return errs && errs.length > 0 ? errs[0] : null
|
||||
}
|
||||
|
||||
const handleSubmit = async (formData: FormData) => {
|
||||
if (!receiverId) {
|
||||
toast.error(t("messages.selectRecipient"))
|
||||
toast.error(t("form.selectRecipient"))
|
||||
return
|
||||
}
|
||||
formData.set("receiverId", receiverId)
|
||||
@@ -52,6 +60,7 @@ export function MessageCompose({
|
||||
}
|
||||
|
||||
setIsWorking(true)
|
||||
setFieldErrors({})
|
||||
try {
|
||||
const res = await sendMessageAction(null, formData)
|
||||
if (res.success) {
|
||||
@@ -59,6 +68,10 @@ export function MessageCompose({
|
||||
router.push("/messages")
|
||||
router.refresh()
|
||||
} else {
|
||||
// 展示字段级错误(来自 Zod 校验)
|
||||
if (res.errors) {
|
||||
setFieldErrors(res.errors)
|
||||
}
|
||||
toast.error(res.message || t("messages.sendFailed"))
|
||||
}
|
||||
} catch {
|
||||
@@ -85,7 +98,7 @@ export function MessageCompose({
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="receiverId">{t("form.to")}</Label>
|
||||
<Select value={receiverId} onValueChange={setReceiverId} disabled={!!defaultReceiverId}>
|
||||
<SelectTrigger>
|
||||
<SelectTrigger aria-invalid={!!getFieldError("receiverId")}>
|
||||
<SelectValue placeholder={t("form.toPlaceholder")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -98,6 +111,9 @@ export function MessageCompose({
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<input type="hidden" name="receiverId" value={receiverId} />
|
||||
{getFieldError("receiverId") ? (
|
||||
<p className="text-destructive text-xs">{getFieldError("receiverId")}</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
@@ -108,7 +124,11 @@ export function MessageCompose({
|
||||
placeholder={t("form.subjectPlaceholder")}
|
||||
defaultValue={defaultSubject ?? ""}
|
||||
maxLength={255}
|
||||
aria-invalid={!!getFieldError("subject")}
|
||||
/>
|
||||
{getFieldError("subject") ? (
|
||||
<p className="text-destructive text-xs">{getFieldError("subject")}</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
@@ -119,7 +139,11 @@ export function MessageCompose({
|
||||
placeholder={t("form.contentPlaceholder")}
|
||||
className="min-h-[200px]"
|
||||
required
|
||||
aria-invalid={!!getFieldError("content")}
|
||||
/>
|
||||
{getFieldError("content") ? (
|
||||
<p className="text-destructive text-xs">{getFieldError("content")}</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<CardFooter className="justify-end gap-2 px-0">
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { useMemo, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { Mail, MailOpen, Plus, Send, Inbox, Search, Loader2 } from "lucide-react"
|
||||
import { Mail, MailOpen, Plus, Send, Inbox, Search, Loader2, ChevronLeft, ChevronRight } from "lucide-react"
|
||||
import { useTranslations } from "next-intl"
|
||||
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
@@ -16,10 +16,14 @@ import { usePermission } from "@/shared/hooks/use-permission"
|
||||
import { Permissions } from "@/shared/types/permissions"
|
||||
|
||||
import { getMessagesAction } from "../actions"
|
||||
import { useMessageSearch } from "../hooks/use-message-search"
|
||||
import type { Message, MessageType } from "../types"
|
||||
|
||||
type Tab = "inbox" | "sent"
|
||||
|
||||
/** 客户端分页大小 */
|
||||
const PAGE_SIZE = 20
|
||||
|
||||
export function MessageList({
|
||||
messages,
|
||||
currentUserId,
|
||||
@@ -31,54 +35,44 @@ export function MessageList({
|
||||
}) {
|
||||
const t = useTranslations("messages")
|
||||
const [tab, setTab] = useState<Tab>(initialType === "sent" ? "sent" : "inbox")
|
||||
const [keyword, setKeyword] = useState("")
|
||||
const [searchResults, setSearchResults] = useState<{ kw: string; tab: Tab; items: Message[] } | null>(null)
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const { hasPermission } = usePermission()
|
||||
const canSend = hasPermission(Permissions.MESSAGE_SEND)
|
||||
|
||||
// 防抖搜索:keyword 或 tab 变化时调用 getMessagesAction
|
||||
useEffect(() => {
|
||||
const kw = keyword.trim()
|
||||
if (kw.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
let cancelled = false
|
||||
const timer = setTimeout(async () => {
|
||||
if (cancelled) return
|
||||
const res = await getMessagesAction({ type: tab, keyword: kw })
|
||||
if (cancelled) return
|
||||
if (res.success && res.data) {
|
||||
setSearchResults({ kw, tab, items: res.data.items })
|
||||
}
|
||||
}, 400)
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}, [keyword, tab])
|
||||
|
||||
// 当前搜索结果是否匹配最新的 keyword 和 tab
|
||||
const currentResults = searchResults && searchResults.kw === keyword.trim() && searchResults.tab === tab
|
||||
? searchResults.items
|
||||
: null
|
||||
|
||||
// 搜索中:keyword 非空且尚无匹配结果
|
||||
const searching = keyword.trim().length > 0 && currentResults === null
|
||||
|
||||
// 当 keyword 为空时使用 prop messages,否则使用搜索结果
|
||||
const displayMessages = currentResults ?? messages
|
||||
const { keyword, setKeyword, results, searching, isUsingInitial } = useMessageSearch({
|
||||
searchAction: getMessagesAction,
|
||||
tab,
|
||||
})
|
||||
|
||||
// 客户端过滤仅在初始数据(type=all)时需要,搜索结果已由服务端按 tab 过滤
|
||||
const filtered = useMemo(() => {
|
||||
const displayMessages = isUsingInitial ? messages : (results ?? [])
|
||||
if (!isUsingInitial) return displayMessages
|
||||
if (tab === "inbox") return displayMessages.filter((m) => m.receiverId === currentUserId)
|
||||
return displayMessages.filter((m) => m.senderId === currentUserId)
|
||||
}, [displayMessages, tab, currentUserId])
|
||||
}, [messages, results, tab, currentUserId, isUsingInitial])
|
||||
|
||||
// 客户端分页:超过 PAGE_SIZE 条时显示分页 UI
|
||||
const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE))
|
||||
const safePage = Math.min(currentPage, totalPages)
|
||||
const paged = filtered.slice((safePage - 1) * PAGE_SIZE, safePage * PAGE_SIZE)
|
||||
const showPagination = filtered.length > PAGE_SIZE
|
||||
|
||||
// 切换 tab 或搜索时重置分页
|
||||
const handleTabChange = (v: string): void => {
|
||||
setTab(v as Tab)
|
||||
setCurrentPage(1)
|
||||
}
|
||||
|
||||
const handleKeywordChange = (v: string): void => {
|
||||
setKeyword(v)
|
||||
setCurrentPage(1)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<Tabs value={tab} onValueChange={(v) => setTab(v as Tab)}>
|
||||
<Tabs value={tab} onValueChange={handleTabChange}>
|
||||
<TabsList>
|
||||
<TabsTrigger value="inbox" className="gap-2">
|
||||
<Inbox className="h-4 w-4" />
|
||||
@@ -108,7 +102,7 @@ export function MessageList({
|
||||
aria-label={t("search.placeholder")}
|
||||
placeholder={t("search.placeholder")}
|
||||
value={keyword}
|
||||
onChange={(e) => setKeyword(e.target.value)}
|
||||
onChange={(e) => handleKeywordChange(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
{searching ? (
|
||||
@@ -116,7 +110,7 @@ export function MessageList({
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{filtered.length === 0 ? (
|
||||
{paged.length === 0 ? (
|
||||
<EmptyState
|
||||
title={tab === "inbox" ? t("empty.inboxEmpty") : t("empty.sentEmpty")}
|
||||
description={
|
||||
@@ -128,45 +122,73 @@ export function MessageList({
|
||||
className="h-auto border-none shadow-none"
|
||||
/>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{filtered.map((m) => {
|
||||
const isReceived = m.receiverId === currentUserId
|
||||
const counterpart = isReceived ? m.senderName : m.receiverName
|
||||
const unread = isReceived && !m.isRead
|
||||
return (
|
||||
<Link key={m.id} href={`/messages/${m.id}`} className="block" aria-label={m.subject ?? t("meta.noSubject")}>
|
||||
<Card className={cn("transition-colors hover:bg-accent/50", unread && "border-primary/40")}>
|
||||
<CardHeader className="flex flex-row items-start justify-between gap-2 space-y-0 pb-3">
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-2">
|
||||
{unread ? (
|
||||
<Mail className="h-4 w-4 text-primary" aria-hidden="true" />
|
||||
) : (
|
||||
<MailOpen className="text-muted-foreground h-4 w-4" aria-hidden="true" />
|
||||
)}
|
||||
<span className={cn("text-sm font-medium", unread && "text-primary")}>
|
||||
{m.subject ?? t("meta.noSubject")}
|
||||
</span>
|
||||
{unread ? <Badge variant="default" className="text-xs">{t("status.new")}</Badge> : null}
|
||||
<>
|
||||
<div className="space-y-3">
|
||||
{paged.map((m) => {
|
||||
const isReceived = m.receiverId === currentUserId
|
||||
const counterpart = isReceived ? m.senderName : m.receiverName
|
||||
const unread = isReceived && !m.isRead
|
||||
return (
|
||||
<Link key={m.id} href={`/messages/${m.id}`} className="block" aria-label={m.subject ?? t("meta.noSubject")}>
|
||||
<Card className={cn("transition-colors hover:bg-accent/50", unread && "border-primary/40")}>
|
||||
<CardHeader className="flex flex-row items-start justify-between gap-2 space-y-0 pb-3">
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-2">
|
||||
{unread ? (
|
||||
<Mail className="h-4 w-4 text-primary" aria-hidden="true" />
|
||||
) : (
|
||||
<MailOpen className="text-muted-foreground h-4 w-4" aria-hidden="true" />
|
||||
)}
|
||||
<span className={cn("text-sm font-medium", unread && "text-primary")}>
|
||||
{m.subject ?? t("meta.noSubject")}
|
||||
</span>
|
||||
{unread ? <Badge variant="default" className="text-xs">{t("status.new")}</Badge> : null}
|
||||
</div>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{isReceived ? t("meta.from") : t("meta.to")}: {counterpart ?? t("meta.unknown")}
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{isReceived ? t("meta.from") : t("meta.to")}: {counterpart ?? t("meta.unknown")}
|
||||
<span className="text-muted-foreground shrink-0 text-xs">
|
||||
{formatDate(m.createdAt)}
|
||||
</span>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
<p className="text-muted-foreground line-clamp-2 text-sm whitespace-pre-wrap">
|
||||
{m.content}
|
||||
</p>
|
||||
</div>
|
||||
<span className="text-muted-foreground shrink-0 text-xs">
|
||||
{formatDate(m.createdAt)}
|
||||
</span>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
<p className="text-muted-foreground line-clamp-2 text-sm whitespace-pre-wrap">
|
||||
{m.content}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{showPagination ? (
|
||||
<div className="flex items-center justify-center gap-4 pt-2" role="navigation" aria-label={t("tabs.inbox")}>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
|
||||
disabled={safePage <= 1}
|
||||
aria-label="Previous page"
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<span className="text-muted-foreground text-sm" aria-live="polite">
|
||||
{safePage} / {totalPages}
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
|
||||
disabled={safePage >= totalPages}
|
||||
aria-label="Next page"
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,181 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useTranslations } from "next-intl"
|
||||
import { Bell, CheckCheck, MessageSquare, Megaphone, PenTool, GraduationCap } from "lucide-react"
|
||||
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import { ScrollArea } from "@/shared/components/ui/scroll-area"
|
||||
import { cn, formatDate } from "@/shared/lib/utils"
|
||||
|
||||
import {
|
||||
getNotificationsAction,
|
||||
getUnreadNotificationCountAction,
|
||||
markAllNotificationsAsReadAction,
|
||||
markNotificationAsReadAction,
|
||||
} from "../actions"
|
||||
import type { Notification, NotificationType } from "@/modules/notifications/types"
|
||||
|
||||
const TYPE_ICON: Record<NotificationType, typeof Bell> = {
|
||||
message: MessageSquare,
|
||||
announcement: Megaphone,
|
||||
homework: PenTool,
|
||||
grade: GraduationCap,
|
||||
}
|
||||
|
||||
export function NotificationDropdown() {
|
||||
const t = useTranslations("messages")
|
||||
const router = useRouter()
|
||||
const [notifications, setNotifications] = useState<Notification[]>([])
|
||||
const [unreadCount, setUnreadCount] = useState(0)
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
|
||||
const fetchNotifications = async () => {
|
||||
const res = await getNotificationsAction({ pageSize: 10 })
|
||||
if (!active) return
|
||||
if (res.success && res.data) {
|
||||
setNotifications(res.data.items)
|
||||
}
|
||||
}
|
||||
|
||||
const fetchUnreadCount = async () => {
|
||||
const res = await getUnreadNotificationCountAction()
|
||||
if (!active) return
|
||||
if (res.success && typeof res.data === "number") {
|
||||
setUnreadCount(res.data)
|
||||
}
|
||||
}
|
||||
|
||||
void fetchNotifications()
|
||||
void fetchUnreadCount()
|
||||
|
||||
// 每 30 秒轮询刷新通知和未读计数
|
||||
const timer = setInterval(() => {
|
||||
void fetchNotifications()
|
||||
void fetchUnreadCount()
|
||||
}, 30_000)
|
||||
|
||||
return () => {
|
||||
active = false
|
||||
clearInterval(timer)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleMarkAllRead = async () => {
|
||||
const res = await markAllNotificationsAsReadAction()
|
||||
if (res.success) {
|
||||
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })))
|
||||
setUnreadCount(0)
|
||||
router.refresh()
|
||||
}
|
||||
}
|
||||
|
||||
const handleMarkRead = async (id: string) => {
|
||||
const res = await markNotificationAsReadAction(id)
|
||||
if (res.success) {
|
||||
setNotifications((prev) =>
|
||||
prev.map((n) => (n.id === id ? { ...n, isRead: true } : n))
|
||||
)
|
||||
setUnreadCount((c) => Math.max(0, c - 1))
|
||||
router.refresh()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenu open={open} onOpenChange={setOpen}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="relative text-muted-foreground" aria-label={t("title.notifications")}>
|
||||
<Bell className="size-5" aria-hidden="true" />
|
||||
{unreadCount > 0 ? (
|
||||
<Badge
|
||||
variant="destructive"
|
||||
className="absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center px-1 text-[10px]"
|
||||
>
|
||||
{unreadCount > 9 ? "9+" : unreadCount}
|
||||
</Badge>
|
||||
) : null}
|
||||
<span className="sr-only">{t("title.notifications")}</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-80 p-0">
|
||||
<DropdownMenuLabel className="flex items-center justify-between">
|
||||
<span>{t("title.notifications")}</span>
|
||||
{unreadCount > 0 ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleMarkAllRead}
|
||||
className="text-primary text-xs hover:underline"
|
||||
>
|
||||
<CheckCheck className="mr-1 inline h-3 w-3" aria-hidden="true" />
|
||||
{t("actions.markAllRead")}
|
||||
</button>
|
||||
) : null}
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator className="mb-0" />
|
||||
<ScrollArea className="max-h-[320px]">
|
||||
{notifications.length === 0 ? (
|
||||
<div className="text-muted-foreground px-4 py-8 text-center text-sm">
|
||||
{t("empty.noNotificationsDropdown")}
|
||||
</div>
|
||||
) : (
|
||||
notifications.map((n) => {
|
||||
const Icon = TYPE_ICON[n.type] ?? Bell
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={n.id}
|
||||
className="flex items-start gap-2 py-3"
|
||||
onSelect={(e) => {
|
||||
if (!n.isRead) {
|
||||
e.preventDefault()
|
||||
handleMarkRead(n.id)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="bg-muted mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-full">
|
||||
<Icon className="h-3.5 w-3.5" aria-hidden="true" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 space-y-0.5">
|
||||
<div className="flex items-center gap-1.5">
|
||||
{!n.isRead ? (
|
||||
<span className="bg-primary size-1.5 shrink-0 rounded-full" aria-hidden="true" />
|
||||
) : null}
|
||||
<span className={cn("text-xs", !n.isRead ? "font-semibold" : "font-medium")}>
|
||||
{n.title}
|
||||
</span>
|
||||
</div>
|
||||
{n.content ? (
|
||||
<p className="text-muted-foreground line-clamp-2 text-xs">{n.content}</p>
|
||||
) : null}
|
||||
<span className="text-muted-foreground text-[10px]">
|
||||
{formatDate(n.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</ScrollArea>
|
||||
<DropdownMenuSeparator className="mt-0" />
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href="/messages" className="text-primary justify-center text-xs">
|
||||
{t("actions.viewAll")}
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { toast } from "sonner"
|
||||
import { useTranslations } from "next-intl"
|
||||
import { Bell, CheckCheck, MessageSquare, Megaphone, PenTool, GraduationCap } from "lucide-react"
|
||||
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Card, CardContent } from "@/shared/components/ui/card"
|
||||
import { EmptyState } from "@/shared/components/ui/empty-state"
|
||||
import { cn, formatDate } from "@/shared/lib/utils"
|
||||
|
||||
import { markAllNotificationsAsReadAction, markNotificationAsReadAction } from "../actions"
|
||||
import type { Notification, NotificationType } from "@/modules/notifications/types"
|
||||
|
||||
const TYPE_ICON: Record<NotificationType, typeof Bell> = {
|
||||
message: MessageSquare,
|
||||
announcement: Megaphone,
|
||||
homework: PenTool,
|
||||
grade: GraduationCap,
|
||||
}
|
||||
|
||||
export function NotificationList({ notifications }: { notifications: Notification[] }) {
|
||||
const t = useTranslations("messages")
|
||||
const router = useRouter()
|
||||
const [isWorking, setIsWorking] = useState(false)
|
||||
const hasUnread = notifications.some((n) => !n.isRead)
|
||||
|
||||
const handleMarkAllRead = async () => {
|
||||
setIsWorking(true)
|
||||
try {
|
||||
const res = await markAllNotificationsAsReadAction()
|
||||
if (res.success) {
|
||||
toast.success(res.message)
|
||||
router.refresh()
|
||||
} else {
|
||||
toast.error(res.message || t("messages.markReadFailed"))
|
||||
}
|
||||
} catch {
|
||||
toast.error(t("messages.markReadFailed"))
|
||||
} finally {
|
||||
setIsWorking(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleMarkRead = async (id: string) => {
|
||||
try {
|
||||
const res = await markNotificationAsReadAction(id)
|
||||
if (res.success) {
|
||||
router.refresh()
|
||||
}
|
||||
} catch {
|
||||
toast.error(t("messages.markReadFailed"))
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold tracking-tight">{t("title.notifications")}</h2>
|
||||
<p className="text-muted-foreground text-sm">{t("description.notifications")}</p>
|
||||
</div>
|
||||
{hasUnread ? (
|
||||
<Button onClick={handleMarkAllRead} disabled={isWorking} variant="outline">
|
||||
<CheckCheck className="mr-2 h-4 w-4" />
|
||||
{t("actions.markAllRead")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{notifications.length === 0 ? (
|
||||
<EmptyState
|
||||
title={t("empty.noNotifications")}
|
||||
description={t("empty.noNotificationsDesc")}
|
||||
icon={Bell}
|
||||
className="h-auto border-none shadow-none"
|
||||
/>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{notifications.map((n) => {
|
||||
const Icon = TYPE_ICON[n.type] ?? Bell
|
||||
return (
|
||||
<Card
|
||||
key={n.id}
|
||||
className={cn("transition-colors", !n.isRead && "border-primary/40 bg-primary/5")}
|
||||
>
|
||||
<CardContent className="flex items-start gap-3 py-4">
|
||||
<div className="bg-muted flex size-9 shrink-0 items-center justify-center rounded-full">
|
||||
<Icon className="h-4 w-4" aria-hidden="true" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 space-y-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={cn("text-sm", !n.isRead ? "font-semibold" : "font-medium")}>
|
||||
{n.title}
|
||||
</span>
|
||||
{!n.isRead ? <Badge variant="default" className="text-xs">{t("status.new")}</Badge> : null}
|
||||
</div>
|
||||
{n.content ? (
|
||||
<p className="text-muted-foreground line-clamp-2 text-sm whitespace-pre-wrap">
|
||||
{n.content}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{t(`notificationType.${n.type}`)}
|
||||
</Badge>
|
||||
<span>{formatDate(n.createdAt)}</span>
|
||||
{!n.isRead ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleMarkRead(n.id)}
|
||||
className="text-primary hover:underline"
|
||||
aria-label={t("actions.markRead")}
|
||||
>
|
||||
{t("actions.markRead")}
|
||||
</button>
|
||||
) : null}
|
||||
{n.link ? (
|
||||
<Link href={n.link} className="ml-auto text-primary hover:underline">
|
||||
{t("actions.view")}
|
||||
</Link>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -6,11 +6,14 @@ import { Badge } from "@/shared/components/ui/badge"
|
||||
|
||||
import { getUnreadMessageCountAction } from "../actions"
|
||||
|
||||
/** 未读消息计数轮询间隔(毫秒) */
|
||||
const POLL_INTERVAL_MS = 60_000
|
||||
|
||||
/**
|
||||
* 未读消息计数徽章
|
||||
*
|
||||
* 在侧边栏 Messages 导航项旁显示未读私信数。
|
||||
* 每 60 秒轮询一次以保持计数更新。
|
||||
* 每 POLL_INTERVAL_MS 毫秒轮询一次以保持计数更新。
|
||||
*/
|
||||
export function UnreadMessageBadge() {
|
||||
const [count, setCount] = useState(0)
|
||||
@@ -30,7 +33,7 @@ export function UnreadMessageBadge() {
|
||||
|
||||
const timer = setInterval(() => {
|
||||
void fetchCount()
|
||||
}, 60_000)
|
||||
}, POLL_INTERVAL_MS)
|
||||
|
||||
return () => {
|
||||
active = false
|
||||
|
||||
Reference in New Issue
Block a user