首次提交:姜十三论坛

后端 Go+Gin:认证/CSRF/限流、板块、帖子、评论、点赞、通知、用户资料、置顶推荐;前端 Next.js 16:发帖/编辑/删除、搜索、分页、点赞、通知中心、设置;基础设施 docker-compose 与配置模板;添加 .gitignore 与专有许可证(保留所有权利)
This commit is contained in:
2026-09-12 01:11:05 +08:00
commit 0c2b0d2d6a
62 changed files with 8289 additions and 0 deletions

View File

@@ -0,0 +1,83 @@
import Link from "next/link";
import { Metadata } from "next";
import { fetchPosts, fetchBoards } from "@/lib/api";
import Pagination from "@/components/Pagination";
interface PageProps {
params: Promise<{ id: string }>;
searchParams: Promise<{ page?: string }>;
}
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
const { id } = await params;
const { boards } = await fetchBoards();
const board = boards.find((b) => b.id === Number(id));
return {
title: board ? `${board.name} - 姜十三论坛` : "板块 - 姜十三论坛",
description: board?.description || "板块帖子列表",
};
}
export default async function BoardPage({ params, searchParams }: PageProps) {
const { id } = await params;
const { page: pageStr } = await searchParams;
const page = Math.max(1, parseInt(pageStr || "1", 10) || 1);
const [postsData, boardsData] = await Promise.all([
fetchPosts(page, 20, Number(id)),
fetchBoards(),
]);
const board = boardsData.boards.find((b) => b.id === Number(id));
return (
<div>
<nav className="text-sm mb-4" style={{ color: "var(--text-secondary)" }}>
<Link href="/" className="hover:underline">首页</Link>
<span className="mx-2">/</span>
<span>{board?.name || "板块"}</span>
</nav>
<h1 className="text-2xl font-bold mb-2">{board?.name}</h1>
<p className="mb-6" style={{ color: "var(--text-secondary)" }}>{board?.description}</p>
<div className="space-y-3">
{postsData.posts.map((post) => (
<Link
key={post.id}
href={`/post/${post.id}`}
className="block 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>
<h2 className="font-semibold mb-1 hover:underline">{post.title}</h2>
<div className="flex items-center gap-4 text-sm" style={{ color: "var(--text-secondary)" }}>
<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>
</Link>
))}
{postsData.posts.length === 0 && (
<p className="text-center py-12" style={{ color: "var(--text-secondary)" }}>
该板块暂无帖子
</p>
)}
</div>
<Pagination
total={postsData.total}
page={page}
size={20}
basePath={`/board/${id}`}
/>
</div>
);
}

View File

@@ -0,0 +1,122 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { apiCreatePost, apiMe, fetchBoards, type Board } from "@/lib/api";
export default function ComposePage() {
const router = useRouter();
const [boards, setBoards] = useState<Board[]>([]);
const [boardId, setBoardId] = useState<number>(0);
const [title, setTitle] = useState("");
const [content, setContent] = useState("");
const [tags, setTags] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
useEffect(() => {
// 通过 /api/me 检查登录态(HttpOnly cookie 自动携带)
apiMe()
.then((res) => {
if (!res.user) {
router.push("/login?redirect=/compose");
return;
}
fetchBoards().then((data) => {
setBoards(data.boards);
if (data.boards.length > 0) setBoardId(data.boards[0].id);
});
})
.catch(() => router.push("/login?redirect=/compose"));
}, [router]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError("");
try {
const res = await apiCreatePost({
board_id: boardId,
title,
content,
tags,
post_type: "normal",
});
if (res.post) {
router.push(`/post/${res.post.id}`);
} else {
setError(res.error || "发帖失败");
}
} finally {
setLoading(false);
}
};
return (
<div className="max-w-3xl mx-auto">
<h1 className="text-2xl font-bold mb-6">发布新帖</h1>
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<div className="p-3 rounded-lg bg-red-50 text-red-600 text-sm">{error}</div>
)}
<div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>板块</label>
<select
value={boardId}
onChange={(e) => setBoardId(Number(e.target.value))}
className="w-full px-3 py-2 rounded-lg border"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
>
{boards.map((b) => (
<option key={b.id} value={b.id}>{b.name}</option>
))}
</select>
</div>
<div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>标题</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
required
maxLength={256}
placeholder="帖子标题"
className="w-full px-3 py-2 rounded-lg border"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/>
</div>
<div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>标签(逗号分隔,可选)</label>
<input
type="text"
value={tags}
onChange={(e) => setTags(e.target.value)}
placeholder="例如:技术,Go"
className="w-full px-3 py-2 rounded-lg border"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/>
</div>
<div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>内容(支持 Markdown)</label>
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
required
rows={12}
placeholder="帖子内容,支持 Markdown 格式..."
className="w-full px-3 py-2 rounded-lg border resize-y font-mono"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/>
</div>
<button
type="submit"
disabled={loading || !title.trim() || !content.trim()}
className="px-6 py-2 rounded-lg text-white disabled:opacity-50"
style={{ background: "var(--primary)" }}
>
{loading ? "发布中..." : "发布帖子"}
</button>
</form>
</div>
);
}

40
frontend/app/globals.css Normal file
View File

@@ -0,0 +1,40 @@
@import "tailwindcss";
:root {
--bg: #ffffff;
--bg-secondary: #f8fafc;
--text: #1e293b;
--text-secondary: #64748b;
--border: #e2e8f0;
--primary: #3b82f6;
--primary-hover: #2563eb;
}
.dark {
--bg: #0f172a;
--bg-secondary: #1e293b;
--text: #e2e8f0;
--text-secondary: #94a3b8;
--border: #334155;
--primary: #60a5fa;
--primary-hover: #3b82f6;
}
body {
background-color: var(--bg);
color: var(--text);
}
/* Markdown 内容样式 */
.prose-content h1 { font-size: 1.875rem; font-weight: 700; margin: 1rem 0; }
.prose-content h2 { font-size: 1.5rem; font-weight: 700; margin: 1rem 0; }
.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; }
.prose-content ol { list-style: decimal; padding-left: 1.5rem; margin: 0.75rem 0; }
.prose-content code { background: var(--bg-secondary); padding: 0.125rem 0.375rem; border-radius: 0.25rem; font-size: 0.875rem; }
.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; }
.prose-content blockquote { border-left: 4px solid var(--border); padding-left: 1rem; color: var(--text-secondary); margin: 1rem 0; }
.prose-content a { color: var(--primary); text-decoration: underline; }
.prose-content img { max-width: 100%; border-radius: 0.5rem; }

36
frontend/app/layout.tsx Normal file
View File

@@ -0,0 +1,36 @@
import type { Metadata } from "next";
import { cookies } from "next/headers";
import "./globals.css";
import Header from "@/components/Header";
import Footer from "@/components/Footer";
export const metadata: Metadata = {
title: "姜十三论坛",
description: "姜十三论坛 - 技术分享与讨论社区",
openGraph: {
title: "姜十三论坛",
description: "姜十三论坛 - 技术分享与讨论社区",
type: "website",
},
};
export default async function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
const cookieStore = await cookies();
const theme = cookieStore.get("j13-theme")?.value || "light";
return (
<html lang="zh-CN" className={theme === "dark" ? "dark" : ""}>
<body className="min-h-screen flex flex-col">
<Header />
<main className="flex-1 max-w-5xl mx-auto w-full px-4 py-6">
{children}
</main>
<Footer />
</body>
</html>
);
}

View File

