diff --git a/app/api/admin/custom-css/route.js b/app/api/admin/custom-css/route.js
new file mode 100644
index 0000000..535fc59
--- /dev/null
+++ b/app/api/admin/custom-css/route.js
@@ -0,0 +1,63 @@
+// POST /api/admin/custom-css, DELETE /api/admin/custom-css — 管理自定义 CSS
+import { writeFile, mkdir, unlink } from 'fs/promises';
+import path from 'path';
+import pool from '@/lib/db';
+import { getUser, requireAdmin } from '@/lib/auth';
+
+export const runtime = 'nodejs';
+
+// 上传 style.css(管理员)
+export async function POST(req) {
+ const user = getUser(req);
+ if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
+ const forbidden = await requireAdmin(user);
+ if (forbidden) return forbidden;
+
+ const form = await req.formData();
+ const file = form.get('file');
+ if (!file || typeof file === 'string') {
+ return Response.json({ error: '请选择文件' }, { status: 400 });
+ }
+ if (file.name !== 'style.css') {
+ return Response.json({ error: '文件名必须是 style.css' }, { status: 400 });
+ }
+ if (file.size > 1024 * 1024) {
+ return Response.json({ error: 'CSS 文件不能超过 1MB' }, { status: 400 });
+ }
+
+ try {
+ const dir = path.join(process.cwd(), 'uploads', 'custom');
+ await mkdir(dir, { recursive: true });
+ const buffer = Buffer.from(await file.arrayBuffer());
+ await writeFile(path.join(dir, 'style.css'), buffer);
+ await pool.query(
+ `INSERT INTO settings (key, value) VALUES ($1, $2)
+ ON CONFLICT (key) DO UPDATE SET value = $2, updated_at = NOW()`,
+ ['custom_css_enabled', 'true']
+ );
+ return Response.json({ success: true });
+ } catch {
+ return Response.json({ error: '上传失败,请稍后重试' }, { status: 500 });
+ }
+}
+
+// 删除自定义 CSS(管理员)
+export async function DELETE(req) {
+ const user = getUser(req);
+ if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
+ const forbidden = await requireAdmin(user);
+ if (forbidden) return forbidden;
+
+ try {
+ const cssPath = path.join(process.cwd(), 'uploads', 'custom', 'style.css');
+ try { await unlink(cssPath); } catch { /* 不存在则忽略 */ }
+ await pool.query(
+ `INSERT INTO settings (key, value) VALUES ($1, $2)
+ ON CONFLICT (key) DO UPDATE SET value = $2, updated_at = NOW()`,
+ ['custom_css_enabled', 'false']
+ );
+ return Response.json({ success: true });
+ } catch {
+ return Response.json({ error: '删除失败,请稍后重试' }, { status: 500 });
+ }
+}
diff --git a/app/api/custom-css/route.js b/app/api/custom-css/route.js
new file mode 100644
index 0000000..693e19e
--- /dev/null
+++ b/app/api/custom-css/route.js
@@ -0,0 +1,15 @@
+// GET /api/custom-css — 公开获取自定义 CSS
+import { readFile } from 'fs/promises';
+import path from 'path';
+
+export const runtime = 'nodejs';
+
+export async function GET() {
+ try {
+ const cssPath = path.join(process.cwd(), 'uploads', 'custom', 'style.css');
+ const css = await readFile(cssPath, 'utf-8');
+ return new Response(css, { headers: { 'Content-Type': 'text/css' } });
+ } catch {
+ return new Response('', { status: 404 });
+ }
+}
diff --git a/app/api/posts/[id]/pin/route.js b/app/api/posts/[id]/pin/route.js
new file mode 100644
index 0000000..d257c29
--- /dev/null
+++ b/app/api/posts/[id]/pin/route.js
@@ -0,0 +1,42 @@
+// PUT /api/posts/[id]/pin — 置顶/取消置顶(管理员)
+import pool from '@/lib/db';
+import { getUser, requireAdmin } from '@/lib/auth';
+import { createNotification } from '@/lib/notify';
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+export async function PUT(req, { params }) {
+ const user = getUser(req);
+ if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
+ const forbidden = await requireAdmin(user);
+ if (forbidden) return forbidden;
+ if (!UUID_RE.test(params.id)) {
+ return Response.json({ error: '帖子不存在' }, { status: 404 });
+ }
+
+ try {
+ const post = await pool.query('SELECT id, user_id FROM posts WHERE id = $1', [params.id]);
+ if (post.rows.length === 0) {
+ return Response.json({ error: '帖子不存在' }, { status: 404 });
+ }
+ const check = await pool.query('SELECT is_pinned FROM posts WHERE id = $1', [params.id]);
+ const isPinned = check.rows[0].is_pinned;
+
+ const r = await pool.query(
+ `UPDATE posts SET is_pinned = $1, pinned_at = $2 WHERE id = $3 RETURNING *`,
+ [!isPinned, !isPinned ? new Date().toISOString() : null, params.id]
+ );
+
+ await createNotification(
+ post.rows[0].user_id,
+ 'system',
+ isPinned ? '你的帖子已被取消置顶' : '你的帖子已被置顶',
+ isPinned ? '管理员取消了你的帖子置顶' : '管理员把你的帖子置顶了',
+ '/?post=' + params.id
+ );
+
+ return Response.json(r.rows[0]);
+ } catch {
+ return Response.json({ error: '操作失败,请稍后重试' }, { status: 500 });
+ }
+}
diff --git a/app/layout.js b/app/layout.js
index b1a4dd4..618a7e2 100644
--- a/app/layout.js
+++ b/app/layout.js
@@ -1,5 +1,6 @@
// 全局布局
import './globals.css';
+import CustomCssLoader from '@/components/CustomCssLoader';
export const metadata = {
title: 'Forumlify',
@@ -9,7 +10,10 @@ export const metadata = {
export default function RootLayout({ children }) {
return (
-
{children}
+
+
+ {children}
+
);
}
diff --git a/components/AdminPage.js b/components/AdminPage.js
index 3040b7f..f24c959 100644
--- a/components/AdminPage.js
+++ b/components/AdminPage.js
@@ -9,6 +9,7 @@ import AdminLogs from './admin/AdminLogs';
import AdminLinks from './admin/AdminLinks';
import AdminForumSettings from './admin/AdminForumSettings';
import AdminCustomPages from './admin/AdminCustomPages';
+import AdminCustomCss from './admin/AdminCustomCss';
const TABS = [
{ key: 'reports', label: '举报', icon: 'shieldAlert' },
@@ -16,6 +17,7 @@ const TABS = [
{ key: 'logs', label: '日志', icon: 'file' },
{ key: 'links', label: '友链', icon: 'link' },
{ key: 'custom', label: '自定义页面', icon: 'file' },
+ { key: 'css', label: '自定义CSS', icon: 'file' },
{ key: 'settings', label: '论坛设置', icon: 'settings' },
];
@@ -44,6 +46,7 @@ export default function AdminPage() {
{tab === 'logs' && }
{tab === 'links' && }
{tab === 'custom' && }
+ {tab === 'css' && }
{tab === 'settings' && }
diff --git a/components/AppProvider.js b/components/AppProvider.js
index 5eb271b..c76a1bf 100644
--- a/components/AppProvider.js
+++ b/components/AppProvider.js
@@ -12,7 +12,13 @@ export function useApp() {
export default function AppProvider({ children }) {
const [currentUser, setCurrentUser] = useState(null);
- const [forumName, setForumName] = useState('Forumlify');
+ // 初始化时先用 localStorage 缓存的论坛名,避免闪烁(默认名 → 正确名)
+ const [forumName, setForumName] = useState(() => {
+ if (typeof window !== 'undefined') {
+ return localStorage.getItem('forumlify-forum-name') || 'Forumlify';
+ }
+ return 'Forumlify';
+ });
const [theme, setThemeState] = useState('light');
const [view, setView] = useState('feed'); // feed | post | new | admin | settings | messages | user | custom
const [currentPostId, setCurrentPostId] = useState(null);
@@ -58,7 +64,10 @@ export default function AppProvider({ children }) {
}
try {
const s = await API.getSettings();
- if (s.forum_name) setForumName(s.forum_name);
+ if (s.forum_name) {
+ setForumName(s.forum_name);
+ localStorage.setItem('forumlify-forum-name', s.forum_name);
+ }
} catch { /* 用默认名 */ }
}
init();
@@ -182,7 +191,11 @@ export default function AppProvider({ children }) {
const updateForumName = useCallback((name) => {
setForumName(name);
+ localStorage.setItem('forumlify-forum-name', name);
document.title = name;
+ // 同步更新 元素(防止 Next.js metadata 覆盖)
+ const titleEl = document.querySelector('title');
+ if (titleEl) titleEl.textContent = name;
}, []);
const value = {
diff --git a/components/CustomCssLoader.js b/components/CustomCssLoader.js
new file mode 100644
index 0000000..3c541d0
--- /dev/null
+++ b/components/CustomCssLoader.js
@@ -0,0 +1,17 @@
+'use client';
+
+// 加载自定义 CSS(管理员上传的 style.css,覆盖默认样式)
+import { useEffect } from 'react';
+
+export default function CustomCssLoader() {
+ useEffect(() => {
+ // 尝试加载 /api/custom-css;404 表示未设置,静默跳过
+ const link = document.createElement('link');
+ link.rel = 'stylesheet';
+ link.href = '/api/custom-css';
+ link.id = 'custom-css-link';
+ document.head.appendChild(link);
+ }, []);
+
+ return null;
+}
diff --git a/components/Feed.js b/components/Feed.js
index a6741d6..88a3375 100644
--- a/components/Feed.js
+++ b/components/Feed.js
@@ -78,6 +78,9 @@ export default function Feed({ onOpenModal, onReport }) {
return (
openPost(p.id)}>
+ {p.is_pinned && (
+
📌 置顶
+ )}
{time}
+ {p.edited_at && (
+ (已编辑)
+ )}
{p.title || '无标题'}
{(p.content || '').split('\n').map((l, i) => {l}
)}
diff --git a/components/Navbar.js b/components/Navbar.js
index a341702..07e61d9 100644
--- a/components/Navbar.js
+++ b/components/Navbar.js
@@ -16,6 +16,13 @@ export default function Navbar({ onOpenModal }) {
API.getCustomPages().then(setCustomPages).catch(() => {});
}, []);
+ // 点击菜单外部关闭下拉(与原版行为一致)
+ useEffect(() => {
+ const closeMenu = () => setMenuOpen(false);
+ document.addEventListener('click', closeMenu);
+ return () => document.removeEventListener('click', closeMenu);
+ }, []);
+
const avatarSrc = currentUser?.avatar_url ||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(currentUser?.username || 'U') +
'&background=6366f1&color=fff';
diff --git a/components/PostDetail.js b/components/PostDetail.js
index c7a6a03..93265c3 100644
--- a/components/PostDetail.js
+++ b/components/PostDetail.js
@@ -42,6 +42,7 @@ export default function PostDetail({ postId }) {
const time = post.created_at ? new Date(post.created_at).toLocaleString('zh-CN') : '';
const canDelete = currentUser && currentUser.id === post.user_id;
+ const canEdit = currentUser && currentUser.id === post.user_id;
const handleDelete = async () => {
if (!confirm('确定要删除这条帖子吗?')) return;
@@ -54,6 +55,37 @@ export default function PostDetail({ postId }) {
}
};
+ const handleTogglePin = async () => {
+ if (!confirm('确定要' + (post.is_pinned ? '取消' : '') + '置顶吗?')) return;
+ try {
+ await API.togglePinPost(postId);
+ load();
+ } catch (err) {
+ alert('操作失败:' + err.message);
+ }
+ };
+
+ const [editing, setEditing] = useState(false);
+ const [editTitle, setEditTitle] = useState('');
+ const [editContent, setEditContent] = useState('');
+
+ const handleEdit = () => {
+ setEditTitle(post.title || '');
+ setEditContent(post.content || '');
+ setEditing(true);
+ };
+
+ const handleSaveEdit = async () => {
+ if (!editContent.trim()) { alert('请填写内容'); return; }
+ try {
+ await API.updatePost(postId, editTitle.trim() || '无标题', editContent.trim());
+ setEditing(false);
+ load();
+ } catch (err) {
+ alert('编辑失败:' + err.message);
+ }
+ };
+
return (
@@ -71,14 +103,31 @@ export default function PostDetail({ postId }) {
{post.username || '匿名用户'}
{time}
- {canDelete && (
-
+ {post.edited_at && (
+
+ (已编辑 {new Date(post.edited_at).toLocaleString('zh-CN')})
+
)}
-
-
- {post.title || '无标题'}
+ {post.is_pinned && (
+
📌 置顶
+ )}
+
+ {currentUser && currentUser.role === 'admin' && (
+
+ )}
+ {canDelete && (
+
+ )}
+ {canDelete && (
+
+ )}
+
{(post.content || '').split('\n').map((l, i) => {l}
)}
@@ -91,6 +140,31 @@ export default function PostDetail({ postId }) {
+
+ {/* 编辑帖子 modal */}
+ {editing && (
+
{ if (e.target === e.currentTarget) setEditing(false); }}>
+
+ setEditing(false)}>×
+
✏️ 编辑帖子
+ setEditTitle(e.target.value)}
+ style={{ width: '100%', padding: '10px 14px', border: '1px solid var(--border)', borderRadius: 6, fontSize: 15, fontWeight: 600, marginBottom: 12, background: 'var(--bg)', color: 'var(--text)' }}
+ />
+
+
+ )}
);
}
diff --git a/components/admin/AdminCustomCss.js b/components/admin/AdminCustomCss.js
new file mode 100644
index 0000000..d92ba55
--- /dev/null
+++ b/components/admin/AdminCustomCss.js
@@ -0,0 +1,82 @@
+'use client';
+
+// 管理后台 - 自定义 CSS(上传 style.css 覆盖默认样式)
+import { useState, useRef } from 'react';
+import { API } from '@/lib/api';
+
+export default function AdminCustomCss() {
+ const [status, setStatus] = useState(null);
+ const [dragOver, setDragOver] = useState(false);
+ const fileInputRef = useRef(null);
+
+ const handleFile = async (file) => {
+ if (!file) return;
+ if (file.name !== 'style.css') {
+ setStatus({ ok: false, msg: '❌ 文件名必须是 style.css' });
+ return;
+ }
+ if (file.size > 1024 * 1024) {
+ setStatus({ ok: false, msg: '❌ CSS 文件不能超过 1MB' });
+ return;
+ }
+ try {
+ await API.uploadCustomCss(file);
+ setStatus({ ok: true, msg: '✅ 自定义 CSS 已生效(刷新页面后应用)' });
+ // 强制刷新样式
+ const link = document.getElementById('custom-css-link');
+ if (link) link.href = '/api/custom-css?t=' + Date.now();
+ } catch (err) {
+ setStatus({ ok: false, msg: '❌ ' + err.message });
+ }
+ };
+
+ const handleDelete = async () => {
+ if (!confirm('确定要删除自定义 CSS 吗?')) return;
+ try {
+ await API.deleteCustomCss();
+ setStatus({ ok: true, msg: '✅ 已删除自定义 CSS' });
+ const link = document.getElementById('custom-css-link');
+ if (link) link.remove();
+ } catch (err) {
+ setStatus({ ok: false, msg: '❌ ' + err.message });
+ }
+ };
+
+ return (
+ <>
+ 🎨 自定义 CSS
+
+ 上传一个 style.css 文件覆盖默认样式(支持 CSS 变量、暗色模式等)。
+
+ fileInputRef.current?.click()}
+ onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
+ onDragLeave={() => setDragOver(false)}
+ onDrop={(e) => { e.preventDefault(); setDragOver(false); if (e.dataTransfer.files?.[0]) handleFile(e.dataTransfer.files[0]); }}
+ >
+
+ {dragOver ? '松开上传' : '📄 点击或拖拽上传 style.css'}
+
+
+ { if (e.target.files?.[0]) handleFile(e.target.files[0]); }}
+ />
+ {status && (
+ {status.msg}
+ )}
+
+
+
+
+ >
+ );
+}
diff --git a/lib/api.js b/lib/api.js
index a5d1df6..f9d5ca3 100644
--- a/lib/api.js
+++ b/lib/api.js
@@ -60,6 +60,9 @@ export const API = {
updatePost(postId, title, content) {
return apiFetch('/posts/' + postId, { method: 'PUT', body: JSON.stringify({ title, content }) });
},
+ togglePinPost(postId) {
+ return apiFetch('/posts/' + postId + '/pin', { method: 'PUT' });
+ },
deletePost(postId) { return apiFetch('/posts/' + postId, { method: 'DELETE' }); },
// 回复
@@ -142,6 +145,22 @@ export const API = {
return apiFetch('/admin/custom-pages/' + id, { method: 'DELETE' });
},
+ // 自定义 CSS
+ uploadCustomCss(file) {
+ const fd = new FormData();
+ fd.append('file', file);
+ const headers = {};
+ if (token) headers['Authorization'] = 'Bearer ' + token;
+ return fetch('/api/admin/custom-css', { method: 'POST', body: fd, headers }).then(async (res) => {
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok || data.error) throw new Error(data.error || '上传失败');
+ return data;
+ });
+ },
+ deleteCustomCss() {
+ return apiFetch('/admin/custom-css', { method: 'DELETE' });
+ },
+
// 通知
getNotifications() { return apiFetch('/notifications'); },
markNotificationRead(id) { return apiFetch('/notifications/' + id + '/read', { method: 'PUT' }); },
diff --git a/lib/notify.js b/lib/notify.js
new file mode 100644
index 0000000..21bc0a6
--- /dev/null
+++ b/lib/notify.js
@@ -0,0 +1,14 @@
+// 通知工具(供各 Route Handler 调用)
+import pool from './db';
+
+// 创建通知(内部函数,静默失败不影响主流程)
+export async function createNotification(userId, type, title, content, link = null) {
+ try {
+ await pool.query(
+ 'INSERT INTO notifications (user_id, type, title, content, link) VALUES ($1, $2, $3, $4, $5)',
+ [userId, type, title, content, link]
+ );
+ } catch {
+ // 静默失败
+ }
+}
diff --git a/schema.sql b/schema.sql
index 640bf61..8486b59 100644
--- a/schema.sql
+++ b/schema.sql
@@ -21,6 +21,8 @@ CREATE TABLE IF NOT EXISTS posts (
title VARCHAR(200) NOT NULL,
content TEXT NOT NULL,
images TEXT[] DEFAULT '{}',
+ is_pinned BOOLEAN DEFAULT false,
+ pinned_at TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now(),
edited_at TIMESTAMPTZ