feat: 新增大量社区功能与基础组件,优化站点整体体验

- 新增事件总线式toast通知系统
- 新增头像、阅读进度、404/500错误页等基础组件
- 重构页脚、布局、分页、点赞按钮等现有组件
- 新增用户个人页、通知中心、帖子编辑/发布/置顶/推荐管理功能
- 优化登录注册页面样式与交互
- 修复路径类型文件引用,更新站点元信息与字体配置
This commit is contained in:
2026-09-12 04:30:02 +08:00
parent a8f6ce4e4f
commit 1eaf3903d4
31 changed files with 2395 additions and 740 deletions

View File

@@ -1,9 +1,11 @@
import Link from "next/link"; import Link from "next/link";
import { Metadata } from "next"; import type { Metadata } from "next";
import { cookies } from "next/headers"; import { cookies } from "next/headers";
import { PenSquare, MessagesSquare, ChevronRight } from "lucide-react";
import { fetchPosts, fetchBoards } from "@/lib/api"; import { fetchPosts, fetchBoards } from "@/lib/api";
import Pagination from "@/components/Pagination"; import Pagination from "@/components/Pagination";
import LikeButton from "@/components/LikeButton"; import PostRow from "@/components/PostRow";
import PinnedPosts from "@/components/PinnedPosts";
interface PageProps { interface PageProps {
params: Promise<{ id: string }>; params: Promise<{ id: string }>;
@@ -15,7 +17,7 @@ export async function generateMetadata({ params }: PageProps): Promise<Metadata>
const { boards } = await fetchBoards(); const { boards } = await fetchBoards();
const board = boards.find((b) => b.id === Number(id)); const board = boards.find((b) => b.id === Number(id));
return { return {
title: board ? `${board.name} - 姜十三论坛` : "板块 - 姜十三论坛", title: board ? `${board.name} · 姜十三论坛` : "板块 · 姜十三论坛",
description: board?.description || "板块帖子列表", description: board?.description || "板块帖子列表",
}; };
} }
@@ -29,62 +31,111 @@ export default async function BoardPage({ params, searchParams }: PageProps) {
fetchPosts(page, 20, Number(id), "latest", "", cookie), fetchPosts(page, 20, Number(id), "latest", "", cookie),
fetchBoards(), fetchBoards(),
]); ]);
const board = boardsData.boards.find((b) => b.id === Number(id)); const boardIndex = boardsData.boards.findIndex((b) => b.id === Number(id));
const board = boardIndex >= 0 ? boardsData.boards[boardIndex] : null;
// 第一页:置顶帖独立成区,列表只保留非置顶
const pinned = page === 1 ? postsData.posts.filter((p) => p.pinned > 0) : [];
const rows = page === 1 ? postsData.posts.filter((p) => p.pinned <= 0) : postsData.posts;
return ( return (
<div> <div>
<nav className="text-sm mb-4" style={{ color: "var(--text-secondary)" }}> {/* 面包屑 */}
<Link href="/" className="hover:underline">首页</Link> <nav className="meta mb-5 flex items-center gap-1.5 text-[13px]">
<span className="mx-2">/</span> <Link href="/" className="hover:text-[var(--accent)] transition-colors">首页</Link>
<span>{board?.name || "板块"}</span> <ChevronRight size={13} />
<span style={{ color: "var(--accent)" }}>{board?.name || "未知板块"}</span>
</nav> </nav>
<h1 className="text-2xl font-bold mb-2">{board?.name}</h1> <div className="panel p-6 sm:p-7 mb-6 relative overflow-hidden">
<p className="mb-6" style={{ color: "var(--text-secondary)" }}>{board?.description}</p> <span
aria-hidden
<div className="space-y-3"> className="absolute -top-16 -right-12 w-48 h-48 rounded-full"
{postsData.posts.map((post) => ( style={{ background: "var(--accent-soft)" }}
<div />
key={post.id} <div className="relative flex items-end justify-between gap-4 flex-wrap">
className="p-4 rounded-lg border hover:shadow-md transition-shadow"
style={{ borderColor: "var(--border)", background: "var(--bg)" }}
>
<div className="flex items-center gap-2 mb-1">
{post.pinned > 0 && (
<span className="text-xs px-2 py-0.5 rounded bg-amber-100 text-amber-700">置顶</span>
)}
{post.recommended && (
<span className="text-xs px-2 py-0.5 rounded bg-rose-100 text-rose-700">推荐</span>
)}
</div>
<Link href={`/post/${post.id}`}>
<h2 className="font-semibold mb-1 hover:underline">{post.title}</h2>
</Link>
<div className="flex items-center justify-between gap-4 text-sm" style={{ color: "var(--text-secondary)" }}>
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
<Link href={`/u/${post.user.id}`} className="hover:underline" style={{ color: "var(--primary)" }}> <span
{post.user.nickname} className={`av-${Math.max(0, boardIndex) % 8} w-14 h-14 sm:w-16 sm:h-16 rounded-2xl flex items-center justify-center text-2xl font-extrabold shrink-0`}
</Link> >
<span>{new Date(post.created_at).toLocaleDateString("zh-CN")}</span> {board?.name.slice(0, 1) || "?"}
<span>💬 {post.comment_count}</span> </span>
<span>👁 {post.view_count}</span> <div>
</div> <h1 className="text-2xl sm:text-[28px] font-extrabold tracking-tight" style={{ color: "var(--ink)" }}>
<LikeButton postId={String(post.id)} liked={post.liked} likeCount={post.like_count} variant="compact" /> {board?.name || "未知板块"}
</div> </h1>
</div> {board?.description && (
))} <p className="mt-1 text-sm" style={{ color: "var(--ink-2)" }}>
{postsData.posts.length === 0 && ( {board.description}
<p className="text-center py-12" style={{ color: "var(--text-secondary)" }}>
该板块暂无帖子
</p> </p>
)} )}
<p className="meta mt-1.5">{postsData.total} 篇讨论</p>
</div>
</div>
<Link href="/compose" className="btn btn-primary">
<PenSquare size={15} /> 在此板块发帖
</Link>
</div>
</div>
<div className="grid grid-cols-1 lg:grid-cols-[1fr_290px] gap-6">
<div>
<PinnedPosts posts={pinned} showBoard={false} />
{rows.length > 0 ? (
<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-xs">第 {page} 页</span>
</div>
{rows.map((post) => (
<PostRow key={post.id} post={post} />
))}
</div>
) : (
pinned.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)" }}
>
<MessagesSquare size={26} />
</span>
<p className="font-bold text-lg" style={{ color: "var(--ink)" }}>该板块还没有帖子</p>
<p className="meta mt-1.5">来发第一篇,抢占沙发</p>
<Link href="/compose" className="btn btn-primary mt-6">
<PenSquare size={15} /> 写新帖
</Link>
</div>
)
)}
<Pagination total={postsData.total} page={page} size={20} basePath={`/board/${id}`} />
</div>
<aside>
<div className="panel p-5">
<p className="font-bold text-[15px] mb-3.5" style={{ color: "var(--ink)" }}>其他板块</p>
<div className="space-y-1">
{boardsData.boards
.map((b, i) => ({ b, i }))
.filter(({ b }) => b.id !== Number(id))
.map(({ b, i }) => (
<Link
key={b.id}
href={`/board/${b.id}`}
className="group flex items-center gap-3 py-1.5 px-2 -mx-2 rounded-xl transition-colors hover:bg-[var(--panel-2)]"
>
<span className={`av-${i % 8} w-8 h-8 rounded-xl flex items-center justify-center text-[13px] font-bold shrink-0`}>
{b.name.slice(0, 1)}
</span>
<span className="text-sm font-medium flex-1 truncate group-hover:text-[var(--accent)] transition-colors" style={{ color: "var(--ink)" }}>
{b.name}
</span>
</Link>
))}
</div>
</div>
</aside>
</div> </div>
<Pagination
total={postsData.total}
page={page}
size={20}
basePath={`/board/${id}`}
/>
</div> </div>
); );
} }

View File