@@ -0,0 +1,77 @@
"use client";
import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import { apiLogin } from "@/lib/api";
export default function LoginPage() {
const router = useRouter();
const searchParams = useSearchParams();
const redirect = searchParams.get("redirect") || "/";
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError("");
setLoading(true);
try {
const res = await apiLogin(username, password);
// 登录成功后后端通过 Set-Cookie 写入 HttpOnly JWT,前端无需存储 token
if (res.user) {
router.push(redirect);
} else {
setError(res.error || "登录失败");
}
} finally {
setLoading(false);
}
};
return (
<div className="max-w-md mx-auto mt-12">
<h1 className="text-2xl font-bold mb-6 text-center">登录</h1>
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<div className="p-3 rounded-lg bg-red-50 text-red-600 text-sm">{error}</div>
)}
<div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>用户名</label>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
className="w-full px-3 py-2 rounded-lg border"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/>
</div>
<div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>密码</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="w-full px-3 py-2 rounded-lg border"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/>
</div>
<button
type="submit"
disabled={loading}
className="w-full py-2 rounded-lg text-white disabled:opacity-50"
style={{ background: "var(--primary)" }}
>
{loading ? "登录中..." : "登录"}
</button>
</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>
</div>
);
}

View File

@@ -0,0 +1,131 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Heart, MessageCircle, CheckCheck } from "lucide-react";
import {
apiFetchNotifications,
apiMarkRead,
apiMarkAllRead,
type NotificationItem,
} from "@/lib/api";
export default function NotificationsPage() {
const router = useRouter();
const [notifications, setNotifications] = useState<NotificationItem[]>([]);
const [loading, setLoading] = useState(true);
const load = async () => {
setLoading(true);
try {
const res = await apiFetchNotifications(1);
setNotifications(res.notifications || []);
} catch {
setNotifications([]);
}
setLoading(false);
};
useEffect(() => {
load();
}, []);
const handleClick = async (n: NotificationItem) => {
if (!n.is_read) {
apiMarkRead(n.id).catch(() => {});
setNotifications((list) =>
list.map((item) => (item.id === n.id ? { ...item, is_read: true } : item))
);
}
router.push(`/post/${n.post_id}`);
};
const handleMarkAll = async () => {
await apiMarkAllRead();
setNotifications((list) => list.map((item) => ({ ...item, is_read: true })));
};
const formatTime = (dateStr: string) => {
const diff = Date.now() - new Date(dateStr).getTime();
const min = Math.floor(diff / 60000);
if (min < 1) return "刚刚";
if (min < 60) return `${min} 分钟前`;
const hour = Math.floor(min / 60);
if (hour < 24) return `${hour} 小时前`;
return `${Math.floor(hour / 24)} 天前`;
};
const hasUnread = notifications.some((n) => !n.is_read);
return (
<div className="max-w-2xl mx-auto">
<div className="flex items-center justify-between mb-6">
<h1 className="text-2xl font-bold" style={{ color: "var(--text)" }}>通知中心</h1>
{hasUnread && (
<button
onClick={handleMarkAll}
className="flex items-center gap-1 text-sm hover:opacity-80"
style={{ color: "var(--primary)" }}
>
<CheckCheck size={16} /> 全部标记已读
</button>
)}
</div>
{loading ? (
<p className="text-center py-12" style={{ color: "var(--text-secondary)" }}>加载中...</p>
) : notifications.length === 0 ? (
<p className="text-center py-12" style={{ color: "var(--text-secondary)" }}>暂无通知</p>
) : (
<div className="space-y-2">
{notifications.map((n) => (
<button
key={n.id}
onClick={() => handleClick(n)}
className="w-full text-left p-4 rounded-lg border hover:shadow-sm transition-shadow"
style={{
borderColor: "var(--border)",
background: n.is_read ? "var(--bg)" : "var(--bg-secondary)",
}}
>
<div className="flex items-start gap-3">
<span style={{ color: n.type === "like" ? "#ef4444" : "var(--primary)" }}>
{n.type === "like" ? <Heart size={18} /> : <MessageCircle size={18} />}
</span>
<div className="flex-1 min-w-0">
<p className="text-sm" style={{ color: "var(--text)" }}>
<Link
href={`/u/${n.actor.id}`}
onClick={(e) => e.stopPropagation()}
className="font-medium hover:underline"
>
{n.actor.nickname}
</Link>{" "}
<span style={{ color: "var(--text-secondary)" }}>
{n.type === "comment" ? "评论了你的帖子" : "点赞了你的帖子"}
</span>
</p>
<p className="text-sm mt-1 font-medium truncate" style={{ color: "var(--text)" }}>
《{n.post.title}》
</p>
{n.content && (
<p className="text-sm mt-1 line-clamp-2" style={{ color: "var(--text-secondary)" }}>
{n.content}
</p>
)}
<p className="text-xs mt-2" style={{ color: "var(--text-secondary)" }}>
{formatTime(n.created_at)}
</p>
</div>
{!n.is_read && (
<span className="w-2.5 h-2.5 rounded-full shrink-0 mt-1.5" style={{ background: "var(--primary)" }} />
)}
</div>
</button>
))}
</div>
)}
</div>
);
}

105
frontend/app/page.tsx Normal file
View File

@@ -0,0 +1,105 @@
import Link from "next/link";
import { Metadata } from "next";
import { fetchPosts, fetchBoards } from "@/lib/api";
import Pagination from "@/components/Pagination";
export const metadata: Metadata = {
title: "姜十三论坛 - 技术分享与讨论社区",
description: "姜十三论坛,分享技术、讨论问题、交流心得的社区",
openGraph: {
title: "姜十三论坛 - 技术分享与讨论社区",
description: "姜十三论坛,分享技术、讨论问题、交流心得的社区",
type: "website",
},
};
interface HomePageProps {
searchParams: Promise<{ q?: string; page?: string }>;
}
export default async function HomePage({ searchParams }: HomePageProps) {
const { q, page: pageStr } = await searchParams;
const keyword = q?.trim() || "";
const page = Math.max(1, parseInt(pageStr || "1", 10) || 1);
const [postsData, boardsData] = await Promise.all([
fetchPosts(page, 20, undefined, "latest", keyword),
fetchBoards(),
]);
return (
<div className="grid grid-cols-1 md:grid-cols-4 gap-6">
{/* 主内容:帖子列表 */}
<div className="md:col-span-3">
<h1 className="text-2xl font-bold mb-4">
{keyword ? `搜索结果:"${keyword}"` : "最新帖子"}
</h1>
<div className="space-y-3">
{postsData.posts.map((post) => (
<Link
key={post.id}
href={`/post/${post.id}`}
className="block 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>
<h2 className="font-semibold mb-1 hover:underline" style={{ color: "var(--text)" }}>
{post.title}
</h2>
<div className="flex items-center gap-4 text-sm" style={{ color: "var(--text-secondary)" }}>
<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>
</Link>
))}
{postsData.posts.length === 0 && (
<p className="text-center py-12" style={{ color: "var(--text-secondary)" }}>
{keyword ? "没有找到相关帖子" : "暂无帖子,来发第一篇吧!"}
</p>
)}
</div>
<Pagination
total={postsData.total}
page={page}
size={20}
basePath="/"
query={keyword ? { q: keyword } : {}}
/>
</div>
{/* 侧边栏:板块列表 */}
<aside className="md:col-span-1">
<h2 className="text-lg font-bold mb-3">板块</h2>
<div className="space-y-2">
{boardsData.boards.map((board) => (
<Link
key={board.id}
href={`/board/${board.id}`}
className="block p-3 rounded-lg border hover:shadow-sm transition-shadow"
style={{ borderColor: "var(--border)", background: "var(--bg-secondary)" }}
>
<div className="font-medium" style={{ color: "var(--text)" }}>{board.name}</div>
<div className="text-xs mt-1" style={{ color: "var(--text-secondary)" }}>{board.description}</div>
</Link>
))}
</div>
</aside>
</div>
);
}

View File

