feat: 新增站点公告系统与多项体验优化

此提交完成了以下核心功能与优化:
1. 新增站点公告全流程支持:包含公告模型、CRUD接口、管理后台页面、公告详情页与首页展示
2. 实现评论楼层化与回复嵌套:重构评论系统为树状结构,支持回复评论与层级限制
3. 添加用户在线状态追踪:异步更新用户最后活跃时间并做SQL限频
4. 优化用户体验:移动端浮动操作条、统一板块标签样式、用户页签到积分展示、注册即登录优化
5. 其他细节优化:SEO站点地图新增公告页、评论分页与统计、登录/注册表单增强等
This commit is contained in:
2026-09-13 21:38:01 +08:00
parent 9bae6f2513
commit 996a870015
41 changed files with 2846 additions and 786 deletions

View File

@@ -0,0 +1,372 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import {
Plus,
Pencil,
Trash2,
Loader2,
Save,
X,
ExternalLink,
Megaphone,
FileText,
} from "lucide-react";
import {
apiAdminListAnnouncements,
apiAdminCreateAnnouncement,
apiAdminUpdateAnnouncement,
apiAdminDeleteAnnouncement,
type Announcement,
type AnnouncementColor,
type AnnouncementInput,
} from "@/lib/api";
import { formatDate } from "@/lib/format";
import { toast } from "@/lib/toast";
const COLORS: { value: AnnouncementColor; label: string }[] = [
{ value: "blue", label: "蓝色" },
{ value: "green", label: "绿色" },
{ value: "orange", label: "橙色" },
{ value: "red", label: "红色" },
{ value: "purple", label: "紫色" },
{ value: "gray", label: "灰色" },
];
type FormState = AnnouncementInput & { id: number | null };
const EMPTY_FORM: FormState = {
id: null,
title: "",
content: "",
tag: "公告",
tag_color: "blue",
published: true,
};
export default function AnnouncementAdmin() {
const [list, setList] = useState<Announcement[]>([]);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState("");
const [form, setForm] = useState<FormState | null>(null);
const [saving, setSaving] = useState(false);
const [deletingId, setDeletingId] = useState<number | null>(null);
const load = useCallback(async () => {
setLoading(true);
try {
const res = await apiAdminListAnnouncements();
setList(res.announcements);
setLoadError("");
} catch (e) {
setLoadError(e instanceof Error ? e.message : "加载公告失败");
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
load();
}, [load]);
const startCreate = () => setForm({ ...EMPTY_FORM });
const startEdit = (a: Announcement) =>
setForm({
id: a.id,
title: a.title,
content: a.content,
tag: a.tag,
tag_color: a.tag_color,
published: a.published,
});
async function save() {
if (!form) return;
const payload: AnnouncementInput = {
title: form.title.trim(),
content: form.content.trim(),
tag: form.tag.trim() || "公告",
tag_color: form.tag_color,
published: form.published,
};
if (!payload.title || !payload.content) {
toast("标题和内容不能为空");
return;
}
setSaving(true);
try {
if (form.id == null) {
await apiAdminCreateAnnouncement(payload);
toast("公告已发布", "ok");
} else {
await apiAdminUpdateAnnouncement(form.id, payload);
toast("公告已更新", "ok");
}
setForm(null);
await load();
} catch (e) {
toast(e instanceof Error ? e.message : "保存失败");
} finally {
setSaving(false);
}
}
async function remove(a: Announcement) {
if (!window.confirm(`确定删除公告「${a.title}」吗?此操作不可撤销。`)) return;
setDeletingId(a.id);
try {
await apiAdminDeleteAnnouncement(a.id);
setList((l) => l.filter((x) => x.id !== a.id));
if (form?.id === a.id) setForm(null);
toast("公告已删除", "ok");
} catch (e) {
toast(e instanceof Error ? e.message : "删除失败");
} finally {
setDeletingId(null);
}
}
return (
<div>
{/* 页头 */}
<div className="flex items-center justify-between gap-3 flex-wrap mb-5">
<div>
<h1 className="text-[22px] sm:text-[26px] font-extrabold tracking-tight flex items-center gap-2.5" style={{ color: "var(--ink)" }}>
<span
className="w-9 h-9 rounded-xl flex items-center justify-center"
style={{ background: "var(--accent-soft)", color: "var(--accent)" }}
>
<Megaphone size={18} />
</span>
站点公告管理
</h1>
<p className="meta mt-1.5 text-[12.5px]">发布、编辑与下线右栏站点公告,支持自定义标签与标签颜色</p>
</div>
{form?.id == null && (
<button onClick={startCreate} className="btn btn-primary">
<Plus size={15} /> 新建公告
</button>
)}
</div>
<div className="grid grid-cols-1 lg:grid-cols-[400px_minmax(0,1fr)] gap-6 items-start">
{/* 编辑/新建表单 */}
{form ? (
<div className="panel p-5 lg:sticky lg:top-24">
<p className="font-extrabold text-[15px] mb-4" style={{ color: "var(--ink)" }}>
{form.id == null ? "新建公告" : "编辑公告"}
</p>
<label className="field-label" htmlFor="anno-title">
标题
</label>
<input
id="anno-title"
className="field mb-4"
maxLength={200}
value={form.title}
onChange={(e) => setForm({ ...form, title: e.target.value })}
placeholder="请输入公告标题"
/>
<div className="flex items-end gap-4 mb-4 flex-wrap">
<div className="w-36">
<label className="field-label" htmlFor="anno-tag">
标签
</label>
<input
id="anno-tag"
className="field"
maxLength={32}
value={form.tag}
onChange={(e) => setForm({ ...form, tag: e.target.value })}
placeholder="公告"
/>
</div>
<div>
<p className="field-label">标签颜色</p>
<div className="flex items-center gap-2">
{COLORS.map((c) => (
<button
key={c.value}
type="button"
title={c.label}
aria-label={c.label}
aria-pressed={form.tag_color === c.value}
className={`j13-anno-dot is-${c.value}`}
onClick={() => setForm({ ...form, tag_color: c.value })}
/>
))}
</div>
</div>
</div>
<p className="field-label">发布状态</p>
<div className="flex items-center gap-2 mb-4" role="group" aria-label="发布状态">
<button
type="button"
className="j13-tab"
aria-pressed={form.published}
onClick={() => setForm({ ...form, published: true })}
style={form.published ? { background: "var(--accent-soft)", borderColor: "color-mix(in srgb, var(--accent) 38%, var(--line))", color: "var(--accent)" } : undefined}
>
立即发布
</button>
<button
type="button"
className="j13-tab"
aria-pressed={!form.published}
onClick={() => setForm({ ...form, published: false })}
style={!form.published ? { background: "var(--gold-soft)", borderColor: "color-mix(in srgb, var(--gold) 38%, var(--line))", color: "var(--gold)" } : undefined}
>
存为草稿
</button>
</div>
<label className="field-label" htmlFor="anno-content">
正文(支持 Markdown)
</label>
<textarea
id="anno-content"
className="field min-h-[260px]"
value={form.content}
onChange={(e) => setForm({ ...form, content: e.target.value })}
placeholder="请输入公告正文,支持 Markdown 语法…"
/>
<div className="flex items-center gap-2.5 mt-4">
<button onClick={save} disabled={saving} className="btn btn-primary flex-1 justify-center">
{saving ? (
<>
<Loader2 size={15} className="animate-spin" /> 保存中…
</>
) : (
<>
<Save size={15} /> {form.id == null ? "发布公告" : "保存修改"}
</>
)}
</button>
<button
onClick={() => setForm(null)}
disabled={saving}
className="btn btn-line"
aria-label="取消编辑"
>
<X size={15} /> 取消
</button>
</div>
</div>
) : (
<div className="panel p-6 text-center lg:sticky lg:top-24">
<span
className="inline-flex w-12 h-12 rounded-2xl items-center justify-center mb-3"
style={{ background: "var(--accent-soft)", color: "var(--accent)" }}
>
<FileText size={22} />
</span>
<p className="font-bold text-[14.5px]" style={{ color: "var(--ink)" }}>
公告编辑器
</p>
<p className="meta mt-1.5 text-[12.5px] leading-relaxed">
点击右上「新建公告」发布公告,
<br />
或在右侧列表中选择已有公告进行编辑。
</p>
<button onClick={startCreate} className="btn btn-primary mt-4">
<Plus size={15} /> 新建公告
</button>
</div>
)}
{/* 公告列表 */}
<div className="panel overflow-hidden">
<div
className="px-4 sm:px-5 py-3.5 flex items-center justify-between"
style={{ borderBottom: "1px solid var(--line)" }}
>
<span className="font-bold text-[15px]" style={{ color: "var(--ink)" }}>
全部公告
</span>
<span className="meta text-[12px] tabular-nums">共 {list.length} 条</span>
</div>
{loading ? (
<div className="flex items-center justify-center gap-2 py-16 meta text-[13px]">
<Loader2 size={16} className="animate-spin" /> 加载中…
</div>
) : loadError ? (
<p className="alert-error m-4">{loadError}</p>
) : list.length === 0 ? (
<p className="meta text-center py-16 text-[13px]">还没有公告,点击「新建公告」发布第一条吧</p>
) : (
list.map((a) => (
<div
key={a.id}
className="group flex items-center gap-3 px-4 sm:px-5 py-3.5"
style={{ borderTop: "1px solid var(--line)" }}
>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 flex-wrap">
<span className={`j13-anno-tag is-${a.tag_color}`}>{a.tag}</span>
{!a.published && (
<span
className="inline-flex items-center rounded-full px-2 py-px text-[10.5px] font-bold leading-[1.55]"
style={{ background: "var(--gold-soft)", color: "var(--gold)" }}
>
草稿
</span>
)}
<span className="meta text-[11px] tabular-nums">{formatDate(a.created_at)}</span>
</div>
<p
className="mt-1 truncate text-[14px] font-semibold"
style={{ color: "var(--ink)" }}
title={a.title}
>
{a.title}
</p>
</div>
<div className="flex items-center gap-1 shrink-0">
{a.published && (
<Link
href={`/announcement/${a.id}`}
target="_blank"
className="w-8 h-8 inline-flex items-center justify-center rounded-full transition-colors hover:bg-[var(--panel-2)]"
style={{ color: "var(--ink-3)" }}
title="查看"
aria-label="查看公告"
>
<ExternalLink size={15} />
</Link>
)}
<button
onClick={() => startEdit(a)}
className="w-8 h-8 inline-flex items-center justify-center rounded-full transition-colors hover:bg-[var(--panel-2)]"
style={{ color: "var(--ink-3)" }}
title="编辑"
aria-label="编辑公告"
>
<Pencil size={15} />
</button>
<button
onClick={() => remove(a)}
disabled={deletingId === a.id}
className="w-8 h-8 inline-flex items-center justify-center rounded-full transition-colors hover:bg-[var(--danger-soft)] disabled:opacity-50"
style={{ color: "var(--ink-3)" }}
onMouseEnter={(e) => (e.currentTarget.style.color = "var(--danger)")}
onMouseLeave={(e) => (e.currentTarget.style.color = "var(--ink-3)")}
title="删除"
aria-label="删除公告"
>
{deletingId === a.id ? <Loader2 size={15} className="animate-spin" /> : <Trash2 size={15} />}
</button>
</div>
</div>
))
)}
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,41 @@
import type { Metadata } from "next";
import Link from "next/link";
import { cookies } from "next/headers";
import { ShieldAlert } from "lucide-react";
import { authCookieHeader } from "@/lib/cookies";
import { getMeCached } from "@/lib/serverData";
import AnnouncementAdmin from "./AnnouncementAdmin";
export const metadata: Metadata = {
title: "站点公告管理",
robots: { index: false, follow: false },
};
// 权限以 Go 端 RequireAdmin 为唯一判定;这里仅决定管理界面是否直出,
// 非管理员访问时 SSR 直接给出无权限提示(所有写接口仍由后端 403 兜底)。
export default async function AdminAnnouncementsPage() {
const cookie = authCookieHeader(await cookies());
const me = await getMeCached(cookie || undefined);
if (me.user?.role !== "admin") {
return (
<div className="max-w-md mx-auto panel p-8 text-center mt-10">
<span
className="inline-flex w-14 h-14 rounded-full items-center justify-center mb-4"
style={{ background: "var(--gold-soft)", color: "var(--gold)" }}
>
<ShieldAlert size={26} />
</span>
<h1 className="text-lg font-extrabold" style={{ color: "var(--ink)" }}>
需要管理员权限
</h1>
<p className="meta mt-2 text-[13px]">仅站点管理员可以发布和管理站点公告。</p>
<Link href="/" className="btn btn-primary mt-6">
返回首页
</Link>
</div>
);
}
return <AnnouncementAdmin />;
}

View File

@@ -0,0 +1,99 @@
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import ReactMarkdown from "react-markdown";
import { ChevronRight, Megaphone } from "lucide-react";
import { fetchAnnouncementDetail } from "@/lib/api";
import { formatDate } from "@/lib/format";
interface PageProps {
params: Promise<{ id: string }>;
}
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
const { id } = await params;
const data = await fetchAnnouncementDetail(id).catch(() => null);
if (!data) return { title: "公告不存在" };
return {
title: data.announcement.title,
description: `站点公告 · ${data.announcement.tag}`,
openGraph: {
title: data.announcement.title,
description: `站点公告 · ${data.announcement.tag}`,
type: "article",
publishedTime: data.announcement.created_at,
},
};
}
export default async function AnnouncementPage({ params }: PageProps) {
const { id } = await params;
const data = await fetchAnnouncementDetail(id).catch(() => null);
if (!data) notFound();
const a = data.announcement;
const jsonLd = {
"@context": "https://schema.org",
"@type": "Article",
headline: a.title,
datePublished: a.created_at,
dateModified: a.updated_at,
articleSection: "站点公告",
keywords: a.tag,
};
return (
<div className="max-w-3xl mx-auto">
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
{/* 面包屑 */}
<nav className="meta mb-5 flex items-center gap-1.5 text-[13px]">
<Link href="/" className="hover:text-[var(--accent)] transition-colors">
首页
</Link>
<ChevronRight size={13} />
<span style={{ color: "var(--accent)" }}>站点公告</span>
</nav>
<article className="panel p-6 sm:p-8">
<div className="flex items-center justify-between gap-3 flex-wrap">
<span className={`j13-anno-tag is-${a.tag_color}`}>{a.tag}</span>
<time className="meta text-[12px] tabular-nums" dateTime={a.created_at}>
{formatDate(a.created_at)}
</time>
</div>
<h1
className="mt-3.5 text-[24px] sm:text-[28px] font-extrabold leading-snug tracking-tight"
style={{ color: "var(--ink)" }}
>
{a.title}
</h1>
<div
className="mt-5 pt-5"
style={{ borderTop: "1px solid var(--line)" }}
>
<div className="prose-content">
<ReactMarkdown>{a.content}</ReactMarkdown>
</div>
</div>
</article>
<div className="mt-5 flex items-center gap-2 text-[12.5px] meta">
<Megaphone size={14} style={{ color: "var(--accent)" }} />
<span>由站点管理团队发布</span>
<Link
href="/"
className="ml-auto font-semibold transition-colors hover:text-[var(--accent)]"
style={{ color: "var(--accent)" }}
>
返回首页
</Link>
</div>
</div>
);
}

View File

@@ -378,6 +378,80 @@ h1, h2, h3, h4 {
white-space: nowrap;
}
/* 帖子列表中的板块小标签:全站统一浅灰配色,避免每行多色眩目 */
.j13-board-tag {
display: inline-flex;
align-items: center;
padding: 0 7px;
border-radius: 6px;
font-size: 11px;
font-weight: 600;
line-height: 1.65;
background: var(--tint);
color: var(--ink-2);
white-space: nowrap;
transition: background 0.15s ease, color 0.15s ease;
}
.j13-board-tag:hover {
background: var(--accent-soft);
color: var(--accent);
}
/* 站点公告标签:预设色板(浅/暗成对,文字与底色均满足 AA 对比度) */
.j13-anno-tag {
display: inline-flex;
align-items: center;
max-width: 132px;
padding: 2px 10px;
border-radius: 999px;
font-size: 11px;
font-weight: 700;
line-height: 1.55;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.j13-anno-tag.is-blue { background: rgba(52, 81, 200, 0.12); color: #3451c8; }
.j13-anno-tag.is-green { background: rgba(19, 115, 51, 0.12); color: #137333; }
.j13-anno-tag.is-orange { background: rgba(165, 66, 10, 0.12); color: #a5420a; }
.j13-anno-tag.is-red { background: rgba(200, 40, 30, 0.1); color: #c8281e; }
.j13-anno-tag.is-purple { background: rgba(109, 71, 192, 0.12); color: #6d47c0; }
.j13-anno-tag.is-gray { background: rgba(82, 96, 122, 0.13); color: #52607a; }
.dark .j13-anno-tag.is-blue { background: rgba(169, 184, 255, 0.18); color: #a9b8ff; }
.dark .j13-anno-tag.is-green { background: rgba(88, 209, 138, 0.16); color: #58d18a; }
.dark .j13-anno-tag.is-orange { background: rgba(240, 135, 90, 0.17); color: #f0875a; }
.dark .j13-anno-tag.is-red { background: rgba(255, 107, 96, 0.16); color: #ff6b60; }
.dark .j13-anno-tag.is-purple { background: rgba(192, 168, 245, 0.18); color: #c0a8f5; }
.dark .j13-anno-tag.is-gray { background: rgba(170, 182, 207, 0.17); color: #aab6cf; }
/* 后台颜色选择器圆点 */
.j13-anno-dot {
width: 22px;
height: 22px;
border-radius: 999px;
border: 2px solid transparent;
cursor: pointer;
padding: 0;
transition: transform 0.12s ease, box-shadow 0.12s ease;
}
.j13-anno-dot:hover { transform: scale(1.12); }
.j13-anno-dot[aria-pressed="true"] {
border-color: var(--panel);
box-shadow: 0 0 0 2px var(--accent);
}
.j13-anno-dot.is-blue { background: #3451c8; }
.j13-anno-dot.is-green { background: #137333; }
.j13-anno-dot.is-orange { background: #a5420a; }
.j13-anno-dot.is-red { background: #c8281e; }
.j13-anno-dot.is-purple { background: #6d47c0; }
.j13-anno-dot.is-gray { background: #52607a; }
.dark .j13-anno-dot.is-blue { background: #a9b8ff; }
.dark .j13-anno-dot.is-green { background: #58d18a; }
.dark .j13-anno-dot.is-orange { background: #f0875a; }
.dark .j13-anno-dot.is-red { background: #ff6b60; }
.dark .j13-anno-dot.is-purple { background: #c0a8f5; }
.dark .j13-anno-dot.is-gray { background: #aab6cf; }
/* ----- 分页 ----- */
.pager-btn {
background: var(--panel);
@@ -688,6 +762,147 @@ h1, h2, h3, h4 {
.prose-content hr { border: none; border-top: 1px solid var(--line); margin: 2.2rem 0; }
.prose-content strong { font-weight: 700; }
/* 评论区的 Markdown 紧凑排版:继承 prose-content 全部规则,仅收紧行距与间距 */
.prose-comment { font-size: 14.5px; line-height: 1.7; }
.prose-comment p { margin: 0.35rem 0; }
.prose-comment blockquote { margin: 0.5rem 0; padding: 0.45rem 0.9rem; }
.prose-comment pre { margin: 0.6rem 0; }
.prose-comment h1, .prose-comment h2, .prose-comment h3, .prose-comment h4 {
font-size: 1em;
margin: 0.6rem 0 0.3rem;
border-bottom: none;
font-weight: 700;
}
/* 移动端浮动操作条内的点赞按钮:放大到 44px 触控标准 */
.j13-bar-like .j13-like {
height: 44px;
padding: 0 14px;
font-size: 13px;
}
/* 评论楼层树:抖音风格
主评论全宽;子回复折叠在 panel-2 背景容器内,点击"展开 X 条回复"显示
子回复之间用淡分隔线;depth≥2 时昵称后显示 ▶ 被回复者 */
/* 子回复行:紧凑布局,头像 28px */
.cmt-reply-row {
padding: 8px 0;
border-top: 1px solid var(--line);
}
.cmt-reply-row:first-child {
border-top: none;
padding-top: 0;
}
/* 子回复昵称 */
.cmt-reply-name {
font-size: 13px;
font-weight: 600;
color: var(--ink-2);
}
/* 楼层号标签(主评论昵称旁) */
.cmt-floor-label {
font-size: 11.5px;
font-weight: 600;
color: var(--ink-3);
text-decoration: none;
padding: 1px 6px;
border-radius: 6px;
background: var(--tint);
transition: color 0.15s;
}
.cmt-floor-label:hover {
color: var(--accent);
}
/* 回复文字按钮:放在时间右侧,抖音风格 */
.cmt-reply-btn {
font-size: 12px;
font-weight: 500;
color: var(--ink-3);
background: none;
border: none;
padding: 0;
cursor: pointer;
}
.cmt-reply-btn:hover {
color: var(--accent);
}
/* 右三角箭头(回复子评论时) */
.cmt-reply-arrow {
color: var(--ink-3);
flex-shrink: 0;
}
/* 被回复者名称(可点击跳转) */
.cmt-reply-target {
font-size: 13px;
font-weight: 600;
color: var(--ink-2);
text-decoration: none;
white-space: nowrap;
}
.cmt-reply-target:hover {
color: var(--accent);
}
/* 子回复容器:背景与主评论区分,圆角 */
.cmt-replies-wrap {
margin-top: 8px;
padding: 4px 12px;
background: var(--panel-2);
border-radius: 12px;
}
/* 孙评论及更深:小幅缩进 + 细引导线 */
.cmt-children {
margin-top: 2px;
padding-left: 10px;
border-left: 1px solid var(--line);
}
/* 展开/收起按钮 */
.cmt-fold-btn {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 12.5px;
font-weight: 600;
color: var(--accent);
padding: 4px 10px;
border-radius: 99px;
background: var(--accent-soft);
border: none;
cursor: pointer;
transition: background 0.15s;
}
.cmt-fold-btn:hover {
background: color-mix(in srgb, var(--accent) 18%, transparent);
}
/* 评论内联回复表单:出现在目标评论正下方 */
.cmt-reply-form {
padding: 12px 14px;
border-radius: 14px;
background: var(--panel-2);
margin-top: 8px;
}
.cmt-reply-form .field {
font-size: 13.5px;
}
@media (max-width: 640px) {
.cmt-replies-wrap {
padding: 4px 8px;
}
.cmt-children {
padding-left: 8px;
}
}
@media (prefers-reduced-motion: reduce) {
* { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; }
}

View File

@@ -5,8 +5,8 @@ import "./globals.css";
import Header from "@/components/Header";
import Footer from "@/components/Footer";
import Toaster from "@/components/Toaster";
import type { User } from "@/lib/api";
import { getMeCached } from "@/lib/serverData";
import type { User, Board } from "@/lib/api";
import { getMeCached, getBoardsCached } from "@/lib/serverData";
import { TOKEN_COOKIE, REFRESH_COOKIE, authCookieHeader } from "@/lib/cookies";
// 构建期下载并自托管字体:同源加载 + 自动 preload + fallback 度量校正,
@@ -69,6 +69,9 @@ export default async function RootLayout({
unread = me.unread_count;
}
// 全站板块导航(Header 桌面下拉 + 移动抽屉共用)
const boards: Board[] = await getBoardsCached();
return (
<html
lang="zh-CN"
@@ -78,7 +81,7 @@ export default async function RootLayout({
<a href="#main" className="skip-link">
跳到主要内容
</a>
<Header initialUser={user} initialUnread={unread} initialTheme={theme} />
<Header initialUser={user} initialUnread={unread} initialTheme={theme} boards={boards} />
<main
id="main"
tabIndex={-1}

View File

@@ -57,12 +57,14 @@ export default function LoginPage() {
return (
<div className="max-w-md mx-auto pt-8 sm:pt-14">
<div className="mb-7 text-center">
<span
className="inline-flex w-14 h-14 rounded-2xl items-center justify-center mb-4"
<Link
href="/"
aria-label="返回首页"
className="inline-flex w-14 h-14 rounded-2xl items-center justify-center mb-4 transition-transform duration-300 hover:rotate-[-6deg]"
style={{ background: "var(--accent-soft)", color: "var(--accent)" }}
>
<MessagesSquare size={26} />
</span>
</Link>
<h1 className="text-[28px] font-extrabold tracking-tight" style={{ color: "var(--ink)" }}>
欢迎回来
</h1>
@@ -72,28 +74,32 @@ export default function LoginPage() {
</div>
<form onSubmit={handleSubmit} className="panel p-6 sm:p-7 space-y-4">
{error && <div className="alert-error">{error}</div>}
{error && <div className="alert-error" role="alert">{error}</div>}
<div>
<label className="field-label">用户名</label>
<label className="field-label" htmlFor="login-username">用户名</label>
<input
id="login-username"
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
autoFocus
autoComplete="username"
className="field"
placeholder="testuser"
placeholder="你的用户名"
/>
</div>
<div>
<label className="field-label">密码</label>
<label className="field-label" htmlFor="login-password">密码</label>
<input
id="login-password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
autoComplete="current-password"
className="field"
placeholder="••••••"
placeholder="输入密码"
/>
</div>
<button type="submit" disabled={loading} className="btn btn-primary w-full justify-center mt-2">

View File

@@ -0,0 +1,124 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Heart, MessageCircle, CheckCheck, Bell } from "lucide-react";
import { apiMarkRead, apiMarkAllRead, type NotificationsResponse, type NotificationItem } from "@/lib/api";
/**
* 通知列表交互层:数据由服务端 SSR 直出,这里只承担已读标记等客户端操作。
*/
export default function NotificationsClient({ initialData }: { initialData: NotificationsResponse }) {
const router = useRouter();
const [notifications, setNotifications] = useState<NotificationItem[]>(initialData.notifications || []);
const handleClick = async (n: NotificationItem) => {
if (!n.is_read) {
apiMarkRead(n.id).catch(() => {});
setNotifications((list) =>
list.map((item) => (item.id === n.id ? { ...item, is_read: true } : item))
);
}
router.push(`/post/${n.post_id}`);
};
const handleMarkAll = async () => {
await apiMarkAllRead();
setNotifications((list) => list.map((item) => ({ ...item, is_read: true })));
// 同步刷新 Header 未读红点(layout 重新取 unread_count)
router.refresh();
};
const formatTime = (dateStr: string) => {
const diff = Date.now() - new Date(dateStr).getTime();
const min = Math.floor(diff / 60000);
if (min < 1) return "刚刚";
if (min < 60) return `${min} 分钟前`;
const hour = Math.floor(min / 60);
if (hour < 24) return `${hour} 小时前`;
return `${Math.floor(hour / 24)} 天前`;
};
const hasUnread = notifications.some((n) => !n.is_read);
return (
<>
{hasUnread && (
<div className="flex justify-end mb-4">
<button onClick={handleMarkAll} className="btn btn-line btn-sm">
<CheckCheck size={14} /> 全部已读
</button>
</div>
)}
{notifications.length === 0 ? (
<div className="panel text-center py-20 px-6">
<span
className="inline-flex w-14 h-14 rounded-full items-center justify-center mb-4"
style={{ background: "var(--accent-soft)", color: "var(--accent)" }}
>
<Bell size={26} />
</span>
<p className="font-bold text-lg" style={{ color: "var(--ink)" }}>还没有通知</p>
<p className="meta mt-1.5">当有人评论或点赞你的帖子时,会在这里提醒你</p>
</div>
) : (
<div className="panel overflow-hidden p-0">
{notifications.map((n, i) => (
<button
key={n.id}
onClick={() => handleClick(n)}
className="w-full text-left px-4 sm:px-5 py-4 flex items-start gap-3.5 transition-colors hover:bg-[var(--panel-2)]"
style={{
borderTop: i === 0 ? "none" : "1px solid var(--line)",
background: n.is_read ? "transparent" : "var(--panel-2)",
}}
>
<span
className="w-10 h-10 shrink-0 rounded-full flex items-center justify-center"
style={{
color: n.type === "like" ? "var(--clay)" : "var(--accent)",
background:
n.type === "like" ? "var(--clay-soft)" : "var(--accent-soft)",
}}
>
{n.type === "like" ? <Heart size={16} /> : <MessageCircle size={16} />}
</span>
<div className="flex-1 min-w-0">
<p className="text-sm leading-snug" style={{ color: "var(--ink)" }}>
<Link
href={`/u/${n.actor.id}`}
onClick={(e) => e.stopPropagation()}
className="font-semibold hover:text-[var(--accent)] transition-colors"
>
{n.actor.nickname}
</Link>{" "}
<span className="meta">
{n.type === "comment"
? "评论了你的帖子"
: n.type === "reply"
? "回复了你的评论"
: "点赞了你的帖子"}
</span>
</p>
<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}
</p>
)}
<p className="meta text-xs mt-2">{formatTime(n.created_at)}</p>
</div>
{!n.is_read && (
<span className="w-2.5 h-2.5 shrink-0 mt-2 rounded-full" style={{ background: "var(--clay)" }} />
)}
</button>
))}
</div>
)}
</>
);
}

View File

@@ -1,62 +1,34 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { redirect } from "next/navigation";
import Link from "next/link";
import { Heart, MessageCircle, CheckCheck, Bell, ChevronRight } from "lucide-react";
import {
apiFetchNotifications,
apiMarkRead,
apiMarkAllRead,
type NotificationItem,
} from "@/lib/api";
import { cookies } from "next/headers";
import { ChevronRight } from "lucide-react";
import { authCookieHeader } from "@/lib/cookies";
import { getMeCached } from "@/lib/serverData";
import { fetchNotifications } from "@/lib/api";
import Pagination from "@/components/Pagination";
import NotificationsClient from "./NotificationsClient";
export default function NotificationsPage() {
const router = useRouter();
const [notifications, setNotifications] = useState<NotificationItem[]>([]);
const [loading, setLoading] = useState(true);
interface NotificationsPageProps {
searchParams: Promise<{ page?: string }>;
}
const load = async () => {
setLoading(true);
try {
const res = await apiFetchNotifications(1);
setNotifications(res.notifications || []);
} catch {
setNotifications([]);
}
setLoading(false);
};
// SSR 直出通知列表:F5 直接看到内容,不再先渲染"正在加载…"
export default async function NotificationsPage({ searchParams }: NotificationsPageProps) {
const sp = await searchParams;
const page = Math.max(1, parseInt(sp.page || "1", 10) || 1);
const cookie = authCookieHeader(await cookies());
const me = await getMeCached(cookie || undefined);
if (!me.user) {
redirect(`/login?redirect=${encodeURIComponent(`/notifications`)}`);
}
useEffect(() => {
load();
}, []);
const handleClick = async (n: NotificationItem) => {
if (!n.is_read) {
apiMarkRead(n.id).catch(() => {});
setNotifications((list) =>
list.map((item) => (item.id === n.id ? { ...item, is_read: true } : item))
);
}
router.push(`/post/${n.post_id}`);
};
const handleMarkAll = async () => {
await apiMarkAllRead();
setNotifications((list) => list.map((item) => ({ ...item, is_read: true })));
};
const formatTime = (dateStr: string) => {
const diff = Date.now() - new Date(dateStr).getTime();
const min = Math.floor(diff / 60000);
if (min < 1) return "刚刚";
if (min < 60) return `${min} 分钟前`;
const hour = Math.floor(min / 60);
if (hour < 24) return `${hour} 小时前`;
return `${Math.floor(hour / 24)} 天前`;
};
const hasUnread = notifications.some((n) => !n.is_read);
let data = null;
let loadError = false;
try {
data = await fetchNotifications(page, cookie);
} catch {
loadError = true;
}
return (
<div className="max-w-2xl mx-auto">
@@ -66,81 +38,26 @@ export default function NotificationsPage() {
<span style={{ color: "var(--accent)" }}>通知中心</span>
</nav>
<div className="flex items-end justify-between mb-6 gap-4">
<h1 className="text-[26px] sm:text-[30px] font-extrabold tracking-tight" style={{ color: "var(--ink)" }}>
通知中心
</h1>
{hasUnread && (
<button onClick={handleMarkAll} className="btn btn-line btn-sm">
<CheckCheck size={14} /> 全部已读
</button>
)}
</div>
<h1 className="text-[26px] sm:text-[30px] font-extrabold tracking-tight mb-6" style={{ color: "var(--ink)" }}>
通知中心
</h1>
{loading ? (
<div className="panel text-center py-16">
<p className="meta">正在加载通知…</p>
</div>
) : notifications.length === 0 ? (
<div className="panel text-center py-20 px-6">
<span
className="inline-flex w-14 h-14 rounded-full items-center justify-center mb-4"
style={{ background: "var(--accent-soft)", color: "var(--accent)" }}
>
<Bell size={26} />
</span>
<p className="font-bold text-lg" style={{ color: "var(--ink)" }}>还没有通知</p>
<p className="meta mt-1.5">当有人评论或点赞你的帖子时,会在这里提醒你</p>
{loadError || !data ? (
<div className="panel text-center py-16 px-6" role="alert">
<p className="text-sm font-semibold" style={{ color: "var(--ink-2)" }}>通知加载失败</p>
<p className="meta mt-1.5 mb-4">网络异常,请稍后重试</p>
<Link href="/notifications" className="btn btn-line btn-sm">重新加载</Link>
</div>
) : (
<div className="panel overflow-hidden p-0">
{notifications.map((n, i) => (
<button
key={n.id}
onClick={() => handleClick(n)}
className="w-full text-left px-4 sm:px-5 py-4 flex items-start gap-3.5 transition-colors hover:bg-[var(--panel-2)]"
style={{
borderTop: i === 0 ? "none" : "1px solid var(--line)",
background: n.is_read ? "transparent" : "var(--panel-2)",
}}
>
<span
className="w-10 h-10 shrink-0 rounded-full flex items-center justify-center"
style={{
color: n.type === "like" ? "var(--clay)" : "var(--accent)",
background:
n.type === "like" ? "var(--clay-soft)" : "var(--accent-soft)",
}}
>
{n.type === "like" ? <Heart size={16} /> : <MessageCircle size={16} />}
</span>
<div className="flex-1 min-w-0">
<p className="text-sm leading-snug" style={{ color: "var(--ink)" }}>
<Link
href={`/u/${n.actor.id}`}
onClick={(e) => e.stopPropagation()}
className="font-semibold hover:text-[var(--accent)] transition-colors"
>
{n.actor.nickname}
</Link>{" "}
<span className="meta">{n.type === "comment" ? "评论了你的帖子" : "点赞了你的帖子"}</span>
</p>
<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}
</p>
)}
<p className="meta text-xs mt-2">{formatTime(n.created_at)}</p>
</div>
{!n.is_read && (
<span className="w-2.5 h-2.5 shrink-0 mt-2 rounded-full" style={{ background: "var(--clay)" }} />
)}
</button>
))}
</div>
<>
<NotificationsClient initialData={data} />
<Pagination
total={data.total}
page={data.page}
size={data.size}
basePath="/notifications"
/>
</>
)}
</div>
);

View File

@@ -190,7 +190,7 @@ export default async function HomePage({ searchParams }: HomePageProps) {
stats={overview.stats}
hot={overview.hot}
activeUsers={overview.active_users}
latestComments={overview.latest_comments}
announcements={overview.announcements}
newUsers={overview.new_users}
checkin={overview.checkin ?? undefined}
/>
@@ -203,7 +203,7 @@ export default async function HomePage({ searchParams }: HomePageProps) {
<CommunityPanelsMobile
hot={overview.hot}
activeUsers={overview.active_users}
latestComments={overview.latest_comments}
announcements={overview.announcements}
newUsers={overview.new_users}
checkin={overview.checkin ?? undefined}
/>

View File

@@ -23,16 +23,20 @@ import {
type Board,
} from "@/lib/api";
import { authCookieHeader } from "@/lib/cookies";
import { getMeCached } from "@/lib/serverData";
import CommentSection from "@/components/CommentSection";
import PostActions from "@/components/PostActions";
import LikeButton from "@/components/LikeButton";
import ReadingProgress from "@/components/ReadingProgress";
import PostToc, { type TocItem } from "@/components/PostToc";
import MobilePostBar from "@/components/MobilePostBar";
import Avatar from "@/components/Avatar";
import { IconComment, IconEye } from "@/components/Icons";
interface PageProps {
params: Promise<{ id: string }>;
// page 同时用于评论分页(?page=N),帖子正文本身不分页
searchParams: Promise<{ page?: string }>;
}
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
@@ -313,14 +317,17 @@ function AuthorCardStacked({ profile }: { profile: UserProfile }) {
);
}
export default async function PostDetailPage({ params }: PageProps) {
export default async function PostDetailPage({ params, searchParams }: PageProps) {
const { id } = await params;
const sp = await searchParams;
const commentPage = Math.max(1, parseInt(sp.page || "1", 10) || 1);
const cookie = authCookieHeader(await cookies());
const { post } = await fetchPostDetail(id, cookie);
// 评论 / 作者资料 / 同板块热议并行拉取;侧栏数据失败一律静默降级,不阻塞正文
const [commentsData, profile, relatedData] = await Promise.all([
fetchComments(id),
// 评论 / 当前用户 / 作者资料 / 同板块热议并行拉取;侧栏数据失败一律静默降级,不阻塞正文
const [commentsData, me, profile, relatedData] = await Promise.all([
fetchComments(id, commentPage),
getMeCached(cookie || undefined),
fetchUserProfile(String(post.user.id), 1, cookie).catch(() => null),
fetchPosts(1, 8, post.board_id, "hot", "", false, cookie).catch(() => null),
]);
@@ -369,6 +376,8 @@ export default async function PostDetailPage({ params }: PageProps) {
<>
<ReadingProgress />
<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} />
{/* 移动端浮动操作条:长文阅读中途可点赞 / 跳评论 / 回顶部 */}
<MobilePostBar postId={id} liked={post.liked} likeCount={post.like_count} />
{/* 三栏阅读布局:xl = 左导航240 + 正文 + 右辅助280;lg = 正文 + 右辅助260;以下单栏 */}
<div className="grid grid-cols-1 items-start lg:grid-cols-[minmax(0,1fr)_260px] xl:grid-cols-[240px_minmax(0,1fr)_280px] gap-x-6 xl:gap-x-7">
@@ -487,7 +496,15 @@ export default async function PostDetailPage({ params }: PageProps) {
</div>
)}
<CommentSection postId={id} comments={comments} />
<CommentSection
postId={id}
comments={comments}
total={commentsData.total}
totalComments={commentsData.total_comments}
page={commentsData.page}
size={commentsData.size}
user={me.user}
/>
{/* 窄屏相关讨论(lg 起由右栏承载) */}
<div className="lg:hidden mt-6">
@@ -505,6 +522,9 @@ export default async function PostDetailPage({ params }: PageProps) {
<RelatedPosts posts={related} boardId={post.board_id} />
</aside>
</div>
{/* 给移动端浮动操作条让位,避免遮住页尾内容 */}
<div className="lg:hidden h-16" aria-hidden />
</>
);
}

View File

@@ -31,7 +31,12 @@ export default function RegisterPage() {
setLoading(true);
try {
const res = await apiRegister(username, email, password);
if (res.id) {
if (res.user) {
// 后端注册即签发登录态 cookie:直接进入社区,无需再手动登录
router.push("/");
router.refresh();
} else if (res.id) {
// 极端情况:注册成功但自动签发失败,引导去登录
router.push("/login");
} else {
setError(res.error || "注册失败");
@@ -59,10 +64,11 @@ export default function RegisterPage() {
</div>
<form onSubmit={handleSubmit} className="panel p-6 sm:p-7 space-y-4">
{error && <div className="alert-error">{error}</div>}
{error && <div className="alert-error" role="alert">{error}</div>}
<div>
<label className="field-label">用户名</label>
<label className="field-label" htmlFor="reg-username">用户名</label>
<input
id="reg-username"
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
@@ -70,28 +76,33 @@ export default function RegisterPage() {
minLength={3}
maxLength={32}
autoFocus
autoComplete="username"
className="field"
placeholder="3–32 位"
/>
</div>
<div>
<label className="field-label">邮箱(可选)</label>
<label className="field-label" htmlFor="reg-email">邮箱(可选)</label>
<input
id="reg-email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
autoComplete="email"
className="field"
placeholder="you@example.com"
/>
</div>
<div>
<label className="field-label">密码</label>
<label className="field-label" htmlFor="reg-password">密码</label>
<input
id="reg-password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
minLength={6}
autoComplete="new-password"
className="field"
placeholder="至少 6 位"
/>

View File

@@ -0,0 +1,106 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { apiChangePassword } from "@/lib/api";
/**
* 修改密码表单:提交成功后后端已递增 TokenVersion 并清除全部登录 cookie,
* 刷新 layout 使 Header 回到游客态,随后跳转登录页重新登录。
*/
export default function PasswordForm() {
const router = useRouter();
const [oldPassword, setOldPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState("");
const [success, setSuccess] = useState(false);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError("");
if (newPassword.length < 6) {
setError("新密码至少 6 位");
return;
}
if (newPassword !== confirmPassword) {
setError("两次输入的新密码不一致");
return;
}
setSubmitting(true);
try {
const res = await apiChangePassword(oldPassword, newPassword);
if (res.message) {
setSuccess(true);
// 后端已使全部 token 失效并清 cookie,刷新 layout 让 Header 回到游客态
router.refresh();
setTimeout(() => router.push("/login"), 1500);
} else {
setError(res.error || "修改失败");
}
} catch {
setError("网络错误,请重试");
} finally {
setSubmitting(false);
}
};
return (
<>
<p className="font-bold text-[15px] mb-3.5" style={{ color: "var(--ink)" }}>修改密码</p>
<form onSubmit={handleSubmit} className="panel p-5 sm:p-6 space-y-4">
{success && <div className="alert-ok" role="status">密码修改成功,正在跳转登录页...</div>}
{error && <div className="alert-error" role="alert">{error}</div>}
<div>
<label className="field-label" htmlFor="pwd-old">当前密码</label>
<input
id="pwd-old"
type="password"
value={oldPassword}
onChange={(e) => setOldPassword(e.target.value)}
required
autoComplete="current-password"
className="field"
/>
</div>
<div>
<label className="field-label" htmlFor="pwd-new">新密码(至少 6 位)</label>
<input
id="pwd-new"
type="password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
required
minLength={6}
autoComplete="new-password"
className="field"
/>
</div>
<div>
<label className="field-label" htmlFor="pwd-confirm">确认新密码</label>
<input
id="pwd-confirm"
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
required
minLength={6}
autoComplete="new-password"
className="field"
/>
</div>
<button
type="submit"
disabled={submitting || success}
className="btn btn-primary w-full justify-center mt-2"
>
{submitting ? "提交中..." : "修改密码"}
</button>
</form>
</>
);
}

View File

@@ -1,71 +1,19 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { redirect } from "next/navigation";
import Link from "next/link";
import { cookies } from "next/headers";
import { ChevronRight } from "lucide-react";
import { apiChangePassword, apiMe, type User } from "@/lib/api";
import { authCookieHeader } from "@/lib/cookies";
import { getMeCached } from "@/lib/serverData";
import Avatar from "@/components/Avatar";
import PasswordForm from "./PasswordForm";
export default function SettingsPage() {
const router = useRouter();
const [user, setUser] = useState<User | null>(null);
const [oldPassword, setOldPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState("");
const [success, setSuccess] = useState(false);
useEffect(() => {
apiMe()
.then((res) => {
if (!res.user) {
router.push("/login");
return;
}
setUser(res.user);
})
.catch(() => router.push("/login"));
}, [router]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError("");
if (newPassword.length < 6) {
setError("新密码至少 6 位");
return;
}
if (newPassword !== confirmPassword) {
setError("两次输入的新密码不一致");
return;
}
setSubmitting(true);
try {
const res = await apiChangePassword(oldPassword, newPassword);
if (res.message) {
setSuccess(true);
// 后端已使全部 token 失效并清 cookie,刷新 layout 让 Header 回到游客态
router.refresh();
setTimeout(() => router.push("/login"), 1500);
} else {
setError(res.error || "修改失败");
}
} catch (e) {
setError("网络错误,请重试");
} finally {
setSubmitting(false);
}
};
// SSR 直出账号信息:未登录直接跳登录页,登录后 F5 不再有"正在加载…"闪动
export default async function SettingsPage() {
const cookie = authCookieHeader(await cookies());
const me = await getMeCached(cookie || undefined);
const user = me.user;
if (!user) {
return (
<div className="max-w-md mx-auto text-center py-20">
<p className="meta">正在加载…</p>
</div>
);
redirect(`/login?redirect=${encodeURIComponent(`/settings`)}`);
}
return (
@@ -92,51 +40,7 @@ export default function SettingsPage() {
</div>
</div>
<p className="font-bold text-[15px] mb-3.5" style={{ color: "var(--ink)" }}>修改密码</p>
<form onSubmit={handleSubmit} className="panel p-5 sm:p-6 space-y-4">
{success && <div className="alert-ok">密码修改成功,正在跳转登录页...</div>}
{error && <div className="alert-error">{error}</div>}
<div>
<label className="field-label">当前密码</label>
<input
type="password"
value={oldPassword}
onChange={(e) => setOldPassword(e.target.value)}
required
className="field"
/>
</div>
<div>
<label className="field-label">新密码(至少 6 位)</label>
<input
type="password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
required
minLength={6}
className="field"
/>
</div>
<div>
<label className="field-label">确认新密码</label>
<input
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
required
minLength={6}
className="field"
/>
</div>
<button
type="submit"
disabled={submitting || success}
className="btn btn-primary w-full justify-center mt-2"
>
{submitting ? "提交中..." : "修改密码"}
</button>
</form>
<PasswordForm />
</div>
);
}

View File

@@ -1,180 +0,0 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import { FileText, MessageCircle } from "lucide-react";
import { fetchUserComments, type UserProfile, type UserCommentsResponse } from "@/lib/api";
import Pagination from "@/components/Pagination";
import { IconComment, IconEye, IconHeart } from "@/components/Icons";
interface UserProfileClientProps {
userId: string;
initialPosts: UserProfile;
initialPage: number;
}
type Tab = "posts" | "comments";
export default function UserProfileClient({ userId, initialPosts, initialPage }: UserProfileClientProps) {
const [tab, setTab] = useState<Tab>("posts");
const [commentData, setCommentData] = useState<UserCommentsResponse | null>(null);
const [commentLoading, setCommentLoading] = useState(false);
const [commentPage, setCommentPage] = useState(1);
const loadComments = async (page: number) => {
setCommentLoading(true);
try {
const data = await fetchUserComments(userId, page);
setCommentData({ ...data, comments: data.comments || [] });
setCommentPage(page);
} catch {
setCommentData({ comments: [], total: 0, page, size: 20 });
}
setCommentLoading(false);
};
const handleTabChange = (t: Tab) => {
setTab(t);
if (t === "comments" && commentData === null) {
loadComments(1);
}
};
const tabBtn = (t: Tab, label: string, count: number, icon: React.ReactNode) => {
const active = tab === t;
return (
<button
onClick={() => handleTabChange(t)}
className="flex-1 sm:flex-none inline-flex items-center justify-center gap-1.5 px-4 py-2 rounded-full text-sm font-semibold transition-all"
style={{
background: active ? "var(--panel)" : "transparent",
color: active ? "var(--accent)" : "var(--ink-3)",
boxShadow: active ? "var(--shadow-sm)" : "none",
}}
>
{icon}
{label}
<span
className="text-[11px] font-bold px-1.5 py-px rounded-full"
style={{
background: active ? "var(--accent-soft)" : "var(--tint)",
color: active ? "var(--accent)" : "var(--ink-3)",
}}
>
{count}
</span>
</button>
);
};
return (
<div>
<div
className="inline-flex w-full sm:w-auto items-center gap-1 mb-6 p-1 rounded-full"
style={{ background: "var(--panel-2)" }}
>
{tabBtn("posts", "发帖", initialPosts.stats.post_count, <FileText size={15} />)}
{tabBtn("comments", "评论", initialPosts.stats.comment_count, <MessageCircle size={15} />)}
</div>
{tab === "posts" ? (
<div>
{initialPosts.posts.length > 0 ? (
<div className="panel overflow-hidden p-0">
{initialPosts.posts.map((post, i) => (
<Link
key={post.id}
href={`/post/${post.id}`}
className="block px-4 sm:px-5 py-4 transition-colors hover:bg-[var(--panel-2)]"
style={{ borderTop: i === 0 ? "none" : "1px solid var(--line)" }}
>
<div className="flex items-center gap-2 mb-2 flex-wrap">
<span className="chip">{post.board.name}</span>
{post.pinned > 0 && <span className="badge-pin">置顶</span>}
{post.recommended && <span className="badge-rec">推荐</span>}
</div>
<h2
className="font-semibold mb-2 leading-snug group-hover:text-[var(--accent)]"
style={{ color: "var(--ink)" }}
>
{post.title}
</h2>
<div className="flex items-center gap-4 meta text-[12px]">
<span>{new Date(post.created_at).toLocaleDateString("zh-CN")}</span>
<span className="inline-flex items-center gap-1">
<IconComment size={12} /> {post.comment_count}
</span>
<span className="inline-flex items-center gap-1">
<IconEye size={12} /> {post.view_count}
</span>
<span className="inline-flex items-center gap-1">
<IconHeart size={12} /> {post.like_count}
</span>
</div>
</Link>
))}
</div>
) : (
<div className="panel text-center py-16 px-6">
<FileText size={26} className="mx-auto mb-3" style={{ color: "var(--ink-3)" }} />
<p className="text-sm font-semibold" style={{ color: "var(--ink-2)" }}>暂无发帖</p>
</div>
)}
<Pagination
total={initialPosts.posts_total}
page={initialPage}
size={20}
basePath={`/u/${userId}`}
/>
</div>
) : (
<div>
{commentLoading ? (
<div className="panel text-center py-16">
<p className="meta">正在加载评论…</p>
</div>
) : commentData && commentData.comments.length > 0 ? (
<>
<div className="panel overflow-hidden p-0">
{commentData.comments.map((c, i) => (
<Link
key={c.id}
href={`/post/${c.post_id}`}
className="block px-4 sm:px-5 py-4 transition-colors hover:bg-[var(--panel-2)]"
style={{ borderTop: i === 0 ? "none" : "1px solid var(--line)" }}
>
<div className="meta text-xs mb-2">
评论于《<span style={{ color: "var(--accent)" }}>{c.post_title}</span>》
</div>
<p
className="text-[15px] leading-relaxed line-clamp-2"
style={{ color: "var(--ink)" }}
>
{c.content}
</p>
<div className="meta text-xs mt-2">
{new Date(c.created_at).toLocaleString("zh-CN")}
</div>
</Link>
))}
</div>
<Pagination
total={commentData.total}
page={commentPage}
size={20}
basePath={`/u/${userId}`}
query={{ tab: "comments" }}
onChange={loadComments}
/>
</>
) : (
<div className="panel text-center py-16 px-6">
<MessageCircle size={26} className="mx-auto mb-3" style={{ color: "var(--ink-3)" }} />
<p className="text-sm font-semibold" style={{ color: "var(--ink-2)" }}>暂无评论</p>
</div>
)}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,165 @@
import Link from "next/link";
import { FileText, MessageCircle, AlertCircle } from "lucide-react";
import Pagination from "@/components/Pagination";
import { IconComment, IconEye, IconHeart } from "@/components/Icons";
import type { UserProfile, UserCommentsResponse } from "@/lib/api";
/**
* 用户主页内容区(纯服务端渲染):
* tab 与分页全部走 URL(?tab=comments&page=N),刷新/后退/分享链接均保持一致。
*/
export default function UserProfileContent({
userId,
profile,
tab,
commentData,
commentError,
page,
}: {
userId: string;
profile: UserProfile;
tab: "posts" | "comments";
commentData: UserCommentsResponse | null;
commentError: boolean;
page: number;
}) {
const tabLink = (t: "posts" | "comments", label: string, count: number, icon: React.ReactNode) => {
const active = tab === t;
const href = t === "posts" ? `/u/${userId}` : `/u/${userId}?tab=comments`;
return (
<Link
href={href}
aria-current={active ? "page" : undefined}
className={`inline-flex items-center justify-center gap-1.5 px-4 py-2 rounded-full text-sm font-semibold transition-all flex-1 sm:flex-none ${
active ? "" : "hover:text-[var(--ink)]"
}`}
style={{
background: active ? "var(--panel)" : "transparent",
color: active ? "var(--accent)" : "var(--ink-3)",
boxShadow: active ? "var(--shadow-sm)" : "none",
}}
>
{icon}
{label}
<span
className="text-[11px] font-bold px-1.5 py-px rounded-full tabular-nums"
style={{
background: active ? "var(--accent-soft)" : "var(--tint)",
color: active ? "var(--accent)" : "var(--ink-3)",
}}
>
{count}
</span>
</Link>
);
};
return (
<div>
<div
className="inline-flex w-full sm:w-auto items-center gap-1 mb-6 p-1 rounded-full"
style={{ background: "var(--panel-2)" }}
>
{tabLink("posts", "发帖", profile.stats.post_count, <FileText size={15} />)}
{tabLink("comments", "评论", profile.stats.comment_count, <MessageCircle size={15} />)}
</div>
{tab === "posts" ? (
<div>
{profile.posts.length > 0 ? (
<div className="panel overflow-hidden p-0">
{profile.posts.map((post, i) => (
<Link
key={post.id}
href={`/post/${post.id}`}
className="group block px-4 sm:px-5 py-4 transition-colors hover:bg-[var(--panel-2)]"
style={{ borderTop: i === 0 ? "none" : "1px solid var(--line)" }}
>
<div className="flex items-center gap-2 mb-2 flex-wrap">
<span className="j13-board-tag">{post.board.name}</span>
{post.pinned > 0 && <span className="badge-pin">置顶</span>}
{post.recommended && <span className="badge-rec">推荐</span>}
</div>
<h2
className="font-semibold mb-2 leading-snug transition-colors group-hover:text-[var(--accent)]"
style={{ color: "var(--ink)" }}
>
{post.title}
</h2>
<div className="flex items-center gap-4 meta text-[12px]">
<span className="tabular-nums">{new Date(post.created_at).toLocaleDateString("zh-CN")}</span>
<span className="inline-flex items-center gap-1">
<IconComment size={12} /> {post.comment_count}
</span>
<span className="inline-flex items-center gap-1">
<IconEye size={12} /> {post.view_count}
</span>
<span className="inline-flex items-center gap-1">
<IconHeart size={12} /> {post.like_count}
</span>
</div>
</Link>
))}
</div>
) : (
<div className="panel text-center py-16 px-6">
<FileText size={26} className="mx-auto mb-3" style={{ color: "var(--ink-3)" }} />
<p className="text-sm font-semibold" style={{ color: "var(--ink-2)" }}>暂无发帖</p>
</div>
)}
<Pagination
total={profile.posts_total}
page={page}
size={20}
basePath={`/u/${userId}`}
/>
</div>
) : commentError ? (
<div className="panel text-center py-16 px-6" role="alert">
<AlertCircle size={26} className="mx-auto mb-3" style={{ color: "var(--danger)" }} />
<p className="text-sm font-semibold" style={{ color: "var(--ink-2)" }}>评论加载失败</p>
<p className="meta mt-1.5 mb-4">网络异常,请稍后重试</p>
<Link href={`/u/${userId}?tab=comments`} className="btn btn-line btn-sm">重新加载</Link>
</div>
) : commentData && commentData.comments.length > 0 ? (
<div>
<div className="panel overflow-hidden p-0">
{commentData.comments.map((c, i) => (
<Link
key={c.id}
href={`/post/${c.post_id}`}
className="block px-4 sm:px-5 py-4 transition-colors hover:bg-[var(--panel-2)]"
style={{ borderTop: i === 0 ? "none" : "1px solid var(--line)" }}
>
<div className="meta text-xs mb-2">
评论于《<span style={{ color: "var(--accent)" }}>{c.post_title}</span>》
</div>
<p
className="text-[15px] leading-relaxed line-clamp-2"
style={{ color: "var(--ink)" }}
>
{c.content}
</p>
<div className="meta text-xs mt-2 tabular-nums">
{new Date(c.created_at).toLocaleString("zh-CN")}
</div>
</Link>
))}
</div>
<Pagination
total={commentData.total}
page={commentData.page}
size={20}
basePath={`/u/${userId}`}
query={{ tab: "comments" }}
/>
</div>
) : (
<div className="panel text-center py-16 px-6">
<MessageCircle size={26} className="mx-auto mb-3" style={{ color: "var(--ink-3)" }} />
<p className="text-sm font-semibold" style={{ color: "var(--ink-2)" }}>暂无评论</p>
</div>
)}
</div>
);
}

View File

@@ -1,8 +1,8 @@
import Link from "next/link";
import { Metadata } from "next";
import { ChevronRight, FileText, MessageCircle } from "lucide-react";
import { fetchUserProfile, type UserProfile } from "@/lib/api";
import UserProfileClient from "./UserProfileClient";
import { ChevronRight, FileText, MessageCircle, Flame, AlertCircle } from "lucide-react";
import { fetchUserProfile, fetchUserComments, type UserProfile, type UserCommentsResponse } from "@/lib/api";
import UserProfileContent from "./UserProfileContent";
import Avatar from "@/components/Avatar";
interface UserPageProps {
@@ -25,8 +25,9 @@ export async function generateMetadata({ params }: UserPageProps): Promise<Metad
export default async function UserPage({ params, searchParams }: UserPageProps) {
const { id } = await params;
const { page: pageStr } = await searchParams;
const page = Math.max(1, parseInt(pageStr || "1", 10) || 1);
const sp = await searchParams;
const page = Math.max(1, parseInt(sp.page || "1", 10) || 1);
const tab: "posts" | "comments" = sp.tab === "comments" ? "comments" : "posts";
let data: UserProfile;
try {
@@ -45,11 +46,23 @@ export default async function UserPage({ params, searchParams }: UserPageProps)
);
}
// 评论 tab:SSR 直出对应分页,URL(?tab=comments&page=N)与内容严格一致
let commentData: UserCommentsResponse | null = null;
let commentError = false;
if (tab === "comments") {
try {
commentData = await fetchUserComments(id, page);
} catch {
commentError = true;
}
}
const u = data.user;
const stats = [
{ label: "发帖", value: data.stats.post_count, icon: <FileText size={15} /> },
{ label: "评论", value: data.stats.comment_count, icon: <MessageCircle size={15} /> },
];
const showPoints = data.stats.points > 0;
return (
<div className="max-w-4xl mx-auto">
@@ -70,8 +83,7 @@ export default async function UserPage({ params, searchParams }: UserPageProps)
<Avatar
name={u.nickname || u.username}
src={u.avatar || undefined}
size={80}
className="sm:!w-[88px] sm:!h-[88px]"
size={88}
/>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2.5 flex-wrap">
@@ -90,7 +102,7 @@ export default async function UserPage({ params, searchParams }: UserPageProps)
<p className="meta mt-1.5 text-[13px]">
@{u.username} · {new Date(u.created_at).toLocaleDateString("zh-CN")} 加入
</p>
<div className="flex gap-2.5 mt-4">
<div className="flex gap-2.5 mt-4 flex-wrap">
{stats.map((s) => (
<span
key={s.label}
@@ -98,16 +110,34 @@ export default async function UserPage({ params, searchParams }: UserPageProps)
style={{ background: "var(--panel-2)", color: "var(--ink-2)" }}
>
<span style={{ color: "var(--accent)" }}>{s.icon}</span>
{s.value} {s.label}
<span className="tabular-nums">{s.value}</span> {s.label}
</span>
))}
{showPoints && (
<span
className="inline-flex items-center gap-2 px-3.5 py-2 rounded-full text-[13px] font-semibold"
style={{ background: "var(--gold-soft)", color: "var(--gold)" }}
title={`连续签到 ${data.stats.streak} 天`}
>
<Flame size={15} />
<span className="tabular-nums">{data.stats.points}</span> 积分
{data.stats.streak > 0 && <span className="font-normal opacity-80">· 连签 {data.stats.streak} 天</span>}
</span>
)}
</div>
</div>
</div>
</section>
{/* 发帖 / 评论 切换 */}
<UserProfileClient userId={id} initialPosts={data} initialPage={page} />
{/* 发帖 / 评论 切换(URL 驱动,SSR 直出) */}
<UserProfileContent
userId={id}
profile={data}
tab={tab}
commentData={commentData}
commentError={commentError}
page={page}
/>
</div>
);
}