diff --git a/.github/workflows/docker-ghcr.yml b/.github/workflows/docker-ghcr.yml index f2f4e5a..e0ea4f6 100644 --- a/.github/workflows/docker-ghcr.yml +++ b/.github/workflows/docker-ghcr.yml @@ -47,6 +47,8 @@ jobs: context: . push: true platforms: linux/amd64, linux/arm64 + build-args: | + FORUMLIFY_COMMIT=${{ github.sha }} tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} cache-from: type=gha diff --git a/app/api/admin/favicon/route.js b/app/api/admin/favicon/route.js new file mode 100644 index 0000000..6e0c6ef --- /dev/null +++ b/app/api/admin/favicon/route.js @@ -0,0 +1,58 @@ +import pool from '@/lib/db'; +import { randomUUID } from 'crypto'; +import { getUser, requireAdmin } from '@/lib/auth'; +import { sniffImage } from '@/lib/image-type'; +import { deleteObject, saveObject } from '@/lib/storage'; + +export const runtime = 'nodejs'; + +const MAX_SIZE = 5 * 1024 * 1024; + +export async function POST(req) { + const user = getUser(req); + const forbidden = await requireAdmin(user); + if (forbidden) return forbidden; + + const form = await req.formData(); + const file = form.get('file'); + if (!file || typeof file === 'string') { + return Response.json({ error: '请选择图标文件' }, { status: 400 }); + } + if (file.size > MAX_SIZE) { + return Response.json({ error: '图标大小不能超过 5MB' }, { status: 400 }); + } + + const buffer = Buffer.from(await file.arrayBuffer()); + const image = sniffImage(buffer, { allowIcon: true }); + if (!image) { + return Response.json({ error: '仅支持 PNG、JPEG、GIF、WebP 或 ICO 图标' }, { status: 400 }); + } + + const objectName = `forumlify-favicon-${randomUUID()}${image.ext}`; + let oldObject = ''; + try { + const current = await pool.query("SELECT value FROM settings WHERE key = 'favicon_object'"); + oldObject = current.rows[0]?.value || ''; + const { url } = await saveObject(objectName, buffer, image.mime); + const version = Date.now().toString(); + + try { + await pool.query( + `INSERT INTO settings (key, value) VALUES ($1, $2), ($3, $4), ($5, $6) + ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()`, + ['favicon_url', url, 'favicon_version', version, 'favicon_object', objectName] + ); + } catch (error) { + await deleteObject(objectName).catch(() => {}); + throw error; + } + + if (oldObject && /^forumlify-favicon-[\w-]+\.(?:png|jpg|gif|webp|ico)$/.test(oldObject)) { + await deleteObject(oldObject).catch(() => {}); + } + + return Response.json({ favicon_url: url, favicon_version: version }); + } catch { + return Response.json({ error: '上传失败,请稍后重试' }, { status: 500 }); + } +} diff --git a/app/api/settings/route.js b/app/api/settings/route.js index 53a3b8d..0e4aa4a 100644 --- a/app/api/settings/route.js +++ b/app/api/settings/route.js @@ -3,6 +3,8 @@ import pool from '@/lib/db'; import { getUser, requireAdmin } from '@/lib/auth'; import { jsonWithEtag } from '@/lib/http-cache'; +const VERSION_COMMIT = (process.env.FORUMLIFY_COMMIT || 'unknown').slice(0, 7); + // 避免 GET 被静态优化导致 PUT 405(动态接口,不能缓存) export const dynamic = 'force-dynamic'; @@ -16,8 +18,10 @@ export async function GET(req) { const r = await pool.query('SELECT key, value FROM settings ORDER BY key'); const settings = {}; r.rows.forEach((row) => { settings[row.key] = row.value; }); + delete settings.favicon_object; // 兜底:即使插入失败也保证返回 forum_name if (!settings.forum_name) settings.forum_name = 'Forumlify'; + settings.version_commit = VERSION_COMMIT; return jsonWithEtag(req, settings); } catch { return Response.json({ error: '服务器错误' }, { status: 500 }); diff --git a/app/api/upload/route.js b/app/api/upload/route.js index fa4185d..5476abe 100644 --- a/app/api/upload/route.js +++ b/app/api/upload/route.js @@ -3,24 +3,11 @@ import path from 'path'; import { randomUUID } from 'crypto'; import { getUser } from '@/lib/auth'; +import { sniffImage } from '@/lib/image-type'; import { saveObject } from '@/lib/storage'; const MAX_SIZE = 5 * 1024 * 1024; -// 从文件头字节嗅探真实图片类型(JPEG/PNG/GIF/WebP),拒绝伪造内容 -function sniffImage(buf) { - if (buf.length < 12) return null; - // JPEG: FF D8 FF - if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return { ext: '.jpg', mime: 'image/jpeg' }; - // PNG: 89 50 4E 47 0D 0A 1A 0A - if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 && buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a) return { ext: '.png', mime: 'image/png' }; - // GIF: "GIF8" - if (buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x38) return { ext: '.gif', mime: 'image/gif' }; - // WebP: "RIFF" .... "WEBP" - if (buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 && buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50) return { ext: '.webp', mime: 'image/webp' }; - return null; -} - export const runtime = 'nodejs'; export async function POST(req) { diff --git a/app/api/uploads/[name]/route.js b/app/api/uploads/[name]/route.js index 9b6f123..441952c 100644 --- a/app/api/uploads/[name]/route.js +++ b/app/api/uploads/[name]/route.js @@ -12,6 +12,7 @@ const MIME = { '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', + '.ico': 'image/x-icon', }; export async function GET(req, { params }) { diff --git a/app/globals.css b/app/globals.css index c9b5cf8..a29304e 100644 --- a/app/globals.css +++ b/app/globals.css @@ -94,6 +94,10 @@ } /* ===== 全局基础 ===== */ +html { + scrollbar-gutter: stable; +} + * { margin: 0; padding: 0; @@ -510,6 +514,12 @@ svg { margin-right: 6px; } +.new-post-launch-label, +.new-post-title-label { + display: inline-block; + white-space: pre-wrap; +} + .feed-posts-drawer { display: grid; grid-template-rows: 1fr; @@ -524,6 +534,8 @@ svg { .feed-posts-drawer-inner { min-height: 0; overflow: hidden; + padding-top: 4px; + margin-top: -4px; } .feed-posts-drawer.closing, @@ -908,6 +920,26 @@ svg { resize: vertical; } +.new-post-heading { + min-width: 0; + overflow-wrap: anywhere; +} + +.new-post-title-icon { + flex: 0 0 auto; +} + +.new-post-terminal-cursor { + display: inline-block; + width: 2px; + height: 1.05em; + margin-left: 3px; + vertical-align: -0.12em; + background: currentColor; + border-radius: 1px; + animation: newPostCursorBlink 0.82s steps(1, end) infinite; +} + /* ===== 独立页面(滑入) ===== */ .page-slide { display: none; @@ -921,12 +953,12 @@ svg { overflow-y: auto; transition: background 0.3s ease; } -.page-slide.active:not(#pagePost):not(#pageUser):not(#pageSettings) { +.page-slide.active:not(#pagePost):not(#pageUser):not(#pageSettings):not(#pageNew) { display: block; animation: slideIn 0.35s cubic-bezier(0.22, 1, 0.36, 1); } -.page-slide.active:is(#pagePost, #pageUser, #pageSettings) { +.page-slide.active:is(#pagePost, #pageUser, #pageSettings, #pageNew) { display: block; } @@ -1065,6 +1097,89 @@ html.user-transition-settled #pageUser .user-profile-posts { animation: userPageContentReveal 0.28s ease-out both; } +/* ===== 发布新帖共享元素过渡 ===== */ +html.new-post-view-transition #navbar { + view-transition-name: persistent-navbar; +} + +html.new-post-view-transition #pageNew .new-post-title-icon { + view-transition-name: new-post-plus; +} + +html.new-post-view-transition #pageNew .new-post-title-label { + view-transition-name: new-post-title; +} + +html.new-post-view-transition::view-transition { + background: linear-gradient(145deg, var(--bg-start) 0%, var(--bg-end) 100%); + pointer-events: none; +} + +html.new-post-view-transition::view-transition-group(new-post-plus), +html.new-post-view-transition::view-transition-group(new-post-title) { + z-index: 20; + animation-duration: 0.82s; + animation-timing-function: cubic-bezier(0.16, 1, 0.3, 1); +} + +html.new-post-view-transition::view-transition-image-pair(new-post-plus), +html.new-post-view-transition::view-transition-image-pair(new-post-title), +html.new-post-view-transition::view-transition-old(new-post-plus), +html.new-post-view-transition::view-transition-new(new-post-plus), +html.new-post-view-transition::view-transition-old(new-post-title), +html.new-post-view-transition::view-transition-new(new-post-title) { + overflow: visible; + mix-blend-mode: normal; +} + +html.new-post-view-transition::view-transition-old(root) { + animation: newPostFeedFadeOut 0.36s 0.08s ease-out both; +} + +html.new-post-view-transition::view-transition-new(root) { + animation: newPostPageReveal 0.3s 0.44s ease-out both; +} + +html.new-post-view-transition.returning-new-post-home::view-transition-old(root) { + animation: newPostPageHide 0.3s 0.04s ease-in both; +} + +html.new-post-view-transition.returning-new-post-home::view-transition-new(root) { + animation: newPostFeedReveal 0.34s 0.36s ease-out both; +} + +html.new-post-view-transition::view-transition-group(persistent-navbar), +html.new-post-view-transition::view-transition-old(persistent-navbar), +html.new-post-view-transition::view-transition-new(persistent-navbar) { + animation: none; + mix-blend-mode: normal; +} + +@keyframes newPostFeedFadeOut { + from { opacity: 1; } + to { opacity: 0; } +} + +@keyframes newPostPageReveal { + from { opacity: 0; } + to { opacity: 1; } +} + +@keyframes newPostPageHide { + from { opacity: 1; } + to { opacity: 0; } +} + +@keyframes newPostFeedReveal { + from { opacity: 0; } + to { opacity: 1; } +} + +@keyframes newPostCursorBlink { + 0%, 48% { opacity: 1; } + 49%, 100% { opacity: 0; } +} + /* ===== 设置页共享元素过渡 ===== */ html.settings-view-transition #navbar { view-transition-name: persistent-navbar; @@ -1774,7 +1889,8 @@ html.home-view-transition.returning-home::view-transition-new(post-body) { @media (prefers-reduced-motion: reduce) { .page-slide.active, - html.settings-navbar-avatar-reveal #navbar #userDropdown .avatar { + html.settings-navbar-avatar-reveal #navbar #userDropdown .avatar, + .new-post-terminal-cursor { animation: none !important; } } @@ -2167,6 +2283,46 @@ html.home-view-transition.returning-home::view-transition-new(post-body) { border-radius: var(--radius); padding: 20px 24px; box-shadow: var(--glass-shadow); + overflow: hidden; + transition: height 0.36s cubic-bezier(0.22, 1, 0.36, 1); +} + +.admin-content-drawer { + min-height: 0; + min-width: 0; + transform-origin: left center; + transition: + clip-path 0.36s cubic-bezier(0.22, 1, 0.36, 1), + opacity 0.18s ease, + transform 0.36s cubic-bezier(0.22, 1, 0.36, 1); + will-change: clip-path, opacity, transform; +} + +.admin-content-drawer-inner { + min-height: 0; + min-width: 0; + overflow: hidden; +} + +.admin-content-drawer.closing { + clip-path: inset(0 100% 0 0); + opacity: 0; + transform: translateX(-10px) scaleX(0.985); + transition-duration: 0.22s, 0.16s, 0.22s; +} + +.admin-content-drawer.hidden { + clip-path: inset(0 100% 0 0); + opacity: 0; + transform: translateX(-10px) scaleX(0.985); + transition: none; +} + +.admin-content-drawer.opening, +.admin-content-drawer.idle { + clip-path: inset(0 0 0 0); + opacity: 1; + transform: translateX(0) scaleX(1); } /* ===== 移动端适配:底部导航栏(磨砂玻璃风格) ===== */ @@ -2597,6 +2753,140 @@ html.home-view-transition.returning-home::view-transition-new(post-body) { background: #181826; border-color: var(--glass-border); } + +.admin-forum-settings { + width: min(100%, 560px); + overflow-wrap: anywhere; +} + +.admin-forum-divider { + height: 1px; + margin: 24px 0; + background: var(--border); +} + +.admin-forum-hint { + margin: 0 0 12px; + color: var(--text-secondary); + font-size: 13px; + line-height: 1.6; +} + +.admin-favicon-row { + display: grid; + grid-template-columns: 64px minmax(0, 1fr); + gap: 14px; + align-items: stretch; +} + +.admin-favicon-preview { + width: 64px; + height: 64px; + display: grid; + place-items: center; + overflow: hidden; + color: var(--text-secondary); + background: var(--bg); + border: 1px solid var(--border); + border-radius: 8px; +} + +.admin-favicon-preview img { + width: 100%; + height: 100%; + object-fit: contain; +} + +.admin-favicon-upload { + min-width: 0; + min-height: 64px; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 8px; + padding: 16px 14px; + color: var(--text-secondary); + font: inherit; + font-size: 13px; + line-height: 1.4; + text-align: center; + overflow-wrap: anywhere; + background: var(--bg); + border: 1.5px dashed var(--border); + border-radius: 8px; + cursor: pointer; + transition: border-color 0.2s ease, background 0.2s ease, color 0.2s ease; +} + +.admin-favicon-upload:hover, +.admin-favicon-upload.drag-over { + color: var(--primary); + border-color: var(--primary); + background: var(--primary-bg); +} + +.admin-favicon-upload svg { + display: block; + color: var(--text-secondary); +} + +.admin-favicon-upload:hover svg, +.admin-favicon-upload.drag-over svg { + color: var(--primary); +} + +.admin-favicon-upload:disabled { + cursor: wait; + opacity: 0.65; +} + +.admin-version-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + color: var(--text-secondary); + font-size: 13px; + line-height: 1.5; +} + +.admin-version-label { + display: inline-flex; + align-items: center; + gap: 6px; +} + +.admin-version-label svg { + color: var(--primary); +} + +.admin-version-value { + flex-shrink: 0; + padding: 3px 8px; + color: var(--text-secondary); + background: color-mix(in srgb, var(--bg) 72%, transparent); + border: 1px solid var(--border); + border-radius: 999px; + font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + font-size: 11px; + letter-spacing: 0.02em; +} + +@media (max-width: 520px) { + .admin-favicon-row { + grid-template-columns: 56px minmax(0, 1fr); + } + + .admin-favicon-preview { + width: 56px; + height: 56px; + } + + .admin-favicon-upload { + min-height: 56px; + } +} [data-theme="dark"] .admin-sidebar { border: 1px solid var(--glass-border); } diff --git a/components/AdminPage.js b/components/AdminPage.js index b3ba3ac..4863232 100644 --- a/components/AdminPage.js +++ b/components/AdminPage.js @@ -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 ; + if (tab === 'users') return ; + if (tab === 'logs') return ; + if (tab === 'links') return ; + if (tab === 'custom') return ; + if (tab === 'css') return ; + return ; + }; return (
@@ -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); }} > {t(n.labelKey)} @@ -48,14 +144,17 @@ export default function AdminPage() { ))} -
- {tab === 'reports' && } - {tab === 'users' && } - {tab === 'logs' && } - {tab === 'links' && } - {tab === 'custom' && } - {tab === 'css' && } - {tab === 'settings' && } +
+
+
+ {renderPanel()} +
+
diff --git a/components/AppProvider.js b/components/AppProvider.js index af923b3..0f8b78a 100644 --- a/components/AppProvider.js +++ b/components/AppProvider.js @@ -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); diff --git a/components/Feed.js b/components/Feed.js index bbf3818..8d18e6a 100644 --- a/components/Feed.js +++ b/components/Feed.js @@ -147,7 +147,8 @@ export default function Feed({ onOpenModal, onReport }) { navigate('new'); }} > - {t('feed.newPost')} + + {t('feed.newPost')}
diff --git a/components/NewPost.js b/components/NewPost.js index c11cef5..fae4f61 100644 --- a/components/NewPost.js +++ b/components/NewPost.js @@ -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 ( -
-
-

{t('newPost.title')}

+
+
+

+ + {headingText} + {headingPhase !== 'idle' &&

-
+
setTitle(e.target.value)} + onChange={handleTitleChange} />