@@ -0,0 +1,137 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { fetchPostDetail, apiMe, apiUpdatePost, type Post, type User } from "@/lib/api";
interface EditPageProps {
params: Promise<{ id: string }>;
}
export default function EditPostPage({ params }: EditPageProps) {
const router = useRouter();
const [post, setPost] = useState<Post | null>(null);
const [user, setUser] = useState<User | null>(null);
const [title, setTitle] = useState("");
const [content, setContent] = useState("");
const [tags, setTags] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [checking, setChecking] = useState(true);
// params 是 Promise,需要解包
const [id, setId] = useState("");
useEffect(() => {
params.then((p) => setId(p.id));
}, [params]);
// 加载帖子 + 校验权限
useEffect(() => {
if (!id) return;
Promise.all([fetchPostDetail(id), apiMe()])
.then(([postData, meData]) => {
setPost(postData.post);
setTitle(postData.post.title);
setContent(postData.post.content);
setTags(postData.post.tags || "");
const u = meData.user;
setUser(u || null);
// 非作者且非管理员 → 跳转
if (!u || (u.id !== postData.post.user.id && u.role !== "admin")) {
router.push(`/post/${id}`);
}
})
.catch(() => router.push(`/post/${id}`))
.finally(() => setChecking(false));
}, [id, router]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!post) return;
setLoading(true);
setError("");
try {
const res = await apiUpdatePost(String(post.id), { title, content, tags });
if (res.post) {
router.push(`/post/${post.id}`);
} else {
setError(res.error || "更新失败");
}
} finally {
setLoading(false);
}
};
if (checking) {
return (
<div className="max-w-3xl mx-auto mt-12 text-center" style={{ color: "var(--text-secondary)" }}>
加载中...
</div>
);
}
if (!post) return null;
return (
<div className="max-w-3xl mx-auto">
<h1 className="text-2xl font-bold mb-6">编辑帖子</h1>
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<div className="p-3 rounded-lg bg-red-50 text-red-600 text-sm">{error}</div>
)}
<div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>标题</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
required
maxLength={256}
className="w-full px-3 py-2 rounded-lg border"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/>
</div>
<div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>标签(逗号分隔,可选)</label>
<input
type="text"
value={tags}
onChange={(e) => setTags(e.target.value)}
placeholder="例如:技术,Go"
className="w-full px-3 py-2 rounded-lg border"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/>
</div>
<div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>内容(支持 Markdown)</label>
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
required
rows={12}
className="w-full px-3 py-2 rounded-lg border resize-y font-mono"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/>
</div>
<div className="flex gap-3">
<button
type="submit"
disabled={loading || !title.trim() || !content.trim()}
className="px-6 py-2 rounded-lg text-white disabled:opacity-50"
style={{ background: "var(--primary)" }}
>
{loading ? "保存中..." : "保存修改"}
</button>
<button
type="button"
onClick={() => router.push(`/post/${post.id}`)}
className="px-6 py-2 rounded-lg"
style={{ background: "var(--bg-secondary)", color: "var(--text)" }}
>
取消
</button>
</div>
</form>
</div>
);
}

View File

@@ -0,0 +1,98 @@
import { Metadata } from "next";
import Link from "next/link";
import ReactMarkdown from "react-markdown";
import { fetchPostDetail, fetchComments } from "@/lib/api";
import CommentSection from "@/components/CommentSection";
import PostActions from "@/components/PostActions";
import LikeButton from "@/components/LikeButton";
interface PageProps {
params: Promise<{ id: string }>;
}
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
const { id } = await params;
try {
const { post } = await fetchPostDetail(id);
return {
title: `${post.title} - 姜十三论坛`,
description: post.content.slice(0, 160),
openGraph: {
title: post.title,
description: post.content.slice(0, 160),
type: "article",
},
};
} catch {
return { title: "帖子不存在 - 姜十三论坛" };
}
}
export default async function PostDetailPage({ params }: PageProps) {
const { id } = await params;
const { post } = await fetchPostDetail(id);
const { comments } = await fetchComments(id);
const jsonLd = {
"@context": "https://schema.org",
"@type": "DiscussionForumPosting",
headline: post.title,
articleBody: post.content,
datePublished: post.created_at,
dateModified: post.updated_at,
author: {
"@type": "Person",
name: post.user.nickname,
},
commentCount: post.comment_count,
interactionStatistic: {
"@type": "InteractionCounter",
interactionType: { "@type": "ReadAction" },
userInteractionCount: post.view_count,
},
};
return (
<article className="max-w-3xl mx-auto">
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
<nav className="text-sm mb-4" style={{ color: "var(--text-secondary)" }}>
<Link href="/" className="hover:underline">首页</Link>
<span className="mx-2">/</span>
<Link href={`/board/${post.board.id}`} className="hover:underline">{post.board.name}</Link>
</nav>
<div className="flex items-center gap-2 mb-3">
{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>
<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>
<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>
<PostActions postId={id} authorId={post.user.id} pinned={post.pinned} recommended={post.recommended} />
</div>
<div className="prose-content mb-8" style={{ color: "var(--text)" }}>
<ReactMarkdown>{post.content}</ReactMarkdown>
</div>
<CommentSection postId={id} comments={comments} />
</article>
);
}

View File

@@ -0,0 +1,88 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { apiRegister } from "@/lib/api";
export default function RegisterPage() {
const router = useRouter();
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError("");
setLoading(true);
try {
const res = await apiRegister(username, email, password);
if (res.id) {
router.push("/login");
} else {
setError(res.error || "注册失败");
}
} finally {
setLoading(false);
}
};
return (
<div className="max-w-md mx-auto mt-12">
<h1 className="text-2xl font-bold mb-6 text-center">注册</h1>
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<div className="p-3 rounded-lg bg-red-50 text-red-600 text-sm">{error}</div>
)}
<div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>用户名</label>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
minLength={3}
maxLength={32}
className="w-full px-3 py-2 rounded-lg border"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/>
</div>
<div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>邮箱(可选)</label>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="w-full px-3 py-2 rounded-lg border"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/>
</div>
<div>
<label className="block text-sm mb-1" style={{ color: "var(--text-secondary)" }}>密码</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
minLength={6}
className="w-full px-3 py-2 rounded-lg border"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/>
</div>
<button
type="submit"
disabled={loading}
className="w-full py-2 rounded-lg text-white disabled:opacity-50"
style={{ background: "var(--primary)" }}
>
{loading ? "注册中..." : "注册"}
</button>
</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>
</div>
);
}

11
frontend/app/robots.ts Normal file
View File

@@ -0,0 +1,11 @@
import type { MetadataRoute } from "next";
export default function robots(): MetadataRoute.Robots {
return {
rules: {
userAgent: "*",
allow: "/",
},
sitemap: "http://localhost:3000/sitemap.xml",
};
}

View File

