feat: follow lite forum updates

This commit is contained in:
lezi-fun committed 2026-10-01 14:10:12 +08:00
1 parent f59739e36f
commit b42944b687
38 files changed
+1433 -71

No files matched your search

+3
View File
@@ -11,6 +11,7 @@ import AdminLinks from './admin/AdminLinks';
import AdminForumSettings from './admin/AdminForumSettings';
import AdminCustomPages from './admin/AdminCustomPages';
import AdminCustomCss from './admin/AdminCustomCss';
import AdminMailSettings from './admin/AdminMailSettings';
const NAV = [
{ key: 'reports', labelKey: 'admin.reports', icon: 'shieldAlert' },
@@ -18,6 +19,7 @@ const NAV = [
{ key: 'logs', labelKey: 'admin.logs', icon: 'file' },
{ key: 'links', labelKey: 'admin.links', icon: 'link' },
{ key: 'settings', labelKey: 'admin.forumSettings', icon: 'settings' },
{ key: 'mail', labelKey: 'admin.mail', icon: 'message' },
{ key: 'custom', labelKey: 'admin.customPages', icon: 'file' },
{ key: 'css', labelKey: 'admin.customCss', icon: 'file' },
];
@@ -123,6 +125,7 @@ export default function AdminPage() {
if (tab === 'links') return <AdminLinks />;
if (tab === 'custom') return <AdminCustomPages />;
if (tab === 'css') return <AdminCustomCss />;
if (tab === 'mail') return <AdminMailSettings />;
return <AdminForumSettings />;
};
+3 -3
View File
@@ -13,7 +13,7 @@ const POST_TRANSITION_PARTS = [
['.post-username', 'post-author'],
['.post-title', 'post-heading'],
['.post-time', 'post-time'],
['.post-content', 'post-body'],
['.post-content, .topic-preview', 'post-body'],
['.post-images', 'post-media'],
['.post-pin-state', 'post-pin-state'],
['.post-edited-label', 'post-edited-label'],
@@ -937,8 +937,8 @@ export default function AppProvider({ children, cachedName = '' }) {
return result;
}, []);
const register = useCallback(async (email, password, username, captcha) => {
const result = await API.register(email, password, username, captcha);
const register = useCallback(async (email, password, username, captcha, emailCode = '') => {
const result = await API.register(email, password, username, captcha, emailCode);
const loginResult = await API.login(email, password);
if (loginResult.user) {
setCurrentUser(loginResult.user);
+71 -5
View File
@@ -17,7 +17,7 @@ function avatar(username) {
export default function Feed({ onOpenModal, onReport }) {
const { currentUser, sort, setSort, openPost, openUser, navigate, refreshKey } = useApp();
const { t } = useTranslation();
const { t, i18n } = useTranslation();
const { toast, confirmAction } = useToast();
const [posts, setPosts] = useState(null);
const [error, setError] = useState(null);
@@ -26,24 +26,33 @@ export default function Feed({ onOpenModal, onReport }) {
const [totalPages, setTotalPages] = useState(1);
const [viewerSrc, setViewerSrc] = useState(null);
const [selectedSort, setSelectedSort] = useState(sort);
const [searchInput, setSearchInput] = useState(() => typeof window === 'undefined' ? '' : new URLSearchParams(window.location.search).get('q') || '');
const [searchQuery, setSearchQuery] = useState(() => typeof window === 'undefined' ? '' : new URLSearchParams(window.location.search).get('q') || '');
const [drawerPhase, setDrawerPhase] = useState('closed');
const postListRef = useRef(null);
const sortTimerRef = useRef(null);
const pendingSortRef = useRef(null);
const initialDrawerOpenedRef = useRef(false);
const requestRef = useRef(0);
const PAGE_SIZE = 20;
const load = useCallback(async (targetPage) => {
const requestId = ++requestRef.current;
setError(null);
try {
const result = await API.getPosts(sort, null, targetPage, PAGE_SIZE);
const result = searchQuery
? await API.searchPosts(searchQuery, targetPage, PAGE_SIZE)
: await API.getPosts(sort, null, targetPage, PAGE_SIZE);
if (requestId !== requestRef.current) return;
setPosts(result.data || []);
setTotalPages(result.pagination?.totalPages || 1);
setPage(result.pagination?.page || 1);
} catch (err) {
if (requestId !== requestRef.current) return;
setError(err.message);
setPosts([]);
} finally {
if (requestId !== requestRef.current) return;
if (pendingSortRef.current === sort) {
requestAnimationFrame(() => {
setDrawerPhase('opening');
@@ -62,10 +71,35 @@ export default function Feed({ onOpenModal, onReport }) {
});
}
}
}, [sort, refreshKey]);
}, [sort, searchQuery, refreshKey]);
useEffect(() => { load(page); }, [load]);
useEffect(() => {
const onPopState = () => {
const query = new URLSearchParams(window.location.search).get('q') || '';
setSearchInput(query);
setSearchQuery(query);
setPage(1);
};
window.addEventListener('popstate', onPopState);
return () => window.removeEventListener('popstate', onPopState);
}, []);
useEffect(() => {
const timer = setTimeout(() => {
const next = searchInput.trim();
if (next === searchQuery) return;
const url = new URL(window.location.href);
if (next) url.searchParams.set('q', next);
else url.searchParams.delete('q');
window.history.replaceState(window.history.state, '', url);
setPage(1);
setSearchQuery(next);
}, 350);
return () => clearTimeout(timer);
}, [searchInput, searchQuery]);
// 长帖内容:超过 3 行时加 .has-fade(底部渐变遮罩提示还有更多内容)
useEffect(() => {
if (!posts || posts.length === 0 || !postListRef.current) return;
@@ -85,6 +119,13 @@ export default function Feed({ onOpenModal, onReport }) {
useEffect(() => () => clearTimeout(sortTimerRef.current), []);
const handleSortChange = (nextSort) => {
if (searchInput) {
setSearchInput('');
setSearchQuery('');
const url = new URL(window.location.href);
url.searchParams.delete('q');
window.history.replaceState(window.history.state, '', url);
}
if (nextSort === selectedSort) return;
setSelectedSort(nextSort);
@@ -151,6 +192,31 @@ export default function Feed({ onOpenModal, onReport }) {
<span className="new-post-launch-label">{t('feed.newPost')}</span>
</button>
</div>
<div className="feed-search">
<Icon name="search" size={18} aria-hidden="true" />
<input
type="search"
name="forumlify-post-search"
autoComplete="off"
aria-label={t('feed.searchPlaceholder')}
placeholder={t('feed.searchPlaceholder')}
value={searchInput}
maxLength={100}
onChange={(event) => setSearchInput(event.target.value)}
onKeyDown={(event) => {
if (event.key === 'Enter') {
const next = event.currentTarget.value.trim();
const url = new URL(window.location.href);
if (next) url.searchParams.set('q', next);
else url.searchParams.delete('q');
window.history.replaceState(window.history.state, '', url);
setPage(1);
setSearchQuery(next);
}
}}
/>
{searchInput && <button type="button" aria-label={t('feed.clearSearch')} onClick={() => setSearchInput('')}><Icon name="close" size={16} /></button>}
</div>
<div className={'feed-posts-drawer ' + drawerPhase}>
<div className="feed-posts-drawer-inner">
<div id="postList" ref={postListRef}>
@@ -159,10 +225,10 @@ export default function Feed({ onOpenModal, onReport }) {
) : 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>
<div className="search-empty">{searchQuery ? t('feed.searchEmpty', { query: searchQuery }) : t('feed.empty')}</div>
) : (
posts.map((p) => {
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
const time = p.created_at ? new Date(p.created_at).toLocaleString(i18n.language === 'en' ? 'en-US' : 'zh-CN') : '';
return (
<div key={p.id} className="post-card topic-row" data-post-id={p.id} data-post-ref={p.post_number || p.id} data-username={p.username || ''} style={{ cursor: 'pointer' }}
onClick={(e) => openPost(p.post_number || p.id, e.currentTarget, p)}>
+5
View File
@@ -12,6 +12,11 @@ export function Icon({ name, size = 16, ...rest }) {
}
const PATHS = {
search: (
<>
<circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>
</>
),
message: (
<>
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
+73 -11
View File
@@ -22,6 +22,12 @@ export default function Modals({ modal, onClose, reportPostId }) {
const [resetRecoveryCode, setResetRecoveryCode] = useState('');
const [resetPassword, setResetPassword] = useState('');
const [resetPasswordConfirm, setResetPasswordConfirm] = useState('');
const [resetMethod, setResetMethod] = useState('recovery');
const [mailReady, setMailReady] = useState(false);
const [emailCodeRequired, setEmailCodeRequired] = useState(false);
const [regEmailCode, setRegEmailCode] = useState('');
const [regCodeCooldown, setRegCodeCooldown] = useState(0);
const [resetCodeCooldown, setResetCodeCooldown] = useState(0);
// 注册表单
const [regUsername, setRegUsername] = useState('');
@@ -35,6 +41,12 @@ export default function Modals({ modal, onClose, reportPostId }) {
// 打开注册弹窗时从服务器获取验证码挑战(HMAC 签名)
useEffect(() => {
if (modal === 'login' || modal === 'register') {
API.getSettings().then((settings) => {
setMailReady(!!settings.smtp_ready);
setEmailCodeRequired(!!settings.email_verify_required);
}).catch(() => { setMailReady(false); setEmailCodeRequired(false); });
}
if (modal === 'register') {
API.getCaptcha().then((c) => setRegCaptcha(c)).catch(() => {});
}
@@ -44,9 +56,19 @@ export default function Modals({ modal, onClose, reportPostId }) {
setResetRecoveryCode('');
setResetPassword('');
setResetPasswordConfirm('');
setResetMethod('recovery');
}
}, [modal]);
useEffect(() => {
if (!regCodeCooldown && !resetCodeCooldown) return;
const timer = setInterval(() => {
setRegCodeCooldown((seconds) => Math.max(0, seconds - 1));
setResetCodeCooldown((seconds) => Math.max(0, seconds - 1));
}, 1000);
return () => clearInterval(timer);
}, [regCodeCooldown > 0, resetCodeCooldown > 0]);
if (!modal) return null;
const close = (e) => {
@@ -83,7 +105,11 @@ export default function Modals({ modal, onClose, reportPostId }) {
return;
}
try {
await API.resetPassword(resetEmail.trim(), resetRecoveryCode.trim(), resetPassword);
if (resetMethod === 'email') {
await API.resetPasswordByEmail(resetEmail.trim(), resetRecoveryCode.trim(), resetPassword);
} else {
await API.resetPassword(resetEmail.trim(), resetRecoveryCode.trim(), resetPassword);
}
setAuthMode('login');
setLoginEmail(resetEmail.trim());
setLoginPassword('');
@@ -97,6 +123,23 @@ export default function Modals({ modal, onClose, reportPostId }) {
}
};
const sendCode = async (purpose) => {
const email = purpose === 'register' ? regEmail.trim() : resetEmail.trim();
if (!email) { toast(t('auth.emailRequired'), 'warning'); return; }
try {
if (purpose === 'register') {
await API.sendRegisterCode(email);
setRegCodeCooldown(60);
} else {
await API.sendResetCode(email);
setResetCodeCooldown(60);
}
toast(t('auth.emailCodeSent'), 'success');
} catch (error) {
toast(t('auth.emailCodeFailed', { msg: error.message }), 'error');
}
};
const returnToLogin = () => {
setAuthMode('login');
setResetEmail('');
@@ -108,18 +151,20 @@ export default function Modals({ modal, onClose, reportPostId }) {
const handleRegister = async () => {
if (!regUsername.trim() || !regEmail.trim() || !regPassword) { toast('请填写完整信息', 'warning'); return; }
if (regPassword.length < 6) { toast('密码至少6位', 'warning'); return; }
if (emailCodeRequired && !regEmailCode.trim()) { toast(t('auth.emailCodeRequired'), 'warning'); return; }
if (!regCaptcha || !regCaptchaInput.trim()) {
toast('请填写验证码', 'warning');
return;
}
try {
// 答案由服务端 HMAC 校验,前端不对比答案
await register(regEmail.trim(), regPassword, regUsername.trim(), { id: regCaptcha.id, answer: regCaptchaInput.trim(), sig: regCaptcha.sig });
await register(regEmail.trim(), regPassword, regUsername.trim(), { id: regCaptcha.id, answer: regCaptchaInput.trim(), sig: regCaptcha.sig }, regEmailCode.trim());
onClose();
setRegUsername('');
setRegEmail('');
setRegPassword('');
setRegCaptchaInput('');
setRegEmailCode('');
toast('注册成功!', 'success');
refresh();
} catch (err) {
@@ -148,10 +193,11 @@ export default function Modals({ modal, onClose, reportPostId }) {
<div className="modal-content">
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
<h2 style={{ marginBottom: 16 }}>{t('auth.login')}</h2>
<form onSubmit={(event) => { event.preventDefault(); handleLogin(); }}>
<input type="email" placeholder={t('auth.email')} value={loginEmail} onChange={(e) => setLoginEmail(e.target.value)} />
<input type="password" placeholder={t('auth.password')} value={loginPassword} onChange={(e) => setLoginPassword(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') handleLogin(); }} />
<button className="btn-primary" style={{ width: '100%' }} onClick={handleLogin}>{t('auth.login')}</button>
<input type="password" placeholder={t('auth.password')} value={loginPassword} onChange={(e) => setLoginPassword(e.target.value)} />
<button type="submit" className="btn-primary" style={{ width: '100%' }}>{t('auth.login')}</button>
</form>
<button
type="button"
className="auth-forgot-link"
@@ -170,19 +216,27 @@ export default function Modals({ modal, onClose, reportPostId }) {
<div className="modal active" onClick={close}>
<div className="modal-content">
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
<h2 style={{ marginBottom: 16 }}>{t('auth.resetTitle')}</h2>
<p className="auth-reset-hint">{t('auth.resetHint')}</p>
<h2 style={{ marginBottom: 16 }}>{t(resetMethod === 'email' ? 'auth.resetEmailTitle' : 'auth.resetTitle')}</h2>
{mailReady && (
<div className="auth-reset-methods">
<button type="button" className={resetMethod === 'recovery' ? 'active' : ''} onClick={() => { setResetMethod('recovery'); setResetRecoveryCode(''); }}>{t('auth.recoveryMethod')}</button>
<button type="button" className={resetMethod === 'email' ? 'active' : ''} onClick={() => { setResetMethod('email'); setResetRecoveryCode(''); }}>{t('auth.emailMethod')}</button>
</div>
)}
<p className="auth-reset-hint">{t(resetMethod === 'email' ? 'auth.resetEmailHint' : 'auth.resetHint')}</p>
<form onSubmit={(event) => { event.preventDefault(); handleResetPassword(); }}>
<input type="email" placeholder={t('auth.email')} value={resetEmail} onChange={(e) => setResetEmail(e.target.value)} />
<input type="text" placeholder={t('auth.recoveryCode')} value={resetRecoveryCode} onChange={(e) => setResetRecoveryCode(e.target.value)} />
{resetMethod === 'email' && <button type="button" className="auth-send-code" disabled={resetCodeCooldown > 0} onClick={() => sendCode('reset')}>{resetCodeCooldown || t('auth.sendCode')}</button>}
<input type="text" placeholder={t(resetMethod === 'email' ? 'auth.emailCode' : 'auth.recoveryCode')} value={resetRecoveryCode} onChange={(e) => setResetRecoveryCode(e.target.value)} />
<input type="password" placeholder={t('auth.newPassword')} value={resetPassword} onChange={(e) => setResetPassword(e.target.value)} />
<input
type="password"
placeholder={t('auth.confirmPassword')}
value={resetPasswordConfirm}
onChange={(e) => setResetPasswordConfirm(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') handleResetPassword(); }}
/>
<button className="btn-primary" style={{ width: '100%' }} onClick={handleResetPassword}>{t('auth.resetPassword')}</button>
<button type="submit" className="btn-primary" style={{ width: '100%' }}>{t('auth.resetPassword')}</button>
</form>
<button type="button" className="auth-forgot-link" onClick={returnToLogin}>
{t('auth.backToLogin')}
</button>
@@ -195,8 +249,15 @@ export default function Modals({ modal, onClose, reportPostId }) {
<div className="modal-content">
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
<h2 style={{ marginBottom: 16 }}>{t('auth.register')}</h2>
<form onSubmit={(event) => { event.preventDefault(); handleRegister(); }}>
<input type="text" placeholder={t('auth.username')} value={regUsername} onChange={(e) => setRegUsername(e.target.value)} />
<input type="email" placeholder={t('auth.email')} value={regEmail} onChange={(e) => setRegEmail(e.target.value)} />
{emailCodeRequired && (
<div className="auth-email-code-row">
<input type="text" inputMode="numeric" maxLength={6} placeholder={t('auth.emailCode')} value={regEmailCode} onChange={(e) => setRegEmailCode(e.target.value)} />
<button type="button" disabled={regCodeCooldown > 0} onClick={() => sendCode('register')}>{regCodeCooldown || t('auth.sendCode')}</button>
</div>
)}
<input type="password" placeholder={t('auth.passwordHint')} value={regPassword} onChange={(e) => setRegPassword(e.target.value)} />
<div className="captcha-row" style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '12px 0' }}>
{regCaptcha ? (
@@ -206,7 +267,8 @@ export default function Modals({ modal, onClose, reportPostId }) {
)}
<input type="text" placeholder="答案" style={{ width: 80, background: 'var(--bg)', color: 'var(--text)', border: '1px solid var(--border)', padding: '8px 12px', borderRadius: 4 }} value={regCaptchaInput} onChange={(e) => setRegCaptchaInput(e.target.value)} />
</div>
<button className="btn-primary" style={{ width: '100%' }} onClick={handleRegister}>{t('auth.register')}</button>
<button type="submit" className="btn-primary" style={{ width: '100%' }}>{t('auth.register')}</button>
</form>
</div>
</div>
)}
+42 -1
View File
@@ -8,6 +8,7 @@ import { Icon } from './Icons';
import { useOpenPrivateChat } from './chat/ChatManager';
import { renderMarkdown } from '@/lib/markdown';
import { useTranslation } from 'react-i18next';
import { useToast } from './Toast';
function avatar(username, size = 128) {
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
@@ -18,7 +19,9 @@ export default function UserProfile({ username, initialUser = null, initialPosts
const { currentUser, openPost } = useApp();
const { t, i18n } = useTranslation();
const openPrivateChat = useOpenPrivateChat();
const { toast, confirmAction } = useToast();
const [user, setUser] = useState(initialUser);
const [blockStatus, setBlockStatus] = useState(null);
const [posts, setPosts] = useState(initialPosts || []);
const [error, setError] = useState(null);
const postsRef = useRef(null);
@@ -45,6 +48,37 @@ export default function UserProfile({ username, initialUser = null, initialPosts
load();
}, [initialPosts, initialUser, load]);
useEffect(() => {
if (!currentUser || !user?.id || currentUser.id === user.id) {
setBlockStatus(null);
return;
}
let canceled = false;
API.getBlockStatus(user.id)
.then((status) => { if (!canceled) setBlockStatus(status); })
.catch(() => { if (!canceled) setBlockStatus(null); });
return () => { canceled = true; };
}, [currentUser?.id, user?.id]);
const toggleBlock = async () => {
const blocked = !!blockStatus?.blocked_by_me;
const confirmed = await confirmAction(t(blocked ? 'blocking.unblockConfirm' : 'blocking.blockConfirm', { name: user.username }), {
title: t(blocked ? 'blocking.unblock' : 'blocking.block'),
confirmLabel: t(blocked ? 'blocking.unblock' : 'blocking.block'),
danger: !blocked,
});
if (!confirmed) return;
try {
if (blocked) await API.unblockUser(user.id);
else await API.blockUser(user.id);
setBlockStatus((previous) => ({ ...previous, blocked_by_me: !blocked }));
setPosts(blocked ? (await API.getPosts('latest', user.id)).data || [] : []);
toast(t(blocked ? 'blocking.unblocked' : 'blocking.blocked'), 'success');
} catch (error) {
toast(t('blocking.failed', { msg: error.message }), 'error');
}
};
useEffect(() => {
const contents = postsRef.current?.querySelectorAll('.user-post-preview') || [];
contents.forEach((element) => {
@@ -76,14 +110,21 @@ export default function UserProfile({ username, initialUser = null, initialPosts
<div className="user-profile-details">
<p style={{ color: 'var(--text-secondary)', fontSize: 14 }}>{user.bio || '这个人很懒,什么都没写'}</p>
{currentUser && currentUser.username !== user.username && (
<div className="user-profile-actions">
{!blockStatus?.blocked_by_me && (
<button
className="btn-primary"
style={{ marginTop: 12, padding: '8px 20px' }}
onClick={() => openPrivateChat(user.id, user.username)}
>
<Icon name="message" size={14} /> 发私信
</button>
)}
<button type="button" className="btn-secondary" onClick={toggleBlock}>
<Icon name="shield" size={14} /> {t(blockStatus?.blocked_by_me ? 'blocking.unblock' : 'blocking.block')}
</button>
</div>
)}
{blockStatus?.blocked_by_me && <p className="blocked-user-hint">{t('blocking.blockedHint')}</p>}
<div style={{ display: 'flex', justifyContent: 'center', gap: 32, marginTop: 16, fontSize: 14, color: 'var(--text-secondary)', flexWrap: 'wrap' }}>
<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>
+105
View File
@@ -0,0 +1,105 @@
'use client';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '@/lib/api';
import { Icon } from '../Icons';
import { useToast } from '../Toast';
const DEFAULTS = {
enabled: false, host: '', port: 587, secure: false, user: '', password: '',
from_name: '', from_email: '', allow_self_signed: false, password_set: false,
};
export default function AdminMailSettings() {
const { t } = useTranslation();
const { toast, confirmAction } = useToast();
const [config, setConfig] = useState(DEFAULTS);
const [required, setRequired] = useState(false);
const [testTo, setTestTo] = useState('');
const [busy, setBusy] = useState(false);
const load = async () => {
try {
const [smtp, settings] = await Promise.all([API.adminGetSmtp(), API.getSettings()]);
setConfig({ ...DEFAULTS, ...smtp, password: '' });
setRequired(!!settings.email_verify_required);
} catch (error) {
toast(t('admin.mailForm.failed', { msg: error.message }), 'error');
}
};
useEffect(() => { load(); }, []);
const update = (key, value) => setConfig((current) => ({ ...current, [key]: value }));
const save = async () => {
setBusy(true);
try {
await API.adminSaveSmtp(config);
await load();
toast(t('admin.mailForm.saved'), 'success');
} catch (error) {
toast(t('admin.mailForm.failed', { msg: error.message }), 'error');
} finally { setBusy(false); }
};
const test = async () => {
setBusy(true);
try {
await API.adminTestSmtp(testTo.trim() || undefined);
toast(t('admin.mailForm.testSent'), 'success');
} catch (error) {
toast(t('admin.mailForm.failed', { msg: error.message }), 'error');
} finally { setBusy(false); }
};
const clearPassword = async () => {
if (!await confirmAction(t('admin.mailForm.clearPasswordConfirm'))) return;
setBusy(true);
try {
await API.adminClearSmtpPassword();
await load();
toast(t('admin.mailForm.passwordCleared'), 'success');
} catch (error) {
toast(t('admin.mailForm.failed', { msg: error.message }), 'error');
} finally { setBusy(false); }
};
const changeVerification = async (value) => {
setBusy(true);
try {
await API.adminSetEmailVerification(value);
setRequired(value);
toast(t('admin.mailForm.saved'), 'success');
} catch (error) {
toast(t('admin.mailForm.failed', { msg: error.message }), 'error');
} finally { setBusy(false); }
};
return (
<div className="smtp-settings">
<h3><Icon name="message" size={17} /> {t('admin.mailForm.title')}</h3>
<p className="admin-forum-hint">{t('admin.mailForm.hint')}</p>
<label className="smtp-check"><input type="checkbox" checked={config.enabled} onChange={(event) => update('enabled', event.target.checked)} /> {t('admin.mailForm.enabled')}</label>
<div className="smtp-grid">
<label>{t('admin.mailForm.host')}<input value={config.host} maxLength={255} onChange={(event) => update('host', event.target.value)} /></label>
<label>{t('admin.mailForm.port')}<input type="number" min="1" max="65535" value={config.port} onChange={(event) => update('port', event.target.value)} /></label>
<label>{t('admin.mailForm.user')}<input value={config.user} maxLength={255} autoComplete="off" onChange={(event) => update('user', event.target.value)} /></label>
<label>{t('admin.mailForm.password')}<input type="password" value={config.password} maxLength={255} autoComplete="new-password" placeholder={config.password_set ? t('admin.mailForm.passwordSaved') : ''} onChange={(event) => update('password', event.target.value)} /></label>
<label>{t('admin.mailForm.fromName')}<input value={config.from_name} maxLength={100} onChange={(event) => update('from_name', event.target.value)} /></label>
<label>{t('admin.mailForm.fromEmail')}<input type="email" value={config.from_email} maxLength={255} onChange={(event) => update('from_email', event.target.value)} /></label>
</div>
<label className="smtp-check"><input type="checkbox" checked={config.secure} onChange={(event) => update('secure', event.target.checked)} /> {t('admin.mailForm.secure')}</label>
<label className="smtp-check"><input type="checkbox" checked={config.allow_self_signed} onChange={(event) => update('allow_self_signed', event.target.checked)} /> {t('admin.mailForm.selfSigned')}</label>
<div className="smtp-actions">
<button className="btn-primary" disabled={busy} onClick={save}>{t('admin.mailForm.save')}</button>
{config.password_set && <button className="btn-secondary" disabled={busy} onClick={clearPassword}>{t('admin.mailForm.clearPassword')}</button>}
</div>
<div className="admin-forum-divider" />
<label>{t('admin.mailForm.testTo')}<input type="email" value={testTo} onChange={(event) => setTestTo(event.target.value)} placeholder={t('admin.mailForm.testToHint')} /></label>
<div className="smtp-actions"><button className="btn-secondary" disabled={busy} onClick={test}>{t('admin.mailForm.sendTest')}</button></div>
<div className="admin-forum-divider" />
<label className="smtp-check"><input type="checkbox" checked={required} disabled={busy} onChange={(event) => changeVerification(event.target.checked)} /> {t('admin.mailForm.requireVerification')}</label>
<p className="admin-forum-hint">{t('admin.mailForm.verifyHint')}</p>
</div>
);
}
+11 -4
View File
@@ -6,6 +6,7 @@ import { API } from '@/lib/api';
import { useApp } from '../AppProvider';
import { Icon } from '../Icons';
import { useToast } from '../Toast';
import { useTranslation } from 'react-i18next';
function avatar(username) {
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
@@ -15,9 +16,12 @@ function avatar(username) {
export default function ChatWindow({ conversationId, otherUserId, otherUsername, onClose, onRefreshList }) {
const { currentUser } = useApp();
const { toast } = useToast();
const { t, i18n } = useTranslation();
const [messages, setMessages] = useState(null);
const [content, setContent] = useState('');
const containerRef = useRef(null);
const waitingForReply = messages && !messages.some((message) => message.sender_id === otherUserId)
&& messages.filter((message) => message.sender_id === currentUser?.id).length >= 3;
const load = useCallback(async (silent = false) => {
if (!silent) setMessages(null);
@@ -43,14 +47,15 @@ export default function ChatWindow({ conversationId, otherUserId, otherUsername,
}, [messages]);
const send = async () => {
if (!content.trim()) return;
if (!content.trim() || waitingForReply) return;
try {
await API.sendMessage(conversationId, content.trim());
setContent('');
load();
onRefreshList();
} catch (err) {
toast('发送失败:' + err.message, 'error');
toast(err.status === 429 ? t('chat.limitReached') : err.message, 'error');
if (err.status === 429) load(true);
}
};
@@ -69,7 +74,7 @@ export default function ChatWindow({ conversationId, otherUserId, otherUsername,
) : (
messages.map((m) => {
const isMine = m.sender_id === currentUser?.id;
const time = m.created_at ? new Date(m.created_at).toLocaleString('zh-CN') : '';
const time = m.created_at ? new Date(m.created_at).toLocaleString(i18n.language === 'en' ? 'en-US' : 'zh-CN') : '';
return (
<div key={m.id} style={{ display: 'flex', justifyContent: isMine ? 'flex-end' : 'flex-start', marginBottom: 12 }}>
{!isMine && (
@@ -94,6 +99,7 @@ export default function ChatWindow({ conversationId, otherUserId, otherUsername,
})
)}
</div>
{waitingForReply && <div className="chat-limit-hint">{t('chat.limitReached')}</div>}
<div style={{ display: 'flex', gap: 8, padding: '12px 16px', borderTop: '1px solid var(--border)', flexShrink: 0 }}>
<input
type="text"
@@ -101,10 +107,11 @@ export default function ChatWindow({ conversationId, otherUserId, otherUsername,
placeholder="输入消息..."
style={{ flex: 1, padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 6, fontSize: 14, background: 'var(--bg)', color: 'var(--text)', outline: 'none' }}
value={content}
disabled={waitingForReply}
onChange={(e) => setContent(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') send(); }}
/>
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={send}>发送</button>
<button className="btn-primary" style={{ padding: '8px 16px' }} disabled={waitingForReply} onClick={send}>发送</button>
</div>
</div>
</div>
+58 -5
View File
@@ -4,6 +4,8 @@
import { useEffect, useState } from 'react';
import { API } from '@/lib/api';
import { Icon } from '../Icons';
import { useTranslation } from 'react-i18next';
import { useToast } from '../Toast';
function avatar(username) {
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
@@ -11,7 +13,12 @@ function avatar(username) {
}
export default function ConversationList({ onOpenChat, onClose }) {
const { t, i18n } = useTranslation();
const { toast } = useToast();
const [conversations, setConversations] = useState(null);
const [search, setSearch] = useState('');
const [matches, setMatches] = useState([]);
const [searching, setSearching] = useState(false);
const load = () => {
API.getConversations()
@@ -21,23 +28,67 @@ export default function ConversationList({ onOpenChat, onClose }) {
useEffect(load, []);
useEffect(() => {
const keyword = search.trim();
if (!keyword) { setMatches([]); setSearching(false); return; }
let canceled = false;
const timer = setTimeout(async () => {
setSearching(true);
try {
const result = await API.searchUsers(keyword);
if (!canceled) setMatches(result.data || []);
} catch (error) {
if (!canceled) toast(t('chat.openFailed', { msg: error.message }), 'error');
} finally {
if (!canceled) setSearching(false);
}
}, 300);
return () => { canceled = true; clearTimeout(timer); };
}, [search, t, toast]);
const startChat = async (user) => {
try {
const conversation = await API.getOrCreateConversation(user.id);
onOpenChat(conversation.id, user.id, user.username);
} catch (error) {
toast(t('chat.openFailed', { msg: error.message }), 'error');
}
};
return (
<div className="modal active" onClick={(e) => { if (e.target === e.currentTarget) 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>
<h2 style={{ fontSize: 18, margin: 0 }}><Icon name="message" size={18} style={{ verticalAlign: -3, marginRight: 6 }} /> {t('chat.title')}</h2>
<span className="close" onClick={onClose} style={{ cursor: 'pointer', color: 'var(--text-light)', lineHeight: 1 }}><Icon name="close" size={20} /></span>
</div>
<div className="chat-user-search">
<Icon name="search" size={17} aria-hidden="true" />
<input type="search" name="forumlify-user-search" autoComplete="off" maxLength={50}
aria-label={t('chat.searchPlaceholder')} placeholder={t('chat.searchPlaceholder')}
value={search} onChange={(event) => setSearch(event.target.value)} />
</div>
<div id="messageListContent" style={{ flex: 1, overflowY: 'auto', padding: 0 }}>
{search.trim() ? (
searching ? <div className="chat-search-state">{t('chat.loading')}</div>
: matches.length === 0 ? <div className="chat-search-state">{t('chat.searchEmpty')}</div>
: matches.map((user) => (
<button key={user.id} type="button" className="chat-user-result" onClick={() => startChat(user)}>
<img src={user.avatar_url || avatar(user.username)} alt="" />
<span>{user.username}</span>
</button>
))
) : (
<>
{conversations === null ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}><span className="spinner-sm" />加载中...</div>
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}><span className="spinner-sm" />{t('chat.loading')}</div>
) : conversations.length === 0 ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>暂无私信</div>
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>{t('chat.empty')}</div>
) : (
conversations.map((c) => {
const unread = c.unread_count || 0;
const lastMsg = c.last_message || '暂无消息';
const time = c.last_message_time ? new Date(c.last_message_time).toLocaleString('zh-CN') : '';
const lastMsg = c.last_message || t('chat.noMessage');
const time = c.last_message_time ? new Date(c.last_message_time).toLocaleString(i18n.language === 'en' ? 'en-US' : 'zh-CN') : '';
return (
<div
key={c.id}
@@ -62,6 +113,8 @@ export default function ConversationList({ onOpenChat, onClose }) {
);
})
)}
</>
)}
</div>
</div>
</div>