feat: align with upstream — pin posts, edit marker, custom CSS, UX fixes

- Pin/unpin posts (PUT /api/posts/:id/pin, admin) with notification to author
- is_pinned/pinned_at in schema; 📌 badge on feed + detail; admin pin button
- Edited marker (已编辑) on feed + detail; edit button + modal for authors
- Custom CSS: upload/delete API + admin tab + global loader (style.css override)
- Fix: duplicate post title on detail page (remove card title, keep header)
- Fix: forum name flicker on load (localStorage cache before fetch)
- Fix: dropdown menu closes on outside click (document listener)
- Fix: document.title + <title> sync on forum rename
This commit is contained in:
lezi-fun committed 2026-08-10 12:35:50 +08:00
1 parent 721e4bfe42
commit 48372aa14f
14 files changed
+371 -10

No files matched your search

+63
View File
@@ -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 });
}
}
+15
View File
@@ -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 });
}
}
+42
View File
@@ -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 });
}
}
+5 -1
View File
@@ -1,5 +1,6 @@
// 全局布局 // 全局布局
import './globals.css'; import './globals.css';
import CustomCssLoader from '@/components/CustomCssLoader';
export const metadata = { export const metadata = {
title: 'Forumlify', title: 'Forumlify',
@@ -9,7 +10,10 @@ export const metadata = {
export default function RootLayout({ children }) { export default function RootLayout({ children }) {
return ( return (
<html lang="zh-CN" suppressHydrationWarning> <html lang="zh-CN" suppressHydrationWarning>
<body>{children}</body> <body>
<CustomCssLoader />
{children}
</body>
</html> </html>
); );
} }
+3
View File
@@ -9,6 +9,7 @@ import AdminLogs from './admin/AdminLogs';
import AdminLinks from './admin/AdminLinks'; import AdminLinks from './admin/AdminLinks';
import AdminForumSettings from './admin/AdminForumSettings'; import AdminForumSettings from './admin/AdminForumSettings';
import AdminCustomPages from './admin/AdminCustomPages'; import AdminCustomPages from './admin/AdminCustomPages';
import AdminCustomCss from './admin/AdminCustomCss';
const TABS = [ const TABS = [
{ key: 'reports', label: '举报', icon: 'shieldAlert' }, { key: 'reports', label: '举报', icon: 'shieldAlert' },
@@ -16,6 +17,7 @@ const TABS = [
{ key: 'logs', label: '日志', icon: 'file' }, { key: 'logs', label: '日志', icon: 'file' },
{ key: 'links', label: '友链', icon: 'link' }, { key: 'links', label: '友链', icon: 'link' },
{ key: 'custom', label: '自定义页面', icon: 'file' }, { key: 'custom', label: '自定义页面', icon: 'file' },
{ key: 'css', label: '自定义CSS', icon: 'file' },
{ key: 'settings', label: '论坛设置', icon: 'settings' }, { key: 'settings', label: '论坛设置', icon: 'settings' },
]; ];
@@ -44,6 +46,7 @@ export default function AdminPage() {
{tab === 'logs' && <AdminLogs />} {tab === 'logs' && <AdminLogs />}
{tab === 'links' && <AdminLinks />} {tab === 'links' && <AdminLinks />}
{tab === 'custom' && <AdminCustomPages />} {tab === 'custom' && <AdminCustomPages />}
{tab === 'css' && <AdminCustomCss />}
{tab === 'settings' && <AdminForumSettings />} {tab === 'settings' && <AdminForumSettings />}
</div> </div>
</div> </div>
+15 -2
View File
@@ -12,7 +12,13 @@ export function useApp() {
export default function AppProvider({ children }) { export default function AppProvider({ children }) {
const [currentUser, setCurrentUser] = useState(null); 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 [theme, setThemeState] = useState('light');
const [view, setView] = useState('feed'); // feed | post | new | admin | settings | messages | user | custom const [view, setView] = useState('feed'); // feed | post | new | admin | settings | messages | user | custom
const [currentPostId, setCurrentPostId] = useState(null); const [currentPostId, setCurrentPostId] = useState(null);
@@ -58,7 +64,10 @@ export default function AppProvider({ children }) {
} }
try { try {
const s = await API.getSettings(); 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 { /* 用默认名 */ } } catch { /* 用默认名 */ }
} }
init(); init();
@@ -182,7 +191,11 @@ export default function AppProvider({ children }) {
const updateForumName = useCallback((name) => { const updateForumName = useCallback((name) => {
setForumName(name); setForumName(name);
localStorage.setItem('forumlify-forum-name', name);
document.title = name; document.title = name;
// 同步更新 <title> 元素(防止 Next.js metadata 覆盖)
const titleEl = document.querySelector('title');
if (titleEl) titleEl.textContent = name;
}, []); }, []);
const value = { const value = {
+17
View File
@@ -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;
}
+6
View File
@@ -78,6 +78,9 @@ export default function Feed({ onOpenModal, onReport }) {
return ( return (
<div key={p.id} className="post-card" style={{ cursor: 'pointer' }} <div key={p.id} className="post-card" style={{ cursor: 'pointer' }}
onClick={() => openPost(p.id)}> onClick={() => openPost(p.id)}>
{p.is_pinned && (
<div style={{ fontSize: 12, color: 'var(--primary)', fontWeight: 600, marginBottom: 4 }}>📌 置顶</div>
)}
<div className="post-header"> <div className="post-header">
<img src={avatar(p.username)} className="post-avatar" alt="" /> <img src={avatar(p.username)} className="post-avatar" alt="" />
<span <span
@@ -88,6 +91,9 @@ export default function Feed({ onOpenModal, onReport }) {
{p.username || '匿名用户'} {p.username || '匿名用户'}
</span> </span>
<span className="post-time">{time}</span> <span className="post-time">{time}</span>
{p.edited_at && (
<span style={{ fontSize: 11, color: 'var(--text-light)', marginLeft: 6 }}>(已编辑)</span>
)}
</div> </div>
<div className="post-title">{p.title || '无标题'}</div> <div className="post-title">{p.title || '无标题'}</div>
<div className="post-content">{(p.content || '').split('\n').map((l, i) => <span key={i}>{l}<br /></span>)}</div> <div className="post-content">{(p.content || '').split('\n').map((l, i) => <span key={i}>{l}<br /></span>)}</div>
+7
View File
@@ -16,6 +16,13 @@ export default function Navbar({ onOpenModal }) {
API.getCustomPages().then(setCustomPages).catch(() => {}); API.getCustomPages().then(setCustomPages).catch(() => {});
}, []); }, []);
// 点击菜单外部关闭下拉(与原版行为一致)
useEffect(() => {
const closeMenu = () => setMenuOpen(false);
document.addEventListener('click', closeMenu);
return () => document.removeEventListener('click', closeMenu);
}, []);
const avatarSrc = currentUser?.avatar_url || const avatarSrc = currentUser?.avatar_url ||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(currentUser?.username || 'U') + 'https://ui-avatars.com/api/?name=' + encodeURIComponent(currentUser?.username || 'U') +
'&background=6366f1&color=fff'; '&background=6366f1&color=fff';
+81 -7
View File
@@ -42,6 +42,7 @@ export default function PostDetail({ postId }) {
const time = post.created_at ? new Date(post.created_at).toLocaleString('zh-CN') : ''; const time = post.created_at ? new Date(post.created_at).toLocaleString('zh-CN') : '';
const canDelete = currentUser && currentUser.id === post.user_id; const canDelete = currentUser && currentUser.id === post.user_id;
const canEdit = currentUser && currentUser.id === post.user_id;
const handleDelete = async () => { const handleDelete = async () => {
if (!confirm('确定要删除这条帖子吗?')) return; 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 ( return (
<div className="page-slide active"> <div className="page-slide active">
<div className="page-header" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}> <div className="page-header" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
@@ -71,14 +103,31 @@ export default function PostDetail({ postId }) {
{post.username || '匿名用户'} {post.username || '匿名用户'}
</span> </span>
<span className="post-time">{time}</span> <span className="post-time">{time}</span>
{canDelete && ( {post.edited_at && (
<button className="btn-sm btn-danger" onClick={handleDelete}> <span style={{ fontSize: 12, color: 'var(--text-light)', marginLeft: 8 }}>
<Icon name="trash" size={14} /> 删除 (已编辑 {new Date(post.edited_at).toLocaleString('zh-CN')})
</button> </span>
)} )}
</div> {post.is_pinned && (
<div className="post-title" style={{ fontSize: 20, fontWeight: 700, margin: '8px 0 12px' }}> <span style={{ fontSize: 12, color: 'var(--primary)', marginLeft: 8 }}>📌 置顶</span>
{post.title || '无标题'} )}
<div style={{ display: 'flex', gap: 4, marginLeft: 'auto' }}>
{currentUser && currentUser.role === 'admin' && (
<button className="btn-sm btn-secondary" style={{ padding: '4px 10px' }} onClick={handleTogglePin}>
{post.is_pinned ? '📌 取消置顶' : '📌 置顶'}
</button>
)}
{canDelete && (
<button className="btn-sm btn-secondary" style={{ padding: '4px 10px' }} onClick={handleEdit}>
✏️ 编辑
</button>
)}
{canDelete && (
<button className="btn-sm btn-danger" style={{ padding: '4px 10px' }} onClick={handleDelete}>
<Icon name="trash" size={14} /> 删除
</button>
)}
</div>
</div> </div>
<div className="post-content" style={{ fontSize: 16, lineHeight: 1.8 }}> <div className="post-content" style={{ fontSize: 16, lineHeight: 1.8 }}>
{(post.content || '').split('\n').map((l, i) => <span key={i}>{l}<br /></span>)} {(post.content || '').split('\n').map((l, i) => <span key={i}>{l}<br /></span>)}
@@ -91,6 +140,31 @@ export default function PostDetail({ postId }) {
</div> </div>
<ReplyList postId={postId} onRefresh={load} /> <ReplyList postId={postId} onRefresh={load} />
</div> </div>
{/* 编辑帖子 modal */}
{editing && (
<div className="modal active" style={{ display: 'flex' }} onClick={(e) => { if (e.target === e.currentTarget) setEditing(false); }}>
<div className="modal-content" style={{ maxWidth: 600, position: 'relative' }}>
<span className="close" style={{ position: 'absolute', top: 12, right: 16, fontSize: 24, cursor: 'pointer', color: 'var(--text-light)' }} onClick={() => setEditing(false)}>&times;</span>
<h2 style={{ marginBottom: 16 }}>✏️ 编辑帖子</h2>
<input
type="text"
placeholder="标题"
value={editTitle}
onChange={(e) => 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)' }}
/>
<textarea
rows={6}
placeholder="说点什么..."
value={editContent}
onChange={(e) => setEditContent(e.target.value)}
style={{ width: '100%', padding: 12, border: '1px solid var(--border)', borderRadius: 6, fontSize: 15, fontFamily: 'inherit', resize: 'vertical', background: 'var(--bg)', color: 'var(--text)' }}
/>
<button className="btn-primary" style={{ padding: '10px 32px', fontSize: 15, marginTop: 8 }} onClick={handleSaveEdit}>保存</button>
</div>
</div>
)}
</div> </div>
); );
} }
+82
View File
@@ -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 (
<>
<h3 style={{ marginBottom: 16 }}>🎨 自定义 CSS</h3>
<p style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 12 }}>
上传一个 <code>style.css</code> 文件覆盖默认样式(支持 CSS 变量、暗色模式等)。
</p>
<div
style={{
border: '2px dashed ' + (dragOver ? 'var(--primary)' : 'var(--border)'),
borderRadius: 8, padding: 32, textAlign: 'center', cursor: 'pointer',
transition: 'all 0.3s', background: dragOver ? 'var(--primary-bg)' : 'var(--bg)',
}}
onClick={() => 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]); }}
>
<span style={{ fontSize: 13, color: 'var(--text-secondary)' }}>
{dragOver ? '松开上传' : '📄 点击或拖拽上传 style.css'}
</span>
</div>
<input
type="file"
ref={fileInputRef}
accept=".css"
style={{ display: 'none' }}
onChange={(e) => { if (e.target.files?.[0]) handleFile(e.target.files[0]); }}
/>
{status && (
<div style={{ fontSize: 13, marginTop: 8, color: status.ok ? '#22c55e' : '#ef4444' }}>{status.msg}</div>
)}
<div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
<button className="btn-primary" style={{ padding: '8px 20px' }} onClick={() => fileInputRef.current?.click()}>💾 保存 CSS</button>
<button className="btn-secondary" style={{ padding: '8px 20px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={handleDelete}>🗑️ 删除自定义 CSS</button>
</div>
</>
);
}
+19
View File
@@ -60,6 +60,9 @@ export const API = {
updatePost(postId, title, content) { updatePost(postId, title, content) {
return apiFetch('/posts/' + postId, { method: 'PUT', body: JSON.stringify({ 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' }); }, deletePost(postId) { return apiFetch('/posts/' + postId, { method: 'DELETE' }); },
// 回复 // 回复
@@ -142,6 +145,22 @@ export const API = {
return apiFetch('/admin/custom-pages/' + id, { method: 'DELETE' }); 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'); }, getNotifications() { return apiFetch('/notifications'); },
markNotificationRead(id) { return apiFetch('/notifications/' + id + '/read', { method: 'PUT' }); }, markNotificationRead(id) { return apiFetch('/notifications/' + id + '/read', { method: 'PUT' }); },
+14
View File
@@ -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 {
// 静默失败
}
}
+2
View File
@@ -21,6 +21,8 @@ CREATE TABLE IF NOT EXISTS posts (
title VARCHAR(200) NOT NULL, title VARCHAR(200) NOT NULL,
content TEXT NOT NULL, content TEXT NOT NULL,
images TEXT[] DEFAULT '{}', images TEXT[] DEFAULT '{}',
is_pinned BOOLEAN DEFAULT false,
pinned_at TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT now(), created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now(), updated_at TIMESTAMPTZ DEFAULT now(),
edited_at TIMESTAMPTZ edited_at TIMESTAMPTZ