feat: 实时消息与管理端运营能力

新增群聊/私信与公共 WebSocket 总线,站长用户内容档案,并将通知与待审角标改为推送驱动;同步精简管理仪表盘并修复主题换肤 DOM 冲突。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-09-15 22:58:16 +08:00
parent 29db9ae9b5
commit 42c395a864
55 changed files with 7607 additions and 346 deletions

View File

@@ -21,6 +21,7 @@ import {
isSuperOrOwner,
type RoleUserLike,
} from "@/lib/roles";
import { realtime, RT_MODERATION_CHANGED } from "@/lib/realtime";
import Avatar from "@/components/Avatar";
import RoleBadge from "@/components/RoleBadge";
@@ -69,7 +70,7 @@ function isActive(pathname: string, href: string, exact?: boolean) {
return exact ? pathname === href : pathname === href || pathname.startsWith(`${href}/`);
}
/** 待审核数量轮询(30 秒);仅内容审核入口可见时启用 */
/** 待审核数量:首屏 + WS 推送 + 回前台校准(无定时轮询) */
function usePendingCounts(enabled: boolean) {
const [counts, setCounts] = useState({ posts: 0, comments: 0 });
useEffect(() => {
@@ -83,14 +84,14 @@ function usePendingCounts(enabled: boolean) {
.catch(() => {});
};
load();
const t = setInterval(load, 30_000);
const off = realtime.on(RT_MODERATION_CHANGED, () => load());
const onVisible = () => {
if (document.visibilityState === "visible") load();
};
document.addEventListener("visibilitychange", onVisible);
return () => {
alive = false;
clearInterval(t);
off();
document.removeEventListener("visibilitychange", onVisible);
};
}, [enabled]);

View File

@@ -2,21 +2,22 @@ import type { Metadata } from "next";
import Link from "next/link";
import { cookies } from "next/headers";
import {
Users,
PenLine,
MessageCircle,
Activity,
Megaphone,
Palette,
ChevronRight,
UserPlus,
LayoutGrid,
ClipboardCheck,
ChevronRight,
MessageSquareText,
FileText,
Users,
} from "lucide-react";
import { fetchOverview, type OverviewResponse } from "@/lib/api";
import {
fetchOverview,
fetchAdminPendingCounts,
type PendingCounts,
} from "@/lib/api";
import { authCookieHeader } from "@/lib/cookies";
import { getMeCached } from "@/lib/serverData";
import { canModerateAny, isAdminOrAbove, isSuperOrOwner } from "@/lib/roles";
import { canModerateAny, isSuperOrOwner } from "@/lib/roles";
import Avatar from "@/components/Avatar";
import { formatRelative } from "@/lib/format";
@@ -24,7 +25,6 @@ export const metadata: Metadata = {
title: "管理仪表盘",
};
// 精确千分位(管理员视角需要真实数值,不用首页的紧凑 K/M)
const fmt = (n: number) => n.toLocaleString("zh-CN");
function greeting(hour: number) {
@@ -35,91 +35,6 @@ function greeting(hour: number) {
return "晚上好";
}
// 统计 Bento 卡:总量 + 今日增量,语义色与全站令牌一致
function StatCard({
label,
value,
foot,
icon,
color,
soft,
}: {
label: string;
value: string;
foot: string;
icon: React.ReactNode;
color: string;
soft: string;
}) {
return (
<div className="panel p-4 sm:p-5">
<div className="flex items-start justify-between gap-2">
<p className="text-[12.5px] font-semibold" style={{ color: "var(--ink-3)" }}>
{label}
</p>
<span
className="w-8 h-8 rounded-lg flex items-center justify-center shrink-0"
style={{ background: soft, color }}
aria-hidden="true"
>
{icon}
</span>
</div>
<p
className="mt-3 text-[26px] sm:text-[30px] font-extrabold tabular-nums leading-none tracking-tight"
style={{ color: "var(--ink)" }}
>
{value}
</p>
<p className="mt-2 text-[11.5px] sm:text-[12px] font-semibold" style={{ color: "var(--ink-3)" }}>
{foot}
</p>
</div>
);
}
// 快捷管理入口:整卡可点(stretch-link),图标 + 标题 + 描述 + 箭头
function QuickLink({
href,
icon,
title,
desc,
soft,
color,
}: {
href: string;
icon: React.ReactNode;
title: string;
desc: string;
soft: string;
color: string;
}) {
return (
<Link href={href} className="panel hover-lift relative block p-5 group">
<div className="flex items-start gap-3.5">
<span
className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0"
style={{ background: soft, color }}
aria-hidden="true"
>
{icon}
</span>
<div className="min-w-0 flex-1">
<p className="text-[15px] font-extrabold" style={{ color: "var(--ink)" }}>
{title}
</p>
<p className="meta mt-1 text-[12.5px] leading-relaxed">{desc}</p>
</div>
<ChevronRight
size={17}
className="shrink-0 mt-1 transition-transform group-hover:translate-x-0.5"
style={{ color: "var(--ink-3)" }}
/>
</div>
</Link>
);
}
function PanelHead({ title, extra }: { title: string; extra?: string }) {
return (
<div
@@ -138,12 +53,86 @@ function PanelHead({ title, extra }: { title: string; extra?: string }) {
);
}
/** 待办工作区:待审帖子 / 评论数量,整块进入审核页 */
function PendingWorkPanel({ counts }: { counts: PendingCounts }) {
const total = counts.posts + counts.comments;
const idle = total === 0;
return (
<Link
href="/admin/moderation"
className="panel hover-lift relative block p-4 sm:p-5 mb-4 group"
>
<div className="flex items-start gap-3.5">
<span
className="w-11 h-11 rounded-xl flex items-center justify-center shrink-0"
style={{
background: idle ? "var(--tint)" : "var(--ok-soft)",
color: idle ? "var(--ink-3)" : "var(--ok)",
}}
aria-hidden="true"
>
<ClipboardCheck size={20} />
</span>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 flex-wrap">
<p className="text-[15px] font-extrabold" style={{ color: "var(--ink)" }}>
内容审核
</p>
{idle ? (
<span
className="text-[11.5px] font-semibold px-2 py-0.5 rounded-full"
style={{ background: "var(--tint)", color: "var(--ink-3)" }}
>
暂无待审
</span>
) : (
<span
className="text-[11.5px] font-semibold px-2 py-0.5 rounded-full tabular-nums"
style={{ background: "var(--ok-soft)", color: "var(--ok)" }}
>
{fmt(total)} 项待处理
</span>
)}
</div>
<div className="mt-3 flex flex-wrap gap-3 sm:gap-5">
<span className="inline-flex items-center gap-1.5 text-[13px]" style={{ color: "var(--ink-2)" }}>
<FileText size={14} style={{ color: "var(--ink-3)" }} aria-hidden="true" />
待审帖子
<strong className="tabular-nums font-extrabold" style={{ color: "var(--ink)" }}>
{fmt(counts.posts)}
</strong>
</span>
<span className="inline-flex items-center gap-1.5 text-[13px]" style={{ color: "var(--ink-2)" }}>
<MessageSquareText size={14} style={{ color: "var(--ink-3)" }} aria-hidden="true" />
待审评论
<strong className="tabular-nums font-extrabold" style={{ color: "var(--ink)" }}>
{fmt(counts.comments)}
</strong>
</span>
</div>
</div>
<ChevronRight
size={18}
className="shrink-0 mt-1 transition-transform group-hover:translate-x-0.5"
style={{ color: "var(--ink-3)" }}
/>
</div>
</Link>
);
}
export default async function AdminDashboardPage() {
const cookie = authCookieHeader(await cookies());
// 与 layout 的 /me 请求共享 React cache;概览失败降级,不阻塞仪表盘骨架
const [me, overview] = await Promise.all([
getMeCached(cookie || undefined),
const me = await getMeCached(cookie || undefined);
const canMod = canModerateAny(me.user);
const canUsers = isSuperOrOwner(me.user?.role);
const [overview, pendingCounts] = await Promise.all([
fetchOverview(cookie).catch(() => null),
canMod
? fetchAdminPendingCounts(cookie).catch(() => ({ posts: 0, comments: 0 }))
: Promise.resolve(null),
]);
const now = new Date();
@@ -162,100 +151,24 @@ export default async function AdminDashboardPage() {
return (
<div>
{/* 页头 */}
<div className="mb-5">
<h1 className="text-[22px] sm:text-[26px] font-extrabold tracking-tight" style={{ color: "var(--ink)" }}>
<h1
className="text-[22px] sm:text-[26px] font-extrabold tracking-tight"
style={{ color: "var(--ink)" }}
>
{greeting(now.getHours())},{me.user?.nickname}
</h1>
<p className="meta mt-1.5 text-[12.5px]">{dateLabel} · 这里是站点运营全貌</p>
<p className="meta mt-1.5 text-[12.5px]">{dateLabel} · 站点管理</p>
</div>
{/* 统计 Bento */}
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
<StatCard
label="注册用户"
value={stats ? fmt(stats.users) : "—"}
foot={stats ? `今日新增 +${fmt(stats.today_users)}` : "统计暂不可用"}
icon={<Users size={16} />}
color="var(--accent)"
soft="var(--accent-soft)"
/>
<StatCard
label="话题总数"
value={stats ? fmt(stats.posts) : "—"}
foot={stats ? `今日新发 +${fmt(stats.today_posts)}` : "统计暂不可用"}
icon={<PenLine size={16} />}
color="var(--clay)"
soft="var(--clay-soft)"
/>
<StatCard
label="回复总数"
value={stats ? fmt(stats.comments) : "—"}
foot={stats ? `今日新增 +${fmt(stats.today_comments)}` : "统计暂不可用"}
icon={<MessageCircle size={16} />}
color="var(--ok)"
soft="var(--ok-soft)"
/>
<StatCard
label="在线用户"
value={stats ? fmt(stats.online) : "—"}
foot={stats ? `近 5 分钟活跃 · 峰值 ${fmt(stats.peak_online)}` : "统计暂不可用"}
icon={<Activity size={16} />}
color="var(--gold)"
soft="var(--gold-soft)"
/>
</div>
{canMod && pendingCounts && <PendingWorkPanel counts={pendingCounts} />}
{/* 快捷入口(按角色权限过滤,与侧边栏一致;后端路由另有守卫) */}
<h2 className="sr-only">快捷管理</h2>
<div className="grid sm:grid-cols-2 xl:grid-cols-3 gap-3 sm:gap-4 mt-4">
{canModerateAny(me.user) && (
<QuickLink
href="/admin/moderation"
icon={<ClipboardCheck size={18} />}
title="内容审核"
desc="审核普通用户提交的帖子与评论,通过后内容公开可见"
soft="var(--ok-soft)"
color="var(--ok)"
/>
)}
{isAdminOrAbove(me.user?.role) && (
<QuickLink
href="/admin/announcements"
icon={<Megaphone size={18} />}
title="公告管理"
desc="发布、编辑与下线站点公告,支持标签颜色与草稿状态"
soft="var(--clay-soft)"
color="var(--clay)"
/>
)}
{isSuperOrOwner(me.user?.role) && (
<QuickLink
href="/admin/users"
icon={<Users size={18} />}
title="用户权限"
desc="查看全站成员,授予管理角色与板块授权,封禁违规账号"
soft="var(--accent-soft)"
color="var(--accent)"
/>
)}
{isSuperOrOwner(me.user?.role) && (
<QuickLink
href="/admin/appearance"
icon={<Palette size={18} />}
title="外观设置"
desc="配置全站主题强调色,实时预览后保存并对所有用户生效"
soft="var(--gold-soft)"
color="var(--gold)"
/>
)}
</div>
{/* 成员与板块 */}
<div className="grid lg:grid-cols-2 gap-4 mt-4 items-start">
{/* 最新注册成员 */}
<div className="grid lg:grid-cols-2 gap-4 items-start">
<div className="panel overflow-hidden">
<PanelHead title="最新注册成员" extra={stats ? `共 ${fmt(stats.users)} 人` : undefined} />
<PanelHead
title="最新注册成员"
extra={stats ? `共 ${fmt(stats.users)} 人` : undefined}
/>
{newUsers.length === 0 ? (
<p className="meta text-center py-14 text-[13px]">暂无成员数据</p>
) : (
@@ -266,12 +179,22 @@ export default async function AdminDashboardPage() {
className="flex items-center gap-3 px-4 sm:px-5 py-3 transition-colors hover:bg-[var(--panel-2)]"
style={{ borderTop: "1px solid var(--line)" }}
>
<Avatar name={u.nickname || u.username} src={u.avatar || undefined} size={34} />
<Avatar
name={u.nickname || u.username}
src={u.avatar || undefined}
size={34}
/>
<span className="min-w-0 flex-1 leading-tight">
<span className="block text-[13.5px] font-bold truncate" style={{ color: "var(--ink)" }}>
<span
className="block text-[13.5px] font-bold truncate"
style={{ color: "var(--ink)" }}
>
{u.nickname}
</span>
<span className="block text-[11.5px] truncate" style={{ color: "var(--ink-3)" }}>
<span
className="block text-[11.5px] truncate"
style={{ color: "var(--ink-3)" }}
>
@{u.username}
</span>
</span>
@@ -285,9 +208,22 @@ export default async function AdminDashboardPage() {
</Link>
))
)}
{canUsers && (
<Link
href="/admin/users"
className="flex items-center justify-center gap-1.5 px-4 py-3 text-[13px] font-semibold transition-colors hover:bg-[var(--panel-2)]"
style={{
borderTop: "1px solid var(--line)",
color: "var(--accent)",
}}
>
<Users size={14} aria-hidden="true" />
前往用户权限
<ChevronRight size={14} aria-hidden="true" />
</Link>
)}
</div>
{/* 板块分布 */}
<div className="panel overflow-hidden">
<PanelHead title="板块话题分布" extra={`${boards.length} 个板块`} />
{topBoards.length === 0 ? (
@@ -309,14 +245,19 @@ export default async function AdminDashboardPage() {
</span>
<span className="min-w-0 flex-1">
<span className="flex items-center justify-between gap-2">
<span className="text-[13.5px] font-bold truncate" style={{ color: "var(--ink)" }}>
<span
className="text-[13.5px] font-bold truncate"
style={{ color: "var(--ink)" }}
>
{b.name}
</span>
<span className="text-[12px] font-bold tabular-nums shrink-0" style={{ color: "var(--ink-2)" }}>
<span
className="text-[12px] font-bold tabular-nums shrink-0"
style={{ color: "var(--ink-2)" }}
>
{fmt(b.post_count)}
</span>
</span>
{/* 相对占比迷你条(纯装饰) */}
<span
className="block mt-1.5 h-1 rounded-full overflow-hidden"
style={{ background: "var(--tint)" }}

View File

@@ -9,6 +9,7 @@ import {
ChevronRight,
Clock,
ExternalLink,
FolderSearch,
History,
Loader2,
Monitor,
@@ -31,9 +32,10 @@ import {
type Board,
type LoginLog,
} from "@/lib/api";
import { ROLES } from "@/lib/roles";
import { isOwner, ROLES } from "@/lib/roles";
import { formatDate, formatRelative } from "@/lib/format";
import { toast } from "@/lib/toast";
import { realtime } from "@/lib/realtime";
import Avatar from "@/components/Avatar";
import RoleBadge from "@/components/RoleBadge";
@@ -156,6 +158,24 @@ export default function UsersAdmin({
.catch(() => {});
}, []);
// 在线状态实时化:WS hello 全量快照校正当前页绿点,之后 presence:update 增量跳变;
// 后端在线判定(有活跃 WS 连接)比列表接口的 5 分钟 last_seen 启发式更精确
useEffect(() => {
const reconcile = (ids: ReadonlySet<number>) => {
if (ids.size === 0) return;
setUsers((prev) =>
prev.map((u) => (u.online === ids.has(u.id) ? u : { ...u, online: ids.has(u.id) }))
);
};
reconcile(realtime.getOnlineIds());
const off = realtime.onPresence(({ user_id: id, online }) => {
setUsers((prev) =>
prev.map((u) => (u.id === id && u.online !== online ? { ...u, online } : u))
);
});
return off;
}, []);
const load = useCallback(async (opts: { page: number; filter: UserFilter; q: string }) => {
const seq = ++seqRef.current;
setLoading(true);
@@ -319,10 +339,24 @@ export default function UsersAdmin({
);
const renderActions = (u: AdminUser, isSelf: boolean) => {
// 站长账号:任何人不可操作(后端 403 兜底),仅保留主页入口与站长标识
const canAudit = isOwner(currentUserRole);
const auditBtn = canAudit ? (
<Link
href={`/admin/users/${u.id}`}
title="内容档案"
aria-label={`查看 ${u.username} 的内容档案`}
className={ghostBtn}
style={{ color: "var(--accent)" }}
>
<FolderSearch size={15} />
</Link>
) : null;
// 站长账号:不可改角色/封禁,保留主页与(站长自己的)内容档案
if (u.role === ROLES.OWNER) {
return (
<div className="flex items-center gap-1 justify-end">
{auditBtn}
<Link
href={`/u/${u.id}`}
title="查看个人主页"
@@ -336,17 +370,21 @@ export default function UsersAdmin({
}
if (isSelf) {
return (
<span
className="inline-flex items-center rounded-full px-2.5 py-1 text-[11px] font-bold whitespace-nowrap"
style={{ background: "var(--panel-2)", color: "var(--ink-3)" }}
>
当前账号
</span>
<div className="flex items-center gap-1 justify-end">
{auditBtn}
<span
className="inline-flex items-center rounded-full px-2.5 py-1 text-[11px] font-bold whitespace-nowrap"
style={{ background: "var(--panel-2)", color: "var(--ink-3)" }}
>
当前账号
</span>
</div>
);
}
const busy = actingId === u.id;
return (
<div className="flex items-center gap-1 justify-end">
{auditBtn}
<button
type="button"
title="登录历史"
@@ -623,7 +661,11 @@ export default function UsersAdmin({
</div>
<div className="min-w-0">{renderLastLogin(u)}</div>
<div className="hidden xl:block">
<p className="text-[12.5px] font-semibold tabular-nums" style={{ color: "var(--ink-2)" }}>
<p
className="text-[12.5px] font-semibold tabular-nums"
style={{ color: "var(--ink-2)" }}
title="仅统计已发布内容;驳回/删除见内容档案"
>
帖 {u.post_count} · 评 {u.comment_count}
</p>
<p className="text-[11px] tabular-nums" style={{ color: "var(--ink-3)" }}>
@@ -661,7 +703,11 @@ export default function UsersAdmin({
</div>
{renderStatus(u)}
</div>
<p className="mt-2.5 text-[11.5px] tabular-nums" style={{ color: "var(--ink-3)" }}>
<p
className="mt-2.5 text-[11.5px] tabular-nums"
style={{ color: "var(--ink-3)" }}
title="仅统计已发布内容;驳回/删除见内容档案"
>
帖 {u.post_count} · 评 {u.comment_count} · 注册 {formatDate(u.created_at)}
</p>
<p className="mt-1 text-[11.5px] tabular-nums flex items-center gap-1.5" style={{ color: "var(--ink-3)" }}>
@@ -671,37 +717,49 @@ export default function UsersAdmin({
{u.last_login_at ? ` · ${formatRelative(u.last_login_at)}` : ""}
</button>
</p>
{!isSelf && u.role !== ROLES.OWNER && (
<div className="flex items-center gap-2 mt-3 flex-wrap">
<div className="flex items-center gap-2 mt-3 flex-wrap">
{isOwner(currentUserRole) && (
<Link href={`/admin/users/${u.id}`} className="btn btn-line btn-sm">
<FolderSearch size={13} /> 内容档案
</Link>
)}
{(isSelf || u.role === ROLES.OWNER) && (
<Link href={`/u/${u.id}`} className="btn btn-line btn-sm">
<ExternalLink size={13} /> 主页
</Link>
<button
type="button"
disabled={actingId === u.id}
onClick={() => setRoleTarget(u)}
className="btn btn-line btn-sm"
style={u.role !== ROLES.USER ? { color: "var(--accent)", borderColor: "var(--accent)" } : undefined}
>
<ShieldCheck size={13} />
角色权限
</button>
<button
type="button"
disabled={actingId === u.id}
onClick={() => setBanTarget(u)}
className="btn btn-sm"
style={
u.banned
? { background: "var(--ok-soft)", color: "var(--ok)" }
: { background: "var(--danger-soft)", color: "var(--danger)" }
}
>
{u.banned ? <RotateCcw size={13} /> : <Ban size={13} />}
{u.banned ? "解封" : "封禁"}
</button>
</div>
)}
)}
{!isSelf && u.role !== ROLES.OWNER && (
<>
<Link href={`/u/${u.id}`} className="btn btn-line btn-sm">
<ExternalLink size={13} /> 主页
</Link>
<button
type="button"
disabled={actingId === u.id}
onClick={() => setRoleTarget(u)}
className="btn btn-line btn-sm"
style={u.role !== ROLES.USER ? { color: "var(--accent)", borderColor: "var(--accent)" } : undefined}
>
<ShieldCheck size={13} />
角色权限
</button>
<button
type="button"
disabled={actingId === u.id}
onClick={() => setBanTarget(u)}
className="btn btn-sm"
style={
u.banned
? { background: "var(--ok-soft)", color: "var(--ok)" }
: { background: "var(--danger-soft)", color: "var(--danger)" }
}
>
{u.banned ? <RotateCcw size={13} /> : <Ban size={13} />}
{u.banned ? "解封" : "封禁"}
</button>
</>
)}
</div>
</div>
</div>
);

View File

@@ -0,0 +1,400 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import {
ArrowLeft,
ChevronLeft,
ChevronRight,
ExternalLink,
FileText,
Loader2,
MessageCircle,
MessagesSquare,
} from "lucide-react";
import {
apiAdminUserAuditComments,
apiAdminUserAuditMessages,
apiAdminUserAuditPosts,
type AdminAuditCommentItem,
type AdminAuditMessageItem,
type AdminAuditPostItem,
type AdminUserAuditProfile,
} from "@/lib/api";
import { formatDate, formatRelative } from "@/lib/format";
import Avatar from "@/components/Avatar";
import RoleBadge from "@/components/RoleBadge";
type TabKey = "posts" | "comments" | "messages";
const TABS: { key: TabKey; label: string; icon: React.ReactNode }[] = [
{ key: "posts", label: "帖子", icon: <FileText size={14} /> },
{ key: "comments", label: "评论", icon: <MessageCircle size={14} /> },
{ key: "messages", label: "私信与群消息", icon: <MessagesSquare size={14} /> },
];
const PAGE_SIZE = 20;
function StatusChip({
status,
deleted,
recalled,
}: {
status?: string;
deleted?: boolean;
recalled?: boolean;
}) {
const chips: { label: string; color: string; soft: string }[] = [];
if (deleted) chips.push({ label: "已删除", color: "var(--danger)", soft: "var(--danger-soft)" });
if (recalled) chips.push({ label: "已撤回", color: "var(--ink-3)", soft: "var(--tint)" });
if (status === "pending") chips.push({ label: "待审", color: "var(--gold)", soft: "var(--gold-soft)" });
if (status === "rejected") chips.push({ label: "已驳回", color: "var(--danger)", soft: "var(--danger-soft)" });
if (status === "published" && !deleted) {
chips.push({ label: "已发布", color: "var(--ok)", soft: "var(--ok-soft)" });
}
if (chips.length === 0 && !recalled) {
chips.push({ label: "正常", color: "var(--ink-3)", soft: "var(--tint)" });
}
return (
<span className="inline-flex flex-wrap gap-1">
{chips.map((c) => (
<span
key={c.label}
className="inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-bold"
style={{ background: c.soft, color: c.color }}
>
{c.label}
</span>
))}
</span>
);
}
function Pager({
page,
total,
onChange,
loading,
}: {
page: number;
total: number;
onChange: (p: number) => void;
loading?: boolean;
}) {
const pages = Math.max(1, Math.ceil(total / PAGE_SIZE));
if (pages <= 1) return null;
return (
<div className="flex items-center justify-center gap-2 py-3">
<button
type="button"
disabled={page <= 1 || loading}
onClick={() => onChange(page - 1)}
className="btn btn-line btn-sm"
aria-label="上一页"
>
<ChevronLeft size={14} />
</button>
<span className="text-[12.5px] tabular-nums meta">
{page} / {pages}
</span>
<button
type="button"
disabled={page >= pages || loading}
onClick={() => onChange(page + 1)}
className="btn btn-line btn-sm"
aria-label="下一页"
>
<ChevronRight size={14} />
</button>
</div>
);
}
export default function UserAuditClient({
userId,
initial,
}: {
userId: number;
initial: AdminUserAuditProfile;
}) {
const [profile] = useState(initial);
const [tab, setTab] = useState<TabKey>("posts");
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [posts, setPosts] = useState<AdminAuditPostItem[]>([]);
const [comments, setComments] = useState<AdminAuditCommentItem[]>([]);
const [messages, setMessages] = useState<AdminAuditMessageItem[]>([]);
const [total, setTotal] = useState(0);
const u = profile.user;
const load = useCallback(
async (t: TabKey, p: number) => {
setLoading(true);
setError("");
try {
if (t === "posts") {
const res = await apiAdminUserAuditPosts(userId, p);
setPosts(res.items || []);
setTotal(res.total);
} else if (t === "comments") {
const res = await apiAdminUserAuditComments(userId, p);
setComments(res.items || []);
setTotal(res.total);
} else {
const res = await apiAdminUserAuditMessages(userId, p);
setMessages(res.items || []);
setTotal(res.total);
}
} catch (e) {
setError(e instanceof Error ? e.message : "加载失败");
} finally {
setLoading(false);
}
},
[userId]
);
useEffect(() => {
load(tab, page);
}, [tab, page, load]);
const switchTab = (t: TabKey) => {
setTab(t);
setPage(1);
};
const tabCount = (t: TabKey) => {
if (t === "posts") return profile.posts_total;
if (t === "comments") return profile.comments_total;
return profile.messages_total;
};
return (
<div>
<Link
href="/admin/users"
className="inline-flex items-center gap-1.5 text-[13px] font-semibold mb-4 hover:opacity-80"
style={{ color: "var(--accent)" }}
>
<ArrowLeft size={14} />
返回用户列表
</Link>
<div className="panel p-4 sm:p-5 mb-4">
<div className="flex items-start gap-3.5">
<Avatar name={u.nickname || u.username} src={u.avatar || undefined} size={48} />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 flex-wrap">
<h1
className="text-[18px] sm:text-[20px] font-extrabold truncate"
style={{ color: "var(--ink)" }}
>
{u.nickname}
</h1>
<RoleBadge role={u.role} />
{u.banned && (
<span
className="text-[11px] font-bold px-2 py-0.5 rounded-full"
style={{ background: "var(--danger-soft)", color: "var(--danger)" }}
>
已封禁
</span>
)}
</div>
<p className="meta text-[12.5px] mt-0.5 truncate">@{u.username}</p>
<p className="meta text-[12px] mt-2">
注册于 {formatDate(u.created_at)} · 已发布帖 {profile.published_posts} / 评{" "}
{profile.published_comments}
</p>
</div>
<Link
href={`/u/${u.id}`}
className="btn btn-line btn-sm gap-1.5 shrink-0"
target="_blank"
>
<ExternalLink size={13} />
主页
</Link>
</div>
<div
className="mt-4 grid grid-cols-3 gap-2 sm:gap-3 pt-4"
style={{ borderTop: "1px solid var(--line)" }}
>
{[
{ label: "全部帖子", value: profile.posts_total },
{ label: "全部评论", value: profile.comments_total },
{ label: "全部消息", value: profile.messages_total },
].map((c) => (
<div key={c.label} className="text-center">
<p
className="text-[20px] font-extrabold tabular-nums leading-none"
style={{ color: "var(--ink)" }}
>
{c.value.toLocaleString("zh-CN")}
</p>
<p className="meta text-[11.5px] mt-1.5">{c.label}</p>
</div>
))}
</div>
</div>
<div
className="flex gap-1 mb-3 overflow-x-auto"
style={{ borderBottom: "1px solid var(--line)" }}
>
{TABS.map((t) => {
const active = tab === t.key;
return (
<button
key={t.key}
type="button"
onClick={() => switchTab(t.key)}
className="inline-flex items-center gap-1.5 px-3 py-2.5 text-[13px] font-bold whitespace-nowrap -mb-px"
style={{
color: active ? "var(--accent)" : "var(--ink-3)",
borderBottom: active ? "2px solid var(--accent)" : "2px solid transparent",
}}
>
{t.icon}
{t.label}
<span className="tabular-nums font-semibold opacity-70">
{tabCount(t.key).toLocaleString("zh-CN")}
</span>
</button>
);
})}
</div>
<div className="panel overflow-hidden">
{error && (
<p className="text-center py-10 text-[13px]" style={{ color: "var(--danger)" }}>
{error}
</p>
)}
{!error && loading && posts.length + comments.length + messages.length === 0 && (
<div className="flex justify-center py-14" style={{ color: "var(--ink-3)" }}>
<Loader2 size={22} className="animate-spin" />
</div>
)}
{!error && !loading && total === 0 && (
<p className="meta text-center py-14 text-[13px]">该分类暂无内容</p>
)}
{tab === "posts" &&
posts.map((p) => (
<div
key={p.id}
className="px-4 sm:px-5 py-3.5"
style={{ borderTop: "1px solid var(--line)" }}
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 flex-wrap mb-1">
<StatusChip status={p.status} deleted={p.deleted} />
{p.board_name && (
<span className="text-[11.5px] meta truncate">{p.board_name}</span>
)}
</div>
{p.deleted ? (
<p className="text-[14px] font-bold" style={{ color: "var(--ink-3)" }}>
{p.title || "(无标题)"}
</p>
) : (
<Link
href={`/post/${p.id}`}
className="text-[14px] font-bold hover:underline"
style={{ color: "var(--ink)" }}
>
{p.title || "(无标题)"}
</Link>
)}
{p.content && (
<p className="meta text-[12.5px] mt-1 line-clamp-2 leading-relaxed">
{p.content}
</p>
)}
</div>
<span className="shrink-0 text-[11.5px] meta tabular-nums">
{formatRelative(p.created_at)}
</span>
</div>
</div>
))}
{tab === "comments" &&
comments.map((c) => (
<div
key={c.id}
className="px-4 sm:px-5 py-3.5"
style={{ borderTop: "1px solid var(--line)" }}
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 flex-wrap mb-1">
<StatusChip status={c.status} deleted={c.deleted} />
{c.deleted ? (
<span className="text-[11.5px] meta">帖子 #{c.post_id}</span>
) : (
<Link
href={`/post/${c.post_id}`}
className="text-[11.5px] font-semibold hover:underline"
style={{ color: "var(--accent)" }}
>
帖子 #{c.post_id}
</Link>
)}
</div>
<p
className="text-[13.5px] leading-relaxed whitespace-pre-wrap break-words"
style={{ color: c.deleted ? "var(--ink-3)" : "var(--ink)" }}
>
{c.content || "(空)"}
</p>
</div>
<span className="shrink-0 text-[11.5px] meta tabular-nums">
{formatRelative(c.created_at)}
</span>
</div>
</div>
))}
{tab === "messages" &&
messages.map((m) => (
<div
key={m.id}
className="px-4 sm:px-5 py-3.5"
style={{ borderTop: "1px solid var(--line)" }}
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 flex-wrap mb-1">
<StatusChip deleted={m.deleted} recalled={m.recalled} />
<span className="text-[11.5px] meta truncate">
{m.room_name}
{m.room_type === "direct" ? " · 私聊" : m.room_type === "group" ? " · 群聊" : ""}
</span>
</div>
<p
className="text-[13.5px] leading-relaxed whitespace-pre-wrap break-words"
style={{
color: m.recalled || m.deleted ? "var(--ink-3)" : "var(--ink)",
fontStyle: m.recalled ? "italic" : undefined,
}}
>
{m.content || "(空)"}
</p>
</div>
<span className="shrink-0 text-[11.5px] meta tabular-nums">
{formatRelative(m.created_at)}
</span>
</div>
</div>
))}
<Pager page={page} total={total} onChange={setPage} loading={loading} />
</div>
</div>
);
}

View File

@@ -0,0 +1,44 @@
import type { Metadata } from "next";
import { cookies } from "next/headers";
import { authCookieHeader } from "@/lib/cookies";
import { fetchAdminUserAudit } from "@/lib/api";
import { getMeCached } from "@/lib/serverData";
import { isOwner, isSuperOrOwner } from "@/lib/roles";
import Forbidden from "../../Forbidden";
import UserAuditClient from "./UserAuditClient";
export const metadata: Metadata = {
title: "用户内容档案",
};
interface PageProps {
params: Promise<{ id: string }>;
}
export default async function AdminUserAuditPage({ params }: PageProps) {
const { id: idRaw } = await params;
const userId = parseInt(idRaw, 10);
if (!Number.isFinite(userId) || userId <= 0) {
return <Forbidden text="无效的用户 ID。" />;
}
const cookie = authCookieHeader(await cookies());
const me = await getMeCached(cookie || undefined);
if (!me.user || !isSuperOrOwner(me.user.role)) {
return <Forbidden text="用户与角色权限仅超级管理员和站长可操作。" />;
}
if (!isOwner(me.user.role)) {
return <Forbidden text="用户内容档案仅站长可查看。" />;
}
let profile;
try {
profile = await fetchAdminUserAudit(userId, cookie || undefined);
} catch (e) {
const msg = e instanceof Error ? e.message : "获取用户档案失败";
return <Forbidden text={msg} />;
}
return <UserAuditClient userId={userId} initial={profile} />;
}

View File

@@ -4,9 +4,11 @@ import { cookies } from "next/headers";
import { PenSquare, MessagesSquare, ChevronRight } from "lucide-react";
import { fetchPosts, fetchBoards } from "@/lib/api";
import { authCookieHeader } from "@/lib/cookies";
import { getMeCached } from "@/lib/serverData";
import Pagination from "@/components/Pagination";
import PostRow from "@/components/PostRow";
import PinnedPosts from "@/components/PinnedPosts";
import FeedNewTip from "@/components/home/FeedNewTip";
interface PageProps {
params: Promise<{ id: string }>;
@@ -28,12 +30,14 @@ export default async function BoardPage({ params, searchParams }: PageProps) {
const { page: pageStr } = await searchParams;
const page = Math.max(1, parseInt(pageStr || "1", 10) || 1);
const cookie = authCookieHeader(await cookies());
const [postsData, boardsData] = await Promise.all([
const [postsData, boardsData, me] = await Promise.all([
fetchPosts(page, 20, Number(id), "latest", "", false, cookie),
fetchBoards(),
getMeCached(cookie || undefined),
]);
const boardIndex = boardsData.boards.findIndex((b) => b.id === Number(id));
const board = boardIndex >= 0 ? boardsData.boards[boardIndex] : null;
const user = me.user;
// 第一页:置顶帖独立成区,列表只保留非置顶
const pinned = page === 1 ? postsData.posts.filter((p) => p.pinned > 0) : [];
@@ -88,6 +92,16 @@ export default async function BoardPage({ params, searchParams }: PageProps) {
<span className="font-bold text-[15px]" style={{ color: "var(--ink)" }}>全部讨论</span>
<span className="meta text-xs">第 {page} 页</span>
</div>
{user && (
<div className="pt-2.5">
<FeedNewTip
sort="latest"
boardId={Number(id)}
page={page}
userId={user.id}
/>
</div>
)}
{rows.map((post, i) => (
<PostRow key={post.id} post={post} index={i} />
))}

View File

@@ -0,0 +1,706 @@
"use client";
import { useState, useEffect, useCallback, useRef } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
Search,
Plus,
MessageSquare,
Users,
X,
Pin,
} from "lucide-react";
import {
apiListChatRooms,
apiSearchChatUsers,
apiOpenDirectChat,
apiCreateChatRoom,
apiPinChatRoom,
type ChatRoomView,
type User,
} from "@/lib/api";
import { realtime, RT_CHAT_UNREAD, RT_CHAT_MEMBERSHIP } from "@/lib/realtime";
import type { RtChatUnreadData, RtChatMembershipData } from "@/lib/realtime";
import { toast } from "@/lib/toast";
import Avatar from "@/components/Avatar";
import ContextMenu, { type CtxMenuItem } from "@/components/ContextMenu";
function roomTitle(room: ChatRoomView) {
if (room.room_type === "direct") {
return room.peer?.nickname || room.peer?.username || room.name || "私聊";
}
return room.name || "未命名群";
}
function roomPreview(room: ChatRoomView) {
const lm = room.last_message;
if (!lm) return room.description || "暂无消息";
if (lm.recalled_at) {
if (lm.recalled_by && lm.recalled_by !== lm.sender_id) {
return "管理员撤回了此消息";
}
return "此消息已撤回";
}
const who =
room.room_type === "direct"
? ""
: `${lm.sender?.nickname || lm.sender?.username || ""}:`;
return `${who}${lm.content || ""}`.slice(0, 48);
}
function formatTime(dateStr?: string) {
if (!dateStr) return "";
const d = new Date(dateStr);
const now = new Date();
const sameDay =
d.getFullYear() === now.getFullYear() &&
d.getMonth() === now.getMonth() &&
d.getDate() === now.getDate();
if (sameDay) {
return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
}
return `${d.getMonth() + 1}/${d.getDate()}`;
}
/** 与后端一致:大厅强制置顶 > 个人置顶 > last_message_id */
function sortRooms(list: ChatRoomView[]): ChatRoomView[] {
return [...list].sort((a, b) => {
const aHall = !!a.is_default;
const bHall = !!b.is_default;
if (aHall !== bHall) return aHall ? -1 : 1;
const aPin = !aHall && !!a.pinned;
const bPin = !bHall && !!b.pinned;
if (aPin !== bPin) return aPin ? -1 : 1;
if (a.last_message_id !== b.last_message_id) {
return (b.last_message_id || 0) - (a.last_message_id || 0);
}
return b.id - a.id;
});
}
function isPinnedView(room: ChatRoomView) {
return !!room.is_default || !!room.pinned || !!room.pin_forced;
}
/**
* PC 端飞书式消息壳:左会话列表 + 右会话区;移动端列表/会话互斥全屏。
*/
export default function ChatShell({
meId,
initialRooms,
activeRoomId = null,
children,
}: {
meId: number;
initialRooms: ChatRoomView[];
activeRoomId?: number | null;
children?: React.ReactNode;
}) {
const router = useRouter();
const [rooms, setRooms] = useState<ChatRoomView[]>(initialRooms);
const [query, setQuery] = useState("");
const [userHits, setUserHits] = useState<User[]>([]);
const [searching, setSearching] = useState(false);
const [showCreate, setShowCreate] = useState(false);
const [ctxMenu, setCtxMenu] = useState<{
x: number;
y: number;
room: ChatRoomView;
} | null>(null);
const longPressTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
setRooms(sortRooms(initialRooms));
}, [initialRooms]);
const refreshRooms = useCallback(async () => {
try {
const res = await apiListChatRooms(1, 50, "", "joined");
setRooms(sortRooms(res.rooms || []));
} catch {
// 静默
}
}, []);
// 每次进入消息壳都用 HTTP 拉最新排序(避免首页 Link 预取/路由缓存导致新消息会话不置顶)
useEffect(() => {
refreshRooms();
}, [refreshRooms, activeRoomId]);
// 从其他标签页切回时也对账一次
useEffect(() => {
const onVisible = () => {
if (document.visibilityState === "visible") refreshRooms();
};
document.addEventListener("visibilitychange", onVisible);
return () => document.removeEventListener("visibilitychange", onVisible);
}, [refreshRooms]);
// 实时未读:更新侧栏角标与预览,按置顶规则重排(不盲目置顶到最前)
useEffect(() => {
const off = realtime.on<RtChatUnreadData>(RT_CHAT_UNREAD, (data) => {
if (!data?.room_id) return;
if (activeRoomId === data.room_id) return;
setRooms((prev) => {
const idx = prev.findIndex((r) => r.id === data.room_id);
if (idx < 0) {
refreshRooms();
return prev;
}
const next = [...prev];
const cur = next[idx];
next[idx] = {
...cur,
unread_count: (cur.unread_count || 0) + (data.delta || 1),
last_message_id: data.message_id,
last_message: {
id: data.message_id,
room_id: data.room_id,
sender_id: data.sender_id,
content: data.preview || "",
created_at: new Date().toISOString(),
sender: cur.last_message?.sender || ({
id: data.sender_id,
username: "",
nickname: "",
avatar: "",
role: "user",
} as User),
},
};
return sortRooms(next);
});
});
return off;
}, [activeRoomId, refreshRooms]);
useEffect(() => {
const off = realtime.on<RtChatMembershipData>(RT_CHAT_MEMBERSHIP, (data) => {
if (!data) return;
if (data.status === "invited" || data.status === "dissolved" || data.status === "kicked") {
refreshRooms();
}
});
return off;
}, [refreshRooms]);
// 进入会话后清零该会话未读
useEffect(() => {
if (!activeRoomId) return;
setRooms((prev) =>
prev.map((r) => (r.id === activeRoomId ? { ...r, unread_count: 0 } : r))
);
}, [activeRoomId]);
// 搜索:会话本地过滤 + 用户远程搜索
useEffect(() => {
const q = query.trim();
if (!q) {
setUserHits([]);
return;
}
const t = setTimeout(async () => {
setSearching(true);
try {
const res = await apiSearchChatUsers(q);
setUserHits(res.users || []);
} catch {
setUserHits([]);
} finally {
setSearching(false);
}
}, 300);
return () => clearTimeout(t);
}, [query]);
const filteredRooms = (() => {
const q = query.trim().toLowerCase();
if (!q) return rooms;
return rooms.filter((r) => {
const title = roomTitle(r).toLowerCase();
const uname = r.peer?.username?.toLowerCase() || "";
return title.includes(q) || uname.includes(q) || r.name.toLowerCase().includes(q);
});
})();
const openDM = async (uid: number) => {
try {
const { room } = await apiOpenDirectChat(uid);
setQuery("");
setUserHits([]);
router.push(`/chat/${room.id}`);
refreshRooms();
} catch (e) {
toast(e instanceof Error ? e.message : "无法发起私聊");
}
};
const togglePin = async (room: ChatRoomView) => {
setCtxMenu(null);
if (room.is_default || room.pin_forced) {
toast("大厅已置顶且不可取消");
return;
}
const next = !room.pinned;
try {
await apiPinChatRoom(room.id, next);
setRooms((prev) =>
sortRooms(
prev.map((r) =>
r.id === room.id ? { ...r, pinned: next } : r
)
)
);
toast(next ? "已置顶" : "已取消置顶", "ok");
} catch (err) {
toast(err instanceof Error ? err.message : "操作失败");
}
};
const openRoomMenu = (room: ChatRoomView, x: number, y: number) => {
if (room.is_default || room.pin_forced) return;
setCtxMenu({ x, y, room });
};
const clearLongPress = () => {
if (longPressTimer.current) {
clearTimeout(longPressTimer.current);
longPressTimer.current = null;
}
};
const showList = !activeRoomId;
// 移动端:有会话时隐藏列表;桌面始终显示列表
const listClass = activeRoomId
? "hidden lg:flex"
: "flex";
const paneClass = activeRoomId
? "flex"
: "hidden lg:flex";
return (
<div
className="panel overflow-hidden grid grid-cols-1 lg:grid-cols-[320px_minmax(0,1fr)]"
style={{
height: "calc(100vh - 8.5rem)",
minHeight: "480px",
borderColor: "var(--line)",
}}
>
{/* 左栏:会话列表 */}
<aside
className={`${listClass} flex-col min-h-0`}
style={{ borderRight: "1px solid var(--line)" }}
>
<div
className="flex items-center justify-between gap-2 px-4 py-3 shrink-0"
style={{ borderBottom: "1px solid var(--line)" }}
>
<h1 className="font-extrabold text-[17px]" style={{ color: "var(--ink)" }}>
消息
</h1>
<button
onClick={() => setShowCreate(true)}
className="w-8 h-8 flex items-center justify-center rounded-full hover:bg-[var(--accent-soft)] transition-colors"
style={{ color: "var(--accent)" }}
aria-label="新建群聊"
title="新建群聊"
>
<Plus size={18} />
</button>
</div>
<div className="px-3 py-2.5 shrink-0 space-y-1.5">
<label
className="j13-chat-search flex items-center gap-2 px-3 h-10 rounded-xl cursor-text transition-[border-color,box-shadow] duration-150"
style={{
background: "var(--bg)",
border: "1px solid var(--line)",
}}
>
<Search size={15} className="shrink-0 pointer-events-none" style={{ color: query ? "var(--accent)" : "var(--ink-3)" }} />
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="搜索会话、用户名或昵称"
className="j13-chat-search-input bg-transparent flex-1 self-stretch h-full text-[13px] min-w-0"
style={{ color: "var(--ink)" }}
/>
{query && (
<button
type="button"
onClick={(e) => {
e.preventDefault();
setQuery("");
}}
aria-label="清除搜索"
className="w-5 h-5 flex items-center justify-center rounded-full hover:bg-[var(--accent-soft)] shrink-0"
style={{ color: "var(--ink-3)" }}
>
<X size={12} />
</button>
)}
</label>
{query.trim() && (
<p className="px-1 text-[11px] meta">
{searching
? "正在搜索用户…"
: `会话 ${filteredRooms.length} · 用户 ${userHits.length}`}
</p>
)}
</div>
<div className="flex-1 overflow-y-auto min-h-0">
{query.trim() && (
<div className="px-2 pb-2">
<p
className="px-2 py-1.5 text-[11px] font-bold uppercase tracking-wider"
style={{ color: "var(--ink-3)" }}
>
用户 {searching ? "…" : ""}
</p>
{userHits.length === 0 && !searching ? (
<p className="px-2 py-2 text-[12px] meta">无匹配用户</p>
) : (
userHits.map((u) => (
<button
key={u.id}
onClick={() => openDM(u.id)}
className="w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-left hover:bg-[var(--accent-soft)] transition-colors"
>
<Avatar name={u.nickname || u.username} src={u.avatar || undefined} size={36} />
<div className="min-w-0">
<p className="text-[13px] font-semibold truncate" style={{ color: "var(--ink)" }}>
{u.nickname || u.username}
</p>
<p className="text-[11px] meta truncate">@{u.username}</p>
</div>
</button>
))
)}
<p
className="px-2 py-1.5 mt-1 text-[11px] font-bold uppercase tracking-wider"
style={{ color: "var(--ink-3)" }}
>
会话
</p>
</div>
)}
{filteredRooms.length === 0 ? (
<div className="text-center py-16 px-4">
<MessageSquare size={28} style={{ color: "var(--ink-3)", margin: "0 auto 8px" }} />
<p className="text-[13px] meta">
{query ? "无匹配会话" : "还没有会话,搜索用户发起私聊或新建群聊"}
</p>
</div>
) : (
<ul className="px-1.5 pb-2">
{filteredRooms.map((room) => {
const active = room.id === activeRoomId;
const pinned = isPinnedView(room);
return (
<li key={room.id}>
<Link
href={`/chat/${room.id}`}
className="flex items-center gap-2.5 px-2.5 py-2.5 rounded-xl transition-colors"
style={{
background: active ? "var(--accent-soft)" : "transparent",
}}
onContextMenu={(e) => {
if (room.is_default || room.pin_forced) return;
e.preventDefault();
openRoomMenu(room, e.clientX, e.clientY);
}}
onTouchStart={(e) => {
if (room.is_default || room.pin_forced) return;
const t = e.touches[0];
if (!t) return;
clearLongPress();
longPressTimer.current = setTimeout(() => {
openRoomMenu(room, t.clientX, t.clientY);
}, 480);
}}
onTouchEnd={clearLongPress}
onTouchMove={clearLongPress}
>
<span
className="w-10 h-10 shrink-0 rounded-xl flex items-center justify-center overflow-hidden"
style={{ background: "var(--panel-2)" }}
>
{room.room_type === "direct" && room.peer ? (
<Avatar
name={room.peer.nickname || room.peer.username}
src={room.peer.avatar || undefined}
size={40}
/>
) : (
<Users size={18} style={{ color: "var(--accent)" }} />
)}
</span>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5">
<span
className="font-semibold text-[13.5px] truncate"
style={{ color: "var(--ink)" }}
>
{roomTitle(room)}
</span>
{pinned && (
<span
className="inline-flex items-center gap-0.5 text-[10px] font-bold shrink-0 px-1.5 py-0.5 rounded"
style={{
background: "var(--accent-soft)",
color: "var(--accent)",
}}
title={room.is_default ? "强制置顶" : "置顶"}
>
<Pin size={10} /> 置顶
</span>
)}
{room.is_default && (
<span className="text-[10px] font-bold shrink-0" style={{ color: "var(--gold)" }}>
大厅
</span>
)}
{room.is_private && room.room_type === "group" && (
<span className="text-[10px] font-bold shrink-0 meta">私密</span>
)}
<span className="ml-auto meta text-[10.5px] shrink-0">
{formatTime(room.last_message?.created_at || room.updated_at)}
</span>
</div>
<div className="flex items-center gap-2 mt-0.5">
<p className="text-[12px] truncate meta flex-1">{roomPreview(room)}</p>
{room.unread_count > 0 && (
<span
className="shrink-0 min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold flex items-center justify-center"
style={{ background: "var(--clay)", color: "#fff" }}
>
{room.unread_count > 99 ? "99+" : room.unread_count}
</span>
)}
</div>
</div>
</Link>
</li>
);
})}
</ul>
)}
</div>
</aside>
{/* 右栏:会话内容 */}
<section className={`${paneClass} flex-col min-h-0 min-w-0`}>
{children ? (
children
) : (
<div className="flex-1 flex flex-col items-center justify-center px-6 text-center">
<span
className="w-16 h-16 rounded-2xl flex items-center justify-center mb-4"
style={{ background: "var(--accent-soft)", color: "var(--accent)" }}
>
<MessageSquare size={28} />
</span>
<p className="font-bold text-[16px]" style={{ color: "var(--ink)" }}>
选择一个会话开始聊天
</p>
<p className="meta mt-1.5 text-[13px] max-w-xs">
在左侧搜索用户发起私聊,或新建群聊。全站大厅已为你自动加入。
</p>
{showList && (
<p className="lg:hidden meta mt-4 text-[12px]">请从上方列表选择会话</p>
)}
</div>
)}
</section>
{showCreate && (
<CreateGroupModal
onClose={() => setShowCreate(false)}
onCreated={(id) => {
setShowCreate(false);
toast("群已创建", "ok");
router.push(`/chat/${id}`);
refreshRooms();
}}
/>
)}
{ctxMenu && (
<ContextMenu
x={ctxMenu.x}
y={ctxMenu.y}
items={
[
{
key: "pin",
label: ctxMenu.room.pinned ? "取消置顶" : "置顶",
icon: <Pin size={14} />,
onClick: () => togglePin(ctxMenu.room),
},
] as CtxMenuItem[]
}
onClose={() => setCtxMenu(null)}
/>
)}
</div>
);
}
function CreateGroupModal({
onClose,
onCreated,
}: {
onClose: () => void;
onCreated: (roomId: number) => void;
}) {
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [isPrivate, setIsPrivate] = useState(false);
const [memberInput, setMemberInput] = useState("");
const [submitting, setSubmitting] = useState(false);
const submit = async () => {
const trimmed = name.trim();
if (trimmed.length < 2 || trimmed.length > 32) {
toast("群名称需为 2-32 个字符");
return;
}
if (description.length > 200) {
toast("群简介不能超过 200 个字符");
return;
}
const usernames = memberInput
.split(/[\s,,]+/)
.map((s) => s.trim())
.filter(Boolean);
setSubmitting(true);
try {
const { room } = await apiCreateChatRoom(trimmed, description.trim(), {
is_private: isPrivate,
member_usernames: isPrivate ? usernames : [],
});
onCreated(room.id);
} catch (e) {
toast(e instanceof Error ? e.message : "建群失败");
} finally {
setSubmitting(false);
}
};
return (
<div
className="fixed inset-0 z-[1000] flex items-center justify-center p-4"
style={{ background: "rgba(0,0,0,0.55)" }}
// 刻意不绑定外侧点击关闭,避免误关丢失已填内容
>
<div
className="w-full max-w-md rounded-2xl p-6 j13-toast-in"
style={{ background: "var(--panel)", border: "1px solid var(--line)" }}
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between mb-5">
<h2 className="text-[18px] font-extrabold" style={{ color: "var(--ink)" }}>
新建群聊
</h2>
<button
onClick={onClose}
disabled={submitting}
aria-label="关闭"
className="w-7 h-7 flex items-center justify-center rounded-full hover:bg-[var(--accent-soft)] transition-colors"
style={{ color: "var(--ink-3)" }}
>
<X size={15} />
</button>
</div>
<div className="space-y-4">
<div>
<label className="block text-[12px] font-bold mb-1.5" style={{ color: "var(--ink-2)" }}>
群名称 <span style={{ color: "var(--danger)" }}>*</span>
</label>
<input
autoFocus
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
maxLength={32}
placeholder="2-32 个字符"
className="w-full px-3.5 h-10 rounded-lg outline-none"
style={{ background: "var(--bg)", border: "1px solid var(--line)", color: "var(--ink)" }}
/>
</div>
<div>
<label className="block text-[12px] font-bold mb-1.5" style={{ color: "var(--ink-2)" }}>
群简介(选填)
</label>
<textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
maxLength={200}
rows={3}
className="w-full px-3.5 py-2.5 rounded-lg outline-none resize-none"
style={{ background: "var(--bg)", border: "1px solid var(--line)", color: "var(--ink)" }}
/>
</div>
<div>
<label className="block text-[12px] font-bold mb-2" style={{ color: "var(--ink-2)" }}>
可见性
</label>
<div className="flex gap-2">
<button
type="button"
onClick={() => setIsPrivate(false)}
className="flex-1 h-9 rounded-lg text-[13px] font-semibold"
style={{
background: !isPrivate ? "var(--accent-soft)" : "var(--bg)",
color: !isPrivate ? "var(--accent)" : "var(--ink-2)",
border: `1px solid ${!isPrivate ? "var(--accent)" : "var(--line)"}`,
}}
>
公开
</button>
<button
type="button"
onClick={() => setIsPrivate(true)}
className="flex-1 h-9 rounded-lg text-[13px] font-semibold"
style={{
background: isPrivate ? "var(--accent-soft)" : "var(--bg)",
color: isPrivate ? "var(--accent)" : "var(--ink-2)",
border: `1px solid ${isPrivate ? "var(--accent)" : "var(--line)"}`,
}}
>
私密
</button>
</div>
</div>
{isPrivate && (
<div>
<label className="block text-[12px] font-bold mb-1.5" style={{ color: "var(--ink-2)" }}>
初始成员(选填)
</label>
<input
type="text"
value={memberInput}
onChange={(e) => setMemberInput(e.target.value)}
placeholder="用户名,多个用空格或逗号分隔"
className="w-full px-3.5 h-10 rounded-lg outline-none"
style={{ background: "var(--bg)", border: "1px solid var(--line)", color: "var(--ink)" }}
/>
</div>
)}
<div className="flex justify-end gap-2 pt-1">
<button onClick={onClose} disabled={submitting} className="btn btn-line btn-sm">
取消
</button>
<button onClick={submit} disabled={submitting} className="btn btn-accent btn-sm">
{submitting ? "创建中..." : "创建"}
</button>
</div>
</div>
</div>
</div>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,94 @@
import type { Metadata } from "next";
import { notFound, redirect } from "next/navigation";
import { cookies } from "next/headers";
import { authCookieHeader } from "@/lib/cookies";
import { getMeCached } from "@/lib/serverData";
import { fetchChatRoom, fetchChatMessages, fetchChatRooms } from "@/lib/api";
import ChatShell from "../ChatShell";
import ChatRoomClient from "./ChatRoomClient";
interface PageProps {
params: Promise<{ id: string }>;
}
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
const { id } = await params;
try {
const { room } = await fetchChatRoom(id, authCookieHeader(await cookies()));
const title =
room.room_type === "direct"
? room.peer?.nickname || room.peer?.username || room.name || "私聊"
: room.name;
return { title: `消息 · ${title}` };
} catch {
return { title: "会话不存在" };
}
}
export default async function ChatRoomPage({ params }: PageProps) {
const { id } = await params;
const cookie = authCookieHeader(await cookies());
const me = await getMeCached(cookie || undefined);
if (!me.user) {
redirect(`/login?redirect=${encodeURIComponent(`/chat/${id}`)}`);
}
let rooms: Awaited<ReturnType<typeof fetchChatRooms>>["rooms"] = [];
try {
const data = await fetchChatRooms(1, 50, "", cookie, "joined");
rooms = data.rooms || [];
} catch {
rooms = [];
}
let room: Awaited<ReturnType<typeof fetchChatRoom>>["room"];
try {
({ room } = await fetchChatRoom(id, cookie));
} catch {
notFound();
}
let initialMessages: Awaited<ReturnType<typeof fetchChatMessages>> = {
messages: [],
has_more: false,
};
if (room.joined) {
try {
initialMessages = await fetchChatMessages(id, 0, 30, cookie);
} catch {
// 客户端兜底
}
}
const displayName =
room.room_type === "direct"
? room.peer?.nickname || room.peer?.username || room.name || "私聊"
: room.name;
return (
<div className="max-w-6xl mx-auto">
<ChatShell meId={me.user.id} initialRooms={rooms} activeRoomId={room.id}>
<ChatRoomClient
roomId={room.id}
roomName={displayName}
roomDescription={room.description}
ownerId={room.owner_id}
memberCount={room.member_count}
myRole={room.my_role}
joined={room.joined}
isPrivate={room.is_private}
isDefault={room.is_default}
roomType={room.room_type || "group"}
peer={room.peer || null}
meId={me.user.id}
meRole={me.user.role}
meName={me.user.nickname || me.user.username}
meAvatar={me.user.avatar || ""}
initialMessages={initialMessages.messages}
initialHasMore={initialMessages.has_more}
embedded
/>
</ChatShell>
</div>
);
}

View File

@@ -0,0 +1,34 @@
import { redirect } from "next/navigation";
import { cookies } from "next/headers";
import type { Metadata } from "next";
import { authCookieHeader } from "@/lib/cookies";
import { getMeCached } from "@/lib/serverData";
import { fetchChatRooms } from "@/lib/api";
import ChatShell from "./ChatShell";
export const metadata: Metadata = {
title: "消息",
description: "私聊与群聊,实时交流。",
};
export default async function ChatListPage() {
const cookie = authCookieHeader(await cookies());
const me = await getMeCached(cookie || undefined);
if (!me.user) {
redirect(`/login?redirect=${encodeURIComponent("/chat")}`);
}
let rooms: Awaited<ReturnType<typeof fetchChatRooms>>["rooms"] = [];
try {
const data = await fetchChatRooms(1, 50, "", cookie, "joined");
rooms = data.rooms || [];
} catch {
rooms = [];
}
return (
<div className="max-w-6xl mx-auto">
<ChatShell meId={me.user.id} initialRooms={rooms} activeRoomId={null} />
</div>
);
}

View File

@@ -155,6 +155,89 @@ h1, h2, h3, h4 {
border-radius: 6px;
}
/* 消息侧栏搜索:单层描边,避免外框 + focus-visible 双线 */
.j13-chat-search:focus-within {
border-color: var(--accent) !important;
box-shadow: 0 0 0 3px var(--accent-soft);
}
.j13-chat-search-input,
.j13-chat-search-input:focus,
.j13-chat-search-input:focus-visible {
outline: none !important;
box-shadow: none !important;
}
/* 聊天输入区:与搜索框同款聚焦态 */
.j13-chat-composer:focus-within {
border-color: var(--accent) !important;
box-shadow: 0 0 0 3px var(--accent-soft);
}
.j13-chat-composer-input,
.j13-chat-composer-input:focus,
.j13-chat-composer-input:focus-visible {
outline: none !important;
box-shadow: none !important;
resize: none !important;
}
.j13-chat-composer-input.has-value {
color: transparent;
caret-color: var(--ink);
}
.j13-chat-composer-input.has-value::placeholder {
color: transparent;
}
.j13-chat-composer-mirror {
position: absolute;
inset: 0;
overflow: hidden;
pointer-events: none;
white-space: pre-wrap;
overflow-wrap: break-word;
word-break: break-word;
color: var(--ink);
}
.j13-mention-token {
display: inline-block;
padding: 2px 8px;
margin: 0 2px;
border-radius: 999px;
line-height: 1.35;
vertical-align: baseline;
/* 主题强调色加深 + 对比色字,胶囊形 */
background: color-mix(in srgb, var(--accent) 82%, #000);
color: #fff !important;
font-weight: 600;
text-decoration: none !important;
cursor: pointer;
transition: filter 0.12s ease, opacity 0.12s ease;
box-decoration-break: clone;
-webkit-box-decoration-break: clone;
}
a.j13-mention-token:hover {
filter: brightness(1.08);
opacity: 0.95;
}
.dark .j13-mention-token {
/* 暗色下 accent 偏亮,用实心 accent + 配套字色 */
background: var(--accent);
color: var(--accent-on) !important;
}
/* 输入镜像层:不加粗/不加 padding,避免与透明 textarea 字宽错位 */
.j13-chat-composer-mirror .j13-mention-token {
display: inline;
padding: 0;
margin: 0;
line-height: inherit;
font-weight: inherit;
border-radius: 999px;
box-shadow: none;
background: color-mix(in srgb, var(--accent) 82%, #000);
}
.dark .j13-chat-composer-mirror .j13-mention-token {
background: var(--accent);
color: var(--accent-on) !important;
}
@layer components {
/* ----- 小标签(旧名 .kicker 保留兼容) ----- */
.kicker {
@@ -230,6 +313,22 @@ h1, h2, h3, h4 {
.btn-primary:active:not(:disabled) {
transform: translateY(0);
}
/* 与 btn-primary 同款,历史类名兼容 */
.btn-accent {
background: var(--accent);
color: var(--accent-on);
box-shadow: 0 1px 2px rgba(16, 24, 40, 0.12),
0 2px 8px color-mix(in srgb, var(--accent) 26%, transparent);
}
.btn-accent:hover:not(:disabled) {
background: var(--accent-hi);
transform: translateY(-1px);
box-shadow: 0 2px 6px rgba(16, 24, 40, 0.1),
0 8px 20px color-mix(in srgb, var(--accent) 34%, transparent);
}
.btn-accent:active:not(:disabled) {
transform: translateY(0);
}
.btn-line {
background: var(--panel);
@@ -380,6 +479,18 @@ h1, h2, h3, h4 {
border-radius: 999px;
white-space: nowrap;
}
.badge-pending {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 12px;
font-weight: 700;
padding: 4px 11px;
background: var(--accent-soft);
color: var(--accent);
border-radius: 999px;
white-space: nowrap;
}
/* 帖子列表中的板块小标签:全站统一浅灰配色,避免每行多色眩目 */
.j13-board-tag {
@@ -539,6 +650,20 @@ h1, h2, h3, h4 {
transform: scale(0.97);
}
/* 帖子流「有新内容」提示条(三期) */
.j13-feed-new-tip:hover {
filter: brightness(0.97);
}
.j13-feed-new-tip:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
@media (prefers-reduced-motion: reduce) {
.j13-feed-new-tip {
transition: none;
}
}
/* 侧栏导航项 */
.j13-raillink {
display: flex;

View File

@@ -7,6 +7,7 @@ import Footer from "@/components/Footer";
import Toaster from "@/components/Toaster";
import AccountGuard from "@/components/AccountGuard";
import ThemeSync from "@/components/ThemeSync";
import RealtimeProvider from "@/components/RealtimeProvider";
import type { User } from "@/lib/api";
import { getMeCached, getPublicSettingsCached } from "@/lib/serverData";
import { TOKEN_COOKIE, REFRESH_COOKIE, authCookieHeader } from "@/lib/cookies";
@@ -68,6 +69,7 @@ export default async function RootLayout({
let user: User | null = null;
let unread = 0;
let chatUnread = 0;
const hasAuthCookie =
!!cookieStore.get(TOKEN_COOKIE)?.value || !!cookieStore.get(REFRESH_COOKIE)?.value;
if (hasAuthCookie) {
@@ -75,6 +77,7 @@ export default async function RootLayout({
const me = await getMeCached(authCookieHeader(cookieStore) || undefined);
user = me.user;
unread = me.unread_count;
chatUnread = me.chat_unread_count ?? 0;
}
return (
@@ -84,7 +87,7 @@ export default async function RootLayout({
>
<body className="min-h-screen flex flex-col">
{accentCSS ? (
// id 与 lib/theme 的运行时换肤共用:后台实时预览时直接复用/替换此节点
// React 托管的 SSR 主题节点;客户端换肤走 j13-accent-runtime,禁止对此外挂 remove
<style
id="j13-accent-vars"
data-accent-source="ssr"
@@ -94,7 +97,12 @@ export default async function RootLayout({
<a href="#main" className="skip-link">
跳到主要内容
</a>
<Header initialUser={user} initialUnread={unread} initialTheme={theme} />
<Header
initialUser={user}
initialUnread={unread}
initialChatUnread={chatUnread}
initialTheme={theme}
/>
<main
id="main"
tabIndex={-1}
@@ -106,6 +114,7 @@ export default async function RootLayout({
<Toaster />
<AccountGuard />
<ThemeSync initialAccent={accent || ""} />
<RealtimeProvider userId={user ? user.id : null} />
</body>
</html>
);

View File

@@ -3,7 +3,7 @@
import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Heart, MessageCircle, CheckCheck, Bell, CheckCircle2, XCircle } from "lucide-react";
import { Heart, MessageCircle, CheckCheck, Bell, CheckCircle2, XCircle, AtSign, ClipboardList } from "lucide-react";
import { apiMarkRead, apiMarkAllRead, type NotificationsResponse, type NotificationItem } from "@/lib/api";
/**
@@ -20,7 +20,14 @@ export default function NotificationsClient({ initialData }: { initialData: Noti
list.map((item) => (item.id === n.id ? { ...item, is_read: true } : item))
);
}
router.push(`/post/${n.post_id}`);
// @提及通知跳到群聊房间;其余跳到帖子/评论
if (n.type === "mention" && n.room_id) {
router.push(`/chat/${n.room_id}`);
} else if (n.type === "pending_review") {
router.push(n.post_id ? `/post/${n.post_id}` : "/admin/moderation");
} else {
router.push(`/post/${n.post_id}`);
}
};
const handleMarkAll = async () => {
@@ -73,7 +80,11 @@ export default function NotificationsClient({ initialData }: { initialData: Noti
? <XCircle size={16} />
: n.type === "like"
? <Heart size={16} />
: <MessageCircle size={16} />;
: n.type === "mention"
? <AtSign size={16} />
: n.type === "pending_review"
? <ClipboardList size={16} />
: <MessageCircle size={16} />;
const iconColor = n.type === "approved"
? "var(--ok)"
: n.type === "rejected"
@@ -128,14 +139,28 @@ export default function NotificationsClient({ initialData }: { initialData: Noti
? "评论了你的帖子"
: n.type === "reply"
? "回复了你的评论"
: "点赞了你的帖子"}
: n.type === "mention"
? "在消息中提到了你"
: n.type === "pending_review"
? "有新内容待审核"
: "点赞了你的帖子"}
</span>
</>
)}
</p>
<p className="text-sm mt-1 truncate" style={{ color: "var(--ink-2)" }}>
《{n.post.title}》
</p>
{n.type === "mention" ? (
n.room && (
<p className="text-sm mt-1 truncate" style={{ color: "var(--ink-2)" }}>
# {n.room.name}
</p>
)
) : (
n.post && (
<p className="text-sm mt-1 truncate" style={{ color: "var(--ink-2)" }}>
《{n.post.title}》
</p>
)
)}
{n.content && (
<p className="text-[13px] mt-1.5 line-clamp-2" style={{ color: "var(--ink-3)" }}>
{n.content}

View File

@@ -12,6 +12,7 @@ import { getMeCached } from "@/lib/serverData";
import Pagination from "@/components/Pagination";
import PostRow from "@/components/PostRow";
import FeedTabs, { type FeedSort } from "@/components/home/FeedTabs";
import FeedNewTip from "@/components/home/FeedNewTip";
import { WorkspaceNav, WorkspaceNavMobile } from "@/components/home/WorkspaceNav";
import { CommunityPanels, CommunityPanelsMobile } from "@/components/home/CommunityPanels";
@@ -158,6 +159,14 @@ export default async function HomePage({ searchParams }: HomePageProps) {
共 {postsData.total} 篇
</span>
</div>
{user && (
<FeedNewTip
sort={sort}
boardId={boardId}
page={page}
userId={user.id}
/>
)}
{postsData.posts.length > 0 ? (
postsData.posts.map((post, i) => (
<PostRow

View File

@@ -33,7 +33,7 @@ import PostToc, { type TocItem } from "@/components/PostToc";
import MobilePostBar from "@/components/MobilePostBar";
import Avatar from "@/components/Avatar";
import RoleBadge from "@/components/RoleBadge";
import { isStaff } from "@/lib/roles";
import { canModerateBoard } from "@/lib/roles";
import { IconComment, IconEye } from "@/components/Icons";
interface PageProps {
@@ -340,7 +340,7 @@ export default async function PostDetailPage({ params, searchParams }: PageProps
// 非公开帖(待审/未通过)仅作者本人与管理团队可看,顶部给出醒目状态
const isPublished = post.status === "published";
const canSeeStatus = !!me.user && (me.user.id === post.user.id || isStaff(me.user.role));
const canSeeStatus = !!me.user && (me.user.id === post.user.id || canModerateBoard(me.user, post.board_id));
const jsonLd = {
"@context": "https://schema.org",

View File

@@ -0,0 +1,36 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { MessageSquare } from "lucide-react";
import { apiOpenDirectChat } from "@/lib/api";
import { toast } from "@/lib/toast";
/** 用户主页:发起私聊 */
export default function StartDMButton({ userId }: { userId: number }) {
const router = useRouter();
const [loading, setLoading] = useState(false);
const start = async () => {
setLoading(true);
try {
const { room } = await apiOpenDirectChat(userId);
router.push(`/chat/${room.id}`);
} catch (e) {
toast(e instanceof Error ? e.message : "无法发起私聊");
} finally {
setLoading(false);
}
};
return (
<button
onClick={start}
disabled={loading}
className="btn btn-accent btn-sm gap-1.5"
>
<MessageSquare size={14} />
{loading ? "打开中…" : "私聊"}
</button>
);
}

View File

@@ -14,6 +14,7 @@ import PasswordForm from "./PasswordForm";
import Avatar from "@/components/Avatar";
import RoleBadge from "@/components/RoleBadge";
import { roleMeta } from "@/lib/roles";
import StartDMButton from "./StartDMButton";
interface UserPageProps {
params: Promise<{ id: string }>;
@@ -132,8 +133,8 @@ export default async function UserPage({ params, searchParams }: UserPageProps)
/>
</div>
{/* 本人操作按钮 */}
{isOwner && (
{/* 本人操作按钮 / 访客私聊 */}
{isOwner ? (
<div className="absolute top-3 right-3 sm:top-4 sm:right-4 z-20 flex items-center gap-2">
<Link href={`/u/${id}?tab=settings`} className="btn btn-line btn-sm">
<PenLine size={13.5} />
@@ -148,7 +149,11 @@ export default async function UserPage({ params, searchParams }: UserPageProps)
<Shield size={14} />
</Link>
</div>
)}
) : currentUser ? (
<div className="absolute top-3 right-3 sm:top-4 sm:right-4 z-20">
<StartDMButton userId={data.user.id} />
</div>
) : null}
{/* 身份信息:纯文档流,头像 + 右侧文字 baseline 对齐 */}
<div className="relative z-10 px-5 sm:px-7 pt-5 sm:pt-6">

View File

@@ -64,6 +64,7 @@ export default function CommentSection({
setContent("");
if (res.comment.status === "pending") {
toast("已提交,等待审核通过后公开");
router.refresh();
} else {
// 新楼层在最后一页:刷新后由服务端直出最新分页
router.refresh();
@@ -91,6 +92,7 @@ export default function CommentSection({
setReplyContent("");
if (res.comment.status === "pending") {
toast("已提交,等待审核通过后公开");
router.refresh();
} else {
// 刷新后由 SSR 直出新树(子评论全量挂在本楼)
router.refresh();
@@ -221,6 +223,7 @@ export default function CommentSection({
{c.user.nickname || c.user.username}
</span>
</Link>
{c.status === "pending" && <span className="badge-pending shrink-0 !text-[10px] !py-0.5 !px-1.5">待审</span>}
{isReplyToReply && parent && (
<>
<ChevronRight size={12} className="cmt-reply-arrow" aria-hidden="true" />
@@ -301,6 +304,7 @@ export default function CommentSection({
{c.user.nickname || c.user.username}
</span>
</Link>
{c.status === "pending" && <span className="badge-pending shrink-0">待审</span>}
{floor && (
<a href={`#comment-${c.id}`} className="cmt-floor-label" aria-label={`楼层 ${floor}`}>
#{floor}

View File

@@ -0,0 +1,84 @@
"use client";
import { X } from "lucide-react";
/**
* 站点风格确认框:仅取消/关闭可关,避免点遮罩误关。
* danger 主按钮使用 btn-danger,其余用 btn-accent。
*/
export default function ConfirmDialog({
open,
title,
message,
confirmLabel = "确定",
cancelLabel = "取消",
danger = false,
busy = false,
onConfirm,
onCancel,
}: {
open: boolean;
title: string;
message: string;
confirmLabel?: string;
cancelLabel?: string;
danger?: boolean;
busy?: boolean;
onConfirm: () => void;
onCancel: () => void;
}) {
if (!open) return null;
return (
<div
className="fixed inset-0 z-[1100] flex items-center justify-center p-4"
style={{ background: "rgba(0,0,0,0.55)" }}
>
<div
className="w-full max-w-sm rounded-2xl p-5 j13-toast-in"
style={{ background: "var(--panel)", border: "1px solid var(--line)" }}
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-start justify-between gap-3 mb-3">
<h2
className="text-[16px] font-extrabold leading-snug"
style={{ color: "var(--ink)" }}
>
{title}
</h2>
<button
type="button"
onClick={onCancel}
disabled={busy}
aria-label="关闭"
className="w-7 h-7 shrink-0 flex items-center justify-center rounded-full hover:bg-[var(--accent-soft)] transition-colors"
style={{ color: "var(--ink-3)" }}
>
<X size={15} />
</button>
</div>
<p className="text-[13.5px] leading-relaxed mb-5" style={{ color: "var(--ink-2)" }}>
{message}
</p>
<div className="flex justify-end gap-2">
<button
type="button"
onClick={onCancel}
disabled={busy}
className="btn btn-line btn-sm"
>
{cancelLabel}
</button>
<button
type="button"
onClick={onConfirm}
disabled={busy}
className={`btn btn-sm ${danger ? "btn-danger" : "btn-accent"}`}
>
{busy ? "处理中…" : confirmLabel}
</button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,136 @@
"use client";
import { useEffect, useRef } from "react";
export type CtxMenuItem = {
key: string;
label: string;
icon?: React.ReactNode;
danger?: boolean;
disabled?: boolean;
onClick: () => void;
};
/**
* 统一右键/长按浮层菜单(飞书式)。
* 定位会钳制在视口内;点击外侧或滚动关闭。
*/
export default function ContextMenu({
x,
y,
items,
onClose,
}: {
x: number;
y: number;
items: CtxMenuItem[];
onClose: () => void;
}) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const close = () => onClose();
window.addEventListener("click", close);
window.addEventListener("scroll", close, true);
window.addEventListener("resize", close);
return () => {
window.removeEventListener("click", close);
window.removeEventListener("scroll", close, true);
window.removeEventListener("resize", close);
};
}, [onClose]);
useEffect(() => {
const el = ref.current;
if (!el) return;
const rect = el.getBoundingClientRect();
let left = x;
let top = y;
if (left + rect.width > window.innerWidth - 8) {
left = Math.max(8, window.innerWidth - rect.width - 8);
}
if (top + rect.height > window.innerHeight - 8) {
top = Math.max(8, window.innerHeight - rect.height - 8);
}
el.style.left = `${left}px`;
el.style.top = `${top}px`;
}, [x, y, items]);
return (
<div
ref={ref}
className="fixed z-[1200] min-w-[148px] rounded-xl py-1 shadow-lg j13-toast-in"
style={{
left: x,
top: y,
background: "var(--panel)",
border: "1px solid var(--line)",
}}
onClick={(e) => e.stopPropagation()}
onContextMenu={(e) => e.preventDefault()}
>
{items.map((it) => (
<button
key={it.key}
type="button"
disabled={it.disabled}
className="w-full flex items-center gap-2.5 px-3.5 py-2 text-[13px] text-left transition-colors disabled:opacity-40"
style={{
color: it.danger ? "var(--danger)" : "var(--ink)",
}}
onMouseEnter={(e) => {
e.currentTarget.style.background = it.danger
? "var(--danger-soft)"
: "var(--accent-soft)";
}}
onMouseLeave={(e) => {
e.currentTarget.style.background = "transparent";
}}
onClick={() => {
if (it.disabled) return;
onClose();
it.onClick();
}}
>
{it.icon}
{it.label}
</button>
))}
</div>
);
}
/** 绑定桌面右键 + 移动端长按,打开菜单 */
export function usePressMenu(
openAt: (x: number, y: number) => void
): {
onContextMenu: (e: React.MouseEvent) => void;
onTouchStart: (e: React.TouchEvent) => void;
onTouchEnd: () => void;
onTouchMove: () => void;
} {
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const clear = () => {
if (timer.current) {
clearTimeout(timer.current);
timer.current = null;
}
};
return {
onContextMenu: (e) => {
e.preventDefault();
e.stopPropagation();
openAt(e.clientX, e.clientY);
},
onTouchStart: (e) => {
const t = e.touches[0];
if (!t) return;
clear();
timer.current = setTimeout(() => {
openAt(t.clientX, t.clientY);
}, 480);
},
onTouchEnd: clear,
onTouchMove: clear,
};
}

View File

@@ -19,21 +19,26 @@ import {
User as UserIcon,
ChevronDown,
ShieldCheck,
MessageSquare,
} from "lucide-react";
import { apiLogout, apiMe, type User } from "@/lib/api";
import { apiLogout, apiMe, apiChatUnreadSummary, type User } from "@/lib/api";
import { hasAuthCookieHint } from "@/lib/cookies";
import { isStaff } from "@/lib/roles";
import { onUserUpdate, onForceLogout } from "@/lib/userEvents";
import { realtime, RT_CHAT_UNREAD } from "@/lib/realtime";
import type { RtChatUnreadData } from "@/lib/realtime";
import NotificationBell from "./NotificationBell";
import Avatar from "./Avatar";
export default function Header({
initialUser,
initialUnread = 0,
initialChatUnread = 0,
initialTheme = "light",
}: {
initialUser: User | null;
initialUnread?: number;
initialChatUnread?: number;
initialTheme?: "light" | "dark";
}) {
const router = useRouter();
@@ -43,6 +48,7 @@ export default function Header({
// 登录态以 SSR 直出为初始值,F5 无切换闪动;router.refresh() 后随 props 校正
const [user, setUser] = useState<User | null>(initialUser);
const [unread, setUnread] = useState(initialUnread);
const [chatUnread, setChatUnread] = useState(initialChatUnread);
const [searchQuery, setSearchQuery] = useState("");
const searchInputRef = useRef<HTMLInputElement>(null);
@@ -55,6 +61,10 @@ export default function Header({
setUnread(initialUnread);
}, [initialUnread]);
useEffect(() => {
setChatUnread(initialChatUnread);
}, [initialChatUnread]);
// 同页内资料变更(如上传/删除头像)立即生效,不依赖 router.refresh 时序
useEffect(() => onUserUpdate((patch) => {
setUser((prev) => (prev ? { ...prev, ...patch } : prev));
@@ -84,10 +94,49 @@ export default function Header({
.then((res) => {
setUser(res.user);
if (typeof res.unread_count === "number") setUnread(res.unread_count);
if (typeof res.chat_unread_count === "number")
setChatUnread(res.chat_unread_count);
})
.catch(() => {});
}, []);
// 实时未读:chat:unread 推送给所有成员(含未打开会话页);在当前会话页则忽略
useEffect(() => {
if (!user) return;
const off = realtime.on<RtChatUnreadData>(RT_CHAT_UNREAD, (data) => {
if (!data || typeof data.room_id !== "number") return;
if (pathname === `/chat/${data.room_id}`) return;
const delta = typeof data.delta === "number" ? data.delta : 1;
setChatUnread((c) => Math.max(0, c + delta));
});
return off;
}, [user, pathname]);
// 会话内已读后主动对账(ChatRoomClient 派发)
useEffect(() => {
if (!user) return;
const onSync = () => {
apiChatUnreadSummary()
.then((res) => setChatUnread(res.total || 0))
.catch(() => {});
};
window.addEventListener("j13-chat-unread-sync", onSync);
return () => window.removeEventListener("j13-chat-unread-sync", onSync);
}, [user]);
// 切回标签页时重新对账未读
useEffect(() => {
if (!user) return;
const onVisible = () => {
if (document.visibilityState !== "visible") return;
apiChatUnreadSummary()
.then((res) => setChatUnread(res.total || 0))
.catch(() => {});
};
document.addEventListener("visibilitychange", onVisible);
return () => document.removeEventListener("visibilitychange", onVisible);
}, [user]);
const handleSearch = (e: React.FormEvent) => {
e.preventDefault();
const q = searchQuery.trim();
@@ -237,6 +286,39 @@ export default function Header({
>
{theme === "dark" ? <Sun size={17} /> : <Moon size={17} />}
</button>
{user && (
<Link
href="/chat"
prefetch={false}
aria-label="消息"
className="relative inline-flex items-center justify-center w-10 h-10 rounded-full transition-colors"
style={{
color: pathname?.startsWith("/chat")
? "var(--accent)"
: "var(--ink-2)",
border: `1px solid ${
pathname?.startsWith("/chat") ? "var(--accent)" : "var(--line)"
}`,
background: pathname?.startsWith("/chat")
? "var(--accent-soft)"
: "var(--panel)",
}}
>
<MessageSquare size={17} />
{chatUnread > 0 && (
<span
className="absolute -top-1 -right-1 min-w-[18px] h-[18px] px-1 text-[10px] font-bold flex items-center justify-center rounded-full"
style={{
background: "var(--clay)",
color: "#fff",
border: "2px solid var(--bg)",
}}
>
{chatUnread > 99 ? "99+" : chatUnread}
</span>
)}
</Link>
)}
{user && <NotificationBell initialUnread={unread} />}
{user ? (
<>
@@ -289,6 +371,21 @@ export default function Header({
<div className="flex flex-col">
<MobileLink href="/" active={pathname === "/"}>首页</MobileLink>
{user && <MobileLink href="/compose">发帖</MobileLink>}
{user && (
<MobileLink href="/chat" active={pathname?.startsWith("/chat") ?? false}>
<span className="inline-flex items-center gap-2">
<MessageSquare size={15} /> 消息
{chatUnread > 0 && (
<span
className="inline-flex items-center justify-center min-w-[16px] h-4 px-1 text-[10px] font-bold rounded-full"
style={{ background: "var(--clay)", color: "#fff" }}
>
{chatUnread > 99 ? "99+" : chatUnread}
</span>
)}
</span>
</MobileLink>
)}
{user && (
<MobileLink href="/notifications">
<span className="inline-flex items-center gap-2"><Bell size={15} /> 通知中心</span>

View File

@@ -3,7 +3,7 @@
import { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Bell, CheckCheck, Heart, MessageCircle, CheckCircle2, XCircle } from "lucide-react";
import { Bell, CheckCheck, Heart, MessageCircle, CheckCircle2, XCircle, AtSign, ClipboardList } from "lucide-react";
import {
apiFetchNotifications,
apiUnreadCount,
@@ -11,6 +11,7 @@ import {
apiMarkAllRead,
type NotificationItem,
} from "@/lib/api";
import { realtime, RT_NOTIFICATION_NEW } from "@/lib/realtime";
export default function NotificationBell({ initialUnread = 0 }: { initialUnread?: number }) {
const router = useRouter();
@@ -21,10 +22,11 @@ export default function NotificationBell({ initialUnread = 0 }: { initialUnread?
const [loading, setLoading] = useState(false);
const dropdownRef = useRef<HTMLDivElement>(null);
// 轮询未读数(30 秒);页面从后台切回时立即探测一次,
// 使账号被封禁等服务端状态变化在用户切回标签页的瞬间即可被发现
// 未读数:WS 推送后拉取校准;回前台再对账(无定时轮询)
useEffect(() => {
let cancelled = false;
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
const fetchCount = () => {
apiUnreadCount()
.then((res) => {
@@ -32,18 +34,28 @@ export default function NotificationBell({ initialUnread = 0 }: { initialUnread?
})
.catch(() => {});
};
const fetchCountDebounced = () => {
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(fetchCount, 200);
};
fetchCount();
const timer = setInterval(fetchCount, 30000);
const off = realtime.on(RT_NOTIFICATION_NEW, () => {
fetchCountDebounced();
if (open) loadNotifications();
});
const onVisible = () => {
if (document.visibilityState === "visible") fetchCount();
};
document.addEventListener("visibilitychange", onVisible);
return () => {
cancelled = true;
clearInterval(timer);
if (debounceTimer) clearTimeout(debounceTimer);
off();
document.removeEventListener("visibilitychange", onVisible);
};
}, []);
}, [open]);
// 点击外部关闭下拉
useEffect(() => {
@@ -84,7 +96,14 @@ export default function NotificationBell({ initialUnread = 0 }: { initialUnread?
);
}
setOpen(false);
router.push(`/post/${n.post_id}`);
// @提及通知跳到群聊房间;其余跳到帖子/评论
if (n.type === "mention" && n.room_id) {
router.push(`/chat/${n.room_id}`);
} else if (n.type === "pending_review") {
router.push(n.post_id ? `/post/${n.post_id}` : "/admin/moderation");
} else {
router.push(`/post/${n.post_id}`);
}
};
const handleMarkAllRead = async () => {
@@ -109,6 +128,8 @@ export default function NotificationBell({ initialUnread = 0 }: { initialUnread?
if (n.type === "reply") return "回复了你的评论";
if (n.type === "approved") return "审核通过";
if (n.type === "rejected") return "未通过审核";
if (n.type === "mention") return "在消息中提到了你";
if (n.type === "pending_review") return "有新内容待审核";
return "点赞了你的帖子";
};
@@ -121,6 +142,10 @@ export default function NotificationBell({ initialUnread = 0 }: { initialUnread?
return { color: "var(--danger)", bg: "var(--danger-soft)", node: <XCircle size={15} /> };
if (n.type === "like")
return { color: "var(--clay)", bg: "var(--clay-soft)", node: <Heart size={15} /> };
if (n.type === "mention")
return { color: "var(--accent)", bg: "var(--accent-soft)", node: <AtSign size={15} /> };
if (n.type === "pending_review")
return { color: "var(--accent)", bg: "var(--accent-soft)", node: <ClipboardList size={15} /> };
return { color: "var(--accent)", bg: "var(--accent-soft)", node: <MessageCircle size={15} /> };
};
@@ -221,9 +246,19 @@ export default function NotificationBell({ initialUnread = 0 }: { initialUnread?
</>
)}
</p>
<p className="text-xs mt-1 truncate" style={{ color: "var(--ink-2)" }}>
《{n.post.title}》
</p>
{n.type === "mention" ? (
n.room && (
<p className="text-xs mt-1 truncate" style={{ color: "var(--ink-2)" }}>
# {n.room.name}
</p>
)
) : (
n.post && (
<p className="text-xs mt-1 truncate" style={{ color: "var(--ink-2)" }}>
《{n.post.title}》
</p>
)
)}
{n.content && (
<p className="text-xs mt-1 line-clamp-1" style={{ color: "var(--ink-3)" }}>
{n.content}

View File

@@ -54,6 +54,7 @@ export default function PostRow({
<div className="flex items-center gap-2 min-w-0">
{post.pinned > 0 && <span className="badge-pin shrink-0">置顶</span>}
{post.recommended && <span className="badge-rec shrink-0">推荐</span>}
{post.status === "pending" && <span className="badge-pending shrink-0">待审</span>}
<Link
href={`/post/${post.id}`}
className="stretch-link min-w-0 flex-1"

View File

@@ -0,0 +1,18 @@
"use client";
import { useEffect } from "react";
import { realtime } from "@/lib/realtime";
// 实时总线生命周期:登录即连、登出即断;连接/重连/心跳全部封装在 lib/realtime。
// 挂在持久 root layout 上,全标签页只维护一条 WebSocket。
export default function RealtimeProvider({ userId }: { userId: number | null }) {
useEffect(() => {
if (userId) {
realtime.connect();
return () => realtime.disconnect();
}
realtime.disconnect();
}, [userId]);
return null;
}

View File

@@ -4,12 +4,12 @@ import { useEffect, useRef } from "react";
import { usePathname } from "next/navigation";
import { apiGetSettings } from "@/lib/api";
import { applyAccentTheme } from "@/lib/theme";
import { realtime, RT_SETTINGS_CHANGED, type RtSettingsData } from "@/lib/realtime";
// 站点主题色同步器:
// 主题色由管理员在后台修改后,其他用户已打开的标签页不会因软导航重新执行根布局
// SSR,本组件通过轮询 + 标签页重新可见/获焦时探测公开设置,发现变化即热替换
// SSR,本组件通过 WS 推送 + 标签页重新可见/获焦时探测公开设置,发现变化即热替换
// accent CSS 变量(复用 lib/theme 的运行时 style 节点),无需 F5 即可换肤。
const POLL_INTERVAL_MS = 60_000;
// 焦点/可见性事件可能短时间连续触发,限制实际请求间隔
const MIN_FETCH_GAP_MS = 10_000;
@@ -27,6 +27,12 @@ export default function ThemeSync({ initialAccent }: { initialAccent: string })
let cancelled = false;
const apply = (next: string) => {
if (cancelled || next === currentRef.current) return;
currentRef.current = next;
applyAccentTheme(next || null);
};
const sync = async () => {
if (inFlightRef.current) return;
const now = Date.now();
@@ -37,18 +43,19 @@ export default function ThemeSync({ initialAccent }: { initialAccent: string })
// no-store:必须拿到管理员刚保存的最新值,不能走浏览器缓存
const { accent } = await apiGetSettings();
if (cancelled) return;
const next = (accent || "").trim().toLowerCase();
if (next !== currentRef.current) {
currentRef.current = next;
applyAccentTheme(next || null);
}
apply((accent || "").trim().toLowerCase());
} catch {
// 主题同步失败静默处理,下个周期/下次回前台再试,不打扰用户
// 主题同步失败静默处理,下次回前台再试,不打扰用户
} finally {
inFlightRef.current = false;
}
};
// WebSocket 推送优先:管理员保存即换肤;回前台 HTTP 校准兜底
const offPush = realtime.on<RtSettingsData>(RT_SETTINGS_CHANGED, (data) => {
if (data) apply((data.accent || "").trim().toLowerCase());
});
const onActive = () => {
if (document.visibilityState === "visible") void sync();
};
@@ -56,13 +63,12 @@ export default function ThemeSync({ initialAccent }: { initialAccent: string })
window.addEventListener("focus", onActive);
// 离开外观页等 pathname 变化时立刻对齐一次(受 MIN_FETCH_GAP 限频)
void sync();
const timer = setInterval(() => void sync(), POLL_INTERVAL_MS);
return () => {
cancelled = true;
offPush();
document.removeEventListener("visibilitychange", onActive);
window.removeEventListener("focus", onActive);
clearInterval(timer);
};
}, [pathname]);

View File

@@ -0,0 +1,75 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { ArrowUp } from "lucide-react";
import {
realtime,
RT_FEED_CHANGED,
type RtFeedChangedData,
} from "@/lib/realtime";
import type { FeedSort } from "@/components/home/FeedTabs";
interface FeedNewTipProps {
sort: FeedSort;
boardId?: number;
page?: number;
userId: number;
}
// 帖子流「有新内容」提示(三期):WS feed:changed → tip → 点击 refresh SSR
export default function FeedNewTip({
sort,
boardId = 0,
page = 1,
userId,
}: FeedNewTipProps) {
const router = useRouter();
const [visible, setVisible] = useState(false);
useEffect(() => {
// 第 2+ 页与推荐帖不订阅展示(推荐不随新帖/新评变化)
if (page !== 1 || sort === "recommended") {
setVisible(false);
return;
}
const off = realtime.on<RtFeedChangedData>(RT_FEED_CHANGED, (data) => {
if (!data || typeof data.post_id !== "number") return;
// 忽略自己刚发布的内容,避免回首页又弹 tip
if (data.actor_id === userId) return;
if (boardId > 0 && data.board_id !== boardId) return;
// 「新帖子」tab 只关心新帖;「新评论」tab 接受帖与评
if (sort === "new" && data.kind !== "post") return;
if (data.kind !== "post" && data.kind !== "comment") return;
setVisible(true);
});
return off;
}, [sort, boardId, page, userId]);
if (!visible || page !== 1 || sort === "recommended") return null;
const handleClick = () => {
setVisible(false);
router.refresh();
window.scrollTo({ top: 0, behavior: "smooth" });
};
return (
<div className="px-3 sm:px-4 pb-2.5">
<button
type="button"
onClick={handleClick}
className="j13-feed-new-tip w-full inline-flex items-center justify-center gap-1.5 py-2 px-3 text-[13px] font-semibold rounded-[var(--r-sm)] transition-colors"
style={{
color: "var(--accent)",
background: "var(--accent-soft)",
border: "1px solid var(--nav-active-line, var(--accent))",
}}
>
<ArrowUp size={14} aria-hidden />
有新内容
</button>
</div>
);
}

View File

@@ -38,6 +38,8 @@ export interface User {
export interface MeResponse {
user: User | null;
unread_count: number;
// 群聊未读消息总数(二期)
chat_unread_count?: number;
// 后端 OptionalAuth 识别到凭据所属账号已封禁时携带(HTTP 仍 200,不阻断页面)
banned?: boolean;
code?: string;
@@ -144,6 +146,7 @@ export interface PostListItem {
like_count: number;
view_count: number;
comment_count: number;
status?: string;
liked: boolean;
created_at: string;
last_reply?: {
@@ -251,14 +254,17 @@ export interface NotificationItem {
id: number;
user_id: number;
actor_id: number;
type: "comment" | "reply" | "like" | "approved" | "rejected";
type: "comment" | "reply" | "like" | "approved" | "rejected" | "mention" | "pending_review";
post_id: number;
comment_id: number;
room_id?: number;
message_id?: number;
content: string;
is_read: boolean;
created_at: string;
actor: User;
post: { id: number; title: string };
post?: { id: number; title: string };
room?: { id: number; name: string } | null;
}
export interface NotificationsResponse {
@@ -890,6 +896,18 @@ export async function fetchAdminPendingPosts(
return res.json();
}
/** SSR 待审数量(帖子 + 评论);失败时返回零,不阻塞仪表盘 */
export async function fetchAdminPendingCounts(
cookieHeader?: string
): Promise<PendingCounts> {
const res = await fetch(
`${API_BASE}/api/admin/moderation/counts`,
ssrInit(cookieHeaders(cookieHeader))
);
if (!res.ok) return { posts: 0, comments: 0 };
return res.json();
}
// 客户端后台用户列表(走 rewrite,携带 cookie + CSRF)
export async function apiAdminListUsers(query: AdminUsersQuery = {}): Promise<AdminUsersResponse> {
const res = await fetchWithRefresh(`/api/admin/users?${adminUsersParams(query)}`, {
@@ -946,6 +964,115 @@ export async function apiAdminSetUserBan(
return data as { user: AdminUser };
}
// ===== 站长用户内容档案 =====
export interface AdminUserAuditProfile {
user: AdminUser;
posts_total: number;
comments_total: number;
messages_total: number;
published_posts: number;
published_comments: number;
}
export interface AdminAuditPostItem {
id: number;
title: string;
content: string;
status: string;
deleted: boolean;
board_id: number;
board_name: string;
created_at: string;
deleted_at?: string | null;
}
export interface AdminAuditCommentItem {
id: number;
post_id: number;
content: string;
status: string;
deleted: boolean;
created_at: string;
deleted_at?: string | null;
}
export interface AdminAuditMessageItem {
id: number;
room_id: number;
room_name: string;
room_type: string;
content: string;
recalled: boolean;
deleted: boolean;
created_at: string;
deleted_at?: string | null;
}
export interface AdminAuditListResponse<T> {
items: T[];
total: number;
page: number;
}
export async function fetchAdminUserAudit(
id: number,
cookieHeader?: string
): Promise<AdminUserAuditProfile> {
const res = await fetch(
`${API_BASE}/api/admin/users/${id}`,
ssrInit(cookieHeaders(cookieHeader))
);
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "获取用户档案失败");
return data as AdminUserAuditProfile;
}
export async function apiAdminUserAudit(id: number): Promise<AdminUserAuditProfile> {
const res = await fetchWithRefresh(`/api/admin/users/${id}`, {
headers: clientHeaders(),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "获取用户档案失败");
return data as AdminUserAuditProfile;
}
export async function apiAdminUserAuditPosts(
id: number,
page = 1
): Promise<AdminAuditListResponse<AdminAuditPostItem>> {
const res = await fetchWithRefresh(`/api/admin/users/${id}/posts?page=${page}`, {
headers: clientHeaders(),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "获取帖子失败");
return data as AdminAuditListResponse<AdminAuditPostItem>;
}
export async function apiAdminUserAuditComments(
id: number,
page = 1
): Promise<AdminAuditListResponse<AdminAuditCommentItem>> {
const res = await fetchWithRefresh(`/api/admin/users/${id}/comments?page=${page}`, {
headers: clientHeaders(),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "获取评论失败");
return data as AdminAuditListResponse<AdminAuditCommentItem>;
}
export async function apiAdminUserAuditMessages(
id: number,
page = 1
): Promise<AdminAuditListResponse<AdminAuditMessageItem>> {
const res = await fetchWithRefresh(`/api/admin/users/${id}/messages?page=${page}`, {
headers: clientHeaders(),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "获取消息失败");
return data as AdminAuditListResponse<AdminAuditMessageItem>;
}
// ===== 站点外观设置 =====
export async function apiGetSettings(): Promise<PublicSettings> {
@@ -1043,3 +1170,400 @@ export const apiAdminApproveComment = (id: number) =>
moderationAction(`/api/admin/moderation/comments/${id}/approve`);
export const apiAdminRejectComment = (id: number) =>
moderationAction(`/api/admin/moderation/comments/${id}/reject`);
// ===== 群聊(二期) =====
// 群聊房间基础模型(与后端 model.ChatRoom 对齐)
export interface ChatRoom {
id: number;
name: string;
description: string;
owner_id: number;
room_type: "group" | "direct";
member_count: number;
last_message_id: number;
is_private: boolean;
is_default: boolean;
created_at: string;
updated_at: string;
owner: User;
last_message?: ChatMessage | null;
}
// 列表/详情聚合视图:扁平房间 + 当前访问者相关字段
export interface ChatRoomView extends ChatRoom {
joined: boolean;
my_role: "" | "owner" | "member" | "overseer";
unread_count: number;
pinned?: boolean;
pin_forced?: boolean;
peer?: User | null;
}
// 群成员行(名单/踢人用)
export interface ChatRoomMember {
id: number;
room_id: number;
user_id: number;
role: "owner" | "member";
last_read_message_id: number;
muted: boolean;
created_at: string;
updated_at: string;
user: User;
}
// 群消息(发送者已 Preload)
export interface ChatMessage {
id: number;
room_id: number;
sender_id: number;
content: string;
reply_to_id?: number;
reply_snap?: string;
created_at: string;
recalled_at?: string | null;
recalled_by?: number;
sender: User;
}
// 单群未读明细
export interface UnreadRoom {
room_id: number;
count: number;
}
export interface ChatRoomsResponse {
rooms: ChatRoomView[];
total: number;
page: number;
size: number;
}
export interface ChatMembersResponse {
members: ChatRoomMember[];
}
export interface ChatMessagesResponse {
messages: ChatMessage[];
has_more: boolean;
}
export interface ChatUnreadSummaryResponse {
total: number;
rooms: UnreadRoom[];
}
// SSR 消息会话列表(默认仅已加入)
export async function fetchChatRooms(
page = 1,
size = 40,
q = "",
cookieHeader?: string,
scope: "joined" | "all" = "joined"
): Promise<ChatRoomsResponse> {
const params = new URLSearchParams({
page: String(page),
size: String(size),
scope,
});
if (q) params.set("q", q);
const res = await fetch(
`${API_BASE}/api/chat/rooms?${params}`,
ssrInit(cookieHeaders(cookieHeader))
);
if (res.status === 401) throw new Error("未登录");
if (!res.ok) throw new Error("获取会话列表失败");
return res.json();
}
// SSR 群详情:公开非成员 200(joined=false);私密非成员/不存在 404
export async function fetchChatRoom(
id: string,
cookieHeader?: string
): Promise<{ room: ChatRoomView }> {
const res = await fetch(
`${API_BASE}/api/chat/rooms/${id}`,
ssrInit(cookieHeaders(cookieHeader))
);
if (res.status === 401) throw new Error("未登录");
if (res.status === 404) throw new Error("群不存在");
if (!res.ok) throw new Error("获取群详情失败");
return res.json();
}
// SSR 历史消息游标分页(成员可见;非成员抛错由页面层处理)
export async function fetchChatMessages(
id: string,
before = 0,
size = 30,
cookieHeader?: string
): Promise<ChatMessagesResponse> {
const params = new URLSearchParams({ size: String(size) });
if (before) params.set("before_id", String(before));
const res = await fetch(
`${API_BASE}/api/chat/rooms/${id}/messages?${params}`,
ssrInit(cookieHeaders(cookieHeader))
);
if (res.status === 401) throw new Error("未登录");
if (res.status === 403) throw new Error("无权查看消息");
if (res.status === 404) throw new Error("群不存在");
if (!res.ok) throw new Error("获取消息失败");
return res.json();
}
// 客户端:会话列表
export async function apiListChatRooms(
page = 1,
size = 40,
q = "",
scope: "joined" | "all" = "joined"
): Promise<ChatRoomsResponse> {
const params = new URLSearchParams({
page: String(page),
size: String(size),
scope,
});
if (q) params.set("q", q);
const res = await fetchWithRefresh(`/api/chat/rooms?${params}`, {
headers: clientHeaders(),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "获取会话列表失败");
return data as ChatRoomsResponse;
}
// 客户端:打开/创建私聊
export async function apiOpenDirectChat(
userId: number
): Promise<{ room: ChatRoomView }> {
const res = await fetchWithRefresh("/api/chat/direct", {
method: "POST",
headers: clientHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify({ user_id: userId }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "无法发起私聊");
return data as { room: ChatRoomView };
}
// 客户端:搜索用户以发起私聊
export async function apiSearchChatUsers(
q: string
): Promise<{ users: User[] }> {
const params = new URLSearchParams({ q });
const res = await fetchWithRefresh(`/api/chat/users?${params}`, {
headers: clientHeaders(),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "搜索失败");
return data as { users: User[] };
}
// 客户端:建群(可公开/私密,私密可带初始成员用户名)
export async function apiCreateChatRoom(
name: string,
description = "",
opts?: { is_private?: boolean; member_usernames?: string[] }
): Promise<{ room: ChatRoomView }> {
const res = await fetchWithRefresh("/api/chat/rooms", {
method: "POST",
headers: clientHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify({
name,
description,
is_private: opts?.is_private ?? false,
member_usernames: opts?.member_usernames ?? [],
}),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "建群失败");
return data as { room: ChatRoomView };
}
// 客户端:群详情
export async function apiGetChatRoom(id: number): Promise<{ room: ChatRoomView }> {
const res = await fetchWithRefresh(`/api/chat/rooms/${id}`, {
headers: clientHeaders(),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "获取群详情失败");
return data as { room: ChatRoomView };
}
// 客户端:群主改群名/简介
export async function apiUpdateChatRoom(
id: number,
name: string,
description = ""
): Promise<{ room: ChatRoomView }> {
const res = await fetchWithRefresh(`/api/chat/rooms/${id}`, {
method: "PUT",
headers: clientHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify({ name, description }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "修改群信息失败");
return data as { room: ChatRoomView };
}
// 客户端:置顶/取消置顶(大厅强制置顶不可取消)
export async function apiPinChatRoom(
id: number,
pinned: boolean
): Promise<{ room: ChatRoomView }> {
const res = await fetchWithRefresh(`/api/chat/rooms/${id}/pin`, {
method: "PUT",
headers: clientHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify({ pinned }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "置顶失败");
return data as { room: ChatRoomView };
}
// 客户端:群主解散群
export async function apiDissolveChatRoom(id: number): Promise<{ ok: boolean }> {
const res = await fetchWithRefresh(`/api/chat/rooms/${id}`, {
method: "DELETE",
headers: clientHeaders(),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "解散群失败");
return data as { ok: boolean };
}
// 客户端:加入群聊
export async function apiJoinChatRoom(
id: number
): Promise<{ ok: boolean; joined: boolean }> {
const res = await fetchWithRefresh(`/api/chat/rooms/${id}/join`, {
method: "POST",
headers: clientHeaders(),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "加入群失败");
return data as { ok: boolean; joined: boolean };
}
// 客户端:退出群聊
export async function apiLeaveChatRoom(id: number): Promise<{ ok: boolean }> {
const res = await fetchWithRefresh(`/api/chat/rooms/${id}/leave`, {
method: "POST",
headers: clientHeaders(),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "退出群失败");
return data as { ok: boolean };
}
// 客户端:成员名单
export async function apiListChatMembers(
id: number
): Promise<ChatMembersResponse> {
const res = await fetchWithRefresh(`/api/chat/rooms/${id}/members`, {
headers: clientHeaders(),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "获取成员名单失败");
return data as ChatMembersResponse;
}
// 客户端:群主踢人
export async function apiKickChatMember(
roomId: number,
userId: number
): Promise<{ ok: boolean }> {
const res = await fetchWithRefresh(
`/api/chat/rooms/${roomId}/members/${userId}`,
{ method: "DELETE", headers: clientHeaders() }
);
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "踢人失败");
return data as { ok: boolean };
}
// 客户端:邀请成员(用户名列表,群主/监管)
export async function apiInviteChatMembers(
roomId: number,
usernames: string[]
): Promise<{ added: number[] }> {
const res = await fetchWithRefresh(`/api/chat/rooms/${roomId}/members`, {
method: "POST",
headers: clientHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify({ usernames }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "邀请失败");
return data as { added: number[] };
}
// 客户端:撤回消息
export async function apiRecallChatMessage(
roomId: number,
messageId: number
): Promise<{ message: ChatMessage }> {
const res = await fetchWithRefresh(
`/api/chat/rooms/${roomId}/messages/${messageId}`,
{ method: "DELETE", headers: clientHeaders() }
);
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "撤回失败");
return data as { message: ChatMessage };
}
// 客户端:历史消息游标分页
export async function apiListChatMessages(
id: number,
before = 0,
size = 30
): Promise<ChatMessagesResponse> {
const params = new URLSearchParams({ size: String(size) });
if (before) params.set("before_id", String(before));
const res = await fetchWithRefresh(`/api/chat/rooms/${id}/messages?${params}`, {
headers: clientHeaders(),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "获取消息失败");
return data as ChatMessagesResponse;
}
// 客户端:发消息(可带引用;@ 提醒由后端解析)
export async function apiSendChatMessage(
id: number,
content: string,
replyToId = 0
): Promise<{ message: ChatMessage }> {
const res = await fetchWithRefresh(`/api/chat/rooms/${id}/messages`, {
method: "POST",
headers: clientHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify({ content, reply_to_id: replyToId || undefined }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "发送失败");
return data as { message: ChatMessage };
}
// 客户端:推进已读水位(messageId=0 或超过最新则取最新)
export async function apiMarkChatRead(
id: number,
messageId = 0
): Promise<{ ok: boolean }> {
const res = await fetchWithRefresh(`/api/chat/rooms/${id}/read`, {
method: "PUT",
headers: clientHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify({ message_id: messageId }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "标记已读失败");
return data as { ok: boolean };
}
// 客户端:全部群未读明细与总数(Header 红点对账)
export async function apiChatUnreadSummary(): Promise<ChatUnreadSummaryResponse> {
const res = await fetchWithRefresh("/api/chat/unread-summary", {
headers: clientHeaders(),
});
if (!res.ok) return { total: 0, rooms: [] };
return res.json();
}

336
frontend/lib/realtime.ts Normal file
View File

@@ -0,0 +1,336 @@
// 全站实时总线客户端(一期:在线状态 + 站点设置变更;二期:群聊 + 站内通知;三期:帖子流有新内容)。
//
// - 单条 WebSocket(浏览器握手自动携带 HttpOnly cookie 鉴权),后续群聊/通知/
// 审核角标都复用本连接,按 message type 路由。
// - 连接状态机 + 指数退避重连;应用层心跳(协议层 Ping 由浏览器自动应答)。
// - 鉴权失效关闭码 4401 不自动重连(封禁/强制下线由 AccountGuard 统一处理)。
// - 在线集合:hello 帧给 staff 全量快照,之后 presence:update 增量维护。
// - 群聊:进入群详情页调用 joinRoom(roomID) 订阅 chat:{id} 房间,
// 重连后会自动重订当前已订阅集合;离开页面/退出群调用 leaveRoom。
// - 轮询仅作兜底:回前台 / 进页时 HTTP 校准;实时靠 WS(通知、待审、主题、群聊未读)。
export const RT_HELLO = "hello";
export const RT_PONG = "pong";
export const RT_SETTINGS_CHANGED = "settings:changed";
export const RT_PRESENCE_UPDATE = "presence:update";
export const RT_CHAT_MESSAGE = "chat:message";
export const RT_CHAT_MEMBERSHIP = "chat:membership";
export const RT_CHAT_RECALLED = "chat:message_recalled";
export const RT_CHAT_UNREAD = "chat:unread";
export const RT_NOTIFICATION_NEW = "notification:new";
export const RT_FEED_CHANGED = "feed:changed";
export const RT_MODERATION_CHANGED = "moderation:changed";
export interface RtEnvelope<T = unknown> {
type: string;
data?: T;
}
export interface RtHelloData {
user_id: number;
ts: number;
// 仅管理团队成员会收到
online_user_ids?: number[];
}
export interface RtPresenceData {
user_id: number;
online: boolean;
}
export interface RtSettingsData {
accent: string;
}
// 群聊新消息:data 为落库的 ChatMessage(含 sender)
export interface RtChatMessageData {
id: number;
room_id: number;
sender_id: number;
content: string;
reply_to_id?: number;
reply_snap?: string;
created_at: string;
sender: {
id: number;
username: string;
nickname: string;
avatar: string;
};
}
// 群成员关系变更:被踢/群解散/被邀请
export interface RtChatMembershipData {
room_id: number;
status: "kicked" | "dissolved" | "invited";
}
// 消息撤回
export interface RtChatRecalledData {
id: number;
room_id: number;
sender_id?: number;
recalled_by: number;
recalled_at?: string;
}
// 未读增量(推送给未在房内订阅的成员,用于 Header / 会话列表角标)
export interface RtChatUnreadData {
room_id: number;
message_id: number;
sender_id: number;
preview?: string;
delta: number;
}
// 新站内通知(如群聊 @):收到后应刷新通知列表/红点
export interface RtNotificationData {
room_id?: number;
message_id?: number;
}
// 帖子流有公开新内容(三期):首页 tip「有新内容」
export interface RtFeedChangedData {
kind: "post" | "comment";
post_id: number;
board_id: number;
actor_id: number;
}
type RtHandler<T = unknown> = (data: T) => void;
type RtState = "idle" | "connecting" | "open" | "closed";
const HEARTBEAT_MS = 25_000;
const RECONNECT_BASE_MS = 1_000;
const RECONNECT_MAX_MS = 15_000;
const CLOSE_AUTH_INVALID = 4401;
// 开发环境 Next dev 的 rewrite 不透传 WebSocket Upgrade,直连后端 3001;
// Cookie 不按端口隔离,localhost:3000 的 j13_token 会随握手发到 :3001。
// 生产环境前后端同源(反向代理),走同源 /api/ws;可用 NEXT_PUBLIC_WS_URL 覆盖。
function wsEndpoint(): string {
const explicit = process.env.NEXT_PUBLIC_WS_URL;
if (explicit) return explicit;
if (typeof window === "undefined") return "";
const scheme = window.location.protocol === "https:" ? "wss://" : "ws://";
if (process.env.NODE_ENV !== "production") {
return `${scheme}${window.location.hostname}:3001/api/ws`;
}
return `${scheme}${window.location.host}/api/ws`;
}
class RealtimeClient {
private ws: WebSocket | null = null;
private state: RtState = "idle";
// 是否应保持连接(登录态);登出或组件卸载时置 false 停止重连
private wanted = false;
private retryCount = 0;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
private readonly handlers = new Map<string, Set<RtHandler>>();
private readonly presenceHandlers = new Set<RtHandler<RtPresenceData>>();
private onlineIds = new Set<number>();
// 已订阅的群聊房间(roomID 集合):重连后会自动重订,断连期间不丢订阅意图
private readonly joinedRooms = new Set<number>();
/** 建立连接(幂等);登录后调用 */
connect(): void {
if (typeof window === "undefined") return;
this.wanted = true;
if (this.state === "open" || this.state === "connecting") return;
this.clearReconnectTimer();
this.open();
window.addEventListener("online", this.handleNetworkBack);
document.addEventListener("visibilitychange", this.handleVisible);
}
/** 主动断开(登出/卸载);不再自动重连 */
disconnect(): void {
this.wanted = false;
window.removeEventListener("online", this.handleNetworkBack);
document.removeEventListener("visibilitychange", this.handleVisible);
this.clearReconnectTimer();
this.clearHeartbeat();
if (this.ws) {
this.ws.onclose = null;
this.ws.close(1000, "client logout");
this.ws = null;
}
this.state = "idle";
// 登出时清空房间订阅,避免下次同标签页重新登录后误订旧群
this.joinedRooms.clear();
}
isOpen(): boolean {
return this.state === "open";
}
/** 订阅指定事件,返回取消订阅函数 */
on<T>(type: string, handler: RtHandler<T>): () => void {
let set = this.handlers.get(type);
if (!set) {
set = new Set();
this.handlers.set(type, set);
}
set.add(handler as RtHandler);
return () => set!.delete(handler as RtHandler);
}
/** 订阅在线状态增量(用户 0↔1 连接跳变);快照请在订阅时读 getOnlineIds */
onPresence(handler: RtHandler<RtPresenceData>): () => void {
this.presenceHandlers.add(handler);
return () => this.presenceHandlers.delete(handler);
}
/** 当前在线用户 ID 快照 */
getOnlineIds(): ReadonlySet<number> {
return this.onlineIds;
}
/** 订阅群聊房间(进入群详情页调用)。幂等;连接已 open 时立即发 join 帧。
* 后端会按 chat:{id} 实时校验成员身份,被踢后再 join 也会被拒绝。 */
joinRoom(roomId: number): void {
if (!Number.isInteger(roomId) || roomId <= 0) return;
this.joinedRooms.add(roomId);
this.sendRoomFrame("join", roomId);
}
/** 退订群聊房间(离开群详情页/退出群调用)。幂等。 */
leaveRoom(roomId: number): void {
if (!this.joinedRooms.delete(roomId)) return;
this.sendRoomFrame("leave", roomId);
}
/** 退订全部群聊房间(切账号/被踢后清理) */
clearRooms(): void {
for (const id of this.joinedRooms) {
this.sendRoomFrame("leave", id);
}
this.joinedRooms.clear();
}
private sendRoomFrame(type: "join" | "leave", roomId: number): void {
if (this.state !== "open" || !this.ws) return;
this.ws.send(JSON.stringify({ type, room: `chat:${roomId}` }));
}
private handleNetworkBack = (): void => {
if (this.wanted && this.state === "closed") this.open();
};
private handleVisible = (): void => {
if (!this.wanted || document.visibilityState !== "visible") return;
// 后台标签页定时器可能被节流;重新可见时若连接已断则立即重连
if (this.state === "closed" || this.state === "idle") this.open();
};
private open(): void {
if (typeof WebSocket === "undefined") return;
this.state = "connecting";
let ws: WebSocket;
try {
ws = new WebSocket(wsEndpoint());
} catch {
this.scheduleReconnect();
return;
}
this.ws = ws;
ws.onopen = () => {
this.state = "open";
this.retryCount = 0;
this.clearHeartbeat();
this.heartbeatTimer = setInterval(() => {
this.send({ type: "ping" });
}, HEARTBEAT_MS);
// 重连后自动重订群聊房间(避免断线期间错过消息)
// 后端会按 chat:{id} 实时校验成员身份,已退出/被踢的群会被静默拒绝
for (const roomId of this.joinedRooms) {
this.sendRoomFrame("join", roomId);
}
};
ws.onmessage = (ev) => this.handleMessage(ev.data);
ws.onerror = () => {
// close 事件会紧随其后,重连逻辑统一在 onclose 处理
};
ws.onclose = (ev) => {
this.clearHeartbeat();
if (this.ws === ws) this.ws = null;
this.state = "closed";
// 鉴权失效:账号封禁/角色变更导致 token_version 失效,
// 不重连(强制下线/重新登录由现有 HTTP 拦截链路处理)
if (!this.wanted || ev.code === CLOSE_AUTH_INVALID) {
this.wanted = false;
return;
}
this.scheduleReconnect();
};
}
private scheduleReconnect(): void {
if (!this.wanted || this.reconnectTimer) return;
const delay = Math.min(
RECONNECT_MAX_MS,
RECONNECT_BASE_MS * 2 ** this.retryCount
);
// ±20% 抖动,避免后端重启时所有客户端同时重连
const jitter = delay * 0.2 * (Math.random() * 2 - 1);
this.retryCount += 1;
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
if (this.wanted) this.open();
}, Math.max(500, delay + jitter));
}
private clearReconnectTimer(): void {
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
}
private clearHeartbeat(): void {
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
}
}
private send(msg: RtEnvelope): void {
if (this.state === "open" && this.ws) {
this.ws.send(JSON.stringify(msg));
}
}
private handleMessage(raw: unknown): void {
if (typeof raw !== "string") return;
let msg: RtEnvelope;
try {
msg = JSON.parse(raw) as RtEnvelope;
} catch {
return;
}
if (!msg || typeof msg.type !== "string") return;
// 内部状态事件先维护在线集合
if (msg.type === RT_HELLO) {
const data = msg.data as RtHelloData | undefined;
const ids = data?.online_user_ids;
if (Array.isArray(ids)) {
this.onlineIds = new Set(ids.filter((n) => Number.isInteger(n)));
}
} else if (msg.type === RT_PRESENCE_UPDATE) {
const data = msg.data as RtPresenceData | undefined;
if (data && typeof data.user_id === "number") {
if (data.online) this.onlineIds.add(data.user_id);
else this.onlineIds.delete(data.user_id);
this.presenceHandlers.forEach((fn) => fn(data));
}
}
const set = this.handlers.get(msg.type);
if (set) set.forEach((fn) => fn(msg.data));
}
}
// 全站单例(模块级,持久 root layout 下与标签页生命周期一致)
export const realtime = new RealtimeClient();

View File

@@ -39,11 +39,16 @@ export function isSuperOrOwner(role?: string | null): boolean {
return roleLevel(role) >= ROLE_LEVEL[ROLES.SUPER_ADMIN];
}
/** 站长(唯一,不可被操作) */
/** 站长(站点所有者) */
export function isOwner(role?: string | null): boolean {
return role === ROLES.OWNER;
}
/** 站长/超管:群聊监管旁路(可见全部群、撤回任意消息) */
export function canOverseeChat(role?: string | null): boolean {
return role === ROLES.OWNER || role === ROLES.SUPER_ADMIN;
}
/** 携带板块授权的最小用户形状(/me、帖子详情作者等均满足) */
export interface RoleUserLike {
role?: string | null;

View File

@@ -190,10 +190,15 @@ export function deriveAccentPair(input: string): AccentDerivation {
}
// 生成可直接注入的 CSS 文本(覆盖 globals.css 默认 accent 令牌);
// 未配置或等于默认色时返回空串,完全使用内置样式
// 未配置或等于默认色时返回空串,完全使用内置样式(SSR 场景)
export function accentStyleCSS(input: string): string {
if (!input || input.toLowerCase() === DEFAULT_ACCENT) return "";
const { light, dark } = deriveAccentPair(input);
return buildAccentCSS(input);
}
/** 始终输出一套 accent 覆盖(含默认色),供客户端 runtime 盖住 SSR 自定义 style */
function buildAccentCSS(input: string): string {
const { light, dark } = deriveAccentPair(input || DEFAULT_ACCENT);
const hi = mix(light, "#000000", 0.1);
const darkHi = mix(dark, "#ffffff", 0.14);
return [
@@ -222,22 +227,44 @@ export function accentStyleCSS(input: string): string {
// 客户端:实时换肤(后台预览 / 保存后即时生效)
// ---------------------------------------------------------------
const STYLE_ELEMENT_ID = "j13-accent-vars";
/** SSR 注入的 style(React 托管,客户端禁止 remove/改写) */
const SSR_STYLE_ID = "j13-accent-vars";
/** 客户端专用覆盖节点,挂在 body 末尾以压过 SSR */
const RUNTIME_STYLE_ID = "j13-accent-runtime";
// 将主题色应用到当前文档;传 null 移除覆盖、恢复内置默认
function ensureRuntimeStyle(): HTMLStyleElement {
let el = document.getElementById(RUNTIME_STYLE_ID) as HTMLStyleElement | null;
if (el) return el;
el = document.createElement("style");
el.id = RUNTIME_STYLE_ID;
el.setAttribute("data-accent-source", "runtime");
document.body.appendChild(el);
return el;
}
function removeRuntimeStyle(): void {
const el = document.getElementById(RUNTIME_STYLE_ID);
// 只移除我们自己创建的节点,绝不碰 React 的 SSR <style>
el?.remove();
}
// 将主题色应用到当前文档;传 null/默认色时恢复内置令牌(不拆 SSR 节点)
export function applyAccentTheme(input: string | null): void {
if (typeof document === "undefined") return;
let el = document.getElementById(STYLE_ELEMENT_ID) as HTMLStyleElement | null;
const css = input === null ? "" : accentStyleCSS(input);
if (!css) {
el?.remove();
const raw = (input || "").trim().toLowerCase();
const isDefault = !raw || raw === DEFAULT_ACCENT.toLowerCase();
if (isDefault) {
const ssr = document.getElementById(SSR_STYLE_ID);
const ssrHasCustom = !!(ssr && ssr.textContent && ssr.textContent.trim());
if (ssrHasCustom) {
// SSR 仍挂着旧自定义色:用 runtime 写回默认覆盖,等 refresh 后再卸
ensureRuntimeStyle().textContent = buildAccentCSS(DEFAULT_ACCENT);
} else {
removeRuntimeStyle();
}
return;
}
if (!el) {
el = document.createElement("style");
el.id = STYLE_ELEMENT_ID;
document.head.appendChild(el);
}
el.setAttribute("data-accent-source", "runtime");
el.textContent = css;
ensureRuntimeStyle().textContent = buildAccentCSS(raw);
}