Files
Genarrative/apps/admin-web/src/pages/AdminEditorAssetQueryPage.tsx
T
kdletters 7c449f0596 修正音频素材封面
使用用户提供的透明 PNG 替换自绘 SVG 音频封面
统一后台素材查询、精选审核、创作主页和画板素材库的音频封面引用
补齐画板图层列表音频图层封面展示
更新相关测试覆盖
2026-07-06 14:44:43 +08:00

535 lines
17 KiB
TypeScript

import { Eye, FileText, RefreshCcw, X } from 'lucide-react';
import type { ReactNode } from 'react';
import { useEffect, useState } from 'react';
import {
getAdminAssetReadUrl,
listAdminEditorAssets,
} from '../api/adminApiClient';
import type { AdminAssetReadUrlResponse } from '../api/adminApiClient';
import type {
AdminEditorAssetListQuery,
AdminEditorAssetPayload,
} from '../api/adminApiTypes';
import { handlePageError } from './pageUtils';
interface AdminEditorAssetQueryPageProps {
token: string;
onUnauthorized: (message?: string) => void;
}
const ADMIN_ASSET_READ_EXPIRE_SECONDS = 300;
const AUDIO_ASSET_COVER_SRC = '/creation-home/audio-asset-cover.png';
export function AdminEditorAssetQueryPage({
token,
onUnauthorized,
}: AdminEditorAssetQueryPageProps) {
const [entries, setEntries] = useState<AdminEditorAssetPayload[]>([]);
const [keyword, setKeyword] = useState('');
const [ownerUserId, setOwnerUserId] = useState('');
const [createdAfter, setCreatedAfter] = useState('');
const [createdBefore, setCreatedBefore] = useState('');
const [nextCursor, setNextCursor] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [isLoadingMore, setIsLoadingMore] = useState(false);
const [errorMessage, setErrorMessage] = useState('');
const [detailEntry, setDetailEntry] =
useState<AdminEditorAssetPayload | null>(null);
const [promptPreview, setPromptPreview] = useState<{
title: string;
prompt: string;
} | null>(null);
useEffect(() => {
void refreshPage();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [token, ownerUserId, keyword, createdAfter, createdBefore]);
async function refreshPage() {
setIsLoading(true);
setErrorMessage('');
try {
const response = await listAdminEditorAssets(token, buildListQuery());
setEntries(response.entries);
setNextCursor(response.nextCursor ?? null);
} catch (error: unknown) {
handlePageError(error, onUnauthorized, setErrorMessage);
} finally {
setIsLoading(false);
}
}
async function loadMore() {
if (!nextCursor || isLoadingMore) {
return;
}
setIsLoadingMore(true);
setErrorMessage('');
try {
const response = await listAdminEditorAssets(token, {
...buildListQuery(),
cursor: nextCursor,
});
setEntries((current) => mergeAssetEntries(current, response.entries));
setNextCursor(response.nextCursor ?? null);
} catch (error: unknown) {
handlePageError(error, onUnauthorized, setErrorMessage);
} finally {
setIsLoadingMore(false);
}
}
function buildListQuery(): AdminEditorAssetListQuery {
return {
ownerUserId: ownerUserId || null,
keyword: keyword.trim() || null,
createdAfter: dateInputToStartRfc3339(createdAfter),
createdBefore: dateInputToEndRfc3339(createdBefore),
limit: 80,
};
}
return (
<section className="admin-page admin-page-wide">
<div className="admin-page-heading">
<div>
<h2>素材查询</h2>
</div>
<button
className="admin-secondary-button"
disabled={isLoading}
type="button"
onClick={refreshPage}
>
<RefreshCcw size={17} aria-hidden="true" />
<span>{isLoading ? '刷新中' : '刷新'}</span>
</button>
</div>
{errorMessage ? (
<div className="admin-alert" role="status">
{errorMessage}
</div>
) : null}
<section className="admin-panel admin-stack">
<div className="admin-form-row admin-asset-query-filter-row">
<label className="admin-field">
<span>开始时间</span>
<input
type="date"
value={createdAfter}
onChange={(event) => setCreatedAfter(event.target.value)}
/>
</label>
<label className="admin-field">
<span>结束时间</span>
<input
type="date"
value={createdBefore}
onChange={(event) => setCreatedBefore(event.target.value)}
/>
</label>
<label className="admin-field">
<span>用户 ID</span>
<input
value={ownerUserId}
onChange={(event) => setOwnerUserId(event.target.value)}
/>
</label>
<label className="admin-field">
<span>搜索</span>
<input
placeholder="素材名 / 用户 / 模型 / 提示词"
value={keyword}
onChange={(event) => setKeyword(event.target.value)}
/>
</label>
</div>
<div className="admin-table-wrap">
<table className="admin-table admin-table-wide admin-asset-query-table">
<thead>
<tr>
<th>资源图</th>
<th>创建时间</th>
<th>用户</th>
<th>提示词</th>
<th>生成成本</th>
<th>详情</th>
</tr>
</thead>
<tbody>
{entries.map((entry) => {
const promptText = entry.prompt || entry.actualPrompt || '-';
return (
<tr key={entry.assetId}>
<td>
<button
className="admin-asset-query-thumb-button"
title="查看详情"
type="button"
onClick={() => setDetailEntry(entry)}
>
<AdminAssetThumbnail entry={entry} />
</button>
<small>{entry.label || '-'}</small>
</td>
<td>{formatDateTime(entry.createdAt)}</td>
<td>
{authorDisplayName(entry)}
<small>{entry.authorPublicUserCode?.trim() || '-'}</small>
</td>
<td>
<button
className="admin-text-button admin-asset-query-prompt-text"
disabled={promptText === '-'}
title={promptText}
type="button"
onClick={() =>
setPromptPreview({
title: entry.label || entry.assetId,
prompt: promptText,
})
}
>
{promptText}
</button>
</td>
<td>{entry.generationCostMudPoints} 泥点</td>
<td>
<button
className="admin-secondary-button"
type="button"
onClick={() => setDetailEntry(entry)}
>
<Eye size={16} aria-hidden="true" />
<span>详情</span>
</button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
{!isLoading && entries.length === 0 ? (
<div className="admin-empty-state">暂无生成素材</div>
) : null}
{nextCursor ? (
<button
className="admin-secondary-button"
disabled={isLoadingMore}
type="button"
onClick={loadMore}
>
<span>{isLoadingMore ? '读取中' : '读取更多'}</span>
</button>
) : null}
</section>
{detailEntry ? (
<AdminAssetDetailDialog
entry={detailEntry}
onClose={() => setDetailEntry(null)}
onPromptPreview={(entry, prompt) =>
setPromptPreview({
title: entry.label || entry.assetId,
prompt,
})
}
/>
) : null}
{promptPreview ? (
<div className="admin-confirm-backdrop" role="presentation">
<section
className="admin-detail-panel admin-asset-query-prompt-dialog"
role="dialog"
aria-modal="true"
aria-labelledby="admin-asset-query-prompt-dialog-title"
>
<div className="admin-panel-heading">
<div>
<h3 id="admin-asset-query-prompt-dialog-title">完整提示词</h3>
<span>{promptPreview.title}</span>
</div>
<button
aria-label="关闭完整提示词"
className="admin-ghost-button"
type="button"
onClick={() => setPromptPreview(null)}
>
<X size={17} aria-hidden="true" />
</button>
</div>
<pre className="admin-code-block admin-asset-query-prompt-full">
{promptPreview.prompt}
</pre>
</section>
</div>
) : null}
</section>
);
}
function AdminAssetThumbnail({ entry }: { entry: AdminEditorAssetPayload }) {
const isAudio = isAdminAudioAsset(entry);
const imageSrc = useAdminResolvedAssetImageSrc(
isAudio ? AUDIO_ASSET_COVER_SRC : entry.thumbnailSrc || entry.imageSrc,
isAudio ? null : entry.objectKey,
);
const alt = `素材:${entry.label || entry.assetId}`;
return imageSrc ? (
<img alt={alt} className="admin-asset-query-thumb" src={imageSrc} />
) : (
<div className="admin-asset-query-thumb admin-asset-query-thumb-placeholder" />
);
}
function isAdminAudioAsset(entry: AdminEditorAssetPayload) {
const assetKind = entry.assetKind?.trim() ?? '';
return (
assetKind === 'sound-effect' ||
assetKind === 'background-music' ||
assetKind === 'editor_uploaded_audio' ||
/\.(?:mp3|wav|m4a|aac|ogg)(?:$|[?#])/iu.test(entry.imageSrc.trim())
);
}
function AdminAssetDetailDialog({
entry,
onClose,
onPromptPreview,
}: {
entry: AdminEditorAssetPayload;
onClose: () => void;
onPromptPreview: (entry: AdminEditorAssetPayload, prompt: string) => void;
}) {
const promptText = entry.prompt || entry.actualPrompt || '';
return (
<div className="admin-confirm-backdrop" role="presentation">
<section
aria-label="素材详情"
className="admin-detail-panel admin-asset-query-detail-dialog"
role="dialog"
>
<div className="admin-panel-heading">
<div>
<h3>{entry.label || entry.assetId}</h3>
<span>{entry.assetId}</span>
</div>
<button
aria-label="关闭详情"
className="admin-ghost-button"
type="button"
onClick={onClose}
>
<X size={17} aria-hidden="true" />
</button>
</div>
<div className="admin-asset-query-detail-layout">
<AdminAssetThumbnail entry={entry} />
<dl className="admin-info-list admin-detail-list">
<AdminInfoItem label="作者">
{authorDisplayName(entry)}
<small>{entry.authorPublicUserCode?.trim() || '-'}</small>
</AdminInfoItem>
<AdminInfoItem label="用户 ID">{entry.ownerUserId}</AdminInfoItem>
<AdminInfoItem label="尺寸">
{entry.width} x {entry.height}
</AdminInfoItem>
<AdminInfoItem label="成本">
{entry.generationCostMudPoints} 泥点
</AdminInfoItem>
<AdminInfoItem label="模型">{entry.model || '-'}</AdminInfoItem>
<AdminInfoItem label="Provider">
{entry.provider || '-'}
</AdminInfoItem>
<AdminInfoItem label="Task ID">{entry.taskId || '-'}</AdminInfoItem>
<AdminInfoItem label="Object Key">
{entry.objectKey || '-'}
</AdminInfoItem>
<AdminInfoItem label="创建时间">
{formatDateTime(entry.createdAt)}
</AdminInfoItem>
<AdminInfoItem label="更新时间">
{formatDateTime(entry.updatedAt)}
</AdminInfoItem>
<AdminInfoItem label="提示词">
{promptText ? (
<button
className="admin-text-button"
type="button"
onClick={() => onPromptPreview(entry, promptText)}
>
<FileText size={13} aria-hidden="true" />
<span>完整提示词</span>
</button>
) : (
'-'
)}
</AdminInfoItem>
<AdminInfoItem label="生成输入">
<pre className="admin-code-block">
{formatGenerationInputs(entry.generationInputs)}
</pre>
</AdminInfoItem>
</dl>
</div>
</section>
</div>
);
}
function AdminInfoItem({
label,
children,
}: {
label: string;
children: ReactNode;
}) {
return (
<div>
<dt>{label}</dt>
<dd>{children}</dd>
</div>
);
}
function useAdminResolvedAssetImageSrc(
imageSrc: string | null | undefined,
objectKey: string | null | undefined,
) {
const normalizedImageSrc = imageSrc?.trim() ?? '';
const normalizedObjectKey = normalizeAdminObjectKey(objectKey);
const shouldResolve =
Boolean(normalizedObjectKey) || isGeneratedLegacyPath(normalizedImageSrc);
const [resolvedImageSrc, setResolvedImageSrc] = useState(
shouldResolve ? '' : normalizedImageSrc,
);
useEffect(() => {
if (!normalizedImageSrc && !normalizedObjectKey) {
setResolvedImageSrc('');
return;
}
if (!shouldResolve) {
setResolvedImageSrc(normalizedImageSrc);
return;
}
let cancelled = false;
setResolvedImageSrc('');
void getAdminAssetReadUrl(
normalizedObjectKey
? {
objectKey: normalizedObjectKey,
expireSeconds: ADMIN_ASSET_READ_EXPIRE_SECONDS,
}
: {
legacyPublicPath: normalizedImageSrc,
expireSeconds: ADMIN_ASSET_READ_EXPIRE_SECONDS,
},
)
.then(resolveAdminAssetReadSignedUrl)
.then((signedUrl) => {
if (!cancelled) {
setResolvedImageSrc(signedUrl);
}
})
.catch(() => {
if (!cancelled) {
setResolvedImageSrc('');
}
});
return () => {
cancelled = true;
};
}, [normalizedImageSrc, normalizedObjectKey, shouldResolve]);
return resolvedImageSrc;
}
function normalizeAdminObjectKey(value: string | null | undefined) {
return value?.trim().replace(/^\/+/u, '') ?? '';
}
function isGeneratedLegacyPath(value: string) {
return /^\/?generated-[^/?#]+\/.+/u.test(value.trim());
}
function resolveAdminAssetReadSignedUrl(response: AdminAssetReadUrlResponse) {
const read = response.read ?? response;
return typeof read.signedUrl === 'string' ? read.signedUrl.trim() : '';
}
function mergeAssetEntries(
current: AdminEditorAssetPayload[],
incoming: AdminEditorAssetPayload[],
) {
const byId = new Map<string, AdminEditorAssetPayload>();
[...current, ...incoming].forEach((entry) => byId.set(entry.assetId, entry));
return [...byId.values()].sort(
(left, right) =>
parseAdminTimestamp(right.createdAt) -
parseAdminTimestamp(left.createdAt) ||
right.assetId.localeCompare(left.assetId),
);
}
function dateInputToStartRfc3339(value: string) {
return value ? `${value}T00:00:00+08:00` : null;
}
function dateInputToEndRfc3339(value: string) {
return value ? `${value}T23:59:59.999+08:00` : null;
}
function formatDateTime(value: string) {
const timestamp = parseAdminTimestamp(value);
if (!Number.isFinite(timestamp)) {
return value || '-';
}
return new Intl.DateTimeFormat('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
}).format(timestamp);
}
function parseAdminTimestamp(value: string | null | undefined) {
const normalizedValue = value?.trim() ?? '';
const secondsMicrosMatch = normalizedValue.match(/^(-?\d+)\.(\d{6})Z$/u);
if (secondsMicrosMatch) {
const seconds = Number(secondsMicrosMatch[1]);
const micros = Number(secondsMicrosMatch[2]);
if (Number.isFinite(seconds) && Number.isFinite(micros)) {
return seconds * 1000 + Math.floor(micros / 1000);
}
}
return Date.parse(normalizedValue);
}
function authorDisplayName(entry: AdminEditorAssetPayload) {
return (
entry.authorDisplayName?.trim() || entry.authorPublicUserCode?.trim() || '-'
);
}
function formatGenerationInputs(
value: Record<string, unknown> | null | undefined,
) {
if (!value) {
return '-';
}
return JSON.stringify(value, null, 2);
}