fix: 待审通知实时回填审核态并重构消息页体验

This commit is contained in:
2026-09-02 01:39:27 +08:00
parent 2e9c42a34c
commit 1c0f7ede55
18 changed files with 1458 additions and 463 deletions

View File

@@ -1,6 +1,18 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import { ArrowLeft, Bell, CheckCheck, Inbox, Mail, Send } from 'lucide-react';
import {
ArrowLeft,
AtSign,
Bell,
CheckCheck,
Flag,
Inbox,
Mail,
MessageCircleReply,
Send,
ShieldAlert,
XCircle,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import { notify } from '@/lib/notify';
@@ -9,7 +21,7 @@ import type { MessageConversation, PrivateMessage, User } from '../api/types';
import { useAuth } from '../hooks/useAuth';
import { loginPath } from '../utils/authRedirect';
import { useNoIndexSEO } from '../hooks/usePageSEO';
import { formatTime } from '../utils/content';
import { formatDateTime, formatTime } from '../utils/content';
import { postPath } from '../utils/permalink';
import { userPath } from '../utils/userPath';
import { InFlowSiteFooter } from '../components/SiteFooter';
@@ -20,7 +32,6 @@ import { PAGE_SOFT_REFRESH_COMMIT_EVENT } from '../utils/softRefresh';
type MsgTab = 'dm' | 'notify';
type ConvSnap = { conversations: MessageConversation[]; total: number; page: number };
type NotifySnap = { notifications: PrivateMessage[]; total: number; page: number };
type ThreadSnap = { messages: PrivateMessage[]; total: number; peerUser: User | null };
const NOTIFY_KINDS = [
@@ -28,23 +39,91 @@ const NOTIFY_KINDS = [
{ key: 'reply', label: '回复' },
{ key: 'mention', label: '@提及' },
{ key: 'moderation', label: '待审' },
{ key: 'reject', label: '拒帖' },
{ key: 'reject', label: '未通过' },
{ key: 'report_result', label: '举报' },
{ key: 'system', label: '系统' },
] as const;
function kindLabel(kind: string) {
function kindLabel(kind: string, relatedStatus?: string) {
if (kind === 'moderation') {
if (relatedStatus && relatedStatus !== 'pending') return '审核';
return '待审';
}
switch (kind) {
case 'reject': return '拒帖通知';
case 'reject': return '未通过';
case 'report_result': return '举报结果';
case 'reply': return '回复提醒';
case 'mention': return '@提及';
case 'moderation': return '待审提醒';
case 'system': return '系统通知';
default: return '通知';
}
}
function statusLabel(status?: string) {
switch (status) {
case 'pending': return '待审';
case 'published': return '已通过';
case 'rejected': return '未通过';
case 'deleted': return '已删除';
default: return '';
}
}
/** 仍待处理的审核通知(无状态按待审处理,兼容未回填) */
function isPendingModeration(m: PrivateMessage) {
return m.kind === 'moderation' && (!m.related_status || m.related_status === 'pending');
}
function KindIcon({ kind }: { kind: string }) {
const props = { size: 15, 'aria-hidden': true as const };
switch (kind) {
case 'reply': return <MessageCircleReply {...props} />;
case 'mention': return <AtSign {...props} />;
case 'moderation': return <ShieldAlert {...props} />;
case 'reject': return <XCircle {...props} />;
case 'report_result': return <Flag {...props} />;
default: return <Bell {...props} />;
}
}
/** 按通知类型生成跳转目标与 CTA 文案(待审跳前台帖/楼层) */
function notifyTarget(m: PrivateMessage): { to: string; label: string } | null {
const postID = m.related_post_id;
const commentID = m.related_comment_id;
const floor = m.related_floor && m.related_floor > 0 ? m.related_floor : 0;
const looksLikeComment =
(m.subject || '').includes('评论') || (m.content || '').includes('评论');
if (m.kind === 'moderation') {
if (!postID) return null;
const isComment = !!commentID || looksLikeComment;
const path = isComment && floor > 0
? `${postPath(postID)}#floor-${floor}`
: postPath(postID);
const pending = isPendingModeration(m);
if (isComment) {
return { to: path, label: pending ? '去审核评论' : '查看评论' };
}
return { to: path, label: pending ? '去审核帖子' : '查看帖子' };
}
if (postID) {
const path = floor > 0 ? `${postPath(postID)}#floor-${floor}` : postPath(postID);
if (m.kind === 'reply' || m.kind === 'mention') {
return { to: path, label: floor > 0 ? '查看回复' : '查看帖子' };
}
if (m.kind === 'reject' && (commentID || looksLikeComment)) {
return { to: path, label: '查看评论' };
}
if (m.kind === 'report_result' && floor > 0) {
return { to: path, label: '查看评论' };
}
return { to: path, label: '查看帖子' };
}
return null;
}
function peerTitle(conv: MessageConversation | null, peerUser: User | null | undefined, peerId: number) {
if (peerId === 0 || conv?.is_system) return '系统通知';
return peerUser?.nickname || conv?.peer_user?.nickname || `用户 #${peerId}`;
@@ -72,7 +151,7 @@ function AvatarBubble({
if (system) {
return (
<span className="pm-avatar pm-avatar--system" aria-hidden>
<Bell size={16} />
<Bell size={14} />
</span>
);
}
@@ -83,7 +162,6 @@ function AvatarBubble({
}
function parseTab(raw: string | null, peer: string | null): MsgTab {
// 带 peer 时强制私信页(用户主页「发私信」入口)
if (peer !== null && peer !== '') return 'dm';
return raw === 'notify' ? 'notify' : 'dm';
}
@@ -121,16 +199,23 @@ export default function MessagesPage() {
const [notifyLoading, setNotifyLoading] = useState(false);
const [notifyUnread, setNotifyUnread] = useState(0);
const [dmUnread, setDmUnread] = useState(0);
const [unreadOnly, setUnreadOnly] = useState(false);
const threadEndRef = useRef<HTMLDivElement>(null);
const threadScrollRef = useRef<HTMLDivElement>(null);
const stickToBottomRef = useRef(true);
const notifyLoadSeq = useRef(0);
const dmConversations = useMemo(
() => conversations.filter((c) => !c.is_system && c.peer_user_id > 0),
[conversations],
);
const visibleNotifications = useMemo(
() => (unreadOnly ? notifications.filter((m) => !m.is_read) : notifications),
[notifications, unreadOnly],
);
const refreshUnreadSplit = useCallback(async () => {
try {
const r = await api.messageUnreadCount();
@@ -173,18 +258,9 @@ export default function MessagesPage() {
}
}, []);
// 通知列表不走 session 短路,保证 related_status 实时
const loadNotifications = useCallback(async (page = 1, append = false, kind = 'all') => {
const key = `messages:notify:${kind}:${page}`;
if (!append) {
const hit = getSessionSnapshot<NotifySnap>(key);
if (hit) {
setNotifications(hit.notifications);
setNotifyTotal(hit.total);
setNotifyPage(hit.page);
setNotifyLoading(false);
return;
}
}
const seq = ++notifyLoadSeq.current;
setNotifyLoading(true);
try {
const r = await api.messageNotifications({
@@ -192,24 +268,16 @@ export default function MessagesPage() {
size: 30,
kind: kind === 'all' ? undefined : kind,
});
if (seq !== notifyLoadSeq.current) return;
const next = r.notifications || [];
setNotifyTotal(r.total || 0);
setNotifyPage(r.page || page);
// 打开通知页时标已读(首屏)
if (!append && page === 1) {
await api.markNotificationsRead().catch(() => undefined);
const marked = next.map((m) => ({ ...m, is_read: true }));
setNotifications(marked);
setSessionSnapshot(key, { notifications: marked, total: r.total || 0, page: r.page || page });
setNotifyUnread(0);
window.dispatchEvent(new Event('messages-unread-refresh'));
} else {
setNotifications((prev) => (append ? [...prev, ...next] : next));
}
setNotifications((prev) => (append ? [...prev, ...next] : next));
} catch (e: unknown) {
if (seq !== notifyLoadSeq.current) return;
notify.error(e instanceof Error ? e.message : '加载通知失败');
} finally {
setNotifyLoading(false);
if (seq === notifyLoadSeq.current) setNotifyLoading(false);
}
}, []);
@@ -221,18 +289,16 @@ export default function MessagesPage() {
nav(loginPath('/messages'));
return;
}
void refreshUnreadSplit();
if (tab === 'dm') {
if (!getSessionSnapshot('messages:conv:1')) void refreshUnreadSplit();
loadConversations(1);
} else {
if (!getSessionSnapshot(`messages:notify:${notifyKind}:1`)) void refreshUnreadSplit();
loadNotifications(1, false, notifyKind);
}
}, [user, authLoading, nav, tab, notifyKind, loadConversations, loadNotifications, refreshUnreadSplit]);
useEffect(() => {
const onForce = () => {
// 下拉预热会话列表后直接重读;线程快照需作废以便重拉
void refreshUnreadSplit();
if (tab === 'dm') {
void loadConversations(1);
@@ -241,8 +307,6 @@ export default function MessagesPage() {
setThreadEpoch(n => n + 1);
}
} else {
// 通知列表:预热未覆盖 kind,作废后重拉
deleteSessionSnapshot(`messages:notify:${notifyKind}:1`);
void loadNotifications(1, false, notifyKind);
}
};
@@ -365,6 +429,23 @@ export default function MessagesPage() {
}
};
const openNotification = async (m: PrivateMessage) => {
const target = notifyTarget(m);
if (!m.is_read) {
setNotifications((prev) => prev.map((item) => (item.id === m.id ? { ...item, is_read: true } : item)));
setNotifyUnread((n) => Math.max(0, n - 1));
api.markMessageRead(m.id)
.then(() => {
window.dispatchEvent(new Event('messages-unread-refresh'));
void refreshUnreadSplit();
})
.catch(() => undefined);
}
if (target) {
nav(target.to);
}
};
const loadOlder = async () => {
if (!peerSelected || selectedPeer === null || messages.length === 0) return;
const oldest = messages[0]?.id;
@@ -452,15 +533,10 @@ export default function MessagesPage() {
return (
<div className="page-wrap">
<div className="page-inner-wide">
<Button variant="ghost" className="mb-3" onClick={() => nav('/')}>
<ArrowLeft />
返回
</Button>
<div className="pm-page-head">
<div>
<h1 className="page-title">站内消息</h1>
<p className="page-desc">私信与系统通知分开查看,回复提醒可直达帖子</p>
<p className="page-desc">点开才标已读;待审可直达帖内位置</p>
</div>
{unreadForTab > 0 && (
<Button variant="outline" size="sm" onClick={markAll}>
@@ -470,246 +546,288 @@ export default function MessagesPage() {
)}
</div>
<div className="pm-tabs" role="tablist" aria-label="消息类型">
<button
type="button"
role="tab"
aria-selected={tab === 'dm'}
className={cn('pm-tab', tab === 'dm' && 'active')}
onClick={() => setTab('dm')}
>
<Mail size={15} aria-hidden />
私信
{dmUnread > 0 && <span className="pm-tab__badge">{dmUnread > 99 ? '99+' : dmUnread}</span>}
</button>
<button
type="button"
role="tab"
aria-selected={tab === 'notify'}
className={cn('pm-tab', tab === 'notify' && 'active')}
onClick={() => setTab('notify')}
>
<Bell size={15} aria-hidden />
通知
{notifyUnread > 0 && <span className="pm-tab__badge">{notifyUnread > 99 ? '99+' : notifyUnread}</span>}
</button>
</div>
{tab === 'notify' ? (
<div className="pm-notify content-surface">
<div className="pm-notify-filters" role="tablist" aria-label="通知类型">
{NOTIFY_KINDS.map((k) => (
<button
key={k.key}
type="button"
role="tab"
aria-selected={notifyKind === k.key}
className={cn('pm-notify-filter', notifyKind === k.key && 'active')}
onClick={() => setKind(k.key)}
>
{k.label}
</button>
))}
</div>
{notifyLoading && notifications.length === 0 ? (
<div className="flex justify-center py-16"><Spinner /></div>
) : notifications.length === 0 ? (
<div className="pm-empty">
<Bell size={28} strokeWidth={1.5} aria-hidden />
<p>暂无通知</p>
<span>有人回复你、审核结果等会出现在这里</span>
</div>
) : (
<ul className="pm-notify-list">
{notifications.map((m) => (
<li key={m.id} className={cn('pm-notify-item', !m.is_read && 'unread')}>
<div className="pm-notify-item__kind">{kindLabel(m.kind)}</div>
{m.subject && <div className="pm-notify-item__subject">{m.subject}</div>}
<div className="pm-notify-item__text">{m.content}</div>
<div className="pm-notify-item__meta">
<time>{formatTime(m.created_at)}</time>
{m.related_post_id ? (
<Link className="pm-notify-item__link" to={postPath(m.related_post_id)}>
查看帖子
</Link>
) : null}
</div>
</li>
))}
</ul>
)}
{notifyTotal > notifications.length && (
<div className="pm-list-more">
<Button
variant="ghost"
size="sm"
disabled={notifyLoading}
onClick={() => loadNotifications(notifyPage + 1, true, notifyKind)}
>
加载更多通知
</Button>
</div>
)}
<div className="pm-workspace content-surface">
<div className="pm-tabs" role="tablist" aria-label="消息类型">
<button
type="button"
role="tab"
aria-selected={tab === 'dm'}
className={cn('pm-tab', tab === 'dm' && 'active')}
onClick={() => setTab('dm')}
>
<Mail size={15} aria-hidden />
私信
{dmUnread > 0 && <span className="pm-tab__badge">{dmUnread > 99 ? '99+' : dmUnread}</span>}
</button>
<button
type="button"
role="tab"
aria-selected={tab === 'notify'}
className={cn('pm-tab', tab === 'notify' && 'active')}
onClick={() => setTab('notify')}
>
<Bell size={15} aria-hidden />
通知
{notifyUnread > 0 && <span className="pm-tab__badge">{notifyUnread > 99 ? '99+' : notifyUnread}</span>}
</button>
</div>
) : (
<div className={cn('pm-layout content-surface', peerSelected && 'pm-layout--thread')}>
<aside className="pm-list" aria-label="会话列表">
{listLoading && dmConversations.length === 0 ? (
<div className="flex justify-center py-10"><Spinner /></div>
) : dmConversations.length === 0 ? (
{tab === 'notify' ? (
<div className="pm-notify">
<div className="pm-notify-toolbar">
<div className="pm-notify-filters" role="tablist" aria-label="通知类型">
{NOTIFY_KINDS.map((k) => (
<button
key={k.key}
type="button"
role="tab"
aria-selected={notifyKind === k.key}
className={cn(
'pm-notify-filter',
notifyKind === k.key && 'active',
)}
onClick={() => setKind(k.key)}
>
{k.label}
</button>
))}
</div>
<button
type="button"
className={cn('pm-notify-unread-toggle', unreadOnly && 'active')}
aria-pressed={unreadOnly}
onClick={() => setUnreadOnly((v) => !v)}
>
只看未读
</button>
</div>
{notifyLoading && notifications.length === 0 ? (
<div className="flex justify-center py-16"><Spinner /></div>
) : visibleNotifications.length === 0 ? (
<div className="pm-empty">
<Inbox size={28} strokeWidth={1.5} aria-hidden />
<p>还没有私信</p>
<span>在用户主页点击「发私信」开始对话</span>
<Bell size={28} strokeWidth={1.5} aria-hidden />
<p>{unreadOnly ? '没有未读通知' : '暂无通知'}</p>
<span>{unreadOnly ? '切换筛选查看全部通知' : '有人回复你、审核结果等会出现在这里'}</span>
</div>
) : (
dmConversations.map((c) => {
const name = peerTitle(c, c.peer_user, c.peer_user_id);
const active = peerSelected && selectedPeer === c.peer_user_id;
return (
<button
key={c.peer_user_id}
type="button"
className={cn('pm-conv-item', active && 'active', c.unread_count > 0 && 'unread')}
onClick={() => openPeer(c.peer_user_id)}
>
<AvatarBubble
name={name}
avatar={c.peer_user?.avatar}
/>
<div className="pm-conv-item__body">
<div className="pm-conv-item__top">
<span className="pm-conv-item__name">{name}</span>
<span className="pm-conv-item__time">
{formatTime(c.last_message?.created_at || c.updated_at)}
</span>
</div>
<div className="pm-conv-item__preview">
<span>{previewText(c.last_message)}</span>
{c.unread_count > 0 && (
<span className="pm-conv-item__badge">
{c.unread_count > 99 ? '99+' : c.unread_count}
</span>
<ul className="pm-notify-list">
{visibleNotifications.map((m) => {
const target = notifyTarget(m);
const pendingMod = isPendingModeration(m);
const st = statusLabel(m.related_status);
const clickable = !!target || !m.is_read;
return (
<li key={m.id}>
<button
type="button"
className={cn(
'pm-notify-item',
!m.is_read && 'unread',
pendingMod && 'pm-notify-item--moderation',
clickable && 'pm-notify-item--clickable',
)}
</div>
</div>
</button>
);
})
onClick={() => void openNotification(m)}
disabled={!clickable}
>
<span className="pm-notify-item__icon" aria-hidden>
<KindIcon kind={m.kind} />
</span>
<div className="pm-notify-item__body">
<div className="pm-notify-item__top">
<span className="pm-notify-item__kind">
{kindLabel(m.kind, m.related_status)}
</span>
{m.kind === 'moderation' && st && m.related_status && m.related_status !== 'pending' && (
<span className={cn('pm-notify-status', `pm-notify-status--${m.related_status}`)}>
{st}
</span>
)}
{!m.is_read && <span className="pm-notify-item__dot" aria-label="未读" />}
<time className="pm-notify-item__time">{formatTime(m.created_at)}</time>
</div>
{m.subject && <div className="pm-notify-item__subject">{m.subject}</div>}
<div className="pm-notify-item__text">{m.content}</div>
{target && (
<span className="pm-notify-item__cta">{target.label} →</span>
)}
</div>
</button>
</li>
);
})}
</ul>
)}
{convTotal > conversations.length && (
{notifyTotal > notifications.length && (
<div className="pm-list-more">
<Button
variant="ghost"
size="sm"
disabled={listLoading}
onClick={() => loadConversations(convPage + 1, true)}
disabled={notifyLoading}
onClick={() => loadNotifications(notifyPage + 1, true, notifyKind)}
>
加载更多会话
加载更多通知
</Button>
</div>
)}
</aside>
<section className="pm-thread" aria-label="会话内容">
{!peerSelected || selectedPeer === null ? (
<div className="pm-empty pm-empty--thread">
<Send size={32} strokeWidth={1.4} aria-hidden />
<p>选择左侧会话开始聊天</p>
<span>系统通知请切换到「通知」页签</span>
</div>
) : (
<>
<header className="pm-thread-head">
<button type="button" className="pm-thread-back" onClick={closeThread} aria-label="返回会话列表">
<ArrowLeft size={18} />
</button>
<AvatarBubble
name={title}
avatar={peerUser?.avatar || activeConv?.peer_user?.avatar}
/>
<div className="pm-thread-head__meta">
<Link to={userPath(selectedPeer)} className="pm-thread-head__name">{title}</Link>
<span className="pm-thread-head__sub">私信对话</span>
</div>
</header>
<div
className="pm-thread-scroll"
ref={threadScrollRef}
onScroll={(e) => {
const t = e.currentTarget;
stickToBottomRef.current = t.scrollHeight - t.scrollTop - t.clientHeight < 80;
}}
>
{threadLoading ? (
<div className="flex justify-center py-16"><Spinner /></div>
) : (
<>
{msgTotal > messages.length && (
<div className="pm-thread-older">
<Button variant="ghost" size="sm" loading={loadingOlder} onClick={loadOlder}>
查看更早消息
</Button>
</div>
) : (
<div className={cn('pm-layout', peerSelected && 'pm-layout--thread')}>
<aside className="pm-list" aria-label="会话列表">
{listLoading && dmConversations.length === 0 ? (
<div className="flex justify-center py-10"><Spinner /></div>
) : dmConversations.length === 0 ? (
<div className="pm-empty">
<Inbox size={28} strokeWidth={1.5} aria-hidden />
<p>还没有私信</p>
<span>在用户主页点击「发私信」开始对话</span>
</div>
) : (
dmConversations.map((c) => {
const name = peerTitle(c, c.peer_user, c.peer_user_id);
const active = peerSelected && selectedPeer === c.peer_user_id;
return (
<button
key={c.peer_user_id}
type="button"
className={cn('pm-conv-item', active && 'active', c.unread_count > 0 && 'unread')}
onClick={() => openPeer(c.peer_user_id)}
>
<AvatarBubble name={name} avatar={c.peer_user?.avatar} />
<div className="pm-conv-item__body">
<div className="pm-conv-item__top">
<span className="pm-conv-item__name">{name}</span>
<span className="pm-conv-item__time">
{formatDateTime(c.last_message?.created_at || c.updated_at)}
</span>
</div>
)}
{messages.length === 0 ? (
<div className="pm-empty">还没有消息,打个招呼吧</div>
) : (
messages.map((m) => {
const mine = m.from_user_id === user.id;
return (
<div
key={m.id}
className={cn('pm-bubble-row', mine && 'pm-bubble-row--mine')}
>
<div className={cn('pm-bubble', mine && 'pm-bubble--mine')}>
<div className="pm-bubble__text">{m.content}</div>
<div className="pm-bubble__meta">
<time>{formatTime(m.created_at)}</time>
<div className="pm-conv-item__preview">
<span>{previewText(c.last_message)}</span>
{c.unread_count > 0 && (
<span className="pm-conv-item__badge">
{c.unread_count > 99 ? '99+' : c.unread_count}
</span>
)}
</div>
</div>
</button>
);
})
)}
{convTotal > conversations.length && (
<div className="pm-list-more">
<Button
variant="ghost"
size="sm"
disabled={listLoading}
onClick={() => loadConversations(convPage + 1, true)}
>
加载更多会话
</Button>
</div>
)}
</aside>
<section className="pm-thread" aria-label="会话内容">
{!peerSelected || selectedPeer === null ? (
<div className="pm-empty pm-empty--thread">
<Send size={32} strokeWidth={1.4} aria-hidden />
<p>选择左侧会话开始聊天</p>
<span>系统通知请切换到「通知」页签</span>
</div>
) : (
<>
<header className="pm-thread-head">
<button type="button" className="pm-thread-back" onClick={closeThread} aria-label="返回会话列表">
<ArrowLeft size={18} />
</button>
<AvatarBubble
name={title}
avatar={peerUser?.avatar || activeConv?.peer_user?.avatar}
/>
<div className="pm-thread-head__meta">
<Link to={userPath(selectedPeer)} className="pm-thread-head__name">{title}</Link>
<span className="pm-thread-head__sub">私信对话</span>
</div>
</header>
<div
className="pm-thread-scroll"
ref={threadScrollRef}
onScroll={(e) => {
const t = e.currentTarget;
stickToBottomRef.current = t.scrollHeight - t.scrollTop - t.clientHeight < 80;
}}
>
{threadLoading ? (
<div className="flex justify-center py-16"><Spinner /></div>
) : (
<>
{msgTotal > messages.length && (
<div className="pm-thread-older">
<Button variant="ghost" size="sm" loading={loadingOlder} onClick={loadOlder}>
查看更早消息
</Button>
</div>
)}
{messages.length === 0 ? (
<div className="pm-empty">还没有消息,打个招呼吧</div>
) : (
messages.map((m) => {
const mine = m.from_user_id === user.id;
return (
<div
key={m.id}
className={cn('pm-bubble-row', mine && 'pm-bubble-row--mine')}
>
<div className={cn('pm-bubble', mine && 'pm-bubble--mine')}>
<div className="pm-bubble__text">{m.content}</div>
<div className="pm-bubble__meta">
<time>{formatDateTime(m.created_at)}</time>
</div>
</div>
</div>
</div>
);
})
)}
<div ref={threadEndRef} />
</>
)}
</div>
);
})
)}
<div ref={threadEndRef} />
</>
)}
</div>
{canCompose && (
<footer className="pm-composer">
<textarea
className="pm-composer__input"
value={draft}
onChange={(e) => setDraft(e.target.value)}
rows={2}
maxLength={4000}
placeholder={`发送给 ${title}…`}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
void send();
}
}}
/>
<Button
className="pm-composer__send"
loading={sending}
disabled={!draft.trim()}
onClick={() => void send()}
>
<Send size={16} />
发送
</Button>
</footer>
)}
</>
)}
</section>
</div>
)}
{canCompose && (
<footer className="pm-composer">
<textarea
className="pm-composer__input"
value={draft}
onChange={(e) => setDraft(e.target.value)}
rows={2}
maxLength={4000}
placeholder={`发送给 ${title}…`}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
void send();
}
}}
/>
<Button
className="pm-composer__send"
loading={sending}
disabled={!draft.trim()}
onClick={() => void send()}
>
<Send size={16} />
发送
</Button>
</footer>
)}
</>
)}
</section>
</div>
)}
</div>
<InFlowSiteFooter />
</div>
</div>

View File

@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useEffect, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Trash2, RotateCcw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
@@ -40,6 +40,8 @@ function formatAdminTime(iso: string) {
export default function AdminCommentsPage() {
const nav = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const focusId = Number(searchParams.get('id') || 0) || 0;
const { ready } = useAdminGuard();
const [tab, setTab] = useState<Tab>('pending');
const [comments, setComments] = useState<Comment[]>([]);
@@ -49,6 +51,9 @@ export default function AdminCommentsPage() {
const [totalPages, setTotalPages] = useState(1);
const [pendingCount, setPendingCount] = useState(0);
const [revComment, setRevComment] = useState<Comment | null>(null);
const [highlightId, setHighlightId] = useState<number | null>(focusId > 0 ? focusId : null);
const focusTriedRef = useRef(false);
const highlightTimer = useRef<ReturnType<typeof setTimeout>>();
const loadList = (p = page, st: Tab = tab) => {
setLoading(true);
@@ -90,6 +95,45 @@ export default function AdminCommentsPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ready, tab]);
// 从通知深链 ?id= 定位并高亮待审行
useEffect(() => {
if (!ready || loading || focusId <= 0 || focusTriedRef.current) return;
if (tab === 'trash') return;
const found = comments.find((c) => c.id === focusId);
if (found) {
focusTriedRef.current = true;
setHighlightId(focusId);
requestAnimationFrame(() => {
document.getElementById(`admin-comment-row-${focusId}`)?.scrollIntoView({
behavior: 'smooth',
block: 'center',
});
});
clearTimeout(highlightTimer.current);
highlightTimer.current = setTimeout(() => setHighlightId(null), 2800);
const next = new URLSearchParams(searchParams);
next.delete('id');
setSearchParams(next, { replace: true });
return;
}
// pending 未找到则切到全部再试一次
if (tab === 'pending') {
setTab('all');
setPage(1);
return;
}
focusTriedRef.current = true;
notify.warning('该评论可能已审核或不在当前列表');
const next = new URLSearchParams(searchParams);
next.delete('id');
setSearchParams(next, { replace: true });
}, [ready, loading, comments, focusId, tab, searchParams, setSearchParams]);
useEffect(() => () => clearTimeout(highlightTimer.current), []);
const approve = async (id: number) => {
try {
const r = await api.adminApproveComment(id);
@@ -268,7 +312,11 @@ export default function AdminCommentsPage() {
</thead>
<tbody>
{comments.map(c => (
<tr key={c.id}>
<tr
key={c.id}
id={`admin-comment-row-${c.id}`}
className={cn(highlightId === c.id && 'admin-row-highlight')}
>
<td>{c.id}</td>
<td>#{c.floor}</td>
<td>

View File

@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useEffect, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Search, Lock, LockOpen, MessageSquareOff, Trash2, RotateCcw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@@ -32,6 +32,8 @@ function formatAdminTime(iso: string) {
export default function AdminPostsPage() {
const nav = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const focusId = Number(searchParams.get('id') || 0) || 0;
const { ready } = useAdminGuard();
const [tab, setTab] = useState<Tab>('pending');
const [posts, setPosts] = useState<PostItem[]>([]);
@@ -42,6 +44,9 @@ export default function AdminPostsPage() {
const [pendingCount, setPendingCount] = useState(0);
const [keyword, setKeyword] = useState('');
const [search, setSearch] = useState('');
const [highlightId, setHighlightId] = useState<number | null>(focusId > 0 ? focusId : null);
const focusTriedRef = useRef(false);
const highlightTimer = useRef<ReturnType<typeof setTimeout>>();
const loadActive = (p = page, kw = search, status = tab === 'pending' ? 'pending' : 'all') => {
setLoading(true);
@@ -92,6 +97,43 @@ export default function AdminPostsPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps -- 仅随 tab/search/ready 刷新
}, [ready, search, tab]);
// 从通知深链 ?id= 定位并高亮
useEffect(() => {
if (!ready || loading || focusId <= 0 || focusTriedRef.current) return;
if (tab === 'trash') return;
const found = posts.find((p) => p.id === focusId);
if (found) {
focusTriedRef.current = true;
setHighlightId(focusId);
requestAnimationFrame(() => {
document.getElementById(`admin-post-row-${focusId}`)?.scrollIntoView({
behavior: 'smooth',
block: 'center',
});
});
clearTimeout(highlightTimer.current);
highlightTimer.current = setTimeout(() => setHighlightId(null), 2800);
const next = new URLSearchParams(searchParams);
next.delete('id');
setSearchParams(next, { replace: true });
return;
}
if (tab === 'pending') {
setTab('active');
return;
}
focusTriedRef.current = true;
notify.warning('该帖子可能已审核或不在当前列表');
const next = new URLSearchParams(searchParams);
next.delete('id');
setSearchParams(next, { replace: true });
}, [ready, loading, posts, focusId, tab, searchParams, setSearchParams]);
useEffect(() => () => clearTimeout(highlightTimer.current), []);
const switchTab = (next: Tab) => {
if (next === tab) return;
setTab(next);
@@ -352,7 +394,11 @@ export default function AdminPostsPage() {
{posts.map(p => {
const edited = p.updated_at && isTimeDiffSignificant(p.created_at, p.updated_at);
return (
<tr key={p.id}>
<tr
key={p.id}
id={`admin-post-row-${p.id}`}
className={cn(highlightId === p.id && 'admin-row-highlight')}
>
<td>{p.id}</td>
<td className="max-w-[200px] truncate">
<button type="button" className="admin-text-link" onClick={() => nav(`/post/${p.id}`)}>