@@ -2,6 +2,8 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import Link from "next/link";
import { ChevronRight, PenSquare } from "lucide-react";
import { apiCreatePost, apiMe, fetchBoards, type Board } from "@/lib/api"; import { apiCreatePost, apiMe, fetchBoards, type Board } from "@/lib/api";
export default function ComposePage() { export default function ComposePage() {
@@ -15,7 +17,6 @@ export default function ComposePage() {
const [error, setError] = useState(""); const [error, setError] = useState("");
useEffect(() => { useEffect(() => {
// 通过 /api/me 检查登录态(HttpOnly cookie 自动携带)
apiMe() apiMe()
.then((res) => { .then((res) => {
if (!res.user) { if (!res.user) {
@@ -54,68 +55,93 @@ export default function ComposePage() {
return ( return (
<div className="max-w-3xl mx-auto"> <div className="max-w-3xl mx-auto">
<h1 className="text-2xl font-bold mb-6">发布新帖</h1> <nav className="meta mb-5 flex items-center gap-1.5 text-[13px]">
<form onSubmit={handleSubmit} className="space-y-4"> <Link href="/" className="hover:text-[var(--accent)] transition-colors">首页</Link>
{error && ( <ChevronRight size={13} />
<div className="p-3 rounded-lg bg-red-50 text-red-600 text-sm">{error}</div> <span style={{ color: "var(--accent)" }}>发布新帖</span>
)} </nav>
<div className="mb-7 flex items-center gap-3.5">
<span
className="w-12 h-12 rounded-2xl flex items-center justify-center shrink-0"
style={{ background: "var(--accent-soft)", color: "var(--accent)" }}
>
<PenSquare size={22} />
</span>
<div> <div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>板块</label> <h1 className="text-[26px] sm:text-[30px] font-extrabold tracking-tight leading-tight" style={{ color: "var(--ink)" }}>
发布新帖
</h1>
<p className="meta mt-0.5">清晰的标题和内容,更容易获得回应</p>
</div>
</div>
<form onSubmit={handleSubmit} className="panel p-5 sm:p-7 space-y-5">
{error && <div className="alert-error">{error}</div>}
<div>
<label className="field-label">选择板块</label>
<select <select
value={boardId} value={boardId}
onChange={(e) => setBoardId(Number(e.target.value))} onChange={(e) => setBoardId(Number(e.target.value))}
className="w-full px-3 py-2 rounded-lg border" className="field"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
> >
{boards.map((b) => ( {boards.map((b) => (
<option key={b.id} value={b.id}>{b.name}</option> <option key={b.id} value={b.id}>
{b.name}
</option>
))} ))}
</select> </select>
</div> </div>
<div> <div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>标题</label> <label className="field-label">标题</label>
<input <input
type="text" type="text"
value={title} value={title}
onChange={(e) => setTitle(e.target.value)} onChange={(e) => setTitle(e.target.value)}
required required
maxLength={256} maxLength={256}
placeholder="帖子标题" placeholder="一句话说清楚你要讨论什么"
className="w-full px-3 py-2 rounded-lg border" className="field"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/> />
</div> </div>
<div> <div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>标签(逗号分隔,可选)</label> <label className="field-label">标签(逗号分隔,可选)</label>
<input <input
type="text" type="text"
value={tags} value={tags}
onChange={(e) => setTags(e.target.value)} onChange={(e) => setTags(e.target.value)}
placeholder="例如:技术,Go" placeholder="Go, PostgreSQL, 架构"
className="w-full px-3 py-2 rounded-lg border" className="field"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/> />
</div> </div>
<div> <div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>内容(支持 Markdown)</label> <label className="field-label">正文(支持 Markdown)</label>
<textarea <textarea
value={content} value={content}
onChange={(e) => setContent(e.target.value)} onChange={(e) => setContent(e.target.value)}
required required
rows={12} rows={14}
placeholder="帖子内容,支持 Markdown 格式..." placeholder="# 开头写结论&#10;&#10;支持 Markdown 语法..."
className="w-full px-3 py-2 rounded-lg border resize-y font-mono" className="field"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/> />
</div> </div>
<div className="flex gap-3 pt-2">
<button <button
type="submit" type="submit"
disabled={loading || !title.trim() || !content.trim()} disabled={loading || !title.trim() || !content.trim()}
className="px-6 py-2 rounded-lg text-white disabled:opacity-50" className="btn btn-primary"
style={{ background: "var(--primary)" }}
> >
{loading ? "发布中..." : "发布帖子"} {loading ? "发布中..." : "发布帖子"}
</button> </button>
<Link href="/" className="btn btn-line">
取消
</Link>
</div>
</form> </form>
</div> </div>
); );

45
frontend/app/error.tsx Normal file
View File

@@ -0,0 +1,45 @@
"use client";
import { useEffect } from "react";
import Link from "next/link";
import { CloudOff, RotateCcw } from "lucide-react";
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
console.error(error);
}, [error]);
return (
<div className="max-w-md mx-auto text-center py-20 sm:py-28">
<span
className="inline-flex w-16 h-16 rounded-full items-center justify-center mb-6"
style={{ background: "var(--clay-soft)", color: "var(--clay)" }}
>
<CloudOff size={30} />
</span>
<p className="text-[15px] font-extrabold tracking-wide mb-1" style={{ color: "var(--clay)" }}>
500
</p>
<h1 className="text-2xl font-extrabold mb-2" style={{ color: "var(--ink)" }}>
页面出了点问题
</h1>
<p className="text-sm mb-8" style={{ color: "var(--ink-2)" }}>
可以重试,或先回首页看看其他内容
</p>
<div className="flex items-center justify-center gap-3">
<button onClick={reset} className="btn btn-primary">
<RotateCcw size={15} /> 重试
</button>
<Link href="/" className="btn btn-line">
返回首页
</Link>
</div>
</div>
);
}

View File

@@ -1,40 +1,472 @@
@import "tailwindcss"; @import "tailwindcss";
/* ============================================================
姜十三论坛 · WARM CORNER 设计系统
暖白纸面 / 圆润卡片 / 柔和投影 / 青绿主色 / 陶土辅色
============================================================ */
:root { :root {
--bg: #ffffff; /* 浅色(默认) */
--bg-secondary: #f8fafc; --bg: #f6f2ea;
--text: #1e293b; --panel: #ffffff;
--text-secondary: #64748b; --panel-2: #faf6ef;
--border: #e2e8f0; --tint: #f1ebe0;
--primary: #3b82f6; --ink: #2c2620;
--primary-hover: #2563eb; --ink-2: #6b6257;
--ink-3: #7c7365;
--line: #ece4d8;
--line-2: #ddd2c1;
--accent: #0e6f66;
--accent-hi: #0b5c54;
--accent-soft: rgba(14, 111, 102, 0.1);
--accent-on: #fdfbf6; /* 暖白,与暖纸底色协调,而非冷纯白 */
--clay: #b85c42;
--clay-soft: rgba(200, 105, 77, 0.12);
--gold: #9a6b1f;
--gold-soft: rgba(176, 124, 30, 0.13);
--danger: #d23b32;
--danger-soft: rgba(210, 59, 50, 0.09);
--ok: #2f8f4e;
--ok-soft: rgba(47, 143, 78, 0.1);
--shadow-sm: 0 1px 2px rgba(87, 66, 36, 0.05);
--shadow: 0 2px 8px rgba(87, 66, 36, 0.05), 0 10px 28px rgba(87, 66, 36, 0.05);
--shadow-lg: 0 6px 16px rgba(87, 66, 36, 0.07), 0 20px 48px rgba(87, 66, 36, 0.1);
--font-display: "Plus Jakarta Sans", "Noto Sans SC", -apple-system, "PingFang SC",
"Microsoft YaHei", system-ui, sans-serif;
--font-sans: "Plus Jakarta Sans", "Noto Sans SC", -apple-system, "PingFang SC",
"Microsoft YaHei", system-ui, sans-serif;
--font-mono: "JetBrains Mono", "Noto Sans SC", ui-monospace, "Cascadia Code",
Consolas, monospace;
--r: 18px;
--r-sm: 12px;
color-scheme: light;
} }
.dark { .dark {
--bg: #0f172a; --bg: #181510;
--bg-secondary: #1e293b; --panel: #221e18;
--text: #e2e8f0; --panel-2: #2a251e;
--text-secondary: #94a3b8; --tint: #312b22;
--border: #334155; --ink: #f3ede2;
--primary: #60a5fa; --ink-2: #c3b9a9;
--primary-hover: #3b82f6; --ink-3: #9d9383;
--line: rgba(243, 237, 226, 0.09);
--line-2: rgba(243, 237, 226, 0.17);
--accent: #2dd4bf;
--accent-hi: #5eead4;
--accent-soft: rgba(45, 212, 191, 0.15);
--accent-on: #0c2420;
--clay: #e89070;
--clay-soft: rgba(232, 144, 112, 0.16);
--gold: #d8ae5e;
--gold-soft: rgba(216, 174, 94, 0.16);
--danger: #f26b5e;
--danger-soft: rgba(242, 107, 94, 0.15);
--ok: #6fcf8e;
--ok-soft: rgba(111, 207, 142, 0.15);
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.3);
--shadow: 0 2px 8px rgba(0, 0, 0, 0.28), 0 12px 32px rgba(0, 0, 0, 0.22);
--shadow-lg: 0 6px 18px rgba(0, 0, 0, 0.35), 0 24px 56px rgba(0, 0, 0, 0.3);
color-scheme: dark;
}
* {
border-color: var(--line);
}
html {
scrollbar-color: var(--line-2) transparent;
} }
body { body {
background-color: var(--bg); background-color: var(--bg);
color: var(--text); color: var(--ink);
font-family: var(--font-sans);
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
} }
/* Markdown 内容样式 */ ::selection {
.prose-content h1 { font-size: 1.875rem; font-weight: 700; margin: 1rem 0; } background: var(--accent);
.prose-content h2 { font-size: 1.5rem; font-weight: 700; margin: 1rem 0; } color: var(--accent-on);
.prose-content h3 { font-size: 1.25rem; font-weight: 600; margin: 0.75rem 0; } }
.prose-content p { margin: 0.75rem 0; line-height: 1.7; }
.prose-content ul { list-style: disc; padding-left: 1.5rem; margin: 0.75rem 0; } ::-webkit-scrollbar {
.prose-content ol { list-style: decimal; padding-left: 1.5rem; margin: 0.75rem 0; } width: 10px;
.prose-content code { background: var(--bg-secondary); padding: 0.125rem 0.375rem; border-radius: 0.25rem; font-size: 0.875rem; } height: 10px;
.prose-content pre { background: var(--bg-secondary); padding: 1rem; border-radius: 0.5rem; overflow-x: auto; margin: 1rem 0; } }
.prose-content pre code { background: none; padding: 0; } ::-webkit-scrollbar-thumb {
.prose-content blockquote { border-left: 4px solid var(--border); padding-left: 1rem; color: var(--text-secondary); margin: 1rem 0; } background: var(--line-2);
.prose-content a { color: var(--primary); text-decoration: underline; } border-radius: 99px;
.prose-content img { max-width: 100%; border-radius: 0.5rem; } border: 3px solid var(--bg);
}
/* 链接重置放入 base 层:避免未分层规则击败 components 层的 .btn-primary 等类
(Tailwind v4 中未分层样式优先级高于任何 @layer) */
@layer base {
a {
color: inherit;
text-decoration: none;
}
}
h1, h2, h3, h4 {
font-family: var(--font-display);
letter-spacing: -0.015em;
}
:focus-visible {
outline: 2.5px solid var(--accent);
outline-offset: 2px;
border-radius: 6px;
}
@layer components {
/* ----- 小标签(旧名 .kicker 保留兼容) ----- */
.kicker {
font-family: var(--font-sans);
font-size: 12.5px;
font-weight: 600;
letter-spacing: 0.02em;
color: var(--ink-3);
}
/* ----- 卡片 ----- */
.panel {
background: var(--panel);
border: 1px solid var(--line);
border-radius: var(--r);
box-shadow: var(--shadow-sm);
}
.hover-lift {
transition: transform 0.18s ease, box-shadow 0.18s ease, border-color 0.18s ease;
}
.hover-lift:hover {
transform: translateY(-2px);
box-shadow: var(--shadow);
border-color: var(--line-2);
}
/* ----- 按钮(胶囊) ----- */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 7px;
padding: 10px 20px;
border-radius: 999px;
font-size: 14px;
font-weight: 600;
line-height: 1;
border: 1px solid transparent;
cursor: pointer;
transition: background 0.15s, border-color 0.15s, color 0.15s,
transform 0.12s ease, box-shadow 0.15s;
white-space: nowrap;
}
.btn:active { transform: scale(0.97); }
.btn:disabled { opacity: 0.5; cursor: not-allowed; }
.btn-primary {
background: var(--accent);
color: var(--accent-on);
box-shadow: 0 1px 2px rgba(87, 66, 36, 0.12), 0 2px 8px rgba(14, 111, 102, 0.16);
}
.btn-primary:hover:not(:disabled) {
background: var(--accent-hi);
transform: translateY(-1px);
box-shadow: 0 2px 6px rgba(87, 66, 36, 0.1), 0 8px 20px rgba(14, 111, 102, 0.24);
}
.btn-primary:active:not(:disabled) {
transform: translateY(0);
}
.btn-line {
background: var(--panel);
border-color: var(--line-2);
color: var(--ink);
}
.btn-line:hover:not(:disabled) {
border-color: var(--accent);
color: var(--accent);
}
.btn-danger {
background: var(--danger-soft);
color: var(--danger);
}
.btn-danger:hover:not(:disabled) {
background: var(--danger);
color: #fff;
}
.btn-sm { padding: 7px 14px; font-size: 13px; }
/* ----- 表单 ----- */
.field-label {
display: block;
font-size: 13px;
font-weight: 600;
color: var(--ink-2);
margin-bottom: 8px;
}
.field {
width: 100%;
padding: 12px 15px;
background: var(--bg);
border: 1px solid var(--line-2);
border-radius: var(--r-sm);
color: var(--ink);
font-size: 15px;
font-family: var(--font-sans);
transition: border-color 0.15s, box-shadow 0.15s, background 0.15s;
}
.field::placeholder { color: var(--ink-3); opacity: 0.8; }
.field:focus {
outline: none;
border-color: var(--accent);
box-shadow: 0 0 0 3.5px var(--accent-soft);
background: var(--panel);
}
textarea.field {
font-family: var(--font-sans);
font-size: 15px;
line-height: 1.75;
resize: vertical;
}
/* ----- 标签 / 徽标 ----- */
.chip {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 12.5px;
font-weight: 500;
padding: 4px 12px;
background: var(--tint);
color: var(--ink-2);
border-radius: 999px;
white-space: nowrap;
transition: background 0.15s, color 0.15s;
}
a.chip:hover {
background: var(--accent-soft);
color: var(--accent);
}
.badge-pin {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 12px;
font-weight: 700;
padding: 4px 11px;
background: var(--clay-soft);
color: var(--clay);
border-radius: 999px;
white-space: nowrap;
}
.badge-rec {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 12px;
font-weight: 700;
padding: 4px 11px;
background: var(--gold-soft);
color: var(--gold);
border-radius: 999px;
white-space: nowrap;
}
/* ----- 分页 ----- */
.pager-btn {
background: var(--panel);
border-color: var(--line);
color: var(--ink-2);
}
.pager-btn:hover {
border-color: var(--accent);
color: var(--accent);
transform: translateY(-1px);
}
.pager-btn.is-current,
.pager-btn.is-current:hover {
background: var(--accent);
border-color: var(--accent);
color: var(--accent-on);
font-weight: 700;
}
/* ----- 辅助 ----- */
.meta {
font-family: var(--font-sans);
font-size: 12.5px;
color: var(--ink-3);
font-variant-numeric: tabular-nums;
}
.link-accent { color: var(--accent); }
.link-accent:hover { color: var(--accent-hi); }
.alert-error {
padding: 12px 15px;
border: 1px solid color-mix(in srgb, var(--danger) 30%, transparent);
background: var(--danger-soft);
color: var(--danger);
border-radius: var(--r-sm);
font-size: 14px;
font-weight: 500;
}
.alert-ok {
padding: 12px 15px;
border: 1px solid color-mix(in srgb, var(--ok) 30%, transparent);
background: var(--ok-soft);
color: var(--ok);
border-radius: var(--r-sm);
font-size: 14px;
font-weight: 500;
}
}
/* ============================================================
Markdown 正文
============================================================ */
.prose-content { font-size: 16.5px; line-height: 1.85; color: var(--ink); }
.prose-content h1 { font-size: 1.75rem; font-weight: 800; margin: 1.6rem 0 0.8rem; }
.prose-content h2 {
font-size: 1.4rem;
font-weight: 700;
margin: 1.9rem 0 0.7rem;
padding-bottom: 0.45rem;
border-bottom: 1px solid var(--line);
}
.prose-content h3 { font-size: 1.18rem; font-weight: 700; margin: 1.5rem 0 0.6rem; }
.prose-content p { margin: 0.9rem 0; }
.prose-content ul { list-style: disc; padding-left: 1.5rem; margin: 0.9rem 0; }
.prose-content ol { list-style: decimal; padding-left: 1.5rem; margin: 0.9rem 0; }
.prose-content li { margin: 0.35rem 0; }
.prose-content code {
font-family: var(--font-mono);
background: var(--tint);
padding: 0.12rem 0.45rem;
border-radius: 6px;
font-size: 0.86em;
}
.prose-content pre {
background: var(--panel-2) !important;
border: 1px solid var(--line);
padding: 1.05rem 1.15rem;
border-radius: var(--r-sm);
overflow-x: auto;
margin: 1.15rem 0;
}
.prose-content pre code { background: none; padding: 0; border-radius: 0; }
.prose-content blockquote {
border-left: 3px solid var(--accent);
background: var(--accent-soft);
border-radius: 0 var(--r-sm) var(--r-sm) 0;
padding: 0.7rem 1.1rem;
color: var(--ink-2);
margin: 1.2rem 0;
}
.prose-content a {
color: var(--accent);
text-decoration: underline;
text-underline-offset: 3px;
font-weight: 500;
}
.prose-content img {
max-width: 100%;
border-radius: var(--r-sm);
border: 1px solid var(--line);
}
.prose-content hr { border: none; border-top: 1px solid var(--line); margin: 2.2rem 0; }
.prose-content strong { font-weight: 700; }
@media (prefers-reduced-motion: reduce) {
* { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; }
}
/* 头像配色(浅/暗各自保证可读) */
.av-0 { background: rgba(15, 118, 110, 0.12); color: #0f766e; }
.av-1 { background: rgba(200, 105, 77, 0.14); color: #b85c42; }
.av-2 { background: rgba(176, 124, 30, 0.15); color: #9a6b1f; }
.av-3 { background: rgba(91, 111, 181, 0.14); color: #4c61ab; }
.av-4 { background: rgba(122, 92, 168, 0.14); color: #6f50a0; }
.av-5 { background: rgba(79, 138, 95, 0.15); color: #477e55; }
.av-6 { background: rgba(192, 106, 139, 0.14); color: #b1557a; }
.av-7 { background: rgba(63, 134, 147, 0.14); color: #357985; }
.dark .av-0 { background: rgba(45, 212, 191, 0.16); color: #5eead4; }
.dark .av-1 { background: rgba(232, 144, 112, 0.18); color: #f0a484; }
.dark .av-2 { background: rgba(216, 174, 94, 0.18); color: #e3bf74; }
.dark .av-3 { background: rgba(130, 150, 224, 0.18); color: #a7b8f0; }
.dark .av-4 { background: rgba(178, 150, 224, 0.18); color: #c3abe8; }
.dark .av-5 { background: rgba(129, 201, 148, 0.18); color: #99ddac; }
.dark .av-6 { background: rgba(235, 148, 180, 0.18); color: #f0a5c2; }
.dark .av-7 { background: rgba(102, 190, 206, 0.18); color: #84d4e0; }
/* ============================================================
微交互
============================================================ */
@keyframes j13-toast-in {
from { opacity: 0; transform: translateY(10px) scale(0.98); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
.j13-toast-in { animation: j13-toast-in 0.2s cubic-bezier(0.2, 0.9, 0.3, 1.2); }
@keyframes j13-heart-pop {
0% { transform: scale(1); }
45% { transform: scale(1.4); }
100% { transform: scale(1); }
}
.j13-heart-pop { animation: j13-heart-pop 0.26s ease-out; }
@keyframes j13-fade-up {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
.j13-fade-up { animation: j13-fade-up 0.3s ease-out both; }
/* 跳到主内容 */
.skip-link {
position: fixed;
top: 10px;
left: 10px;
z-index: 10001;
padding: 10px 18px;
font-size: 13.5px;
font-weight: 600;
background: var(--accent);
color: var(--accent-on);
border-radius: 999px;
transform: translateY(-200%);
transition: transform 0.18s ease;
}
.skip-link:focus-visible {
transform: translateY(0);
outline: none;
}
/* 阅读进度条 */
.reading-progress {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 3px;
z-index: 60;
background: var(--accent);
transform-origin: 0 50%;
pointer-events: none;
}

View File

@@ -3,12 +3,16 @@ import { cookies } from "next/headers";
import "./globals.css"; import "./globals.css";
import Header from "@/components/Header"; import Header from "@/components/Header";
import Footer from "@/components/Footer"; import Footer from "@/components/Footer";
import Toaster from "@/components/Toaster";
export const metadata: Metadata = { export const metadata: Metadata = {
title: "姜十三论坛", title: {
default: "姜十三论坛 · J13 FORUM",
template: "%s · 姜十三论坛",
},
description: "姜十三论坛 - 技术分享与讨论社区", description: "姜十三论坛 - 技术分享与讨论社区",
openGraph: { openGraph: {
title: "姜十三论坛", title: "姜十三论坛 · J13 FORUM",
description: "姜十三论坛 - 技术分享与讨论社区", description: "姜十三论坛 - 技术分享与讨论社区",
type: "website", type: "website",
}, },
@@ -20,16 +24,33 @@ export default async function RootLayout({
children: React.ReactNode; children: React.ReactNode;
}) { }) {
const cookieStore = await cookies(); const cookieStore = await cookies();
const theme = cookieStore.get("j13-theme")?.value || "light"; // 浅色优先的设计系统,仅在显式选择暗色时挂 .dark
const theme = cookieStore.get("j13-theme")?.value === "dark" ? "dark" : "light";
return ( return (
<html lang="zh-CN" className={theme === "dark" ? "dark" : ""}> <html lang="zh-CN" className={theme === "dark" ? "dark" : ""}>
<head>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
<link
href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;700&family=Noto+Sans+SC:wght@400;500;700;900&display=swap"
rel="stylesheet"
/>
</head>
<body className="min-h-screen flex flex-col"> <body className="min-h-screen flex flex-col">
<a href="#main" className="skip-link">
跳到主要内容
</a>
<Header /> <Header />
<main className="flex-1 max-w-5xl mx-auto w-full px-4 py-6"> <main
id="main"
tabIndex={-1}
className="flex-1 w-full max-w-6xl mx-auto px-4 sm:px-6 py-7 sm:py-9 outline-none"
>
{children} {children}
</main> </main>
<Footer /> <Footer />
<Toaster />
</body> </body>
</html> </html>
); );

View File

@@ -3,6 +3,7 @@
import { useState } from "react"; import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation"; import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link"; import Link from "next/link";
import { MessagesSquare } from "lucide-react";
import { apiLogin } from "@/lib/api"; import { apiLogin } from "@/lib/api";
export default function LoginPage() { export default function LoginPage() {
@@ -32,45 +33,57 @@ export default function LoginPage() {
}; };
return ( return (
<div className="max-w-md mx-auto mt-12"> <div className="max-w-md mx-auto pt-8 sm:pt-14">
<h1 className="text-2xl font-bold mb-6 text-center">登录</h1> <div className="mb-7 text-center">
<form onSubmit={handleSubmit} className="space-y-4"> <span
{error && ( className="inline-flex w-14 h-14 rounded-2xl items-center justify-center mb-4"
<div className="p-3 rounded-lg bg-red-50 text-red-600 text-sm">{error}</div> style={{ background: "var(--accent-soft)", color: "var(--accent)" }}
)} >
<MessagesSquare size={26} />
</span>
<h1 className="text-[28px] font-extrabold tracking-tight" style={{ color: "var(--ink)" }}>
欢迎回来
</h1>
<p className="text-sm mt-2" style={{ color: "var(--ink-2)" }}>
登录后发帖、评论与点赞
</p>
</div>
<form onSubmit={handleSubmit} className="panel p-6 sm:p-7 space-y-4">
{error && <div className="alert-error">{error}</div>}
<div> <div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>用户名</label> <label className="field-label">用户名</label>
<input <input
type="text" type="text"
value={username} value={username}
onChange={(e) => setUsername(e.target.value)} onChange={(e) => setUsername(e.target.value)}
required required
className="w-full px-3 py-2 rounded-lg border" autoFocus
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }} className="field"
placeholder="testuser"
/> />
</div> </div>
<div> <div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>密码</label> <label className="field-label">密码</label>
<input <input
type="password" type="password"
value={password} value={password}
onChange={(e) => setPassword(e.target.value)} onChange={(e) => setPassword(e.target.value)}
required required
className="w-full px-3 py-2 rounded-lg border" className="field"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }} placeholder="••••••"
/> />
</div> </div>
<button <button type="submit" disabled={loading} className="btn btn-primary w-full justify-center mt-2">
type="submit"
disabled={loading}
className="w-full py-2 rounded-lg text-white disabled:opacity-50"
style={{ background: "var(--primary)" }}
>
{loading ? "登录中..." : "登录"} {loading ? "登录中..." : "登录"}
</button> </button>
</form> </form>
<p className="text-center mt-4 text-sm" style={{ color: "var(--text-secondary)" }}>
还没有账号?<Link href="/register" className="hover:underline" style={{ color: "var(--primary)" }}>立即注册</Link> <p className="meta text-center mt-5">
还没有账号?
<Link href="/register" className="ml-1 font-semibold" style={{ color: "var(--accent)" }}>
立即注册
</Link>
</p> </p>
</div> </div>
); );

View File

@@ -0,0 +1,32 @@
import Link from "next/link";
import { Compass, Home } from "lucide-react";
export default function NotFound() {
return (
<div className="max-w-md mx-auto text-center py-20 sm:py-28">
<span
className="inline-flex w-16 h-16 rounded-full items-center justify-center mb-6"
style={{ background: "var(--accent-soft)", color: "var(--accent)" }}
>
<Compass size={30} />
</span>
<p className="text-[15px] font-extrabold tracking-wide mb-1" style={{ color: "var(--accent)" }}>
404
</p>
<h1 className="text-2xl font-extrabold mb-2" style={{ color: "var(--ink)" }}>
这一页走丢了
</h1>
<p className="text-sm mb-8" style={{ color: "var(--ink-2)" }}>
链接可能已失效,或帖子已被作者删除
</p>
<div className="flex items-center justify-center gap-3">
<Link href="/" className="btn btn-primary">
<Home size={15} /> 返回首页
</Link>
<Link href="/board/1" className="btn btn-line">
逛逛板块
</Link>
</div>
</div>
);
}

View File

@@ -3,7 +3,7 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import Link from "next/link"; import Link from "next/link";
import { Heart, MessageCircle, CheckCheck } from "lucide-react"; import { Heart, MessageCircle, CheckCheck, Bell, ChevronRight } from "lucide-react";
import { import {
apiFetchNotifications, apiFetchNotifications,
apiMarkRead, apiMarkRead,
@@ -60,68 +60,84 @@ export default function NotificationsPage() {
return ( return (
<div className="max-w-2xl mx-auto"> <div className="max-w-2xl mx-auto">
<div className="flex items-center justify-between mb-6"> <nav className="meta mb-5 flex items-center gap-1.5 text-[13px]">
<h1 className="text-2xl font-bold" style={{ color: "var(--text)" }}>通知中心</h1> <Link href="/" className="hover:text-[var(--accent)] transition-colors">首页</Link>
<ChevronRight size={13} />
<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 && ( {hasUnread && (
<button <button onClick={handleMarkAll} className="btn btn-line btn-sm">
onClick={handleMarkAll} <CheckCheck size={14} /> 全部已读
className="flex items-center gap-1 text-sm hover:opacity-80"
style={{ color: "var(--primary)" }}
>
<CheckCheck size={16} /> 全部标记已读
</button> </button>
)} )}
</div> </div>
{loading ? ( {loading ? (
<p className="text-center py-12" style={{ color: "var(--text-secondary)" }}>加载中...</p> <div className="panel text-center py-16">
<p className="meta">正在加载通知…</p>
</div>
) : notifications.length === 0 ? ( ) : notifications.length === 0 ? (
<p className="text-center py-12" style={{ color: "var(--text-secondary)" }}>暂无通知</p> <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="space-y-2"> <div className="panel overflow-hidden p-0">
{notifications.map((n) => ( {notifications.map((n, i) => (
<button <button
key={n.id} key={n.id}
onClick={() => handleClick(n)} onClick={() => handleClick(n)}
className="w-full text-left p-4 rounded-lg border hover:shadow-sm transition-shadow" 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={{ style={{
borderColor: "var(--border)", borderTop: i === 0 ? "none" : "1px solid var(--line)",
background: n.is_read ? "var(--bg)" : "var(--bg-secondary)", background: n.is_read ? "transparent" : "var(--panel-2)",
}} }}
> >
<div className="flex items-start gap-3"> <span
<span style={{ color: n.type === "like" ? "#ef4444" : "var(--primary)" }}> className="w-10 h-10 shrink-0 rounded-full flex items-center justify-center"
{n.type === "like" ? <Heart size={18} /> : <MessageCircle size={18} />} 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> </span>
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<p className="text-sm" style={{ color: "var(--text)" }}> <p className="text-sm leading-snug" style={{ color: "var(--ink)" }}>
<Link <Link
href={`/u/${n.actor.id}`} href={`/u/${n.actor.id}`}
onClick={(e) => e.stopPropagation()} onClick={(e) => e.stopPropagation()}
className="font-medium hover:underline" className="font-semibold hover:text-[var(--accent)] transition-colors"
> >
{n.actor.nickname} {n.actor.nickname}
</Link>{" "} </Link>{" "}
<span style={{ color: "var(--text-secondary)" }}> <span className="meta">{n.type === "comment" ? "评论了你的帖子" : "点赞了你的帖子"}</span>
{n.type === "comment" ? "评论了你的帖子" : "点赞了你的帖子"}
</span>
</p> </p>
<p className="text-sm mt-1 font-medium truncate" style={{ color: "var(--text)" }}> <p className="text-sm mt-1 truncate" style={{ color: "var(--ink-2)" }}>
《{n.post.title}》 《{n.post.title}》
</p> </p>
{n.content && ( {n.content && (
<p className="text-sm mt-1 line-clamp-2" style={{ color: "var(--text-secondary)" }}> <p className="text-[13px] mt-1.5 line-clamp-2" style={{ color: "var(--ink-3)" }}>
{n.content} {n.content}
</p> </p>
)} )}
<p className="text-xs mt-2" style={{ color: "var(--text-secondary)" }}> <p className="meta text-xs mt-2">{formatTime(n.created_at)}</p>
{formatTime(n.created_at)}
</p>
</div> </div>
{!n.is_read && ( {!n.is_read && (
<span className="w-2.5 h-2.5 rounded-full shrink-0 mt-1.5" style={{ background: "var(--primary)" }} /> <span className="w-2.5 h-2.5 shrink-0 mt-2 rounded-full" style={{ background: "var(--clay)" }} />
)} )}
</div>
</button> </button>
))} ))}
</div> </div>

View File

@@ -1,18 +1,16 @@
import Link from "next/link"; import Link from "next/link";
import { Metadata } from "next"; import type { Metadata } from "next";
import { cookies } from "next/headers"; import { cookies } from "next/headers";
import { PenSquare, SearchX, MessagesSquare, Check, ArrowRight } from "lucide-react";
import { fetchPosts, fetchBoards } from "@/lib/api"; import { fetchPosts, fetchBoards } from "@/lib/api";
import Pagination from "@/components/Pagination"; import Pagination from "@/components/Pagination";
import LikeButton from "@/components/LikeButton"; import PostRow from "@/components/PostRow";
import FeaturePost from "@/components/FeaturePost";
import PinnedPosts from "@/components/PinnedPosts";
export const metadata: Metadata = { export const metadata: Metadata = {
title: "姜十三论坛 - 技术分享与讨论社区", title: "姜十三论坛 · 技术讨论社区",
description: "姜十三论坛,分享技术、讨论问题、交流心得的社区", description: "姜十三论坛,分享技术、讨论问题、交流心得的社区",
openGraph: {
title: "姜十三论坛 - 技术分享与讨论社区",
description: "姜十三论坛,分享技术、讨论问题、交流心得的社区",
type: "website",
},
}; };
interface HomePageProps { interface HomePageProps {
@@ -29,84 +27,179 @@ export default async function HomePage({ searchParams }: HomePageProps) {
fetchBoards(), fetchBoards(),
]); ]);
// 第一页且非搜索时拆分为三段:管理员置顶 → 今日精选(首条非置顶)→ 普通列表
const split = page === 1 && !keyword;
const pinned = split ? postsData.posts.filter((p) => p.pinned > 0) : [];
const normal = split ? postsData.posts.filter((p) => p.pinned <= 0) : postsData.posts;
const feature = split && normal.length > 0 ? normal[0] : null;
const rows = feature ? normal.slice(1) : normal;
return ( return (
<div className="grid grid-cols-1 md:grid-cols-4 gap-6"> <div>
{/* 主内容:帖子列表 */} {/* 页头 */}
<div className="md:col-span-3"> <div className="flex items-end justify-between gap-4 mb-6">
<h1 className="text-2xl font-bold mb-4"> <div>
{keyword ? `搜索结果:"${keyword}"` : "最新帖子"} <h1 className="text-[26px] sm:text-[32px] font-extrabold tracking-tight" style={{ color: "var(--ink)" }}>
{keyword ? (
<>
搜索“<span style={{ color: "var(--accent)" }}>{keyword}</span>”
</>
) : (
"最新讨论"
)}
</h1> </h1>
<div className="space-y-3"> <p className="meta mt-2">
{postsData.posts.map((post) => ( {keyword
<div ? `共找到 ${postsData.total} 篇相关帖子`
key={post.id} : `共 ${postsData.total} 篇帖子 · ${boardsData.boards.length} 个板块,欢迎加入讨论`}
className="p-4 rounded-lg border hover:shadow-md transition-shadow"
style={{ borderColor: "var(--border)", background: "var(--bg)" }}
>
<div className="flex items-center gap-2 mb-2">
<span
className="text-xs px-2 py-0.5 rounded"
style={{ background: "var(--bg-secondary)", color: "var(--primary)" }}
>
{post.board.name}
</span>
{post.pinned > 0 && (
<span className="text-xs px-2 py-0.5 rounded bg-amber-100 text-amber-700">置顶</span>
)}
{post.recommended && (
<span className="text-xs px-2 py-0.5 rounded bg-rose-100 text-rose-700">推荐</span>
)}
</div>
<Link href={`/post/${post.id}`}>
<h2 className="font-semibold mb-1 hover:underline" style={{ color: "var(--text)" }}>
{post.title}
</h2>
</Link>
<div className="flex items-center justify-between gap-4 text-sm" style={{ color: "var(--text-secondary)" }}>
<div className="flex items-center gap-4">
<Link href={`/u/${post.user.id}`} className="hover:underline" style={{ color: "var(--primary)" }}>
{post.user.nickname}
</Link>
<span>{new Date(post.created_at).toLocaleDateString("zh-CN")}</span>
<span>💬 {post.comment_count}</span>
<span>👁 {post.view_count}</span>
</div>
<LikeButton postId={String(post.id)} liked={post.liked} likeCount={post.like_count} variant="compact" />
</div>
</div>
))}
{postsData.posts.length === 0 && (
<p className="text-center py-12" style={{ color: "var(--text-secondary)" }}>
{keyword ? "没有找到相关帖子" : "暂无帖子,来发第一篇吧!"}
</p> </p>
</div>
<Link href="/compose" className="btn btn-primary hidden sm:inline-flex">
<PenSquare size={16} /> 写新帖
</Link>
</div>
<div className="grid grid-cols-1 lg:grid-cols-[1fr_290px] gap-6">
{/* 主列 */}
<div>
<PinnedPosts posts={pinned} />
{feature && (
<div className="mb-6">
<FeaturePost post={feature} />
</div>
)}
<div className="panel overflow-hidden">
{rows.length > 0 ? (
<>
<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)" }}>
{keyword ? "搜索结果" : "全部讨论"}
</span>
<span className="meta text-xs">共 {postsData.total} 篇</span>
</div>
{rows.map((post) => (
<PostRow key={post.id} post={post} boardHref />
))}
</>
) : (
<div className="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)" }}
>
{keyword ? <SearchX size={26} /> : <MessagesSquare size={26} />}
</span>
<p className="font-bold text-lg" style={{ color: "var(--ink)" }}>
{keyword ? "没有找到相关帖子" : "还没有帖子"}
</p>
<p className="meta mt-1.5">
{keyword ? `换个关键词试试,或者发起“${keyword}”相关的话题` : "成为第一个发起讨论的人吧"}
</p>
{keyword ? (
<div className="flex items-center justify-center gap-3 mt-6">
<Link href="/" className="btn btn-line">
清除搜索
</Link>
<Link href="/compose" className="btn btn-primary">
<PenSquare size={15} /> 发起这个话题
</Link>
</div>
) : (
<Link href="/compose" className="btn btn-primary mt-6">
<PenSquare size={15} /> 写新帖
</Link>
)} )}
</div> </div>
)}
</div>
<Pagination <Pagination
total={postsData.total} total={postsData.total}
page={page} page={page}
size={20} size={20}
basePath="/" basePath="/"
query={keyword ? { q: keyword } : {}} query={keyword ? { q: keyword } : undefined}
/> />
</div> </div>
{/* 侧边栏:板块列表 */} {/* 侧栏 */}
<aside className="md:col-span-1"> <aside className="space-y-5">
<h2 className="text-lg font-bold mb-3">板块</h2> {/* 发帖引导 */}
<div className="space-y-2"> {!keyword && (
{boardsData.boards.map((board) => ( <div
<Link className="p-5"
key={board.id} style={{
href={`/board/${board.id}`} background: "var(--accent-soft)",
className="block p-3 rounded-lg border hover:shadow-sm transition-shadow" borderRadius: "var(--r)",
style={{ borderColor: "var(--border)", background: "var(--bg-secondary)" }} }}
> >
<div className="font-medium" style={{ color: "var(--text)" }}>{board.name}</div> <p className="font-extrabold text-[16px] mb-1" style={{ color: "var(--ink)" }}>
<div className="text-xs mt-1" style={{ color: "var(--text-secondary)" }}>{board.description}</div> 有什么想聊的?
</p>
<p className="text-[13px] leading-relaxed mb-4" style={{ color: "var(--ink-2)" }}>
分享你的想法、问题或经验,社区里有人正在等你的回答。
</p>
<Link
href="/compose"
className="btn btn-primary w-full justify-center"
>
<PenSquare size={15} /> 发起讨论
</Link>
</div>
)}
<div className="panel p-5">
<p className="font-bold text-[15px] mb-3.5" style={{ color: "var(--ink)" }}>板块导航</p>
<div className="space-y-1">
{boardsData.boards.map((b, i) => (
<Link
key={b.id}
href={`/board/${b.id}`}
className="group flex items-center gap-3 py-1.5 px-2 -mx-2 rounded-xl transition-colors hover:bg-[var(--panel-2)]"
>
<span
className={`av-${i % 8} w-8 h-8 rounded-xl flex items-center justify-center text-[13px] font-bold shrink-0`}
>
{b.name.slice(0, 1)}
</span>
<span
className="text-sm font-medium flex-1 truncate group-hover:text-[var(--accent)] transition-colors"
style={{ color: "var(--ink)" }}
>
{b.name}
</span>
<ArrowRight size={14} className="opacity-0 -translate-x-1 group-hover:opacity-100 group-hover:translate-x-0 transition-all" style={{ color: "var(--accent)" }} />
</Link> </Link>
))} ))}
</div> </div>
</div>
<div className="panel p-5">
<p className="font-bold text-[15px] mb-3.5" style={{ color: "var(--ink)" }}>社区守则</p>
<ul className="space-y-3 text-[13.5px] leading-relaxed" style={{ color: "var(--ink-2)" }}>
<li className="flex gap-2.5">
<span className="shrink-0 w-5 h-5 rounded-full flex items-center justify-center mt-0.5" style={{ background: "var(--accent-soft)", color: "var(--accent)" }}>
<Check size={12} strokeWidth={3} />
</span>
标题清晰,内容支持 Markdown
</li>
<li className="flex gap-2.5">
<span className="shrink-0 w-5 h-5 rounded-full flex items-center justify-center mt-0.5" style={{ background: "var(--accent-soft)", color: "var(--accent)" }}>
<Check size={12} strokeWidth={3} />
</span>
友善讨论,就事论事
</li>
<li className="flex gap-2.5">
<span className="shrink-0 w-5 h-5 rounded-full flex items-center justify-center mt-0.5" style={{ background: "var(--accent-soft)", color: "var(--accent)" }}>
<Check size={12} strokeWidth={3} />
</span>
违规内容可向管理员举报
</li>
</ul>
</div>
</aside> </aside>
</div> </div>
</div>
); );
} }

View File

@@ -2,6 +2,8 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import Link from "next/link";
import { ChevronRight } from "lucide-react";
import { fetchPostDetail, apiMe, apiUpdatePost, type Post, type User } from "@/lib/api"; import { fetchPostDetail, apiMe, apiUpdatePost, type Post, type User } from "@/lib/api";
interface EditPageProps { interface EditPageProps {
@@ -19,13 +21,11 @@ export default function EditPostPage({ params }: EditPageProps) {
const [error, setError] = useState(""); const [error, setError] = useState("");
const [checking, setChecking] = useState(true); const [checking, setChecking] = useState(true);
// params 是 Promise,需要解包
const [id, setId] = useState(""); const [id, setId] = useState("");
useEffect(() => { useEffect(() => {
params.then((p) => setId(p.id)); params.then((p) => setId(p.id));
}, [params]); }, [params]);
// 加载帖子 + 校验权限
useEffect(() => { useEffect(() => {
if (!id) return; if (!id) return;
Promise.all([fetchPostDetail(id), apiMe()]) Promise.all([fetchPostDetail(id), apiMe()])
@@ -36,7 +36,6 @@ export default function EditPostPage({ params }: EditPageProps) {
setTags(postData.post.tags || ""); setTags(postData.post.tags || "");
const u = meData.user; const u = meData.user;
setUser(u || null); setUser(u || null);
// 非作者且非管理员 → 跳转
if (!u || (u.id !== postData.post.user.id && u.role !== "admin")) { if (!u || (u.id !== postData.post.user.id && u.role !== "admin")) {
router.push(`/post/${id}`); router.push(`/post/${id}`);
} }
@@ -64,8 +63,8 @@ export default function EditPostPage({ params }: EditPageProps) {
if (checking) { if (checking) {
return ( return (
<div className="max-w-3xl mx-auto mt-12 text-center" style={{ color: "var(--text-secondary)" }}> <div className="max-w-3xl mx-auto text-center py-20">
加载中... <p className="meta">正在加载帖子…</p>
</div> </div>
); );
} }
@@ -74,59 +73,71 @@ export default function EditPostPage({ params }: EditPageProps) {
return ( return (
<div className="max-w-3xl mx-auto"> <div className="max-w-3xl mx-auto">
<h1 className="text-2xl font-bold mb-6">编辑帖子</h1> <nav className="meta mb-5 flex items-center gap-1.5 flex-wrap text-[13px]">
<form onSubmit={handleSubmit} className="space-y-4"> <Link href="/" className="hover:text-[var(--accent)] transition-colors">首页</Link>
{error && ( <ChevronRight size={13} />
<div className="p-3 rounded-lg bg-red-50 text-red-600 text-sm">{error}</div> <Link href={`/post/${post.id}`} className="hover:text-[var(--accent)] transition-colors truncate max-w-[12rem]">
)} 帖子详情
</Link>
<ChevronRight size={13} />
<span style={{ color: "var(--accent)" }}>编辑</span>
</nav>
<div className="mb-7">
<h1 className="text-[26px] sm:text-[30px] font-extrabold tracking-tight" style={{ color: "var(--ink)" }}>
编辑帖子
</h1>
</div>
<form onSubmit={handleSubmit} className="panel p-5 sm:p-7 space-y-5">
{error && <div className="alert-error">{error}</div>}
<div> <div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>标题</label> <label className="field-label">标题</label>
<input <input
type="text" type="text"
value={title} value={title}
onChange={(e) => setTitle(e.target.value)} onChange={(e) => setTitle(e.target.value)}
required required
maxLength={256} maxLength={256}
className="w-full px-3 py-2 rounded-lg border" className="field"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/> />
</div> </div>
<div> <div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>标签(逗号分隔,可选)</label> <label className="field-label">标签(逗号分隔,可选)</label>
<input <input
type="text" type="text"
value={tags} value={tags}
onChange={(e) => setTags(e.target.value)} onChange={(e) => setTags(e.target.value)}
placeholder="例如:技术,Go" placeholder="Go, PostgreSQL, 架构"
className="w-full px-3 py-2 rounded-lg border" className="field"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/> />
</div> </div>
<div> <div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>内容(支持 Markdown)</label> <label className="field-label">正文(支持 Markdown)</label>
<textarea <textarea
value={content} value={content}
onChange={(e) => setContent(e.target.value)} onChange={(e) => setContent(e.target.value)}
required required
rows={12} rows={14}
className="w-full px-3 py-2 rounded-lg border resize-y font-mono" className="field"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/> />
</div> </div>
<div className="flex gap-3">
<div className="flex gap-3 pt-2">
<button <button
type="submit" type="submit"
disabled={loading || !title.trim() || !content.trim()} disabled={loading || !title.trim() || !content.trim()}
className="px-6 py-2 rounded-lg text-white disabled:opacity-50" className="btn btn-primary"
style={{ background: "var(--primary)" }}
> >
{loading ? "保存中..." : "保存修改"} {loading ? "保存中..." : "保存修改"}
</button> </button>
<button <button
type="button" type="button"
onClick={() => router.push(`/post/${post.id}`)} onClick={() => router.push(`/post/${post.id}`)}
className="px-6 py-2 rounded-lg" className="btn btn-line"
style={{ background: "var(--bg-secondary)", color: "var(--text)" }}
> >
取消 取消
</button> </button>

View File

@@ -1,4 +1,4 @@
import { Metadata } from "next"; import type { Metadata } from "next";
import Link from "next/link"; import Link from "next/link";
import { cookies } from "next/headers"; import { cookies } from "next/headers";
import ReactMarkdown from "react-markdown"; import ReactMarkdown from "react-markdown";
@@ -6,6 +6,10 @@ import { fetchPostDetail, fetchComments } from "@/lib/api";
import CommentSection from "@/components/CommentSection"; import CommentSection from "@/components/CommentSection";
import PostActions from "@/components/PostActions"; import PostActions from "@/components/PostActions";
import LikeButton from "@/components/LikeButton"; import LikeButton from "@/components/LikeButton";
import ReadingProgress from "@/components/ReadingProgress";
import Avatar from "@/components/Avatar";
import { IconComment, IconEye } from "@/components/Icons";
import { ChevronRight } from "lucide-react";
interface PageProps { interface PageProps {
params: Promise<{ id: string }>; params: Promise<{ id: string }>;
@@ -16,7 +20,7 @@ export async function generateMetadata({ params }: PageProps): Promise<Metadata>
try { try {
const { post } = await fetchPostDetail(id); const { post } = await fetchPostDetail(id);
return { return {
title: `${post.title} - 姜十三论坛`, title: post.title,
description: post.content.slice(0, 160), description: post.content.slice(0, 160),
openGraph: { openGraph: {
title: post.title, title: post.title,
@@ -25,7 +29,7 @@ export async function generateMetadata({ params }: PageProps): Promise<Metadata>
}, },
}; };
} catch { } catch {
return { title: "帖子不存在 - 姜十三论坛" }; return { title: "帖子不存在" };
} }
} }
@@ -42,10 +46,7 @@ export default async function PostDetailPage({ params }: PageProps) {
articleBody: post.content, articleBody: post.content,
datePublished: post.created_at, datePublished: post.created_at,
dateModified: post.updated_at, dateModified: post.updated_at,
author: { author: { "@type": "Person", name: post.user.nickname },
"@type": "Person",
name: post.user.nickname,
},
commentCount: post.comment_count, commentCount: post.comment_count,
interactionStatistic: { interactionStatistic: {
"@type": "InteractionCounter", "@type": "InteractionCounter",
@@ -56,43 +57,80 @@ export default async function PostDetailPage({ params }: PageProps) {
return ( return (
<article className="max-w-3xl mx-auto"> <article className="max-w-3xl mx-auto">
<script <ReadingProgress />
type="application/ld+json" <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} />
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
<nav className="text-sm mb-4" style={{ color: "var(--text-secondary)" }}> <nav className="meta mb-5 flex items-center gap-1.5 flex-wrap text-[13px]">
<Link href="/" className="hover:underline">首页</Link> <Link href="/" className="hover:text-[var(--accent)] transition-colors">首页</Link>
<span className="mx-2">/</span> <ChevronRight size={13} />
<Link href={`/board/${post.board.id}`} className="hover:underline">{post.board.name}</Link> <Link href={`/board/${post.board.id}`} className="hover:text-[var(--accent)] transition-colors">
{post.board.name}
</Link>
</nav> </nav>
<div className="flex items-center gap-2 mb-3"> <div className="panel p-6 sm:p-9">
{post.pinned > 0 && ( <header className="mb-7">
<span className="text-xs px-2 py-0.5 rounded bg-amber-100 text-amber-700">置顶</span> <div className="flex items-center gap-2 mb-4 flex-wrap">
)} {post.pinned > 0 && <span className="badge-pin">置顶</span>}
{post.recommended && ( {post.recommended && <span className="badge-rec">推荐</span>}
<span className="text-xs px-2 py-0.5 rounded bg-rose-100 text-rose-700">推荐</span> <Link href={`/board/${post.board.id}`} className="chip">
)} {post.board.name}
</div>
<h1 className="text-3xl font-bold mb-4">{post.title}</h1>
<div className="flex items-center justify-between gap-4 mb-6 pb-4 border-b" style={{ borderColor: "var(--border)" }}>
<div className="flex items-center gap-4" style={{ color: "var(--text-secondary)" }}>
<Link href={`/u/${post.user.id}`} className="hover:underline" style={{ color: "var(--primary)" }}>
{post.user.nickname}
</Link> </Link>
<span>{new Date(post.created_at).toLocaleString("zh-CN")}</span>
<span>👁 {post.view_count}</span>
<span>💬 {post.comment_count}</span>
<LikeButton postId={id} liked={post.liked} likeCount={post.like_count} />
</div> </div>
<h1 className="text-[26px] sm:text-[34px] font-extrabold leading-tight tracking-tight mb-6" style={{ color: "var(--ink)" }}>
{post.title}
</h1>
<div
className="flex items-center justify-between gap-4 flex-wrap pb-5"
style={{ borderBottom: "1px solid var(--line)" }}
>
<div className="flex items-center gap-4 flex-wrap">
<Link
href={`/u/${post.user.id}`}
className="flex items-center gap-2.5 group"
>
<Avatar name={post.user.nickname || post.user.username} size={40} />
<span className="text-sm font-semibold group-hover:text-[var(--accent)] transition-colors" style={{ color: "var(--ink)" }}>
{post.user.nickname}
</span>
</Link>
<span className="meta">{new Date(post.created_at).toLocaleString("zh-CN")}</span>
<span className="inline-flex items-center gap-1.5 meta">
<IconEye size={14} /> {post.view_count}
</span>
<span className="inline-flex items-center gap-1.5 meta">
<IconComment size={14} /> {post.comment_count}
</span>
</div>
<div className="flex items-center gap-2">
<LikeButton postId={id} liked={post.liked} likeCount={post.like_count} />
<PostActions postId={id} authorId={post.user.id} pinned={post.pinned} recommended={post.recommended} /> <PostActions postId={id} authorId={post.user.id} pinned={post.pinned} recommended={post.recommended} />
</div> </div>
</div>
</header>
<div className="prose-content mb-8" style={{ color: "var(--text)" }}> {post.tags && (
<div className="flex flex-wrap gap-2 mb-7">
{[
...new Set(
post.tags
.split(",")
.map((t) => t.trim())
.filter(Boolean)
),
].map((t, i) => (
<span key={`${t}-${i}`} className="chip">
# {t}
</span>
))}
</div>
)}
<div className="prose-content">
<ReactMarkdown>{post.content}</ReactMarkdown> <ReactMarkdown>{post.content}</ReactMarkdown>
</div> </div>
</div>
<CommentSection postId={id} comments={comments} /> <CommentSection postId={id} comments={comments} />
</article> </article>

View File

@@ -3,6 +3,7 @@
import { useState } from "react"; import { useState } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import Link from "next/link"; import Link from "next/link";
import { UserPlus } from "lucide-react";
import { apiRegister } from "@/lib/api"; import { apiRegister } from "@/lib/api";
export default function RegisterPage() { export default function RegisterPage() {
@@ -30,14 +31,26 @@ export default function RegisterPage() {
}; };
return ( return (
<div className="max-w-md mx-auto mt-12"> <div className="max-w-md mx-auto pt-8 sm:pt-14">
<h1 className="text-2xl font-bold mb-6 text-center">注册</h1> <div className="mb-7 text-center">
<form onSubmit={handleSubmit} className="space-y-4"> <span
{error && ( className="inline-flex w-14 h-14 rounded-2xl items-center justify-center mb-4"
<div className="p-3 rounded-lg bg-red-50 text-red-600 text-sm">{error}</div> style={{ background: "var(--accent-soft)", color: "var(--accent)" }}
)} >
<UserPlus size={26} />
</span>
<h1 className="text-[28px] font-extrabold tracking-tight" style={{ color: "var(--ink)" }}>
创建账号
</h1>
<p className="text-sm mt-2" style={{ color: "var(--ink-2)" }}>
加入姜十三,开始你的第一帖
</p>
</div>
<form onSubmit={handleSubmit} className="panel p-6 sm:p-7 space-y-4">
{error && <div className="alert-error">{error}</div>}
<div> <div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>用户名</label> <label className="field-label">用户名</label>
<input <input
type="text" type="text"
value={username} value={username}
@@ -45,43 +58,43 @@ export default function RegisterPage() {
required required
minLength={3} minLength={3}
maxLength={32} maxLength={32}
className="w-full px-3 py-2 rounded-lg border" autoFocus
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }} className="field"
placeholder="3–32 位"
/> />
</div> </div>
<div> <div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>邮箱(可选)</label> <label className="field-label">邮箱(可选)</label>
<input <input
type="email" type="email"
value={email} value={email}
onChange={(e) => setEmail(e.target.value)} onChange={(e) => setEmail(e.target.value)}
className="w-full px-3 py-2 rounded-lg border" className="field"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }} placeholder="you@example.com"
/> />
</div> </div>
<div> <div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>密码</label> <label className="field-label">密码</label>
<input <input
type="password" type="password"
value={password} value={password}
onChange={(e) => setPassword(e.target.value)} onChange={(e) => setPassword(e.target.value)}
required required
minLength={6} minLength={6}
className="w-full px-3 py-2 rounded-lg border" className="field"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }} placeholder="至少 6 位"
/> />
</div> </div>
<button <button type="submit" disabled={loading} className="btn btn-primary w-full justify-center mt-2">
type="submit"
disabled={loading}
className="w-full py-2 rounded-lg text-white disabled:opacity-50"
style={{ background: "var(--primary)" }}
>
{loading ? "注册中..." : "注册"} {loading ? "注册中..." : "注册"}
</button> </button>
</form> </form>
<p className="text-center mt-4 text-sm" style={{ color: "var(--text-secondary)" }}>
已有账号?<Link href="/login" className="hover:underline" style={{ color: "var(--primary)" }}>去登录</Link> <p className="meta text-center mt-5">
已有账号?
<Link href="/login" className="ml-1 font-semibold" style={{ color: "var(--accent)" }}>
去登录
</Link>
</p> </p>
</div> </div>
); );

View File

@@ -3,7 +3,9 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import Link from "next/link"; import Link from "next/link";
import { ChevronRight } from "lucide-react";
import { apiChangePassword, apiMe, type User } from "@/lib/api"; import { apiChangePassword, apiMe, type User } from "@/lib/api";
import Avatar from "@/components/Avatar";
export default function SettingsPage() { export default function SettingsPage() {
const router = useRouter(); const router = useRouter();
@@ -57,79 +59,78 @@ export default function SettingsPage() {
}; };
if (!user) { if (!user) {
return <p style={{ color: "var(--text-secondary)" }}>加载中...</p>; return (
<div className="max-w-md mx-auto text-center py-20">
<p className="meta">正在加载…</p>
</div>
);
} }
return ( return (
<div className="max-w-md mx-auto"> <div className="max-w-md mx-auto">
<nav className="text-sm mb-4" style={{ color: "var(--text-secondary)" }}> <nav className="meta mb-5 flex items-center gap-1.5 text-[13px]">
<Link href="/" className="hover:underline">首页</Link> <Link href="/" className="hover:text-[var(--accent)] transition-colors">首页</Link>
<span className="mx-2">/</span> <ChevronRight size={13} />
<span>账号设置</span> <span style={{ color: "var(--accent)" }}>账号设置</span>
</nav> </nav>
<h1 className="text-2xl font-bold mb-6">账号设置</h1> <div className="mb-7">
<h1 className="text-[26px] sm:text-[30px] font-extrabold tracking-tight" style={{ color: "var(--ink)" }}>
<div className="p-4 rounded-lg mb-6" style={{ background: "var(--bg-secondary)" }}> 账号设置
<div className="text-sm" style={{ color: "var(--text-secondary)" }}>当前账号</div> </h1>
<div className="font-medium mt-1" style={{ color: "var(--text)" }}>{user.nickname}({user.username})</div>
</div> </div>
<h2 className="text-lg font-semibold mb-4">修改密码</h2> <div className="panel p-5 mb-7 flex items-center gap-4">
<Avatar name={user.nickname || user.username} size={46} />
{success && ( <div className="min-w-0">
<div className="p-3 rounded-lg mb-4 text-sm" style={{ background: "var(--success-bg, #dcfce7)", color: "#166534" }}> <div className="font-bold truncate" style={{ color: "var(--ink)" }}>
密码修改成功,正在跳转登录页... {user.nickname}
</div>
<div className="meta">@{user.username} · {user.role === "admin" ? "管理员" : "普通用户"}</div>
</div> </div>
)}
{error && (
<div className="p-3 rounded-lg mb-4 text-sm" style={{ background: "var(--error-bg, #fee2e2)", color: "#991b1b" }}>
{error}
</div> </div>
)}
<form onSubmit={handleSubmit} className="space-y-4"> <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> <div>
<label className="block text-sm font-medium mb-1" style={{ color: "var(--text)" }}>当前密码</label> <label className="field-label">当前密码</label>
<input <input
type="password" type="password"
value={oldPassword} value={oldPassword}
onChange={(e) => setOldPassword(e.target.value)} onChange={(e) => setOldPassword(e.target.value)}
required required
className="w-full p-3 rounded-lg border" className="field"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/> />
</div> </div>
<div> <div>
<label className="block text-sm font-medium mb-1" style={{ color: "var(--text)" }}>新密码</label> <label className="field-label">新密码(至少 6 位)</label>
<input <input
type="password" type="password"
value={newPassword} value={newPassword}
onChange={(e) => setNewPassword(e.target.value)} onChange={(e) => setNewPassword(e.target.value)}
required required
minLength={6} minLength={6}
className="w-full p-3 rounded-lg border" className="field"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/> />
</div> </div>
<div> <div>
<label className="block text-sm font-medium mb-1" style={{ color: "var(--text)" }}>确认新密码</label> <label className="field-label">确认新密码</label>
<input <input
type="password" type="password"
value={confirmPassword} value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)} onChange={(e) => setConfirmPassword(e.target.value)}
required required
minLength={6} minLength={6}
className="w-full p-3 rounded-lg border" className="field"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/> />
</div> </div>
<button <button
type="submit" type="submit"
disabled={submitting || success} disabled={submitting || success}
className="w-full py-3 rounded-lg text-white font-medium disabled:opacity-50" className="btn btn-primary w-full justify-center mt-2"
style={{ background: "var(--primary)" }}
> >
{submitting ? "提交中..." : "修改密码"} {submitting ? "提交中..." : "修改密码"}
</button> </button>

View File

@@ -2,8 +2,10 @@
import { useState } from "react"; import { useState } from "react";
import Link from "next/link"; import Link from "next/link";
import { FileText, MessageCircle } from "lucide-react";
import { fetchUserComments, type UserProfile, type UserCommentsResponse } from "@/lib/api"; import { fetchUserComments, type UserProfile, type UserCommentsResponse } from "@/lib/api";
import Pagination from "@/components/Pagination"; import Pagination from "@/components/Pagination";
import { IconComment, IconEye, IconHeart } from "@/components/Icons";
interface UserProfileClientProps { interface UserProfileClientProps {
userId: string; userId: string;
@@ -38,65 +40,85 @@ export default function UserProfileClient({ userId, initialPosts, initialPage }:
} }
}; };
const tabBtn = (t: Tab, label: string) => ( const tabBtn = (t: Tab, label: string, count: number, icon: React.ReactNode) => {
const active = tab === t;
return (
<button <button
onClick={() => handleTabChange(t)} onClick={() => handleTabChange(t)}
className="px-4 py-2 rounded-lg text-sm font-medium transition-colors" 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={ style={{
tab === t background: active ? "var(--panel)" : "transparent",
? { background: "var(--primary)", color: "white" } color: active ? "var(--accent)" : "var(--ink-3)",
: { background: "var(--bg-secondary)", color: "var(--text-secondary)" } boxShadow: active ? "var(--shadow-sm)" : "none",
} }}
> >
{icon}
{label} {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> </button>
); );
};
return ( return (
<div> <div>
<div className="flex gap-2 mb-5"> <div
{tabBtn("posts", `发帖 (${initialPosts.stats.post_count})`)} className="inline-flex w-full sm:w-auto items-center gap-1 mb-6 p-1 rounded-full"
{tabBtn("comments", `评论 (${initialPosts.stats.comment_count})`)} style={{ background: "var(--panel-2)" }}
>
{tabBtn("posts", "发帖", initialPosts.stats.post_count, <FileText size={15} />)}
{tabBtn("comments", "评论", initialPosts.stats.comment_count, <MessageCircle size={15} />)}
</div> </div>
{tab === "posts" ? ( {tab === "posts" ? (
<div className="space-y-3"> <div>
{initialPosts.posts.map((post) => ( {initialPosts.posts.length > 0 ? (
<div className="panel overflow-hidden p-0">
{initialPosts.posts.map((post, i) => (
<Link <Link
key={post.id} key={post.id}
href={`/post/${post.id}`} href={`/post/${post.id}`}
className="block p-4 rounded-lg border hover:shadow-md transition-shadow" className="block px-4 sm:px-5 py-4 transition-colors hover:bg-[var(--panel-2)]"
style={{ borderColor: "var(--border)", background: "var(--bg)" }} style={{ borderTop: i === 0 ? "none" : "1px solid var(--line)" }}
> >
<div className="flex items-center gap-2 mb-2"> <div className="flex items-center gap-2 mb-2 flex-wrap">
<span <span className="chip">{post.board.name}</span>
className="text-xs px-2 py-0.5 rounded" {post.pinned > 0 && <span className="badge-pin">置顶</span>}
style={{ background: "var(--bg-secondary)", color: "var(--primary)" }} {post.recommended && <span className="badge-rec">推荐</span>}
>
{post.board.name}
</span>
{post.pinned > 0 && (
<span className="text-xs px-2 py-0.5 rounded bg-amber-100 text-amber-700">置顶</span>
)}
{post.recommended && (
<span className="text-xs px-2 py-0.5 rounded bg-rose-100 text-rose-700">推荐</span>
)}
</div> </div>
<h2 className="font-semibold mb-1 hover:underline" style={{ color: "var(--text)" }}> <h2
className="font-semibold mb-2 leading-snug group-hover:text-[var(--accent)]"
style={{ color: "var(--ink)" }}
>
{post.title} {post.title}
</h2> </h2>
<div className="flex items-center gap-4 text-sm" style={{ color: "var(--text-secondary)" }}> <div className="flex items-center gap-4 meta text-[12px]">
<span>{new Date(post.created_at).toLocaleDateString("zh-CN")}</span> <span>{new Date(post.created_at).toLocaleDateString("zh-CN")}</span>
<span>💬 {post.comment_count}</span> <span className="inline-flex items-center gap-1">
<span>👁 {post.view_count}</span> <IconComment size={12} /> {post.comment_count}
<span>❤️ {post.like_count}</span> </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> </div>
</Link> </Link>
))} ))}
{initialPosts.posts.length === 0 && ( </div>
<p className="text-center py-12" style={{ color: "var(--text-secondary)" }}> ) : (
暂无发帖 <div className="panel text-center py-16 px-6">
</p> <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 <Pagination
total={initialPosts.posts_total} total={initialPosts.posts_total}
@@ -106,27 +128,36 @@ export default function UserProfileClient({ userId, initialPosts, initialPage }:
/> />
</div> </div>
) : ( ) : (
<div className="space-y-3"> <div>
{commentLoading ? ( {commentLoading ? (
<p className="text-center py-12" style={{ color: "var(--text-secondary)" }}>加载中...</p> <div className="panel text-center py-16">
<p className="meta">正在加载评论…</p>
</div>
) : commentData && commentData.comments.length > 0 ? ( ) : commentData && commentData.comments.length > 0 ? (
<> <>
{commentData.comments.map((c) => ( <div className="panel overflow-hidden p-0">
{commentData.comments.map((c, i) => (
<Link <Link
key={c.id} key={c.id}
href={`/post/${c.post_id}`} href={`/post/${c.post_id}`}
className="block p-4 rounded-lg border hover:shadow-md transition-shadow" className="block px-4 sm:px-5 py-4 transition-colors hover:bg-[var(--panel-2)]"
style={{ borderColor: "var(--border)", background: "var(--bg)" }} style={{ borderTop: i === 0 ? "none" : "1px solid var(--line)" }}
> >
<div className="text-sm mb-2" style={{ color: "var(--text-secondary)" }}> <div className="meta text-xs mb-2">
评论于 <span className="hover:underline" style={{ color: "var(--primary)" }}>{c.post_title}</span> 评论于《<span style={{ color: "var(--accent)" }}>{c.post_title}</span>》
</div> </div>
<p className="line-clamp-2" style={{ color: "var(--text)" }}>{c.content}</p> <p
<div className="text-xs mt-2" style={{ color: "var(--text-secondary)" }}> 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")} {new Date(c.created_at).toLocaleString("zh-CN")}
</div> </div>
</Link> </Link>
))} ))}
</div>
<Pagination <Pagination
total={commentData.total} total={commentData.total}
page={commentPage} page={commentPage}
@@ -137,9 +168,10 @@ export default function UserProfileClient({ userId, initialPosts, initialPage }:
/> />
</> </>
) : ( ) : (
<p className="text-center py-12" style={{ color: "var(--text-secondary)" }}> <div className="panel text-center py-16 px-6">
暂无评论 <MessageCircle size={26} className="mx-auto mb-3" style={{ color: "var(--ink-3)" }} />
</p> <p className="text-sm font-semibold" style={{ color: "var(--ink-2)" }}>暂无评论</p>
</div>
)} )}
</div> </div>
)} )}

View File

@@ -1,8 +1,9 @@
import Link from "next/link"; import Link from "next/link";
import { Metadata } from "next"; import { Metadata } from "next";
import { ChevronRight, FileText, MessageCircle } from "lucide-react";
import { fetchUserProfile, type UserProfile } from "@/lib/api"; import { fetchUserProfile, type UserProfile } from "@/lib/api";
import Pagination from "@/components/Pagination";
import UserProfileClient from "./UserProfileClient"; import UserProfileClient from "./UserProfileClient";
import Avatar from "@/components/Avatar";
interface UserPageProps { interface UserPageProps {
params: Promise<{ id: string }>; params: Promise<{ id: string }>;
@@ -11,10 +12,15 @@ interface UserPageProps {
export async function generateMetadata({ params }: UserPageProps): Promise<Metadata> { export async function generateMetadata({ params }: UserPageProps): Promise<Metadata> {
const { id } = await params; const { id } = await params;
try {
const data = await fetchUserProfile(id, 1);
return { return {
title: `用户资料 - 姜十三论坛`, title: data.user.nickname || data.user.username,
description: `查看用户 ${id} 的资料、发帖与评论`, description: `查看 ${data.user.nickname} 的资料、发帖与评论`,
}; };
} catch {
return { title: "用户不存在" };
}
} }
export default async function UserPage({ params, searchParams }: UserPageProps) { export default async function UserPage({ params, searchParams }: UserPageProps) {
@@ -27,9 +33,12 @@ export default async function UserPage({ params, searchParams }: UserPageProps)
data = await fetchUserProfile(id, page); data = await fetchUserProfile(id, page);
} catch { } catch {
return ( return (
<div className="text-center py-16" style={{ color: "var(--text-secondary)" }}> <div className="max-w-md mx-auto text-center py-24">
<p className="text-lg">用户不存在</p> <p className="text-lg font-extrabold mb-1.5" style={{ color: "var(--ink)" }}>
<Link href="/" className="mt-4 inline-block hover:underline" style={{ color: "var(--primary)" }}> 用户不存在
</p>
<p className="meta mb-5">该用户可能已注销或链接有误</p>
<Link href="/" className="btn btn-line btn-sm">
返回首页 返回首页
</Link> </Link>
</div> </div>
@@ -37,54 +46,65 @@ export default async function UserPage({ params, searchParams }: UserPageProps)
} }
const u = data.user; const u = data.user;
const roleLabel = u.role === "admin" ? "管理员" : "用户"; const stats = [
{ label: "发帖", value: data.stats.post_count, icon: <FileText size={15} /> },
{ label: "评论", value: data.stats.comment_count, icon: <MessageCircle size={15} /> },
];
return ( return (
<div className="max-w-4xl mx-auto"> <div className="max-w-4xl mx-auto">
<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)" }}>{u.nickname || u.username}</span>
</nav>
{/* 用户信息卡片 */} {/* 用户信息卡片 */}
<div <section className="panel relative overflow-hidden p-6 sm:p-8 mb-6">
className="rounded-xl border p-6 mb-6 flex items-start gap-5" <span
style={{ borderColor: "var(--border)", background: "var(--bg)" }} aria-hidden
> className="absolute -top-20 -right-16 w-60 h-60 rounded-full"
<div style={{ background: "var(--accent-soft)" }}
className="w-20 h-20 rounded-full flex items-center justify-center text-2xl font-bold shrink-0" />
style={{ background: "var(--bg-secondary)", color: "var(--primary)" }} <div className="relative flex items-start gap-5 sm:gap-6">
> <Avatar
{u.avatar ? ( name={u.nickname || u.username}
<img src={u.avatar} alt={u.nickname} className="w-full h-full rounded-full object-cover" /> src={u.avatar || undefined}
) : ( size={80}
(u.nickname || u.username).charAt(0).toUpperCase() className="sm:!w-[88px] sm:!h-[88px]"
)} />
</div>
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap"> <div className="flex items-center gap-2.5 flex-wrap">
<h1 className="text-2xl font-bold" style={{ color: "var(--text)" }}> <h1 className="text-[24px] sm:text-[28px] font-extrabold tracking-tight" style={{ color: "var(--ink)" }}>
{u.nickname || u.username} {u.nickname || u.username}
</h1> </h1>
{u.role === "admin" && ( {u.role === "admin" && (
<span <span
className="text-xs px-2 py-0.5 rounded font-medium" className="text-[11.5px] font-bold px-2.5 py-1 rounded-full"
style={{ background: "var(--primary)", color: "white" }} style={{ background: "var(--gold-soft)", color: "var(--gold)" }}
> >
{roleLabel} 管理员
</span> </span>
)} )}
</div> </div>
<p className="text-sm mt-1" style={{ color: "var(--text-secondary)" }}> <p className="meta mt-1.5 text-[13px]">
@{u.username} · 加入于 {new Date(u.created_at).toLocaleDateString("zh-CN")} @{u.username} · {new Date(u.created_at).toLocaleDateString("zh-CN")} 加入
</p> </p>
<div className="flex gap-6 mt-3 text-sm"> <div className="flex gap-2.5 mt-4">
<span style={{ color: "var(--text)" }}> {stats.map((s) => (
<strong>{data.stats.post_count}</strong>{" "} <span
<span style={{ color: "var(--text-secondary)" }}>帖子</span> key={s.label}
</span> className="inline-flex items-center gap-2 px-3.5 py-2 rounded-full text-[13px] font-semibold"
<span style={{ color: "var(--text)" }}> style={{ background: "var(--panel-2)", color: "var(--ink-2)" }}
<strong>{data.stats.comment_count}</strong>{" "} >
<span style={{ color: "var(--text-secondary)" }}>评论</span> <span style={{ color: "var(--accent)" }}>{s.icon}</span>
{s.value} {s.label}
</span> </span>
))}
</div> </div>
</div> </div>
</div> </div>
</section>
{/* 发帖 / 评论 切换 */} {/* 发帖 / 评论 切换 */}
<UserProfileClient userId={id} initialPosts={data} initialPage={page} /> <UserProfileClient userId={id} initialPosts={data} initialPage={page} />

View File

@@ -0,0 +1,35 @@
// 柔和多色头像:按用户名确定性取色,圆形软底,浅/暗主题在 globals.css 各自配色
function hash(s: string) {
let h = 0;
for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0;
return h;
}
export default function Avatar({
name,
size = 36,
src,
className = "",
}: {
name: string;
size?: number;
src?: string | null;
className?: string;
}) {
const idx = hash(name || "?") % 8;
const initial = (name || "?").trim().charAt(0).toUpperCase();
return (
<span
className={`inline-flex items-center justify-center shrink-0 select-none font-bold rounded-full overflow-hidden av-${idx} ${className}`}
style={{ width: size, height: size, fontSize: size * 0.42 }}
aria-hidden="true"
>
{src ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={src} alt="" className="w-full h-full object-cover" />
) : (
initial
)}
</span>
);
}

View File

@@ -3,8 +3,10 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import Link from "next/link"; import Link from "next/link";
import { Trash2 } from "lucide-react"; import { Trash2, MessagesSquare } from "lucide-react";
import { apiCreateComment, apiDeleteComment, apiMe, type Comment, type User } from "@/lib/api"; import { apiCreateComment, apiDeleteComment, apiMe, type Comment, type User } from "@/lib/api";
import { toast } from "@/lib/toast";
import Avatar from "./Avatar";
interface CommentSectionProps { interface CommentSectionProps {
postId: string; postId: string;
@@ -27,7 +29,6 @@ export default function CommentSection({ postId, comments }: CommentSectionProps
const handleSubmit = async (e: React.FormEvent) => { const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
if (!content.trim()) return; if (!content.trim()) return;
setSubmitting(true); setSubmitting(true);
try { try {
const res = await apiCreateComment(postId, content); const res = await apiCreateComment(postId, content);
@@ -35,10 +36,12 @@ export default function CommentSection({ postId, comments }: CommentSectionProps
setContent(""); setContent("");
router.refresh(); router.refresh();
} else if (res.error === "未登录") { } else if (res.error === "未登录") {
router.push("/login"); router.push(`/login?redirect=${encodeURIComponent(`/post/${postId}`)}`);
} else { } else {
alert(res.error || "评论失败"); toast(res.error || "评论失败");
} }
} catch {
toast("网络错误,评论失败");
} finally { } finally {
setSubmitting(false); setSubmitting(false);
} }
@@ -52,8 +55,10 @@ export default function CommentSection({ postId, comments }: CommentSectionProps
if (res.message) { if (res.message) {
router.refresh(); router.refresh();
} else { } else {
alert(res.error || "删除失败"); toast(res.error || "删除失败");
} }
} catch {
toast("网络错误,删除失败");
} finally { } finally {
setDeletingId(null); setDeletingId(null);
} }
@@ -63,57 +68,103 @@ export default function CommentSection({ postId, comments }: CommentSectionProps
user && (user.id === comment.user.id || user.role === "admin"); user && (user.id === comment.user.id || user.role === "admin");
return ( return (
<section className="mt-8 pt-6 border-t" style={{ borderColor: "var(--border)" }}> <section className="panel p-6 sm:p-8 mt-6">
<h2 className="text-xl font-bold mb-4">评论 ({comments.length})</h2> <div className="flex items-center gap-2.5 mb-6">
<h2 className="text-lg font-extrabold" style={{ color: "var(--ink)" }}>
评论
</h2>
<span
className="text-[12px] font-bold px-2 py-0.5 rounded-full"
style={{ background: "var(--accent-soft)", color: "var(--accent)" }}
>
{comments.length}
</span>
</div>
<form onSubmit={handleSubmit} className="mb-6"> {user ? (
<form onSubmit={handleSubmit} className="mb-8">
<textarea <textarea
value={content} value={content}
onChange={(e) => setContent(e.target.value)} onChange={(e) => setContent(e.target.value)}
placeholder="写下你的评论..." onKeyDown={(e) => {
className="w-full p-3 rounded-lg border resize-none h-24" if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }} e.preventDefault();
e.currentTarget.form?.requestSubmit();
}
}}
placeholder="友善发言,说说你的看法..."
rows={3}
className="field"
/> />
<button <div className="flex items-center justify-between gap-3 mt-2.5">
type="submit" <span className="meta text-[11.5px]">支持 Markdown · Ctrl + Enter 发送</span>
disabled={submitting || !content.trim()} <button type="submit" disabled={submitting || !content.trim()} className="btn btn-primary">
className="mt-2 px-4 py-2 rounded-lg text-white disabled:opacity-50"
style={{ background: "var(--primary)" }}
>
{submitting ? "发送中..." : "发表评论"} {submitting ? "发送中..." : "发表评论"}
</button> </button>
</div>
</form> </form>
) : (
<div className="space-y-4"> <div
{comments.map((comment) => ( className="mb-8 px-5 py-4 rounded-2xl flex items-center justify-between gap-4 flex-wrap"
<div key={comment.id} className="p-4 rounded-lg" style={{ background: "var(--bg-secondary)" }}> style={{ background: "var(--panel-2)" }}
<div className="flex items-center justify-between mb-2"> >
<div className="flex items-center gap-2"> <span className="text-sm" style={{ color: "var(--ink-2)" }}>
<Link href={`/u/${comment.user.id}`} className="font-medium hover:underline" style={{ color: "var(--primary)" }}> 登录后参与讨论
{comment.user.nickname}
</Link>
<span className="text-sm" style={{ color: "var(--text-secondary)" }}>
{new Date(comment.created_at).toLocaleString("zh-CN")}
</span> </span>
<Link href="/login" className="btn btn-line btn-sm">
去登录
</Link>
</div>
)}
<div>
{comments.map((comment) => (
<div
key={comment.id}
className="flex gap-3.5 py-5 border-t first:border-t-0"
style={{ borderColor: "var(--line)" }}
>
<Link href={`/u/${comment.user.id}`} className="shrink-0 mt-0.5" aria-label={comment.user.nickname}>
<Avatar name={comment.user.nickname || comment.user.username} size={38} />
</Link>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-3 mb-1.5">
<div className="flex items-center gap-2.5 min-w-0 flex-wrap">
<Link href={`/u/${comment.user.id}`} className="group">
<span
className="text-sm font-semibold truncate group-hover:text-[var(--accent)] transition-colors"
style={{ color: "var(--ink)" }}
>
{comment.user.nickname}
</span>
</Link>
<span className="meta text-xs">{new Date(comment.created_at).toLocaleString("zh-CN")}</span>
</div> </div>
{canDelete(comment) && ( {canDelete(comment) && (
<button <button
onClick={() => handleDelete(comment.id)} onClick={() => handleDelete(comment.id)}
disabled={deletingId === comment.id} disabled={deletingId === comment.id}
className="flex items-center gap-1 text-sm text-red-600 hover:opacity-80 disabled:opacity-50" className="meta hover:text-[var(--danger)] transition-colors disabled:opacity-50 p-1"
aria-label="删除评论"
> >
<Trash2 size={14} /> <Trash2 size={14} />
{deletingId === comment.id ? "删除中" : "删除"}
</button> </button>
)} )}
</div> </div>
<p style={{ color: "var(--text)" }}>{comment.content}</p> <p className="text-[15px] leading-relaxed" style={{ color: "var(--ink)" }}>
{comment.content}
</p>
</div>
</div> </div>
))} ))}
{comments.length === 0 && ( {comments.length === 0 && (
<p className="text-center py-8" style={{ color: "var(--text-secondary)" }}> <div className="text-center py-14">
暂无评论,来抢沙发吧! <MessagesSquare size={28} className="mx-auto mb-3" style={{ color: "var(--ink-3)" }} />
<p className="text-sm font-semibold" style={{ color: "var(--ink-2)" }}>
暂无评论
</p> </p>
<p className="meta text-[12.5px] mt-1">来说两句,抢占沙发</p>
</div>
)} )}
</div> </div>
</section> </section>

View File

@@ -0,0 +1,95 @@
import Link from "next/link";
import type { PostListItem } from "@/lib/api";
import LikeButton from "./LikeButton";
import Avatar from "./Avatar";
import { IconComment, IconEye } from "./Icons";
function formatTime(dateStr: string) {
return new Date(dateStr).toLocaleDateString("zh-CN");
}
/**
* 首页精选主卡:取自非置顶帖中的最新一帖(置顶帖由 PinnedPosts 承载)
*/
export default function FeaturePost({ post }: { post: PostListItem }) {
return (
<article className="panel hover-lift group relative overflow-hidden">
{/* 柔和装饰块,非发光 */}
<span
aria-hidden
className="absolute -top-20 -right-16 w-56 h-56 rounded-full"
style={{ background: "var(--accent-soft)" }}
/>
<div className="relative p-6 sm:p-8">
<div className="flex items-center gap-2 mb-4 flex-wrap">
<span
className="inline-flex items-center gap-1.5 text-[12.5px] font-bold"
style={{ color: "var(--accent)" }}
>
<span className="w-1.5 h-1.5 rounded-full" style={{ background: "var(--accent)" }} />
今日精选
</span>
{post.recommended && <span className="badge-rec">推荐</span>}
<Link href={`/board/${post.board.id}`} className="chip">
{post.board.name}
</Link>
</div>
<Link href={`/post/${post.id}`}>
<h2
className="font-extrabold text-2xl sm:text-[28px] leading-tight tracking-tight transition-colors group-hover:text-[var(--accent)]"
style={{ color: "var(--ink)" }}
>
{post.title}
</h2>
</Link>
{post.tags && (
<div className="flex flex-wrap gap-2 mt-4">
{[
...new Set(
post.tags
.split(",")
.map((t) => t.trim())
.filter(Boolean)
),
]
.slice(0, 4)
.map((t, i) => (
<span key={`${t}-${i}`} className="chip">
# {t}
</span>
))}
</div>
)}
<div className="flex items-center justify-between gap-4 mt-6 pt-5" style={{ borderTop: "1px solid var(--line)" }}>
<div className="flex items-center gap-4 min-w-0">
<Link href={`/u/${post.user.id}`} className="flex items-center gap-2.5 min-w-0 group/au">
<Avatar name={post.user.nickname || post.user.username} size={38} />
<span className="min-w-0">
<span
className="block text-sm font-semibold truncate group-hover/au:text-[var(--accent)] transition-colors"
style={{ color: "var(--ink)" }}
>
{post.user.nickname}
</span>
<span className="meta block text-[11.5px]">{formatTime(post.created_at)}</span>
</span>
</Link>
<span className="hidden sm:inline-flex items-center gap-1.5 meta">
<IconComment size={14} /> {post.comment_count}
</span>
<span className="hidden sm:inline-flex items-center gap-1.5 meta">
<IconEye size={14} /> {post.view_count}
</span>
</div>
<LikeButton
postId={String(post.id)}
liked={post.liked}
likeCount={post.like_count}
/>
</div>
</div>
</article>
);
}

View File

@@ -1,7 +1,35 @@
import Link from "next/link";
export default function Footer() { export default function Footer() {
return ( return (
<footer className="border-t py-6 text-center text-sm" style={{ borderColor: "var(--border)", color: "var(--text-secondary)" }}> <footer className="mt-14" style={{ borderTop: "1px solid var(--line)" }}>
<p>姜十三论坛 · Powered by Go 1.27 + Next.js 16</p> <div className="max-w-6xl mx-auto px-4 sm:px-6 py-8 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
<div className="flex items-center gap-2.5">
<span
className="w-7 h-7 rounded-lg flex items-center justify-center"
style={{ background: "var(--accent)", color: "var(--accent-on)" }}
>
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
<path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" />
</svg>
</span>
<span className="text-[13.5px] font-bold" style={{ color: "var(--ink)" }}>
姜十三社区
</span>
</div>
<nav className="flex items-center gap-5 text-[13px]" style={{ color: "var(--ink-2)" }}>
<Link href="/" className="hover:text-[var(--accent)] transition-colors">
首页
</Link>
<Link href="/board/1" className="hover:text-[var(--accent)] transition-colors">
板块
</Link>
<span className="meta">Go × Next.js</span>
</nav>
<span className="meta text-[12.5px]">
© 2026 姜十三
</span>
</div>
</footer> </footer>
); );
} }

View File

@@ -1,38 +1,79 @@
"use client"; "use client";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/navigation"; import { usePathname, useRouter } from "next/navigation";
import { useState, useEffect } from "react"; import { useState, useEffect, useRef } from "react";
import { Menu, X, Sun, Moon, LogIn, UserPlus, LogOut, PenSquare, Search, Settings } from "lucide-react"; import {
Menu,
X,
Sun,
Moon,
LogIn,
UserPlus,
LogOut,
PenSquare,
Search,
Settings,
Bell,
Home,
} from "lucide-react";
import { apiMe, apiLogout, type User } from "@/lib/api"; import { apiMe, apiLogout, type User } from "@/lib/api";
import NotificationBell from "./NotificationBell"; import NotificationBell from "./NotificationBell";
import Avatar from "./Avatar";
export default function Header() { export default function Header() {
const router = useRouter(); const router = useRouter();
const pathname = usePathname();
const [menuOpen, setMenuOpen] = useState(false); const [menuOpen, setMenuOpen] = useState(false);
const [theme, setTheme] = useState<"light" | "dark">("light"); const [theme, setTheme] = useState<"light" | "dark">("light");
const [user, setUser] = useState<User | null>(null); const [user, setUser] = useState<User | null>(null);
const [searchQuery, setSearchQuery] = useState(""); const [searchQuery, setSearchQuery] = useState("");
const searchInputRef = useRef<HTMLInputElement>(null);
const handleSearch = (e: React.FormEvent) => { const handleSearch = (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
const q = searchQuery.trim(); const q = searchQuery.trim();
if (q) { router.push(q ? `/?q=${encodeURIComponent(q)}` : "/");
router.push(`/?q=${encodeURIComponent(q)}`); setMenuOpen(false);
} searchInputRef.current?.blur();
}; };
useEffect(() => { useEffect(() => {
// 读取主题 // cookie 为单一真相源,客户端导航后校正(预取载荷可能回滚类名)
const savedTheme = document.documentElement.classList.contains("dark") ? "dark" : "light"; const isDark = document.cookie.match(/(?:^|;\s*)j13-theme=dark/);
const savedTheme: "light" | "dark" = isDark ? "dark" : "light";
document.documentElement.classList.toggle("dark", savedTheme === "dark");
setTheme(savedTheme); setTheme(savedTheme);
setSearchQuery(new URLSearchParams(window.location.search).get("q")?.trim() || "");
// 从后端获取登录态(HttpOnly cookie 自动携带)
apiMe() apiMe()
.then((res) => setUser(res.user || null)) .then((res) => setUser(res.user || null))
.catch(() => setUser(null)); .catch(() => setUser(null));
}, [pathname]);
// "/" 快速聚焦搜索
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
const el = e.target as HTMLElement;
const typing =
el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.tagName === "SELECT" || el.isContentEditable;
if (e.key === "/" && !typing && !e.metaKey && !e.ctrlKey && !e.altKey) {
e.preventDefault();
searchInputRef.current?.focus();
searchInputRef.current?.select();
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, []); }, []);
const onSearchKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Escape") {
setSearchQuery("");
if (new URLSearchParams(window.location.search).get("q")) router.push("/");
e.currentTarget.blur();
}
};
const toggleTheme = () => { const toggleTheme = () => {
const newTheme = theme === "dark" ? "light" : "dark"; const newTheme = theme === "dark" ? "light" : "dark";
setTheme(newTheme); setTheme(newTheme);
@@ -51,101 +92,232 @@ export default function Header() {
router.refresh(); router.refresh();
}; };
const iconBtn =
"w-10 h-10 flex items-center justify-center rounded-full transition-colors";
const iconBtnStyle = {
border: "1px solid var(--line)",
background: "var(--panel)",
color: "var(--ink-2)",
} as const;
return ( return (
<header className="sticky top-0 z-50 border-b" style={{ borderColor: "var(--border)", background: "var(--bg)" }}> <header
<div className="max-w-5xl mx-auto px-4 h-14 flex items-center justify-between"> className="sticky top-0 z-50 border-b"
<Link href="/" className="font-bold text-lg" style={{ color: "var(--primary)" }}> style={{
姜十三论坛 borderColor: "var(--line)",
background: "color-mix(in srgb, var(--bg) 82%, transparent)",
backdropFilter: "blur(14px)",
WebkitBackdropFilter: "blur(14px)",
}}
>
<div className="max-w-6xl mx-auto px-4 sm:px-6 h-[68px] flex items-center justify-between gap-4">
{/* 品牌 */}
<Link href="/" className="flex items-center gap-2.5 shrink-0 group">
<span
className="w-9 h-9 rounded-2xl flex items-center justify-center transition-transform duration-300 group-hover:rotate-[-6deg]"
style={{ background: "var(--accent)", color: "var(--accent-on)" }}
>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
<path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" />
</svg>
</span>
<span className="leading-none">
<span className="block font-extrabold text-[17px] tracking-tight" style={{ color: "var(--ink)" }}>
姜十三
</span>
<span className="block text-[10.5px] font-semibold mt-0.5" style={{ color: "var(--ink-3)" }}>
J13 社区
</span>
</span>
</Link> </Link>
{/* 桌面端导航 */} {/* 桌面端 */}
<nav className="hidden md:flex items-center gap-4"> <nav className="hidden lg:flex items-center gap-1">
<form onSubmit={handleSearch} className="relative"> <NavPill href="/" active={pathname === "/"} icon={<Home size={14} />}>
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: "var(--text-secondary)" }} /> 首页
</NavPill>
<NavPill href="/board/1" active={pathname.startsWith("/board")}>
板块
</NavPill>
<form onSubmit={handleSearch} className="relative ml-2">
<Search
size={15}
className="absolute left-4 top-1/2 -translate-y-1/2"
style={{ color: "var(--ink-3)" }}
/>
<input <input
ref={searchInputRef}
type="text" type="text"
value={searchQuery} value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)} onChange={(e) => setSearchQuery(e.target.value)}
onKeyDown={onSearchKeyDown}
placeholder="搜索帖子..." placeholder="搜索帖子..."
className="pl-9 pr-3 py-1.5 rounded-lg text-sm w-44 focus:outline-none focus:w-56 transition-all" aria-label="搜索帖子"
style={{ background: "var(--bg-secondary)", color: "var(--text)", border: "1px solid var(--border)" }} className="w-48 focus:w-64 transition-[width] duration-200 pl-10 pr-10 py-2.5 text-sm rounded-full"
style={{
background: "var(--panel)",
color: "var(--ink)",
border: "1px solid var(--line)",
}}
/> />
<kbd
className="absolute right-3.5 top-1/2 -translate-y-1/2 text-[11px] w-5 h-5 flex items-center justify-center rounded-md pointer-events-none"
style={{ color: "var(--ink-3)", border: "1px solid var(--line-2)", background: "var(--bg)" }}
>
/
</kbd>
</form> </form>
<Link href="/" className="hover:opacity-80" style={{ color: "var(--text)" }}>首页</Link> </nav>
{user && (
<Link href="/compose" className="flex items-center gap-1 hover:opacity-80" style={{ color: "var(--text)" }}> <div className="hidden lg:flex items-center gap-2">
<PenSquare size={16} /> 发帖 <button onClick={toggleTheme} className={iconBtn} style={iconBtnStyle} aria-label="切换主题">
</Link> {theme === "dark" ? <Sun size={17} /> : <Moon size={17} />}
)}
<button onClick={toggleTheme} className="p-2 rounded-lg hover:opacity-80" style={{ color: "var(--text)" }}>
{theme === "dark" ? <Sun size={18} /> : <Moon size={18} />}
</button> </button>
{user && <NotificationBell />} {user && <NotificationBell />}
{user ? ( {user ? (
<div className="flex items-center gap-3"> <>
<span className="text-sm" style={{ color: "var(--text-secondary)" }}>{user.nickname}</span> <Link href="/compose" className="btn btn-primary btn-sm ml-1">
<Link href="/settings" className="flex items-center gap-1 text-sm hover:opacity-80" style={{ color: "var(--text-secondary)" }}> <PenSquare size={14} /> 发帖
<Settings size={14} /> 设置
</Link> </Link>
<button onClick={handleLogout} className="flex items-center gap-1 text-sm hover:opacity-80" style={{ color: "var(--text-secondary)" }}> <Link
<LogOut size={14} /> 退出 href={`/u/${user.id}`}
className="flex items-center gap-2 rounded-full pl-1 pr-3 py-1 transition-colors"
style={{ border: "1px solid var(--line)", background: "var(--panel)" }}
>
<Avatar name={user.nickname || user.username} size={28} />
<span className="text-[13px] font-semibold max-w-[90px] truncate" style={{ color: "var(--ink)" }}>
{user.nickname}
</span>
</Link>
<button onClick={() => router.push("/settings")} className={iconBtn} style={iconBtnStyle} aria-label="设置">
<Settings size={16} />
</button> </button>
</div> <button onClick={handleLogout} className={iconBtn} style={iconBtnStyle} aria-label="退出登录">
<LogOut size={16} />
</button>
</>
) : ( ) : (
<div className="flex items-center gap-2"> <>
<Link href="/login" className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm" style={{ background: "var(--bg-secondary)", color: "var(--text)" }}> <Link href="/login" className="btn btn-line btn-sm">
<LogIn size={14} /> 登录 <LogIn size={14} /> 登录
</Link> </Link>
<Link href="/register" className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm text-white" style={{ background: "var(--primary)" }}> <Link href="/register" className="btn btn-primary btn-sm">
<UserPlus size={14} /> 注册 <UserPlus size={14} /> 注册
</Link> </Link>
</div> </>
)} )}
</nav> </div>
{/* 移动端菜单按钮 */} {/* 移动端按钮 */}
<button onClick={() => setMenuOpen(!menuOpen)} className="md:hidden p-2" style={{ color: "var(--text)" }}> <div className="flex items-center gap-2 lg:hidden">
{menuOpen ? <X size={20} /> : <Menu size={20} />} {user && <NotificationBell />}
<button
onClick={() => setMenuOpen(!menuOpen)}
className="w-10 h-10 flex items-center justify-center rounded-full"
style={{ border: "1px solid var(--line)", background: "var(--panel)", color: "var(--ink)" }}
aria-label="菜单"
aria-expanded={menuOpen}
>
{menuOpen ? <X size={19} /> : <Menu size={19} />}
</button> </button>
</div> </div>
</div>
{/* 移动端下拉菜单 */} {/* 移动端抽屉 */}
{menuOpen && ( {menuOpen && (
<div className="md:hidden border-t px-4 py-3 space-y-2" style={{ borderColor: "var(--border)", background: "var(--bg)" }}> <div
<form onSubmit={(e) => { handleSearch(e); setMenuOpen(false); }} className="relative"> className="lg:hidden border-t px-4 py-4"
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: "var(--text-secondary)" }} /> style={{ borderColor: "var(--line)", background: "var(--bg)" }}
>
<form onSubmit={handleSearch} className="relative mb-3">
<Search size={16} className="absolute left-4 top-1/2 -translate-y-1/2" style={{ color: "var(--ink-3)" }} />
<input <input
type="text" type="text"
value={searchQuery} value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)} onChange={(e) => setSearchQuery(e.target.value)}
placeholder="搜索帖子..." onKeyDown={onSearchKeyDown}
className="w-full pl-9 pr-3 py-2 rounded-lg text-sm" aria-label="搜索帖子"
style={{ background: "var(--bg-secondary)", color: "var(--text)", border: "1px solid var(--border)" }} placeholder="搜索帖子...(Esc 清除)"
className="w-full pl-10 pr-4 py-3 rounded-full text-sm"
style={{ background: "var(--panel)", color: "var(--ink)", border: "1px solid var(--line-2)" }}
/> />
</form> </form>
<Link href="/" onClick={() => setMenuOpen(false)} className="block py-2" style={{ color: "var(--text)" }}>首页</Link> <div className="flex flex-col">
<MobileLink href="/" active={pathname === "/"}>首页</MobileLink>
<MobileLink href="/board/1" active={pathname.startsWith("/board")}>板块</MobileLink>
{user && <MobileLink href="/compose">发帖</MobileLink>}
{user && ( {user && (
<Link href="/compose" onClick={() => setMenuOpen(false)} className="block py-2" style={{ color: "var(--text)" }}>发帖</Link> <MobileLink href="/notifications">
<span className="inline-flex items-center gap-2"><Bell size={15} /> 通知中心</span>
</MobileLink>
)} )}
<button onClick={toggleTheme} className="block py-2 w-full text-left" style={{ color: "var(--text)" }}> {user && <MobileLink href="/settings">账号设置</MobileLink>}
{theme === "dark" ? "切换亮色主题" : "切换暗色主题"} {!user && <MobileLink href="/login">登录</MobileLink>}
{!user && <MobileLink href="/register">注册</MobileLink>}
</div>
<div className="pt-3 mt-2 border-t flex items-center justify-between" style={{ borderColor: "var(--line)" }}>
<button onClick={toggleTheme} className="btn btn-line btn-sm">
{theme === "dark" ? <Sun size={14} /> : <Moon size={14} />}
{theme === "dark" ? "浅色模式" : "深色模式"}
</button>
{user && (
<button onClick={handleLogout} className="btn btn-danger btn-sm">
<LogOut size={14} /> 退出
</button> </button>
{user ? (
<Link href="/notifications" onClick={() => setMenuOpen(false)} className="block py-2" style={{ color: "var(--text)" }}>通知中心</Link>
) : null}
{user ? (
<>
<Link href="/settings" onClick={() => setMenuOpen(false)} className="block py-2" style={{ color: "var(--text)" }}>账号设置</Link>
<button onClick={handleLogout} className="block py-2 w-full text-left" style={{ color: "var(--text)" }}>退出登录</button>
</>
) : (
<>
<Link href="/login" onClick={() => setMenuOpen(false)} className="block py-2" style={{ color: "var(--text)" }}>登录</Link>
<Link href="/register" onClick={() => setMenuOpen(false)} className="block py-2" style={{ color: "var(--text)" }}>注册</Link>
</>
)} )}
</div> </div>
</div>
)} )}
</header> </header>
); );
} }
function NavPill({
href,
active,
icon,
children,
}: {
href: string;
active?: boolean;
icon?: React.ReactNode;
children: React.ReactNode;
}) {
return (
<Link
href={href}
className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-full text-[13.5px] font-semibold transition-colors"
style={
active
? { background: "var(--accent-soft)", color: "var(--accent)" }
: { color: "var(--ink-2)" }
}
>
{icon}
{children}
</Link>
);
}
function MobileLink({
href,
active,
children,
}: {
href: string;
active?: boolean;
children: React.ReactNode;
}) {
return (
<Link
href={href}
className="px-3 py-3 rounded-2xl text-[15px] font-semibold transition-colors"
style={{
color: active ? "var(--accent)" : "var(--ink)",
background: active ? "var(--accent-soft)" : "transparent",
}}
>
{children}
</Link>
);
}

View File

@@ -0,0 +1,84 @@
// 统一的细线统计图标(避免 emoji 渲染不一致)
interface IconProps {
size?: number;
filled?: boolean;
className?: string;
}
export function IconComment({ size = 14, className }: IconProps) {
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
className={className}
aria-hidden
>
<path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" />
</svg>
);
}
export function IconEye({ size = 14, className }: IconProps) {
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
className={className}
aria-hidden
>
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
<circle cx="12" cy="12" r="3" />
</svg>
);
}
export function IconHeart({ size = 14, filled, className }: IconProps) {
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill={filled ? "currentColor" : "none"}
stroke="currentColor"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
className={className}
aria-hidden
>
<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />
</svg>
);
}
export function StatItem({
icon,
value,
accent,
}: {
icon: React.ReactNode;
value: number | string;
accent?: boolean;
}) {
return (
<span
className="inline-flex items-center gap-1.5 meta"
style={accent ? { color: "var(--accent)" } : undefined}
>
{icon}
{value}
</span>
);
}

View File

@@ -1,8 +1,10 @@
"use client"; "use client";
import { useState } from "react"; import { useState } from "react";
import { Heart } from "lucide-react"; import { useRouter, usePathname } from "next/navigation";
import { IconHeart } from "./Icons";
import { apiToggleLike } from "@/lib/api"; import { apiToggleLike } from "@/lib/api";
import { toast } from "@/lib/toast";
interface LikeButtonProps { interface LikeButtonProps {
postId: string; postId: string;
@@ -11,7 +13,14 @@ interface LikeButtonProps {
variant?: "default" | "compact"; variant?: "default" | "compact";
} }
export default function LikeButton({ postId, liked: initialLiked, likeCount: initialCount, variant = "default" }: LikeButtonProps) { export default function LikeButton({
postId,
liked: initialLiked,
likeCount: initialCount,
variant = "default",
}: LikeButtonProps) {
const router = useRouter();
const pathname = usePathname();
const [liked, setLiked] = useState(initialLiked); const [liked, setLiked] = useState(initialLiked);
const [count, setCount] = useState(initialCount); const [count, setCount] = useState(initialCount);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -19,36 +28,52 @@ export default function LikeButton({ postId, liked: initialLiked, likeCount: ini
const handleClick = async () => { const handleClick = async () => {
if (loading) return; if (loading) return;
setLoading(true); setLoading(true);
// 乐观更新:先给反馈,失败再回滚
const wasLiked = liked;
setLiked(!wasLiked);
setCount((c) => c + (wasLiked ? -1 : 1));
try { try {
const res = await apiToggleLike(postId); const res = await apiToggleLike(postId);
if (res.error === "未登录") { if (res.error === "未登录") {
window.location.href = "/login"; router.push(`/login?redirect=${encodeURIComponent(pathname)}`);
return; return;
} }
if (typeof res.liked === "boolean") { if (typeof res.liked === "boolean") {
setLiked(res.liked); setLiked(res.liked);
setCount(res.like_count ?? count); setCount(res.like_count ?? count);
} else {
throw new Error(res.error || "FAIL");
} }
} catch {
setLiked(wasLiked);
setCount((c) => c + (wasLiked ? 1 : -1));
toast("操作失败,请稍后重试");
} finally { } finally {
setLoading(false); setLoading(false);
} }
}; };
const sizing = variant === "compact" ? "px-2 py-1 gap-1" : "px-3 py-1.5 gap-1.5"; const compact =
const iconSize = variant === "compact" ? 14 : 16; variant === "compact"
? "px-2.5 py-1.5 gap-1 text-[12.5px]"
: "px-4 py-2 gap-1.5 text-sm";
return ( return (
<button <button
onClick={handleClick} onClick={handleClick}
disabled={loading} disabled={loading}
title={liked ? "取消点赞" : "点赞"} title={liked ? "取消点赞" : "点赞"}
className={`flex items-center ${sizing} rounded-full text-sm font-medium transition-all disabled:opacity-50 ${ aria-pressed={liked}
liked className={`inline-flex items-center font-semibold tabular-nums rounded-full border transition-colors duration-150 hover:border-[var(--accent)] disabled:opacity-50 ${compact}`}
? "text-red-500 bg-red-50 dark:bg-red-900/20" style={{
: "text-gray-500 hover:text-red-500 hover:bg-gray-100 dark:hover:bg-gray-800" borderColor: liked ? "var(--accent)" : "var(--line-2)",
}`} color: liked ? "var(--accent)" : "var(--ink-2)",
background: liked ? "var(--accent-soft)" : "var(--panel)",
}}
> >
<Heart size={iconSize} fill={liked ? "currentColor" : "none"} /> <span key={String(liked)} className={liked ? "j13-heart-pop inline-flex" : "inline-flex"}>
<IconHeart size={variant === "compact" ? 13 : 15} filled={liked} />
</span>
<span>{count}</span> <span>{count}</span>
</button> </button>
); );

View File

@@ -100,15 +100,23 @@ export default function NotificationBell() {
<div className="relative" ref={dropdownRef}> <div className="relative" ref={dropdownRef}>
<button <button
onClick={handleToggle} onClick={handleToggle}
className="relative p-2 rounded-lg hover:opacity-80"
style={{ color: "var(--text)" }}
aria-label="通知" aria-label="通知"
className="relative w-10 h-10 flex items-center justify-center rounded-full transition-colors"
style={{
color: open ? "var(--accent)" : "var(--ink-2)",
border: "1px solid " + (open ? "var(--accent)" : "var(--line)"),
background: open ? "var(--accent-soft)" : "var(--panel)",
}}
> >
<Bell size={18} /> <Bell size={17} />
{unread > 0 && ( {unread > 0 && (
<span <span
className="absolute -top-0.5 -right-0.5 min-w-[16px] h-4 px-1 rounded-full text-xs text-white flex items-center justify-center font-bold" 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(--primary)" }} style={{
background: "var(--clay)",
color: "#fff",
border: "2px solid var(--bg)",
}}
> >
{unread > 99 ? "99+" : unread} {unread > 99 ? "99+" : unread}
</span> </span>
@@ -117,77 +125,94 @@ export default function NotificationBell() {
{open && ( {open && (
<div <div
className="absolute right-0 mt-2 w-80 rounded-xl border shadow-xl overflow-hidden z-50" className="absolute right-0 mt-2.5 w-[340px] max-w-[calc(100vw-2rem)] overflow-hidden z-50 j13-toast-in"
style={{ borderColor: "var(--border)", background: "var(--bg)" }} style={{
background: "var(--panel)",
border: "1px solid var(--line)",
borderRadius: "var(--r)",
boxShadow: "var(--shadow-lg)",
}}
> >
<div <div
className="flex items-center justify-between px-4 py-3 border-b" className="flex items-center justify-between px-5 py-3.5"
style={{ borderColor: "var(--border)" }} style={{ borderBottom: "1px solid var(--line)" }}
> >
<span className="font-semibold" style={{ color: "var(--text)" }}>通知</span> <span className="font-bold text-[15px]" style={{ color: "var(--ink)" }}>通知</span>
{unread > 0 && ( {unread > 0 && (
<button <button
onClick={handleMarkAllRead} onClick={handleMarkAllRead}
className="flex items-center gap-1 text-xs hover:opacity-80" className="flex items-center gap-1 text-xs meta hover:text-[var(--accent)] transition-colors"
style={{ color: "var(--primary)" }}
> >
<CheckCheck size={14} /> 全部已读 <CheckCheck size={13} /> 全部已读
</button> </button>
)} )}
</div> </div>
<div className="max-h-96 overflow-y-auto"> <div className="max-h-[24rem] overflow-y-auto">
{loading ? ( {loading ? (
<p className="text-center py-8 text-sm" style={{ color: "var(--text-secondary)" }}>加载中...</p> <p className="text-center py-10 meta">加载中...</p>
) : notifications.length === 0 ? ( ) : notifications.length === 0 ? (
<p className="text-center py-8 text-sm" style={{ color: "var(--text-secondary)" }}>暂无通知</p> <div className="text-center py-12">
<Bell size={26} className="mx-auto mb-2.5" style={{ color: "var(--ink-3)" }} />
<p className="meta">还没有通知</p>
</div>
) : ( ) : (
notifications.map((n) => ( notifications.map((n) => (
<button <button
key={n.id} key={n.id}
onClick={() => handleClickNotification(n)} onClick={() => handleClickNotification(n)}
className="w-full text-left px-4 py-3 border-b hover:opacity-90 transition-opacity" className="w-full text-left px-4 py-3.5 flex items-start gap-3 transition-colors"
style={{ style={{
borderColor: "var(--border)", borderBottom: "1px solid var(--line)",
background: n.is_read ? "transparent" : "var(--bg-secondary)", background: n.is_read ? "transparent" : "var(--panel-2)",
}} }}
> >
<div className="flex items-start gap-2"> <span
<span style={{ color: n.type === "like" ? "#ef4444" : "var(--primary)" }}> className="w-9 h-9 shrink-0 rounded-full flex items-center justify-center"
{n.type === "like" ? <Heart size={16} /> : <MessageCircle size={16} />} style={{
color: n.type === "like" ? "var(--clay)" : "var(--accent)",
background:
n.type === "like" ? "var(--clay-soft)" : "var(--accent-soft)",
}}
>
{n.type === "like" ? <Heart size={15} /> : <MessageCircle size={15} />}
</span> </span>
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<p className="text-sm" style={{ color: "var(--text)" }}> <p className="text-sm leading-snug" style={{ color: "var(--ink)" }}>
<span className="font-medium">{n.actor.nickname}</span>{" "} <span className="font-medium">{n.actor.nickname}</span>{" "}
<span style={{ color: "var(--text-secondary)" }}>{actionText(n)}</span> <span className="meta">{actionText(n)}</span>
</p> </p>
<p className="text-xs mt-0.5 truncate" style={{ color: "var(--text-secondary)" }}> <p className="text-xs mt-1 truncate" style={{ color: "var(--ink-2)" }}>
《{n.post.title}》 《{n.post.title}》
</p> </p>
{n.content && ( {n.content && (
<p className="text-xs mt-1 line-clamp-1" style={{ color: "var(--text-secondary)" }}> <p className="text-xs mt-1 line-clamp-1" style={{ color: "var(--ink-3)" }}>
{n.content} {n.content}
</p> </p>
)} )}
<p className="text-xs mt-1" style={{ color: "var(--text-secondary)" }}> <p className="meta mt-1.5 text-xs">{formatTime(n.created_at)}</p>
{formatTime(n.created_at)}
</p>
</div> </div>
{!n.is_read && ( {!n.is_read && (
<span <span
className="w-2 h-2 rounded-full shrink-0 mt-1.5" className="w-2.5 h-2.5 shrink-0 mt-2 rounded-full"
style={{ background: "var(--primary)" }} style={{ background: "var(--clay)" }}
/> />
)} )}
</div>
</button> </button>
)) ))
)} )}
</div> </div>
<div className="px-4 py-2 border-t text-center" style={{ borderColor: "var(--border)" }}> <div
<Link href="/notifications" className="text-sm hover:underline" style={{ color: "var(--primary)" }}> className="px-4 py-2.5 text-center"
查看全部通知 style={{ borderTop: "1px solid var(--line)" }}
>
<Link
href="/notifications"
onClick={() => setOpen(false)}
className="meta text-xs hover:text-[var(--accent)] transition-colors"
>
查看全部通知 →
</Link> </Link>
</div> </div>
</div> </div>

View File

@@ -7,9 +7,9 @@ interface PaginationProps {
total: number; total: number;
page: number; page: number;
size: number; size: number;
basePath: string; // e.g. "/" or "/board/1" basePath: string;
query?: Record<string, string>; // additional query params (e.g. q for search) query?: Record<string, string>;
onChange?: (page: number) => void; // 客户端分页回调;提供时不渲染 Link 而是按钮 onChange?: (page: number) => void;
} }
export default function Pagination({ total, page, size, basePath, query = {}, onChange }: PaginationProps) { export default function Pagination({ total, page, size, basePath, query = {}, onChange }: PaginationProps) {
@@ -29,7 +29,6 @@ export default function Pagination({ total, page, size, basePath, query = {}, on
} }
}; };
// 生成页码按钮(最多显示 7 个,带省略号)
const pages: (number | "...")[] = []; const pages: (number | "...")[] = [];
const add = (p: number | "...") => pages.push(p); const add = (p: number | "...") => pages.push(p);
@@ -45,35 +44,33 @@ export default function Pagination({ total, page, size, basePath, query = {}, on
add(totalPages); add(totalPages);
} }
const cls =
"pager-btn min-w-[38px] h-9 px-1 flex items-center justify-center font-semibold text-[13px] rounded-full border transition-colors duration-150";
return ( return (
<nav className="flex items-center justify-center gap-1 mt-8"> <nav className="flex items-center justify-center gap-1.5 mt-10 flex-wrap" aria-label="分页">
{page > 1 && ( {page > 1 && (
<Link <Link
href={buildHref(page - 1)} href={buildHref(page - 1)}
onClick={(e) => handleClick(page - 1, e)} onClick={(e) => handleClick(page - 1, e)}
className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm hover:opacity-80" className={`${cls} px-3 gap-1`}
style={{ background: "var(--bg-secondary)", color: "var(--text)" }}
> >
<ChevronLeft size={16} /> 上一页 <ChevronLeft size={14} /> 上一页
</Link> </Link>
)} )}
{pages.map((p, i) => {pages.map((p, i) =>
p === "..." ? ( p === "..." ? (
<span key={`e${i}`} className="px-2" style={{ color: "var(--text-secondary)" }}>…</span> <span key={`e${i}`} className="px-1 meta">
—
</span>
) : ( ) : (
<Link <Link
key={p} key={p}
href={buildHref(p)} href={buildHref(p)}
onClick={(e) => handleClick(p, e)} onClick={(e) => handleClick(p, e)}
className={`min-w-[36px] h-9 flex items-center justify-center rounded-lg text-sm ${ aria-current={p === page ? "page" : undefined}
p === page ? "text-white" : "hover:opacity-80" className={`${cls} ${p === page ? "is-current" : ""}`}
}`}
style={
p === page
? { background: "var(--primary)" }
: { background: "var(--bg-secondary)", color: "var(--text)" }
}
> >
{p} {p}
</Link> </Link>
@@ -84,10 +81,9 @@ export default function Pagination({ total, page, size, basePath, query = {}, on
<Link <Link
href={buildHref(page + 1)} href={buildHref(page + 1)}
onClick={(e) => handleClick(page + 1, e)} onClick={(e) => handleClick(page + 1, e)}
className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm hover:opacity-80" className={`${cls} px-3 gap-1`}
style={{ background: "var(--bg-secondary)", color: "var(--text)" }}
> >
下一页 <ChevronRight size={16} /> 下一页 <ChevronRight size={14} />
</Link> </Link>
)} )}
</nav> </nav>

View File

@@ -0,0 +1,91 @@
import Link from "next/link";
import { Pin } from "lucide-react";
import type { PostListItem } from "@/lib/api";
import Avatar from "./Avatar";
import { IconComment, IconEye } from "./Icons";
function formatTime(dateStr: string) {
const d = new Date(dateStr);
return `${d.getFullYear()}.${String(d.getMonth() + 1).padStart(2, "0")}.${String(
d.getDate()
).padStart(2, "0")}`;
}
/**
* 管理员置顶区:独立于"今日精选"和普通列表。
* 陶土色语义(与 badge-pin 一致),紧凑排列,一眼识别为公告性质内容。
*/
export default function PinnedPosts({
posts,
showBoard = true,
}: {
posts: PostListItem[];
showBoard?: boolean;
}) {
if (posts.length === 0) return null;
return (
<section className="mb-6" aria-label="置顶讨论">
<div className="flex items-center gap-2 mb-2.5 px-1">
<span
className="w-6 h-6 rounded-full flex items-center justify-center"
style={{ background: "var(--clay-soft)", color: "var(--clay)" }}
>
<Pin size={12} fill="currentColor" strokeWidth={2.4} />
</span>
<h2 className="text-[13.5px] font-extrabold tracking-wide" style={{ color: "var(--clay)" }}>
置顶讨论
</h2>
<span className="meta text-xs">管理员置顶 · {posts.length}</span>
</div>
<div className="panel overflow-hidden">
{posts.map((p, i) => (
<Link
key={p.id}
href={`/post/${p.id}`}
className="group flex items-center gap-3 sm:gap-3.5 px-4 sm:px-5 py-3.5 transition-colors hover:bg-[var(--panel-2)]"
style={i > 0 ? { borderTop: "1px solid var(--line)" } : undefined}
>
<Avatar name={p.user.nickname || p.user.username} size={36} />
<div className="flex-1 min-w-0">
<h3
className="text-[14.5px] font-bold leading-snug truncate transition-colors group-hover:text-[var(--accent)]"
style={{ color: "var(--ink)" }}
>
{p.title}
</h3>
<div className="meta flex items-center gap-2 mt-1 text-xs min-w-0">
<span className="truncate">{p.user.nickname}</span>
<span aria-hidden>·</span>
<span className="shrink-0">{formatTime(p.created_at)}</span>
{showBoard && (
<>
<span aria-hidden>·</span>
<span className="truncate">{p.board.name}</span>
</>
)}
{p.recommended && <span className="badge-rec !text-[10.5px] !px-1.5 !py-0 shrink-0">推荐</span>}
</div>
</div>
<div className="hidden sm:flex items-center gap-3 shrink-0 meta text-[12.5px]">
<span className="inline-flex items-center gap-1.5" aria-label={`${p.comment_count} 条评论`}>
<IconComment size={14} /> {p.comment_count}
</span>
<span className="inline-flex items-center gap-1.5" aria-label={`${p.view_count} 次浏览`}>
<IconEye size={14} /> {p.view_count}
</span>
</div>
<Pin
size={13}
className="shrink-0 hidden sm:block"
style={{ color: "var(--clay)" }}
fill="currentColor"
strokeWidth={2.2}
/>
</Link>
))}
</div>
</section>
);
}

View File

@@ -5,6 +5,7 @@ import { useRouter } from "next/navigation";
import Link from "next/link"; import Link from "next/link";
import { Pencil, Trash2, Pin, Star } from "lucide-react"; import { Pencil, Trash2, Pin, Star } from "lucide-react";
import { apiMe, apiDeletePost, apiTogglePin, apiToggleRecommend, type User } from "@/lib/api"; import { apiMe, apiDeletePost, apiTogglePin, apiToggleRecommend, type User } from "@/lib/api";
import { toast } from "@/lib/toast";
interface PostActionsProps { interface PostActionsProps {
postId: string; postId: string;
@@ -19,7 +20,7 @@ export default function PostActions({ postId, authorId, pinned, recommended }: P
const [deleting, setDeleting] = useState(false); const [deleting, setDeleting] = useState(false);
const [isPinned, setIsPinned] = useState(pinned > 0); const [isPinned, setIsPinned] = useState(pinned > 0);
const [isRecommended, setIsRecommended] = useState(recommended); const [isRecommended, setIsRecommended] = useState(recommended);
const [acting, setActing] = useState(""); const [acting, setActing] = useState(false);
useEffect(() => { useEffect(() => {
apiMe() apiMe()
@@ -27,7 +28,6 @@ export default function PostActions({ postId, authorId, pinned, recommended }: P
.catch(() => setUser(null)); .catch(() => setUser(null));
}, []); }, []);
// 仅作者本人或管理员可编辑/删除;置顶/推荐仅管理员
const canManage = user && (user.id === authorId || user.role === "admin"); const canManage = user && (user.id === authorId || user.role === "admin");
const isAdmin = user?.role === "admin"; const isAdmin = user?.role === "admin";
if (!canManage) return null; if (!canManage) return null;
@@ -39,78 +39,76 @@ export default function PostActions({ postId, authorId, pinned, recommended }: P
const res = await apiDeletePost(postId); const res = await apiDeletePost(postId);
if (res.message) { if (res.message) {
router.push("/"); router.push("/");
toast("帖子已删除", "ok");
} else { } else {
alert(res.error || "删除失败"); toast(res.error || "删除失败");
} }
} catch {
toast("网络错误,删除失败");
} finally { } finally {
setDeleting(false); setDeleting(false);
} }
}; };
const handlePin = async () => { const handlePin = async () => {
setActing("pin"); setActing(true);
try { try {
const res = await apiTogglePin(postId); const res = await apiTogglePin(postId);
setIsPinned(res.pinned > 0); setIsPinned(res.pinned > 0);
toast(res.pinned > 0 ? "已置顶" : "已取消置顶", "ok");
router.refresh(); router.refresh();
} catch {
toast("操作失败,请稍后重试");
} finally { } finally {
setActing(""); setActing(false);
} }
}; };
const handleRecommend = async () => { const handleRecommend = async () => {
setActing("recommend"); setActing(true);
try { try {
const res = await apiToggleRecommend(postId); const res = await apiToggleRecommend(postId);
setIsRecommended(res.recommended); setIsRecommended(res.recommended);
toast(res.recommended ? "已设为推荐" : "已取消推荐", "ok");
router.refresh(); router.refresh();
} catch {
toast("操作失败,请稍后重试");
} finally { } finally {
setActing(""); setActing(false);
} }
}; };
return ( return (
<div className="flex items-center gap-2 flex-wrap justify-end"> <div className="flex items-center gap-1.5 flex-wrap">
{isAdmin && ( {isAdmin && (
<> <>
<button <button
onClick={handlePin} onClick={handlePin}
disabled={acting !== ""} disabled={acting}
className="flex items-center gap-1 text-sm px-3 py-1.5 rounded-lg hover:opacity-80 disabled:opacity-50" className="btn btn-line btn-sm"
style={{ style={isPinned ? { borderColor: "var(--accent)", color: "var(--accent)" } : undefined}
background: isPinned ? "var(--primary)" : "var(--bg-secondary)",
color: isPinned ? "white" : "var(--text)",
}}
> >
<Pin size={14} /> {isPinned ? "取消置顶" : "置顶"} <Pin size={13} /> {isPinned ? "取消置顶" : "置顶"}
</button> </button>
<button <button
onClick={handleRecommend} onClick={handleRecommend}
disabled={acting !== ""} disabled={acting}
className="flex items-center gap-1 text-sm px-3 py-1.5 rounded-lg hover:opacity-80 disabled:opacity-50" className="btn btn-line btn-sm"
style={{ style={
background: isRecommended ? "#e11d48" : "var(--bg-secondary)", isRecommended
color: isRecommended ? "white" : "var(--text)", ? { borderColor: "var(--gold)", color: "var(--gold)", background: "var(--gold-soft)" }
}} : undefined
}
> >
<Star size={14} /> {isRecommended ? "取消推荐" : "推荐"} <Star size={13} /> {isRecommended ? "取消推荐" : "推荐"}
</button> </button>
</> </>
)} )}
<Link <Link href={`/post/${postId}/edit`} className="btn btn-line btn-sm">
href={`/post/${postId}/edit`} <Pencil size={13} /> 编辑
className="flex items-center gap-1 text-sm px-3 py-1.5 rounded-lg hover:opacity-80"
style={{ background: "var(--bg-secondary)", color: "var(--text)" }}
>
<Pencil size={14} /> 编辑
</Link> </Link>
<button <button onClick={handleDelete} disabled={deleting} className="btn btn-danger btn-sm">
onClick={handleDelete} <Trash2 size={13} /> {deleting ? "删除中..." : "删除"}
disabled={deleting}
className="flex items-center gap-1 text-sm px-3 py-1.5 rounded-lg text-red-600 hover:bg-red-50 disabled:opacity-50"
style={{ background: "var(--bg-secondary)" }}
>
<Trash2 size={14} /> {deleting ? "删除中..." : "删除"}
</button> </button>
</div> </div>
); );

View File

@@ -0,0 +1,91 @@
import Link from "next/link";
import type { PostListItem } from "@/lib/api";
import LikeButton from "./LikeButton";
import Avatar from "./Avatar";
import { IconComment, IconEye } from "./Icons";
function formatTime(dateStr: string) {
const d = new Date(dateStr);
return `${d.getFullYear()}.${String(d.getMonth() + 1).padStart(2, "0")}.${String(
d.getDate()
).padStart(2, "0")}`;
}
/**
* 帖子列表行:头像 + 标题 + 作者元信息 + 统计 + 点赞
* 用于首页/板块页,以细线串联,悬浮浅色反馈
*/
export default function PostRow({
post,
boardHref,
}: {
post: PostListItem;
index?: number;
boardHref?: boolean;
}) {
return (
<div
className="group flex items-center gap-3 sm:gap-4 px-4 sm:px-5 py-4 border-t transition-colors hover:bg-[var(--panel-2)]"
style={{ borderColor: "var(--line)" }}
>
<Link href={`/u/${post.user.id}`} className="shrink-0" aria-label={post.user.nickname}>
<Avatar name={post.user.nickname || post.user.username} size={42} />
</Link>
<div className="flex-1 min-w-0">
{(post.pinned > 0 || post.recommended) && (
<div className="flex items-center gap-1.5 mb-1.5 flex-wrap">
{post.pinned > 0 && <span className="badge-pin">置顶</span>}
{post.recommended && <span className="badge-rec">推荐</span>}
</div>
)}
<Link href={`/post/${post.id}`}>
<h3
className="font-semibold text-[15px] sm:text-[16px] leading-snug truncate transition-colors group-hover:text-[var(--accent)]"
style={{ color: "var(--ink)" }}
>
{post.title}
</h3>
</Link>
<div className="meta flex items-center gap-2.5 mt-1.5 flex-wrap">
<Link
href={`/u/${post.user.id}`}
className="hover:text-[var(--accent)] transition-colors"
>
{post.user.nickname}
</Link>
{boardHref && (
<>
<span aria-hidden>·</span>
<Link
href={`/board/${post.board.id}`}
className="hover:text-[var(--accent)] transition-colors"
>
{post.board.name}
</Link>
</>
)}
<span aria-hidden>·</span>
<span>{formatTime(post.created_at)}</span>
</div>
</div>
<div className="flex items-center gap-2.5 sm:gap-3.5 shrink-0">
<span className="hidden sm:inline-flex items-center gap-1.5 meta" aria-label={`${post.comment_count} 条评论`}>
<IconComment size={15} />
{post.comment_count}
</span>
<span className="hidden md:inline-flex items-center gap-1.5 meta" aria-label={`${post.view_count} 次浏览`}>
<IconEye size={15} />
{post.view_count}
</span>
<LikeButton
postId={String(post.id)}
liked={post.liked}
likeCount={post.like_count}
variant="compact"
/>
</div>
</div>
);
}

View File

@@ -0,0 +1,37 @@
"use client";
import { useEffect, useState } from "react";
export default function ReadingProgress() {
const [progress, setProgress] = useState(0);
useEffect(() => {
let raf = 0;
const update = () => {
raf = 0;
const doc = document.documentElement;
const max = doc.scrollHeight - doc.clientHeight;
setProgress(max > 0 ? Math.min(1, doc.scrollTop / max) : 0);
};
const onScroll = () => {
if (!raf) raf = requestAnimationFrame(update);
};
update();
window.addEventListener("scroll", onScroll, { passive: true });
window.addEventListener("resize", onScroll);
return () => {
window.removeEventListener("scroll", onScroll);
window.removeEventListener("resize", onScroll);
if (raf) cancelAnimationFrame(raf);
};
}, []);
if (progress <= 0) return null;
return (
<div
className="reading-progress"
style={{ transform: `scaleX(${progress})`, opacity: progress >= 1 ? 0 : 1 }}
aria-hidden="true"
/>
);
}

View File

@@ -0,0 +1,66 @@
"use client";
import { useEffect, useState } from "react";
import { X, AlertCircle, CheckCircle2 } from "lucide-react";
import type { ToastDetail } from "@/lib/toast";
export default function Toaster() {
const [items, setItems] = useState<ToastDetail[]>([]);
useEffect(() => {
const handler = (e: Event) => {
const detail = (e as CustomEvent<ToastDetail>).detail;
setItems((list) => [...list.slice(-2), detail]);
window.setTimeout(() => {
setItems((list) => list.filter((t) => t.id !== detail.id));
}, 3600);
};
window.addEventListener("j13-toast", handler);
return () => window.removeEventListener("j13-toast", handler);
}, []);
const dismiss = (id: number) => setItems((list) => list.filter((t) => t.id !== id));
return (
<div
className="fixed bottom-5 right-4 sm:right-6 z-[10000] flex flex-col gap-2 w-[calc(100vw-2rem)] sm:w-80"
aria-live="polite"
role="status"
>
{items.map((t) => (
<ToastCard key={t.id} toast={t} onClose={() => dismiss(t.id)} />
))}
</div>
);
}
function ToastCard({ toast, onClose }: { toast: ToastDetail; onClose: () => void }) {
const color = toast.variant === "error" ? "var(--danger)" : "var(--ok)";
return (
<div
className="j13-toast-in flex items-start gap-3 px-4 py-3.5"
style={{
background: "var(--panel)",
border: "1px solid var(--line)",
borderLeft: `3px solid ${color}`,
borderRadius: "var(--r-sm)",
boxShadow: "var(--shadow-lg)",
}}
role="alert"
>
<span className="shrink-0 mt-0.5" style={{ color }}>
{toast.variant === "error" ? <AlertCircle size={16} /> : <CheckCircle2 size={16} />}
</span>
<p className="flex-1 text-[13.5px] leading-snug" style={{ color: "var(--ink)" }}>
{toast.message}
</p>
<button
onClick={onClose}
className="shrink-0 meta hover:text-[var(--ink)] transition-colors"
aria-label="关闭提示"
>
<X size={14} />
</button>
</div>
);
}

17
frontend/lib/toast.ts Normal file
View File

@@ -0,0 +1,17 @@
// 零依赖的事件总线式 toast,避免在每个交互组件里包 Context
export type ToastVariant = "error" | "ok";
export interface ToastDetail {
id: number;
message: string;
variant: ToastVariant;
}
export function toast(message: string, variant: ToastVariant = "error") {
if (typeof window === "undefined") return;
window.dispatchEvent(
new CustomEvent<ToastDetail>("j13-toast", {
detail: { id: Date.now() + Math.random(), message, variant },
})
);
}

View File

@@ -1,7 +1,7 @@
/// <reference types="next" /> /// <reference types="next" />
/// <reference types="next/image-types/global" /> /// <reference types="next/image-types/global" />
import "./.next/dev/types/routes.d.ts"; import "./.next/types/routes.d.ts";
import "./.next/dev/types/root-params.d.ts"; import "./.next/types/root-params.d.ts";
// NOTE: This file should not be edited // NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information. // see https://nextjs.org/docs/app/api-reference/config/typescript for more information.