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

+2
View File
@@ -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
+58
View File
@@ -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 });
}
}
+4
View File
@@ -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 });
+1 -14
View File
@@ -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) {
+1
View File
@@ -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 }) {
+293 -3
View File
@@ -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);
}
+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>
</>
);
+1 -5
View File
@@ -1,4 +1,3 @@
version: '3'
services:
db:
image: postgres:15
@@ -9,14 +8,11 @@ services:
volumes:
- ./schema.sql:/docker-entrypoint-initdb.d/schema.sql
- db_data:/var/lib/postgresql/data
ports:
- "5432:5432"
app:
# 从 GHCR 拉取镜像(每次 push next 自动重建),不再本地构建
image: ghcr.io/furrium/forumlify:next
ports:
- "3000:3000"
- "${FORUMLIFY_PORT:-3000}:3000"
depends_on:
- db
environment:
+2
View File
@@ -5,7 +5,9 @@
# ---- 构建阶段 ----
FROM node:24-alpine AS builder
WORKDIR /app
ARG FORUMLIFY_COMMIT=unknown
ENV DOCKER=1
ENV FORUMLIFY_COMMIT=$FORUMLIFY_COMMIT
# 用 bun 装依赖(bun.lock 最新;npm 会读旧的 package-lock.json → react 18 → 构建失败)
RUN npm i -g bun
+11
View File
@@ -127,6 +127,17 @@ export const API = {
updateSettings(forum_name) {
return apiFetch('/settings', { method: 'PUT', body: JSON.stringify({ forum_name }) });
},
uploadFavicon(file) {
const fd = new FormData();
fd.append('file', file);
const headers = {};
if (token) headers['Authorization'] = 'Bearer ' + token;
return fetch('/api/admin/favicon', { method: 'POST', body: fd, headers }).then(async (res) => {
const data = await res.json().catch(() => ({}));
if (!res.ok || data.error) throw new Error(data.error || '上传失败');
return data;
});
},
getLinks() { return apiFetch('/links'); },
addLink(title, url) {
return apiFetch('/links', { method: 'POST', body: JSON.stringify({ title, url }) });
+82
View File
@@ -0,0 +1,82 @@
export const DIRECT_IMAGE_LIMIT = 5 * 1024 * 1024;
export const MAX_IMAGE_SOURCE_SIZE = 20 * 1024 * 1024;
function canvasToBlob(canvas, quality) {
return new Promise((resolve, reject) => {
canvas.toBlob(
(blob) => blob ? resolve(blob) : reject(new Error('compression_failed')),
'image/webp',
quality
);
});
}
async function decodeImage(file) {
if (typeof createImageBitmap === 'function') {
const bitmap = await createImageBitmap(file);
return {
source: bitmap,
width: bitmap.width,
height: bitmap.height,
close: () => bitmap.close(),
};
}
const url = URL.createObjectURL(file);
const image = new Image();
try {
await new Promise((resolve, reject) => {
image.onload = resolve;
image.onerror = reject;
image.src = url;
});
return {
source: image,
width: image.naturalWidth,
height: image.naturalHeight,
close: () => URL.revokeObjectURL(url),
};
} catch (error) {
URL.revokeObjectURL(url);
throw error;
}
}
export async function compressImage(file, { maxDimension = 4096 } = {}) {
if (file.size <= DIRECT_IMAGE_LIMIT) return file;
if (file.size > MAX_IMAGE_SOURCE_SIZE) throw new Error('source_too_large');
const decoded = await decodeImage(file);
try {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d', { alpha: true });
if (!context) throw new Error('compression_failed');
const maxEdge = Math.max(decoded.width, decoded.height);
const initialScale = Math.min(1, maxDimension / maxEdge);
const qualities = [0.88, 0.76, 0.64, 0.52, 0.4];
for (const sizeScale of [1, 0.8, 0.64, 0.5]) {
canvas.width = Math.max(1, Math.round(decoded.width * initialScale * sizeScale));
canvas.height = Math.max(1, Math.round(decoded.height * initialScale * sizeScale));
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(decoded.source, 0, 0, canvas.width, canvas.height);
for (const quality of qualities) {
const blob = await canvasToBlob(canvas, quality);
if (blob.size <= DIRECT_IMAGE_LIMIT) {
const baseName = file.name.replace(/\.[^.]+$/, '') || 'favicon';
return new File([blob], `${baseName}.webp`, { type: 'image/webp' });
}
}
}
throw new Error('compression_failed');
} finally {
decoded.close();
}
}
export function compressFavicon(file) {
return compressImage(file, { maxDimension: 1024 });
}
+20
View File
@@ -0,0 +1,20 @@
export function applyFavicon(url, version = '') {
if (typeof document === 'undefined' || !url) return;
let href = url;
try {
const resolved = new URL(url, window.location.href);
if (version) resolved.searchParams.set('v', version);
href = resolved.href;
} catch {
href = url;
}
let link = document.querySelector('link[rel="icon"]');
if (!link) {
link = document.createElement('link');
link.rel = 'icon';
document.head.appendChild(link);
}
link.href = href;
}
+27
View File
@@ -0,0 +1,27 @@
export function sniffImage(buffer, { allowIcon = false } = {}) {
if (buffer.length < 12) return null;
if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {
return { ext: '.jpg', mime: 'image/jpeg' };
}
if (
buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4e && buffer[3] === 0x47
&& buffer[4] === 0x0d && buffer[5] === 0x0a && buffer[6] === 0x1a && buffer[7] === 0x0a
) {
return { ext: '.png', mime: 'image/png' };
}
if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x38) {
return { ext: '.gif', mime: 'image/gif' };
}
if (
buffer[0] === 0x52 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x46
&& buffer[8] === 0x57 && buffer[9] === 0x45 && buffer[10] === 0x42 && buffer[11] === 0x50
) {
return { ext: '.webp', mime: 'image/webp' };
}
if (allowIcon && buffer[0] === 0x00 && buffer[1] === 0x00 && buffer[2] === 0x01 && buffer[3] === 0x00) {
return { ext: '.ico', mime: 'image/x-icon' };
}
return null;
}
+18 -2
View File
@@ -55,7 +55,10 @@
"answer": "Answer",
"captchaLoading": "Loading captcha...",
"drop": "Release to upload",
"dropHint": "Click or drag to upload image"
"dropHint": "Click or drag to upload image",
"compressing": "Compressing image...",
"imageTooLarge": "The source image must be smaller than 20MB",
"imageCompressFailed": "This image could not be compressed. Try another image or reduce its dimensions first."
},
"reply": {
"loading": "Loading replies...",
@@ -290,7 +293,20 @@
"saveFailed": "Save failed",
"title": "Forum settings",
"nameLabel": "Forum name",
"save": "Save"
"save": "Save",
"faviconLabel": "Site icon",
"faviconHint": "PNG, JPEG, GIF, WebP, or ICO up to 20MB. Files over 5MB are compressed automatically. A square image works best.",
"faviconPreview": "Current site icon",
"faviconUpload": "Click or drag to upload an icon",
"faviconDrop": "Release to upload the icon",
"faviconUploading": "Uploading...",
"faviconCompressing": "Compressing image...",
"faviconInvalid": "Choose a PNG, JPEG, GIF, WebP, or ICO icon",
"faviconTooLarge": "The source image must be smaller than 20MB",
"faviconCompressFailed": "This image could not be compressed. Try another image or reduce its dimensions first.",
"faviconSaved": "Site icon updated",
"faviconSaveFailed": "Icon upload failed: {{msg}}",
"versionLabel": "Current commit"
}
}
}
+18 -2
View File
@@ -55,7 +55,10 @@
"answer": "答案",
"captchaLoading": "验证码加载中...",
"drop": "松开上传",
"dropHint": "点击或拖拽上传图片"
"dropHint": "点击或拖拽上传图片",
"compressing": "正在压缩图片...",
"imageTooLarge": "原图大小不能超过 20MB",
"imageCompressFailed": "无法压缩这张图片,请换一张图片或先缩小尺寸"
},
"reply": {
"loading": "正在加载回复...",
@@ -290,7 +293,20 @@
"saveFailed": "保存失败",
"title": "论坛设置",
"nameLabel": "论坛名称",
"save": "保存"
"save": "保存",
"faviconLabel": "网站图标",
"faviconHint": "支持 PNG、JPEG、GIF、WebP 或 ICO,最大 20MB;超过 5MB 时自动压缩。建议使用正方形图片。",
"faviconPreview": "当前网站图标",
"faviconUpload": "点击或拖拽上传图标",
"faviconDrop": "松开上传图标",
"faviconUploading": "正在上传...",
"faviconCompressing": "正在压缩图片...",
"faviconInvalid": "请选择 PNG、JPEG、GIF、WebP 或 ICO 图标",
"faviconTooLarge": "原图大小不能超过 20MB",
"faviconCompressFailed": "无法压缩这张图片,请换一张图片或先缩小尺寸",
"faviconSaved": "网站图标已更新",
"faviconSaveFailed": "图标上传失败:{{msg}}",
"versionLabel": "当前版本 Commit"
}
}
}
+13
View File
@@ -1,7 +1,20 @@
const enableCodecovBundleAnalysis = process.env.CODECOV_BUNDLE_ANALYSIS === 'true';
const { execFileSync } = require('child_process');
function resolveCommit() {
if (process.env.FORUMLIFY_COMMIT) return process.env.FORUMLIFY_COMMIT.slice(0, 7);
try {
return execFileSync('git', ['rev-parse', '--short=7', 'HEAD'], { encoding: 'utf8' }).trim();
} catch {
return 'unknown';
}
}
/** @type {import('next').NextConfig} */
const nextConfig = {
env: {
FORUMLIFY_COMMIT: resolveCommit(),
},
// 本地开发允许的来源:默认本机;局域网/其他设备通过环境变量追加
// ALLOWED_DEV_ORIGINS=192.168.x.x,10.0.0.x (仅开发用,不写死具体 IP)
allowedDevOrigins: [
+32
View File
@@ -117,6 +117,38 @@ test('获取论坛设置', async () => {
const { status, data } = await api('/settings');
assert.equal(status, 200);
assert.equal(data.forum_name, '测试论坛');
assert.match(data.version_commit, /^(?:[0-9a-f]{7}|unknown)$/);
assert.equal(data.favicon_object, undefined);
});
test('未登录用户不能上传网站图标', async () => {
const form = new FormData();
form.append('file', new Blob([Buffer.from('not-an-image')]), 'favicon.png');
const res = await fetch(BASE + '/api/admin/favicon', { method: 'POST', body: form });
assert.equal(res.status, 401);
});
test('管理员上传网站图标', async () => {
const png = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',
'base64'
);
const form = new FormData();
form.append('file', new Blob([png], { type: 'image/png' }), 'favicon.png');
const res = await fetch(BASE + '/api/admin/favicon', {
method: 'POST',
headers: { Authorization: `Bearer ${adminToken}` },
body: form,
});
const data = await res.json();
assert.equal(res.status, 200);
assert.match(data.favicon_url, /^\/uploads\/forumlify-favicon-[\w-]+\.png$/);
assert.match(data.favicon_version, /^\d+$/);
const settings = await api('/settings');
assert.equal(settings.data.favicon_url, data.favicon_url);
assert.equal(settings.data.favicon_version, data.favicon_version);
assert.equal(settings.data.favicon_object, undefined);
});
test('添加友情链接', async () => {
+17
View File
@@ -0,0 +1,17 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { sniffImage } from '../lib/image-type.js';
test('image signatures are detected without trusting file extensions', () => {
assert.deepEqual(
sniffImage(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0])),
{ ext: '.png', mime: 'image/png' }
);
assert.equal(sniffImage(Buffer.from('not an image')), null);
});
test('ICO signatures are accepted only for favicon uploads', () => {
const ico = Buffer.from([0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x10, 0, 0, 0, 0]);
assert.equal(sniffImage(ico), null);
assert.deepEqual(sniffImage(ico, { allowIcon: true }), { ext: '.ico', mime: 'image/x-icon' });
});