feat: port upstream custom pages, notifications, recovery codes, account security

- schema: custom_pages, notifications, recovery_codes tables + UNIQUE(conversations) + posts.edited_at
- API: custom-pages CRUD (public + admin), notifications (list/read/read-all), recovery-codes (generate/count/reset-password), user avatar/password/email, post edit
- UI: custom page nav links + iframe rendering, admin custom pages tab with editor modal, messages page shows notifications, settings page gains avatar upload, password/email change, recovery codes manager
- Sync globals.css with upstream rewrite
This commit is contained in:
lezi-fun committed 2026-08-10 09:07:06 +08:00
1 parent 9e72e4de8e
commit 4732e7d61d
28 files changed
+1196 -255

No files matched your search

+71
View File
@@ -0,0 +1,71 @@
'use client';
// 账户安全:修改密码 + 修改邮箱
import { useState } from 'react';
import { API } from '@/lib/api';
import { useApp } from './AppProvider';
export default function AccountSecurity() {
const { currentUser } = useApp();
const [oldPassword, setOldPassword] = useState('');
const [newPassword, setNewPassword] = useState('');
const [pwStatus, setPwStatus] = useState(null);
const [emailPassword, setEmailPassword] = useState('');
const [newEmail, setNewEmail] = useState('');
const [emailStatus, setEmailStatus] = useState(null);
const changePassword = async () => {
if (!oldPassword || !newPassword) { alert('请填写完整信息'); return; }
if (newPassword.length < 6) { alert('新密码至少6位'); return; }
try {
await API.updatePassword(currentUser.id, oldPassword, newPassword);
setPwStatus({ ok: true, msg: '✅ 密码修改成功' });
setOldPassword('');
setNewPassword('');
} catch (err) {
setPwStatus({ ok: false, msg: '❌ ' + err.message });
}
};
const changeEmail = async () => {
if (!emailPassword || !newEmail) { alert('请填写完整信息'); return; }
try {
await API.updateEmail(currentUser.id, emailPassword, newEmail);
setEmailStatus({ ok: true, msg: '✅ 邮箱修改成功' });
setEmailPassword('');
setNewEmail('');
} catch (err) {
setEmailStatus({ ok: false, msg: '❌ ' + err.message });
}
};
return (
<div style={{ marginTop: 16, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20 }}>
<h3 style={{ fontSize: 16, marginBottom: 12 }}>🔒 账户安全</h3>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>当前密码</label>
<input type="password" value={oldPassword} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setOldPassword(e.target.value)} />
</div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>新密码</label>
<input type="password" value={newPassword} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setNewPassword(e.target.value)} />
</div>
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={changePassword}>修改密码</button>
{pwStatus && <div style={{ fontSize: 13, marginTop: 6, color: pwStatus.ok ? '#22c55e' : '#ef4444' }}>{pwStatus.msg}</div>}
<div style={{ borderTop: '1px solid var(--border)', margin: '16px 0' }}></div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>当前密码(验证身份)</label>
<input type="password" value={emailPassword} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setEmailPassword(e.target.value)} />
</div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>新邮箱</label>
<input type="email" value={newEmail} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setNewEmail(e.target.value)} />
</div>
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={changeEmail}>修改邮箱</button>
{emailStatus && <div style={{ fontSize: 13, marginTop: 6, color: emailStatus.ok ? '#22c55e' : '#ef4444' }}>{emailStatus.msg}</div>}
</div>
);
}
+3
View File
@@ -8,12 +8,14 @@ import AdminUsers from './admin/AdminUsers';
import AdminLogs from './admin/AdminLogs';
import AdminLinks from './admin/AdminLinks';
import AdminForumSettings from './admin/AdminForumSettings';
import AdminCustomPages from './admin/AdminCustomPages';
const TABS = [
{ key: 'reports', label: '举报', icon: 'shieldAlert' },
{ key: 'users', label: '用户', icon: 'users' },
{ key: 'logs', label: '日志', icon: 'file' },
{ key: 'links', label: '友链', icon: 'link' },
{ key: 'custom', label: '自定义页面', icon: 'file' },
{ key: 'settings', label: '论坛设置', icon: 'settings' },
];
@@ -41,6 +43,7 @@ export default function AdminPage() {
{tab === 'users' && <AdminUsers />}
{tab === 'logs' && <AdminLogs />}
{tab === 'links' && <AdminLinks />}
{tab === 'custom' && <AdminCustomPages />}
{tab === 'settings' && <AdminForumSettings />}
</div>
</div>
+21 -1
View File
@@ -14,9 +14,10 @@ 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 | user
const [view, setView] = useState('feed'); // feed | post | new | admin | settings | messages | user | custom
const [currentPostId, setCurrentPostId] = useState(null);
const [currentUsername, setCurrentUsername] = useState(null);
const [currentPageName, setCurrentPageName] = useState(null);
const [sort, setSort] = useState('latest');
const [refreshKey, setRefreshKey] = useState(0);
const loadedRef = useRef(false);
@@ -77,6 +78,10 @@ export default function AppProvider({ children }) {
setCurrentUsername(userParam);
} else if (pageParam && ['messages', 'settings', 'admin', 'new'].includes(pageParam)) {
setView(pageParam);
} else if (pageParam) {
// 未知 page 参数视为自定义页面
setView('custom');
setCurrentPageName(pageParam);
}
}, []);
@@ -116,6 +121,16 @@ export default function AppProvider({ children }) {
setCurrentUsername(username);
}, []);
const openCustomPage = useCallback((pageName) => {
const url = new URL(window.location);
url.searchParams.set('page', pageName);
url.searchParams.delete('post');
url.searchParams.delete('user');
window.history.pushState({ page: 'custom', pageName }, '', url);
setView('custom');
setCurrentPageName(pageName);
}, []);
// 浏览器前进后退
useEffect(() => {
const onPop = (e) => {
@@ -126,10 +141,14 @@ export default function AppProvider({ children }) {
} else if (state.username) {
setView('user');
setCurrentUsername(state.username);
} else if (state.pageName) {
setView('custom');
setCurrentPageName(state.pageName);
} else {
setView(state.page || 'feed');
setCurrentPostId(null);
setCurrentUsername(null);
setCurrentPageName(null);
}
};
window.addEventListener('popstate', onPop);
@@ -173,6 +192,7 @@ export default function AppProvider({ children }) {
view, navigate,
currentPostId, openPost,
currentUsername, openUser,
currentPageName, openCustomPage,
sort, setSort,
refreshKey, refresh,
login, register, logout,
+61
View File
@@ -0,0 +1,61 @@
'use client';
// 自定义页面:以 iframe srcdoc 渲染 HTML 内容(与原版一致)
import { useEffect, useState } from 'react';
import { API } from '@/lib/api';
export default function CustomPage({ pageName }) {
const [html, setHtml] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
setHtml(null);
setError(null);
API.getCustomPage(pageName)
.then((page) => setHtml(page.content))
.catch((err) => setError(err.message));
}, [pageName]);
if (error) {
return (
<div style={{ padding: '84px 32px', textAlign: 'center', color: '#ef4444' }}>
页面加载失败:{error}
</div>
);
}
if (html === null) {
return <div style={{ padding: '84px 32px', textAlign: 'center', color: '#94a3b8' }}>加载中...</div>;
}
const srcdoc = `<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
padding: 24px;
background: var(--bg, #f6f8fc);
color: var(--text, #0a0e1a);
}
@media (prefers-color-scheme: dark) {
body { background: #0f1117; color: #e8edf5; }
}
</style>
</head>
<body>${html}</body>
</html>`;
return (
<div style={{ padding: '84px 32px 40px', background: 'var(--bg)', minHeight: '100vh' }}>
<iframe
style={{ width: '100%', minHeight: '70vh', border: 'none', borderRadius: 8, background: 'var(--surface)' }}
sandbox="allow-scripts allow-modals allow-same-origin"
srcDoc={srcdoc}
title={pageName}
/>
</div>
);
}
+67
View File
@@ -0,0 +1,67 @@
'use client';
// 消息页:通知列表(回复/删除/举报处理/系统)
import { useEffect, useState } from 'react';
import { API } from '@/lib/api';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
const TYPE_MAP = { reply: '💬', post_deleted: '🗑️', report_handled: '🛡️', system: '📢' };
export default function MessagesPage() {
const { currentUser } = useApp();
const [notifications, setNotifications] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
if (!currentUser) return;
API.getNotifications()
.then((data) => {
setNotifications(data || []);
setError(null);
API.markAllNotificationsRead().catch(() => {});
})
.catch((e) => { setError(e.message); setNotifications([]); });
}, [currentUser]);
if (!currentUser) {
return <div className="page-slide active" style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>请先登录</div>;
}
return (
<div className="page-slide active">
<div className="page-header" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
<h2><Icon name="message" size={20} /> 消息</h2>
</div>
<div style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
{error ? (
<div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>加载失败:{error}</div>
) : notifications === null ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>加载中...</div>
) : notifications.length === 0 ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '60px 0' }}>
<Icon name="message" size={48} />
<p style={{ fontSize: 16 }}>暂无消息</p>
<p style={{ fontSize: 13 }}>当有人回复你的帖子或处理你的举报时,会在这里通知你</p>
</div>
) : (
notifications.map((n) => {
const icon = TYPE_MAP[n.type] || '📌';
const time = n.created_at ? new Date(n.created_at).toLocaleString('zh-CN') : '';
return (
<div key={n.id} style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '14px 16px', borderBottom: '1px solid var(--border-light)', background: 'var(--surface)', borderRadius: 6, marginBottom: 6 }}>
<span style={{ fontSize: 20 }}>{icon}</span>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontWeight: 600, fontSize: 14 }}>{n.title}</div>
<div style={{ color: 'var(--text-secondary)', fontSize: 13, marginTop: 2 }}>{n.content}</div>
{n.link && <a href={n.link} style={{ color: 'var(--primary)', fontSize: 13, textDecoration: 'none', marginTop: 4, display: 'inline-block' }}>查看详情 →</a>}
<div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 4 }}>{time}</div>
</div>
</div>
);
})
)}
</div>
</div>
);
}
+25 -3
View File
@@ -1,13 +1,19 @@
'use client';
// 导航栏:论坛名、登录/注册按钮、用户下拉菜单、主题切换
import { useState } from 'react';
// 导航栏:论坛名、自定义页面链接、登录/注册、用户菜单、主题切换
import { useState, useEffect } from 'react';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
import { API } from '@/lib/api';
export default function Navbar({ onOpenModal }) {
const { currentUser, forumName, theme, toggleTheme, navigate, logout } = useApp();
const { currentUser, forumName, theme, toggleTheme, navigate, openCustomPage, logout } = useApp();
const [menuOpen, setMenuOpen] = useState(false);
const [customPages, setCustomPages] = useState([]);
useEffect(() => {
API.getCustomPages().then(setCustomPages).catch(() => {});
}, []);
const avatarSrc = currentUser?.avatar_url ||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(currentUser?.username || 'U') +
@@ -35,6 +41,22 @@ export default function Navbar({ onOpenModal }) {
<span className="forum-name" onClick={() => navigate('feed')} style={{ cursor: 'pointer' }}>
{forumName}
</span>
<span id="customNavLinks" style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginLeft: 16 }}>
{customPages.map((p) => (
<a
key={p.id}
href="#"
className="custom-page-nav-link"
data-custom={p.name}
onClick={(e) => { e.preventDefault(); openCustomPage(p.name); }}
style={{ color: 'var(--text-secondary)', textDecoration: 'none', fontSize: 14, padding: '4px 10px', borderRadius: 4, transition: 'color 0.15s' }}
onMouseEnter={(e) => { e.currentTarget.style.color = 'var(--text)'; }}
onMouseLeave={(e) => { e.currentTarget.style.color = 'var(--text-secondary)'; }}
>
{p.title}
</a>
))}
</span>
</div>
<div className="nav-right">
<div id="userMenu">
+65
View File
@@ -0,0 +1,65 @@
'use client';
// 恢复码管理:查看 + 重新生成
import { useState, useEffect } from 'react';
import { API } from '@/lib/api';
export default function RecoveryCodes() {
const [count, setCount] = useState(0);
const [modal, setModal] = useState(null); // null | {codes, isNew}
const loadCount = () => {
API.getRecoveryCodeCount().then((d) => setCount(d.count || 0)).catch(() => {});
};
useEffect(loadCount, []);
const regenerate = async () => {
if (!confirm('重新生成将使所有旧恢复码失效,确定继续吗?')) return;
try {
const d = await API.generateRecoveryCodes();
setModal({ codes: d.codes || [], isNew: true });
loadCount();
} catch (err) {
alert('生成失败:' + err.message);
}
};
const view = async () => {
try {
// 生成后直接展示;若已有恢复码则重新生成展示(与原版一致:查看即生成新码)
const d = await API.generateRecoveryCodes();
setModal({ codes: d.codes || [], isNew: false });
loadCount();
} catch (err) {
alert('获取失败:' + err.message);
}
};
return (
<div style={{ marginTop: 16, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20 }}>
<h3 style={{ fontSize: 16, marginBottom: 8 }}>🔑 恢复码</h3>
<p style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 12 }}>用于忘记密码时重置账户。每个恢复码只能使用一次。</p>
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={view}>📋 查看恢复码</button>
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={regenerate}>🔄 重新生成</button>
</div>
<div id="recoveryCodesStatus" style={{ fontSize: 13, color: 'var(--text-light)', marginTop: 8 }}>剩余 {count} 个可用恢复码</div>
{modal && (
<div className="modal active" style={{ display: 'flex' }} onClick={(e) => { if (e.target === e.currentTarget) setModal(null); }}>
<div className="modal-content" style={{ maxWidth: 480, position: 'relative' }}>
<span className="close" style={{ position: 'absolute', top: 12, right: 16, fontSize: 24, cursor: 'pointer', color: 'var(--text-light)' }} onClick={() => setModal(null)}>&times;</span>
<h2 style={{ marginBottom: 12 }}>{modal.isNew ? '🆕 新恢复码' : '🔑 恢复码'}</h2>
<p style={{ fontSize: 13, color: '#ef4444', marginBottom: 12 }}>⚠️ 请妥善保存这些恢复码,关闭窗口后无法再次查看。</p>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
{modal.codes.map((c, i) => (
<code key={i} style={{ background: 'var(--bg)', padding: '8px 12px', borderRadius: 6, fontSize: 13, textAlign: 'center', userSelect: 'all' }}>{c}</code>
))}
</div>
<button className="btn-primary" style={{ width: '100%', padding: 10, marginTop: 16 }} onClick={() => setModal(null)}>我已保存</button>
</div>
</div>
)}
</div>
);
}
+62 -20
View File
@@ -1,15 +1,35 @@
'use client';
// 个人设置页
import { useState } from 'react';
import { API } from '@/lib/api';
// 个人设置页:头像 + 基本资料 + 账户安全 + 恢复码
import { useState, useRef } from 'react';
import { API, uploadImage } from '@/lib/api';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
import AccountSecurity from './AccountSecurity';
import RecoveryCodes from './RecoveryCodes';
export default function SettingsPage() {
const { currentUser, setCurrentUser } = useApp();
const [username, setUsername] = useState(currentUser?.username || '');
const [bio, setBio] = useState(currentUser?.bio || '');
const [avatarUrl, setAvatarUrl] = useState(currentUser?.avatar_url || '');
const [avatarStatus, setAvatarStatus] = useState(null);
const avatarInputRef = useRef(null);
const handleAvatar = async (file) => {
if (!file) return;
if (!file.type.startsWith('image/')) { setAvatarStatus({ ok: false, msg: '❌ 请选择图片文件' }); return; }
if (file.size > 5 * 1024 * 1024) { setAvatarStatus({ ok: false, msg: '❌ 图片不能超过 5MB' }); return; }
try {
const url = await uploadImage(file);
await API.updateAvatar(currentUser.id, url);
setAvatarUrl(url);
setCurrentUser({ ...currentUser, avatar_url: url });
setAvatarStatus({ ok: true, msg: '✅ 头像已更新' });
} catch (err) {
setAvatarStatus({ ok: false, msg: '❌ ' + err.message });
}
};
const handleSave = async () => {
if (!currentUser) { alert('请先登录'); return; }
@@ -24,27 +44,49 @@ export default function SettingsPage() {
}
};
const avatarSrc = avatarUrl ||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(currentUser?.username || 'U') + '&background=6366f1&color=fff&size=128';
return (
<div className="page-slide active">
<div className="page-header" style={{ maxWidth: 400, margin: '0 auto', width: '100%' }}>
<div className="page-header" style={{ maxWidth: 500, margin: '0 auto', width: '100%' }}>
<h2><Icon name="settings" size={20} /> 设置</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 style={{ maxWidth: 500, margin: '0 auto', width: '100%', padding: '20px 0' }}>
{/* 头像 */}
<div style={{ textAlign: 'center', marginBottom: 24 }}>
<div style={{ position: 'relative', display: 'inline-block' }}>
<img src={avatarSrc} style={{ width: 100, height: 100, borderRadius: '50%', objectFit: 'cover', border: '3px solid var(--primary)' }} alt="" />
<button
style={{ position: 'absolute', bottom: 0, right: 0, background: 'var(--primary)', color: '#fff', border: 'none', borderRadius: '50%', width: 32, height: 32, cursor: 'pointer', fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 2px 8px rgba(99,102,241,0.4)' }}
onClick={() => avatarInputRef.current?.click()}
>
📷
</button>
</div>
<input type="file" ref={avatarInputRef} accept="image/*" style={{ display: 'none' }} onChange={(e) => { if (e.target.files?.[0]) handleAvatar(e.target.files[0]); }} />
<h2 style={{ margin: '12px 0 4px' }}>{currentUser?.username}</h2>
<p style={{ color: 'var(--text-secondary)', fontSize: 14 }}>{bio || '这个人很懒,什么都没写'}</p>
{avatarStatus && (
<div style={{ fontSize: 13, marginTop: 8, color: avatarStatus.ok ? '#22c55e' : '#ef4444' }}>{avatarStatus.msg}</div>
)}
</div>
{/* 基本资料 */}
<div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20 }}>
<div style={{ marginBottom: 16 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>用户名</label>
<input type="text" value={username} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setUsername(e.target.value)} />
</div>
<div style={{ marginBottom: 16 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>个人简介</label>
<textarea rows={3} value={bio} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)', resize: 'vertical' }} onChange={(e) => setBio(e.target.value)} />
</div>
<button className="btn-primary" style={{ width: '100%', padding: 10 }} onClick={handleSave}>保存设置</button>
</div>
<AccountSecurity />
<RecoveryCodes />
</div>
</div>
);
+86
View File
@@ -0,0 +1,86 @@
'use client';
// 管理后台 - 自定义页面管理(列表)
import { useEffect, useState } from 'react';
import { API } from '@/lib/api';
import CustomPageEditor from './CustomPageEditor';
export default function AdminCustomPages() {
const [pages, setPages] = useState(null);
const [error, setError] = useState(null);
const [editing, setEditing] = useState(null); // null | 'new' | page对象
const load = () => {
API.adminGetCustomPages()
.then((data) => { setPages(data || []); setError(null); })
.catch((e) => { setError(e.message); setPages([]); });
};
useEffect(load, []);
const handleDelete = async (p) => {
if (!confirm('确定要删除这个页面吗?')) return;
try {
await API.adminDeleteCustomPage(p.id);
load();
} catch (err) {
alert('删除失败:' + err.message);
}
};
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>加载失败:{error}</div>;
return (
<>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
<h3 style={{ margin: 0 }}>📄 自定义页面</h3>
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={() => setEditing('new')}>➕ 添加页面</button>
</div>
<div id="customPageList">
{pages === null ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}>加载中...</div>
) : pages.length === 0 ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}>暂无自定义页面</div>
) : (
<div style={{ overflowX: 'auto' }}>
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}>
<thead>
<tr style={{ textAlign: 'left', borderBottom: '2px solid var(--border)' }}>
<th style={{ padding: '8px 12px' }}>名称</th>
<th style={{ padding: '8px 12px' }}>标题</th>
<th style={{ padding: '8px 12px' }}>URL</th>
<th style={{ padding: '8px 12px' }}>状态</th>
<th style={{ padding: '8px 12px', textAlign: 'center' }}>操作</th>
</tr>
</thead>
<tbody>
{pages.map((p) => (
<tr key={p.id} style={{ borderBottom: '1px solid var(--border-light)' }}>
<td style={{ padding: '8px 12px' }}><code style={{ background: 'var(--bg)', padding: '2px 6px', borderRadius: 4, fontSize: 12 }}>{p.name}</code></td>
<td style={{ padding: '8px 12px' }}>{p.title}</td>
<td style={{ padding: '8px 12px' }}><code style={{ background: 'var(--bg)', padding: '2px 6px', borderRadius: 4, fontSize: 12 }}>?custom={p.name}</code></td>
<td style={{ padding: '8px 12px' }}>
<span style={{ color: p.enabled ? '#22c55e' : '#ef4444' }}>{p.enabled ? '✅ 启用' : '❌ 禁用'}</span>
</td>
<td style={{ padding: '8px 12px', textAlign: 'center', display: 'flex', gap: 6, justifyContent: 'center' }}>
<button className="btn-sm btn-secondary" onClick={() => setEditing(p)}>✏️</button>
<button className="btn-sm btn-danger" onClick={() => handleDelete(p)}>🗑️</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
{editing && (
<CustomPageEditor
page={editing === 'new' ? null : editing}
onClose={() => setEditing(null)}
onSaved={() => { setEditing(null); load(); }}
/>
)}
</>
);
}
+88
View File
@@ -0,0 +1,88 @@
'use client';
// 管理后台 - 自定义页面编辑器(modal)
import { useState } from 'react';
import { API } from '@/lib/api';
export default function CustomPageEditor({ page, onClose, onSaved }) {
const isEdit = !!page;
const [name, setName] = useState(page?.name || '');
const [title, setTitle] = useState(page?.title || '');
const [content, setContent] = useState(page?.content || '');
const [enabled, setEnabled] = useState(page?.enabled !== false);
const handleSave = async () => {
if (!name.trim()) { alert('请输入页面名称'); return; }
if (!title.trim()) { alert('请输入导航栏显示名称'); return; }
if (!content.trim()) { alert('请输入页面内容'); return; }
if (!/^[a-zA-Z0-9\-_]+$/.test(name.trim())) {
alert('页面名称只允许字母、数字、短横线和下划线');
return;
}
try {
if (isEdit) {
await API.adminUpdateCustomPage(page.id, title.trim(), content.trim(), enabled);
} else {
await API.adminCreateCustomPage(name.trim(), title.trim(), content.trim());
}
onSaved();
} catch (err) {
alert('保存失败:' + err.message);
}
};
return (
<div className="modal active" style={{ display: 'flex' }} onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
<div className="modal-content" style={{ maxWidth: 600, maxHeight: '90vh', overflowY: 'auto', position: 'relative' }}>
<span className="close" style={{ position: 'absolute', top: 12, right: 16, fontSize: 24, cursor: 'pointer', color: 'var(--text-light)' }} onClick={onClose}>&times;</span>
<h2 style={{ marginBottom: 16 }}>{isEdit ? '✏️ 编辑页面' : '📄 添加页面'}</h2>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>页面名称</label>
<input
type="text"
value={name}
readOnly={isEdit}
placeholder="about (用于 URL: ?custom=about)"
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: isEdit ? 'var(--border-light)' : 'var(--bg)', color: 'var(--text)' }}
onChange={(e) => setName(e.target.value)}
/>
{isEdit
? <div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}>⚠️ 名称不可修改</div>
: <div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}>只允许字母、数字、短横线和下划线</div>}
</div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>导航栏显示名称</label>
<input
type="text"
value={title}
placeholder="关于我们"
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }}
onChange={(e) => setTitle(e.target.value)}
/>
</div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>状态</label>
<select
value={String(enabled)}
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }}
onChange={(e) => setEnabled(e.target.value === 'true')}
>
<option value="true">启用</option>
<option value="false">禁用</option>
</select>
</div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>页面内容(HTML + CSS + JS)</label>
<textarea
rows={12}
value={content}
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 13, fontFamily: 'monospace', background: 'var(--bg)', color: 'var(--text)', resize: 'vertical' }}
onChange={(e) => setContent(e.target.value)}
/>
<div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}>支持 HTML、CSS(&lt;style&gt;)、JS(&lt;script&gt;),内容会在独立的沙盒中渲染</div>
</div>
<button className="btn-primary" style={{ padding: '10px 24px', width: '100%' }} onClick={handleSave}>保存</button>
</div>
</div>
);
}