feat: migrate to Next.js 14 (App Router + Route Handlers)
- Replace Express server with Next.js Route Handlers (16 API routes) - Rewrite index.html SPA as React components (feed, post, admin, modals) - Move style.css to app/globals.css with dark/light themes intact - Add lib/db.js, lib/auth.js (JWT), lib/api.js (client API wrapper) - Server binds 0.0.0.0 by default; host/port configurable via config.js - Uploads served via /api/uploads route (rewrite keeps /uploads/ URLs) - Multi-stage dockerfile using standalone output
This commit is contained in:
1 parent
ef1318da66
commit
281460fb03
52 files changed
+2833
-3372
No files matched your search
@@ -0,0 +1,47 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台:5 个 tab
|
||||
import { useState } from 'react';
|
||||
import AdminReports from './admin/AdminReports';
|
||||
import AdminUsers from './admin/AdminUsers';
|
||||
import AdminLogs from './admin/AdminLogs';
|
||||
import AdminLinks from './admin/AdminLinks';
|
||||
import AdminForumSettings from './admin/AdminForumSettings';
|
||||
|
||||
const TABS = [
|
||||
{ key: 'reports', label: '举报' },
|
||||
{ key: 'users', label: '用户' },
|
||||
{ key: 'logs', label: '日志' },
|
||||
{ key: 'links', label: '友链' },
|
||||
{ key: 'settings', label: '论坛设置' },
|
||||
];
|
||||
|
||||
export default function AdminPage() {
|
||||
const [tab, setTab] = useState('reports');
|
||||
|
||||
return (
|
||||
<div className="page-slide active">
|
||||
<div className="page-header" style={{ maxWidth: 900, margin: '0 auto', width: '100%' }}>
|
||||
<h2>管理后台</h2>
|
||||
</div>
|
||||
<div className="admin-tabs" style={{ maxWidth: 900, margin: '0 auto', width: '100%' }}>
|
||||
{TABS.map((t) => (
|
||||
<button
|
||||
key={t.key}
|
||||
className={'admin-tab' + (tab === t.key ? ' active' : '')}
|
||||
onClick={() => setTab(t.key)}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div id="adminContent" style={{ maxWidth: 900, margin: '0 auto', width: '100%' }}>
|
||||
{tab === 'reports' && <AdminReports />}
|
||||
{tab === 'users' && <AdminUsers />}
|
||||
{tab === 'logs' && <AdminLogs />}
|
||||
{tab === 'links' && <AdminLinks />}
|
||||
{tab === 'settings' && <AdminForumSettings />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
'use client';
|
||||
|
||||
// 全局状态 Provider:用户、主题、论坛名、当前视图(feed/post/new/admin/...)
|
||||
import { createContext, useContext, useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { API, getTheme, setToken, getToken } from '@/lib/api';
|
||||
|
||||
const AppContext = createContext(null);
|
||||
|
||||
export function useApp() {
|
||||
return useContext(AppContext);
|
||||
}
|
||||
|
||||
export default function AppProvider({ children }) {
|
||||
const [currentUser, setCurrentUser] = useState(null);
|
||||
const [forumName, setForumName] = useState('Forumlify');
|
||||
const [theme, setThemeState] = useState('light');
|
||||
const [view, setView] = useState('feed'); // feed | post | new | admin | settings | messages
|
||||
const [currentPostId, setCurrentPostId] = useState(null);
|
||||
const [sort, setSort] = useState('latest');
|
||||
const [refreshKey, setRefreshKey] = useState(0);
|
||||
const loadedRef = useRef(false);
|
||||
|
||||
const refresh = useCallback(() => setRefreshKey((k) => k + 1), []);
|
||||
|
||||
// 主题
|
||||
useEffect(() => {
|
||||
const t = getTheme();
|
||||
setThemeState(t);
|
||||
document.documentElement.setAttribute('data-theme', t);
|
||||
}, []);
|
||||
|
||||
const toggleTheme = useCallback(() => {
|
||||
setThemeState((prev) => {
|
||||
const next = prev === 'light' ? 'dark' : 'light';
|
||||
document.documentElement.setAttribute('data-theme', next);
|
||||
localStorage.setItem('forumlify-theme', next);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
// 初始化:恢复登录、加载论坛名
|
||||
useEffect(() => {
|
||||
if (loadedRef.current) return;
|
||||
loadedRef.current = true;
|
||||
|
||||
async function init() {
|
||||
const token = getToken();
|
||||
if (token) {
|
||||
try {
|
||||
const user = await API.getMe();
|
||||
setCurrentUser(user);
|
||||
API.logEvent('login').catch(() => {});
|
||||
} catch {
|
||||
setToken(null);
|
||||
}
|
||||
}
|
||||
try {
|
||||
const s = await API.getSettings();
|
||||
if (s.forum_name) setForumName(s.forum_name);
|
||||
} catch { /* 用默认名 */ }
|
||||
}
|
||||
init();
|
||||
}, []);
|
||||
|
||||
// 按 URL 参数初始化视图
|
||||
useEffect(() => {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const postParam = params.get('post');
|
||||
const pageParam = params.get('page');
|
||||
if (postParam) {
|
||||
setView('post');
|
||||
setCurrentPostId(postParam);
|
||||
} else if (pageParam && ['messages', 'settings', 'admin', 'new'].includes(pageParam)) {
|
||||
setView(pageParam);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 视图切换:同步 URL (pushState,模拟原 SPA 行为)
|
||||
const navigate = useCallback((page) => {
|
||||
const url = new URL(window.location);
|
||||
if (page === 'feed') {
|
||||
url.searchParams.delete('page');
|
||||
url.searchParams.delete('post');
|
||||
} else {
|
||||
url.searchParams.set('page', page);
|
||||
url.searchParams.delete('post');
|
||||
}
|
||||
window.history.pushState({ page }, '', url);
|
||||
setView(page);
|
||||
setCurrentPostId(null);
|
||||
refresh();
|
||||
}, [refresh]);
|
||||
|
||||
const openPost = useCallback((postId) => {
|
||||
const url = new URL(window.location);
|
||||
url.searchParams.set('post', postId);
|
||||
url.searchParams.delete('page');
|
||||
window.history.pushState({ page: 'post', postId }, '', url);
|
||||
setView('post');
|
||||
setCurrentPostId(postId);
|
||||
}, []);
|
||||
|
||||
// 浏览器前进后退
|
||||
useEffect(() => {
|
||||
const onPop = (e) => {
|
||||
const state = e.state || {};
|
||||
if (state.postId) {
|
||||
setView('post');
|
||||
setCurrentPostId(state.postId);
|
||||
} else {
|
||||
setView(state.page || 'feed');
|
||||
setCurrentPostId(null);
|
||||
}
|
||||
};
|
||||
window.addEventListener('popstate', onPop);
|
||||
return () => window.removeEventListener('popstate', onPop);
|
||||
}, []);
|
||||
|
||||
const login = useCallback(async (email, password) => {
|
||||
const result = await API.login(email, password);
|
||||
if (result.user) {
|
||||
setCurrentUser(result.user);
|
||||
API.logEvent('login').catch(() => {});
|
||||
}
|
||||
return result;
|
||||
}, []);
|
||||
|
||||
const register = useCallback(async (email, password, username) => {
|
||||
const result = await API.register(email, password, username);
|
||||
const loginResult = await API.login(email, password);
|
||||
if (loginResult.user) {
|
||||
setCurrentUser(loginResult.user);
|
||||
API.logEvent('register').catch(() => {});
|
||||
}
|
||||
return result;
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
API.logout();
|
||||
setCurrentUser(null);
|
||||
navigate('feed');
|
||||
}, [navigate]);
|
||||
|
||||
const updateForumName = useCallback((name) => {
|
||||
setForumName(name);
|
||||
document.title = name;
|
||||
}, []);
|
||||
|
||||
const value = {
|
||||
currentUser, setCurrentUser,
|
||||
forumName, updateForumName,
|
||||
theme, toggleTheme,
|
||||
view, navigate,
|
||||
currentPostId, openPost,
|
||||
sort, setSort,
|
||||
refreshKey, refresh,
|
||||
login, register, logout,
|
||||
};
|
||||
|
||||
return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
'use client';
|
||||
|
||||
// 信息流:帖子列表 + 排序 tab + 发布新帖按钮
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
|
||||
function avatar(username) {
|
||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
|
||||
'&background=6366f1&color=fff&size=64';
|
||||
}
|
||||
|
||||
export default function Feed({ onOpenModal, onReport }) {
|
||||
const { currentUser, sort, setSort, openPost, navigate, refreshKey } = useApp();
|
||||
const [posts, setPosts] = useState(null); // null = loading
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setPosts(null);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await API.getPosts(sort);
|
||||
setPosts(data || []);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
setPosts([]);
|
||||
}
|
||||
}, [sort, refreshKey]);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const handleDelete = async (postId) => {
|
||||
if (!confirm('确定要删除这条帖子吗?')) return;
|
||||
try {
|
||||
await API.deletePost(postId);
|
||||
load();
|
||||
} catch (err) {
|
||||
alert('删除失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main id="feed">
|
||||
<div className="feed-header">
|
||||
<div className="feed-header-left">
|
||||
<button className={'tab' + (sort === 'latest' ? ' active' : '')} onClick={() => setSort('latest')}>最新发布</button>
|
||||
<button className={'tab' + (sort === 'hot' ? ' active' : '')} onClick={() => setSort('hot')}>最新回复</button>
|
||||
</div>
|
||||
<button
|
||||
className="btn-primary fab-btn"
|
||||
onClick={() => {
|
||||
if (!currentUser) { alert('请先登录'); return; }
|
||||
navigate('new');
|
||||
}}
|
||||
>
|
||||
发布新帖
|
||||
</button>
|
||||
</div>
|
||||
<div id="postList">
|
||||
{posts === null ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>加载中...</div>
|
||||
) : error ? (
|
||||
<div style={{ textAlign: 'center', color: '#ef4444', padding: '40px 0' }}>加载失败:{error}</div>
|
||||
) : posts.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '60px 0' }}>✨ 还没有帖子,快来发布第一条吧!</div>
|
||||
) : (
|
||||
posts.map((p) => {
|
||||
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
|
||||
return (
|
||||
<div key={p.id} className="post-card" style={{ cursor: 'pointer' }}
|
||||
onClick={() => openPost(p.id)}>
|
||||
<div className="post-header">
|
||||
<img src={avatar(p.username)} className="post-avatar" alt="" />
|
||||
<span className="post-username">{p.username || '匿名用户'}</span>
|
||||
<span className="post-time">{time}</span>
|
||||
</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>
|
||||
{p.images && p.images.length > 0 && (
|
||||
<div className="post-images">
|
||||
{p.images.map((img, i) => <img key={i} src={img} className="post-image" alt="" />)}
|
||||
</div>
|
||||
)}
|
||||
<div className="post-actions">
|
||||
<span>💬 {p.reply_count || 0}</span>
|
||||
<button className="action-report" onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (!currentUser) { alert('请先登录'); return; }
|
||||
onReport(p.id);
|
||||
}}>举报</button>
|
||||
{currentUser && currentUser.id === p.user_id && (
|
||||
<button className="action-delete" onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleDelete(p.id);
|
||||
}}>删除</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
'use client';
|
||||
|
||||
// 登录/注册/举报 模态框
|
||||
import { useState, useEffect } from 'react';
|
||||
import { API, generateCaptcha } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
|
||||
export default function Modals({ modal, onClose, reportPostId }) {
|
||||
const { login, register, currentUser, refresh } = useApp();
|
||||
|
||||
// 登录表单
|
||||
const [loginEmail, setLoginEmail] = useState('');
|
||||
const [loginPassword, setLoginPassword] = useState('');
|
||||
|
||||
// 注册表单
|
||||
const [regUsername, setRegUsername] = useState('');
|
||||
const [regEmail, setRegEmail] = useState('');
|
||||
const [regPassword, setRegPassword] = useState('');
|
||||
const [regCaptcha, setRegCaptcha] = useState(null);
|
||||
const [regCaptchaInput, setRegCaptchaInput] = useState('');
|
||||
|
||||
// 举报表单
|
||||
const [reportReason, setReportReason] = useState('spam');
|
||||
|
||||
useEffect(() => {
|
||||
if (modal === 'register') setRegCaptcha(generateCaptcha());
|
||||
}, [modal]);
|
||||
|
||||
if (!modal) return null;
|
||||
|
||||
const close = (e) => {
|
||||
if (e && e.target !== e.currentTarget) return;
|
||||
onClose();
|
||||
};
|
||||
|
||||
const handleLogin = async () => {
|
||||
if (!loginEmail.trim() || !loginPassword) { alert('请填写完整信息'); return; }
|
||||
try {
|
||||
const result = await login(loginEmail.trim(), loginPassword);
|
||||
if (result.user) {
|
||||
onClose();
|
||||
setLoginEmail('');
|
||||
setLoginPassword('');
|
||||
refresh();
|
||||
}
|
||||
} catch (err) {
|
||||
alert('登录失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRegister = async () => {
|
||||
if (!regUsername.trim() || !regEmail.trim() || !regPassword) { alert('请填写完整信息'); return; }
|
||||
if (regPassword.length < 6) { alert('密码至少6位'); return; }
|
||||
if (!regCaptcha || parseInt(regCaptchaInput) !== regCaptcha.answer) {
|
||||
alert('验证码错误,请重新计算');
|
||||
setRegCaptcha(generateCaptcha());
|
||||
setRegCaptchaInput('');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await register(regEmail.trim(), regPassword, regUsername.trim());
|
||||
onClose();
|
||||
setRegUsername('');
|
||||
setRegEmail('');
|
||||
setRegPassword('');
|
||||
setRegCaptchaInput('');
|
||||
alert('注册成功!');
|
||||
refresh();
|
||||
} catch (err) {
|
||||
alert('注册失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const handleReport = async () => {
|
||||
if (!reportPostId) return;
|
||||
try {
|
||||
await API.createReport(reportPostId, reportReason);
|
||||
onClose();
|
||||
alert('举报已提交,管理员将尽快处理');
|
||||
} catch (err) {
|
||||
alert('举报失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{modal === 'login' && (
|
||||
<div className="modal active" onClick={close}>
|
||||
<div className="modal-content">
|
||||
<span className="close" onClick={onClose}>✕</span>
|
||||
<h2 style={{ marginBottom: 16 }}>登录</h2>
|
||||
<input type="email" placeholder="邮箱" value={loginEmail} onChange={(e) => setLoginEmail(e.target.value)} />
|
||||
<input type="password" placeholder="密码" value={loginPassword} onChange={(e) => setLoginPassword(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter') handleLogin(); }} />
|
||||
<button className="btn-primary" style={{ width: '100%' }} onClick={handleLogin}>登录</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{modal === 'register' && (
|
||||
<div className="modal active" onClick={close}>
|
||||
<div className="modal-content">
|
||||
<span className="close" onClick={onClose}>✕</span>
|
||||
<h2 style={{ marginBottom: 16 }}>注册</h2>
|
||||
<input type="text" placeholder="用户名" value={regUsername} onChange={(e) => setRegUsername(e.target.value)} />
|
||||
<input type="email" placeholder="邮箱" value={regEmail} onChange={(e) => setRegEmail(e.target.value)} />
|
||||
<input type="password" placeholder="密码(至少6位)" value={regPassword} onChange={(e) => setRegPassword(e.target.value)} />
|
||||
<div className="captcha-row">
|
||||
<span onClick={() => setRegCaptcha(generateCaptcha())} style={{ cursor: 'pointer' }}>
|
||||
{regCaptcha ? regCaptcha.question : ''}
|
||||
</span>
|
||||
<input type="text" placeholder="答案" style={{ width: 80 }} value={regCaptchaInput} onChange={(e) => setRegCaptchaInput(e.target.value)} />
|
||||
</div>
|
||||
<button className="btn-primary" style={{ width: '100%' }} onClick={handleRegister}>注册</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{modal === 'report' && currentUser && (
|
||||
<div className="modal active" onClick={close}>
|
||||
<div className="modal-content">
|
||||
<span className="close" onClick={onClose}>✕</span>
|
||||
<h2 style={{ marginBottom: 16 }}>举报帖子</h2>
|
||||
<p style={{ fontSize: 14, color: '#64748b', marginBottom: 12 }}>请选择举报原因:</p>
|
||||
<select
|
||||
style={{ width: '100%', padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 4, marginBottom: 16 }}
|
||||
value={reportReason}
|
||||
onChange={(e) => setReportReason(e.target.value)}
|
||||
>
|
||||
<option value="spam">垃圾广告</option>
|
||||
<option value="abuse">人身攻击</option>
|
||||
<option value="illegal">违法内容</option>
|
||||
<option value="nsfw">不适当内容</option>
|
||||
<option value="other">其他</option>
|
||||
</select>
|
||||
<button className="btn-primary" style={{ width: '100%' }} onClick={handleReport}>提交举报</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
'use client';
|
||||
|
||||
// 导航栏:论坛名、登录/注册按钮、用户下拉菜单、主题切换
|
||||
import { useState } from 'react';
|
||||
import { useApp } from './AppProvider';
|
||||
|
||||
export default function Navbar({ onOpenModal }) {
|
||||
const { currentUser, forumName, theme, toggleTheme, navigate, logout, setCurrentUser } = useApp();
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
|
||||
const avatarSrc = currentUser?.avatar_url ||
|
||||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(currentUser?.username || 'U') +
|
||||
'&background=6366f1&color=fff';
|
||||
|
||||
const goPage = (page) => {
|
||||
if (page === 'admin' && currentUser?.role !== 'admin') {
|
||||
alert('无权限访问');
|
||||
return;
|
||||
}
|
||||
setMenuOpen(false);
|
||||
navigate(page);
|
||||
};
|
||||
|
||||
return (
|
||||
<nav id="navbar">
|
||||
<div className="nav-left">
|
||||
<span className="forum-name" onClick={() => navigate('feed')} style={{ cursor: 'pointer' }}>
|
||||
{forumName}
|
||||
</span>
|
||||
</div>
|
||||
<div className="nav-right">
|
||||
<div id="userMenu">
|
||||
{!currentUser ? (
|
||||
<div id="authButtons">
|
||||
<button className="btn-ghost" onClick={() => onOpenModal('login')}>登录</button>
|
||||
<button className="btn-primary" onClick={() => onOpenModal('register')}>注册</button>
|
||||
</div>
|
||||
) : (
|
||||
<div id="userDropdown" style={{ display: 'block' }}>
|
||||
<img
|
||||
className="avatar"
|
||||
src={avatarSrc}
|
||||
alt="avatar"
|
||||
onClick={(e) => { e.stopPropagation(); setMenuOpen(!menuOpen); }}
|
||||
/>
|
||||
{menuOpen && (
|
||||
<div className="dropdown-menu show" onClick={(e) => e.stopPropagation()}>
|
||||
<a href="#" onClick={(e) => { e.preventDefault(); goPage('messages'); }}>消息</a>
|
||||
<a href="#" onClick={(e) => { e.preventDefault(); goPage('settings'); }}>设置</a>
|
||||
{currentUser.role === 'admin' && (
|
||||
<a href="#" onClick={(e) => { e.preventDefault(); goPage('admin'); }}>管理后台</a>
|
||||
)}
|
||||
<hr />
|
||||
<a
|
||||
href="#"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
toggleTheme();
|
||||
setMenuOpen(false);
|
||||
}}
|
||||
>
|
||||
{theme === 'dark' ? '☀️ 亮色模式' : '🌙 暗色模式'}
|
||||
</a>
|
||||
<hr />
|
||||
<a
|
||||
href="#"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
if (confirm('确定要退出吗?')) {
|
||||
setMenuOpen(false);
|
||||
logout();
|
||||
}
|
||||
}}
|
||||
>
|
||||
退出
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
'use client';
|
||||
|
||||
// 发布新帖页
|
||||
import { useState, useEffect } from 'react';
|
||||
import { API, generateCaptcha, uploadImage } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
|
||||
export default function NewPost() {
|
||||
const { currentUser, navigate, refresh } = useApp();
|
||||
const [title, setTitle] = useState('');
|
||||
const [content, setContent] = useState('');
|
||||
const [images, setImages] = useState([]); // 上传后的 URL 列表
|
||||
const [previews, setPreviews] = useState([]); // 本地预览 dataURL
|
||||
const [captcha, setCaptcha] = useState(null);
|
||||
const [captchaInput, setCaptchaInput] = useState('');
|
||||
const [uploading, setUploading] = useState(false);
|
||||
|
||||
useEffect(() => { setCaptcha(generateCaptcha()); }, []);
|
||||
|
||||
const handleFiles = async (files) => {
|
||||
setUploading(true);
|
||||
try {
|
||||
const newPreviews = [];
|
||||
for (const file of files) {
|
||||
const dataUrl = await new Promise((resolve) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => resolve(e.target.result);
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
newPreviews.push(dataUrl);
|
||||
// 直接上传拿 URL
|
||||
const url = await uploadImage(file);
|
||||
setImages((prev) => [...prev, url]);
|
||||
}
|
||||
setPreviews((prev) => [...prev, ...newPreviews]);
|
||||
} catch (err) {
|
||||
alert('上传失败:' + err.message);
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!currentUser || !currentUser.id) {
|
||||
alert('请先登录');
|
||||
navigate('feed');
|
||||
return;
|
||||
}
|
||||
if (!content.trim()) { alert('请填写内容'); return; }
|
||||
if (!captcha || parseInt(captchaInput) !== captcha.answer) {
|
||||
alert('验证码错误,请重新计算');
|
||||
setCaptcha(generateCaptcha());
|
||||
setCaptchaInput('');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await API.createPost(title.trim() || '无标题', content.trim(), images);
|
||||
API.logEvent('create_post').catch(() => {});
|
||||
alert('发布成功!');
|
||||
navigate('feed');
|
||||
refresh();
|
||||
} catch (err) {
|
||||
alert('发布失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="page-slide active">
|
||||
<div className="page-header" style={{ maxWidth: 600, margin: '0 auto', width: '100%' }}>
|
||||
<h2>发布新帖</h2>
|
||||
</div>
|
||||
<div style={{ maxWidth: 600, margin: '0 auto', width: '100%' }}>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="标题"
|
||||
style={{ width: '100%', padding: '10px 14px', border: '1.5px solid #e2e8f0', borderRadius: 6, fontSize: 15, fontWeight: 600, marginBottom: 12, fontFamily: 'inherit' }}
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<textarea
|
||||
rows={6}
|
||||
placeholder="说点什么..."
|
||||
style={{ width: '100%', padding: 12, border: '1.5px solid #e2e8f0', borderRadius: 6, fontSize: 15, fontFamily: 'inherit', resize: 'vertical' }}
|
||||
value={content}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
/>
|
||||
<div id="imagePreview" style={{ display: 'flex', flexWrap: 'wrap', gap: 8, margin: '8px 0' }}>
|
||||
{previews.map((src, i) => (
|
||||
<img key={i} src={src} alt="" style={{ width: 80, height: 80, objectFit: 'cover', borderRadius: 4, border: '1px solid #e2e8f0' }} />
|
||||
))}
|
||||
</div>
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
disabled={uploading}
|
||||
onChange={(e) => { if (e.target.files) handleFiles(Array.from(e.target.files)); }}
|
||||
style={{ margin: '8px 0 12px' }}
|
||||
/>
|
||||
<div className="captcha-row" style={{ margin: '12px 0' }}>
|
||||
<span onClick={() => setCaptcha(generateCaptcha())} style={{ cursor: 'pointer' }}>
|
||||
{captcha ? captcha.question : ''}
|
||||
</span>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="答案"
|
||||
style={{ width: 80, padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 4 }}
|
||||
value={captchaInput}
|
||||
onChange={(e) => setCaptchaInput(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<button className="btn-primary" style={{ padding: '10px 32px', fontSize: 15 }} onClick={handleSubmit}>
|
||||
{uploading ? '上传中...' : '发布帖子'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
'use client';
|
||||
|
||||
// 帖子详情页
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import ReplyList from './ReplyList';
|
||||
|
||||
function avatar(username) {
|
||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
|
||||
'&background=6366f1&color=fff&size=64';
|
||||
}
|
||||
|
||||
export default function PostDetail({ postId }) {
|
||||
const { currentUser, navigate, refreshKey } = useApp();
|
||||
const [post, setPost] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setError(null);
|
||||
try {
|
||||
const data = await API.getPost(postId);
|
||||
setPost(data);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
}
|
||||
}, [postId, refreshKey]);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="page-slide active" style={{ padding: '40px 0', textAlign: 'center', color: '#ef4444' }}>
|
||||
加载失败:{error}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!post) {
|
||||
return <div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>加载中...</div>;
|
||||
}
|
||||
|
||||
const time = post.created_at ? new Date(post.created_at).toLocaleString('zh-CN') : '';
|
||||
const canDelete = currentUser && currentUser.id === post.user_id;
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!confirm('确定要删除这条帖子吗?')) return;
|
||||
try {
|
||||
await API.deletePost(postId);
|
||||
alert('删除成功');
|
||||
navigate('feed');
|
||||
} catch (err) {
|
||||
alert('删除失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="page-slide active">
|
||||
<div className="page-header" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
|
||||
<h2>{post.title || '帖子详情'}</h2>
|
||||
</div>
|
||||
<div id="postDetailContent" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
|
||||
<div className="post-detail-card">
|
||||
<div className="post-header">
|
||||
<img src={avatar(post.username)} className="post-avatar" alt="" />
|
||||
<span className="post-username">{post.username || '匿名用户'}</span>
|
||||
<span className="post-time">{time}</span>
|
||||
{canDelete && (
|
||||
<button className="btn-sm btn-danger" onClick={handleDelete}>删除</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="post-title" style={{ fontSize: 20, fontWeight: 700, margin: '8px 0 12px' }}>
|
||||
{post.title || '无标题'}
|
||||
</div>
|
||||
<div className="post-content" style={{ fontSize: 16, lineHeight: 1.8 }}>
|
||||
{(post.content || '').split('\n').map((l, i) => <span key={i}>{l}<br /></span>)}
|
||||
</div>
|
||||
{post.images && post.images.length > 0 && (
|
||||
<div className="post-images">
|
||||
{post.images.map((img, i) => <img key={i} src={img} className="post-image" alt="" />)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<ReplyList postId={postId} onRefresh={load} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
'use client';
|
||||
|
||||
// 回复列表 + 发表回复表单
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { API, generateCaptcha } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
|
||||
function avatar(username) {
|
||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
|
||||
'&background=6366f1&color=fff&size=64';
|
||||
}
|
||||
|
||||
export default function ReplyList({ postId, onRefresh }) {
|
||||
const { currentUser } = useApp();
|
||||
const [replies, setReplies] = useState([]);
|
||||
const [content, setContent] = useState('');
|
||||
const [captcha, setCaptcha] = useState(null);
|
||||
const [captchaInput, setCaptchaInput] = useState('');
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const data = await API.getReplies(postId);
|
||||
setReplies(data || []);
|
||||
} catch { setReplies([]); }
|
||||
}, [postId]);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
useEffect(() => { setCaptcha(generateCaptcha()); }, [postId]);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!currentUser) { alert('请先登录'); return; }
|
||||
if (!content.trim()) { alert('请填写回复内容'); return; }
|
||||
if (!captcha || parseInt(captchaInput) !== captcha.answer) {
|
||||
alert('验证码错误,请重新计算');
|
||||
setCaptcha(generateCaptcha());
|
||||
setCaptchaInput('');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await API.createReply(postId, content.trim());
|
||||
API.logEvent('create_reply').catch(() => {});
|
||||
setContent('');
|
||||
setCaptchaInput('');
|
||||
setCaptcha(generateCaptcha());
|
||||
load();
|
||||
onRefresh();
|
||||
} catch (err) {
|
||||
alert('回复失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (replyId) => {
|
||||
if (!confirm('确定要删除这条回复吗?')) return;
|
||||
try {
|
||||
await API.deleteReply(replyId);
|
||||
load();
|
||||
} catch (err) {
|
||||
alert('删除失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div style={{ marginTop: 20, fontSize: 14, color: '#64748b' }}>💬 {replies.length} 条回复</div>
|
||||
<div style={{ marginTop: 12 }}>
|
||||
{replies.length === 0 ? (
|
||||
<div style={{ color: '#94a3b8', padding: '20px 0', textAlign: 'center' }}>还没有回复,快来抢沙发吧 🛋️</div>
|
||||
) : (
|
||||
replies.map((r) => {
|
||||
const rTime = r.created_at ? new Date(r.created_at).toLocaleString('zh-CN') : '';
|
||||
return (
|
||||
<div key={r.id} className="reply-item">
|
||||
<div className="reply-header">
|
||||
<img src={avatar(r.username)} className="reply-avatar" alt="" />
|
||||
<span className="reply-username">{r.username || '匿名用户'}</span>
|
||||
<span className="reply-time">{rTime}</span>
|
||||
{currentUser && currentUser.id === r.user_id && (
|
||||
<button className="btn-sm btn-danger reply-delete-btn" onClick={() => handleDelete(r.id)}>删除</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="reply-content">
|
||||
{(r.content || '').split('\n').map((l, i) => <span key={i}>{l}<br /></span>)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div id="replyArea" style={{ marginTop: 24, borderTop: '1px solid #e2e8f0', paddingTop: 20 }}>
|
||||
<h3 style={{ fontSize: 16, marginBottom: 12 }}>发表回复</h3>
|
||||
<textarea
|
||||
rows={3}
|
||||
placeholder="写下你的回复..."
|
||||
style={{ width: '100%', padding: '10px 12px', border: '1px solid #e2e8f0', borderRadius: 4, fontSize: 14, fontFamily: 'inherit', resize: 'vertical' }}
|
||||
value={content}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) handleSubmit(); }}
|
||||
/>
|
||||
<div className="captcha-row" style={{ margin: '10px 0' }}>
|
||||
<span onClick={() => setCaptcha(generateCaptcha())} style={{ cursor: 'pointer' }}>
|
||||
{captcha ? captcha.question : ''}
|
||||
</span>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="答案"
|
||||
style={{ width: 80, padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 4 }}
|
||||
value={captchaInput}
|
||||
onChange={(e) => setCaptchaInput(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<button className="btn-primary" style={{ padding: '8px 24px' }} onClick={handleSubmit}>提交回复</button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
'use client';
|
||||
|
||||
// 个人设置页
|
||||
import { useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
|
||||
export default function SettingsPage() {
|
||||
const { currentUser, setCurrentUser } = useApp();
|
||||
const [username, setUsername] = useState(currentUser?.username || '');
|
||||
const [bio, setBio] = useState(currentUser?.bio || '');
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!currentUser) { alert('请先登录'); return; }
|
||||
if (!username.trim()) { alert('用户名不能为空'); return; }
|
||||
try {
|
||||
const data = await API.updateProfile(currentUser.id, username.trim(), bio.trim());
|
||||
if (data.error) throw new Error(data.error);
|
||||
setCurrentUser({ ...currentUser, username: username.trim(), bio: bio.trim() });
|
||||
alert('保存成功!');
|
||||
} catch (err) {
|
||||
alert('保存失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="page-slide active">
|
||||
<div className="page-header" style={{ maxWidth: 400, margin: '0 auto', width: '100%' }}>
|
||||
<h2>设置</h2>
|
||||
</div>
|
||||
<div style={{ maxWidth: 400, margin: '0 auto', width: '100%' }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 14 }}>用户名</label>
|
||||
<input
|
||||
type="text"
|
||||
style={{ width: '100%', padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 4, margin: '6px 0 12px' }}
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
/>
|
||||
<label style={{ fontWeight: 600, fontSize: 14 }}>个人简介</label>
|
||||
<textarea
|
||||
rows={3}
|
||||
style={{ width: '100%', padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 4, margin: '6px 0 12px' }}
|
||||
value={bio}
|
||||
onChange={(e) => setBio(e.target.value)}
|
||||
/>
|
||||
<button className="btn-primary" onClick={handleSave}>保存设置</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
'use client';
|
||||
|
||||
// 侧边栏:社区统计 + 友情链接
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
|
||||
export default function Sidebar() {
|
||||
const [stats, setStats] = useState({ posts: 0, users: 0, topics: 0, online: 0 });
|
||||
const [links, setLinks] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
API.getStats().then(setStats).catch(() => {});
|
||||
API.getLinks().then(setLinks).catch(() => {});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<aside id="sidebar">
|
||||
<div className="stats-box">
|
||||
<h4>社区统计</h4>
|
||||
<div className="stat-item"><span>主题</span><span>{stats.topics || 0}</span></div>
|
||||
<div className="stat-item"><span>帖子</span><span>{stats.posts || 0}</span></div>
|
||||
<div className="stat-item"><span>用户</span><span>{stats.users || 0}</span></div>
|
||||
<div className="stat-item"><span>在线</span><span>{stats.online || 0}</span></div>
|
||||
</div>
|
||||
<div className="links-box">
|
||||
<h4>友情链接</h4>
|
||||
<ul id="friendlyLinks">
|
||||
{links.length === 0 ? (
|
||||
<li style={{ color: '#94a3b8', fontSize: 13 }}>暂无链接</li>
|
||||
) : (
|
||||
links.map((l) => (
|
||||
<li key={l.id}><a href={l.url} target="_blank" rel="noreferrer">{l.title}</a></li>
|
||||
))
|
||||
)}
|
||||
</ul>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 论坛设置
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from '../AppProvider';
|
||||
|
||||
export default function AdminForumSettings() {
|
||||
const { updateForumName } = useApp();
|
||||
const [name, setName] = useState('Forumlify');
|
||||
const [result, setResult] = useState(null); // {ok, msg}
|
||||
|
||||
useEffect(() => {
|
||||
API.getSettings()
|
||||
.then((data) => { if (data.forum_name) setName(data.forum_name); })
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!name.trim()) { alert('请输入论坛名称'); return; }
|
||||
try {
|
||||
await API.updateSettings(name.trim());
|
||||
updateForumName(name.trim());
|
||||
setResult({ ok: true, msg: '✅ 保存成功!' });
|
||||
} catch {
|
||||
setResult({ ok: false, msg: '❌ 保存失败' });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<h3 style={{ marginBottom: 16 }}>⚙️ 论坛设置</h3>
|
||||
<div style={{ maxWidth: 400 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 6 }}>论坛名称</label>
|
||||
<input
|
||||
type="text"
|
||||
style={{ width: '100%', padding: '10px 14px', border: '1.5px solid #e2e8f0', borderRadius: 6, fontSize: 15, marginBottom: 12, fontFamily: 'inherit' }}
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
<button className="btn-primary" style={{ padding: '10px 24px' }} onClick={handleSave}>保存</button>
|
||||
{result && (
|
||||
<span style={{ marginLeft: 12, fontSize: 14, color: result.ok ? '#22c55e' : '#ef4444' }}>{result.msg}</span>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 友情链接管理
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
|
||||
export default function AdminLinks() {
|
||||
const [links, setLinks] = useState([]);
|
||||
const [title, setTitle] = useState('');
|
||||
const [url, setUrl] = useState('');
|
||||
|
||||
const load = () => { API.getLinks().then(setLinks).catch(() => {}); };
|
||||
useEffect(load, []);
|
||||
|
||||
const handleAdd = async () => {
|
||||
if (!title.trim() || !url.trim()) { alert('请填写完整信息'); return; }
|
||||
try {
|
||||
await API.addLink(title.trim(), url.trim());
|
||||
setTitle('');
|
||||
setUrl('');
|
||||
load();
|
||||
} catch (err) {
|
||||
alert('添加失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id) => {
|
||||
if (!confirm('确定删除该链接吗?')) return;
|
||||
try {
|
||||
await API.deleteLink(id);
|
||||
load();
|
||||
} catch (err) {
|
||||
alert('删除失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div style={{ marginBottom: 16, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
|
||||
<input
|
||||
type="text" placeholder="链接名称"
|
||||
style={{ flex: 1, minWidth: 120, padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 4 }}
|
||||
value={title} onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<input
|
||||
type="url" placeholder="链接地址"
|
||||
style={{ flex: 2, minWidth: 160, padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 4 }}
|
||||
value={url} onChange={(e) => setUrl(e.target.value)}
|
||||
/>
|
||||
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={handleAdd}>添加</button>
|
||||
</div>
|
||||
<div id="linkList">
|
||||
{links.length === 0 ? (
|
||||
<div style={{ color: '#94a3b8', fontSize: 13 }}>暂无友情链接</div>
|
||||
) : (
|
||||
links.map((l) => (
|
||||
<div key={l.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 0', borderBottom: '1px solid #f1f5f9' }}>
|
||||
<span><a href={l.url} target="_blank" rel="noreferrer" style={{ color: '#6366f1', textDecoration: 'none' }}>{l.title}</a></span>
|
||||
<button className="btn-sm btn-danger" onClick={() => handleDelete(l.id)}>删除</button>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 事件日志
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
|
||||
export default function AdminLogs() {
|
||||
const [logs, setLogs] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const load = () => {
|
||||
API.getEventLogs()
|
||||
.then((data) => { setLogs(data || []); setError(null); })
|
||||
.catch((e) => { setError(e.message); setLogs([]); });
|
||||
};
|
||||
|
||||
useEffect(load, []);
|
||||
|
||||
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>加载失败:{error}</div>;
|
||||
if (!logs) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}>加载中...</div>;
|
||||
if (logs.length === 0) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 40 }}>暂无日志</div>;
|
||||
|
||||
return (
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
|
||||
<thead>
|
||||
<tr style={{ textAlign: 'left', borderBottom: '1px solid #e2e8f0' }}>
|
||||
<th>时间</th><th>用户</th><th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{logs.map((l) => (
|
||||
<tr key={l.id} style={{ borderBottom: '1px solid #f1f5f9' }}>
|
||||
<td style={{ padding: '6px 0' }}>{new Date(l.created_at).toLocaleString('zh-CN')}</td>
|
||||
<td style={{ padding: '6px 0' }}>{l.username || '系统'}</td>
|
||||
<td style={{ padding: '6px 0' }}>{l.action}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 举报处理
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
|
||||
const STATUS = { pending: '⏳ 待处理', approved: '✅ 已删除', rejected: '❌ 已驳回' };
|
||||
|
||||
export default function AdminReports() {
|
||||
const [reports, setReports] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const load = () => {
|
||||
API.getReports()
|
||||
.then((data) => { setReports(data || []); setError(null); })
|
||||
.catch((e) => { setError(e.message); setReports([]); });
|
||||
};
|
||||
|
||||
useEffect(load, []);
|
||||
|
||||
const handleAction = async (r, action) => {
|
||||
const status = action === 'approve' ? 'approved' : 'rejected';
|
||||
const note = action === 'approve' ? '已删除违规帖子' : '举报不成立';
|
||||
if (action === 'approve' && !confirm('确定要删除该帖子并标记举报为已处理吗?')) return;
|
||||
try {
|
||||
await API.updateReport(r.id, status, note);
|
||||
if (action === 'approve' && r.post_id) {
|
||||
API.deletePost(r.post_id).catch(() => {});
|
||||
}
|
||||
load();
|
||||
} catch (err) {
|
||||
alert('操作失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>加载失败:{error}</div>;
|
||||
if (!reports) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}>加载中...</div>;
|
||||
if (reports.length === 0) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 40 }}>✅ 暂无举报</div>;
|
||||
|
||||
return reports.map((r) => (
|
||||
<div key={r.id} className="report-item">
|
||||
<div><strong>{r.reporter_name || '匿名'}</strong> 举报了帖子</div>
|
||||
<div style={{ fontSize: 13, color: '#64748b', margin: '4px 0' }}>原因:{r.reason}</div>
|
||||
<div style={{ fontSize: 13, color: '#64748b', margin: '4px 0' }}>
|
||||
帖子:{r.post_title || '无标题'} — {(r.post_content || '').substring(0, 30)}
|
||||
{(r.post_content || '').length > 30 ? '...' : ''}
|
||||
</div>
|
||||
<div style={{ fontSize: 13, fontWeight: 600 }}>状态:{STATUS[r.status] || r.status}</div>
|
||||
{r.handler_name && (
|
||||
<div style={{ fontSize: 12, color: '#94a3b8' }}>
|
||||
处理人:{r.handler_name}{r.handler_note ? ' (' + r.handler_note + ')' : ''}
|
||||
</div>
|
||||
)}
|
||||
{r.status === 'pending' && (
|
||||
<div className="report-actions">
|
||||
<button className="btn-sm btn-danger" onClick={() => handleAction(r, 'approve')}>删除帖子</button>
|
||||
<button className="btn-sm btn-secondary" onClick={() => handleAction(r, 'reject')}>驳回举报</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
));
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 用户管理
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from '../AppProvider';
|
||||
|
||||
export default function AdminUsers() {
|
||||
const { currentUser } = useApp();
|
||||
const [users, setUsers] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const load = () => {
|
||||
API.getUsers()
|
||||
.then((data) => { setUsers(data || []); setError(null); })
|
||||
.catch((e) => { setError(e.message); setUsers([]); });
|
||||
};
|
||||
|
||||
useEffect(load, []);
|
||||
|
||||
const handleRole = async (u, role) => {
|
||||
const roleName = role === 'admin' ? '管理员' : '普通用户';
|
||||
if (!confirm(`确定要将该用户设为「${roleName}」吗?`)) return;
|
||||
try {
|
||||
await API.updateUserRole(u.id, role);
|
||||
load();
|
||||
} catch (err) {
|
||||
alert('操作失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>加载失败:{error}</div>;
|
||||
if (!users) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}>加载中...</div>;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div style={{ marginBottom: 12, fontSize: 13, color: '#94a3b8' }}>共 <strong>{users.length}</strong> 位用户</div>
|
||||
<div style={{ overflowX: 'auto' }}>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}>
|
||||
<thead>
|
||||
<tr style={{ textAlign: 'left', borderBottom: '2px solid #e2e8f0' }}>
|
||||
<th style={{ padding: '10px 12px' }}>用户</th>
|
||||
<th style={{ padding: '10px 12px' }}>角色</th>
|
||||
<th style={{ padding: '10px 12px' }}>注册时间</th>
|
||||
<th style={{ padding: '10px 12px', textAlign: 'center' }}>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map((u) => {
|
||||
const isAdmin = u.role === 'admin';
|
||||
const isCurrent = currentUser && currentUser.id === u.id;
|
||||
return (
|
||||
<tr key={u.id} style={{ borderBottom: '1px solid #f1f5f9' }}>
|
||||
<td style={{ padding: '10px 12px' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<img
|
||||
src={u.avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(u.username) + '&background=6366f1&color=fff&size=64'}
|
||||
style={{ width: 28, height: 28, borderRadius: '50%', objectFit: 'cover' }}
|
||||
alt=""
|
||||
/>
|
||||
<span style={{ fontWeight: 500 }}>{u.username}</span>
|
||||
{isCurrent && <span style={{ fontSize: 11, color: '#94a3b8', background: '#eef2ff', padding: '1px 8px', borderRadius: 4 }}>你</span>}
|
||||
</div>
|
||||
</td>
|
||||
<td style={{ padding: '10px 12px' }}>
|
||||
<span style={{
|
||||
display: 'inline-block', padding: '2px 10px', borderRadius: 4, fontSize: 12, fontWeight: 500,
|
||||
...(isAdmin ? { background: '#6366f1', color: '#fff' } : { background: '#e2e8f0', color: '#64748b' }),
|
||||
}}>
|
||||
{isAdmin ? '管理员' : '普通用户'}
|
||||
</span>
|
||||
</td>
|
||||
<td style={{ padding: '10px 12px', color: '#94a3b8', fontSize: 13 }}>
|
||||
{u.created_at ? new Date(u.created_at).toLocaleDateString('zh-CN') : '—'}
|
||||
</td>
|
||||
<td style={{ padding: '10px 12px', textAlign: 'center' }}>
|
||||
{isCurrent ? (
|
||||
<span style={{ fontSize: 12, color: '#94a3b8' }}>不可操作自己</span>
|
||||
) : isAdmin ? (
|
||||
<button className="btn-sm btn-secondary" style={{ padding: '4px 12px' }} onClick={() => handleRole(u, 'user')}>设为普通用户</button>
|
||||
) : (
|
||||
<button className="btn-sm btn-primary" style={{ padding: '4px 12px', background: '#6366f1', color: '#fff', border: 'none', borderRadius: 4, cursor: 'pointer' }} onClick={() => handleRole(u, 'admin')}>设为管理员</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user