feat: refine forum settings uploads and transitions

This commit is contained in:
lezi-fun committed 2026-08-14 10:16:34 +08:00
1 parent e85ced7319
commit f5d173350b
23 files changed
+985 -54

No files matched your search

+109 -10
View File
@@ -1,7 +1,7 @@
'use client';
// 管理后台:侧边栏布局(对齐上游 main 分支)
import { useState } from 'react';
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Icon } from './Icons';
import AdminReports from './admin/AdminReports';
@@ -25,6 +25,102 @@ const NAV = [
export default function AdminPage() {
const { t } = useTranslation();
const [tab, setTab] = useState('reports');
const [panelPhase, setPanelPhase] = useState('idle');
const [panelHeight, setPanelHeight] = useState(null);
const contentRef = useRef(null);
const panelRef = useRef(null);
const transitionTimer = useRef(null);
const transitionFrame = useRef(null);
const pendingTab = useRef('reports');
const switching = useRef(false);
const panelPhaseRef = useRef(panelPhase);
panelPhaseRef.current = panelPhase;
const measurePanelHeight = () => {
if (!contentRef.current || !panelRef.current) return null;
const style = getComputedStyle(panelRef.current);
return contentRef.current.scrollHeight
+ parseFloat(style.paddingTop)
+ parseFloat(style.paddingBottom)
+ parseFloat(style.borderTopWidth)
+ parseFloat(style.borderBottomWidth);
};
useEffect(() => () => {
clearTimeout(transitionTimer.current);
cancelAnimationFrame(transitionFrame.current);
}, []);
// Keep the outer frame at a concrete height. Data-heavy tabs such as reports
// first render a loader, then receive their rows asynchronously. Without
// this lock, the frame switches from auto height to the loaded height in one
// frame after the drawer has already opened.
useLayoutEffect(() => {
if (panelHeight != null) return;
const height = measurePanelHeight();
if (height != null) setPanelHeight(height);
}, [panelHeight, tab]);
useEffect(() => {
if (!contentRef.current || typeof ResizeObserver === 'undefined') return undefined;
const observer = new ResizeObserver(() => {
if (panelPhaseRef.current !== 'idle') return;
const height = measurePanelHeight();
if (height == null) return;
setPanelHeight((currentHeight) => (
currentHeight != null && Math.abs(currentHeight - height) < 1 ? currentHeight : height
));
});
observer.observe(contentRef.current);
return () => observer.disconnect();
}, [tab]);
useLayoutEffect(() => {
if (!switching.current || panelPhase !== 'hidden' || !contentRef.current || !panelRef.current) return;
const targetHeight = measurePanelHeight();
if (targetHeight == null) return;
transitionFrame.current = requestAnimationFrame(() => {
setPanelHeight(targetHeight);
setPanelPhase('opening');
transitionTimer.current = setTimeout(() => {
switching.current = false;
setPanelPhase('idle');
const settledHeight = measurePanelHeight();
if (settledHeight != null) setPanelHeight(settledHeight);
}, 360);
});
}, [panelPhase, tab]);
const changeTab = (nextTab) => {
if (nextTab === tab && panelPhase === 'idle') return;
pendingTab.current = nextTab;
if (switching.current) return;
switching.current = true;
clearTimeout(transitionTimer.current);
setPanelHeight(panelRef.current?.getBoundingClientRect().height || null);
setPanelPhase('closing');
transitionTimer.current = setTimeout(() => {
setTab(pendingTab.current);
setPanelPhase('hidden');
}, 220);
};
const renderPanel = () => {
if (tab === 'reports') return <AdminReports />;
if (tab === 'users') return <AdminUsers />;
if (tab === 'logs') return <AdminLogs />;
if (tab === 'links') return <AdminLinks />;
if (tab === 'custom') return <AdminCustomPages />;
if (tab === 'css') return <AdminCustomCss />;
return <AdminForumSettings />;
};
return (
<div className="page-slide active">
@@ -40,7 +136,7 @@ export default function AdminPage() {
href="#"
className={'admin-nav-item' + (tab === n.key ? ' active' : '')}
data-tab={n.key}
onClick={(e) => { e.preventDefault(); setTab(n.key); }}
onClick={(e) => { e.preventDefault(); changeTab(n.key); }}
>
<span className="nav-icon"><Icon name={n.icon} size={18} /></span>
{t(n.labelKey)}
@@ -48,14 +144,17 @@ export default function AdminPage() {
))}
</nav>
</aside>
<main className="admin-content" id="adminContent">
{tab === 'reports' && <AdminReports />}
{tab === 'users' && <AdminUsers />}
{tab === 'logs' && <AdminLogs />}
{tab === 'links' && <AdminLinks />}
{tab === 'custom' && <AdminCustomPages />}
{tab === 'css' && <AdminCustomCss />}
{tab === 'settings' && <AdminForumSettings />}
<main
ref={panelRef}
className="admin-content"
id="adminContent"
style={panelHeight == null ? undefined : { height: panelHeight }}
>
<div className={'admin-content-drawer ' + panelPhase}>
<div ref={contentRef} className="admin-content-drawer-inner">
{renderPanel()}
</div>
</div>
</main>
</div>
</div>
+64
View File
@@ -4,6 +4,7 @@
import { createContext, useContext, useState, useEffect, useCallback, useRef } from 'react';
import { flushSync } from 'react-dom';
import { API, getTheme, setToken, getToken } from '@/lib/api';
import { applyFavicon } from '@/lib/favicon';
const AppContext = createContext(null);
@@ -425,6 +426,7 @@ export default function AppProvider({ children, cachedName = '' }) {
localStorage.setItem('forumlify-forum-name', s.forum_name);
syncForumNameCookie(s.forum_name);
}
if (s.favicon_url) applyFavicon(s.favicon_url, s.favicon_version);
// 先标记论坛名已收到(加载页原地淡入名字),稍后切换主页
setForumNameLoaded(true);
setTimeout(() => setReady(true), 650);
@@ -496,6 +498,68 @@ export default function AppProvider({ children, cachedName = '' }) {
};
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
if (page === 'new' && view === 'feed' && document.startViewTransition && !reduceMotion) {
const root = document.documentElement;
const sourceIcon = document.querySelector('#feed .fab-btn .new-post-launch-icon');
const sourceLabel = document.querySelector('#feed .fab-btn .new-post-launch-label');
if (!sourceIcon || !sourceLabel) {
commitNavigation();
return;
}
root.classList.add('new-post-view-transition');
sourceIcon.style.viewTransitionName = 'new-post-plus';
sourceLabel.style.viewTransitionName = 'new-post-title';
const transition = document.startViewTransition(() => {
sourceIcon.style.viewTransitionName = '';
sourceLabel.style.viewTransitionName = '';
flushSync(() => commitNavigation(false));
});
transition.finished.finally(() => {
root.classList.remove('new-post-view-transition');
});
return;
}
if (page === 'feed' && view === 'new' && document.startViewTransition && !reduceMotion) {
const root = document.documentElement;
const sourceIcon = document.querySelector('#pageNew .new-post-title-icon');
const sourceLabel = document.querySelector('#pageNew .new-post-title-label');
if (!sourceIcon || !sourceLabel) {
commitNavigation();
return;
}
let targetIcon = null;
let targetLabel = null;
root.classList.add('new-post-view-transition', 'returning-new-post-home');
sourceIcon.style.viewTransitionName = 'new-post-plus';
sourceLabel.style.viewTransitionName = 'new-post-title';
const transition = document.startViewTransition(() => {
sourceIcon.style.viewTransitionName = '';
sourceLabel.style.viewTransitionName = '';
flushSync(() => commitNavigation(false));
targetIcon = document.querySelector('#feed .fab-btn .new-post-launch-icon');
targetLabel = document.querySelector('#feed .fab-btn .new-post-launch-label');
if (targetIcon) targetIcon.style.viewTransitionName = 'new-post-plus';
if (targetLabel) targetLabel.style.viewTransitionName = 'new-post-title';
});
const clearTargetNames = () => {
if (targetIcon) targetIcon.style.viewTransitionName = '';
if (targetLabel) targetLabel.style.viewTransitionName = '';
};
transition.ready.then(clearTargetNames, clearTargetNames);
transition.finished.finally(() => {
root.classList.remove('new-post-view-transition', 'returning-new-post-home');
refresh();
});
return;
}
if (page === 'settings' && view !== 'settings' && document.startViewTransition && !reduceMotion) {
const root = document.documentElement;
const visibleSource = findSettingsTransitionSource(currentUser?.username);
+2 -1
View File
@@ -147,7 +147,8 @@ export default function Feed({ onOpenModal, onReport }) {
navigate('new');
}}
>
<Icon name="plus" /> {t('feed.newPost')}
<Icon name="plus" className="new-post-launch-icon" />
<span className="new-post-launch-label">{t('feed.newPost')}</span>
</button>
</div>
<div className={'feed-posts-drawer ' + drawerPhase}>
+91 -10
View File
@@ -8,6 +8,7 @@ import { useApp } from './AppProvider';
import { Icon } from './Icons';
import { useToast } from './Toast';
import CaptchaImage from './CaptchaImage';
import { compressImage, DIRECT_IMAGE_LIMIT, MAX_IMAGE_SOURCE_SIZE } from '@/lib/compress-image';
export default function NewPost() {
const { currentUser, navigate, refresh } = useApp();
@@ -20,26 +21,101 @@ export default function NewPost() {
const [captcha, setCaptcha] = useState(null);
const [captchaInput, setCaptchaInput] = useState('');
const [uploading, setUploading] = useState(false);
const [uploadStage, setUploadStage] = useState('uploading');
const launchTitle = t('feed.newPost');
const [headingText, setHeadingText] = useState(launchTitle);
const [headingPhase, setHeadingPhase] = useState('idle');
const terminalStartedRef = useRef(false);
useEffect(() => { API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {}); }, []);
useEffect(() => {
if (!terminalStartedRef.current) setHeadingText(launchTitle);
}, [launchTitle]);
useEffect(() => {
if (headingPhase === 'idle') return undefined;
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
if (reduceMotion) {
if (headingText !== title) setHeadingText(title);
return undefined;
}
if (headingPhase === 'erasing') {
if (!headingText) {
setHeadingPhase('typing');
return undefined;
}
const timer = window.setTimeout(() => setHeadingText((text) => text.slice(0, -1)), 48);
return () => window.clearTimeout(timer);
}
if (headingText === title) return undefined;
let commonLength = 0;
while (
commonLength < headingText.length
&& commonLength < title.length
&& headingText[commonLength] === title[commonLength]
) {
commonLength += 1;
}
const needsErasing = headingText.length > commonLength;
const timer = window.setTimeout(() => {
setHeadingText((text) => (
needsErasing ? text.slice(0, -1) : title.slice(0, text.length + 1)
));
}, needsErasing ? 38 : 64);
return () => window.clearTimeout(timer);
}, [headingPhase, headingText, title]);
const handleTitleChange = (event) => {
const nextTitle = event.target.value;
setTitle(nextTitle);
if (!terminalStartedRef.current && nextTitle.length > 0) {
terminalStartedRef.current = true;
if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) {
setHeadingText(nextTitle);
setHeadingPhase('typing');
} else {
setHeadingPhase('erasing');
}
}
};
const handleFiles = async (files) => {
setUploading(true);
try {
const newPreviews = [];
for (const file of files) {
if (!file.type.startsWith('image/')) continue;
if (file.size > 5 * 1024 * 1024) {
toast('图片 ' + file.name + ' 超过 5MB,请压缩后上传', 'warning');
if (file.size > MAX_IMAGE_SOURCE_SIZE) {
toast(t('newPost.imageTooLarge'), 'warning');
continue;
}
let uploadFile = file;
if (file.size > DIRECT_IMAGE_LIMIT) {
setUploadStage('compressing');
try {
uploadFile = await compressImage(file, { maxDimension: 4096 });
} catch {
toast(t('newPost.imageCompressFailed'), 'error');
continue;
}
}
setUploadStage('uploading');
const dataUrl = await new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target.result);
reader.readAsDataURL(file);
reader.readAsDataURL(uploadFile);
});
newPreviews.push(dataUrl);
const url = await uploadImage(file);
const url = await uploadImage(uploadFile);
setImages((prev) => [...prev, url]);
}
setPreviews((prev) => [...prev, ...newPreviews]);
@@ -47,6 +123,7 @@ export default function NewPost() {
toast('上传失败:' + err.message, 'error');
} finally {
setUploading(false);
setUploadStage('uploading');
}
};
@@ -80,17 +157,21 @@ export default function NewPost() {
};
return (
<div className="page-slide active">
<div className="page-header" style={{ maxWidth: 600, margin: '0 auto', width: '100%' }}>
<h2><Icon name="plus" size={20} /> {t('newPost.title')}</h2>
<div id="pageNew" className="page-slide active">
<div className="page-header new-post-page-header" style={{ maxWidth: 600, margin: '0 auto', width: '100%' }}>
<h2 className="new-post-heading">
<Icon name="plus" size={20} className="new-post-title-icon" />
<span className="new-post-title-label">{headingText}</span>
{headingPhase !== 'idle' && <span className="new-post-terminal-cursor" aria-hidden="true" />}
</h2>
</div>
<div style={{ maxWidth: 600, margin: '0 auto', width: '100%' }}>
<div className="new-post-form-body" style={{ maxWidth: 600, margin: '0 auto', width: '100%' }}>
<input
type="text"
placeholder={t('newPost.title')}
style={{ width: '100%', padding: '10px 14px', border: '1.5px solid var(--border)', borderRadius: 6, fontSize: 15, fontWeight: 600, marginBottom: 12, fontFamily: 'inherit', background: 'var(--bg)', color: 'var(--text)' }}
value={title}
onChange={(e) => setTitle(e.target.value)}
onChange={handleTitleChange}
/>
<textarea
rows={6}
@@ -114,7 +195,7 @@ export default function NewPost() {
>
{!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.${uploadStage}`) : (dragOver ? t('newPost.drop') : t('newPost.dropHint'))}
</div>
</div>
<input
+18 -4
View File
@@ -11,6 +11,7 @@ import ImageViewer from './ImageViewer';
import { renderMarkdown } from '@/lib/markdown';
import { useToast } from './Toast';
import { useTranslation } from 'react-i18next';
import { compressImage, DIRECT_IMAGE_LIMIT, MAX_IMAGE_SOURCE_SIZE } from '@/lib/compress-image';
function avatar(username) {
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
@@ -29,6 +30,7 @@ export default function PostDetail({ postId, initialPost = null }) {
const [editContent, setEditContent] = useState('');
const [editImages, setEditImages] = useState([]);
const [editUploading, setEditUploading] = useState(false);
const [editUploadStage, setEditUploadStage] = useState('uploading');
const editImageInputRef = useRef(null);
// 评论抽屉:帖子加载完成后自动展开(动画完整播放)
const [repliesOpen, setRepliesOpen] = useState(false);
@@ -131,15 +133,27 @@ export default function PostDetail({ postId, initialPost = null }) {
const handleEditUpload = async (file) => {
if (!file) return;
if (!file.type.startsWith('image/')) { toast('请选择图片文件', 'warning'); return; }
if (file.size > 5 * 1024 * 1024) { toast('图片不能超过 5MB', 'warning'); return; }
if (file.size > MAX_IMAGE_SOURCE_SIZE) { toast(t('post.imageTooLarge'), 'warning'); return; }
setEditUploading(true);
try {
const url = await uploadImage(file);
let uploadFile = file;
if (file.size > DIRECT_IMAGE_LIMIT) {
setEditUploadStage('compressing');
uploadFile = await compressImage(file, { maxDimension: 4096 });
}
setEditUploadStage('uploading');
const url = await uploadImage(uploadFile);
setEditImages((prev) => [...prev, url]);
} catch (err) {
toast('上传失败:' + err.message, 'error');
toast(
err.message === 'compression_failed'
? t('post.imageCompressFailed')
: t('post.imageUploadFailed', { msg: err.message }),
'error'
);
} finally {
setEditUploading(false);
setEditUploadStage('uploading');
}
};
@@ -290,7 +304,7 @@ export default function PostDetail({ postId, initialPost = null }) {
)}
<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 ? '上传中...' : <><Icon name="camera" size={14} /> 上传图片</>}
{editUploading ? t(`post.image${editUploadStage === 'compressing' ? 'Compressing' : 'Uploading'}`) : <><Icon name="camera" size={14} /> {t('post.imageUpload')}</>}
</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>
+101 -3
View File
@@ -1,8 +1,10 @@
'use client';
// 管理后台 - 论坛设置
import { useEffect, useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { API } from '@/lib/api';
import { applyFavicon } from '@/lib/favicon';
import { compressFavicon, DIRECT_IMAGE_LIMIT, MAX_IMAGE_SOURCE_SIZE } from '@/lib/compress-image';
import { useApp } from '../AppProvider';
import { Icon } from '../Icons';
import { useTranslation } from 'react-i18next';
@@ -14,14 +16,70 @@ export default function AdminForumSettings() {
const { toast } = useToast();
// 初始为空:收到服务器返回的论坛名后才显示,避免默认名一闪而过
const [name, setName] = useState('');
const [faviconUrl, setFaviconUrl] = useState('');
const [faviconVersion, setFaviconVersion] = useState('');
const [versionCommit, setVersionCommit] = useState('unknown');
const [uploading, setUploading] = useState(false);
const [uploadStage, setUploadStage] = useState('uploading');
const [dragOver, setDragOver] = useState(false);
const [result, setResult] = useState(null); // {ok, msg}
const fileInputRef = useRef(null);
useEffect(() => {
API.getSettings()
.then((data) => { if (data.forum_name) setName(data.forum_name); })
.then((data) => {
if (data.forum_name) setName(data.forum_name);
if (data.favicon_url) setFaviconUrl(data.favicon_url);
if (data.favicon_version) setFaviconVersion(data.favicon_version);
if (data.version_commit) setVersionCommit(data.version_commit);
})
.catch(() => {});
}, []);
const handleFavicon = async (file) => {
if (!file || uploading) return;
if (file.size > MAX_IMAGE_SOURCE_SIZE) {
toast(t('admin.forum.faviconTooLarge'), 'warning');
return;
}
const extension = file.name.split('.').pop()?.toLowerCase();
const acceptedMime = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/x-icon', 'image/vnd.microsoft.icon'].includes(file.type);
if (!acceptedMime && extension !== 'ico') {
toast(t('admin.forum.faviconInvalid'), 'warning');
return;
}
setUploading(true);
try {
let uploadFile = file;
if (file.size > DIRECT_IMAGE_LIMIT) {
setUploadStage('compressing');
try {
uploadFile = await compressFavicon(file);
} catch {
toast(t('admin.forum.faviconCompressFailed'), 'error');
return;
}
}
setUploadStage('uploading');
const data = await API.uploadFavicon(uploadFile);
setFaviconUrl(data.favicon_url);
setFaviconVersion(data.favicon_version);
applyFavicon(data.favicon_url, data.favicon_version);
toast(t('admin.forum.faviconSaved'), 'success');
} catch (error) {
toast(t('admin.forum.faviconSaveFailed', { msg: error.message }), 'error');
} finally {
setUploading(false);
setUploadStage('uploading');
if (fileInputRef.current) fileInputRef.current.value = '';
}
};
const faviconSrc = faviconUrl
? `${faviconUrl}${faviconUrl.includes('?') ? '&' : '?'}v=${encodeURIComponent(faviconVersion)}`
: '';
const handleSave = async () => {
if (!name.trim()) { toast(t('admin.forum.nameRequired'), 'warning'); return; }
try {
@@ -36,7 +94,7 @@ export default function AdminForumSettings() {
return (
<>
<h3 style={{ marginBottom: 16 }}><Icon name="settings" size={16} /> {t('admin.forum.title')}</h3>
<div style={{ maxWidth: 400 }}>
<div className="admin-forum-settings">
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 6 }}>{t('admin.forum.nameLabel')}</label>
<input
type="text"
@@ -48,6 +106,46 @@ export default function AdminForumSettings() {
{result && (
<span style={{ marginLeft: 12, fontSize: 14, color: result.ok ? '#22c55e' : '#ef4444' }}><Icon name={result.ok ? 'success' : 'error'} size={14} /> {result.msg}</span>
)}
<div className="admin-forum-divider" />
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 6 }}>{t('admin.forum.faviconLabel')}</label>
<p className="admin-forum-hint">{t('admin.forum.faviconHint')}</p>
<div className="admin-favicon-row">
<div className="admin-favicon-preview" aria-label={t('admin.forum.faviconPreview')}>
{faviconSrc ? <img src={faviconSrc} alt="" /> : <Icon name="image" size={24} />}
</div>
<button
type="button"
className={'admin-favicon-upload' + (dragOver ? ' drag-over' : '')}
disabled={uploading}
onClick={() => fileInputRef.current?.click()}
onDragOver={(event) => { event.preventDefault(); setDragOver(true); }}
onDragLeave={() => setDragOver(false)}
onDrop={(event) => {
event.preventDefault();
setDragOver(false);
handleFavicon(event.dataTransfer.files?.[0]);
}}
>
{!uploading && !dragOver && <Icon name="image" size={32} />}
<span>{uploading ? t(`admin.forum.favicon${uploadStage === 'compressing' ? 'Compressing' : 'Uploading'}`) : (dragOver ? t('admin.forum.faviconDrop') : t('admin.forum.faviconUpload'))}</span>
</button>
<input
ref={fileInputRef}
type="file"
accept=".png,.jpg,.jpeg,.gif,.webp,.ico,image/png,image/jpeg,image/gif,image/webp,image/x-icon"
hidden
onChange={(event) => handleFavicon(event.target.files?.[0])}
/>
</div>
<div className="admin-forum-divider" />
<div className="admin-version-row">
<span className="admin-version-label"><Icon name="code" size={14} /> {t('admin.forum.versionLabel')}</span>
<span className="admin-version-value">{versionCommit}</span>
</div>
</div>
</>
);