fix: polish forum navigation and interface states

This commit is contained in:
lezi-fun committed 2026-08-11 15:25:05 +08:00
1 parent 0933220c70
commit 6947cdaf36
33 files changed
+1615 -360

No files matched your search

+11 -8
View File
@@ -5,10 +5,13 @@ import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
import { useToast } from './Toast';
export default function AccountSecurity() {
const { currentUser } = useApp();
const { t } = useTranslation();
const { toast } = useToast();
const [oldPassword, setOldPassword] = useState('');
const [newPassword, setNewPassword] = useState('');
const [pwStatus, setPwStatus] = useState(null);
@@ -17,33 +20,33 @@ export default function AccountSecurity() {
const [emailStatus, setEmailStatus] = useState(null);
const changePassword = async () => {
if (!oldPassword || !newPassword) { alert(t('security.fillAll')); return; }
if (newPassword.length < 6) { alert(t('security.pwMin')); return; }
if (!oldPassword || !newPassword) { toast(t('security.fillAll'), 'warning'); return; }
if (newPassword.length < 6) { toast(t('security.pwMin'), 'warning'); return; }
try {
await API.updatePassword(currentUser.id, oldPassword, newPassword);
setPwStatus({ ok: true, msg: t('security.pwChanged') });
setOldPassword('');
setNewPassword('');
} catch (err) {
setPwStatus({ ok: false, msg: '❌ ' + err.message });
setPwStatus({ ok: false, msg: err.message });
}
};
const changeEmail = async () => {
if (!emailPassword || !newEmail) { alert(t('security.fillAll')); return; }
if (!emailPassword || !newEmail) { toast(t('security.fillAll'), 'warning'); return; }
try {
await API.updateEmail(currentUser.id, emailPassword, newEmail);
setEmailStatus({ ok: true, msg: t('security.emailChanged') });
setEmailPassword('');
setNewEmail('');
} catch (err) {
setEmailStatus({ ok: false, msg: '❌ ' + err.message });
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 }}>🔒 {t('security.title')}</h3>
<h3 style={{ fontSize: 16, marginBottom: 12 }}><Icon name="lock" size={16} /> {t('security.title')}</h3>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>{t('security.currentPw')}</label>
@@ -54,7 +57,7 @@ export default function AccountSecurity() {
<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}>{t('security.changePw')}</button>
{pwStatus && <div style={{ fontSize: 13, marginTop: 6, color: pwStatus.ok ? '#22c55e' : '#ef4444' }}>{pwStatus.msg}</div>}
{pwStatus && <div style={{ fontSize: 13, marginTop: 6, color: pwStatus.ok ? '#22c55e' : '#ef4444', display: 'flex', alignItems: 'center', gap: 5 }}><Icon name={pwStatus.ok ? 'success' : 'error'} size={14} /> {pwStatus.msg}</div>}
<div style={{ borderTop: '1px solid var(--border)', margin: '16px 0' }}></div>
@@ -67,7 +70,7 @@ export default function AccountSecurity() {
<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}>{t('security.changeEmail')}</button>
{emailStatus && <div style={{ fontSize: 13, marginTop: 6, color: emailStatus.ok ? '#22c55e' : '#ef4444' }}>{emailStatus.msg}</div>}
{emailStatus && <div style={{ fontSize: 13, marginTop: 6, color: emailStatus.ok ? '#22c55e' : '#ef4444', display: 'flex', alignItems: 'center', gap: 5 }}><Icon name={emailStatus.ok ? 'success' : 'error'} size={14} /> {emailStatus.msg}</div>}
</div>
);
}
+131 -10
View File
@@ -2,10 +2,47 @@
// 全局状态 Provider:用户、主题、论坛名、当前视图(feed/post/new/admin/...)
import { createContext, useContext, useState, useEffect, useCallback, useRef } from 'react';
import { flushSync } from 'react-dom';
import { API, getTheme, setToken, getToken } from '@/lib/api';
const AppContext = createContext(null);
function stageSharedGeometry(transition, { name, duration, moveOffset, preserveSizeUntilMove = false }) {
transition.ready.then(() => {
const groupAnimation = document.getAnimations().find(
(animation) => animation.effect?.pseudoElement === `::view-transition-group(${name})`
);
const frames = groupAnimation?.effect?.getKeyframes();
if (!groupAnimation || !frames || frames.length < 2) return;
const start = frames[0];
const end = frames[frames.length - 1];
groupAnimation.effect.setKeyframes([
{
offset: 0,
width: start.width,
height: start.height,
transform: start.transform,
easing: 'cubic-bezier(0.16, 1, 0.3, 1)',
},
{
offset: moveOffset,
width: preserveSizeUntilMove ? start.width : end.width,
height: start.height,
transform: end.transform,
easing: 'cubic-bezier(0.4, 0, 0.2, 1)',
},
{
offset: 1,
width: end.width,
height: end.height,
transform: end.transform,
},
]);
groupAnimation.effect.updateTiming({ duration, easing: 'linear', fill: 'both' });
}).catch(() => {});
}
export function useApp() {
return useContext(AppContext);
}
@@ -17,6 +54,7 @@ export default function AppProvider({ children, cachedName = '' }) {
const [theme, setThemeState] = useState('light');
const [view, setView] = useState('feed'); // feed | post | new | admin | settings | messages | user | custom
const [currentPostId, setCurrentPostId] = useState(null);
const [currentPostPreview, setCurrentPostPreview] = useState(null);
const [currentUsername, setCurrentUsername] = useState(null);
const [currentPageName, setCurrentPageName] = useState(null);
const [sort, setSort] = useState('latest');
@@ -166,20 +204,101 @@ export default function AppProvider({ children, cachedName = '' }) {
url.searchParams.set('page', page);
url.searchParams.delete('post');
}
window.history.pushState({ page }, '', url);
setView(page);
setCurrentPostId(null);
refresh();
}, [refresh]);
const commitNavigation = (refreshFeed = true) => {
window.history.pushState({ page }, '', url);
setView(page);
setCurrentPostId(null);
setCurrentPostPreview(null);
if (refreshFeed) refresh();
};
const openPost = useCallback((postId) => {
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
if (page !== 'feed' || view === 'feed' || !document.startViewTransition || reduceMotion) {
commitNavigation();
return;
}
let targetCard = currentPostId
? Array.from(document.querySelectorAll('[data-post-id]')).find((element) => element.dataset.postId === String(currentPostId))
: null;
let targetTitle = null;
let targetTime = null;
document.documentElement.classList.add('home-view-transition');
if (targetCard) document.documentElement.classList.add('returning-home');
const transition = document.startViewTransition(() => {
flushSync(() => commitNavigation(false));
targetCard = currentPostId
? Array.from(document.querySelectorAll('[data-post-id]')).find((element) => element.dataset.postId === String(currentPostId))
: null;
targetTitle = targetCard?.querySelector('.post-title');
targetTime = targetCard?.querySelector('.post-time');
if (targetCard) targetCard.style.viewTransitionName = 'post-expand';
if (targetTitle) targetTitle.style.viewTransitionName = 'post-heading';
if (targetTime) targetTime.style.viewTransitionName = 'post-time';
});
stageSharedGeometry(transition, { name: 'post-expand', duration: 480, moveOffset: 0.72 });
stageSharedGeometry(transition, {
name: 'post-heading',
duration: 480,
moveOffset: 0.72,
preserveSizeUntilMove: true,
});
const clearTargetNames = () => {
if (targetCard) targetCard.style.viewTransitionName = '';
if (targetTitle) targetTitle.style.viewTransitionName = '';
if (targetTime) targetTime.style.viewTransitionName = '';
};
transition.ready.then(clearTargetNames, clearTargetNames);
transition.finished.finally(() => {
document.documentElement.classList.remove('home-view-transition', 'returning-home');
refresh();
});
}, [currentPostId, refresh, view]);
const openPost = useCallback((postId, sourceElement = null, preview = null) => {
const url = new URL(window.location);
url.searchParams.set('post', postId);
url.searchParams.delete('page');
url.searchParams.delete('user');
window.history.pushState({ page: 'post', postId }, '', url);
setView('post');
setCurrentPostId(postId);
const commitNavigation = () => {
window.history.pushState({ page: 'post', postId }, '', url);
setView('post');
setCurrentPostId(postId);
setCurrentPostPreview(preview);
};
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
if (!sourceElement || !document.startViewTransition || reduceMotion) {
commitNavigation();
return;
}
const sourceTitle = sourceElement.querySelector('.post-title');
const sourceTime = sourceElement.querySelector('.post-time');
sourceElement.style.viewTransitionName = 'post-expand';
if (sourceTitle) sourceTitle.style.viewTransitionName = 'post-heading';
if (sourceTime) sourceTime.style.viewTransitionName = 'post-time';
document.documentElement.classList.add('post-view-transition');
const transition = document.startViewTransition(() => {
flushSync(commitNavigation);
});
stageSharedGeometry(transition, { name: 'post-expand', duration: 960, moveOffset: 0.62 });
stageSharedGeometry(transition, {
name: 'post-heading',
duration: 960,
moveOffset: 0.62,
preserveSizeUntilMove: true,
});
const clearSourceNames = () => {
sourceElement.style.viewTransitionName = '';
if (sourceTitle) sourceTitle.style.viewTransitionName = '';
if (sourceTime) sourceTime.style.viewTransitionName = '';
};
transition.ready.then(clearSourceNames, clearSourceNames);
transition.finished.finally(() => {
document.documentElement.classList.remove('post-view-transition');
});
}, []);
const openUser = useCallback((username) => {
@@ -209,6 +328,7 @@ export default function AppProvider({ children, cachedName = '' }) {
if (state.postId) {
setView('post');
setCurrentPostId(state.postId);
setCurrentPostPreview(null);
} else if (state.username) {
setView('user');
setCurrentUsername(state.username);
@@ -218,6 +338,7 @@ export default function AppProvider({ children, cachedName = '' }) {
} else {
setView(state.page || 'feed');
setCurrentPostId(null);
setCurrentPostPreview(null);
setCurrentUsername(null);
setCurrentPageName(null);
}
@@ -262,7 +383,7 @@ export default function AppProvider({ children, cachedName = '' }) {
forumName, forumNameLoaded, updateForumName,
theme, toggleTheme,
view, navigate,
currentPostId, openPost,
currentPostId, currentPostPreview, openPost,
currentUsername, openUser,
currentPageName, openCustomPage,
sort, setSort,
+68 -25
View File
@@ -8,6 +8,7 @@ import { useApp } from './AppProvider';
import { Icon } from './Icons';
import ImageViewer from './ImageViewer';
import { renderMarkdown } from '@/lib/markdown';
import { useToast } from './Toast';
function avatar(username) {
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
@@ -17,17 +18,21 @@ function avatar(username) {
export default function Feed({ onOpenModal, onReport }) {
const { currentUser, sort, setSort, openPost, openUser, navigate, refreshKey } = useApp();
const { t } = useTranslation();
const { toast, confirmAction } = useToast();
const [posts, setPosts] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(true);
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);
const [viewerSrc, setViewerSrc] = useState(null);
const [selectedSort, setSelectedSort] = useState(sort);
const [drawerPhase, setDrawerPhase] = useState('idle');
const postListRef = useRef(null);
const sortTimerRef = useRef(null);
const pendingSortRef = useRef(null);
const PAGE_SIZE = 20;
const load = useCallback(async (targetPage) => {
setPosts(null);
setError(null);
try {
const result = await API.getPosts(sort, null, targetPage, PAGE_SIZE);
@@ -37,6 +42,16 @@ export default function Feed({ onOpenModal, onReport }) {
} catch (err) {
setError(err.message);
setPosts([]);
} finally {
if (pendingSortRef.current === sort) {
requestAnimationFrame(() => {
setDrawerPhase('opening');
sortTimerRef.current = setTimeout(() => {
pendingSortRef.current = null;
setDrawerPhase('idle');
}, 360);
});
}
}
}, [sort, refreshKey]);
@@ -58,13 +73,37 @@ export default function Feed({ onOpenModal, onReport }) {
// 排序切换时回第一页
useEffect(() => { setPage(1); }, [sort]);
useEffect(() => () => clearTimeout(sortTimerRef.current), []);
const handleSortChange = (nextSort) => {
if (nextSort === selectedSort) return;
setSelectedSort(nextSort);
clearTimeout(sortTimerRef.current);
// 快速切回当前排序时,直接重新展开尚未替换的列表。
if (nextSort === sort) {
pendingSortRef.current = null;
setDrawerPhase('opening');
sortTimerRef.current = setTimeout(() => setDrawerPhase('idle'), 360);
return;
}
setDrawerPhase('closing');
sortTimerRef.current = setTimeout(() => {
pendingSortRef.current = nextSort;
setDrawerPhase('closed');
setSort(nextSort);
}, 220);
};
const handleDelete = async (postId) => {
if (!confirm(t('feed.confirmDelete'))) return;
if (!await confirmAction(t('feed.confirmDelete'))) return;
try {
await API.deletePost(postId);
load(page);
} catch (err) {
alert(t('feed.deleteFailed', { msg: err.message }));
toast(t('feed.deleteFailed', { msg: err.message }), 'error');
}
};
@@ -72,34 +111,36 @@ export default function Feed({ onOpenModal, onReport }) {
<main id="feed">
<div className="feed-header">
<div className="feed-header-left">
<button className={'tab' + (sort === 'latest' ? ' active' : '')} onClick={() => setSort('latest')}>{t('feed.latest')}</button>
<button className={'tab' + (sort === 'hot' ? ' active' : '')} onClick={() => setSort('hot')}>{t('feed.hot')}</button>
<button className={'tab' + (selectedSort === 'latest' ? ' active' : '')} onClick={() => handleSortChange('latest')}>{t('feed.latest')}</button>
<button className={'tab' + (selectedSort === 'hot' ? ' active' : '')} onClick={() => handleSortChange('hot')}>{t('feed.hot')}</button>
</div>
<button
className="btn-primary fab-btn"
onClick={() => {
if (!currentUser) { alert(t('newPost.pleaseLogin')); return; }
if (!currentUser) { toast(t('newPost.pleaseLogin'), 'warning'); return; }
navigate('new');
}}
>
<Icon name="plus" /> {t('feed.newPost')}
</button>
</div>
<div id="postList" ref={postListRef}>
{posts === null ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}><span className="spinner-sm" />{t('feed.loading')}</div>
) : error ? (
<div style={{ textAlign: 'center', color: '#ef4444', padding: '40px 0' }}>{t('feed.loadFailed', { msg: error })}</div>
) : posts.length === 0 ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '60px 0' }}>{t('feed.empty')}</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={'feed-posts-drawer ' + drawerPhase}>
<div className="feed-posts-drawer-inner">
<div id="postList" ref={postListRef}>
{posts === null ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}><span className="spinner-sm" />{t('feed.loading')}</div>
) : error ? (
<div style={{ textAlign: 'center', color: '#ef4444', padding: '40px 0' }}>{t('feed.loadFailed', { msg: error })}</div>
) : posts.length === 0 ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '60px 0' }}>{t('feed.empty')}</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" data-post-id={p.id} style={{ cursor: 'pointer' }}
onClick={(e) => openPost(p.id, e.currentTarget, p)}>
{p.is_pinned && (
<div style={{ fontSize: 12, color: 'var(--primary)', fontWeight: 600, marginBottom: 4 }}>{t('feed.pinned')}</div>
<div style={{ fontSize: 12, color: 'var(--primary)', fontWeight: 600, marginBottom: 4 }}><Icon name="pin" size={12} /> {t('feed.pinned')}</div>
)}
<div className="post-header">
<img src={p.avatar_url || avatar(p.username)} className="post-avatar" alt="" />
@@ -130,7 +171,7 @@ export default function Feed({ onOpenModal, onReport }) {
</span>
<button className="action-report" onClick={(e) => {
e.stopPropagation();
if (!currentUser) { alert(t('newPost.pleaseLogin')); return; }
if (!currentUser) { toast(t('newPost.pleaseLogin'), 'warning'); return; }
onReport(p.id);
}}>
<Icon name="flag" size={14} /> {t('feed.report')}
@@ -144,10 +185,12 @@ export default function Feed({ onOpenModal, onReport }) {
</button>
)}
</div>
</div>
);
})
)}
</div>
);
})
)}
</div>
</div>
</div>
{totalPages > 1 && posts && posts.length > 0 && (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 6, padding: '16px 0', marginTop: 8, borderTop: '1px solid var(--border)', flexWrap: 'wrap' }}>
+90
View File
@@ -87,6 +87,11 @@ const PATHS = {
<path d="M12 5v14"/><path d="M5 12h14"/>
</>
),
back: (
<>
<polyline points="15 18 9 12 15 6"/>
</>
),
close: (
<>
<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
@@ -97,4 +102,89 @@ const PATHS = {
<polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
</>
),
success: (
<>
<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/>
</>
),
error: (
<>
<circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/>
</>
),
warning: (
<>
<path d="M12 9v4"/><path d="M12 17h.01"/><circle cx="12" cy="12" r="10"/>
</>
),
pending: (
<>
<circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>
</>
),
edit: (
<>
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
</>
),
pin: (
<>
<path d="M21 10.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h8.5"/><polyline points="16 2 22 8 16 8"/><line x1="10" y1="14" x2="18" y2="14"/><line x1="10" y1="18" x2="14" y2="18"/>
</>
),
camera: (
<>
<path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/>
</>
),
image: (
<>
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/>
</>
),
key: (
<>
<path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/>
</>
),
calendar: (
<>
<rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>
</>
),
refresh: (
<>
<polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>
</>
),
list: (
<>
<line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/>
</>
),
megaphone: (
<>
<path d="M17 18.5c0 1.5-1.5 3-3.5 3s-3.5-1.5-3.5-3c0-.5.5-1 1-1h5c.5 0 1 .5 1 1z"/><path d="M4 11h16v6H4z"/><path d="M8 17v3"/><path d="M16 17v3"/><path d="M9 11V7a3 3 0 0 1 6 0v4"/>
</>
),
code: (
<>
<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>
</>
),
upload: (
<>
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/>
</>
),
save: (
<>
<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/>
</>
),
flag: (
<>
<path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/><line x1="4" y1="22" x2="4" y2="15"/>
</>
),
};
+3 -3
View File
@@ -6,7 +6,7 @@ import { API } from '@/lib/api';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
const TYPE_MAP = { reply: '💬', post_deleted: '🗑️', report_handled: '🛡️', system: '📢' };
const TYPE_MAP = { reply: 'message', post_deleted: 'trash', report_handled: 'shield', system: 'megaphone' };
export default function MessagesPage() {
const { currentUser } = useApp();
@@ -46,11 +46,11 @@ export default function MessagesPage() {
</div>
) : (
notifications.map((n) => {
const icon = TYPE_MAP[n.type] || '📌';
const icon = TYPE_MAP[n.type] || 'pin';
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>
<span style={{ color: 'var(--text-secondary)', paddingTop: 2 }}><Icon name={icon} size={20} /></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>
+11 -9
View File
@@ -7,10 +7,12 @@ import { API, generateCaptcha } from '@/lib/api';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
import CaptchaImage from './CaptchaImage';
import { useToast } from './Toast';
export default function Modals({ modal, onClose, reportPostId }) {
const { login, register, currentUser, refresh } = useApp();
const { t } = useTranslation();
const { toast } = useToast();
// 登录表单
const [loginEmail, setLoginEmail] = useState('');
@@ -38,7 +40,7 @@ export default function Modals({ modal, onClose, reportPostId }) {
};
const handleLogin = async () => {
if (!loginEmail.trim() || !loginPassword) { alert('请填写完整信息'); return; }
if (!loginEmail.trim() || !loginPassword) { toast('请填写完整信息', 'warning'); return; }
try {
const result = await login(loginEmail.trim(), loginPassword);
if (result.user) {
@@ -48,15 +50,15 @@ export default function Modals({ modal, onClose, reportPostId }) {
refresh();
}
} catch (err) {
alert('登录失败:' + err.message);
toast('登录失败:' + err.message, 'error');
}
};
const handleRegister = async () => {
if (!regUsername.trim() || !regEmail.trim() || !regPassword) { alert('请填写完整信息'); return; }
if (regPassword.length < 6) { alert('密码至少6位'); return; }
if (!regUsername.trim() || !regEmail.trim() || !regPassword) { toast('请填写完整信息', 'warning'); return; }
if (regPassword.length < 6) { toast('密码至少6位', 'warning'); return; }
if (!regCaptcha || parseInt(regCaptchaInput) !== regCaptcha.answer) {
alert('验证码错误,请重新计算');
toast('验证码错误,请重新计算', 'warning');
setRegCaptcha(generateCaptcha());
setRegCaptchaInput('');
return;
@@ -68,10 +70,10 @@ export default function Modals({ modal, onClose, reportPostId }) {
setRegEmail('');
setRegPassword('');
setRegCaptchaInput('');
alert('注册成功!');
toast('注册成功!', 'success');
refresh();
} catch (err) {
alert('注册失败:' + err.message);
toast('注册失败:' + err.message, 'error');
}
};
@@ -80,9 +82,9 @@ export default function Modals({ modal, onClose, reportPostId }) {
try {
await API.createReport(reportPostId, reportReason);
onClose();
alert('举报已提交,管理员将尽快处理');
toast('举报已提交,管理员将尽快处理', 'success');
} catch (err) {
alert('举报失败:' + err.message);
toast('举报失败:' + err.message, 'error');
}
};
+6 -4
View File
@@ -7,10 +7,12 @@ import { useApp } from './AppProvider';
import { Icon } from './Icons';
import { API } from '@/lib/api';
import { DMButton } from './chat/ChatManager';
import { useToast } from './Toast';
export default function Navbar({ onOpenModal }) {
const { currentUser, forumName, theme, toggleTheme, navigate, openCustomPage, logout } = useApp();
const { t } = useTranslation();
const { toast, confirmAction } = useToast();
const [menuOpen, setMenuOpen] = useState(false);
const [customPages, setCustomPages] = useState([]);
@@ -37,7 +39,7 @@ export default function Navbar({ onOpenModal }) {
const goPage = (page) => {
if (page === 'admin' && currentUser?.role !== 'admin') {
alert('无权限访问');
toast('无权限访问', 'warning');
return;
}
setMenuOpen(false);
@@ -47,7 +49,7 @@ export default function Navbar({ onOpenModal }) {
const openMessages = (e) => {
e.preventDefault();
setMenuOpen(false);
// 消息页 = 通知列表(与原版一致),私信走导航栏 ✉️ 按钮
// 消息页展示通知列表,私信使用导航栏按钮。
navigate('messages');
};
@@ -117,9 +119,9 @@ export default function Navbar({ onOpenModal }) {
<hr />
<a
href="#"
onClick={(e) => {
onClick={async (e) => {
e.preventDefault();
if (confirm(t('nav.logoutConfirm'))) {
if (await confirmAction(t('nav.logoutConfirm'))) {
setMenuOpen(false);
logout();
}
+4 -3
View File
@@ -30,7 +30,7 @@ export default function NewPost() {
for (const file of files) {
if (!file.type.startsWith('image/')) continue;
if (file.size > 5 * 1024 * 1024) {
alert('图片 ' + file.name + ' 超过 5MB,请压缩后上传');
toast('图片 ' + file.name + ' 超过 5MB,请压缩后上传', 'warning');
continue;
}
const dataUrl = await new Promise((resolve) => {
@@ -44,7 +44,7 @@ export default function NewPost() {
}
setPreviews((prev) => [...prev, ...newPreviews]);
} catch (err) {
alert('上传失败:' + err.message);
toast('上传失败:' + err.message, 'error');
} finally {
setUploading(false);
}
@@ -117,8 +117,9 @@ export default function NewPost() {
onDragLeave={(e) => { e.preventDefault(); setDragOver(false); }}
onDrop={(e) => { e.preventDefault(); setDragOver(false); if (e.dataTransfer.files) handleFiles(Array.from(e.dataTransfer.files)); }}
>
{!uploading && !dragOver && <Icon name="image" size={32} style={{ display: 'block', margin: '0 auto 8px', color: 'var(--text-secondary)' }} />}
<div style={{ fontSize: 13, color: 'var(--text-secondary)' }}>
{uploading ? t('newPost.uploading') : (dragOver ? t('newPost.drop') : '📷 ' + t('newPost.dropHint'))}
{uploading ? t('newPost.uploading') : (dragOver ? t('newPost.drop') : t('newPost.dropHint'))}
</div>
</div>
<input
+73 -64
View File
@@ -5,18 +5,21 @@ import { useEffect, useState, useCallback, useRef } from 'react';
import { API, uploadImage } from '@/lib/api';
import { useApp } from './AppProvider';
import ReplyList from './ReplyList';
import Sidebar from './Sidebar';
import { Icon } from './Icons';
import ImageViewer from './ImageViewer';
import { renderMarkdown } from '@/lib/markdown';
import { useToast } from './Toast';
function avatar(username) {
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
'&background=6366f1&color=fff&size=64';
}
export default function PostDetail({ postId }) {
export default function PostDetail({ postId, initialPost = null }) {
const { currentUser, navigate, openUser, refreshKey } = useApp();
const [post, setPost] = useState(null);
const { toast, confirmAction } = useToast();
const [post, setPost] = useState(initialPost);
const [error, setError] = useState(null);
const [viewerSrc, setViewerSrc] = useState(null);
const [editing, setEditing] = useState(false);
@@ -46,7 +49,7 @@ export default function PostDetail({ postId }) {
);
}
if (!post) {
return <div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>加载中...</div>;
return <div id="pagePost" className="page-slide active" style={{ textAlign: 'center', color: '#94a3b8' }}><span className="spinner-sm" />加载中...</div>;
}
const time = post.created_at ? new Date(post.created_at).toLocaleString('zh-CN') : '';
@@ -55,23 +58,23 @@ export default function PostDetail({ postId }) {
const canEdit = currentUser && currentUser.id === post.user_id;
const handleDelete = async () => {
if (!confirm('确定要删除这条帖子吗?')) return;
if (!await confirmAction('确定要删除这条帖子吗?')) return;
try {
await API.deletePost(postId);
alert('删除成功');
toast('删除成功', 'success');
navigate('feed');
} catch (err) {
alert('删除失败:' + err.message);
toast('删除失败:' + err.message, 'error');
}
};
const handleTogglePin = async () => {
if (!confirm('确定要' + (post.is_pinned ? '取消' : '') + '置顶吗?')) return;
if (!await confirmAction('确定要' + (post.is_pinned ? '取消' : '') + '置顶吗?', { danger: false })) return;
try {
await API.togglePinPost(postId);
load();
} catch (err) {
alert('操作失败:' + err.message);
toast('操作失败:' + err.message, 'error');
}
};
@@ -83,27 +86,27 @@ export default function PostDetail({ postId }) {
};
const handleSaveEdit = async () => {
if (!editContent.trim()) { alert('请填写内容'); return; }
if (!editContent.trim()) { toast('请填写内容', 'warning'); return; }
try {
await API.updatePost(postId, editTitle.trim() || '无标题', editContent.trim(), editImages);
setEditing(false);
load();
} catch (err) {
alert('编辑失败:' + err.message);
toast('编辑失败:' + err.message, 'error');
}
};
// 编辑时上传新图片
const handleEditUpload = async (file) => {
if (!file) return;
if (!file.type.startsWith('image/')) { alert('请选择图片文件'); return; }
if (file.size > 5 * 1024 * 1024) { alert('图片不能超过 5MB'); return; }
if (!file.type.startsWith('image/')) { toast('请选择图片文件', 'warning'); return; }
if (file.size > 5 * 1024 * 1024) { toast('图片不能超过 5MB', 'warning'); return; }
setEditUploading(true);
try {
const url = await uploadImage(file);
setEditImages((prev) => [...prev, url]);
} catch (err) {
alert('上传失败:' + err.message);
toast('上传失败:' + err.message, 'error');
} finally {
setEditUploading(false);
}
@@ -116,68 +119,74 @@ export default function PostDetail({ postId }) {
return (
<div id="pagePost" className="page-slide active">
<div className="page-header" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
<div className="page-header post-page-header">
<button className="back-btn" onClick={() => navigate('feed')}>
<Icon name="back" size={16} /> 返回
</button>
<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={post.avatar_url || avatar(post.username)} className="post-avatar" alt="" />
<span
className="post-username"
style={{ cursor: 'pointer', color: 'var(--primary)' }}
onClick={() => openUser(post.username)}
>
{post.username || '匿名用户'}
</span>
<span className="post-time">{time}</span>
{post.edited_at && (
<span style={{ fontSize: 12, color: 'var(--text-light)', marginLeft: 8 }}>
(已编辑 {new Date(post.edited_at).toLocaleString('zh-CN')})
<div className="post-page-layout">
<Sidebar id="postSidebar" />
<div id="postDetailContent" className="post-page-main">
<div className="post-detail-card">
<div className="post-header">
<img src={post.avatar_url || avatar(post.username)} className="post-avatar" alt="" />
<span
className="post-username"
style={{ cursor: 'pointer', color: 'var(--primary)' }}
onClick={() => openUser(post.username)}
>
{post.username || '匿名用户'}
</span>
)}
{post.is_pinned && (
<span style={{ fontSize: 12, color: 'var(--primary)', marginLeft: 8 }}>📌 置顶</span>
)}
<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>
<span className="post-time">{time}</span>
{post.edited_at && (
<span style={{ fontSize: 12, color: 'var(--text-light)', marginLeft: 8 }}>
(已编辑 {new Date(post.edited_at).toLocaleString('zh-CN')})
</span>
)}
{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>
{post.is_pinned && (
<span style={{ fontSize: 12, color: 'var(--primary)', marginLeft: 8, display: 'inline-flex', alignItems: 'center', gap: 3 }}><Icon name="pin" size={12} /> 置顶</span>
)}
<div style={{ display: 'flex', gap: 4, marginLeft: 'auto' }}>
{currentUser && currentUser.role === 'admin' && (
<button className="btn-sm btn-secondary" style={{ padding: '4px 10px' }} onClick={handleTogglePin}>
<Icon name="pin" size={12} /> {post.is_pinned ? '取消置顶' : '置顶'}
</button>
)}
{canEdit && (
<button className="btn-sm btn-secondary" style={{ padding: '4px 10px' }} onClick={handleEdit}>
<Icon name="edit" size={12} /> 编辑
</button>
)}
{canDelete && (
<button className="btn-sm btn-danger" style={{ padding: '4px 10px' }} onClick={handleDelete}>
<Icon name="trash" size={14} /> 删除
</button>
)}
</div>
</div>
<div className="post-content" style={{ fontSize: 16, lineHeight: 1.8 }} dangerouslySetInnerHTML={{ __html: renderMarkdown(post.content) }} />
{post.images && post.images.length > 0 && (
<div className="post-images">
{post.images.map((img, i) => (
<img key={i} src={img} className="post-image" alt="" style={{ cursor: 'pointer' }} onClick={() => setViewerSrc(img)} />
))}
</div>
)}
{post.signature && (
<div style={{ marginTop: 16, paddingTop: 12, borderTop: '1px solid var(--border-light)', fontSize: 12, color: 'var(--text-secondary)' }} dangerouslySetInnerHTML={{ __html: renderMarkdown(post.signature) }} />
)}
</div>
<div className="post-content" style={{ fontSize: 16, lineHeight: 1.8 }} dangerouslySetInnerHTML={{ __html: renderMarkdown(post.content) }} />
{post.images && post.images.length > 0 && (
<div className="post-images">
{post.images.map((img, i) => (
<img key={i} src={img} className="post-image" alt="" style={{ cursor: 'pointer' }} onClick={() => setViewerSrc(img)} />
))}
</div>
)}
{post.signature && (
<div style={{ marginTop: 16, paddingTop: 12, borderTop: '1px solid var(--border-light)', fontSize: 12, color: 'var(--text-secondary)' }} dangerouslySetInnerHTML={{ __html: renderMarkdown(post.signature) }} />
)}
<ReplyList postId={postId} onRefresh={load} />
</div>
<ReplyList postId={postId} onRefresh={load} />
</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>
<span className="close" style={{ position: 'absolute', top: 12, right: 16, cursor: 'pointer', color: 'var(--text-light)' }} onClick={() => setEditing(false)}><Icon name="close" size={20} /></span>
<h2 style={{ marginBottom: 16 }}><Icon name="edit" size={20} /> 编辑帖子</h2>
<input
type="text"
placeholder="标题"
@@ -202,15 +211,15 @@ export default function PostDetail({ postId }) {
type="button"
title="删除图片"
onClick={() => handleEditRemoveImage(img)}
style={{ position: 'absolute', top: -6, right: -6, width: 20, height: 20, borderRadius: '50%', background: '#ef4444', color: '#fff', border: 'none', cursor: 'pointer', fontSize: 12, lineHeight: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
>&times;</button>
style={{ position: 'absolute', top: -6, right: -6, width: 20, height: 20, borderRadius: '50%', background: '#ef4444', color: '#fff', border: 'none', cursor: 'pointer', lineHeight: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
><Icon name="close" size={12} /></button>
</div>
))}
</div>
)}
<div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
<button type="button" className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={() => editImageInputRef.current?.click()}>
{editUploading ? '上传中...' : '📷 上传图片'}
{editUploading ? '上传中...' : <><Icon name="camera" size={14} /> 上传图片</>}
</button>
<input type="file" ref={editImageInputRef} accept="image/*" multiple style={{ display: 'none' }} onChange={(e) => { const files = e.target.files; if (files && files.length > 0) { [...files].forEach((f) => handleEditUpload(f)); e.target.value = ''; } }} />
</div>
+22 -10
View File
@@ -4,11 +4,23 @@
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { Icon } from './Icons';
import { useToast } from './Toast';
export default function RecoveryCodes() {
const { t } = useTranslation();
const { toast, confirmAction } = useToast();
const [count, setCount] = useState(0);
const [modal, setModal] = useState(null); // null | {codes, isNew}
const [modalClosing, setModalClosing] = useState(false);
const closeModal = () => {
setModalClosing(true);
setTimeout(() => {
setModal(null);
setModalClosing(false);
}, 340);
};
const loadCount = () => {
API.getRecoveryCodeCount().then((d) => setCount(d.count || 0)).catch(() => {});
@@ -16,13 +28,13 @@ export default function RecoveryCodes() {
useEffect(loadCount, []);
const regenerate = async () => {
if (!confirm(t('recovery.confirmRegenerate'))) return;
if (!await confirmAction(t('recovery.confirmRegenerate'))) return;
try {
const d = await API.generateRecoveryCodes();
setModal({ codes: d.codes || [], isNew: true });
loadCount();
} catch (err) {
alert(t('recovery.genFailed', { msg: err.message }));
toast(t('recovery.genFailed', { msg: err.message }), 'error');
}
};
@@ -33,32 +45,32 @@ export default function RecoveryCodes() {
setModal({ codes: d.codes || [], isNew: false });
loadCount();
} catch (err) {
alert(t('recovery.fetchFailed', { msg: err.message }));
toast(t('recovery.fetchFailed', { msg: err.message }), 'error');
}
};
return (
<div style={{ marginTop: 16, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20 }}>
<h3 style={{ fontSize: 16, marginBottom: 8 }}>🔑 {t('recovery.title')}</h3>
<h3 style={{ fontSize: 16, marginBottom: 8 }}><Icon name="key" size={16} /> {t('recovery.title')}</h3>
<p style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 12 }}>{t('recovery.desc')}</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}>📋 {t('recovery.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}>🔄 {t('recovery.regenerate')}</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={view}><Icon name="list" size={14} /> {t('recovery.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}><Icon name="refresh" size={14} /> {t('recovery.regenerate')}</button>
</div>
<div id="recoveryCodesStatus" style={{ fontSize: 13, color: 'var(--text-light)', marginTop: 8 }}>{t('recovery.remaining', { count })}</div>
{modal && (
<div className="modal active" style={{ display: 'flex' }} onClick={(e) => { if (e.target === e.currentTarget) setModal(null); }}>
<div className={'modal active' + (modalClosing ? ' closing' : '')} style={{ display: 'flex' }} onClick={(e) => { if (e.target === e.currentTarget) closeModal(); }}>
<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>
<span className="close" style={{ position: 'absolute', top: 12, right: 16, cursor: 'pointer', color: 'var(--text-light)' }} onClick={closeModal}><Icon name="close" size={20} /></span>
<h2 style={{ marginBottom: 12 }}>{modal.isNew ? t('recovery.newCodes') : t('recovery.title')}</h2>
<p style={{ fontSize: 13, color: '#ef4444', marginBottom: 12 }}>{t('recovery.saveWarning')}</p>
<p style={{ fontSize: 13, color: '#ef4444', marginBottom: 12, display: 'flex', alignItems: 'flex-start', gap: 6 }}><Icon name="warning" size={14} /> {t('recovery.saveWarning')}</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)}>{t('recovery.saved')}</button>
<button className="btn-primary" style={{ width: '100%', padding: 10, marginTop: 16 }} onClick={closeModal}>{t('recovery.saved')}</button>
</div>
</div>
)}
+9 -7
View File
@@ -7,6 +7,7 @@ import { useApp } from './AppProvider';
import { Icon } from './Icons';
import { renderMarkdown } from '@/lib/markdown';
import CaptchaImage from './CaptchaImage';
import { useToast } from './Toast';
function avatar(username) {
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
@@ -15,6 +16,7 @@ function avatar(username) {
export default function ReplyList({ postId, onRefresh }) {
const { currentUser, openUser } = useApp();
const { toast, confirmAction } = useToast();
const [replies, setReplies] = useState([]);
const [content, setContent] = useState('');
const [captcha, setCaptcha] = useState(null);
@@ -31,10 +33,10 @@ export default function ReplyList({ postId, onRefresh }) {
useEffect(() => { setCaptcha(generateCaptcha()); }, [postId]);
const handleSubmit = async () => {
if (!currentUser) { alert('请先登录'); return; }
if (!content.trim()) { alert('请填写回复内容'); return; }
if (!currentUser) { toast('请先登录', 'warning'); return; }
if (!content.trim()) { toast('请填写回复内容', 'warning'); return; }
if (!captcha || parseInt(captchaInput) !== captcha.answer) {
alert('验证码错误,请重新计算');
toast('验证码错误,请重新计算', 'warning');
setCaptcha(generateCaptcha());
setCaptchaInput('');
return;
@@ -48,17 +50,17 @@ export default function ReplyList({ postId, onRefresh }) {
load();
onRefresh();
} catch (err) {
alert('回复失败:' + err.message);
toast('回复失败:' + err.message, 'error');
}
};
const handleDelete = async (replyId) => {
if (!confirm('确定要删除这条回复吗?')) return;
if (!await confirmAction('确定要删除这条回复吗?')) return;
try {
await API.deleteReply(replyId);
load();
} catch (err) {
alert('删除失败:' + err.message);
toast('删除失败:' + err.message, 'error');
}
};
@@ -69,7 +71,7 @@ export default function ReplyList({ postId, onRefresh }) {
</div>
<div style={{ marginTop: 12 }}>
{replies.length === 0 ? (
<div style={{ color: '#94a3b8', padding: '20px 0', textAlign: 'center' }}>还没有回复,快来抢沙发吧 🛋️</div>
<div style={{ color: '#94a3b8', padding: '20px 0', textAlign: 'center' }}><Icon name="message" size={16} /> 还没有回复,快来发表第一条回复吧</div>
) : (
replies.map((r) => {
const rTime = r.created_at ? new Date(r.created_at).toLocaleString('zh-CN') : '';
+2 -2
View File
@@ -47,10 +47,10 @@ export default function SettingsPage() {
return (
<div className="page-slide active">
<div className="page-header" style={{ maxWidth: 1200, margin: '0 auto', width: '100%' }}>
<div className="page-header" style={{ width: '100%' }}>
<h2><Icon name="settings" size={20} /> {t('settings.title')}</h2>
</div>
<div className="settings-layout" style={{ maxWidth: 1200, margin: '0 auto', width: '100%', display: 'flex', gap: 28, alignItems: 'flex-start' }}>
<div className="settings-layout" style={{ width: '100%', display: 'flex', gap: 28, alignItems: 'flex-start' }}>
<aside className="settings-sidebar" style={{ width: 200, flexShrink: 0 }}>
<nav className="settings-nav">
{NAV.map((n) => (
+26 -21
View File
@@ -6,10 +6,13 @@ import { useTranslation } from 'react-i18next';
import { API, uploadImage } from '@/lib/api';
import { useApp } from './AppProvider';
import { setAppLanguage } from '@/lib/i18n';
import { Icon } from './Icons';
import { useToast } from './Toast';
export default function SettingsProfile() {
const { currentUser, setCurrentUser } = useApp();
const { t, i18n } = useTranslation();
const { toast } = useToast();
const [username, setUsername] = useState(currentUser?.username || '');
const [bio, setBio] = useState(currentUser?.bio || '');
const [signature, setSignature] = useState(currentUser?.signature || '');
@@ -19,29 +22,29 @@ export default function SettingsProfile() {
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; }
if (!file.type.startsWith('image/')) { setAvatarStatus({ ok: false, msg: t('settings.avatarFileRequired') }); return; }
if (file.size > 5 * 1024 * 1024) { setAvatarStatus({ ok: false, msg: t('settings.avatarTooLarge') }); return; }
try {
const url = await uploadImage(file);
await API.updateAvatar(currentUser.id, url);
setAvatarUrl(url);
setCurrentUser({ ...currentUser, avatar_url: url });
setAvatarStatus({ ok: true, msg: '✅ 头像已更新' });
setAvatarStatus({ ok: true, msg: t('settings.avatarUpdated') });
} catch (err) {
setAvatarStatus({ ok: false, msg: '❌ ' + err.message });
setAvatarStatus({ ok: false, msg: err.message });
}
};
const handleSave = async () => {
if (!currentUser) { alert('请先登录'); return; }
if (!username.trim()) { alert('用户名不能为空'); return; }
if (!currentUser) { toast(t('settings.pleaseLogin'), 'warning'); return; }
if (!username.trim()) { toast(t('settings.usernameRequired'), 'warning'); return; }
try {
const data = await API.updateProfile(currentUser.id, username.trim(), bio.trim(), signature.trim());
if (data.error) throw new Error(data.error);
setCurrentUser({ ...currentUser, username: username.trim(), bio: bio.trim(), signature: signature.trim() });
alert('保存成功!');
toast(t('settings.saved'), 'success');
} catch (err) {
alert('保存失败:' + err.message);
toast(t('settings.saveFailed', { msg: err.message }), 'error');
}
};
@@ -57,49 +60,51 @@ export default function SettingsProfile() {
<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()}
aria-label={t('settings.changeAvatar')}
title={t('settings.changeAvatar')}
>
📷
<Icon name="camera" size={16} />
</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>
<p style={{ color: 'var(--text-secondary)', fontSize: 14 }}>{bio || t('user.bioEmpty')}</p>
{avatarStatus && (
<div style={{ fontSize: 13, marginTop: 8, color: avatarStatus.ok ? '#22c55e' : '#ef4444' }}>{avatarStatus.msg}</div>
<div style={{ fontSize: 13, marginTop: 8, color: avatarStatus.ok ? '#22c55e' : '#ef4444', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5 }}><Icon name={avatarStatus.ok ? 'success' : 'error'} size={14} /> {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>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('settings.username')}</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>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('settings.bio')}</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>
<div style={{ marginBottom: 16 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>个性签名 <span style={{ color: 'var(--text-light)', fontWeight: 400 }}>(显示在每篇帖子底部,支持 Markdown)</span></label>
<textarea rows={2} value={signature} placeholder="签名..." style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)', resize: 'vertical', fontFamily: 'inherit' }} onChange={(e) => setSignature(e.target.value)} />
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('settings.signature')} <span style={{ color: 'var(--text-light)', fontWeight: 400 }}>({t('settings.signatureHint')})</span></label>
<textarea rows={2} value={signature} placeholder={t('settings.signaturePlaceholder')} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)', resize: 'vertical', fontFamily: 'inherit' }} onChange={(e) => setSignature(e.target.value)} />
</div>
<button className="btn-primary" style={{ width: '100%', padding: 10 }} onClick={handleSave}>保存设置</button>
<button className="btn-primary" style={{ width: '100%', padding: 10 }} onClick={handleSave}>{t('settings.save')}</button>
</div>
{/* 语言设置 */}
<div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20, marginTop: 16 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 8 }}>{t('settings.language')}</label>
<div style={{ display: 'flex', gap: 10 }}>
<div className="feed-header-left language-toggle" style={{ display: 'inline-flex' }}>
<button
className={'btn' + (i18n.language === 'zh' ? ' btn-primary' : '')}
style={{ padding: '8px 20px', borderRadius: 6, cursor: 'pointer', border: '1px solid var(--border)', background: i18n.language === 'zh' ? 'var(--primary)' : 'transparent', color: i18n.language === 'zh' ? '#fff' : 'var(--text)' }}
className={'tab' + (i18n.language.startsWith('zh') ? ' active' : '')}
aria-pressed={i18n.language.startsWith('zh')}
onClick={() => setAppLanguage('zh')}
>
{t('settings.languageZh')}
</button>
<button
className={'btn' + (i18n.language === 'en' ? ' btn-primary' : '')}
style={{ padding: '8px 20px', borderRadius: 6, cursor: 'pointer', border: '1px solid var(--border)', background: i18n.language === 'en' ? 'var(--primary)' : 'transparent', color: i18n.language === 'en' ? '#fff' : 'var(--text)' }}
className={'tab' + (i18n.language.startsWith('en') ? ' active' : '')}
aria-pressed={i18n.language.startsWith('en')}
onClick={() => setAppLanguage('en')}
>
{t('settings.languageEn')}
+21 -7
View File
@@ -5,17 +5,31 @@ import { useEffect, useState } from 'react';
import { API } from '@/lib/api';
import { Icon } from './Icons';
export default function Sidebar() {
const [stats, setStats] = useState({ posts: 0, users: 0, topics: 0, online: 0 });
const [links, setLinks] = useState([]);
const emptyStats = { posts: 0, users: 0, topics: 0, online: 0 };
let cachedStats = null;
let cachedLinks = null;
export default function Sidebar({ id = 'sidebar' }) {
const [stats, setStats] = useState(() => cachedStats || emptyStats);
const [links, setLinks] = useState(() => cachedLinks || []);
useEffect(() => {
API.getStats().then(setStats).catch(() => {});
API.getLinks().then(setLinks).catch(() => {});
if (!cachedStats) {
API.getStats().then((nextStats) => {
cachedStats = nextStats;
setStats(nextStats);
}).catch(() => {});
}
if (!cachedLinks) {
API.getLinks().then((nextLinks) => {
cachedLinks = nextLinks;
setLinks(nextLinks);
}).catch(() => {});
}
}, []);
return (
<aside id="sidebar">
<aside id={id} className="sidebar">
<div className="stats-box">
<h4>
<Icon name="book" size={14} /> 社区统计
@@ -29,7 +43,7 @@ export default function Sidebar() {
<h4>
<Icon name="link" size={14} /> 友情链接
</h4>
<ul id="friendlyLinks">
<ul id={id === 'sidebar' ? 'friendlyLinks' : undefined} className="friendly-links">
{links.length === 0 ? (
<li style={{ color: '#94a3b8', fontSize: 13 }}>暂无链接</li>
) : (
+67 -14
View File
@@ -4,7 +4,8 @@
// 用法:const { toast } = useToast(); toast('发布成功', 'success');
// 注意:不用 createPortal(SSR 时 document 不存在会造成 hydration mismatch,
// 导致整树重建)。toast-container 是 position:fixed,渲染位置不影响视觉。
import { createContext, useContext, useState, useCallback, useRef } from 'react';
import { createContext, useContext, useState, useCallback, useRef, useEffect } from 'react';
import { Icon } from './Icons';
const ToastContext = createContext(null);
@@ -16,33 +17,85 @@ let idCounter = 0;
export function ToastProvider({ children }) {
const [toasts, setToasts] = useState([]);
const [dialog, setDialog] = useState(null);
const timersRef = useRef({});
const dialogTimerRef = useRef(null);
const dialogResolverRef = useRef(null);
const toast = useCallback((message, type = 'success', duration = 3000) => {
const id = ++idCounter;
setToasts((prev) => [...prev, { id, message, type }]);
if (timersRef.current[id]) clearTimeout(timersRef.current[id]);
timersRef.current[id] = setTimeout(() => {
setToasts((prev) => prev.filter((t) => t.id !== id));
delete timersRef.current[id];
}, duration);
const removeToast = useCallback((id) => {
setToasts((prev) => prev.filter((item) => item.id !== id));
delete timersRef.current[id];
}, []);
const dismiss = useCallback((id) => {
setToasts((prev) => prev.filter((t) => t.id !== id));
if (timersRef.current[id]) { clearTimeout(timersRef.current[id]); delete timersRef.current[id]; }
if (timersRef.current[id]) clearTimeout(timersRef.current[id]);
setToasts((prev) => prev.map((item) => item.id === id ? { ...item, closing: true } : item));
timersRef.current[id] = setTimeout(() => removeToast(id), 220);
}, [removeToast]);
const toast = useCallback((message, type = 'success', duration = 3000) => {
const id = ++idCounter;
setToasts((prev) => [...prev, { id, message, type, closing: false }]);
if (timersRef.current[id]) clearTimeout(timersRef.current[id]);
timersRef.current[id] = setTimeout(() => dismiss(id), duration);
}, [dismiss]);
const confirmAction = useCallback((message, options = {}) => {
if (dialogResolverRef.current) dialogResolverRef.current(false);
const isEnglish = localStorage.getItem('forumlify-lang') === 'en';
setDialog({
message,
title: options.title || (isEnglish ? 'Confirm action' : '确认操作'),
confirmLabel: options.confirmLabel || (isEnglish ? 'Confirm' : '确定'),
cancelLabel: options.cancelLabel || (isEnglish ? 'Cancel' : '取消'),
danger: options.danger !== false,
closing: false,
});
return new Promise((resolve) => {
dialogResolverRef.current = resolve;
});
}, []);
const closeDialog = useCallback((result) => {
setDialog((current) => current ? { ...current, closing: true } : current);
if (dialogTimerRef.current) clearTimeout(dialogTimerRef.current);
dialogTimerRef.current = setTimeout(() => {
setDialog(null);
const resolve = dialogResolverRef.current;
dialogResolverRef.current = null;
if (resolve) resolve(result);
}, 340);
}, []);
useEffect(() => () => {
Object.values(timersRef.current).forEach(clearTimeout);
if (dialogTimerRef.current) clearTimeout(dialogTimerRef.current);
if (dialogResolverRef.current) dialogResolverRef.current(false);
}, []);
return (
<ToastContext.Provider value={{ toast }}>
<ToastContext.Provider value={{ toast, confirmAction }}>
{children}
<div className="toast-container">
{toasts.map((t) => (
<div key={t.id} className={'toast toast-' + t.type} onClick={() => dismiss(t.id)}>
{t.message}
<div key={t.id} className={'toast toast-' + t.type + (t.closing ? ' closing' : '')} onClick={() => dismiss(t.id)} role="status">
<Icon name={t.type === 'error' ? 'error' : t.type === 'warning' ? 'warning' : 'success'} size={16} />
<span>{t.message}</span>
</div>
))}
</div>
{dialog && (
<div className={'modal active feedback-confirm' + (dialog.closing ? ' closing' : '')} onClick={(e) => { if (e.target === e.currentTarget) closeDialog(false); }}>
<div className="modal-content" role="alertdialog" aria-modal="true" aria-labelledby="feedbackConfirmTitle" aria-describedby="feedbackConfirmMessage">
<h2 id="feedbackConfirmTitle"><Icon name="warning" size={20} /> {dialog.title}</h2>
<p id="feedbackConfirmMessage">{dialog.message}</p>
<div className="feedback-confirm-actions">
<button className={dialog.danger ? 'btn-danger' : 'btn-primary'} onClick={() => closeDialog(true)}>{dialog.confirmLabel}</button>
<button className="btn-secondary" onClick={() => closeDialog(false)}>{dialog.cancelLabel}</button>
</div>
</div>
</div>
)}
</ToastContext.Provider>
);
}
+5 -5
View File
@@ -68,19 +68,19 @@ export default function UserProfile({ username }) {
</button>
)}
<div style={{ display: 'flex', justifyContent: 'center', gap: 32, marginTop: 16, fontSize: 14, color: 'var(--text-secondary)', flexWrap: 'wrap' }}>
<span>📅 加入于 {user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
<span>📝 发了 {posts.length} 个帖子</span>
{user.role === 'admin' && <span style={{ color: 'var(--primary)', fontWeight: 600 }}>🛡️ 管理员</span>}
<span><Icon name="calendar" size={14} /> 加入于 {user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
<span><Icon name="file" size={14} /> 发了 {posts.length} 个帖子</span>
{user.role === 'admin' && <span style={{ color: 'var(--primary)', fontWeight: 600 }}><Icon name="shield" size={14} /> 管理员</span>}
</div>
</div>
<h3 style={{ margin: '24px 0 16px', fontSize: 18 }}>📝 发布的帖子</h3>
<h3 style={{ margin: '24px 0 16px', fontSize: 18 }}><Icon name="file" size={18} /> 发布的帖子</h3>
{posts.length === 0 ? (
<div style={{ color: '#94a3b8', padding: '20px 0', textAlign: 'center' }}>还没有发帖</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 key={p.id} className="post-card" style={{ cursor: 'pointer' }} onClick={(e) => openPost(p.id, e.currentTarget, p)}>
<div className="post-title" style={{ fontSize: 16, fontWeight: 600 }}>{p.title || '无标题'}</div>
<div className="post-content" style={{ fontSize: 14, color: 'var(--text-secondary)' }}>
{(p.content || '').substring(0, 100)}{(p.content || '').length > 100 ? '...' : ''}
+23 -18
View File
@@ -2,9 +2,14 @@
// 管理后台 - 自定义 CSS(上传 style.css 覆盖默认样式)
import { useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { Icon } from '../Icons';
import { useToast } from '../Toast';
export default function AdminCustomCss() {
const { t } = useTranslation();
const { confirmAction } = useToast();
const [status, setStatus] = useState(null);
const [dragOver, setDragOver] = useState(false);
const [pendingFile, setPendingFile] = useState(null); // 待确认的 CSS 文件
@@ -13,11 +18,11 @@ export default function AdminCustomCss() {
const handleFile = async (file) => {
if (!file) return;
if (file.name !== 'style.css') {
setStatus({ ok: false, msg: '❌ 文件名必须是 style.css' });
setStatus({ ok: false, msg: t('admin.css.filenameInvalid') });
return;
}
if (file.size > 1024 * 1024) {
setStatus({ ok: false, msg: '❌ CSS 文件不能超过 1MB' });
setStatus({ ok: false, msg: t('admin.css.sizeInvalid') });
return;
}
// 上传前警告确认(与原版一致)
@@ -27,33 +32,33 @@ export default function AdminCustomCss() {
const doUpload = async () => {
try {
await API.uploadCustomCss(pendingFile);
setStatus({ ok: true, msg: '✅ 自定义 CSS 已生效(刷新页面后应用)' });
setStatus({ ok: true, msg: t('admin.css.active') });
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 });
setStatus({ ok: false, msg: err.message });
} finally {
setPendingFile(null);
}
};
const handleDelete = async () => {
if (!confirm('确定要删除自定义 CSS 吗?')) return;
if (!await confirmAction(t('admin.css.confirmDelete'))) return;
try {
await API.deleteCustomCss();
setStatus({ ok: true, msg: '✅ 已删除自定义 CSS' });
setStatus({ ok: true, msg: t('admin.css.deleted') });
const link = document.getElementById('custom-css-link');
if (link) link.remove();
} catch (err) {
setStatus({ ok: false, msg: '❌ ' + err.message });
setStatus({ ok: false, msg: err.message });
}
};
return (
<>
<h3 style={{ marginBottom: 16 }}>🎨 自定义 CSS</h3>
<h3 style={{ marginBottom: 16 }}><Icon name="code" size={16} /> {t('admin.css.title')}</h3>
<p style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 12 }}>
上传一个 <code>style.css</code> 文件覆盖默认样式(支持 CSS 变量、暗色模式等)。
{t('admin.css.description')}
</p>
<div
style={{
@@ -67,7 +72,7 @@ export default function AdminCustomCss() {
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'}
<Icon name="upload" size={14} /> {dragOver ? t('admin.css.releaseUpload') : t('admin.css.uploadHint')}
</span>
</div>
<input
@@ -78,27 +83,27 @@ export default function AdminCustomCss() {
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={{ fontSize: 13, marginTop: 8, color: status.ok ? '#22c55e' : '#ef4444', display: 'flex', alignItems: 'center', gap: 5 }}><Icon name={status.ok ? 'success' : 'error'} size={14} /> {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>
<button className="btn-primary" style={{ padding: '8px 20px' }} onClick={() => fileInputRef.current?.click()}><Icon name="save" size={14} /> {t('admin.css.save')}</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}><Icon name="trash" size={14} /> {t('admin.css.delete')}</button>
</div>
{/* 上传前警告确认 */}
{pendingFile && (
<div className="modal active" style={{ display: 'flex' }} onClick={() => setPendingFile(null)}>
<div className="modal-content" style={{ maxWidth: 420 }} onClick={(e) => e.stopPropagation()}>
<h2 style={{ marginBottom: 12 }}>⚠️ 警告</h2>
<h2 style={{ marginBottom: 12 }}><Icon name="warning" size={20} /> {t('admin.css.warningTitle')}</h2>
<p style={{ fontSize: 14, color: 'var(--text-secondary)', marginBottom: 16 }}>
若上传的 <strong>style.css</strong> 存在问题,将导致整个论坛界面样式错乱,甚至无法正常使用。
{t('admin.css.warningBody')}
</p>
<p style={{ fontSize: 13, color: 'var(--text-light)', marginBottom: 20 }}>
请确保 CSS 文件是完整的、经过测试的版本。如出现问题,可点击「删除自定义 CSS」恢复默认样式。
{t('admin.css.warningHelp')}
</p>
<div style={{ display: 'flex', gap: 8 }}>
<button className="btn-primary" style={{ padding: '8px 24px' }} onClick={doUpload}>我了解,继续上传</button>
<button className="btn-secondary" style={{ padding: '8px 24px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={() => setPendingFile(null)}>取消</button>
<button className="btn-primary" style={{ padding: '8px 24px' }} onClick={doUpload}><Icon name="upload" size={14} /> {t('admin.css.continueUpload')}</button>
<button className="btn-secondary" style={{ padding: '8px 24px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={() => setPendingFile(null)}>{t('admin.common.cancel')}</button>
</div>
</div>
</div>
+20 -15
View File
@@ -2,10 +2,15 @@
// 管理后台 - 自定义页面管理(列表)
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import CustomPageEditor from './CustomPageEditor';
import { Icon } from '../Icons';
import { useToast } from '../Toast';
export default function AdminCustomPages() {
const { t } = useTranslation();
const { toast, confirmAction } = useToast();
const [pages, setPages] = useState(null);
const [error, setError] = useState(null);
const [editing, setEditing] = useState(null); // null | 'new' | page对象
@@ -19,38 +24,38 @@ export default function AdminCustomPages() {
useEffect(load, []);
const handleDelete = async (p) => {
if (!confirm('确定要删除这个页面吗?')) return;
if (!await confirmAction(t('admin.page.confirmDelete'))) return;
try {
await API.adminDeleteCustomPage(p.id);
load();
} catch (err) {
alert('删除失败:' + err.message);
toast(t('admin.common.deleteFailed', { msg: err.message }), 'error');
}
};
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>加载失败:{error}</div>;
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>{t('admin.common.loadFailed', { msg: 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>
<h3 style={{ margin: 0 }}><Icon name="file" size={16} /> {t('admin.page.title')}</h3>
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={() => setEditing('new')}><Icon name="plus" size={14} /> {t('admin.page.add')}</button>
</div>
<div id="customPageList">
{pages === null ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />加载中...</div>
<div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />{t('admin.common.loading')}</div>
) : pages.length === 0 ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}>暂无自定义页面</div>
<div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}>{t('admin.page.empty')}</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>
<th style={{ padding: '8px 12px' }}>{t('admin.page.name')}</th>
<th style={{ padding: '8px 12px' }}>{t('admin.page.columnTitle')}</th>
<th style={{ padding: '8px 12px' }}>{t('admin.page.url')}</th>
<th style={{ padding: '8px 12px' }}>{t('admin.common.status')}</th>
<th style={{ padding: '8px 12px', textAlign: 'center' }}>{t('admin.common.actions')}</th>
</tr>
</thead>
<tbody>
@@ -60,11 +65,11 @@ export default function AdminCustomPages() {
<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>
<span style={{ color: p.enabled ? '#22c55e' : '#ef4444', display: 'inline-flex', alignItems: 'center', gap: 4 }}><Icon name={p.enabled ? 'success' : 'error'} size={13} /> {p.enabled ? t('admin.common.enabled') : t('admin.common.disabled')}</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>
<button className="btn-sm btn-secondary" title={t('admin.page.edit')} aria-label={t('admin.page.edit')} onClick={() => setEditing(p)}><Icon name="edit" size={13} /></button>
<button className="btn-sm btn-danger" title={t('admin.page.delete')} aria-label={t('admin.page.delete')} onClick={() => handleDelete(p)}><Icon name="trash" size={13} /></button>
</td>
</tr>
))}
+11 -7
View File
@@ -5,9 +5,13 @@ import { useEffect, useState } from 'react';
import { API } from '@/lib/api';
import { useApp } from '../AppProvider';
import { Icon } from '../Icons';
import { useTranslation } from 'react-i18next';
import { useToast } from '../Toast';
export default function AdminForumSettings() {
const { updateForumName } = useApp();
const { t } = useTranslation();
const { toast } = useToast();
// 初始为空:收到服务器返回的论坛名后才显示,避免默认名一闪而过
const [name, setName] = useState('');
const [result, setResult] = useState(null); // {ok, msg}
@@ -19,30 +23,30 @@ export default function AdminForumSettings() {
}, []);
const handleSave = async () => {
if (!name.trim()) { alert('请输入论坛名称'); return; }
if (!name.trim()) { toast(t('admin.forum.nameRequired'), 'warning'); return; }
try {
await API.updateSettings(name.trim());
updateForumName(name.trim());
setResult({ ok: true, msg: '✅ 保存成功!' });
setResult({ ok: true, msg: t('admin.forum.saved') });
} catch {
setResult({ ok: false, msg: '❌ 保存失败' });
setResult({ ok: false, msg: t('admin.forum.saveFailed') });
}
};
return (
<>
<h3 style={{ marginBottom: 16 }}><Icon name="settings" size={16} /> 论坛设置</h3>
<h3 style={{ marginBottom: 16 }}><Icon name="settings" size={16} /> {t('admin.forum.title')}</h3>
<div style={{ maxWidth: 400 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 6 }}>论坛名称</label>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 6 }}>{t('admin.forum.nameLabel')}</label>
<input
type="text"
style={{ width: '100%', padding: '10px 14px', border: '1.5px solid var(--border)', borderRadius: 6, fontSize: 15, marginBottom: 12, fontFamily: 'inherit', background: 'var(--bg)', color: 'var(--text)' }}
value={name}
onChange={(e) => setName(e.target.value)}
/>
<button className="btn-primary" style={{ padding: '10px 24px' }} onClick={handleSave}>保存</button>
<button className="btn-primary" style={{ padding: '10px 24px' }} onClick={handleSave}><Icon name="save" size={14} /> {t('admin.forum.save')}</button>
{result && (
<span style={{ marginLeft: 12, fontSize: 14, color: result.ok ? '#22c55e' : '#ef4444' }}>{result.msg}</span>
<span style={{ marginLeft: 12, fontSize: 14, color: result.ok ? '#22c55e' : '#ef4444' }}><Icon name={result.ok ? 'success' : 'error'} size={14} /> {result.msg}</span>
)}
</div>
</>
+13 -9
View File
@@ -2,10 +2,14 @@
// 管理后台 - 友情链接管理
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { Icon } from '../Icons';
import { useToast } from '../Toast';
export default function AdminLinks() {
const { t } = useTranslation();
const { toast, confirmAction } = useToast();
const [links, setLinks] = useState([]);
const [title, setTitle] = useState('');
const [url, setUrl] = useState('');
@@ -14,24 +18,24 @@ export default function AdminLinks() {
useEffect(load, []);
const handleAdd = async () => {
if (!title.trim() || !url.trim()) { alert('请填写完整信息'); return; }
if (!title.trim() || !url.trim()) { toast(t('admin.link.incomplete'), 'warning'); return; }
try {
await API.addLink(title.trim(), url.trim());
setTitle('');
setUrl('');
load();
} catch (err) {
alert('添加失败:' + err.message);
toast(t('admin.link.addFailed', { msg: err.message }), 'error');
}
};
const handleDelete = async (id) => {
if (!confirm('确定删除该链接吗?')) return;
if (!await confirmAction(t('admin.link.confirmDelete'))) return;
try {
await API.deleteLink(id);
load();
} catch (err) {
alert('删除失败:' + err.message);
toast(t('admin.common.deleteFailed', { msg: err.message }), 'error');
}
};
@@ -39,26 +43,26 @@ export default function AdminLinks() {
<>
<div style={{ marginBottom: 16, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
<input
type="text" placeholder="链接名称"
type="text" placeholder={t('admin.link.namePlaceholder')}
style={{ flex: 1, minWidth: 120, padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--bg)', color: 'var(--text)' }}
value={title} onChange={(e) => setTitle(e.target.value)}
/>
<input
type="url" placeholder="链接地址"
type="url" placeholder={t('admin.link.urlPlaceholder')}
style={{ flex: 2, minWidth: 160, padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--bg)', color: 'var(--text)' }}
value={url} onChange={(e) => setUrl(e.target.value)}
/>
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={handleAdd}>添加</button>
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={handleAdd}>{t('admin.link.add')}</button>
</div>
<div id="linkList">
{links.length === 0 ? (
<div style={{ color: '#94a3b8', fontSize: 13 }}>暂无友情链接</div>
<div style={{ color: '#94a3b8', fontSize: 13 }}>{t('admin.link.empty')}</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)}>
<Icon name="trash" size={12} /> 删除
<Icon name="trash" size={12} /> {t('admin.common.delete')}
</button>
</div>
))
+10 -6
View File
@@ -2,9 +2,11 @@
// 管理后台 - 事件日志
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
export default function AdminLogs() {
const { t, i18n } = useTranslation();
const [logs, setLogs] = useState(null);
const [error, setError] = useState(null);
@@ -16,22 +18,24 @@ export default function AdminLogs() {
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 }}><span className="spinner-sm" />加载中...</div>;
if (logs.length === 0) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 40 }}>暂无日志</div>;
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>{t('admin.common.loadFailed', { msg: error })}</div>;
if (!logs) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />{t('admin.common.loading')}</div>;
if (logs.length === 0) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 40 }}>{t('admin.log.empty')}</div>;
const dateLocale = i18n.resolvedLanguage === 'en' ? 'en-US' : 'zh-CN';
return (
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
<thead>
<tr style={{ textAlign: 'left', borderBottom: '1px solid var(--border)' }}>
<th>时间</th><th>用户</th><th>操作</th>
<th>{t('admin.log.time')}</th><th>{t('admin.log.user')}</th><th>{t('admin.log.action')}</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' }}>{new Date(l.created_at).toLocaleString(dateLocale)}</td>
<td style={{ padding: '6px 0' }}>{l.username || t('admin.log.system')}</td>
<td style={{ padding: '6px 0' }}>{l.action}</td>
</tr>
))}
+29 -16
View File
@@ -2,12 +2,14 @@
// 管理后台 - 举报处理
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { Icon } from '../Icons';
const STATUS = { pending: '⏳ 待处理', approved: '✅ 已删除', rejected: '❌ 已驳回' };
import { useToast } from '../Toast';
export default function AdminReports() {
const { t } = useTranslation();
const { toast, confirmAction } = useToast();
const [reports, setReports] = useState(null);
const [error, setError] = useState(null);
@@ -21,8 +23,8 @@ export default function AdminReports() {
const handleAction = async (r, action) => {
const status = action === 'approve' ? 'approved' : 'rejected';
const note = action === 'approve' ? '已删除违规帖子' : '举报不成立';
if (action === 'approve' && !confirm('确定要删除该帖子并标记举报为已处理吗?')) return;
const note = action === 'approve' ? t('admin.report.approvedNote') : t('admin.report.rejectedNote');
if (action === 'approve' && !await confirmAction(t('admin.report.confirmApprove'))) return;
try {
await API.updateReport(r.id, status, note);
if (action === 'approve' && r.post_id) {
@@ -30,35 +32,46 @@ export default function AdminReports() {
}
load();
} catch (err) {
alert('操作失败:' + err.message);
toast(t('admin.common.operationFailed', { msg: err.message }), 'error');
}
};
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>加载失败:{error}</div>;
if (!reports) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />加载中...</div>;
if (reports.length === 0) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 40 }}>✅ 暂无举报</div>;
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>{t('admin.common.loadFailed', { msg: error })}</div>;
if (!reports) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />{t('admin.common.loading')}</div>;
if (reports.length === 0) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 40 }}><Icon name="success" size={16} /> {t('admin.report.empty')}</div>;
const statusLabels = {
pending: t('admin.report.statusPending'),
approved: t('admin.report.statusApproved'),
rejected: t('admin.report.statusRejected'),
};
const statusIcons = { pending: 'pending', approved: 'success', rejected: 'error' };
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>{t('admin.report.reportedPost', { name: r.reporter_name || t('admin.report.anonymous') })}</div>
<div style={{ fontSize: 13, color: '#64748b', margin: '4px 0' }}>{t('admin.report.reason', { reason: 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 ? '...' : ''}
{t('admin.report.post', {
title: r.post_title || t('admin.report.untitled'),
content: (r.post_content || '').substring(0, 30) + ((r.post_content || '').length > 30 ? '...' : ''),
})}
</div>
<div style={{ fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 4 }}>
{statusIcons[r.status] && <Icon name={statusIcons[r.status]} size={13} />} {t('admin.common.status')}: {statusLabels[r.status] || r.status}
</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 + ')' : ''}
{t('admin.report.handler', { name: 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')}>
<Icon name="trash" size={12} /> 删除帖子
<Icon name="trash" size={12} /> {t('admin.report.deletePost')}
</button>
<button className="btn-sm btn-secondary" onClick={() => handleAction(r, 'reject')}>
<Icon name="close" size={12} /> 驳回举报
<Icon name="close" size={12} /> {t('admin.report.reject')}
</button>
</div>
)}
+22 -16
View File
@@ -2,11 +2,15 @@
// 管理后台 - 用户管理
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { useApp } from '../AppProvider';
import { useToast } from '../Toast';
export default function AdminUsers() {
const { currentUser } = useApp();
const { t, i18n } = useTranslation();
const { toast, confirmAction } = useToast();
const [users, setUsers] = useState(null);
const [error, setError] = useState(null);
@@ -19,30 +23,32 @@ export default function AdminUsers() {
useEffect(load, []);
const handleRole = async (u, role) => {
const roleName = role === 'admin' ? '管理员' : '普通用户';
if (!confirm(`确定要将该用户设为「${roleName}」吗?`)) return;
const roleName = role === 'admin' ? t('admin.user.roleAdmin') : t('admin.user.roleUser');
if (!await confirmAction(t('admin.user.confirmRole', { role: roleName }), { danger: false })) return;
try {
await API.updateUserRole(u.id, role);
load();
} catch (err) {
alert('操作失败:' + err.message);
toast(t('admin.common.operationFailed', { msg: err.message }), 'error');
}
};
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>加载失败:{error}</div>;
if (!users) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />加载中...</div>;
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>{t('admin.common.loadFailed', { msg: error })}</div>;
if (!users) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />{t('admin.common.loading')}</div>;
const dateLocale = i18n.resolvedLanguage === 'en' ? 'en-US' : 'zh-CN';
return (
<>
<div style={{ marginBottom: 12, fontSize: 13, color: '#94a3b8' }}>共 <strong>{users.length}</strong> 位用户</div>
<div style={{ marginBottom: 12, fontSize: 13, color: '#94a3b8' }}>{t('admin.user.count', { count: users.length })}</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: '10px 12px' }}>用户</th>
<th style={{ padding: '10px 12px' }}>角色</th>
<th style={{ padding: '10px 12px' }}>注册时间</th>
<th style={{ padding: '10px 12px', textAlign: 'center' }}>操作</th>
<th style={{ padding: '10px 12px' }}>{t('admin.user.user')}</th>
<th style={{ padding: '10px 12px' }}>{t('admin.user.role')}</th>
<th style={{ padding: '10px 12px' }}>{t('admin.user.registeredAt')}</th>
<th style={{ padding: '10px 12px', textAlign: 'center' }}>{t('admin.common.actions')}</th>
</tr>
</thead>
<tbody>
@@ -59,7 +65,7 @@ export default function AdminUsers() {
alt=""
/>
<span style={{ fontWeight: 500 }}>{u.username}</span>
{isCurrent && <span style={{ fontSize: 11, color: '#94a3b8', background: '#eef2ff', padding: '1px 8px', borderRadius: 4 }}>你</span>}
{isCurrent && <span style={{ fontSize: 11, color: '#94a3b8', background: '#eef2ff', padding: '1px 8px', borderRadius: 4 }}>{t('admin.user.you')}</span>}
</div>
</td>
<td style={{ padding: '10px 12px' }}>
@@ -67,19 +73,19 @@ export default function AdminUsers() {
display: 'inline-block', padding: '2px 10px', borderRadius: 4, fontSize: 12, fontWeight: 500,
...(isAdmin ? { background: '#6366f1', color: '#fff' } : { background: 'var(--border)', color: 'var(--text-secondary)' }),
}}>
{isAdmin ? '管理员' : '普通用户'}
{isAdmin ? t('admin.user.roleAdmin') : t('admin.user.roleUser')}
</span>
</td>
<td style={{ padding: '10px 12px', color: '#94a3b8', fontSize: 13 }}>
{u.created_at ? new Date(u.created_at).toLocaleDateString('zh-CN') : '—'}
{u.created_at ? new Date(u.created_at).toLocaleDateString(dateLocale) : '—'}
</td>
<td style={{ padding: '10px 12px', textAlign: 'center' }}>
{isCurrent ? (
<span style={{ fontSize: 12, color: '#94a3b8' }}>不可操作自己</span>
<span style={{ fontSize: 12, color: '#94a3b8' }}>{t('admin.user.cannotSelf')}</span>
) : isAdmin ? (
<button className="btn-sm btn-secondary" style={{ padding: '4px 12px' }} onClick={() => handleRole(u, 'user')}>设为普通用户</button>
<button className="btn-sm btn-secondary" style={{ padding: '4px 12px' }} onClick={() => handleRole(u, 'user')}>{t('admin.user.makeUser')}</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>
<button className="btn-sm btn-primary" style={{ padding: '4px 12px', background: '#6366f1', color: '#fff', border: 'none', borderRadius: 4, cursor: 'pointer' }} onClick={() => handleRole(u, 'admin')}>{t('admin.user.makeAdmin')}</button>
)}
</td>
</tr>
+24 -19
View File
@@ -2,9 +2,14 @@
// 管理后台 - 自定义页面编辑器(modal)
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { Icon } from '../Icons';
import { useToast } from '../Toast';
export default function CustomPageEditor({ page, onClose, onSaved }) {
const { t } = useTranslation();
const { toast } = useToast();
const isEdit = !!page;
const [name, setName] = useState(page?.name || '');
const [title, setTitle] = useState(page?.title || '');
@@ -12,11 +17,11 @@ export default function CustomPageEditor({ page, onClose, onSaved }) {
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 (!name.trim()) { toast(t('admin.page.nameRequired'), 'warning'); return; }
if (!title.trim()) { toast(t('admin.page.titleRequired'), 'warning'); return; }
if (!content.trim()) { toast(t('admin.page.contentRequired'), 'warning'); return; }
if (!/^[a-zA-Z0-9\-_]+$/.test(name.trim())) {
alert('页面名称只允许字母、数字、短横线和下划线');
toast(t('admin.page.nameInvalid'), 'warning');
return;
}
try {
@@ -27,61 +32,61 @@ export default function CustomPageEditor({ page, onClose, onSaved }) {
}
onSaved();
} catch (err) {
alert('保存失败:' + err.message);
toast(t('admin.common.saveFailed', { msg: err.message }), 'error');
}
};
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>
<span className="close" style={{ position: 'absolute', top: 12, right: 16, cursor: 'pointer', color: 'var(--text-light)' }} onClick={onClose}><Icon name="close" size={20} /></span>
<h2 style={{ marginBottom: 16 }}><Icon name={isEdit ? 'edit' : 'file'} size={20} /> {isEdit ? t('admin.page.editTitle') : t('admin.page.addTitle')}</h2>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>页面名称</label>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('admin.page.nameLabel')}</label>
<input
type="text"
value={name}
readOnly={isEdit}
placeholder="about (用于 URL: ?custom=about)"
placeholder={t('admin.page.namePlaceholder')}
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 style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}><Icon name="warning" size={12} /> {t('admin.page.nameLocked')}</div>
: <div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}>{t('admin.page.nameHint')}</div>}
</div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>导航栏显示名称</label>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('admin.page.navTitleLabel')}</label>
<input
type="text"
value={title}
placeholder="关于我们"
placeholder={t('admin.page.navTitlePlaceholder')}
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>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('admin.common.status')}</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>
<option value="true">{t('admin.common.enabled')}</option>
<option value="false">{t('admin.common.disabled')}</option>
</select>
</div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>页面内容(HTML + CSS + JS)</label>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('admin.page.contentLabel')}</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 style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}>{t('admin.page.contentHelp')}</div>
</div>
<button className="btn-primary" style={{ padding: '10px 24px', width: '100%' }} onClick={handleSave}>保存</button>
<button className="btn-primary" style={{ padding: '10px 24px', width: '100%' }} onClick={handleSave}>{t('admin.common.save')}</button>
</div>
</div>
);
+4 -2
View File
@@ -7,6 +7,7 @@ import { useApp } from '../AppProvider';
import { Icon } from '../Icons';
import ConversationList from './ConversationList';
import ChatWindow from './ChatWindow';
import { useToast } from '../Toast';
// 私信按钮(含未读 badge),渲染在导航栏内
export function DMButton() {
@@ -101,15 +102,16 @@ export default function ChatManager() {
// 供其他组件调用的打开私信(通过自定义事件桥接)
export function useOpenPrivateChat() {
const { currentUser } = useApp();
const { toast } = useToast();
const open = async (otherUserId, otherUsername) => {
if (!currentUser) { alert('请先登录'); return; }
if (!currentUser) { toast('请先登录', 'warning'); return; }
try {
const result = await API.getOrCreateConversation(otherUserId);
window.dispatchEvent(new CustomEvent('forumlify-open-chat', {
detail: { conversationId: result.id, otherUserId, otherUsername },
}));
} catch (err) {
alert('打开私信失败:' + err.message);
toast('打开私信失败:' + err.message, 'error');
}
};
return open;
+6 -3
View File
@@ -4,6 +4,8 @@
import { useEffect, useState, useRef, useCallback } from 'react';
import { API } from '@/lib/api';
import { useApp } from '../AppProvider';
import { Icon } from '../Icons';
import { useToast } from '../Toast';
function avatar(username) {
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
@@ -12,6 +14,7 @@ function avatar(username) {
export default function ChatWindow({ conversationId, otherUserId, otherUsername, onClose, onRefreshList }) {
const { currentUser } = useApp();
const { toast } = useToast();
const [messages, setMessages] = useState(null);
const [content, setContent] = useState('');
const containerRef = useRef(null);
@@ -47,7 +50,7 @@ export default function ChatWindow({ conversationId, otherUserId, otherUsername,
load();
onRefreshList();
} catch (err) {
alert('发送失败:' + err.message);
toast('发送失败:' + err.message, 'error');
}
};
@@ -56,7 +59,7 @@ export default function ChatWindow({ conversationId, otherUserId, otherUsername,
<div className="modal-content" style={{ display: 'flex', flexDirection: 'column', height: '70vh', maxHeight: '70vh', padding: 0, overflow: 'hidden' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 20px', borderBottom: '1px solid var(--border)' }}>
<span id="chatTitle" style={{ fontWeight: 600, fontSize: 16 }}>{otherUsername}</span>
<span className="close" onClick={onClose} style={{ fontSize: 24, cursor: 'pointer', color: 'var(--text-light)', lineHeight: 1 }}>&times;</span>
<span className="close" onClick={onClose} style={{ cursor: 'pointer', color: 'var(--text-light)', lineHeight: 1 }}><Icon name="close" size={20} /></span>
</div>
<div id="chatMessages" ref={containerRef} style={{ flex: 1, overflowY: 'auto', padding: 16, minHeight: 0 }}>
{messages === null ? (
@@ -83,7 +86,7 @@ export default function ChatWindow({ conversationId, otherUserId, otherUsername,
{m.content}
</div>
<div style={{ fontSize: 11, color: 'var(--text-light)', marginTop: 4, textAlign: isMine ? 'right' : 'left' }}>
{time} {isMine ? (m.is_read ? '✓✓' : '✓') : ''}
{time} {isMine && <Icon name="success" size={10} aria-label={m.is_read ? '已读' : '已发送'} />}
</div>
</div>
</div>
+1 -1
View File
@@ -26,7 +26,7 @@ export default function ConversationList({ onOpenChat, onClose }) {
<div className="modal-content" style={{ display: 'flex', flexDirection: 'column', height: '70vh', maxHeight: '70vh', padding: 0, overflow: 'hidden' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 20px', borderBottom: '1px solid var(--border)' }}>
<h2 style={{ fontSize: 18, margin: 0 }}><Icon name="message" size={18} style={{ verticalAlign: -3, marginRight: 6 }} /> 私信</h2>
<span className="close" onClick={onClose} style={{ fontSize: 24, cursor: 'pointer', color: 'var(--text-light)', lineHeight: 1 }}>&times;</span>
<span className="close" onClick={onClose} style={{ cursor: 'pointer', color: 'var(--text-light)', lineHeight: 1 }}><Icon name="close" size={20} /></span>
</div>
<div id="messageListContent" style={{ flex: 1, overflowY: 'auto', padding: 0 }}>
{conversations === null ? (