F2-11: 消息中心前端 — Drawer、顶栏铃铛、工作台通知卡、e2e

- src/api/notice.ts:新增 fetchNotices/fetchUnreadCount/markNoticeRead/markAllNoticesRead
- src/shell/NoticeDrawer.tsx:消息中心抽屉(未读蓝点/展开内容/全部已读/过滤标签)
- src/shell/Topbar.tsx:新增消息图标按钮(doc 图标,noticeBadge badge)
- src/shell/AppShell.tsx:消息未读数 60s 轮询 + NoticeDrawer 状态管理
- src/pages/WorkbenchPage.tsx:点亮通知公告卡片(原占位注释替换为真实卡片)
- e2e/notice.spec.ts:5 个用例(API 3 + UI 2),50/50 全绿
- e2e/artifacts/f2-11/:截图(工作台卡片/Drawer 展开/全部已读后)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-06-12 02:27:05 +08:00
parent c8d3209e4d
commit a1c60f8a42
9 changed files with 845 additions and 1 deletions

48
src/api/notice.ts Normal file
View File

@@ -0,0 +1,48 @@
// 消息中心 API — F2-11
// 数据源:eip3.sys_message + eip3.sys_messageuser
import { http } from './http';
/** 消息列表条目 */
export interface NoticeItem {
id: string;
title: string;
summary: string | null;
type: number | null;
createtime: number | null;
isread: number;
}
/** 消息列表响应 */
export interface NoticeListResult {
items: NoticeItem[];
total: number;
}
/** 获取当前用户消息列表 */
export async function fetchNotices(
params: { unreadOnly?: boolean; page?: number; perPage?: number } = {},
): Promise<NoticeListResult> {
const { data } = await http.get<{ status: number; data: NoticeListResult }>(
'/api/notice',
{ params },
);
return data.data;
}
/** 获取未读消息数(顶栏轮询用) */
export async function fetchUnreadCount(): Promise<number> {
const { data } = await http.get<{ status: number; data: { count: number } }>(
'/api/notice/unread-count',
);
return data.data?.count ?? 0;
}
/** 单条消息置已读 */
export async function markNoticeRead(id: string): Promise<void> {
await http.post(`/api/notice/${encodeURIComponent(id)}/read`);
}
/** 当前用户全部消息置已读 */
export async function markAllNoticesRead(): Promise<void> {
await http.post('/api/notice/read-all');
}

View File

