import { useMemo, useState } from "react"; import { useMutation, useMutationState, useQuery, useQueryClient } from "@tanstack/react-query"; import { App, Button, Dropdown, Form, Input, Modal, Popconfirm, Select, Tabs, type FormInstance } from "antd"; import { Box, Check, ChevronDown, Download, FileText, Image as ImageIcon, Link2, Music2, Plus, RefreshCw, Sparkles, Trash2, UserRound, Video, VolumeX } from "lucide-react"; import { WorkspaceState } from "@/components/layout/workspace-state"; import { AssetMediaPreview } from "@/components/asset-media-preview"; import { AssetLibraryCard, AssetLibraryCardMedia } from "@/components/assets/asset-library-card"; import { AssetLibraryPickerModal, type AssetLibraryPickerItem } from "@/components/assets/asset-library-picker-modal"; import { resolveProjectCanvasStyle } from "@/components/canvas/canvas-style-picker-modal"; import { resourceFileUrl, resourceIdFromStorageKey } from "@/services/api/resources"; import { bindProjectCharacterVoice, confirmProjectAssetCandidate, createProjectAssetVersion, createProjectCharacter, getProjectCharacter, linkProjectAsset, listVoiceProfiles, replaceProjectCharacterRepresentations, unbindProjectCharacterVoice, unlinkProjectAsset, updateProjectAssetCategory, updateProjectCharacter, type ProjectAsset, type ProjectDetail, } from "@/services/api/projects"; import { saveRemoteUserDataNow } from "@/services/user-data-sync"; import { useAssetStore, type Asset, type AssetCategory, type AssetStatus, type EntityAsset, type ImageAsset } from "@/stores/use-asset-store"; import { useConfigStore, useEffectiveConfig } from "@/stores/use-config-store"; import { saveAs } from "file-saver"; import { ProjectCharacterCard } from "./project-character-card"; import { generateCharacterTurnaround } from "./project-character-media"; import { categoryLabels, categoryLabel, mediaLabel, StatusPill, formatTime, textValue, type ProjectDetailViewProps } from "./shared"; const categories = ["all", "character", "environment", "wardrobe", "prop", "weapon", "style", "other"]; const pickerCategoryLabels = { all: "全部素材", ...categoryLabels }; const characterFields = [ ["role", "剧情定位与人物关系"], ["aliases", "别名"], ["appearance", "稳定外貌"], ["physique", "身高、体型与体态"], ["clothing", "默认服装造型"], ["personality", "性格与表演基线"], ["props", "固定道具"], ["consistencyPrompt", "跨镜头一致性约束"], ["multiViewPrompt", "三视图补充约束"], ["voiceLanguage", "语言与口音"], ["voiceAge", "声音年龄感"], ["voiceTimbre", "音色气质"], ] as const; type CharacterForm = { name: string } & Record<(typeof characterFields)[number][0], string>; export default function ProjectAssetsView({ detail, refreshProject }: ProjectDetailViewProps) { const { message } = App.useApp(); const queryClient = useQueryClient(); const personalAssets = useAssetStore((state) => state.assets); const updatePersonalAsset = useAssetStore((state) => state.updateAsset); const effectiveConfig = useEffectiveConfig(); const isAiConfigReady = useConfigStore((state) => state.isAiConfigReady); const [category, setCategory] = useState("all"); const [addOpen, setAddOpen] = useState(false); const [editorAsset, setEditorAsset] = useState(null); const [imageAsset, setImageAsset] = useState(null); const [voiceAsset, setVoiceAsset] = useState(null); const [previewAsset, setPreviewAsset] = useState(null); const [voiceProfileId, setVoiceProfileId] = useState(""); const [voiceInstructions, setVoiceInstructions] = useState(""); const [form] = Form.useForm(); const projectAssetIds = new Set(detail.assets.map((asset) => asset.id)); const availableAssets = personalAssets.filter((asset) => !projectAssetIds.has(asset.id)); const imageAssets = personalAssets.filter((asset): asset is ImageAsset => asset.kind === "image"); const availablePickerItems = useMemo(() => availableAssets.map((asset) => ({ id: asset.id, title: asset.title, category: asset.kind === "entity" ? "character" : asset.category || "other", kindLabel: mediaLabel(asset.kind), asset, description: asset.note, searchText: asset.tags.join(" "), })), [availableAssets]); const imagePickerItems = useMemo(() => imageAssets.map((asset) => ({ id: asset.id, title: asset.title, category: asset.category || "other", kindLabel: "图片", asset, searchText: asset.tags.join(" "), })), [imageAssets]); const pendingCandidates = detail.assetCandidates.filter((candidate) => candidate.category === "character" && candidate.status === "pending_confirmation"); const characterAssets = detail.assets.filter((asset) => asset.category === "character" && asset.character); const mediaAssetCount = detail.assets.filter((asset) => asset.category !== "character").length; const visibleAssets = useMemo(() => category === "all" ? detail.assets : detail.assets.filter((asset) => asset.category === category), [category, detail.assets]); const categoryCounts = categories.map((value) => ({ value, count: value === "all" ? detail.assets.length + pendingCandidates.length : detail.assets.filter((asset) => asset.category === value).length + (value === "character" ? pendingCandidates.length : 0), })); const voices = useQuery({ queryKey: ["voice-profiles"], queryFn: listVoiceProfiles, enabled: Boolean(voiceAsset) }); const generatingAssets = useMutationState({ filters: { mutationKey: ["project-character-turnaround", detail.project.id], status: "pending" }, select: (mutation) => mutation.state.variables as ProjectAsset | undefined, }); const generatingAssetIds = new Set(generatingAssets.map((asset) => asset?.id).filter((id): id is string => Boolean(id))); const done = (content: string) => { refreshProject(); message.success(content); }; const failed = (fallback: string) => (error: unknown) => message.error(error instanceof Error ? error.message : fallback); const addMutation = useMutation({ mutationFn: ({ assetId, category: nextCategory }: { assetId: string; category: string }) => linkProjectAsset(detail.project.id, { assetId, category: nextCategory }), onSuccess: ({ asset }) => { updatePersonalAsset(asset.id, { category: asset.category as AssetCategory, status: asset.status as AssetStatus, primaryVersionId: asset.primaryVersionId }); setAddOpen(false); done("资产已加入项目"); }, onError: failed("资产加入失败") }); const versionMutation = useMutation({ mutationFn: (id: string) => createProjectAssetVersion(detail.project.id, id, {}), onSuccess: () => done("已创建新版本"), onError: failed("版本创建失败") }); const unlinkMutation = useMutation({ mutationFn: (id: string) => unlinkProjectAsset(detail.project.id, id), onSuccess: () => done("资产已移出项目"), onError: failed("资产移除失败") }); const categoryMutation = useMutation({ mutationFn: ({ id, next }: { id: string; next: string }) => updateProjectAssetCategory(detail.project.id, id, next), onSuccess: ({ asset }) => { updatePersonalAsset(asset.id, { category: asset.category as AssetCategory }); done("资产分类已更新"); }, onError: failed("资产分类更新失败") }); const confirmMutation = useMutation({ mutationFn: ({ candidateId, targetAssetId }: { candidateId: string; targetAssetId?: string }) => confirmProjectAssetCandidate(detail.project.id, candidateId, targetAssetId), onSuccess: ({ asset }, variables) => { // 候选确认后先精确更新当前项,剩余队列不依赖整页异步刷新才能继续操作。 queryClient.setQueryData(["project", detail.project.id], (current) => current ? { ...current, assetCandidates: current.assetCandidates.map((candidate) => candidate.id === variables.candidateId ? { ...candidate, status: "confirmed", resolvedAssetId: asset.id, updatedAt: asset.updatedAt } : candidate), assets: current.assets.some((item) => item.id === asset.id) ? current.assets.map((item) => item.id === asset.id ? asset : item) : [asset, ...current.assets], } : current); syncPersonalCharacterProjection(asset); done(variables.targetAssetId ? "候选信息已归并到角色新版本" : "角色卡已创建"); }, onError: failed("角色确认失败"), }); const confirmingCandidateId = confirmMutation.isPending ? confirmMutation.variables?.candidateId || "" : ""; const saveCharacter = useMutation({ mutationFn: async (values: CharacterForm) => { const definition = characterDefinition(values); return editorAsset === "new" ? createProjectCharacter(detail.project.id, { name: values.name, definition }) : updateProjectCharacter(detail.project.id, editorAsset!.id, { name: values.name, definition }); }, onSuccess: (result) => { syncPersonalCharacterProjection(result.asset); setEditorAsset(null); done(editorAsset === "new" ? "角色卡已创建" : "角色设定已保存并生成新版本"); }, onError: failed("角色保存失败"), }); const generateMutation = useMutation({ mutationKey: ["project-character-turnaround", detail.project.id], mutationFn: async (asset: ProjectAsset) => { if (!asset.character) throw new Error("角色版本信息不完整"); const model = effectiveConfig.imageModel || effectiveConfig.model; const config = { ...effectiveConfig, model }; if (!isAiConfigReady(config, model)) throw new Error("请先在设置中配置可用的图片模型"); const projectStyle = resolveProjectCanvasStyle(detail.project.stylePresetId, detail.project.styleProfileJson); await generateCharacterTurnaround({ projectId: detail.project.id, assetId: asset.id, versionId: asset.character.versionId, name: asset.title, definition: asset.character.definition, projectStyle, config }); return getProjectCharacter(detail.project.id, asset.id); }, onSuccess: (result) => { syncPersonalCharacterProjection(result.asset); done("三视图已生成并绑定到新角色版本"); }, onError: failed("三视图生成失败"), }); const bindImagesMutation = useMutation({ mutationFn: async (selectedAssetId: string) => { if (!imageAsset) throw new Error("未选择角色"); await saveRemoteUserDataNow(); const latest = useAssetStore.getState().assets; const selected = latest.find((asset) => asset.id === selectedAssetId); if (selected?.kind !== "image") throw new Error("请选择一张包含正面、侧面和背面的三视图设定图"); const resourceId = resourceIdFromStorageKey((selected as ImageAsset).data.storageKey); if (!resourceId) throw new Error("所选图片尚未同步到后端资源库"); return replaceProjectCharacterRepresentations(detail.project.id, imageAsset.id, [{ role: "turnaround_sheet", resourceId, metadata: { sourceAssetId: selected.id } }, { role: "primary", resourceId, metadata: { source: "turnaround_sheet", sourceAssetId: selected.id } }]); }, onSuccess: (result) => { syncPersonalCharacterProjection(result.asset); setImageAsset(null); done("三视图已绑定到新角色版本"); }, onError: failed("三视图绑定失败"), }); const bindVoiceMutation = useMutation({ mutationFn: () => voiceAsset ? bindProjectCharacterVoice(detail.project.id, voiceAsset.id, { voiceProfileId, instructions: voiceInstructions }) : Promise.reject(new Error("未选择角色")), onSuccess: (result) => { syncPersonalCharacterProjection(result.asset); setVoiceAsset(null); done("声音素材已绑定到新角色版本"); }, onError: failed("声音绑定失败") }); const unbindVoiceMutation = useMutation({ mutationFn: () => voiceAsset ? unbindProjectCharacterVoice(detail.project.id, voiceAsset.id) : Promise.reject(new Error("未选择角色")), onSuccess: (result) => { syncPersonalCharacterProjection(result.asset); setVoiceAsset(null); done("声音绑定已解除并生成新角色版本"); }, onError: failed("声音解绑失败") }); const openCharacterEditor = (asset: ProjectAsset | "new") => { setEditorAsset(asset); const definition = asset === "new" ? {} : asset.character?.definition || {}; form.setFieldsValue({ name: asset === "new" ? "" : asset.title, ...Object.fromEntries(characterFields.map(([key]) => [key, fieldValue(definition[key])])) } as CharacterForm); }; const openImages = (asset: ProjectAsset) => setImageAsset(asset); const openVoice = (asset: ProjectAsset) => { setVoiceAsset(asset); setVoiceProfileId(asset.character?.voice?.profile.id || ""); setVoiceInstructions(asset.character?.voice?.instructions || ""); }; const downloadPreviewAsset = (asset: ProjectAsset) => { const personal = personalAssets.find((item) => item.id === asset.id); if (personal && (personal.kind === "image" || personal.kind === "video" || personal.kind === "audio" || personal.kind === "model")) { const url = personal.kind === "image" ? personal.data.dataUrl : personal.data.url; const extension = personal.kind === "model" ? personal.data.fileName.split(".").pop() || "glb" : personal.data.mimeType.split("/")[1] || "bin"; saveAs(url, `${asset.title || "asset"}.${extension}`); return; } const cover = asset.character?.representations.find((item) => item.role === "turnaround_sheet") || asset.character?.representations.find((item) => item.role === "primary") || asset.character?.representations[0]; if (cover) saveAs(resourceFileUrl(cover.resourceId), `${asset.title || "character"}.png`); else message.warning("当前资产没有可下载的媒体文件"); }; return (

角色与资产

{detail.assets.length} 项已确认
{characterAssets.length} 个角色 {mediaAssetCount} 项媒体 {pendingCandidates.length ? {pendingCandidates.length} 个待确认 : null}
{(category === "all" || category === "character") && pendingCandidates.length ? (
剧情识别出的角色
剩余 {pendingCandidates.length} 个待确认
{pendingCandidates.map((candidate) => { const confirming = confirmingCandidateId === candidate.id; return (
{candidate.name}
待确认角色卡 · 来自章节分析
{characterAssets.length ? ({ key: asset.id, label: asset.title })), onClick: ({ key }) => confirmMutation.mutate({ candidateId: candidate.id, targetAssetId: key }) }}> : null}
); })}
) : null}
{category === "all" ? "全部资产" : categoryLabel(category)}{visibleAssets.length} 项已确认
{visibleAssets.length ?
{visibleAssets.map((asset) => asset.category === "character" ? setPreviewAsset(asset)} onEdit={() => openCharacterEditor(asset)} onGenerate={() => generateMutation.mutate(asset)} onBindImages={() => openImages(asset)} onBindVoice={() => openVoice(asset)} onRemove={() => unlinkMutation.mutate(asset.id)} /> : item.id === asset.id)} onOpen={() => setPreviewAsset(asset)} onCategoryChange={(next) => categoryMutation.mutate({ id: asset.id, next })} onVersion={() => versionMutation.mutate(asset.id)} onRemove={() => unlinkMutation.mutate(asset.id)} loading={(categoryMutation.isPending && categoryMutation.variables?.id === asset.id) || (versionMutation.isPending && versionMutation.variables === asset.id) || (unlinkMutation.isPending && unlinkMutation.variables === asset.id)} />)}
: (category === "all" || category === "character") && pendingCandidates.length ? null : }
"加入项目"} emptyTitle="没有可引用的个人素材" emptyDescription="个人素材已全部加入项目,或素材库仍为空。" onClose={() => setAddOpen(false)} onConfirm={async (ids) => { const selected = personalAssets.find((asset) => asset.id === ids[0]); if (!selected) throw new Error("所选素材已不存在,请重新选择"); await addMutation.mutateAsync({ assetId: selected.id, category: selected.kind === "entity" ? "character" : selected.category || "other" }); }} /> item.id === previewAsset.id) : undefined} onClose={() => setPreviewAsset(null)} onDownload={() => previewAsset && downloadPreviewAsset(previewAsset)} onReplaceImage={() => { if (!previewAsset || previewAsset.category !== "character") return; setPreviewAsset(null); openImages(previewAsset); }} /> setEditorAsset(null)} onSave={() => form.validateFields().then((values) => saveCharacter.mutate(values))} /> "绑定并生成新版本"} emptyTitle="个人图片素材为空" emptyDescription="需要一张包含正面、侧面、背面的角色设定图。" onClose={() => setImageAsset(null)} onConfirm={async (ids) => { if (!ids[0]) throw new Error("请选择一张三视图设定图"); await bindImagesMutation.mutateAsync(ids[0]); }} /> setVoiceAsset(null)} onOk={() => bindVoiceMutation.mutate()}>
; return
角色设定