@@ -0,0 +1,139 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { apiChangePassword, apiMe, type User } from "@/lib/api";
export default function SettingsPage() {
const router = useRouter();
const [user, setUser] = useState<User | null>(null);
const [oldPassword, setOldPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState("");
const [success, setSuccess] = useState(false);
useEffect(() => {
apiMe()
.then((res) => {
if (!res.user) {
router.push("/login");
return;
}
setUser(res.user);
})
.catch(() => router.push("/login"));
}, [router]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError("");
if (newPassword.length < 6) {
setError("新密码至少 6 位");
return;
}
if (newPassword !== confirmPassword) {
setError("两次输入的新密码不一致");
return;
}
setSubmitting(true);
try {
const res = await apiChangePassword(oldPassword, newPassword);
if (res.message) {
setSuccess(true);
setTimeout(() => router.push("/login"), 1500);
} else {
setError(res.error || "修改失败");
}
} catch (e) {
setError("网络错误,请重试");
} finally {
setSubmitting(false);
}
};
if (!user) {
return <p style={{ color: "var(--text-secondary)" }}>加载中...</p>;
}
return (
<div className="max-w-md mx-auto">
<nav className="text-sm mb-4" style={{ color: "var(--text-secondary)" }}>
<Link href="/" className="hover:underline">首页</Link>
<span className="mx-2">/</span>
<span>账号设置</span>
</nav>
<h1 className="text-2xl font-bold mb-6">账号设置</h1>
<div className="p-4 rounded-lg mb-6" style={{ background: "var(--bg-secondary)" }}>
<div className="text-sm" style={{ color: "var(--text-secondary)" }}>当前账号</div>
<div className="font-medium mt-1" style={{ color: "var(--text)" }}>{user.nickname}({user.username})</div>
</div>
<h2 className="text-lg font-semibold mb-4">修改密码</h2>
{success && (
<div className="p-3 rounded-lg mb-4 text-sm" style={{ background: "var(--success-bg, #dcfce7)", color: "#166534" }}>
密码修改成功,正在跳转登录页...
</div>
)}
{error && (
<div className="p-3 rounded-lg mb-4 text-sm" style={{ background: "var(--error-bg, #fee2e2)", color: "#991b1b" }}>
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium mb-1" style={{ color: "var(--text)" }}>当前密码</label>
<input
type="password"
value={oldPassword}
onChange={(e) => setOldPassword(e.target.value)}
required
className="w-full p-3 rounded-lg border"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/>
</div>
<div>
<label className="block text-sm font-medium mb-1" style={{ color: "var(--text)" }}>新密码</label>
<input
type="password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
required
minLength={6}
className="w-full p-3 rounded-lg border"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/>
</div>
<div>
<label className="block text-sm font-medium mb-1" style={{ color: "var(--text)" }}>确认新密码</label>
<input
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
required
minLength={6}
className="w-full p-3 rounded-lg border"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/>
</div>
<button
type="submit"
disabled={submitting || success}
className="w-full py-3 rounded-lg text-white font-medium disabled:opacity-50"
style={{ background: "var(--primary)" }}
>
{submitting ? "提交中..." : "修改密码"}
</button>
</form>
</div>
);
}

35
frontend/app/sitemap.ts Normal file
View File

@@ -0,0 +1,35 @@
import type { MetadataRoute } from "next";
import { fetchPosts, fetchBoards } from "@/lib/api";
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const baseUrl = "http://localhost:3000";
const entries: MetadataRoute.Sitemap = [
{ url: `${baseUrl}/`, lastModified: new Date(), changeFrequency: "daily", priority: 1 },
];
try {
const { boards } = await fetchBoards();
for (const board of boards) {
entries.push({
url: `${baseUrl}/board/${board.id}`,
lastModified: new Date(),
changeFrequency: "daily",
priority: 0.8,
});
}
const { posts } = await fetchPosts(1, 100);
for (const post of posts) {
entries.push({
url: `${baseUrl}/post/${post.id}`,
lastModified: new Date(post.created_at),
changeFrequency: "weekly",
priority: 0.6,
});
}
} catch {
/* 忽略 API 错误 */
}
return entries;
}

View File

@@ -0,0 +1,148 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import { fetchUserComments, type UserProfile, type UserCommentsResponse } from "@/lib/api";
import Pagination from "@/components/Pagination";
interface UserProfileClientProps {
userId: string;
initialPosts: UserProfile;
initialPage: number;
}
type Tab = "posts" | "comments";
export default function UserProfileClient({ userId, initialPosts, initialPage }: UserProfileClientProps) {
const [tab, setTab] = useState<Tab>("posts");
const [commentData, setCommentData] = useState<UserCommentsResponse | null>(null);
const [commentLoading, setCommentLoading] = useState(false);
const [commentPage, setCommentPage] = useState(1);
const loadComments = async (page: number) => {
setCommentLoading(true);
try {
const data = await fetchUserComments(userId, page);
setCommentData({ ...data, comments: data.comments || [] });
setCommentPage(page);
} catch {
setCommentData({ comments: [], total: 0, page, size: 20 });
}
setCommentLoading(false);
};
const handleTabChange = (t: Tab) => {
setTab(t);
if (t === "comments" && commentData === null) {
loadComments(1);
}
};
const tabBtn = (t: Tab, label: string) => (
<button
onClick={() => handleTabChange(t)}
className="px-4 py-2 rounded-lg text-sm font-medium transition-colors"
style={
tab === t
? { background: "var(--primary)", color: "white" }
: { background: "var(--bg-secondary)", color: "var(--text-secondary)" }
}
>
{label}
</button>
);
return (
<div>
<div className="flex gap-2 mb-5">
{tabBtn("posts", `发帖 (${initialPosts.stats.post_count})`)}
{tabBtn("comments", `评论 (${initialPosts.stats.comment_count})`)}
</div>
{tab === "posts" ? (
<div className="space-y-3">
{initialPosts.posts.map((post) => (
<Link
key={post.id}
href={`/post/${post.id}`}
className="block 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>
<h2 className="font-semibold mb-1 hover:underline" style={{ color: "var(--text)" }}>
{post.title}
</h2>
<div className="flex items-center gap-4 text-sm" style={{ color: "var(--text-secondary)" }}>
<span>{new Date(post.created_at).toLocaleDateString("zh-CN")}</span>
<span>💬 {post.comment_count}</span>
<span>👁 {post.view_count}</span>
<span>❤️ {post.like_count}</span>
</div>
</Link>
))}
{initialPosts.posts.length === 0 && (
<p className="text-center py-12" style={{ color: "var(--text-secondary)" }}>
暂无发帖
</p>
)}
<Pagination
total={initialPosts.posts_total}
page={initialPage}
size={20}
basePath={`/u/${userId}`}
/>
</div>
) : (
<div className="space-y-3">
{commentLoading ? (
<p className="text-center py-12" style={{ color: "var(--text-secondary)" }}>加载中...</p>
) : commentData && commentData.comments.length > 0 ? (
<>
{commentData.comments.map((c) => (
<Link
key={c.id}
href={`/post/${c.post_id}`}
className="block p-4 rounded-lg border hover:shadow-md transition-shadow"
style={{ borderColor: "var(--border)", background: "var(--bg)" }}
>
<div className="text-sm mb-2" style={{ color: "var(--text-secondary)" }}>
评论于 <span className="hover:underline" style={{ color: "var(--primary)" }}>{c.post_title}</span>
</div>
<p className="line-clamp-2" style={{ color: "var(--text)" }}>{c.content}</p>
<div className="text-xs mt-2" style={{ color: "var(--text-secondary)" }}>
{new Date(c.created_at).toLocaleString("zh-CN")}
</div>
</Link>
))}
<Pagination
total={commentData.total}
page={commentPage}
size={20}
basePath={`/u/${userId}`}
query={{ tab: "comments" }}
onChange={loadComments}
/>
</>
) : (
<p className="text-center py-12" style={{ color: "var(--text-secondary)" }}>
暂无评论
</p>
)}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,93 @@
import Link from "next/link";
import { Metadata } from "next";
import { fetchUserProfile, type UserProfile } from "@/lib/api";
import Pagination from "@/components/Pagination";
import UserProfileClient from "./UserProfileClient";
interface UserPageProps {
params: Promise<{ id: string }>;
searchParams: Promise<{ page?: string; tab?: string }>;
}
export async function generateMetadata({ params }: UserPageProps): Promise<Metadata> {
const { id } = await params;
return {
title: `用户资料 - 姜十三论坛`,
description: `查看用户 ${id} 的资料、发帖与评论`,
};
}
export default async function UserPage({ params, searchParams }: UserPageProps) {
const { id } = await params;
const { page: pageStr } = await searchParams;
const page = Math.max(1, parseInt(pageStr || "1", 10) || 1);
let data: UserProfile;
try {
data = await fetchUserProfile(id, page);
} catch {
return (
<div className="text-center py-16" style={{ color: "var(--text-secondary)" }}>
<p className="text-lg">用户不存在</p>
<Link href="/" className="mt-4 inline-block hover:underline" style={{ color: "var(--primary)" }}>
返回首页
</Link>
</div>
);
}
const u = data.user;
const roleLabel = u.role === "admin" ? "管理员" : "用户";
return (
<div className="max-w-4xl mx-auto">
{/* 用户信息卡片 */}
<div
className="rounded-xl border p-6 mb-6 flex items-start gap-5"
style={{ borderColor: "var(--border)", background: "var(--bg)" }}
>
<div
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)" }}
>
{u.avatar ? (
<img src={u.avatar} alt={u.nickname} className="w-full h-full rounded-full object-cover" />
) : (
(u.nickname || u.username).charAt(0).toUpperCase()
)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<h1 className="text-2xl font-bold" style={{ color: "var(--text)" }}>
{u.nickname || u.username}
</h1>
{u.role === "admin" && (
<span
className="text-xs px-2 py-0.5 rounded font-medium"
style={{ background: "var(--primary)", color: "white" }}
>
{roleLabel}
</span>
)}
</div>
<p className="text-sm mt-1" style={{ color: "var(--text-secondary)" }}>
@{u.username} · 加入于 {new Date(u.created_at).toLocaleDateString("zh-CN")}
</p>
<div className="flex gap-6 mt-3 text-sm">
<span style={{ color: "var(--text)" }}>
<strong>{data.stats.post_count}</strong>{" "}
<span style={{ color: "var(--text-secondary)" }}>帖子</span>
</span>
<span style={{ color: "var(--text)" }}>
<strong>{data.stats.comment_count}</strong>{" "}
<span style={{ color: "var(--text-secondary)" }}>评论</span>
</span>
</div>
</div>
</div>
{/* 发帖 / 评论 切换 */}
<UserProfileClient userId={id} initialPosts={data} initialPage={page} />
</div>
);
}

View File

@@ -0,0 +1,121 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Trash2 } from "lucide-react";
import { apiCreateComment, apiDeleteComment, apiMe, type Comment, type User } from "@/lib/api";
interface CommentSectionProps {
postId: string;
comments: Comment[];
}
export default function CommentSection({ postId, comments }: CommentSectionProps) {
const router = useRouter();
const [content, setContent] = useState("");
const [submitting, setSubmitting] = useState(false);
const [user, setUser] = useState<User | null>(null);
const [deletingId, setDeletingId] = useState<number | null>(null);
useEffect(() => {
apiMe()
.then((res) => setUser(res.user || null))
.catch(() => setUser(null));
}, []);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!content.trim()) return;
setSubmitting(true);
try {
const res = await apiCreateComment(postId, content);
if (res.comment) {
setContent("");
router.refresh();
} else if (res.error === "未登录") {
router.push("/login");
} else {
alert(res.error || "评论失败");
}
} finally {
setSubmitting(false);
}
};
const handleDelete = async (commentId: number) => {
if (!confirm("确定要删除这条评论吗?")) return;
setDeletingId(commentId);
try {
const res = await apiDeleteComment(postId, commentId);
if (res.message) {
router.refresh();
} else {
alert(res.error || "删除失败");
}
} finally {
setDeletingId(null);
}
};
const canDelete = (comment: Comment) =>
user && (user.id === comment.user.id || user.role === "admin");
return (
<section className="mt-8 pt-6 border-t" style={{ borderColor: "var(--border)" }}>
<h2 className="text-xl font-bold mb-4">评论 ({comments.length})</h2>
<form onSubmit={handleSubmit} className="mb-6">
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="写下你的评论..."
className="w-full p-3 rounded-lg border resize-none h-24"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/>
<button
type="submit"
disabled={submitting || !content.trim()}
className="mt-2 px-4 py-2 rounded-lg text-white disabled:opacity-50"
style={{ background: "var(--primary)" }}
>
{submitting ? "发送中..." : "发表评论"}
</button>
</form>
<div className="space-y-4">
{comments.map((comment) => (
<div key={comment.id} className="p-4 rounded-lg" style={{ background: "var(--bg-secondary)" }}>
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-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>
</div>
{canDelete(comment) && (
<button
onClick={() => handleDelete(comment.id)}
disabled={deletingId === comment.id}
className="flex items-center gap-1 text-sm text-red-600 hover:opacity-80 disabled:opacity-50"
>
<Trash2 size={14} />
{deletingId === comment.id ? "删除中" : "删除"}
</button>
)}
</div>
<p style={{ color: "var(--text)" }}>{comment.content}</p>
</div>
))}
{comments.length === 0 && (
<p className="text-center py-8" style={{ color: "var(--text-secondary)" }}>
暂无评论,来抢沙发吧!
</p>
)}
</div>
</section>
);
}

View File

@@ -0,0 +1,7 @@
export default function Footer() {
return (
<footer className="border-t py-6 text-center text-sm" style={{ borderColor: "var(--border)", color: "var(--text-secondary)" }}>
<p>姜十三论坛 · Powered by Go 1.27 + Next.js 16</p>
</footer>
);
}

View File

@@ -0,0 +1,151 @@
"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState, useEffect } from "react";
import { Menu, X, Sun, Moon, LogIn, UserPlus, LogOut, PenSquare, Search, Settings } from "lucide-react";
import { apiMe, apiLogout, type User } from "@/lib/api";
import NotificationBell from "./NotificationBell";
export default function Header() {
const router = useRouter();
const [menuOpen, setMenuOpen] = useState(false);
const [theme, setTheme] = useState<"light" | "dark">("light");
const [user, setUser] = useState<User | null>(null);
const [searchQuery, setSearchQuery] = useState("");
const handleSearch = (e: React.FormEvent) => {
e.preventDefault();
const q = searchQuery.trim();
if (q) {
router.push(`/?q=${encodeURIComponent(q)}`);
}
};
useEffect(() => {
// 读取主题
const savedTheme = document.documentElement.classList.contains("dark") ? "dark" : "light";
setTheme(savedTheme);
// 从后端获取登录态(HttpOnly cookie 自动携带)
apiMe()
.then((res) => setUser(res.user || null))
.catch(() => setUser(null));
}, []);
const toggleTheme = () => {
const newTheme = theme === "dark" ? "light" : "dark";
setTheme(newTheme);
document.documentElement.classList.toggle("dark", newTheme === "dark");
document.cookie = `j13-theme=${newTheme}; path=/; max-age=31536000`;
};
const handleLogout = async () => {
try {
await apiLogout();
} catch {
/* ignore */
}
setUser(null);
setMenuOpen(false);
router.refresh();
};
return (
<header className="sticky top-0 z-50 border-b" style={{ borderColor: "var(--border)", background: "var(--bg)" }}>
<div className="max-w-5xl mx-auto px-4 h-14 flex items-center justify-between">
<Link href="/" className="font-bold text-lg" style={{ color: "var(--primary)" }}>
姜十三论坛
</Link>
{/* 桌面端导航 */}
<nav className="hidden md:flex items-center gap-4">
<form onSubmit={handleSearch} className="relative">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: "var(--text-secondary)" }} />
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="搜索帖子..."
className="pl-9 pr-3 py-1.5 rounded-lg text-sm w-44 focus:outline-none focus:w-56 transition-all"
style={{ background: "var(--bg-secondary)", color: "var(--text)", border: "1px solid var(--border)" }}
/>
</form>
<Link href="/" className="hover:opacity-80" style={{ color: "var(--text)" }}>首页</Link>
{user && (
<Link href="/compose" className="flex items-center gap-1 hover:opacity-80" style={{ color: "var(--text)" }}>
<PenSquare size={16} /> 发帖
</Link>
)}
<button onClick={toggleTheme} className="p-2 rounded-lg hover:opacity-80" style={{ color: "var(--text)" }}>
{theme === "dark" ? <Sun size={18} /> : <Moon size={18} />}
</button>
{user && <NotificationBell />}
{user ? (
<div className="flex items-center gap-3">
<span className="text-sm" style={{ color: "var(--text-secondary)" }}>{user.nickname}</span>
<Link href="/settings" className="flex items-center gap-1 text-sm hover:opacity-80" style={{ color: "var(--text-secondary)" }}>
<Settings size={14} /> 设置
</Link>
<button onClick={handleLogout} className="flex items-center gap-1 text-sm hover:opacity-80" style={{ color: "var(--text-secondary)" }}>
<LogOut size={14} /> 退出
</button>
</div>
) : (
<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)" }}>
<LogIn size={14} /> 登录
</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)" }}>
<UserPlus size={14} /> 注册
</Link>
</div>
)}
</nav>
{/* 移动端菜单按钮 */}
<button onClick={() => setMenuOpen(!menuOpen)} className="md:hidden p-2" style={{ color: "var(--text)" }}>
{menuOpen ? <X size={20} /> : <Menu size={20} />}
</button>
</div>
{/* 移动端下拉菜单 */}
{menuOpen && (
<div className="md:hidden border-t px-4 py-3 space-y-2" style={{ borderColor: "var(--border)", background: "var(--bg)" }}>
<form onSubmit={(e) => { handleSearch(e); setMenuOpen(false); }} className="relative">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: "var(--text-secondary)" }} />
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="搜索帖子..."
className="w-full pl-9 pr-3 py-2 rounded-lg text-sm"
style={{ background: "var(--bg-secondary)", color: "var(--text)", border: "1px solid var(--border)" }}
/>
</form>
<Link href="/" onClick={() => setMenuOpen(false)} className="block py-2" style={{ color: "var(--text)" }}>首页</Link>
{user && (
<Link href="/compose" onClick={() => setMenuOpen(false)} className="block py-2" style={{ color: "var(--text)" }}>发帖</Link>
)}
<button onClick={toggleTheme} className="block py-2 w-full text-left" style={{ color: "var(--text)" }}>
{theme === "dark" ? "切换亮色主题" : "切换暗色主题"}
</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>
)}
</header>
);
}

