feat: add workspace and claude messages support
This commit is contained in:
+2
-106
@@ -1,10 +1,4 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
import { api } from '../api.js';
|
||||
import { tr } from '../i18n.js';
|
||||
import { SITE_DOCS_URL } from '../docsLink.js';
|
||||
import { buildUpdateReminder } from './helpers/updateCenterPresentation.js';
|
||||
|
||||
const VERSION = '1.3.0';
|
||||
|
||||
@@ -30,14 +24,9 @@ const TECH_STACK = [
|
||||
{ name: 'ComfyUI / Docker', desc: '视频工作台和多租户工作流容器运行环境。' },
|
||||
];
|
||||
|
||||
const LINKS = [
|
||||
{ label: 'GitHub', href: 'https://github.com/cita-777/boosapi', icon: 'GH' },
|
||||
{ label: 'Docker Hub', href: 'https://hub.docker.com/r/1467078763/boosapi', icon: 'DH' },
|
||||
{ label: '站点文档', href: SITE_DOCS_URL, icon: 'DOC' },
|
||||
];
|
||||
|
||||
const ENDPOINTS = [
|
||||
{ path: '/v1/chat/completions', desc: 'OpenAI 兼容对话代理,支持非流式与流式。' },
|
||||
{ path: '/v1/messages', desc: 'Claude Messages API 兼容入口,支持 Anthropic 请求、响应和流式事件。' },
|
||||
{ path: '/v1/responses', desc: 'Responses API 兼容代理,可接入支持该协议的上游。' },
|
||||
{ path: '/v1/images/generations', desc: '图像生成代理,供生图助手和 ComfyUI 图像节点使用。' },
|
||||
{ path: '/v1/videos', desc: '视频生成任务入口,已适配火山方舟任务创建。' },
|
||||
@@ -46,49 +35,6 @@ const ENDPOINTS = [
|
||||
];
|
||||
|
||||
export default function About() {
|
||||
const [currentVersion, setCurrentVersion] = useState(`v${VERSION}`);
|
||||
const [latestGitHubVersion, setLatestGitHubVersion] = useState('');
|
||||
const [latestDockerHubVersion, setLatestDockerHubVersion] = useState('');
|
||||
const [updateReminder, setUpdateReminder] = useState(() => buildUpdateReminder({
|
||||
currentVersion: VERSION,
|
||||
helper: null,
|
||||
githubRelease: null,
|
||||
dockerHubTag: null,
|
||||
}));
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
const loadStatus = async () => {
|
||||
try {
|
||||
const status = await api.getUpdateCenterStatus() as {
|
||||
currentVersion?: string;
|
||||
githubRelease?: { normalizedVersion?: string; displayVersion?: string; tagName?: string | null; digest?: string | null } | null;
|
||||
dockerHubTag?: { normalizedVersion?: string; displayVersion?: string; tagName?: string | null; digest?: string | null } | null;
|
||||
helper?: { imageTag?: string | null; imageDigest?: string | null } | null;
|
||||
};
|
||||
const resolvedCurrentVersion = String(status.currentVersion || VERSION);
|
||||
if (cancelled) return;
|
||||
setCurrentVersion(`v${resolvedCurrentVersion}`);
|
||||
setLatestGitHubVersion(String(status.githubRelease?.displayVersion || status.githubRelease?.normalizedVersion || ''));
|
||||
setLatestDockerHubVersion(String(status.dockerHubTag?.displayVersion || status.dockerHubTag?.normalizedVersion || ''));
|
||||
setUpdateReminder(buildUpdateReminder({
|
||||
currentVersion: resolvedCurrentVersion,
|
||||
helper: status.helper,
|
||||
githubRelease: status.githubRelease,
|
||||
dockerHubTag: status.dockerHubTag,
|
||||
}));
|
||||
} catch {
|
||||
// ignore update-center lookup failures on about page
|
||||
}
|
||||
};
|
||||
|
||||
void loadStatus();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="animate-fade-in" style={{ maxWidth: 860 }}>
|
||||
{/* Header */}
|
||||
@@ -106,7 +52,7 @@ export default function About() {
|
||||
/>
|
||||
<div>
|
||||
<div style={{ fontSize: 18, fontWeight: 700 }}>BoosAPI</div>
|
||||
<div style={{ fontSize: 12, color: 'var(--color-text-tertiary)', marginTop: 2 }}>{currentVersion}</div>
|
||||
<div style={{ fontSize: 12, color: 'var(--color-text-tertiary)', marginTop: 2 }}>v{VERSION}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ fontSize: 14, color: 'var(--color-text-secondary)', lineHeight: 1.8 }}>
|
||||
@@ -131,27 +77,6 @@ export default function About() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card animate-slide-up stagger-1" style={{ padding: 22, marginBottom: 14 }}>
|
||||
<h3 style={{ fontSize: 15, fontWeight: 600, marginBottom: 12 }}>更新提醒</h3>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginBottom: 10 }}>
|
||||
<span className={`${updateReminder.badgeClassName} ${updateReminder.highlight ? 'stat-value-glow' : ''}`.trim()}>
|
||||
{updateReminder.label}
|
||||
</span>
|
||||
<span className={updateReminder.highlight ? 'stat-value-glow' : ''} style={{ fontSize: 13, color: 'var(--color-text-primary)', fontWeight: 600 }}>
|
||||
{updateReminder.detail}
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ display: 'grid', gap: 8, fontSize: 13 }}>
|
||||
<div>GitHub 稳定版:{latestGitHubVersion || '暂无数据'}</div>
|
||||
<div>Docker Hub:{latestDockerHubVersion || '暂无数据'}</div>
|
||||
<div>
|
||||
<Link to="/settings" style={{ color: 'var(--color-primary)', textDecoration: 'none', fontWeight: 600 }}>
|
||||
前往更新中心
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Features */}
|
||||
<div className="card animate-slide-up stagger-2" style={{ padding: 22, marginBottom: 14 }}>
|
||||
<h3 style={{ fontSize: 15, fontWeight: 600, marginBottom: 14 }}>{tr('核心特色')}</h3>
|
||||
@@ -242,35 +167,6 @@ export default function About() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Links */}
|
||||
<div className="card animate-slide-up stagger-5" style={{ padding: 22, marginBottom: 14 }}>
|
||||
<h3 style={{ fontSize: 15, fontWeight: 600, marginBottom: 14 }}>{tr('项目链接')}</h3>
|
||||
<div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
|
||||
{LINKS.map((l) => (
|
||||
<a
|
||||
key={l.label}
|
||||
href={l.href}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
style={{
|
||||
display: 'inline-flex', alignItems: 'center', gap: 6,
|
||||
padding: '8px 16px', borderRadius: 8,
|
||||
border: '1px solid var(--color-border-light)',
|
||||
background: 'var(--color-bg-secondary)',
|
||||
color: 'var(--color-text-primary)',
|
||||
textDecoration: 'none', fontSize: 13, fontWeight: 500,
|
||||
transition: 'border-color 0.15s',
|
||||
}}
|
||||
onMouseEnter={(e) => (e.currentTarget.style.borderColor = 'var(--color-primary)')}
|
||||
onMouseLeave={(e) => (e.currentTarget.style.borderColor = 'var(--color-border-light)')}
|
||||
>
|
||||
<span style={{ fontFamily: 'var(--font-mono)', fontSize: 11 }}>{l.icon}</span>
|
||||
<span>{tr(l.label)}</span>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Privacy */}
|
||||
<div className="card animate-slide-up stagger-5" style={{ padding: 22 }}>
|
||||
<h3 style={{ fontSize: 15, fontWeight: 600, marginBottom: 10 }}>{tr('数据与隐私')}</h3>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
|
||||
@@ -28,32 +28,12 @@ async function flushMicrotasks() {
|
||||
});
|
||||
}
|
||||
|
||||
describe('About update center', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
apiMock.getUpdateCenterStatus.mockResolvedValue({
|
||||
currentVersion: '1.2.3',
|
||||
githubRelease: {
|
||||
normalizedVersion: '1.3.0',
|
||||
displayVersion: '1.3.0',
|
||||
url: 'https://github.com/cita-777/metapi/releases/tag/v1.3.0',
|
||||
},
|
||||
dockerHubTag: {
|
||||
normalizedVersion: 'latest',
|
||||
displayVersion: 'latest @ sha256:efb2ee655386',
|
||||
},
|
||||
helper: {
|
||||
imageTag: 'latest',
|
||||
imageDigest: 'sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
describe('About page', () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('shows current version, newer release summaries, and a highlighted update reminder', async () => {
|
||||
it('shows product information without update prompts or project links', async () => {
|
||||
let root!: ReactTestRenderer;
|
||||
try {
|
||||
await act(async () => {
|
||||
@@ -66,20 +46,13 @@ describe('About update center', () => {
|
||||
await flushMicrotasks();
|
||||
|
||||
const text = collectText(root.root);
|
||||
expect(text).toContain('v1.2.3');
|
||||
expect(text).toContain('GitHub 稳定版');
|
||||
expect(text).toContain('1.3.0');
|
||||
expect(text).toContain('Docker Hub');
|
||||
expect(text).toContain('latest @ sha256:efb2ee655386');
|
||||
expect(text).toContain('发现新版本');
|
||||
expect(text).toContain('前往更新中心');
|
||||
|
||||
const highlightedReminder = root.root.find((node) => (
|
||||
typeof node.props.className === 'string'
|
||||
&& node.props.className.includes('stat-value-glow')
|
||||
&& collectText(node).includes('发现新版本')
|
||||
));
|
||||
expect(collectText(highlightedReminder)).toContain('发现新版本');
|
||||
expect(text).toContain('关于 BoosAPI');
|
||||
expect(text).toContain('核心特色');
|
||||
expect(text).toContain('兼容入口');
|
||||
expect(text).not.toContain('更新提醒');
|
||||
expect(text).not.toContain('前往更新中心');
|
||||
expect(text).not.toContain('项目链接');
|
||||
expect(apiMock.getUpdateCenterStatus).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
root?.unmount();
|
||||
}
|
||||
|
||||
+259
-158
@@ -1,77 +1,82 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useLocation, useNavigate } from 'react-router-dom';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { api } from '../api.js';
|
||||
import { useToast } from '../components/Toast.js';
|
||||
import { clearFocusParams, readFocusAnnouncementId } from './helpers/navigationFocus.js';
|
||||
import {
|
||||
formatSiteAnnouncementSeenAt,
|
||||
readClientTimeZone,
|
||||
resolveSiteAnnouncementTimeZone,
|
||||
SiteAnnouncementContent,
|
||||
} from './helpers/siteAnnouncementPresentation.js';
|
||||
import { SiteAnnouncementContent } from './helpers/siteAnnouncementPresentation.js';
|
||||
import { tr } from '../i18n.js';
|
||||
|
||||
type SiteAnnouncementRow = {
|
||||
type AnnouncementLevel = 'info' | 'warning' | 'error';
|
||||
type AnnouncementStatus = 'draft' | 'published' | 'archived';
|
||||
|
||||
type AnnouncementRow = {
|
||||
id: number;
|
||||
siteId: number;
|
||||
platform: string;
|
||||
sourceKey: string;
|
||||
title: string;
|
||||
content: string;
|
||||
level: 'info' | 'warning' | 'error';
|
||||
level: AnnouncementLevel;
|
||||
status?: AnnouncementStatus;
|
||||
firstSeenAt?: string | null;
|
||||
lastSeenAt?: string | null;
|
||||
readAt?: string | null;
|
||||
publishedAt?: string | null;
|
||||
readCount?: number | null;
|
||||
};
|
||||
|
||||
type SiteRow = {
|
||||
id: number;
|
||||
name: string;
|
||||
platform?: string | null;
|
||||
type AnnouncementForm = {
|
||||
id: number | null;
|
||||
title: string;
|
||||
content: string;
|
||||
level: AnnouncementLevel;
|
||||
status: AnnouncementStatus;
|
||||
};
|
||||
|
||||
const emptyForm: AnnouncementForm = {
|
||||
id: null,
|
||||
title: '',
|
||||
content: '',
|
||||
level: 'info',
|
||||
status: 'published',
|
||||
};
|
||||
|
||||
const levelLabels: Record<AnnouncementLevel, string> = {
|
||||
info: '普通',
|
||||
warning: '重要',
|
||||
error: '紧急',
|
||||
};
|
||||
|
||||
const statusLabels: Record<AnnouncementStatus, string> = {
|
||||
draft: '草稿',
|
||||
published: '已发布',
|
||||
archived: '已归档',
|
||||
};
|
||||
|
||||
function normalizeStatus(value: string | undefined | null): AnnouncementStatus {
|
||||
return value === 'draft' || value === 'archived' ? value : 'published';
|
||||
}
|
||||
|
||||
function normalizeLevel(value: string | undefined | null): AnnouncementLevel {
|
||||
return value === 'warning' || value === 'error' ? value : 'info';
|
||||
}
|
||||
|
||||
export default function SiteAnnouncements() {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
const [rows, setRows] = useState<SiteAnnouncementRow[]>([]);
|
||||
const [sites, setSites] = useState<SiteRow[]>([]);
|
||||
const [rows, setRows] = useState<AnnouncementRow[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [clearing, setClearing] = useState(false);
|
||||
const [markingAll, setMarkingAll] = useState(false);
|
||||
const [serverTimeZone, setServerTimeZone] = useState<string | undefined>(undefined);
|
||||
const [highlightAnnouncementId, setHighlightAnnouncementId] = useState<number | null>(null);
|
||||
const rowRefs = useRef<Map<number, HTMLDivElement>>(new Map());
|
||||
const highlightTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const viewerTimeZone = useMemo(() => readClientTimeZone(), []);
|
||||
const displayTimeZone = resolveSiteAnnouncementTimeZone(viewerTimeZone, serverTimeZone);
|
||||
const [form, setForm] = useState<AnnouncementForm>(emptyForm);
|
||||
|
||||
const siteNameById = useMemo(() => {
|
||||
const map = new Map<number, string>();
|
||||
for (const site of sites) {
|
||||
map.set(site.id, site.name);
|
||||
}
|
||||
return map;
|
||||
}, [sites]);
|
||||
const publishedCount = useMemo(
|
||||
() => rows.filter((row) => normalizeStatus(row.status) === 'published').length,
|
||||
[rows],
|
||||
);
|
||||
|
||||
const load = async (silent = false) => {
|
||||
if (silent) setRefreshing(true);
|
||||
else setLoading(true);
|
||||
try {
|
||||
const [announcementRows, siteRows, runtimeInfo] = await Promise.all([
|
||||
api.getSiteAnnouncements(),
|
||||
api.getSites(),
|
||||
api.getRuntimeSettings().catch(() => null),
|
||||
]);
|
||||
const announcementRows = await api.getSiteAnnouncements();
|
||||
setRows(Array.isArray(announcementRows) ? announcementRows : []);
|
||||
setSites(Array.isArray(siteRows) ? siteRows : []);
|
||||
const nextServerTimeZone = typeof runtimeInfo?.serverTimeZone === 'string'
|
||||
? runtimeInfo.serverTimeZone.trim()
|
||||
: '';
|
||||
setServerTimeZone(nextServerTimeZone || undefined);
|
||||
} catch (error: any) {
|
||||
toast.error(error?.message || '加载站点公告失败');
|
||||
toast.error(error?.message || '加载用户公告失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setRefreshing(false);
|
||||
@@ -80,47 +85,75 @@ export default function SiteAnnouncements() {
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
return () => {
|
||||
const win = globalThis as typeof globalThis & {
|
||||
clearTimeout?: typeof clearTimeout;
|
||||
};
|
||||
if (highlightTimerRef.current && typeof win.clearTimeout === 'function') {
|
||||
win.clearTimeout(highlightTimerRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const focusAnnouncementId = readFocusAnnouncementId(location.search);
|
||||
if (!focusAnnouncementId || loading) return;
|
||||
const row = rowRefs.current.get(focusAnnouncementId);
|
||||
const nextSearch = clearFocusParams(location.search);
|
||||
const win = globalThis as typeof globalThis & {
|
||||
setTimeout?: typeof setTimeout;
|
||||
clearTimeout?: typeof clearTimeout;
|
||||
};
|
||||
if (!row) {
|
||||
navigate({ pathname: location.pathname, search: nextSearch }, { replace: true });
|
||||
const resetForm = () => setForm(emptyForm);
|
||||
|
||||
const editRow = (row: AnnouncementRow) => {
|
||||
setForm({
|
||||
id: row.id,
|
||||
title: row.title || '',
|
||||
content: row.content || '',
|
||||
level: normalizeLevel(row.level),
|
||||
status: normalizeStatus(row.status),
|
||||
});
|
||||
};
|
||||
|
||||
const submit = async () => {
|
||||
const title = form.title.trim();
|
||||
const content = form.content.trim();
|
||||
if (!title) {
|
||||
toast.error('请填写公告标题');
|
||||
return;
|
||||
}
|
||||
row.scrollIntoView?.({ behavior: 'smooth', block: 'center' });
|
||||
setHighlightAnnouncementId(focusAnnouncementId);
|
||||
if (highlightTimerRef.current && typeof win.clearTimeout === 'function') {
|
||||
win.clearTimeout(highlightTimerRef.current);
|
||||
if (!content) {
|
||||
toast.error('请填写公告内容');
|
||||
return;
|
||||
}
|
||||
if (typeof win.setTimeout === 'function') {
|
||||
highlightTimerRef.current = win.setTimeout(() => {
|
||||
setHighlightAnnouncementId((current) => (current === focusAnnouncementId ? null : current));
|
||||
}, 2200);
|
||||
|
||||
setSaving(true);
|
||||
try {
|
||||
const payload = {
|
||||
title,
|
||||
content,
|
||||
level: form.level,
|
||||
status: form.status,
|
||||
};
|
||||
if (form.id) {
|
||||
await api.updateSiteAnnouncement(form.id, payload);
|
||||
toast.success('公告已更新');
|
||||
} else {
|
||||
await api.createSiteAnnouncement(payload);
|
||||
toast.success(form.status === 'published' ? '公告已发布' : '草稿已保存');
|
||||
}
|
||||
resetForm();
|
||||
await load(true);
|
||||
} catch (error: any) {
|
||||
toast.error(error?.message || '保存公告失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
navigate({ pathname: location.pathname, search: nextSearch }, { replace: true });
|
||||
}, [loading, location.pathname, location.search, navigate, rows]);
|
||||
};
|
||||
|
||||
const removeRow = async (row: AnnouncementRow) => {
|
||||
if (typeof window !== 'undefined' && !window.confirm(`确定删除公告「${row.title}」吗?`)) return;
|
||||
try {
|
||||
await api.deleteSiteAnnouncement(row.id);
|
||||
setRows((current) => current.filter((item) => item.id !== row.id));
|
||||
if (form.id === row.id) resetForm();
|
||||
toast.success('公告已删除');
|
||||
} catch (error: any) {
|
||||
toast.error(error?.message || '删除公告失败');
|
||||
}
|
||||
};
|
||||
|
||||
const clearAll = async () => {
|
||||
if (typeof window !== 'undefined' && !window.confirm('确定清空全部用户公告吗?')) return;
|
||||
setClearing(true);
|
||||
try {
|
||||
await api.clearSiteAnnouncements();
|
||||
setRows([]);
|
||||
resetForm();
|
||||
toast.success('公告已清空');
|
||||
} catch (error: any) {
|
||||
toast.error(error?.message || '清空公告失败');
|
||||
@@ -129,35 +162,27 @@ export default function SiteAnnouncements() {
|
||||
}
|
||||
};
|
||||
|
||||
const markAllRead = async () => {
|
||||
setMarkingAll(true);
|
||||
try {
|
||||
await api.markAllSiteAnnouncementsRead();
|
||||
setRows((current) => current.map((row) => ({
|
||||
...row,
|
||||
readAt: row.readAt || new Date().toISOString(),
|
||||
})));
|
||||
toast.success('已标记全部为已读');
|
||||
} catch (error: any) {
|
||||
toast.error(error?.message || '标记失败');
|
||||
} finally {
|
||||
setMarkingAll(false);
|
||||
}
|
||||
};
|
||||
|
||||
const triggerSync = async () => {
|
||||
try {
|
||||
await api.syncSiteAnnouncements();
|
||||
toast.success('公告同步任务已启动');
|
||||
} catch (error: any) {
|
||||
toast.error(error?.message || '启动同步失败');
|
||||
}
|
||||
const inputStyle: React.CSSProperties = {
|
||||
width: '100%',
|
||||
padding: '10px 12px',
|
||||
border: '1px solid var(--color-border)',
|
||||
borderRadius: 8,
|
||||
background: 'var(--color-bg)',
|
||||
color: 'var(--color-text-primary)',
|
||||
fontSize: 13,
|
||||
outline: 'none',
|
||||
boxSizing: 'border-box',
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="animate-fade-in">
|
||||
<div className="page-header">
|
||||
<h2 className="page-title">{tr('站点公告')}</h2>
|
||||
<div>
|
||||
<h2 className="page-title">{tr('用户公告')}</h2>
|
||||
<div style={{ marginTop: 4, fontSize: 12, color: 'var(--color-text-tertiary)' }}>
|
||||
管理员发布给普通用户的站内公告,会在普通用户面板中展示。
|
||||
</div>
|
||||
</div>
|
||||
<div className="page-actions">
|
||||
<button
|
||||
onClick={() => load(true)}
|
||||
@@ -167,24 +192,9 @@ export default function SiteAnnouncements() {
|
||||
>
|
||||
{refreshing ? <><span className="spinner spinner-sm" /> 刷新中...</> : '刷新'}
|
||||
</button>
|
||||
<button
|
||||
onClick={markAllRead}
|
||||
disabled={markingAll}
|
||||
className="btn btn-ghost"
|
||||
style={{ border: '1px solid var(--color-border)', padding: '8px 14px' }}
|
||||
>
|
||||
{markingAll ? <><span className="spinner spinner-sm" /> 标记中...</> : '全部已读'}
|
||||
</button>
|
||||
<button
|
||||
onClick={triggerSync}
|
||||
className="btn btn-ghost"
|
||||
style={{ border: '1px solid var(--color-border)', padding: '8px 14px' }}
|
||||
>
|
||||
手动同步
|
||||
</button>
|
||||
<button
|
||||
onClick={clearAll}
|
||||
disabled={clearing}
|
||||
disabled={clearing || rows.length === 0}
|
||||
className="btn btn-link btn-link-danger"
|
||||
>
|
||||
{clearing ? <><span className="spinner spinner-sm" /> 清空中...</> : '清空公告'}
|
||||
@@ -192,48 +202,139 @@ export default function SiteAnnouncements() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card" style={{ padding: 0 }}>
|
||||
{loading ? (
|
||||
<div style={{ padding: 24, textAlign: 'center' }}>
|
||||
<span className="spinner spinner-sm" />
|
||||
</div>
|
||||
) : rows.length === 0 ? (
|
||||
<div style={{ padding: 32, textAlign: 'center' }}>
|
||||
<div className="empty-state-title">暂无公告</div>
|
||||
<div className="empty-state-desc">当前没有可显示的站点公告。</div>
|
||||
</div>
|
||||
) : (
|
||||
rows.map((row, index) => (
|
||||
<div
|
||||
key={row.id}
|
||||
ref={(node) => {
|
||||
if (node) rowRefs.current.set(row.id, node);
|
||||
else rowRefs.current.delete(row.id);
|
||||
}}
|
||||
className={`animate-slide-up stagger-${Math.min(index + 1, 5)} ${highlightAnnouncementId === row.id ? 'row-focus-highlight' : ''}`.trim()}
|
||||
style={{
|
||||
padding: '16px 18px',
|
||||
borderBottom: index === rows.length - 1 ? 'none' : '1px solid var(--color-border-light)',
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, alignItems: 'center', marginBottom: 6 }}>
|
||||
<div style={{ fontSize: 15, fontWeight: 600 }}>{row.title}</div>
|
||||
<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
|
||||
<span className="badge badge-muted">{siteNameById.get(row.siteId) || `站点 #${row.siteId}`}</span>
|
||||
<span className="badge badge-info">{row.platform}</span>
|
||||
<span className={`badge ${row.readAt ? 'badge-muted' : 'badge-warning'}`}>{row.readAt ? '已读' : '未读'}</span>
|
||||
</div>
|
||||
</div>
|
||||
<SiteAnnouncementContent content={row.content} />
|
||||
<div
|
||||
style={{ marginTop: 8, fontSize: 12, color: 'var(--color-text-muted)' }}
|
||||
title={displayTimeZone ? `本地时区:${displayTimeZone}` : undefined}
|
||||
>
|
||||
首次发现:{formatSiteAnnouncementSeenAt(row.firstSeenAt || row.lastSeenAt || '', displayTimeZone)}
|
||||
</div>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'minmax(280px, 360px) 1fr', gap: 14, alignItems: 'start' }}>
|
||||
<div className="card" style={{ padding: 18 }}>
|
||||
<h3 style={{ fontSize: 15, fontWeight: 600, marginBottom: 14 }}>
|
||||
{form.id ? '编辑公告' : '发布公告'}
|
||||
</h3>
|
||||
<div style={{ display: 'grid', gap: 12 }}>
|
||||
<label style={{ display: 'grid', gap: 6 }}>
|
||||
<span style={{ fontSize: 12, color: 'var(--color-text-secondary)' }}>标题</span>
|
||||
<input
|
||||
value={form.title}
|
||||
onChange={(event) => setForm((current) => ({ ...current, title: event.target.value }))}
|
||||
placeholder="例如:系统维护通知"
|
||||
style={inputStyle}
|
||||
/>
|
||||
</label>
|
||||
<label style={{ display: 'grid', gap: 6 }}>
|
||||
<span style={{ fontSize: 12, color: 'var(--color-text-secondary)' }}>公告内容</span>
|
||||
<textarea
|
||||
value={form.content}
|
||||
onChange={(event) => setForm((current) => ({ ...current, content: event.target.value }))}
|
||||
placeholder="写给普通用户看的公告内容,支持简单 Markdown。"
|
||||
rows={8}
|
||||
style={{ ...inputStyle, resize: 'vertical', lineHeight: 1.6 }}
|
||||
/>
|
||||
</label>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
|
||||
<label style={{ display: 'grid', gap: 6 }}>
|
||||
<span style={{ fontSize: 12, color: 'var(--color-text-secondary)' }}>级别</span>
|
||||
<select
|
||||
value={form.level}
|
||||
onChange={(event) => setForm((current) => ({ ...current, level: event.target.value as AnnouncementLevel }))}
|
||||
style={inputStyle}
|
||||
>
|
||||
<option value="info">普通</option>
|
||||
<option value="warning">重要</option>
|
||||
<option value="error">紧急</option>
|
||||
</select>
|
||||
</label>
|
||||
<label style={{ display: 'grid', gap: 6 }}>
|
||||
<span style={{ fontSize: 12, color: 'var(--color-text-secondary)' }}>状态</span>
|
||||
<select
|
||||
value={form.status}
|
||||
onChange={(event) => setForm((current) => ({ ...current, status: event.target.value as AnnouncementStatus }))}
|
||||
style={inputStyle}
|
||||
>
|
||||
<option value="published">发布</option>
|
||||
<option value="draft">草稿</option>
|
||||
<option value="archived">归档</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
<div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
|
||||
{form.id && (
|
||||
<button type="button" className="btn btn-ghost" onClick={resetForm}>
|
||||
取消编辑
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="btn btn-primary" onClick={submit} disabled={saving}>
|
||||
{saving ? <><span className="spinner spinner-sm" /> 保存中...</> : form.id ? '保存修改' : '发布公告'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card" style={{ padding: 0 }}>
|
||||
<div
|
||||
style={{
|
||||
padding: '14px 18px',
|
||||
borderBottom: '1px solid var(--color-border-light)',
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
gap: 12,
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: 14, fontWeight: 600 }}>公告列表</div>
|
||||
<div style={{ fontSize: 12, color: 'var(--color-text-tertiary)' }}>
|
||||
共 {rows.length} 条,已发布 {publishedCount} 条
|
||||
</div>
|
||||
</div>
|
||||
{loading ? (
|
||||
<div style={{ padding: 24, textAlign: 'center' }}>
|
||||
<span className="spinner spinner-sm" />
|
||||
</div>
|
||||
) : rows.length === 0 ? (
|
||||
<div style={{ padding: 32, textAlign: 'center' }}>
|
||||
<div className="empty-state-title">暂无公告</div>
|
||||
<div className="empty-state-desc">发布后普通用户可以在用户面板查看。</div>
|
||||
</div>
|
||||
) : (
|
||||
rows.map((row, index) => {
|
||||
const status = normalizeStatus(row.status);
|
||||
const level = normalizeLevel(row.level);
|
||||
return (
|
||||
<div
|
||||
key={row.id}
|
||||
className={`animate-slide-up stagger-${Math.min(index + 1, 5)}`}
|
||||
style={{
|
||||
padding: '16px 18px',
|
||||
borderBottom: index === rows.length - 1 ? 'none' : '1px solid var(--color-border-light)',
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, alignItems: 'flex-start', marginBottom: 8 }}>
|
||||
<div>
|
||||
<div style={{ fontSize: 15, fontWeight: 600 }}>{row.title}</div>
|
||||
<div style={{ marginTop: 5, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
|
||||
<span className={`badge ${level === 'error' ? 'badge-error' : level === 'warning' ? 'badge-warning' : 'badge-info'}`}>
|
||||
{levelLabels[level]}
|
||||
</span>
|
||||
<span className={`badge ${status === 'published' ? 'badge-success' : status === 'draft' ? 'badge-muted' : 'badge-warning'}`}>
|
||||
{statusLabels[status]}
|
||||
</span>
|
||||
<span className="badge badge-muted">已读 {row.readCount || 0}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
|
||||
<button type="button" className="btn btn-link btn-link-primary" onClick={() => editRow(row)}>
|
||||
编辑
|
||||
</button>
|
||||
<button type="button" className="btn btn-link btn-link-danger" onClick={() => removeRow(row)}>
|
||||
删除
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<SiteAnnouncementContent content={row.content} />
|
||||
<div style={{ marginTop: 8, fontSize: 12, color: 'var(--color-text-muted)' }}>
|
||||
发布时间:{row.publishedAt || row.firstSeenAt || '-'}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { userApi } from '../api.js';
|
||||
import { useToast } from '../components/Toast.js';
|
||||
import { SiteAnnouncementContent } from './helpers/siteAnnouncementPresentation.js';
|
||||
|
||||
type UserAnnouncementRow = {
|
||||
id: number;
|
||||
title: string;
|
||||
content: string;
|
||||
level: 'info' | 'warning' | 'error';
|
||||
publishedAt?: string | null;
|
||||
firstSeenAt?: string | null;
|
||||
read?: boolean;
|
||||
readAt?: string | null;
|
||||
};
|
||||
|
||||
const levelLabels = {
|
||||
info: '普通',
|
||||
warning: '重要',
|
||||
error: '紧急',
|
||||
} as const;
|
||||
|
||||
export default function UserAnnouncements() {
|
||||
const toast = useToast();
|
||||
const [rows, setRows] = useState<UserAnnouncementRow[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [markingAll, setMarkingAll] = useState(false);
|
||||
const [pending, setPending] = useState<Record<number, boolean>>({});
|
||||
|
||||
const load = async (silent = false) => {
|
||||
if (silent) setRefreshing(true);
|
||||
else setLoading(true);
|
||||
try {
|
||||
const data = await userApi.getAnnouncements();
|
||||
setRows(Array.isArray(data) ? data : []);
|
||||
} catch (error: any) {
|
||||
toast.error(error?.message || '加载公告失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setRefreshing(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, []);
|
||||
|
||||
const markRead = async (id: number) => {
|
||||
setPending((current) => ({ ...current, [id]: true }));
|
||||
try {
|
||||
await userApi.markAnnouncementRead(id);
|
||||
setRows((current) => current.map((row) => (
|
||||
row.id === id ? { ...row, read: true, readAt: new Date().toISOString() } : row
|
||||
)));
|
||||
} catch (error: any) {
|
||||
toast.error(error?.message || '标记失败');
|
||||
} finally {
|
||||
setPending((current) => ({ ...current, [id]: false }));
|
||||
}
|
||||
};
|
||||
|
||||
const markAllRead = async () => {
|
||||
setMarkingAll(true);
|
||||
try {
|
||||
await userApi.markAllAnnouncementsRead();
|
||||
const now = new Date().toISOString();
|
||||
setRows((current) => current.map((row) => ({ ...row, read: true, readAt: row.readAt || now })));
|
||||
toast.success('已全部标记为已读');
|
||||
} catch (error: any) {
|
||||
toast.error(error?.message || '标记失败');
|
||||
} finally {
|
||||
setMarkingAll(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="animate-fade-in">
|
||||
<div className="page-header">
|
||||
<h2 className="page-title">用户公告</h2>
|
||||
<div className="page-actions">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => load(true)}
|
||||
disabled={refreshing}
|
||||
className="btn btn-ghost"
|
||||
style={{ border: '1px solid var(--color-border)', padding: '8px 14px' }}
|
||||
>
|
||||
{refreshing ? <><span className="spinner spinner-sm" /> 刷新中...</> : '刷新'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={markAllRead}
|
||||
disabled={markingAll || rows.length === 0}
|
||||
className="btn btn-ghost"
|
||||
style={{ border: '1px solid var(--color-border)', padding: '8px 14px' }}
|
||||
>
|
||||
{markingAll ? <><span className="spinner spinner-sm" /> 标记中...</> : '全部已读'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card" style={{ padding: 0 }}>
|
||||
{loading ? (
|
||||
<div style={{ padding: 24, textAlign: 'center' }}>
|
||||
<span className="spinner spinner-sm" />
|
||||
</div>
|
||||
) : rows.length === 0 ? (
|
||||
<div style={{ padding: 32, textAlign: 'center' }}>
|
||||
<div className="empty-state-title">暂无公告</div>
|
||||
<div className="empty-state-desc">管理员发布的公告会显示在这里。</div>
|
||||
</div>
|
||||
) : (
|
||||
rows.map((row, index) => {
|
||||
const level = row.level === 'warning' || row.level === 'error' ? row.level : 'info';
|
||||
return (
|
||||
<div
|
||||
key={row.id}
|
||||
className={`animate-slide-up stagger-${Math.min(index + 1, 5)}`}
|
||||
style={{
|
||||
padding: '16px 18px',
|
||||
borderBottom: index === rows.length - 1 ? 'none' : '1px solid var(--color-border-light)',
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, alignItems: 'flex-start', marginBottom: 8 }}>
|
||||
<div>
|
||||
<div style={{ fontSize: 15, fontWeight: 600 }}>{row.title}</div>
|
||||
<div style={{ marginTop: 5, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
|
||||
<span className={`badge ${level === 'error' ? 'badge-error' : level === 'warning' ? 'badge-warning' : 'badge-info'}`}>
|
||||
{levelLabels[level]}
|
||||
</span>
|
||||
<span className={`badge ${row.read ? 'badge-muted' : 'badge-warning'}`}>
|
||||
{row.read ? '已读' : '未读'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{!row.read && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-link btn-link-primary"
|
||||
disabled={!!pending[row.id]}
|
||||
onClick={() => markRead(row.id)}
|
||||
>
|
||||
{pending[row.id] ? <span className="spinner spinner-sm" /> : '标记已读'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<SiteAnnouncementContent content={row.content} />
|
||||
<div style={{ marginTop: 8, fontSize: 12, color: 'var(--color-text-muted)' }}>
|
||||
发布时间:{row.publishedAt || row.firstSeenAt || '-'}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -54,23 +54,48 @@ export default function UserDashboard({ onLogout }: { onLogout?: () => void }) {
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
if (!checkAuth()) return;
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
const [profileRes, keysRes, summaryRes, logsRes] = await Promise.all([
|
||||
userApi.me(),
|
||||
userApi.getApiKeys(),
|
||||
userApi.getSummary(),
|
||||
userApi.getLogs({ limit: 5 }),
|
||||
]);
|
||||
const profileRes = await userApi.me();
|
||||
setProfile(profileRes.user);
|
||||
setKeys(Array.isArray(keysRes) ? keysRes : (keysRes.keys || []));
|
||||
setSummary(summaryRes);
|
||||
setRecentLogs(logsRes.items || []);
|
||||
} catch (err: any) {
|
||||
setError(err?.message || '加载失败');
|
||||
} finally {
|
||||
if (String(err?.message || '').includes('401') || String(err?.message || '').includes('Unauthorized')) {
|
||||
clearSession('user', localStorage);
|
||||
navigate('/user/login', { replace: true });
|
||||
}
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
}, [checkAuth]);
|
||||
|
||||
const [keysRes, summaryRes, logsRes] = await Promise.allSettled([
|
||||
userApi.getApiKeys(),
|
||||
userApi.getSummary(),
|
||||
userApi.getLogs({ limit: 5 }),
|
||||
]);
|
||||
|
||||
if (keysRes.status === 'fulfilled') {
|
||||
const payload: any = keysRes.value;
|
||||
setKeys(Array.isArray(payload) ? payload : (payload.keys || []));
|
||||
} else {
|
||||
setKeys([]);
|
||||
}
|
||||
|
||||
if (summaryRes.status === 'fulfilled') {
|
||||
setSummary(summaryRes.value as UserSummary);
|
||||
} else {
|
||||
setSummary({ totalRequests: 0, successRequests: 0, totalCost: 0 });
|
||||
}
|
||||
|
||||
if (logsRes.status === 'fulfilled') {
|
||||
const payload: any = logsRes.value;
|
||||
setRecentLogs(Array.isArray(payload?.items) ? payload.items : []);
|
||||
} else {
|
||||
setRecentLogs([]);
|
||||
}
|
||||
setLoading(false);
|
||||
}, [checkAuth, navigate]);
|
||||
|
||||
useEffect(() => { loadData(); }, [loadData]);
|
||||
|
||||
@@ -88,7 +113,15 @@ export default function UserDashboard({ onLogout }: { onLogout?: () => void }) {
|
||||
);
|
||||
}
|
||||
|
||||
if (!profile) return null;
|
||||
if (!profile) {
|
||||
return (
|
||||
<div className="page-container" style={{ padding: '24px', maxWidth: '1200px', margin: '0 auto' }}>
|
||||
<div className="card" style={{ padding: 20, color: 'var(--color-danger)' }}>
|
||||
{error || '用户信息加载失败'}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const successRate = summary && summary.totalRequests > 0
|
||||
? ((summary.successRequests / summary.totalRequests) * 100).toFixed(1)
|
||||
|
||||
@@ -0,0 +1,572 @@
|
||||
import React, { CSSProperties, useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { api, fetchSessionResponse, userApi, type WorkspaceAsset } from '../api.js';
|
||||
import type { SessionAudience } from '../authSession.js';
|
||||
|
||||
const SOURCE_OPTIONS = [
|
||||
{ value: 'all', label: '全部来源' },
|
||||
{ value: 'picture-agent', label: '生图助手' },
|
||||
{ value: 'comfyui-agent', label: '视频助手' },
|
||||
{ value: 'video-agent', label: '视频工作台' },
|
||||
{ value: 'comfyui', label: 'ComfyUI' },
|
||||
];
|
||||
|
||||
const KIND_OPTIONS = [
|
||||
{ value: 'all', label: '全部类型' },
|
||||
{ value: 'image', label: '图片' },
|
||||
{ value: 'video', label: '视频' },
|
||||
{ value: 'audio', label: '音频' },
|
||||
{ value: 'workflow', label: '工作流' },
|
||||
{ value: 'file', label: '文件' },
|
||||
];
|
||||
|
||||
function formatBytes(value?: number) {
|
||||
const bytes = Number(value || 0);
|
||||
if (!bytes) return '未记录';
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
function sourceLabel(value: string) {
|
||||
return SOURCE_OPTIONS.find((item) => item.value === value)?.label || value || '未知来源';
|
||||
}
|
||||
|
||||
function kindLabel(value: string) {
|
||||
return KIND_OPTIONS.find((item) => item.value === value)?.label || value || '文件';
|
||||
}
|
||||
|
||||
function statusLabel(value?: string) {
|
||||
if (value === 'failed') return '归档失败';
|
||||
if (value === 'pending') return '处理中';
|
||||
return '已归档';
|
||||
}
|
||||
|
||||
function assetTitle(asset: WorkspaceAsset) {
|
||||
return asset.title || asset.prompt || asset.fileName || asset.publicId;
|
||||
}
|
||||
|
||||
export default function Workspace() {
|
||||
const location = useLocation();
|
||||
const audience: SessionAudience = location.pathname.startsWith('/user/') ? 'user' : 'admin';
|
||||
const [items, setItems] = useState<WorkspaceAsset[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [source, setSource] = useState('all');
|
||||
const [kind, setKind] = useState('all');
|
||||
const [query, setQuery] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [previewUrls, setPreviewUrls] = useState<Record<string, string>>({});
|
||||
const [selectedId, setSelectedId] = useState('');
|
||||
|
||||
const selected = items.find((item) => item.publicId === selectedId) || items[0] || null;
|
||||
const sourceStats = useMemo(() => {
|
||||
const counts = new Map<string, number>();
|
||||
items.forEach((item) => counts.set(item.source, (counts.get(item.source) || 0) + 1));
|
||||
return Array.from(counts.entries())
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.slice(0, 4);
|
||||
}, [items]);
|
||||
const localCount = useMemo(() => items.filter((item) => item.hasLocalFile).length, [items]);
|
||||
|
||||
const params = useMemo(() => ({
|
||||
source: source === 'all' ? undefined : source,
|
||||
kind: kind === 'all' ? undefined : kind,
|
||||
q: query.trim() || undefined,
|
||||
page: 1,
|
||||
pageSize: 60,
|
||||
}), [kind, query, source]);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
const response = audience === 'user'
|
||||
? await userApi.getWorkspaceAssets(params)
|
||||
: await api.getWorkspaceAssets(params);
|
||||
setItems(Array.isArray(response.items) ? response.items : []);
|
||||
setTotal(Number(response.total || 0));
|
||||
setSelectedId((current) => {
|
||||
if (current && response.items?.some((item) => item.publicId === current)) return current;
|
||||
return response.items?.[0]?.publicId || '';
|
||||
});
|
||||
} catch (err: any) {
|
||||
setError(err?.message || '工作空间加载失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [audience, params]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const objectUrls: string[] = [];
|
||||
async function hydratePreviews() {
|
||||
const candidates = items
|
||||
.filter((item) => item.hasLocalFile && (item.kind === 'image' || item.kind === 'video' || item.kind === 'audio'))
|
||||
.slice(0, 24);
|
||||
const next: Record<string, string> = {};
|
||||
await Promise.all(candidates.map(async (asset) => {
|
||||
try {
|
||||
const response = await fetchSessionResponse(
|
||||
audience,
|
||||
`${audience === 'user' ? '/api/user' : '/api'}/workspace/assets/${encodeURIComponent(asset.publicId)}/file`,
|
||||
{ timeoutMs: 30_000 },
|
||||
);
|
||||
if (!response.ok) return;
|
||||
const blob = await response.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
objectUrls.push(url);
|
||||
next[asset.publicId] = url;
|
||||
} catch {
|
||||
// Preview hydration is best-effort; the asset row still remains usable.
|
||||
}
|
||||
}));
|
||||
if (!cancelled) setPreviewUrls(next);
|
||||
}
|
||||
void hydratePreviews();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
objectUrls.forEach((url) => URL.revokeObjectURL(url));
|
||||
};
|
||||
}, [audience, items]);
|
||||
|
||||
const handleDelete = async (asset: WorkspaceAsset) => {
|
||||
if (!window.confirm(`删除「${assetTitle(asset)}」?`)) return;
|
||||
try {
|
||||
if (audience === 'user') {
|
||||
await userApi.deleteWorkspaceAsset(asset.publicId);
|
||||
} else {
|
||||
await api.deleteWorkspaceAsset(asset.publicId);
|
||||
}
|
||||
await load();
|
||||
} catch (err: any) {
|
||||
setError(err?.message || '删除失败');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDownload = async (asset: WorkspaceAsset) => {
|
||||
const previewUrl = previewUrls[asset.publicId];
|
||||
const href = previewUrl || asset.remoteUrl || '';
|
||||
if (!href) return;
|
||||
const link = document.createElement('a');
|
||||
link.href = href;
|
||||
link.download = asset.fileName || `${asset.publicId}`;
|
||||
link.rel = 'noopener';
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="page-header">
|
||||
<div>
|
||||
<h1 className="page-title">工作空间</h1>
|
||||
<p className="page-subtitle">
|
||||
{audience === 'user' ? '你的创作成品库' : '全部用户的创作成品库'} · 自动归档生图助手、视频助手和 ComfyUI 产出
|
||||
</p>
|
||||
</div>
|
||||
<div className="page-actions">
|
||||
<button type="button" className="btn btn-ghost" onClick={() => void load()} disabled={loading}>
|
||||
{loading ? '刷新中...' : '刷新'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={summaryStyle}>
|
||||
<div style={summaryItemStyle}>
|
||||
<span style={summaryLabelStyle}>当前结果</span>
|
||||
<strong style={summaryValueStyle}>{total}</strong>
|
||||
</div>
|
||||
<div style={summaryItemStyle}>
|
||||
<span style={summaryLabelStyle}>本地文件</span>
|
||||
<strong style={summaryValueStyle}>{localCount}</strong>
|
||||
</div>
|
||||
<div style={summaryItemStyle}>
|
||||
<span style={summaryLabelStyle}>主要来源</span>
|
||||
<strong style={{ ...summaryValueStyle, fontSize: 14 }}>
|
||||
{sourceStats.length > 0 ? sourceStats.map(([name, count]) => `${sourceLabel(name)} ${count}`).join(' · ') : '暂无'}
|
||||
</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && <div className="alert alert-error" style={{ marginBottom: 12 }}>{error}</div>}
|
||||
|
||||
<div style={layoutStyle}>
|
||||
<section>
|
||||
<div style={toolbarStyle}>
|
||||
<input
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder="搜索标题、提示词、模型或来源"
|
||||
style={inputStyle}
|
||||
/>
|
||||
<div style={filterRowStyle}>
|
||||
{SOURCE_OPTIONS.map((option) => (
|
||||
<button
|
||||
key={option.value}
|
||||
type="button"
|
||||
style={source === option.value ? activeChipStyle : chipStyle}
|
||||
onClick={() => setSource(option.value)}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div style={filterRowStyle}>
|
||||
{KIND_OPTIONS.map((option) => (
|
||||
<button
|
||||
key={option.value}
|
||||
type="button"
|
||||
style={kind === option.value ? activeChipStyle : chipStyle}
|
||||
onClick={() => setKind(option.value)}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={gridStyle}>
|
||||
{items.length === 0 ? (
|
||||
<div className="empty-state" style={{ minHeight: 360, gridColumn: '1 / -1' }}>
|
||||
<div className="empty-state-title">{loading ? '正在加载工作空间' : '暂无成品产出'}</div>
|
||||
<div className="empty-state-desc">生图助手、视频助手和 ComfyUI 的产出会归档到这里。</div>
|
||||
</div>
|
||||
) : items.map((asset) => {
|
||||
const preview = previewUrls[asset.publicId] || asset.remoteUrl || '';
|
||||
const active = selected?.publicId === asset.publicId;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
key={asset.publicId}
|
||||
style={{
|
||||
...cardStyle,
|
||||
borderColor: active ? 'var(--color-primary)' : 'var(--color-border)',
|
||||
boxShadow: active ? '0 14px 32px color-mix(in srgb, var(--color-primary) 16%, transparent)' : undefined,
|
||||
}}
|
||||
onClick={() => setSelectedId(asset.publicId)}
|
||||
>
|
||||
<div style={thumbStyle}>
|
||||
{asset.kind === 'image' && preview ? (
|
||||
<img src={preview} alt="" style={mediaStyle} />
|
||||
) : asset.kind === 'video' && preview ? (
|
||||
<video src={preview} style={mediaStyle} muted />
|
||||
) : asset.kind === 'audio' ? (
|
||||
<div style={placeholderStyle}>音频</div>
|
||||
) : (
|
||||
<div style={placeholderStyle}>{kindLabel(asset.kind)}</div>
|
||||
)}
|
||||
<span style={typeBadgeStyle}>{kindLabel(asset.kind)}</span>
|
||||
</div>
|
||||
<div style={cardBodyStyle}>
|
||||
<strong style={cardTitleStyle}>{assetTitle(asset)}</strong>
|
||||
<span style={metaStyle}>{sourceLabel(asset.source)} · {asset.model || '未记录模型'}</span>
|
||||
<div style={cardFooterStyle}>
|
||||
<span style={statusPillStyle}>{statusLabel(asset.status)}</span>
|
||||
<span style={metaStyle}>{asset.createdAt || ''}</span>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<aside style={detailStyle}>
|
||||
{selected ? (
|
||||
<>
|
||||
<div style={detailHeaderStyle}>
|
||||
<div>
|
||||
<div style={detailEyebrowStyle}>{sourceLabel(selected.source)} · {kindLabel(selected.kind)}</div>
|
||||
<h2 style={{ margin: '6px 0 0', fontSize: 18 }}>{assetTitle(selected)}</h2>
|
||||
</div>
|
||||
<span style={statusPillStyle}>{statusLabel(selected.status)}</span>
|
||||
</div>
|
||||
<div style={detailPreviewStyle}>
|
||||
{selected.kind === 'image' && (previewUrls[selected.publicId] || selected.remoteUrl) ? (
|
||||
<img src={previewUrls[selected.publicId] || selected.remoteUrl || ''} alt="" style={mediaStyle} />
|
||||
) : selected.kind === 'video' && (previewUrls[selected.publicId] || selected.remoteUrl) ? (
|
||||
<video src={previewUrls[selected.publicId] || selected.remoteUrl || ''} controls style={mediaStyle} />
|
||||
) : selected.kind === 'audio' && previewUrls[selected.publicId] ? (
|
||||
<audio src={previewUrls[selected.publicId]} controls style={{ width: '100%' }} />
|
||||
) : (
|
||||
<div style={placeholderStyle}>{kindLabel(selected.kind)}</div>
|
||||
)}
|
||||
</div>
|
||||
<div style={detailMetaStyle}>
|
||||
<div><span>用户</span><strong>{selected.userId ?? '管理员/系统'}</strong></div>
|
||||
<div><span>模型</span><strong>{selected.model || '未记录'}</strong></div>
|
||||
<div><span>大小</span><strong>{formatBytes(selected.sizeBytes)}</strong></div>
|
||||
<div><span>文件</span><strong>{selected.hasLocalFile ? '本地归档' : '远程引用'}</strong></div>
|
||||
</div>
|
||||
{selected.prompt && (
|
||||
<div style={promptPanelStyle}>
|
||||
<span>提示词</span>
|
||||
<p style={promptStyle}>{selected.prompt}</p>
|
||||
</div>
|
||||
)}
|
||||
<div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
|
||||
<button type="button" className="btn btn-primary" onClick={() => void handleDownload(selected)}>
|
||||
下载
|
||||
</button>
|
||||
<button type="button" className="btn btn-ghost" onClick={() => void handleDelete(selected)}>
|
||||
删除
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="empty-state" style={{ minHeight: 260 }}>
|
||||
<div className="empty-state-title">选择一个成品</div>
|
||||
<div className="empty-state-desc">详情、预览和下载操作会显示在这里。</div>
|
||||
</div>
|
||||
)}
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const toolbarStyle: CSSProperties = {
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: 12,
|
||||
marginBottom: 16,
|
||||
padding: 14,
|
||||
border: '1px solid var(--color-border)',
|
||||
borderRadius: 8,
|
||||
background: 'var(--color-bg-card)',
|
||||
};
|
||||
|
||||
const inputStyle: CSSProperties = {
|
||||
height: 40,
|
||||
border: '1px solid var(--color-border)',
|
||||
borderRadius: 6,
|
||||
padding: '0 12px',
|
||||
background: 'var(--color-bg-card)',
|
||||
color: 'var(--color-text-primary)',
|
||||
};
|
||||
|
||||
const layoutStyle: CSSProperties = {
|
||||
display: 'grid',
|
||||
gridTemplateColumns: 'minmax(0, 1fr) minmax(300px, 380px)',
|
||||
gap: 16,
|
||||
alignItems: 'start',
|
||||
};
|
||||
|
||||
const gridStyle: CSSProperties = {
|
||||
display: 'grid',
|
||||
gridTemplateColumns: 'repeat(auto-fill, minmax(210px, 1fr))',
|
||||
gap: 14,
|
||||
};
|
||||
|
||||
const cardStyle: CSSProperties = {
|
||||
textAlign: 'left',
|
||||
border: '1px solid var(--color-border)',
|
||||
borderRadius: 8,
|
||||
overflow: 'hidden',
|
||||
background: 'var(--color-bg-card)',
|
||||
color: 'var(--color-text-primary)',
|
||||
padding: 0,
|
||||
cursor: 'pointer',
|
||||
transition: 'border-color 140ms ease, transform 140ms ease, box-shadow 140ms ease',
|
||||
};
|
||||
|
||||
const thumbStyle: CSSProperties = {
|
||||
position: 'relative',
|
||||
aspectRatio: '16 / 11',
|
||||
background: 'var(--color-bg-subtle)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
overflow: 'hidden',
|
||||
};
|
||||
|
||||
const mediaStyle: CSSProperties = {
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
objectFit: 'contain',
|
||||
};
|
||||
|
||||
const placeholderStyle: CSSProperties = {
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
color: 'var(--color-text-muted)',
|
||||
fontWeight: 700,
|
||||
background: 'linear-gradient(135deg, color-mix(in srgb, var(--color-primary) 10%, var(--color-bg-card)), var(--color-bg-card))',
|
||||
};
|
||||
|
||||
const cardBodyStyle: CSSProperties = {
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: 6,
|
||||
padding: 12,
|
||||
};
|
||||
|
||||
const cardTitleStyle: CSSProperties = {
|
||||
fontSize: 13,
|
||||
lineHeight: 1.35,
|
||||
whiteSpace: 'nowrap',
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
};
|
||||
|
||||
const metaStyle: CSSProperties = {
|
||||
fontSize: 12,
|
||||
color: 'var(--color-text-muted)',
|
||||
whiteSpace: 'nowrap',
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
};
|
||||
|
||||
const detailStyle: CSSProperties = {
|
||||
border: '1px solid var(--color-border)',
|
||||
borderRadius: 8,
|
||||
background: 'var(--color-bg-card)',
|
||||
padding: 16,
|
||||
position: 'sticky',
|
||||
top: 84,
|
||||
};
|
||||
|
||||
const detailPreviewStyle: CSSProperties = {
|
||||
aspectRatio: '16 / 11',
|
||||
borderRadius: 6,
|
||||
overflow: 'hidden',
|
||||
background: 'var(--color-bg-subtle)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
};
|
||||
|
||||
const detailMetaStyle: CSSProperties = {
|
||||
display: 'grid',
|
||||
gridTemplateColumns: '1fr 1fr',
|
||||
gap: 10,
|
||||
fontSize: 12,
|
||||
color: 'var(--color-text-muted)',
|
||||
marginTop: 14,
|
||||
};
|
||||
|
||||
const promptStyle: CSSProperties = {
|
||||
margin: '6px 0 0',
|
||||
color: 'var(--color-text-secondary)',
|
||||
fontSize: 13,
|
||||
lineHeight: 1.6,
|
||||
maxHeight: 160,
|
||||
overflow: 'auto',
|
||||
};
|
||||
|
||||
const summaryStyle: CSSProperties = {
|
||||
display: 'grid',
|
||||
gridTemplateColumns: '160px 160px minmax(0, 1fr)',
|
||||
gap: 12,
|
||||
marginBottom: 14,
|
||||
};
|
||||
|
||||
const summaryItemStyle: CSSProperties = {
|
||||
border: '1px solid var(--color-border)',
|
||||
borderRadius: 8,
|
||||
background: 'var(--color-bg-card)',
|
||||
padding: '12px 14px',
|
||||
minHeight: 70,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
justifyContent: 'center',
|
||||
gap: 4,
|
||||
};
|
||||
|
||||
const summaryLabelStyle: CSSProperties = {
|
||||
fontSize: 12,
|
||||
color: 'var(--color-text-muted)',
|
||||
};
|
||||
|
||||
const summaryValueStyle: CSSProperties = {
|
||||
fontSize: 22,
|
||||
color: 'var(--color-text-primary)',
|
||||
lineHeight: 1.2,
|
||||
};
|
||||
|
||||
const filterRowStyle: CSSProperties = {
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
gap: 8,
|
||||
};
|
||||
|
||||
const chipStyle: CSSProperties = {
|
||||
border: '1px solid var(--color-border)',
|
||||
borderRadius: 999,
|
||||
background: 'var(--color-bg)',
|
||||
color: 'var(--color-text-secondary)',
|
||||
padding: '7px 12px',
|
||||
cursor: 'pointer',
|
||||
fontSize: 12,
|
||||
};
|
||||
|
||||
const activeChipStyle: CSSProperties = {
|
||||
...chipStyle,
|
||||
borderColor: 'var(--color-primary)',
|
||||
background: 'var(--color-primary-light)',
|
||||
color: 'var(--color-primary)',
|
||||
fontWeight: 700,
|
||||
};
|
||||
|
||||
const typeBadgeStyle: CSSProperties = {
|
||||
position: 'absolute',
|
||||
left: 10,
|
||||
top: 10,
|
||||
borderRadius: 999,
|
||||
padding: '4px 8px',
|
||||
background: 'rgba(0, 0, 0, 0.56)',
|
||||
color: '#fff',
|
||||
fontSize: 12,
|
||||
fontWeight: 700,
|
||||
};
|
||||
|
||||
const cardFooterStyle: CSSProperties = {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
gap: 8,
|
||||
};
|
||||
|
||||
const statusPillStyle: CSSProperties = {
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
borderRadius: 999,
|
||||
padding: '4px 8px',
|
||||
background: 'color-mix(in srgb, var(--color-success) 12%, var(--color-bg-card))',
|
||||
color: 'var(--color-success)',
|
||||
fontSize: 12,
|
||||
fontWeight: 700,
|
||||
whiteSpace: 'nowrap',
|
||||
};
|
||||
|
||||
const detailHeaderStyle: CSSProperties = {
|
||||
display: 'flex',
|
||||
alignItems: 'flex-start',
|
||||
justifyContent: 'space-between',
|
||||
gap: 12,
|
||||
marginBottom: 12,
|
||||
};
|
||||
|
||||
const detailEyebrowStyle: CSSProperties = {
|
||||
fontSize: 12,
|
||||
color: 'var(--color-text-muted)',
|
||||
};
|
||||
|
||||
const promptPanelStyle: CSSProperties = {
|
||||
marginTop: 14,
|
||||
border: '1px solid var(--color-border-light)',
|
||||
borderRadius: 8,
|
||||
padding: 12,
|
||||
background: 'var(--color-bg)',
|
||||
fontSize: 12,
|
||||
color: 'var(--color-text-muted)',
|
||||
};
|
||||
@@ -8,12 +8,12 @@ import { sidebarGroups } from '../App.js';
|
||||
const { apiMock } = vi.hoisted(() => ({
|
||||
apiMock: {
|
||||
getSiteAnnouncements: vi.fn(),
|
||||
getSites: vi.fn(),
|
||||
getRuntimeSettings: vi.fn(),
|
||||
createSiteAnnouncement: vi.fn(),
|
||||
updateSiteAnnouncement: vi.fn(),
|
||||
deleteSiteAnnouncement: vi.fn(),
|
||||
markSiteAnnouncementRead: vi.fn(),
|
||||
markAllSiteAnnouncementsRead: vi.fn(),
|
||||
clearSiteAnnouncements: vi.fn(),
|
||||
syncSiteAnnouncements: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -47,44 +47,38 @@ function collectText(node: any): string {
|
||||
describe('SiteAnnouncements page', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
apiMock.getSites.mockResolvedValue([
|
||||
{ id: 9, name: 'Sub Site', platform: 'sub2api' },
|
||||
]);
|
||||
apiMock.getRuntimeSettings.mockResolvedValue({
|
||||
serverTimeZone: 'UTC',
|
||||
});
|
||||
apiMock.getSiteAnnouncements.mockResolvedValue([
|
||||
{
|
||||
id: 12,
|
||||
siteId: 9,
|
||||
platform: 'sub2api',
|
||||
sourceKey: 'announcement:12',
|
||||
title: 'Maintenance',
|
||||
content: 'Window starts at 10:00',
|
||||
title: '维护通知',
|
||||
content: '今晚 10:00 维护',
|
||||
level: 'info',
|
||||
status: 'published',
|
||||
firstSeenAt: '2026-03-20 04:23:27',
|
||||
lastSeenAt: '2026-03-20 04:23:27',
|
||||
readAt: null,
|
||||
publishedAt: '2026-03-20 04:23:27',
|
||||
readCount: 3,
|
||||
},
|
||||
]);
|
||||
apiMock.clearSiteAnnouncements.mockResolvedValue({ success: true });
|
||||
apiMock.markAllSiteAnnouncementsRead.mockResolvedValue({ success: true });
|
||||
apiMock.syncSiteAnnouncements.mockResolvedValue({ success: true, queued: true, taskId: 'task-1' });
|
||||
apiMock.createSiteAnnouncement.mockResolvedValue({ success: true });
|
||||
apiMock.updateSiteAnnouncement.mockResolvedValue({ success: true });
|
||||
apiMock.deleteSiteAnnouncement.mockResolvedValue({ success: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('exposes the renamed sidebar item and the site announcements entry', () => {
|
||||
it('exposes the user announcements sidebar entry', () => {
|
||||
const consoleGroup = sidebarGroups.find((group) => group.label === '控制台');
|
||||
const labels = (consoleGroup?.items || []).map((item) => item.label);
|
||||
|
||||
expect(labels).toContain('站点管理');
|
||||
expect(labels).toContain('站点公告');
|
||||
expect(labels).toContain('用户公告');
|
||||
});
|
||||
|
||||
it('loads announcements, highlights the focused row, and clears local rows', async () => {
|
||||
it('loads admin announcements and clears local rows', async () => {
|
||||
let root!: WebTestRenderer;
|
||||
try {
|
||||
await act(async () => {
|
||||
@@ -111,17 +105,9 @@ describe('SiteAnnouncements page', () => {
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(apiMock.getSiteAnnouncements).toHaveBeenCalled();
|
||||
expect(apiMock.getSites).toHaveBeenCalled();
|
||||
expect(apiMock.getRuntimeSettings).toHaveBeenCalled();
|
||||
expect(JSON.stringify(root!.toJSON())).toContain('站点公告');
|
||||
expect(JSON.stringify(root!.toJSON())).toContain('Maintenance');
|
||||
expect(JSON.stringify(root!.toJSON())).toContain('2026/03/20 12:23:27');
|
||||
|
||||
const highlightedRows = root!.root.findAll((node) => {
|
||||
const className = typeof node.props.className === 'string' ? node.props.className : '';
|
||||
return className.includes('row-focus-highlight') && collectText(node).includes('Maintenance');
|
||||
});
|
||||
expect(highlightedRows).toHaveLength(1);
|
||||
expect(JSON.stringify(root!.toJSON())).toContain('用户公告');
|
||||
expect(JSON.stringify(root!.toJSON())).toContain('维护通知');
|
||||
expect(JSON.stringify(root!.toJSON())).toContain('今晚 10:00 维护');
|
||||
|
||||
const clearButton = root!.root.find((node) => (
|
||||
node.type === 'button'
|
||||
|
||||
Reference in New Issue
Block a user