@@ -7,6 +7,7 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { fetchTodo, type TodoItem } from '../api/todo';
import { fetchNotices, markNoticeRead, markAllNoticesRead, type NoticeItem } from '../api/notice';
import { fetchMenu, collectLeaves, type MenuLeaf } from '../api/menu';
import { loadRecentPages, type RecentPage } from '../utils/recentPages';
import { Icon } from '../components/ui/Icon';
@@ -165,6 +166,10 @@ export function WorkbenchPage() {
const [quickItems, setQuickItems] = useState<QuickItem[]>([]);
const [quickLoaded, setQuickLoaded] = useState(false);
// F2-11 通知公告快照(最近 5 条未读)
const [noticeItems, setNoticeItems] = useState<NoticeItem[]>([]);
const [noticeLoading, setNoticeLoading] = useState(true);
// 加载待办快照
useEffect(() => {
let alive = true;
@@ -217,6 +222,16 @@ export function WorkbenchPage() {
.finally(() => setQuickLoaded(true));
}, []);
// 加载通知快照(最近 5 条未读)
useEffect(() => {
let alive = true;
fetchNotices({ unreadOnly: true, page: 1, perPage: 5 })
.then((r) => { if (alive) setNoticeItems(r.items.slice(0, 5)); })
.catch(() => alive && setNoticeItems([]))
.finally(() => alive && setNoticeLoading(false));
return () => { alive = false; };
}, []);
const openPage = (templateId: string) => {
navigate(`/page/${templateId}`);
};
@@ -465,7 +480,100 @@ export function WorkbenchPage() {
</div>
</div>
{/* 通知公告区:等待 GET /api/notice 端点,当前隐藏 */}
{/* F2-11 通知公告卡片 */}
{!noticeLoading && noticeItems.length > 0 && (
<div className="card" style={{ overflow: 'hidden' }}>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '12px var(--pad)',
borderBottom: '1px solid var(--line)',
}}
>
<h3 style={{ margin: 0, fontSize: 'var(--fs)', fontWeight: 600 }}>
<Icon name="bell" size={14} style={{ marginRight: 6, color: 'var(--brand)' }} />
未读消息
<span
style={{
marginLeft: 8,
background: 'var(--err)',
color: '#fff',
borderRadius: 10,
padding: '1px 7px',
fontSize: 11,
fontWeight: 700,
verticalAlign: 'middle',
}}
>
{noticeItems.length}
</span>
</h3>
<button
className="btn btn-text btn"
onClick={async () => {
await markAllNoticesRead().catch(() => null);
setNoticeItems([]);
}}
>
全部已读
</button>
</div>
{noticeItems.map((item) => (
<div
key={item.id}
style={{
display: 'flex',
alignItems: 'center',
gap: 10,
padding: '10px var(--pad)',
borderBottom: '1px solid var(--line)',
cursor: 'pointer',
}}
onClick={async () => {
await markNoticeRead(item.id).catch(() => null);
setNoticeItems((prev) => prev.filter((n) => n.id !== item.id));
}}
onMouseEnter={(e) =>
((e.currentTarget as HTMLDivElement).style.background = 'var(--brand-softer)')
}
onMouseLeave={(e) =>
((e.currentTarget as HTMLDivElement).style.background = '')
}
>
<span
style={{
width: 8,
height: 8,
borderRadius: '50%',
background: 'var(--brand)',
flexShrink: 0,
}}
/>
<span
style={{
flex: 1,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
fontSize: 'var(--fs)',
}}
>
{item.title}
</span>
{item.createtime && (
<span className="muted" style={{ fontSize: 'var(--fs-sm)', flexShrink: 0 }}>
{(() => {
const d = new Date(item.createtime);
return `${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
})()}
</span>
)}
</div>
))}
</div>
)}
</div>
);
}

View File

@@ -13,12 +13,14 @@ import { getProfile } from '../auth/token';
import { collectLeaves, fetchMenu } from '../api/menu';
import type { MenuLeaf } from '../api/menu';
import { fetchTodo } from '../api/todo';
import { fetchUnreadCount } from '../api/notice';
import { ToastHost } from '../components/ui/Toast';
import { Topbar } from './Topbar';
import { SideMenu } from './SideMenu';
import { TabBar } from './TabBar';
import type { Tab } from './TabBar';
import { SettingsDrawer, initTheme } from './SettingsDrawer';
import { NoticeDrawer } from './NoticeDrawer';
import { TabTitleContext } from './TabTitleContext';
const TABS_KEY = 'eip4-tabs';
@@ -67,7 +69,11 @@ export function AppShell() {
const [leaves, setLeaves] = useState<MenuLeaf[]>([]);
// 顶栏铃铛真实待办数(F1-3:接真实 API)
const [todoBadge, setTodoBadge] = useState<number | undefined>(undefined);
// F2-11 消息未读数
const [noticeBadge, setNoticeBadge] = useState<number | undefined>(undefined);
const [showNotice, setShowNotice] = useState(false);
const pollTimer = useRef<ReturnType<typeof setInterval> | null>(null);
const noticePollTimer = useRef<ReturnType<typeof setInterval> | null>(null);
const profile = getProfile();
@@ -145,6 +151,20 @@ export function AppShell() {
};
}, []);
// F2-11 消息未读数轮询(60s,与待办同频)
useEffect(() => {
const loadNoticeBadge = () => {
fetchUnreadCount()
.then((n) => setNoticeBadge(n > 0 ? n : undefined))
.catch(() => setNoticeBadge(undefined));
};
loadNoticeBadge();
noticePollTimer.current = setInterval(loadNoticeBadge, TODO_POLL_INTERVAL);
return () => {
if (noticePollTimer.current) clearInterval(noticePollTimer.current);
};
}, []);
// F2-13:回填 Tab 标题(PageRenderPage 拿到 schema title 后调用)
const updateTabTitle = useCallback((path: string, title: string) => {
setTabs((prev) =>
@@ -226,7 +246,9 @@ export function AppShell() {
leaves={leaves}
profile={profile}
todoBadge={todoBadge}
noticeBadge={noticeBadge}
onOpenTodo={() => handleActive('/todo')}
onOpenNotice={() => setShowNotice(true)}
onOpenTemplate={handleSearchOpen}
onOpenSettings={() => setShowSettings(true)}
/>
@@ -258,6 +280,18 @@ export function AppShell() {
<ToastHost />
{showSettings ? <SettingsDrawer onClose={() => setShowSettings(false)} /> : null}
{/* F2-11 消息中心抽屉 */}
{showNotice ? (
<NoticeDrawer
onClose={() => setShowNotice(false)}
onReadChange={() => {
fetchUnreadCount()
.then((n) => setNoticeBadge(n > 0 ? n : undefined))
.catch(() => setNoticeBadge(undefined));
}}
/>
) : null}
</div>
);
}

306
src/shell/NoticeDrawer.tsx Normal file
View File

@@ -0,0 +1,306 @@
// NoticeDrawer — F2-11 消息中心抽屉
// 从铃铛图标点击弹出,显示站内消息列表;支持单条置已读、全部已读、展开内容
import { useEffect, useRef, useState } from 'react';
import { Icon } from '../components/ui/Icon';
import {
fetchNotices,
markNoticeRead,
markAllNoticesRead,
type NoticeItem,
} from '../api/notice';
interface NoticeDrawerProps {
onClose: () => void;
/** 关闭后通知父层刷新未读数 */
onReadChange: () => void;
}
/** 格式化毫秒时间戳为可读字符串 */
function fmtTime(ts: number | null): string {
if (!ts) return '';
const d = new Date(ts);
const now = new Date();
const diffMs = now.getTime() - d.getTime();
const diffMin = Math.floor(diffMs / 60_000);
if (diffMin < 1) return '刚刚';
if (diffMin < 60) return `${diffMin} 分钟前`;
const diffH = Math.floor(diffMin / 60);
if (diffH < 24) return `${diffH} 小时前`;
const diffD = Math.floor(diffH / 24);
if (diffD < 7) return `${diffD} 天前`;
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}
export function NoticeDrawer({ onClose, onReadChange }: NoticeDrawerProps) {
const [items, setItems] = useState<NoticeItem[]>([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(true);
const [unreadOnly, setUnreadOnly] = useState(false);
const [expandedId, setExpandedId] = useState<string | null>(null);
const [markingAll, setMarkingAll] = useState(false);
const drawerRef = useRef<HTMLDivElement>(null);
// 加载消息列表
const load = (unread: boolean) => {
setLoading(true);
fetchNotices({ unreadOnly: unread, page: 1, perPage: 20 })
.then((r) => {
setItems(r.items);
setTotal(r.total);
})
.catch(() => {
setItems([]);
setTotal(0);
})
.finally(() => setLoading(false));
};
useEffect(() => {
load(unreadOnly);
}, [unreadOnly]);
// 点击抽屉外部关闭
useEffect(() => {
const handler = (e: MouseEvent) => {
if (drawerRef.current && !drawerRef.current.contains(e.target as Node)) {
onClose();
}
};
document.addEventListener('mousedown', handler);
return () => document.removeEventListener('mousedown', handler);
}, [onClose]);
// 单条置已读
const handleRead = async (item: NoticeItem) => {
// 展开/收起内容
setExpandedId((prev) => (prev === item.id ? null : item.id));
if (item.isread === 0) {
try {
await markNoticeRead(item.id);
setItems((prev) =>
prev.map((i) => (i.id === item.id ? { ...i, isread: 1 } : i)),
);
onReadChange();
} catch {
// 静默失败,不影响 UI
}
}
};
// 全部已读
const handleReadAll = async () => {
setMarkingAll(true);
try {
await markAllNoticesRead();
setItems((prev) => prev.map((i) => ({ ...i, isread: 1 })));
onReadChange();
} catch {
// 静默失败
} finally {
setMarkingAll(false);
}
};
const unreadCount = items.filter((i) => i.isread === 0).length;
return (
<>
{/* 半透明遮罩 */}
<div
style={{
position: 'fixed',
inset: 0,
background: 'rgba(0,0,0,0.18)',
zIndex: 999,
}}
/>
{/* 抽屉主体 */}
<div
ref={drawerRef}
style={{
position: 'fixed',
top: 0,
right: 0,
bottom: 0,
width: 400,
background: 'var(--surface)',
boxShadow: '-4px 0 24px rgba(0,0,0,0.12)',
zIndex: 1000,
display: 'flex',
flexDirection: 'column',
overflow: 'hidden',
}}
>
{/* 头部 */}
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '14px 16px',
borderBottom: '1px solid var(--line)',
flexShrink: 0,
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<Icon name="bell" size={16} />
<span style={{ fontWeight: 600, fontSize: 'var(--fs)' }}>消息中心</span>
{unreadCount > 0 && (
<span
style={{
background: 'var(--err)',
color: '#fff',
borderRadius: 10,
padding: '1px 7px',
fontSize: 11,
fontWeight: 700,
}}
>
{unreadCount}
</span>
)}
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
{unreadCount > 0 && (
<button
className="btn btn-text btn"
onClick={handleReadAll}
disabled={markingAll}
style={{ fontSize: 'var(--fs-sm)' }}
>
{markingAll ? '处理中…' : '全部已读'}
</button>
)}
<button className="tb-icon" onClick={onClose} title="关闭">
<Icon name="x" size={16} />
</button>
</div>
</div>
{/* 过滤标签 */}
<div
style={{
display: 'flex',
gap: 8,
padding: '8px 16px',
borderBottom: '1px solid var(--line)',
flexShrink: 0,
}}
>
{(['全部', '仅未读'] as const).map((label, i) => {
const active = i === 0 ? !unreadOnly : unreadOnly;
return (
<button
key={label}
className={`btn btn-sm ${active ? 'btn-pri' : 'btn-text'}`}
onClick={() => setUnreadOnly(i === 1)}
>
{label}
</button>
);
})}
<span className="muted" style={{ fontSize: 'var(--fs-sm)', marginLeft: 'auto', lineHeight: '28px' }}>
共 {total} 条
</span>
</div>
{/* 消息列表 */}
<div style={{ flex: 1, overflowY: 'auto' }}>
{loading && (
<div className="empty" style={{ color: 'var(--text-3)' }}>加载中…</div>
)}
{!loading && items.length === 0 && (
<div className="empty">
<Icon name="bell" size={28} style={{ color: 'var(--text-3)' }} />
{unreadOnly ? '没有未读消息' : '暂无消息'}
</div>
)}
{!loading && items.map((item) => {
const isExpanded = expandedId === item.id;
return (
<div
key={item.id}
onClick={() => handleRead(item)}
style={{
padding: '12px 16px',
borderBottom: '1px solid var(--line)',
cursor: 'pointer',
background: item.isread === 0 ? 'var(--brand-softer)' : 'var(--surface)',
transition: 'background .1s',
}}
onMouseEnter={(e) =>
((e.currentTarget as HTMLDivElement).style.background =
item.isread === 0 ? 'var(--brand-soft)' : 'var(--surface-2)')
}
onMouseLeave={(e) =>
((e.currentTarget as HTMLDivElement).style.background =
item.isread === 0 ? 'var(--brand-softer)' : 'var(--surface)')
}
>
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 8 }}>
{/* 未读蓝点 */}
<span
style={{
width: 8,
height: 8,
borderRadius: '50%',
background: item.isread === 0 ? 'var(--brand)' : 'transparent',
flexShrink: 0,
marginTop: 6,
}}
/>
<div style={{ flex: 1, minWidth: 0 }}>
<div
style={{
fontWeight: item.isread === 0 ? 600 : 400,
fontSize: 'var(--fs)',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: isExpanded ? 'normal' : 'nowrap',
}}
>
{item.title}
</div>
{isExpanded && item.summary && (
<div
style={{
marginTop: 6,
fontSize: 'var(--fs-sm)',
color: 'var(--text-2)',
lineHeight: 1.6,
whiteSpace: 'pre-wrap',
wordBreak: 'break-word',
}}
>
{item.summary}
</div>
)}
<div
style={{
marginTop: 4,
fontSize: 11,
color: 'var(--text-3)',
display: 'flex',
gap: 8,
}}
>
{item.type != null && (
<span className="tag tag-info" style={{ fontSize: 10 }}>
{item.type}
</span>
)}
<span>{fmtTime(item.createtime)}</span>
</div>
</div>
</div>
</div>
);
})}
</div>
</div>
</>
);
}

View File

@@ -9,7 +9,9 @@ interface TopbarProps {
leaves: MenuLeaf[];
profile: UserProfile | null;
todoBadge?: number;
noticeBadge?: number;
onOpenTodo: () => void;
onOpenNotice: () => void;
onOpenTemplate: (templateId: string) => void;
onOpenSettings: () => void;
}
@@ -18,7 +20,9 @@ export function Topbar({
leaves,
profile,
todoBadge,
noticeBadge,
onOpenTodo,
onOpenNotice,
onOpenTemplate,
onOpenSettings,
}: TopbarProps) {
@@ -51,6 +55,14 @@ export function Topbar({
) : null}
</button>
{/* 消息铃铛(F2-11) */}
<button className="tb-icon" title="消息" onClick={onOpenNotice}>
<Icon name="doc" size={17} />
{noticeBadge && noticeBadge > 0 ? (
<span className="tb-badge">{noticeBadge > 99 ? '99+' : noticeBadge}</span>
) : null}
</button>
{/* 设置 */}
<button className="tb-icon" title="界面设置" onClick={onOpenSettings}>
<Icon name="gear" size={17} />