View File

@@ -0,0 +1,50 @@
"use client";
import { useState } from "react";
import { Heart } from "lucide-react";
import { apiToggleLike } from "@/lib/api";
interface LikeButtonProps {
postId: string;
liked: boolean;
likeCount: number;
}
export default function LikeButton({ postId, liked: initialLiked, likeCount: initialCount }: LikeButtonProps) {
const [liked, setLiked] = useState(initialLiked);
const [count, setCount] = useState(initialCount);
const [loading, setLoading] = useState(false);
const handleClick = async () => {
if (loading) return;
setLoading(true);
try {
const res = await apiToggleLike(postId);
if (res.error === "未登录") {
window.location.href = "/login";
return;
}
if (typeof res.liked === "boolean") {
setLiked(res.liked);
setCount(res.like_count ?? count);
}
} finally {
setLoading(false);
}
};
return (
<button
onClick={handleClick}
disabled={loading}
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-medium transition-all disabled:opacity-50 ${
liked
? "text-red-500 bg-red-50 dark:bg-red-900/20"
: "text-gray-500 hover:text-red-500 hover:bg-gray-100 dark:hover:bg-gray-800"
}`}
>
<Heart size={16} fill={liked ? "currentColor" : "none"} />
<span>{count}</span>
</button>
);
}

View File

@@ -0,0 +1,197 @@
"use client";
import { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Bell, CheckCheck, Heart, MessageCircle } from "lucide-react";
import {
apiFetchNotifications,
apiUnreadCount,
apiMarkRead,
apiMarkAllRead,
type NotificationItem,
} from "@/lib/api";
export default function NotificationBell() {
const router = useRouter();
const [open, setOpen] = useState(false);
const [unread, setUnread] = useState(0);
const [notifications, setNotifications] = useState<NotificationItem[]>([]);
const [loading, setLoading] = useState(false);
const dropdownRef = useRef<HTMLDivElement>(null);
// 轮询未读数(30 秒)
useEffect(() => {
const fetchCount = () => {
apiUnreadCount()
.then((res) => setUnread(res.count || 0))
.catch(() => {});
};
fetchCount();
const timer = setInterval(fetchCount, 30000);
return () => clearInterval(timer);
}, []);
// 点击外部关闭下拉
useEffect(() => {
const handleClick = (e: MouseEvent) => {
if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
setOpen(false);
}
};
document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, []);
const loadNotifications = async () => {
setLoading(true);
try {
const res = await apiFetchNotifications(1);
setNotifications(res.notifications || []);
} catch {
setNotifications([]);
}
setLoading(false);
};
const handleToggle = () => {
const next = !open;
setOpen(next);
if (next) {
loadNotifications();
}
};
const handleClickNotification = async (n: NotificationItem) => {
if (!n.is_read) {
apiMarkRead(n.id).catch(() => {});
setUnread((c) => Math.max(0, c - 1));
setNotifications((list) =>
list.map((item) => (item.id === n.id ? { ...item, is_read: true } : item))
);
}
setOpen(false);
router.push(`/post/${n.post_id}`);
};
const handleMarkAllRead = async () => {
await apiMarkAllRead();
setUnread(0);
setNotifications((list) => list.map((item) => ({ ...item, is_read: true })));
};
const formatTime = (dateStr: string) => {
const diff = Date.now() - new Date(dateStr).getTime();
const min = Math.floor(diff / 60000);
if (min < 1) return "刚刚";
if (min < 60) return `${min} 分钟前`;
const hour = Math.floor(min / 60);
if (hour < 24) return `${hour} 小时前`;
const day = Math.floor(hour / 24);
return `${day} 天前`;
};
const actionText = (n: NotificationItem) => {
if (n.type === "comment") return "评论了你的帖子";
return "点赞了你的帖子";
};
return (
<div className="relative" ref={dropdownRef}>
<button
onClick={handleToggle}
className="relative p-2 rounded-lg hover:opacity-80"
style={{ color: "var(--text)" }}
aria-label="通知"
>
<Bell size={18} />
{unread > 0 && (
<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"
style={{ background: "var(--primary)" }}
>
{unread > 99 ? "99+" : unread}
</span>
)}
</button>
{open && (
<div
className="absolute right-0 mt-2 w-80 rounded-xl border shadow-xl overflow-hidden z-50"
style={{ borderColor: "var(--border)", background: "var(--bg)" }}
>
<div
className="flex items-center justify-between px-4 py-3 border-b"
style={{ borderColor: "var(--border)" }}
>
<span className="font-semibold" style={{ color: "var(--text)" }}>通知</span>
{unread > 0 && (
<button
onClick={handleMarkAllRead}
className="flex items-center gap-1 text-xs hover:opacity-80"
style={{ color: "var(--primary)" }}
>
<CheckCheck size={14} /> 全部已读
</button>
)}
</div>
<div className="max-h-96 overflow-y-auto">
{loading ? (
<p className="text-center py-8 text-sm" style={{ color: "var(--text-secondary)" }}>加载中...</p>
) : notifications.length === 0 ? (
<p className="text-center py-8 text-sm" style={{ color: "var(--text-secondary)" }}>暂无通知</p>
) : (
notifications.map((n) => (
<button
key={n.id}
onClick={() => handleClickNotification(n)}
className="w-full text-left px-4 py-3 border-b hover:opacity-90 transition-opacity"
style={{
borderColor: "var(--border)",
background: n.is_read ? "transparent" : "var(--bg-secondary)",
}}
>
<div className="flex items-start gap-2">
<span style={{ color: n.type === "like" ? "#ef4444" : "var(--primary)" }}>
{n.type === "like" ? <Heart size={16} /> : <MessageCircle size={16} />}
</span>
<div className="flex-1 min-w-0">
<p className="text-sm" style={{ color: "var(--text)" }}>
<span className="font-medium">{n.actor.nickname}</span>{" "}
<span style={{ color: "var(--text-secondary)" }}>{actionText(n)}</span>
</p>
<p className="text-xs mt-0.5 truncate" style={{ color: "var(--text-secondary)" }}>
《{n.post.title}》
</p>
{n.content && (
<p className="text-xs mt-1 line-clamp-1" style={{ color: "var(--text-secondary)" }}>
{n.content}
</p>
)}
<p className="text-xs mt-1" style={{ color: "var(--text-secondary)" }}>
{formatTime(n.created_at)}
</p>
</div>
{!n.is_read && (
<span
className="w-2 h-2 rounded-full shrink-0 mt-1.5"
style={{ background: "var(--primary)" }}
/>
)}
</div>
</button>
))
)}
</div>
<div className="px-4 py-2 border-t text-center" style={{ borderColor: "var(--border)" }}>
<Link href="/notifications" className="text-sm hover:underline" style={{ color: "var(--primary)" }}>
查看全部通知
</Link>
</div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,95 @@
"use client";
import Link from "next/link";
import { ChevronLeft, ChevronRight } from "lucide-react";
interface PaginationProps {
total: number;
page: number;
size: number;
basePath: string; // e.g. "/" or "/board/1"
query?: Record<string, string>; // additional query params (e.g. q for search)
onChange?: (page: number) => void; // 客户端分页回调;提供时不渲染 Link 而是按钮
}
export default function Pagination({ total, page, size, basePath, query = {}, onChange }: PaginationProps) {
const totalPages = Math.max(1, Math.ceil(total / size));
if (totalPages <= 1) return null;
const buildHref = (p: number) => {
const params = new URLSearchParams(query);
params.set("page", String(p));
return `${basePath}?${params.toString()}`;
};
const handleClick = (p: number, e: React.MouseEvent) => {
if (onChange) {
e.preventDefault();
onChange(p);
}
};
// 生成页码按钮(最多显示 7 个,带省略号)
const pages: (number | "...")[] = [];
const add = (p: number | "...") => pages.push(p);
if (totalPages <= 7) {
for (let i = 1; i <= totalPages; i++) add(i);
} else {
add(1);
if (page > 4) add("...");
const start = Math.max(2, page - 1);
const end = Math.min(totalPages - 1, page + 1);
for (let i = start; i <= end; i++) add(i);
if (page < totalPages - 3) add("...");
add(totalPages);
}
return (
<nav className="flex items-center justify-center gap-1 mt-8">
{page > 1 && (
<Link
href={buildHref(page - 1)}
onClick={(e) => handleClick(page - 1, e)}
className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm hover:opacity-80"
style={{ background: "var(--bg-secondary)", color: "var(--text)" }}
>
<ChevronLeft size={16} /> 上一页
</Link>
)}
{pages.map((p, i) =>
p === "..." ? (
<span key={`e${i}`} className="px-2" style={{ color: "var(--text-secondary)" }}>…</span>
) : (
<Link
key={p}
href={buildHref(p)}
onClick={(e) => handleClick(p, e)}
className={`min-w-[36px] h-9 flex items-center justify-center rounded-lg text-sm ${
p === page ? "text-white" : "hover:opacity-80"
}`}
style={
p === page
? { background: "var(--primary)" }
: { background: "var(--bg-secondary)", color: "var(--text)" }
}
>
{p}
</Link>
)
)}
{page < totalPages && (
<Link
href={buildHref(page + 1)}
onClick={(e) => handleClick(page + 1, e)}
className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm hover:opacity-80"
style={{ background: "var(--bg-secondary)", color: "var(--text)" }}
>
下一页 <ChevronRight size={16} />
</Link>
)}
</nav>
);
}

View File

@@ -0,0 +1,117 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Pencil, Trash2, Pin, Star } from "lucide-react";
import { apiMe, apiDeletePost, apiTogglePin, apiToggleRecommend, type User } from "@/lib/api";
interface PostActionsProps {
postId: string;
authorId: number;
pinned: number;
recommended: boolean;
}
export default function PostActions({ postId, authorId, pinned, recommended }: PostActionsProps) {
const router = useRouter();
const [user, setUser] = useState<User | null>(null);
const [deleting, setDeleting] = useState(false);
const [isPinned, setIsPinned] = useState(pinned > 0);
const [isRecommended, setIsRecommended] = useState(recommended);
const [acting, setActing] = useState("");
useEffect(() => {
apiMe()
.then((res) => setUser(res.user || null))
.catch(() => setUser(null));
}, []);
// 仅作者本人或管理员可编辑/删除;置顶/推荐仅管理员
const canManage = user && (user.id === authorId || user.role === "admin");
const isAdmin = user?.role === "admin";
if (!canManage) return null;
const handleDelete = async () => {
if (!confirm("确定要删除这篇帖子吗?此操作不可恢复。")) return;
setDeleting(true);
try {
const res = await apiDeletePost(postId);
if (res.message) {
router.push("/");
} else {
alert(res.error || "删除失败");
}
} finally {
setDeleting(false);
}
};
const handlePin = async () => {
setActing("pin");
try {
const res = await apiTogglePin(postId);
setIsPinned(res.pinned > 0);
router.refresh();
} finally {
setActing("");
}
};
const handleRecommend = async () => {
setActing("recommend");
try {
const res = await apiToggleRecommend(postId);
setIsRecommended(res.recommended);
router.refresh();
} finally {
setActing("");
}
};
return (
<div className="flex items-center gap-2 flex-wrap justify-end">
{isAdmin && (
<>
<button
onClick={handlePin}
disabled={acting !== ""}
className="flex items-center gap-1 text-sm px-3 py-1.5 rounded-lg hover:opacity-80 disabled:opacity-50"
style={{
background: isPinned ? "var(--primary)" : "var(--bg-secondary)",
color: isPinned ? "white" : "var(--text)",
}}
>
<Pin size={14} /> {isPinned ? "取消置顶" : "置顶"}
</button>
<button
onClick={handleRecommend}
disabled={acting !== ""}
className="flex items-center gap-1 text-sm px-3 py-1.5 rounded-lg hover:opacity-80 disabled:opacity-50"
style={{
background: isRecommended ? "#e11d48" : "var(--bg-secondary)",
color: isRecommended ? "white" : "var(--text)",
}}
>
<Star size={14} /> {isRecommended ? "取消推荐" : "推荐"}
</button>
</>
)}
<Link
href={`/post/${postId}/edit`}
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>
<button
onClick={handleDelete}
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>
</div>
);
}

395
frontend/lib/api.ts Normal file
View File

@@ -0,0 +1,395 @@
// API 基础配置
// 注意:客户端请求使用相对路径 /api/*,走 Next.js rewrite 代理到后端,
// 这样浏览器视为同源,Cookie 自动携带,无需处理 CORS。
// SSR 端(fetchPosts 等公开接口)直接请求后端 API_BASE。
const API_BASE = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
// 类型定义
export interface User {
id: number;
username: string;
nickname: string;
avatar: string;
role: string;
}
export interface Board {
id: number;
name: string;
description: string;
icon: string;
sort_order: number;
}
export interface PostListItem {
id: number;
board_id: number;
user_id: number;
title: string;
tags: string;
post_type: string;
pinned: number;
recommended: boolean;
like_count: number;
view_count: number;
comment_count: number;
liked: boolean;
created_at: string;
board: Board;
user: User;
}
export interface Post {
id: number;
board_id: number;
user_id: number;
title: string;
content: string;
tags: string;
post_type: string;
pinned: number;
recommended: boolean;
status: string;
like_count: number;
view_count: number;
comment_count: number;
liked: boolean;
created_at: string;
updated_at: string;
board: Board;
user: User;
}
export interface Comment {
id: number;
post_id: number;
user_id: number;
content: string;
status: string;
created_at: string;
user: User;
}
export interface PostsResponse {
posts: PostListItem[];
total: number;
page: number;
size: number;
}
export interface UserProfile {
user: {
id: number;
username: string;
nickname: string;
avatar: string;
role: string;
created_at: string;
};
stats: {
post_count: number;
comment_count: number;
};
posts: PostListItem[];
posts_total: number;
page: number;
size: number;
}
export interface UserCommentItem {
id: number;
post_id: number;
post_title: string;
content: string;
created_at: string;
}
export interface UserCommentsResponse {
comments: UserCommentItem[];
total: number;
page: number;
size: number;
}
export interface NotificationItem {
id: number;
user_id: number;
actor_id: number;
type: "comment" | "like";
post_id: number;
comment_id: number;
content: string;
is_read: boolean;
created_at: string;
actor: User;
post: { id: number; title: string };
}
export interface NotificationsResponse {
notifications: NotificationItem[];
total: number;
page: number;
size: number;
}
// 从 cookie 读取 CSRF token(j13_csrf 为非 HttpOnly,前端可读)
function getCSRFToken(): string {
if (typeof document === "undefined") return "";
const match = document.cookie.match(/(?:^|;\s*)j13_csrf=([^;]+)/);
return match ? decodeURIComponent(match[1]) : "";
}
// 构造客户端 fetch 的通用 headers(含 CSRF token)
function clientHeaders(extra: Record<string, string> = {}): HeadersInit {
const headers: Record<string, string> = { ...extra };
const csrf = getCSRFToken();
if (csrf) headers["X-CSRF-Token"] = csrf;
return headers;
}
// ===== Refresh token 自动续期 =====
let refreshPromise: Promise<boolean> | null = null;
// 调用 /api/auth/refresh 刷新 access token(refresh cookie 由浏览器自动携带)
async function apiRefresh(): Promise<boolean> {
try {
const res = await fetch("/api/auth/refresh", {
method: "POST",
credentials: "include",
headers: clientHeaders(),
});
return res.ok;
} catch {
return false;
}
}
// 带自动续期的 fetch:遇到 401 时尝试 refresh,成功后重试原请求
async function fetchWithRefresh(url: string, init: RequestInit): Promise<Response> {
let res = await fetch(url, { ...init, credentials: "include" });
if (res.status === 401) {
// 串行化 refresh:多个并发 401 只触发一次 refresh
if (!refreshPromise) {
refreshPromise = apiRefresh().finally(() => {
refreshPromise = null;
});
}
const refreshed = await refreshPromise;
if (refreshed) {
// refresh 成功,重试原请求(CSRF cookie 可能已更新)
const newHeaders = clientHeaders();
const mergedInit = { ...init, credentials: "include" as const, headers: newHeaders };
res = await fetch(url, mergedInit);
}
}
return res;
}
// ===== SSR 端 fetch(公开接口,直接请求后端) =====
export async function fetchPosts(
page = 1,
size = 20,
boardId?: number,
sort = "latest",
keyword = ""
): Promise<PostsResponse> {
const params = new URLSearchParams({ page: String(page), size: String(size), sort });
if (boardId) params.set("board_id", String(boardId));
if (keyword) params.set("keyword", keyword);
const res = await fetch(`${API_BASE}/api/posts?${params}`, { cache: "no-store" });
if (!res.ok) throw new Error("获取帖子失败");
return res.json();
}
export async function fetchBoards(): Promise<{ boards: Board[] }> {
const res = await fetch(`${API_BASE}/api/boards`, { cache: "no-store" });
if (!res.ok) throw new Error("获取板块失败");
return res.json();
}
export async function fetchPostDetail(id: string): Promise<{ post: Post }> {
const res = await fetch(`${API_BASE}/api/posts/${id}`, { cache: "no-store" });
if (!res.ok) throw new Error("获取帖子失败");
return res.json();
}
export async function fetchComments(postId: string): Promise<{ comments: Comment[] }> {
const res = await fetch(`${API_BASE}/api/posts/${postId}/comments`, { cache: "no-store" });
if (!res.ok) throw new Error("获取评论失败");
return res.json();
}
export async function fetchUserProfile(id: string, page = 1): Promise<UserProfile> {
const params = new URLSearchParams({ page: String(page), size: "20" });
const res = await fetch(`${API_BASE}/api/users/${id}?${params}`, { cache: "no-store" });
if (res.status === 404) throw new Error("用户不存在");
if (!res.ok) throw new Error("获取用户资料失败");
return res.json();
}
export async function fetchUserComments(id: string, page = 1): Promise<UserCommentsResponse> {
const params = new URLSearchParams({ page: String(page), size: "20" });
const res = await fetch(`${API_BASE}/api/users/${id}/comments?${params}`, { cache: "no-store" });
if (res.status === 404) throw new Error("用户不存在");
if (!res.ok) throw new Error("获取评论失败");
return res.json();
}
// ===== 客户端 API 调用(走 rewrite,携带 cookie + CSRF) =====
// 获取当前登录用户(依赖 OptionalAuth,未登录返回 { user: null })
export async function apiMe(): Promise<{ user: User | null }> {
const res = await fetch("/api/me", {
credentials: "include",
cache: "no-store",
});
return res.json();
}
export async function apiLogin(username: string, password: string) {
const res = await fetch("/api/login", {
method: "POST",
credentials: "include",
headers: clientHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify({ username, password }),
});
return res.json();
}
export async function apiRegister(username: string, email: string, password: string) {
const res = await fetch("/api/register", {
method: "POST",
credentials: "include",
headers: clientHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify({ username, email, password }),
});
return res.json();
}
export async function apiLogout() {
const res = await fetchWithRefresh("/api/logout", {
method: "POST",
headers: clientHeaders(),
});
return res.json();
}
export async function apiCreatePost(data: {
board_id: number;
title: string;
content: string;
tags?: string;
post_type?: string;
}) {
const res = await fetchWithRefresh("/api/posts", {
method: "POST",
headers: clientHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify(data),
});
return res.json();
}
export async function apiCreateComment(postId: string, content: string) {
const res = await fetchWithRefresh(`/api/posts/${postId}/comments`, {
method: "POST",
headers: clientHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify({ content }),
});
return res.json();
}
export async function apiUpdatePost(
postId: string,
data: { title?: string; content?: string; tags?: string }
) {
const res = await fetchWithRefresh(`/api/posts/${postId}`, {
method: "PUT",
headers: clientHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify(data),
});
return res.json();
}
export async function apiDeletePost(postId: string) {
const res = await fetchWithRefresh(`/api/posts/${postId}`, {
method: "DELETE",
headers: clientHeaders(),
});
return res.json();
}
export async function apiTogglePin(postId: string): Promise<{ pinned: number }> {
const res = await fetchWithRefresh(`/api/posts/${postId}/pin`, {
method: "PUT",
headers: clientHeaders(),
});
return res.json();
}
export async function apiToggleRecommend(postId: string): Promise<{ recommended: boolean }> {
const res = await fetchWithRefresh(`/api/posts/${postId}/recommend`, {
method: "PUT",
headers: clientHeaders(),
});
return res.json();
}
export async function apiChangePassword(oldPassword: string, newPassword: string) {
const res = await fetchWithRefresh("/api/change-password", {
method: "POST",
headers: clientHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify({ old_password: oldPassword, new_password: newPassword }),
});
return res.json();
}
export async function apiToggleLike(postId: string) {
const res = await fetchWithRefresh(`/api/posts/${postId}/like`, {
method: "POST",
headers: clientHeaders(),
});
return res.json();
}
export async function apiDeleteComment(postId: string, commentId: number) {
const res = await fetchWithRefresh(`/api/posts/${postId}/comments/${commentId}`, {
method: "DELETE",
headers: clientHeaders(),
});
return res.json();
}
// ===== 通知 =====
export async function apiFetchNotifications(page = 1): Promise<NotificationsResponse> {
const res = await fetchWithRefresh(`/api/notifications?page=${page}&size=20`, {
headers: clientHeaders(),
});
return res.json();
}
export async function apiUnreadCount(): Promise<{ count: number }> {
const res = await fetchWithRefresh("/api/notifications/unread-count", {
headers: clientHeaders(),
});
return res.json();
}
export async function apiMarkRead(id: number) {
const res = await fetchWithRefresh(`/api/notifications/${id}/read`, {
method: "PUT",
headers: clientHeaders(),
});
return res.json();
}
export async function apiMarkAllRead() {
const res = await fetchWithRefresh("/api/notifications/read-all", {
method: "PUT",
headers: clientHeaders(),
});
return res.json();
}

7
frontend/next-env.d.ts vendored Normal file
View File

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

20
frontend/next.config.ts Normal file
View File

@@ -0,0 +1,20 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
images: {
minimumCacheTTL: 14400, // 4 小时
remotePatterns: [
{ protocol: "http", hostname: "localhost" },
],
},
async rewrites() {
return [
{
source: "/api/:path*",
destination: "http://localhost:3001/api/:path*",
},
];
},
};
export default nextConfig;

3000
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

26
frontend/package.json Normal file
View File

@@ -0,0 +1,26 @@
{
"name": "jiang13-bbs-frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev -p 3000",
"build": "next build",
"start": "next start -p 3000",
"lint": "next lint"
},
"dependencies": {
"next": "^16.0.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"lucide-react": "^0.460.0",
"react-markdown": "^9.0.1"
},
"devDependencies": {
"@types/node": "^22.0.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"tailwindcss": "^4.0.0",
"@tailwindcss/postcss": "^4.0.0",
"typescript": "^5.7.0"
}
}

View File

@@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;

41
frontend/tsconfig.json Normal file
View File

@@ -0,0 +1,41 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": [
"./*"
]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}