{editing ? "调整角色设定" : "建立一张角色卡"}

{input("role")}{input("aliases")}{textArea("appearance", 4)}{input("physique")}{input("clothing")}{input("props")}{textArea("consistencyPrompt", 4)}{textArea("multiViewPrompt", 3)}
}, { key: "performance", label: "表演与声音", forceRender: true, children:
{textArea("personality", 4)}{input("voiceLanguage")}{input("voiceAge")}{input("voiceTimbre")}
}]} />
; } type CharacterFormKey = (typeof characterFields)[number][0]; function MediaAssetCard({ asset, personalAsset, onOpen, onCategoryChange, onVersion, onRemove, loading }: { asset: ProjectAsset; personalAsset?: Asset; onOpen: () => void; onCategoryChange: (category: string) => void; onVersion: () => void; onRemove: () => void; loading: boolean }) { return
} />
{mediaLabel(asset.mediaType)}
value !== "character").map(([value, label]) => ({ key: value, label })), onClick: ({ key }) => onCategoryChange(key) }}>·v{Math.max(1, asset.versionCount)}
{mediaLabel(asset.mediaType)}
; } function ProjectAssetPreviewModal({ asset, personalAsset, onClose, onDownload, onReplaceImage }: { asset: ProjectAsset | null; personalAsset?: Asset; onClose: () => void; onDownload: () => void; onReplaceImage: () => void }) { const characterCover = asset?.character?.representations.find((item) => item.role === "turnaround_sheet") || asset?.character?.representations.find((item) => item.role === "primary") || asset?.character?.representations[0]; const canDownload = Boolean(personalAsset && ["image", "video", "audio", "model"].includes(personalAsset.kind)) || Boolean(characterCover); const previewClass = asset?.category === "character" ? "is-character" : personalAsset?.kind === "video" ? "is-video" : personalAsset?.kind === "audio" ? "is-audio" : personalAsset?.kind === "text" ? "is-text" : "is-image"; return ( {asset?.category === "character" ? : null}{canDownload ? : null}}> {asset ?
{asset.category === "character" ? characterCover ? {asset.title} :
: personalAsset?.kind === "video" ?
: null}
); } function characterDefinition(values: CharacterForm) { const definition: Record = Object.fromEntries(characterFields.map(([key]) => [key, values[key]?.trim() || (key === "aliases" ? [] : "")])); definition.aliases = values.aliases?.split(/[,,]/).map((item) => item.trim()).filter(Boolean) || []; return definition; } function fieldValue(value: unknown) { return Array.isArray(value) ? value.join(",") : typeof value === "string" ? value : ""; } function syncPersonalCharacterProjection(asset: ProjectAsset) { if (!asset.character) return; const current = useAssetStore.getState().assets; const existing = current.find((item) => item.id === asset.id); const cover = asset.character.representations.find((item) => item.role === "turnaround_sheet") || asset.character.representations.find((item) => item.role === "primary") || asset.character.representations.find((item) => item.role === "front"); const projected: EntityAsset = { id: asset.id, kind: "entity", title: asset.title, coverUrl: cover ? resourceFileUrl(cover.resourceId) : existing?.coverUrl || "", tags: existing?.tags || [], category: "character", status: asset.status as AssetStatus, primaryVersionId: asset.primaryVersionId, source: existing?.source || "project-character", createdAt: existing?.createdAt || asset.updatedAt, updatedAt: asset.updatedAt, data: { definition: asset.character.definition }, }; useAssetStore.getState().replaceAssets([projected, ...current.filter((item) => item.id !== asset.id)]); } function MediaIcon({ kind }: { kind: string }) { if (kind === "image") return ; if (kind === "video") return