2050 lines
113 KiB
TypeScript
2050 lines
113 KiB
TypeScript
/**
|
||
* 平台资产库(跨项目复用的母版:人物 / 场景 / 声线)。
|
||
*
|
||
* 三个视角共用一套筛选条件:
|
||
* · 网格 —— 卡片信息最全,一屏两张,缩略图 / 音频 / 动作都在卡里;
|
||
* · 列表 —— 一行一个母版,专为批量勾选与巡检设计;
|
||
* · 素材墙 —— 跨母版直接翻图片与音频,找一张定妆图不必先猜它挂在哪个角色下。
|
||
*
|
||
* 迁移时保留的几条旧站教训(原文在 .local/vue-ref/src/views/AssetLibrary.vue):
|
||
* · AS-1:AI 生成表单从每张卡片里挪进右侧抽屉。以前每张卡塞一个 600px 表单,
|
||
* 三个人物就能把页面撑出三屏;卡片上只留「AI 生成」入口。
|
||
* · AS-2:所有维度都由后端过滤,前端只负责拼参数与回显,不再自己维护第二套分页。
|
||
* · AS-9:「筛选无结果」和「本来就是空的」是两件事,空态文案与出口都不同。
|
||
* · AS-10:Shift 范围选择 + 全选本页筛选结果;批量动手前先摊开影响面。
|
||
* · 「素材类型」下拉只列当前大分类该有的类型 —— 直接在「人物」下筛「音色样本」
|
||
* 永远 0 条,用户会以为数据丢了。
|
||
* · 模型注册表不参与首屏:/api/providers 是全站最慢的接口,以前和素材列表一起
|
||
* await,白屏时间全被它一个人占走。
|
||
*
|
||
* React 侧的两处结构性改动(行为不变):
|
||
* · 搜索框与生效关键词分开存:输入框即时回显,320ms 防抖后才进请求;其余筛选
|
||
* 条件在 React 里天然合并成一次渲染,不再需要旧站那个 30ms 的 setTimeout 合并。
|
||
* · 版本角标不再由页面传 badge:MediaThumb 自己会显示「v4 · 4版」并挂在左下角,
|
||
* 旧站那张「角标被删除 × 压住」的补丁(把角标让到 right:25px)可以退役了。
|
||
*/
|
||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||
import { Link } from 'react-router-dom'
|
||
import * as api from '../api/client'
|
||
import { fmtAgo, fmtBytes, opt, statusLabel } from '../lib/format'
|
||
import { fromAsset, isAudio as audioOf, isImage as imageOf, type MediaItem } from '../lib/media'
|
||
import { defaultAssetName, existingNames, keepOrRestoreCurrent } from '../lib/versions'
|
||
import { cn } from '../lib/cn'
|
||
import {
|
||
capsOfRef, defaultFor, imageAspectChoices, imageCanvas, imageTiers, isMock, loadModels,
|
||
modelsOf, parseRef, refOf, useModelsStore, type Caps, type ModelRow
|
||
} from '../stores/models'
|
||
import { MultiSelect, Select } from '../components/forms'
|
||
import { AudioPlay } from '../components/media/AudioPlay'
|
||
import { MediaThumb } from '../components/media/MediaThumb'
|
||
import { RecordAudio, type RecordPickMeta } from '../components/media/RecordAudio'
|
||
import { useAutoRefresh } from '../hooks'
|
||
import { useRecordingBusy } from '../stores/recording'
|
||
import {
|
||
BarRight, Between, Button, Chip, ChipBar, Check, Ctlbar, Drawer, Empty, ErrorText, Field, FieldBlock,
|
||
FilePick, FormGrid, FormRow, Grid, LINK_CLS, Modal, MONO, MUTED, MUTED_MONO, Notice, PageHead, Pager, Panel, PanelHead,
|
||
Row, SectionTitle, Spinner, Tag, TagGroup, TEXTAREA_TALL, ViewBtn
|
||
} from '../components/ui'
|
||
|
||
type AssetType = 'human' | 'scene' | 'voice'
|
||
type ViewMode = 'grid' | 'list' | 'media'
|
||
type BatchDialog = '' | 'tag' | 'delete' | 'media-delete'
|
||
|
||
/** 左侧大分类导航:图标 / 说明 / 眉标一次给全,新增分类只改这一张表 */
|
||
const TYPE_META: Record<AssetType, { label: string; icon: string; hint: string }> = {
|
||
human: { label: '人物', icon: '☺', hint: '定妆、造型与角色一致性' },
|
||
scene: { label: '场景', icon: '▧', hint: '空间、光线与美术基调' },
|
||
voice: { label: '声线', icon: '◉', hint: '音色样本与方言 / 情绪参数' }
|
||
}
|
||
const TYPE_KEYS: AssetType[] = ['human', 'scene', 'voice']
|
||
/** 每个大分类允许登记的素材类型:既是上传下拉的选项,也是「素材类型」筛选的兜底 */
|
||
const UPLOAD_KINDS: Record<AssetType, string[]> = {
|
||
human: ['portrait', 'turnaround', 'costume', 'expression', 'reference'],
|
||
scene: ['scene_image', 'reference'],
|
||
voice: ['voice_sample', 'reference']
|
||
}
|
||
/** 保存时走的 REST 路径段(删除/上传用的是 owner_type 本身,不需要映射) */
|
||
const SAVE_PATH: Record<AssetType, string> = { human: 'characters', scene: 'scenes', voice: 'voices' }
|
||
const DEFAULT_KIND: Record<AssetType, string> = { human: 'portrait', scene: 'scene_image', voice: 'voice_sample' }
|
||
const GEN_ASPECT: Record<AssetType, string> = { human: '3:4', scene: '16:9', voice: '16:9' }
|
||
/** 后端 sorts 缺失时的兜底;正常情况用接口回吐的那份,避免两边排序名各写一遍 */
|
||
const SORT_FALLBACK = [
|
||
{ value: 'updated', label: '按更新时间' }, { value: 'created', label: '按创建时间' },
|
||
{ value: 'name', label: '按名称' }, { value: 'media', label: '按素材数量' },
|
||
{ value: 'size', label: '按素材体积' }, { value: 'usage', label: '按被引用项目数' }
|
||
]
|
||
const WALL_SORTS = [
|
||
{ value: 'created', label: '按上传时间' }, { value: 'size', label: '按文件体积' },
|
||
{ value: 'name', label: '按名称' }, { value: 'version', label: '按版本数' }
|
||
]
|
||
/** 0 = 全部:分页大小只出现在 Pager 里(UI规范 §5),筛选栏不再放第二处 */
|
||
const PAGE_SIZES = [24, 60, 120, 0]
|
||
const ROLES = ['主角', '配角', '反派', '旁白', '群众']
|
||
const GENDERS = [
|
||
{ value: '', label: '未指定' }, { value: 'female', label: '女声' },
|
||
{ value: 'male', label: '男声' }, { value: 'neutral', label: '中性' }
|
||
]
|
||
/**
|
||
* 「外星低吼」是 macOS 系统语音适配器的滤镜参数,IndexTTS2 等模型会忽略它。
|
||
* 后端整字典覆盖 tuning,已保留的采样率等参数不会被这次保存清掉。
|
||
*/
|
||
const EFFECTS = [
|
||
{ value: '', label: '真实人声' },
|
||
{ value: 'alien', label: '外星低吼(仅 macos-say 支持)' }
|
||
]
|
||
|
||
const VIEW_ITEMS: { value: ViewMode; label: ReactNode; hint: string }[] = [
|
||
{ value: 'grid', label: <><i className="not-italic text-caption">▦</i>网格</>, hint: '网格视图:卡片信息最全' },
|
||
{ value: 'list', label: <><i className="not-italic text-caption">☰</i>列表</>, hint: '列表视图:一屏看更多母版,便于批量勾选' },
|
||
{ value: 'media', label: <><i className="not-italic text-caption">▣</i>全部素材</>, hint: '素材墙:跨母版直接翻图片 / 音频' }
|
||
]
|
||
|
||
/** 新建 / 编辑表单的初值。旧站一张表混三类字段,这里照搬以免漏字段被后端当成「清空」 */
|
||
function blankForm(kind: AssetType) {
|
||
return {
|
||
type: kind, name: '', code: '', role: '主角', appearance: '', personality: '',
|
||
persona_prompt: '', voice_profile: '', default_voice_id: null as number | null, style_version: 'v1',
|
||
tags: '', notes: '', is_active: true, description: '', prompt: '', lighting: '',
|
||
time_of_day: '', palette: '', provider: '',
|
||
provider_voice_id: '', language: 'zh-CN', gender: '', version: 'v1',
|
||
is_default: false, tuning: {} as Record<string, any>, tuning_speed: 1, tuning_effect: ''
|
||
}
|
||
}
|
||
type MasterForm = ReturnType<typeof blankForm>
|
||
|
||
/** 生成抽屉的一条草稿:按「分类:id」存,切回卡片时不丢已经填好的提示词 */
|
||
type GenDraft = {
|
||
model: string
|
||
kind: string
|
||
prompt: string
|
||
sample_text: string
|
||
reference_media_id: number | null
|
||
reference_media_ids: number[]
|
||
tier: string
|
||
aspect: string
|
||
}
|
||
const BLANK_DRAFT: GenDraft = {
|
||
model: '', kind: '', prompt: '', sample_text: '',
|
||
reference_media_id: null, reference_media_ids: [], tier: '', aspect: '16:9'
|
||
}
|
||
|
||
/* ── 纯函数:素材判定 / 缩略图队列 / 版本说明 ─────────────────────────── */
|
||
|
||
/** 平台素材没有 mime 字段,靠 path 扩展名 + 业务 kind 判定即可(有宽高能兜底) */
|
||
function isImage(item: any) {
|
||
return imageOf(item?.path || item?.url, item?.kind) || Boolean(item?.width)
|
||
}
|
||
function isAudio(item: any) {
|
||
return audioOf(item?.path || item?.url, item?.kind)
|
||
}
|
||
|
||
/** 卡片/列表里的图片条:列表视图只露前 N 张,其余到预览器里翻 */
|
||
function stripOf(row: any, limit = 99) {
|
||
return (row.assets || []).filter((item: any) => !isAudio(item)).slice(0, limit)
|
||
}
|
||
function itemsOf(row: any): MediaItem[] {
|
||
return (row?.assets || []).map((media: any) => fromAsset(media)).filter(Boolean) as MediaItem[]
|
||
}
|
||
/** MediaThumb 的 ←/→ 队列需要 item 在队列里的下标,统一用归一化后的 key 对齐 */
|
||
function mediaIndex(row: any, media: any): number {
|
||
const key = fromAsset(media)?.key
|
||
const at = itemsOf(row).findIndex((item) => item.key === key)
|
||
return at < 0 ? 0 : at
|
||
}
|
||
function latestImage(row: any, kinds: string[] = []) {
|
||
return [...(row.assets || [])]
|
||
.filter((asset: any) => isImage(asset) && (!kinds.length || kinds.includes(asset.kind)))
|
||
.sort((a: any, b: any) => Number(b.id) - Number(a.id))[0] || null
|
||
}
|
||
|
||
function splitTags(value: string) {
|
||
return String(value || '').split(/[,,\s]+/).map((item) => item.trim()).filter(Boolean)
|
||
}
|
||
|
||
/** 「引入到哪个项目」下拉里的副标题:已经收尾的项目不再报「导出完整视频」 */
|
||
function projectHint(p: any) {
|
||
return p?.status === 'delivered' || p?.status === 'archived' ? statusLabel(p.status) : p?.stage_label || '准备中'
|
||
}
|
||
|
||
/**
|
||
* 音频控件右侧那截灰色小字:说清「现在是第几版 / 一共几版」,
|
||
* 多版素材一眼就知道还能去预览器里管版本。
|
||
*/
|
||
function versionHint(media: any) {
|
||
const total = (media?.versions || []).length || media?.version_count || 1
|
||
return total > 1 ? `v${media.version} · 共 ${total} 版` : `v${media.version}`
|
||
}
|
||
|
||
/**
|
||
* 素材出身标记:AI 试听样本能配音,但**不能**反过来当克隆参考。
|
||
* 少了这一层,用户会以为「列表里有声音文件 = 这角色有自己的嗓子」,
|
||
* 于是缺真人参考时反复重新生成——每次都在克隆上一次那个错的女声。
|
||
*/
|
||
function provenanceBadge(media: any) {
|
||
if (!isAudio(media) || !media?.metadata?.generated) return ''
|
||
return '模型生成的试听样本:可用于镜头配音,但不会作为下次生成的克隆参考。'
|
||
+ '要给这个角色固定嗓子,请上传一段真人参考音频。'
|
||
}
|
||
|
||
/**
|
||
* 音色自检标记。后端生成试听时会量一次中位基频,和声线设定的性别比对
|
||
* (见 services/timbre.py):zero-shot 克隆模型只认参考音频,表单里填「男声」
|
||
* 并不会让它变成男声,所以必须由界面把实测结论摊开说,而不是让用户自己听出来。
|
||
*/
|
||
function timbreBadge(media: any): { tone: 'ok' | 'bad' | 'warn'; label: string; title: string } | null {
|
||
const check = media?.metadata?.timbre_check
|
||
if (!check || !check.f0_hz) return null
|
||
if (check.matched === false) {
|
||
return { tone: 'bad', label: `音色不符 · ${check.timbre_gender_label}`, title: check.note }
|
||
}
|
||
if (check.matched === true) {
|
||
return { tone: 'ok', label: `音色一致 · ${check.timbre_gender_label}`, title: check.note }
|
||
}
|
||
return { tone: 'warn', label: `基频 ${check.f0_hz} Hz`, title: check.note }
|
||
}
|
||
|
||
function isAudioPath(value: any) {
|
||
return /\.(wav|mp3|m4a|aac|flac|ogg|opus)(?:[?#].*)?$/i.test(String(value || ''))
|
||
}
|
||
|
||
/* ══════════════════════════════════════════════════════════════════════
|
||
* 页面主体
|
||
* ══════════════════════════════════════════════════════════════════════ */
|
||
|
||
type FilterState = {
|
||
tag: string; kind: string; has_media: string; status: string
|
||
duplicate_only: boolean; sort: string; page_size: number; page: number
|
||
}
|
||
|
||
export default function AssetLibrary() {
|
||
/* ── 视角与筛选条件 ────────────────────────────────────────────── */
|
||
const [type, setType] = useState<AssetType>('human')
|
||
const [view, setView] = useState<ViewMode>('grid')
|
||
/** 输入框里的原始关键词,只负责即时回显 */
|
||
const [search, setSearch] = useState('')
|
||
/** 防抖 320ms 后才进请求:旧站每敲一个字打一次接口,中文输入法还连着发半截拼音 */
|
||
const [keyword, setKeyword] = useState('')
|
||
const [filters, setFilters] = useState<FilterState>({
|
||
tag: '', kind: '', has_media: '', status: '', duplicate_only: false,
|
||
sort: 'updated', page_size: 60, page: 1
|
||
})
|
||
/** 素材墙自己的条件(排序 / 仅多版本 / 页码);每页大小与母版视角共用 */
|
||
const [wallQuery, setWallQuery] = useState({ sort: 'created', multi_only: false, page: 1 })
|
||
|
||
/* ── 数据 ─────────────────────────────────────────────────────── */
|
||
const [rows, setRows] = useState<any[]>([])
|
||
const [stats, setStats] = useState<any>({})
|
||
const [meta, setMeta] = useState<{ tags: any[]; sorts: any[] }>({ tags: [], sorts: [] })
|
||
const [summary, setSummary] = useState({ filtered: 0, page: 1, pages: 1 })
|
||
const [projects, setProjects] = useState<any[]>([])
|
||
const [voices, setVoices] = useState<any[]>([])
|
||
const [wall, setWall] = useState<{ items: any[]; stats: any; kinds: any[]; total: number; page: number; pages: number }>(
|
||
{ items: [], stats: {}, kinds: [], total: 0, page: 1, pages: 1 })
|
||
|
||
/* ── 多选(AS-10)────────────────────────────────────────────── */
|
||
const [selected, setSelected] = useState<Set<string>>(() => new Set())
|
||
const [selectedMedia, setSelectedMedia] = useState<Set<number>>(() => new Set())
|
||
const lastIndex = useRef(-1)
|
||
const lastMediaIndex = useRef(-1)
|
||
|
||
/* ── 弹层 ─────────────────────────────────────────────────────── */
|
||
const [drawer, setDrawer] = useState(false)
|
||
const [editingId, setEditingId] = useState<number | null>(null)
|
||
const [form, setForm] = useState<MasterForm>(() => blankForm('human'))
|
||
const [confirmDelete, setConfirmDelete] = useState<any | null>(null)
|
||
/** 待引入的母版:第 0 条就是对话框上要念出来的主角,数组非空即打开(旧站另开一个 importAsset 状态,两处会不同步)*/
|
||
const [importTargets, setImportTargets] = useState<any[]>([])
|
||
const [importProjectId, setImportProjectId] = useState<number | null>(null)
|
||
const [batchDialog, setBatchDialog] = useState<BatchDialog>('')
|
||
const [batchTags, setBatchTags] = useState({ add: '', remove: '' })
|
||
const [genTarget, setGenTarget] = useState<any | null>(null)
|
||
const [genDrawer, setGenDrawer] = useState(false)
|
||
/** 生成草稿按「分类:id」存:旧站把表单挂在行对象上,刷新列表时整行被替换,填了一半的提示词就没了 */
|
||
const [generation, setGeneration] = useState<Record<string, GenDraft>>({})
|
||
/** 每张卡片上传下拉当前选中的素材类型(不写进母版数据,纯界面态)*/
|
||
const [uploadKinds, setUploadKinds] = useState<Record<string, string>>({})
|
||
const [voiceRefStatus, setVoiceRefStatus] = useState<any | null>(null)
|
||
const [voiceRefBusy, setVoiceRefBusy] = useState(false)
|
||
const [error, setError] = useState('')
|
||
const [notice, setNotice] = useState('')
|
||
const [busy, setBusy] = useState('')
|
||
|
||
/* ── 模型注册表:不参与首屏,见文件头 AS 注释 ─────────────────── */
|
||
const registryRows = useModelsStore((s) => s.rows)
|
||
const registryBusy = useModelsStore((s) => s.busy)
|
||
const registryError = useModelsStore((s) => s.error)
|
||
/** 只认注册表:mock 演练通道不出正式素材,所以 includeMock=false */
|
||
const imageModels = useMemo(() => modelsOf('image', false), [registryRows])
|
||
const ttsModels = useMemo(() => modelsOf('tts', false), [registryRows])
|
||
const genModels = type === 'voice' ? ttsModels : imageModels
|
||
|
||
const recordingBusy = useRecordingBusy()
|
||
/** 有弹窗 / 抽屉 / 批量确认挡在页面上时暂停自动刷新,避免列表在用户手下换人 */
|
||
const modalOpen = drawer || genDrawer || !!confirmDelete || importTargets.length > 0 || !!batchDialog
|
||
|
||
/* ── 派生:统计、分页口径、筛选项 ─────────────────────────────── */
|
||
const totals = useMemo(() => {
|
||
const byOwner = stats.by_owner || {}
|
||
return {
|
||
human: Number(byOwner.human || 0), scene: Number(byOwner.scene || 0), voice: Number(byOwner.voice || 0),
|
||
media: Number(stats.media_count || 0)
|
||
}
|
||
}, [stats])
|
||
const sortOptions: any[] = meta.sorts?.length ? meta.sorts : SORT_FALLBACK
|
||
const tagOptions: any[] = meta.tags || []
|
||
const resultCount = Number(summary.filtered ?? rows.length)
|
||
const filtersActive = Boolean(keyword.trim() || filters.tag || filters.kind || filters.has_media
|
||
|| filters.status || filters.duplicate_only || filters.page > 1)
|
||
|
||
/**
|
||
* 「素材类型」选项:只列**当前大分类**该有的类型。
|
||
*
|
||
* 之前直接用全库 by_kind,于是在「人物」下能筛「音色样本 / 场景图」——选了永远 0 条。
|
||
* 数据源分两种视角:素材墙用墙自己的 by_kind(后端已按 owner_type 过滤),
|
||
* 母版视角用 stats.by_kind_by_owner[type];两者都拿不到的空分类,退回该分类的
|
||
* 登记类型清单(UPLOAD_KINDS),保证下拉不为空且仍属于这个大分类。
|
||
*
|
||
* 写成接收 type 的纯函数,是为了让 chooseType() 在**同一个事件里**就能判断
|
||
* 「原来选中的类型还属不属于新分类」——旧站靠 watcher 事后清,会先闪一屏 0 条。
|
||
*/
|
||
function kindOptionsFor(next: AssetType) {
|
||
const scoped: Record<string, number> = view === 'media'
|
||
? (wall.stats?.by_kind || {})
|
||
: ((stats.by_kind_by_owner || {})[next] || {})
|
||
const seen: string[] = view === 'media'
|
||
? (wall.kinds || []).map((k: any) => String(k.value))
|
||
: Object.keys(scoped)
|
||
const canonical = UPLOAD_KINDS[next]
|
||
const keys = [...new Set([...canonical, ...seen])]
|
||
.filter((key) => Number(scoped[key] || 0) > 0 || seen.includes(key))
|
||
if (!keys.length) {
|
||
return canonical.map((key) => ({ value: key, label: opt('asset_kinds', key), count: 0 }))
|
||
}
|
||
return keys
|
||
.map((key) => ({ value: key, label: opt('asset_kinds', key), count: Number(scoped[key] || 0) }))
|
||
.sort((a, b) => b.count - a.count
|
||
|| (canonical.indexOf(a.value) - canonical.indexOf(b.value))
|
||
|| a.label.localeCompare(b.label, 'zh-CN'))
|
||
}
|
||
const kindOptions = useMemo(() => kindOptionsFor(type), [view, wall, stats, type])
|
||
|
||
/* ── 请求参数:所有维度都由后端过滤(AS-2),这里只负责拼与回显 ── */
|
||
const listParams = useMemo(() => {
|
||
const params: Record<string, any> = {
|
||
owner_type: type, sort: filters.sort, page: filters.page, page_size: filters.page_size
|
||
}
|
||
const needle = keyword.trim()
|
||
if (needle) params.q = needle
|
||
if (filters.tag) params.tag = filters.tag
|
||
if (filters.kind) params.kind = filters.kind
|
||
if (filters.has_media) params.has_media = filters.has_media
|
||
if (filters.status) params.status = filters.status
|
||
if (filters.duplicate_only) params.duplicate_only = true
|
||
return params
|
||
}, [type, keyword, filters])
|
||
|
||
const wallParams = useMemo(() => {
|
||
const params: Record<string, any> = {
|
||
owner_type: type, sort: wallQuery.sort, page: wallQuery.page, page_size: filters.page_size || 120
|
||
}
|
||
const needle = keyword.trim()
|
||
if (needle) params.q = needle
|
||
if (filters.kind) params.kind = filters.kind
|
||
if (wallQuery.multi_only) params.multi_version_only = true
|
||
return params
|
||
}, [type, keyword, filters.kind, filters.page_size, wallQuery])
|
||
|
||
/* ── 装载 ─────────────────────────────────────────────────────── */
|
||
const loadList = useCallback(async () => {
|
||
try {
|
||
const [library, projectList] = await Promise.all([
|
||
api.get('/api/platform/assets', listParams),
|
||
api.get('/api/projects', { brief: 1 })
|
||
])
|
||
const items: any[] = library.items || []
|
||
setRows(items)
|
||
setStats(library.stats || {})
|
||
setMeta({ tags: library.tags || [], sorts: library.sorts || [] })
|
||
setSummary({ filtered: library.filtered ?? items.length, page: library.page ?? 1, pages: library.pages ?? 1 })
|
||
setProjects(projectList.projects || [])
|
||
const voiceRows: any[] = library.voice || items.filter((row: any) => row.owner_type === 'voice')
|
||
setVoices(voiceRows)
|
||
if (type === 'human' && !voiceRows.length) {
|
||
// 人物母版要绑默认声线,声线列表得是全库的,不能受当前筛选影响
|
||
api.get('/api/platform/assets', { owner_type: 'voice', page_size: 0 })
|
||
.then((extra: any) => setVoices(extra.voice || []))
|
||
.catch(() => {})
|
||
}
|
||
// 生成抽屉里的母版在刷新后可能换了对象,重新指认一次,避免表单写进野对象
|
||
setGenTarget((prev) => (prev ? items.find((row: any) => row.id === prev.id) || prev : prev))
|
||
} catch (exc: any) {
|
||
setError(exc?.message || String(exc))
|
||
}
|
||
}, [listParams, type])
|
||
|
||
/** AS-3:跨母版素材墙,找一张图不必先猜它挂在哪个角色下 */
|
||
const loadWall = useCallback(async () => {
|
||
try {
|
||
const data = await api.get('/api/platform/media', wallParams)
|
||
setWall({
|
||
items: data.items || [], stats: data.stats || {}, kinds: data.kinds || [],
|
||
total: data.total || 0, page: data.page || 1, pages: data.pages || 1
|
||
})
|
||
} catch (exc: any) {
|
||
setError(exc?.message || String(exc))
|
||
}
|
||
}, [wallParams])
|
||
|
||
const reload = useCallback(() => (view === 'media' ? loadWall() : loadList()), [view, loadWall, loadList])
|
||
/**
|
||
* 渲染期把最新的 reload 塞进 ref:自动刷新与 nex:media-changed 监听都只在挂载时注册一次,
|
||
* 直接闭包会永远停在首屏那个 view/type 上——切到素材墙后自动刷新的还是母版列表。
|
||
*/
|
||
const reloadRef = useRef(reload)
|
||
reloadRef.current = reload
|
||
|
||
/* 模型注册表不参与首屏:/api/providers 是全站最慢的接口,以前和素材列表一起
|
||
await,白屏时间全被它一个人占走。生成抽屉里的下拉是派生值,它回来自己会填上。 */
|
||
useEffect(() => {
|
||
loadModels().catch(() => {})
|
||
}, [])
|
||
|
||
/**
|
||
* 唯一的取数入口:视角或参数序列化结果一变就请求。
|
||
*
|
||
* 旧站给每个条件挂了 watcher,还要用 30ms setTimeout 把「同一次交互里改了页码 + 条件」
|
||
* 合并成一次请求;React 一次事件只渲染一次,queryKey 天然就是合并后的结果,
|
||
* 所以这里不再需要那层定时器(少一个定时器也少一处「刷新按钮按了没反应」)。
|
||
*/
|
||
const queryKey = view === 'media' ? JSON.stringify(wallParams) : JSON.stringify(listParams)
|
||
useEffect(() => {
|
||
void reloadRef.current()
|
||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||
}, [view, queryKey])
|
||
|
||
/* 预览器里做了版本操作(设为当前 / 删除某版)→ 列表自己跟进,
|
||
否则卡片缩略图和版本号会停在被改之前的旧状态。 */
|
||
useEffect(() => {
|
||
const onMediaChanged = () => { void reloadRef.current() }
|
||
window.addEventListener('nex:media-changed', onMediaChanged)
|
||
return () => window.removeEventListener('nex:media-changed', onMediaChanged)
|
||
}, [])
|
||
|
||
useAutoRefresh(() => void reloadRef.current(), 20000, !!busy, modalOpen || recordingBusy)
|
||
|
||
/**
|
||
* 关键词防抖:输入框每敲一个字就发一次请求的话,中文输入法连发半截拼音时
|
||
* 「孙」会变成「sun 的母版」查一遍、「sunn」再查一遍,既慢又容易看见闪空的结果。
|
||
* 320ms 停顿后才把内容交给 listParams / wallParams(旧站同样的 320ms)。
|
||
*/
|
||
useEffect(() => {
|
||
const timer = window.setTimeout(() => setKeyword(search), 320)
|
||
return () => window.clearTimeout(timer)
|
||
}, [search])
|
||
|
||
/* ── 筛选条件写入:改条件一律回到第 1 页 ─────────────────────── */
|
||
function patchFilters(next: Partial<FilterState>) {
|
||
setFilters((prev) => ({ ...prev, ...next, page: next.page ?? 1 }))
|
||
setWallQuery((prev) => ({ ...prev, page: 1 }))
|
||
}
|
||
function patchWall(next: Partial<{ sort: string; multi_only: boolean; page: number }>) {
|
||
setWallQuery((prev) => ({ ...prev, ...next, page: next.page ?? 1 }))
|
||
}
|
||
function clearFilters() {
|
||
setSearch('')
|
||
setKeyword('')
|
||
setFilters((prev) => ({ ...prev, tag: '', kind: '', has_media: '', status: '', duplicate_only: false, page: 1 }))
|
||
setWallQuery((prev) => ({ ...prev, multi_only: false, page: 1 }))
|
||
}
|
||
|
||
/** 切大分类:顺手判断已选素材类型还属不属于新分类,并清掉跨分类的选择 */
|
||
function chooseType(next: AssetType) {
|
||
if (next === type) return
|
||
const keep = filters.kind && kindOptionsFor(next).some((entry) => entry.value === filters.kind)
|
||
setType(next)
|
||
patchFilters({ kind: keep ? filters.kind : '' })
|
||
clearSelection()
|
||
}
|
||
function chooseView(next: ViewMode) {
|
||
if (next === view) return
|
||
setView(next)
|
||
clearSelection()
|
||
}
|
||
|
||
/* ── AS-10:多选与批量。Shift 范围选择 + 全选当前筛选结果 ─────── */
|
||
const keyOf = (row: any) => `${row.owner_type || type}:${row.id}`
|
||
const isSelected = (row: any) => selected.has(keyOf(row))
|
||
function clearSelection() {
|
||
setSelected(new Set())
|
||
setSelectedMedia(new Set())
|
||
lastIndex.current = -1
|
||
lastMediaIndex.current = -1
|
||
}
|
||
function toggleSelect(row: any, index: number, shift = false) {
|
||
const next = new Set(selected)
|
||
if (shift && lastIndex.current >= 0) {
|
||
const [from, to] = [Math.min(lastIndex.current, index), Math.max(lastIndex.current, index)]
|
||
const adding = !next.has(keyOf(row))
|
||
for (let i = from; i <= to; i += 1) {
|
||
const key = keyOf(rows[i])
|
||
if (adding) next.add(key); else next.delete(key)
|
||
}
|
||
} else if (next.has(keyOf(row))) next.delete(keyOf(row))
|
||
else next.add(keyOf(row))
|
||
setSelected(next)
|
||
lastIndex.current = index
|
||
}
|
||
function selectAllFiltered() {
|
||
const next = new Set(selected)
|
||
const full = rows.length > 0 && rows.every((row) => next.has(keyOf(row)))
|
||
rows.forEach((row) => { if (full) next.delete(keyOf(row)); else next.add(keyOf(row)) })
|
||
setSelected(next)
|
||
}
|
||
const selectedRows = useMemo(() => rows.filter((row) => selected.has(keyOf(row))), [rows, selected]) // eslint-disable-line react-hooks/exhaustive-deps
|
||
const allSelected = rows.length > 0 && rows.every((row) => selected.has(keyOf(row)))
|
||
const selectionRefs = () => selectedRows.map((row) => ({ owner_type: row.owner_type || type, asset_id: row.id }))
|
||
/** 批量条上的影响面摘要:勾选后要先看清「素材量 / 谁在引用」再动手 */
|
||
const selectedSummary = (() => {
|
||
const list = selectedRows
|
||
if (!list.length) return ''
|
||
const media = list.reduce((sum, row) => sum + Number(row.media_count || 0), 0)
|
||
const bytes = list.reduce((sum, row) => sum + Number(row.media_bytes || 0), 0)
|
||
const used = list.filter((row) => Number(row.usage_count || 0) > 0).length
|
||
return `共 ${media} 个素材 · ${fmtBytes(bytes)}`
|
||
+ (used ? `;${used} 个已被项目引用,删除母版不影响项目内的快照副本` : ';均未被项目引用')
|
||
})()
|
||
|
||
/** 素材墙勾选:区间增删跟着点击框的目标态走,和母版选择一样支持 Shift 连选 */
|
||
function toggleMedia(media: any, index: number, shift: boolean) {
|
||
const on = !selectedMedia.has(media.id)
|
||
const next = new Set(selectedMedia)
|
||
if (shift && lastMediaIndex.current >= 0) {
|
||
const [from, to] = [Math.min(lastMediaIndex.current, index), Math.max(lastMediaIndex.current, index)]
|
||
for (let i = from; i <= to; i += 1) {
|
||
const id = wall.items[i]?.id
|
||
if (id) { if (on) next.add(id); else next.delete(id) }
|
||
}
|
||
} else if (on) next.add(media.id)
|
||
else next.delete(media.id)
|
||
setSelectedMedia(next)
|
||
lastMediaIndex.current = index
|
||
}
|
||
const selectedMediaRows = useMemo(
|
||
() => wall.items.filter((media: any) => selectedMedia.has(media.id)), [wall.items, selectedMedia])
|
||
/** 素材墙与预览队列一一对应(下标即墙上的位置),←/→ 才能顺着墙翻 */
|
||
const wallQueue = useMemo(
|
||
() => wall.items.map((media: any) => fromAsset(media)).filter(Boolean) as MediaItem[], [wall.items])
|
||
|
||
/* ── AS-7:顶部四张统计卡都是筛选入口 ────────────────────────── */
|
||
function focusMasters() { setView('grid'); clearFilters() }
|
||
function focusWall() { setView('media'); clearSelection(); setWallQuery((prev) => ({ ...prev, page: 1 })) }
|
||
function focusWithout() { setView('grid'); patchFilters({ has_media: 'without' }) }
|
||
function focusDuplicates() { setView('grid'); patchFilters({ duplicate_only: true }) }
|
||
|
||
/* ── 新建 / 编辑母版 ─────────────────────────────────────────── */
|
||
const patchForm = (next: Partial<MasterForm>) => setForm((prev) => ({ ...prev, ...next }))
|
||
function openCreate() {
|
||
setEditingId(null)
|
||
setForm(blankForm(type))
|
||
setDrawer(true)
|
||
setNotice('')
|
||
}
|
||
function openEdit(row: any) {
|
||
setEditingId(row.id)
|
||
setForm({
|
||
...blankForm(type), ...row,
|
||
tags: (row.tags || []).join(' '),
|
||
tuning: { ...(row.tuning || {}) },
|
||
tuning_speed: Number(row.tuning?.speed || 1),
|
||
tuning_effect: row.tuning?.params?.effect || ''
|
||
})
|
||
setDrawer(true)
|
||
setNotice('')
|
||
}
|
||
/** 按分类挑字段:后端整字典覆盖,多传别分类的空字段会把已存设定写成空串 */
|
||
function payload() {
|
||
const common = { name: String(form.name).trim(), code: String(form.code).trim(), tags: splitTags(form.tags) }
|
||
if (form.type === 'human') {
|
||
return {
|
||
...common, role: form.role, appearance: form.appearance, personality: form.personality,
|
||
persona_prompt: form.persona_prompt, voice_profile: form.voice_profile,
|
||
default_voice_id: form.default_voice_id || null, style_version: form.style_version,
|
||
notes: form.notes, is_active: form.is_active
|
||
}
|
||
}
|
||
if (form.type === 'scene') {
|
||
return {
|
||
...common, description: form.description, prompt: form.prompt, lighting: form.lighting,
|
||
time_of_day: form.time_of_day, palette: form.palette
|
||
}
|
||
}
|
||
// tuning 是整字典覆盖:先保留后端已有键(如 sample_rate),再改界面能控制的两项
|
||
const base = { ...(form.tuning && typeof form.tuning === 'object' ? form.tuning : {}) }
|
||
const params = { ...((base.params as Record<string, any>) || {}) }
|
||
if (form.tuning_effect) params.effect = form.tuning_effect
|
||
else delete params.effect
|
||
return {
|
||
...common, provider: form.provider, provider_voice_id: form.provider_voice_id,
|
||
language: form.language, gender: form.gender, description: form.description,
|
||
version: form.version, is_active: form.is_active, is_default: !!form.is_default,
|
||
tuning: { ...base, speed: Number(form.tuning_speed) || 1, params }
|
||
}
|
||
}
|
||
async function save() {
|
||
if (!String(form.name).trim()) {
|
||
setError('名称不能为空')
|
||
return
|
||
}
|
||
setBusy(editingId ? '保存平台资产' : '创建平台资产')
|
||
setError('')
|
||
try {
|
||
const path = SAVE_PATH[form.type]
|
||
if (editingId) await api.patch(`/api/platform/${path}/${editingId}`, payload())
|
||
else await api.post(`/api/platform/${path}`, payload())
|
||
setDrawer(false)
|
||
setNotice(`${TYPE_META[form.type].label}「${form.name}」已保存`)
|
||
await loadList()
|
||
} catch (exc: any) {
|
||
setError(exc?.message || String(exc))
|
||
} finally {
|
||
setBusy('')
|
||
}
|
||
}
|
||
|
||
/* ── 删除:删除前把「谁在引用这个母版」摊开 ──────────────────── */
|
||
async function runDelete() {
|
||
const target = confirmDelete
|
||
if (!target) return
|
||
if (selected.has(keyOf(target)) && selected.size > 1) {
|
||
await runBatchDelete()
|
||
return
|
||
}
|
||
setBusy('删除母版')
|
||
setError('')
|
||
try {
|
||
await api.del(`/api/platform/${target.owner_type || type}/${target.id}`)
|
||
setNotice(`「${target.name}」已删除,项目内的历史引入副本不受影响`)
|
||
setConfirmDelete(null)
|
||
await loadList()
|
||
} catch (exc: any) {
|
||
setError(exc?.message || String(exc))
|
||
} finally {
|
||
setBusy('')
|
||
}
|
||
}
|
||
|
||
/* ── 上传 / 录音 ─────────────────────────────────────────────── */
|
||
/** 读取时兜底,不在渲染期写 state(旧站在 uploadKey() 里偷偷补默认值) */
|
||
const uploadKindFor = (row: any) => uploadKinds[keyOf(row)] || UPLOAD_KINDS[type][0]
|
||
|
||
/** 上传/录音的公共出口:拿到 File 就登记为新版本,两种入口的行为必须一模一样 */
|
||
async function uploadFile(row: any, file: File, kind: string, note = '') {
|
||
setBusy(`上传${opt('asset_kinds', kind)}`)
|
||
setError('')
|
||
try {
|
||
const media: any = await api.upload(
|
||
`/api/platform/${type}/${row.id}/media`,
|
||
api.formData({ kind, name: file.name.replace(/\.[^.]+$/, ''), note }, file)
|
||
)
|
||
setNotice(`${file.name} 已登记为新版本`)
|
||
await loadList()
|
||
return media || true // 返回媒体行(含 id/version/versions)供「当前版本」回退
|
||
} catch (exc: any) {
|
||
setError(exc?.message || String(exc))
|
||
return false
|
||
} finally {
|
||
setBusy('')
|
||
}
|
||
}
|
||
|
||
/** 录音面板的默认落点:能顺着已有素材追加版本,就别让随手一段试音长出第二条素材 */
|
||
const recordDefaultName = (row: any, kind: string) =>
|
||
defaultAssetName(row?.assets || [], `${row?.name || '素材'} · ${opt('asset_kinds', kind)}`, kind)
|
||
|
||
/** 录完的样本:先登记,再顺手把它选成本次生成的参考,省得用户再去下拉里找 */
|
||
async function recordSample(row: any, file: File, meta: RecordPickMeta) {
|
||
const media = await uploadFile(row, file, uploadKindFor(row), '页面录制')
|
||
if (!media) return
|
||
await keepOrRestoreCurrent(media, meta.setCurrent !== false)
|
||
if (meta.warning) setNotice(`已录入库:${meta.warning}`)
|
||
}
|
||
|
||
async function deleteMedia(media: any) {
|
||
if (!window.confirm(`确认删除「${media.name || media.kind_label}」这个媒体文件?`)) return
|
||
const wasWall = view === 'media'
|
||
setBusy('删除媒体文件')
|
||
setError('')
|
||
try {
|
||
await api.del(`/api/platform/media/${media.id}`)
|
||
setNotice(`「${media.name || media.kind_label}」已删除`)
|
||
if (wasWall) await loadWall()
|
||
await loadList()
|
||
} catch (exc: any) {
|
||
setError(exc?.message || String(exc))
|
||
} finally {
|
||
setBusy('')
|
||
}
|
||
}
|
||
|
||
/* ── 批量操作 ────────────────────────────────────────────────── */
|
||
async function runBatchTag() {
|
||
const items = selectionRefs()
|
||
if (!items.length) return
|
||
const add = splitTags(batchTags.add)
|
||
const remove = splitTags(batchTags.remove)
|
||
if (!add.length && !remove.length) {
|
||
setError('请填写要添加或移除的标签')
|
||
return
|
||
}
|
||
setBusy('批量整理标签')
|
||
setError('')
|
||
try {
|
||
const result = await api.post('/api/platform/assets/batch-tag', { items, add, remove })
|
||
setNotice(`已为 ${result?.count ?? items.length} 个母版`
|
||
+ `${add.length ? ` 添加「${add.join('、')}」` : ''}${remove.length ? ` 移除「${remove.join('、')}」` : ''}`)
|
||
setBatchTags({ add: '', remove: '' })
|
||
setBatchDialog('')
|
||
await loadList()
|
||
} catch (exc: any) {
|
||
setError(exc?.message || String(exc))
|
||
} finally {
|
||
setBusy('')
|
||
}
|
||
}
|
||
|
||
async function runBatchDelete() {
|
||
const items = selectionRefs()
|
||
if (!items.length) return
|
||
setBusy('批量删除母版')
|
||
setError('')
|
||
try {
|
||
const result = await api.post('/api/platform/assets/batch-delete', { items })
|
||
const failed = result?.failures || []
|
||
setNotice(`已删除 ${result?.deleted_count ?? items.length} 个母版`
|
||
+ (failed.length ? `,${failed.length} 个失败:${failed[0].detail}` : ';项目内已引入的快照副本不受影响'))
|
||
setConfirmDelete(null)
|
||
setBatchDialog('')
|
||
clearSelection()
|
||
await loadList()
|
||
} catch (exc: any) {
|
||
setError(exc?.message || String(exc))
|
||
} finally {
|
||
setBusy('')
|
||
}
|
||
}
|
||
|
||
async function runBatchMediaDelete() {
|
||
const ids = [...selectedMedia]
|
||
if (!ids.length) return
|
||
setBusy('批量删除素材')
|
||
setError('')
|
||
try {
|
||
const result = await api.post('/api/platform/media/batch-delete', { media_ids: ids })
|
||
const failed = result?.failures || []
|
||
setNotice(`已删除 ${result?.deleted_count ?? ids.length} 个素材`
|
||
+ (failed.length ? `,${failed.length} 个失败:${failed[0].detail}` : ''))
|
||
setBatchDialog('')
|
||
clearSelection()
|
||
await loadWall()
|
||
await loadList()
|
||
} catch (exc: any) {
|
||
setError(exc?.message || String(exc))
|
||
} finally {
|
||
setBusy('')
|
||
}
|
||
}
|
||
|
||
/* ── 引入项目(快照副本)────────────────────────────────────── */
|
||
/** AS-10:多选后走批量引入,未选中就只引入点开的这一张 */
|
||
function openImportSelection(row?: any) {
|
||
const list = row ? [row] : selectedRows
|
||
if (!list.length) return
|
||
setImportTargets(list)
|
||
setImportProjectId(null)
|
||
setError('')
|
||
}
|
||
const importSubject = importTargets[0] || null
|
||
const importProjectName = projects.find((p) => p.id === importProjectId)?.name || '项目'
|
||
|
||
async function importIntoProject() {
|
||
if (!importSubject) return
|
||
if (!importProjectId) {
|
||
setError('请先选择一个目标项目')
|
||
return
|
||
}
|
||
setBusy(importTargets.length > 1 ? '批量引入项目' : '引入项目')
|
||
setError('')
|
||
try {
|
||
const refs = importTargets.map((row) => ({ owner_type: row.owner_type || type, asset_id: row.id }))
|
||
if (refs.length > 1) {
|
||
const result = await api.post('/api/platform/assets/batch-import', {
|
||
project_id: importProjectId, items: refs
|
||
})
|
||
const failed = result?.failures || []
|
||
setNotice(`已引入 ${result?.imported_count ?? refs.length} 个母版到《${importProjectName}》`
|
||
+ (failed.length ? `,${failed.length} 个失败:${failed[0].detail}` : ''))
|
||
} else {
|
||
const result = await api.post('/api/platform/import', {
|
||
project_id: importProjectId, asset_type: type, asset_id: importSubject.id
|
||
})
|
||
setNotice(`「${result.name}」已引入《${importProjectName}》`)
|
||
}
|
||
setImportTargets([])
|
||
setImportProjectId(null)
|
||
clearSelection()
|
||
await loadList()
|
||
} catch (exc: any) {
|
||
setError(exc?.message || String(exc))
|
||
} finally {
|
||
setBusy('')
|
||
}
|
||
}
|
||
|
||
/* ── AI 生成抽屉 ─────────────────────────────────────────────── */
|
||
const genKey = (row: any) => `${row.owner_type || type}:${row.id}`
|
||
const draftOf = (row: any): GenDraft => generation[genKey(row)] || BLANK_DRAFT
|
||
function setDraft(row: any, patch: Partial<GenDraft>) {
|
||
const key = genKey(row)
|
||
setGeneration((prev) => ({ ...prev, [key]: { ...(prev[key] || BLANK_DRAFT), ...patch } }))
|
||
}
|
||
|
||
/* 声线的「音色预告」:参考音频才决定音色,所以打开抽屉时先问后端「这次会拿到谁的嗓子」 */
|
||
async function loadVoiceReferenceStatus(row: any) {
|
||
setVoiceRefStatus(null)
|
||
if (type !== 'voice') return
|
||
setVoiceRefBusy(true)
|
||
try {
|
||
setVoiceRefStatus(await api.get(`/api/platform/voice/${row.id}/reference-status`))
|
||
} catch {
|
||
setVoiceRefStatus(null) // 预告拿不到不挡生成,后端仍会在缺参考时明确报错
|
||
} finally {
|
||
setVoiceRefBusy(false)
|
||
}
|
||
}
|
||
|
||
function openGenerate(row: any) {
|
||
const key = genKey(row)
|
||
if (!generation[key]) {
|
||
const currentScene = type === 'scene' ? latestImage(row, ['scene_image']) || latestImage(row) : null
|
||
const draft: GenDraft = {
|
||
model: '', kind: DEFAULT_KIND[type], prompt: '',
|
||
// 试听文本是「模型要念出来的台词」,音色描述不是台词,不能拿它当默认值糊上去
|
||
sample_text: '', reference_media_id: null,
|
||
reference_media_ids: currentScene ? [currentScene.id] : [],
|
||
tier: '', aspect: GEN_ASPECT[type]
|
||
}
|
||
setGeneration((prev) => ({ ...prev, [key]: draft }))
|
||
}
|
||
setGenTarget(row)
|
||
setGenDrawer(true)
|
||
setError('')
|
||
void loadVoiceReferenceStatus(row)
|
||
}
|
||
|
||
/** 注册表可能比首屏晚到,所以模型绑定走「草稿值 || 平台默认」而不是初始化时写死 */
|
||
const modelRef = (row: any) => draftOf(row).model || refOf(defaultFor(type === 'voice' ? 'tts' : 'image'))
|
||
const specCaps = (row: any): Caps => capsOfRef(modelRef(row))
|
||
const tierChoices = (row: any) => imageTiers(...parseRef(modelRef(row)))
|
||
const aspectChoices = (row: any) => imageAspectChoices(...parseRef(modelRef(row)))
|
||
/** 档位/画幅在读取时对齐注册表:注册表后到或换了模型时,草稿里存的旧值不能直接发给后端 */
|
||
const draftTier = (row: any) => {
|
||
const list = tierChoices(row)
|
||
const value = draftOf(row).tier
|
||
return list.some((item) => item.value === value) ? value : (list[0]?.value || '')
|
||
}
|
||
const draftAspect = (row: any) => {
|
||
const list = aspectChoices(row)
|
||
const value = draftOf(row).aspect
|
||
return list.some((item) => item.value === value) ? value : (list[0]?.value || '16:9')
|
||
}
|
||
const canvasOf = (row: any) => imageCanvas(draftTier(row), draftAspect(row))
|
||
const generationSpec = (row: any): ModelRow | null => {
|
||
const ref = modelRef(row)
|
||
return registryRows.find((r) => refOf(r) === ref) || null
|
||
}
|
||
const referenceOptions = (row: any) => (row.assets || []).filter((item: any) => isAudio(item))
|
||
const imageReferenceOptions = (row: any) => (row.assets || []).filter((item: any) => isImage(item))
|
||
|
||
function pickReferences(row: any, ids: any[]) {
|
||
const max = specCaps(row).maxReferenceImages || 1
|
||
setDraft(row, { reference_media_ids: ids.map(Number).filter(Boolean).slice(0, max) })
|
||
}
|
||
/** 换类型时顺手把场景图带进「氛围图」的参考:氛围图要贴着已定的空间画 */
|
||
function selectAtmosphereReference(row: any, kind: string) {
|
||
const draft = draftOf(row)
|
||
setDraft(row, { kind })
|
||
if (type === 'scene' && kind === 'reference' && !draft.reference_media_ids.length) {
|
||
const currentScene = latestImage(row, ['scene_image']) || latestImage(row)
|
||
if (currentScene) setDraft(row, { reference_media_ids: [currentScene.id] })
|
||
}
|
||
}
|
||
|
||
function voiceHasReference(row: any) {
|
||
const draft = draftOf(row)
|
||
const caps = specCaps(row)
|
||
if (!caps.requiresReference || draft.reference_media_id) return true
|
||
// 后端的预告优先于「字段里有个 .wav」这种猜测:绑定指向 AI 试听样本时路径看着能用,
|
||
// 实际不能当克隆参考(否则错音色会自我强化),按钮必须跟后端口径一致。
|
||
if (voiceRefStatus) return !!voiceRefStatus.ready
|
||
if (isAudioPath(row.provider_voice_id)) return true
|
||
return !!generationSpec(row)?.config?.reference_audio
|
||
}
|
||
|
||
async function uploadReferenceFile(row: any, file: File, note = '') {
|
||
setBusy('上传参考音色')
|
||
setError('')
|
||
try {
|
||
const media: any = await api.upload(
|
||
`/api/platform/voice/${row.id}/media`,
|
||
api.formData({ kind: 'reference', name: file.name.replace(/\.[^.]+$/, ''), note }, file)
|
||
)
|
||
setDraft(row, { reference_media_id: media?.id || null })
|
||
setNotice(`${file.name} 已作为参考音色(当前模型:${generationSpec(row)?.display_name || '未注册'})`)
|
||
await Promise.all([loadList(), loadVoiceReferenceStatus(row)])
|
||
return media || true
|
||
} catch (exc: any) {
|
||
setError(exc?.message || String(exc))
|
||
return false
|
||
} finally {
|
||
setBusy('')
|
||
}
|
||
}
|
||
|
||
async function recordReference(row: any, file: File, meta: RecordPickMeta) {
|
||
const media = await uploadReferenceFile(row, file, '页面录制')
|
||
if (!media) return
|
||
await keepOrRestoreCurrent(media, meta.setCurrent !== false)
|
||
if (meta.warning) setNotice(`参考音色已录:${meta.warning}`)
|
||
}
|
||
|
||
async function uploadImageReference(row: any, file: File) {
|
||
setBusy('上传参考图')
|
||
setError('')
|
||
try {
|
||
const media: any = await api.upload(
|
||
`/api/platform/${type}/${row.id}/media`,
|
||
api.formData({ kind: 'reference', name: file.name.replace(/\.[^.]+$/, '') }, file)
|
||
)
|
||
const max = specCaps(row).maxReferenceImages || 1
|
||
if (media?.id) {
|
||
setDraft(row, { reference_media_ids: [...new Set([...draftOf(row).reference_media_ids, media.id])].slice(0, max) })
|
||
}
|
||
setNotice(`${file.name} 已作为生成参考图(最多 ${max} 张)`)
|
||
await loadList()
|
||
} catch (exc: any) {
|
||
setError(exc?.message || String(exc))
|
||
} finally {
|
||
setBusy('')
|
||
}
|
||
}
|
||
|
||
async function generate(row: any) {
|
||
const draft = draftOf(row)
|
||
const spec = generationSpec(row)
|
||
if (!spec) {
|
||
setError(`尚未启用真实${type === 'voice' ? '声音' : '图像'}模型;Mock 模型已从生产选择中隐藏`)
|
||
return
|
||
}
|
||
if (isMock(spec)) {
|
||
setError('Mock 模型仅用于内部自检,不能在平台资产库中生成正式素材')
|
||
return
|
||
}
|
||
if (type === 'voice' && !String(draft.sample_text || '').trim()) {
|
||
setError('请先填写试听文本:它是模型要朗读的台词,「音色描述」是声线设定,不会被念出来')
|
||
return
|
||
}
|
||
if (type === 'voice' && specCaps(row).requiresReference && !voiceHasReference(row)) {
|
||
setError('该声线模型需要参考音色,请上传参考音频或使用模型默认参考音频')
|
||
return
|
||
}
|
||
const body: any = type === 'voice'
|
||
? {
|
||
kind: 'voice_sample', provider: spec.provider, model: spec.model,
|
||
sample_text: draft.sample_text, reference_media_id: draft.reference_media_id || null
|
||
}
|
||
: {
|
||
kind: draft.kind, provider: spec.provider, model: spec.model, prompt: draft.prompt,
|
||
...canvasOf(row),
|
||
reference_media_ids: draft.reference_media_ids.slice(0, specCaps(row).maxReferenceImages || 1)
|
||
}
|
||
setBusy(`生成${TYPE_META[type].label}资产`)
|
||
setError('')
|
||
try {
|
||
const media: any = await api.post(`/api/platform/${type}/${row.id}/generate`, body)
|
||
setNotice(`${row.name} 的${type === 'voice' ? '试听样本' : opt('asset_kinds', draft.kind)}`
|
||
+ `已生成(${spec.provider}/${spec.model}${media?.id ? ` · v${media.version}` : ''})`)
|
||
await loadList()
|
||
if (view === 'media') await loadWall()
|
||
} catch (exc: any) {
|
||
setError(exc?.message || String(exc))
|
||
} finally {
|
||
setBusy('')
|
||
}
|
||
}
|
||
|
||
const mediaAverageKb = totals.media ? Math.round((stats.media_bytes || 0) / totals.media / 1024) : 0
|
||
// 抽屉关闭时 genTarget 为 null,草稿与能力都退回空值:这两行只在抽屉打开时被读到
|
||
const draft = genTarget ? draftOf(genTarget) : BLANK_DRAFT
|
||
const caps: Caps = genTarget ? specCaps(genTarget) : capsOfRef('')
|
||
|
||
/* ── 渲染 ────────────────────────────────────────────────────── */
|
||
const typeMeta = TYPE_META[type]
|
||
const isVoice = type === 'voice'
|
||
const isScene = type === 'scene'
|
||
|
||
return (
|
||
<div className="min-w-0">
|
||
<PageHead
|
||
title={<span title="人物、场景与声线在这里沉淀为可复用母版;项目可随时引入快照,已锁定的版本会随生成记录一起留痕。">平台资产库</span>}
|
||
actions={<Button variant="primary" onClick={openCreate}>+ 新建{typeMeta.label}</Button>}
|
||
/>
|
||
|
||
<Notice danger>{error}</Notice>
|
||
<Notice onClose={() => setNotice('')}>{notice}</Notice>
|
||
|
||
{/* AS-7:四张卡本身就是筛选入口,数字点下去就到对应视角,不用先去翻筛选下拉。
|
||
窄屏收列走断点变体(4 → ≤1180 两列 → ≤820 一列 → 手机上再并回两列,
|
||
四行竖条在一屏里等于整页都是统计卡)。 */}
|
||
<div className="grid min-w-0 gap-[10px] mb-[14px] grid-cols-4 max-mid:grid-cols-2 max-short:grid-cols-1 max-narrow:grid-cols-2">
|
||
<MetricCard lead label="母版资产" value={totals.human + totals.scene + totals.voice}
|
||
title="查看全部母版:清空筛选并回到网格视图"
|
||
active={view !== 'media' && !filtersActive} onClick={focusMasters}
|
||
hint={`人物 ${totals.human} · 场景 ${totals.scene} · 声线 ${totals.voice}`} />
|
||
<MetricCard label="已登记素材" value={totals.media}
|
||
title="切换到跨母版的「全部素材」视角,直接翻找图片与音频"
|
||
active={view === 'media'} onClick={focusWall}
|
||
hint={`${fmtBytes(stats.media_bytes || 0)} · ${stats.versions || 0} 个版本 · 平均 ${mediaAverageKb} KB/个`} />
|
||
<MetricCard label="待补素材" value={stats.without_media || 0}
|
||
title="只看还没有任何素材的母版(补齐定妆图 / 试听样本)"
|
||
active={filters.has_media === 'without' && view !== 'media'} onClick={focusWithout}
|
||
hint="母版已建档,但一张图 / 一段音都没有" />
|
||
<MetricCard warn label="疑似重复" value={stats.duplicate_masters || 0}
|
||
title="同名或同代号的母版分组,建议人工确认后合并"
|
||
active={filters.duplicate_only && view !== 'media'} onClick={focusDuplicates}
|
||
hint={`${stats.duplicate_groups || 0} 组同名 / 同代号 · 已引用母版 ${stats.referenced || 0}`} />
|
||
</div>
|
||
|
||
<div className="grid min-w-0 items-start gap-[13px] grid-cols-[224px_minmax(0,1fr)] max-short:grid-cols-1 [&>*]:min-w-0">
|
||
{/* 左侧大分类(.type-rail):新增一类只改 TYPE_META */}
|
||
<aside className="sticky top-[14px] flex flex-col gap-1.5 p-2 bg-card border border-line rounded-float min-w-0 max-short:static max-short:grid max-short:grid-cols-3">
|
||
{TYPE_KEYS.map((key) => (
|
||
<button key={key} type="button" onClick={() => chooseType(key)}
|
||
className={cn('flex items-center gap-2.5 w-full min-w-0 p-[12px_9px] text-left text-ink-2 '
|
||
+ 'border border-transparent rounded-tile bg-transparent hover:bg-panel',
|
||
type === key && 'bg-raised border-success-line shadow-[inset_3px_0_0_var(--c-accent)]')}>
|
||
<span className="grid place-items-center w-[31px] h-[31px] flex-none rounded-tile bg-line-soft text-accent text-[16px]">
|
||
{TYPE_META[key].icon}
|
||
</span>
|
||
<span className="min-w-0">
|
||
<b className="block text-body">{TYPE_META[key].label}</b>
|
||
<small className="block mt-[3px] text-dim text-tiny leading-[1.35]">{TYPE_META[key].hint}</small>
|
||
</span>
|
||
<em className="ml-auto text-success not-italic text-h2">{totals[key]}</em>
|
||
</button>
|
||
))}
|
||
<div title={`${typeMeta.hint}。资产在此管理母版,进入项目后仍可独立改版`}
|
||
className="border-t border-active pt-5 pb-[5px] px-[7px] max-short:col-span-3">
|
||
{view === 'media' && (
|
||
<p className="mt-[6px] mb-0 text-dim text-tiny leading-[1.6]">
|
||
素材墙按 <b>当前类型</b> 过滤:{typeMeta.label}素材 {wall.stats?.by_owner?.[type] || 0} 个。
|
||
</p>
|
||
)}
|
||
</div>
|
||
</aside>
|
||
|
||
<section className="min-w-0">
|
||
<Panel className="bg-shell p-[16px]">
|
||
<PanelHead
|
||
title={view === 'media' ? '全部素材墙' : `${typeMeta.label}母版`}
|
||
sub={view === 'media'
|
||
? `共 ${wall.total} 个素材,当前第 ${wall.page} / ${wall.pages} 页`
|
||
: filtersActive
|
||
? `筛选出 ${resultCount} 个母版,本页 ${rows.length} 个(第 ${summary.page} / ${summary.pages} 页)`
|
||
: `共 ${resultCount} 个母版`}
|
||
right={
|
||
<div role="group" aria-label="切换视图"
|
||
className="flex gap-[3px] shrink-0 p-[3px] bg-card border border-line rounded-tile max-narrow:w-full max-narrow:[&>button]:flex-1">
|
||
{VIEW_ITEMS.map((item) => (
|
||
<ViewBtn key={item.value} active={view === item.value} title={item.hint}
|
||
onClick={() => chooseView(item.value)}>{item.label}</ViewBtn>
|
||
))}
|
||
</div>
|
||
} />
|
||
|
||
{/* 筛选栏:只有皮肤,布局(等高 / 折行 / 行内标签)全部来自 Ctlbar。
|
||
「每页」不在这里——分页条是 page_size 唯一的家(UI规范 §5)。 */}
|
||
<Ctlbar className="px-[10px] py-2 mb-3 border border-emphasis rounded-[10px] bg-card">
|
||
<Field label="搜索" width="grow" title="跨字段匹配名称、代号、设定、提示词与标签">
|
||
<input type="search" value={search} onChange={(e) => setSearch(e.target.value)}
|
||
aria-label="搜索平台资产" placeholder="名称 / 代号 / 设定 / 提示词 / 标签(跨字段)" />
|
||
</Field>
|
||
<Field label="素材类型" title="选项只列当前大分类该有的类型:在「人物」下筛「音色样本」永远 0 条">
|
||
<Select size="sm" value={filters.kind} ariaLabel="按素材类型筛选"
|
||
onChange={(next) => patchFilters({ kind: String(next) })}
|
||
options={[{ value: '', label: '全部类型' },
|
||
...kindOptions.map((entry) => ({
|
||
value: entry.value,
|
||
label: entry.count ? `${entry.label} · ${entry.count}` : entry.label
|
||
}))]} />
|
||
</Field>
|
||
{view !== 'media' ? (
|
||
<>
|
||
<Field label="素材情况">
|
||
<Select size="sm" value={filters.has_media} ariaLabel="按素材情况筛选"
|
||
onChange={(next) => patchFilters({ has_media: String(next) })}
|
||
options={[{ value: '', label: '全部情况' },
|
||
{ value: 'with', label: '已有素材' }, { value: 'without', label: '待补素材' }]} />
|
||
</Field>
|
||
<Field label="状态">
|
||
<Select size="sm" value={filters.status} ariaLabel="按状态筛选"
|
||
onChange={(next) => patchFilters({ status: String(next) })}
|
||
options={[{ value: '', label: '全部状态' },
|
||
{ value: 'active', label: '启用中' }, { value: 'inactive', label: '已停用' }]} />
|
||
</Field>
|
||
</>
|
||
) : (
|
||
<Check checked={wallQuery.multi_only} onChange={(next) => patchWall({ multi_only: next })}>
|
||
仅多版本素材
|
||
</Check>
|
||
)}
|
||
<Field label="排序" width="narrow">
|
||
<Select size="sm" ariaLabel="排序方式"
|
||
value={view === 'media' ? wallQuery.sort : filters.sort}
|
||
onChange={(next) => (view === 'media'
|
||
? patchWall({ sort: String(next) })
|
||
: patchFilters({ sort: String(next) }))}
|
||
options={view === 'media' ? WALL_SORTS : sortOptions} />
|
||
</Field>
|
||
{view !== 'media' && (
|
||
<Check checked={filters.duplicate_only} onChange={(next) => patchFilters({ duplicate_only: next })}>
|
||
仅疑似重复
|
||
</Check>
|
||
)}
|
||
{/* 自动刷新的倒计时/手动按钮由 useAutoRefresh 与它自己的展示组件负责,
|
||
这里只补一句「正在忙什么」,避免同一行出现两个刷新入口。 */}
|
||
<BarRight>{busy && <span className={cn(MUTED, 'text-tiny')}><Spinner /> {busy}…</span>}</BarRight>
|
||
</Ctlbar>
|
||
|
||
{tagOptions.length > 0 && (
|
||
<ChipBar label="标签">
|
||
<Chip active={!filters.tag} onClick={() => patchFilters({ tag: '' })}>全部</Chip>
|
||
{tagOptions.map((entry: any) => {
|
||
const on = filters.tag === entry.tag
|
||
return (
|
||
<Chip key={entry.tag} active={on}
|
||
title={`只看带「${entry.tag}」标签的母版(${entry.count} 个)`}
|
||
onClick={() => patchFilters({ tag: on ? '' : entry.tag })}>
|
||
{entry.tag}
|
||
<em className={cn('not-italic text-tiny', on ? 'text-on-accent opacity-70' : 'text-dim')}>
|
||
{entry.count}
|
||
</em>
|
||
</Chip>
|
||
)
|
||
})}
|
||
{filtersActive && (
|
||
<Chip className="border-dashed text-warn" onClick={clearFilters}>✕ 清除全部筛选</Chip>
|
||
)}
|
||
</ChipBar>
|
||
)}
|
||
|
||
{/* AS-10:勾选后先摊开影响面(素材量 / 体积 / 谁在引用),再给动作 */}
|
||
{view !== 'media' && selected.size > 0 && (
|
||
<div className="flex items-center flex-wrap gap-2 mt-[10px] px-[11px] py-[9px] border border-accent-line rounded-tile bg-accent-tint text-tiny text-ink-2 [--ctl-h:var(--ctl-h-md)]">
|
||
<b className="text-caption">已选 {selected.size} 个{typeMeta.label}母版</b>
|
||
<span className={cn(MUTED, 'text-tiny')}>{selectedSummary}</span>
|
||
<Button variant="outline" size="sm" className="ml-auto" onClick={selectAllFiltered}>
|
||
{allSelected ? '取消全选' : '全选本页筛选结果'}
|
||
</Button>
|
||
<Button variant="outline" size="sm" onClick={() => openImportSelection()}>引入项目 →</Button>
|
||
<Button variant="outline" size="sm" onClick={() => { setBatchDialog('tag'); setError('') }}>批量标签</Button>
|
||
<Button variant="del" disabled={!!busy} title="删除这些母版(项目内的快照副本不受影响)"
|
||
onClick={() => setBatchDialog('delete')}>批量删除</Button>
|
||
<Button variant="ghost" size="sm" onClick={clearSelection}>取消选择</Button>
|
||
</div>
|
||
)}
|
||
{view === 'media' && selectedMedia.size > 0 && (
|
||
<div className="flex items-center flex-wrap gap-2 mt-[10px] px-[11px] py-[9px] border border-accent-line rounded-tile bg-accent-tint text-tiny text-ink-2 [--ctl-h:var(--ctl-h-md)]">
|
||
<b className="text-caption">已选 {selectedMedia.size} 个素材</b>
|
||
<Button variant="del" className="ml-auto" disabled={!!busy}
|
||
title="Shift 可范围勾选;删除会连同全部历史版本一起移除"
|
||
onClick={() => setBatchDialog('media-delete')}>批量删除素材</Button>
|
||
<Button variant="ghost" size="sm" onClick={clearSelection}>取消选择</Button>
|
||
</div>
|
||
)}
|
||
|
||
{view === 'media' ? (
|
||
!wall.items.length ? (
|
||
/* AS-9:「筛不出东西」和「本来就空的」是两件事,出口也不同 */
|
||
<Empty>
|
||
{filtersActive
|
||
? <>没有符合条件的素材。<Button variant="link" onClick={clearFilters}>清除全部筛选</Button></>
|
||
: <>当前类型还没有登记任何素材。切回母版视图,用卡片上的「AI 生成」或「上传」补素材。</>}
|
||
</Empty>
|
||
) : (
|
||
<div className="grid gap-[9px] grid-cols-[repeat(auto-fill,minmax(148px,1fr))] max-narrow:grid-cols-[repeat(auto-fill,minmax(120px,1fr))] min-w-0 [&>*]:min-w-0">
|
||
{wall.items.map((media: any, idx: number) => (
|
||
<div key={media.id}
|
||
className={cn('relative flex flex-col gap-[5px] p-[7px_7px_8px] rounded-[10px] bg-card border border-emphasis',
|
||
selectedMedia.has(media.id) && 'border-accent-line shadow-[0_0_0_1px_var(--c-accent-tint)]')}>
|
||
<label title="勾选后可批量删除(Shift 范围选择)" className={cn(PICK, 'left-[12px] top-[12px]')}>
|
||
<input type="checkbox" checked={selectedMedia.has(media.id)}
|
||
onClick={(e) => e.stopPropagation()}
|
||
onChange={(e) => toggleMedia(media, idx, (e.nativeEvent as MouseEvent).shiftKey)} />
|
||
</label>
|
||
<MediaThumb item={wallQueue[idx]} size="sm" radius={8} queue={wallQueue} index={idx}
|
||
title={`${media.name || media.kind_label} · ${media.owner_name}`} />
|
||
<div className="min-w-0">
|
||
<b className="block truncate text-ink-2 text-tiny" title={media.name || media.kind_label}>
|
||
{media.name || media.kind_label}
|
||
</b>
|
||
<small className="block text-dim text-tiny leading-[1.45] break-anywhere">
|
||
{media.kind_label} · {media.owner_name}
|
||
{!!media.width && ` · ${media.width}×${media.height}`}
|
||
{!!media.duration_ms && ` · ${Math.round(media.duration_ms / 100) / 10}s`}
|
||
</small>
|
||
<small className={cn(MUTED_MONO, 'block text-tiny')}>
|
||
{fmtBytes(media.size_bytes)} · v{media.version}
|
||
{media.version_count > 1 && `(共 ${media.version_count} 版)`}
|
||
</small>
|
||
</div>
|
||
</div>
|
||
))}
|
||
</div>
|
||
)
|
||
) : !rows.length ? (
|
||
<Empty>
|
||
{filtersActive ? (
|
||
<>没有符合当前筛选条件的{typeMeta.label}母版。
|
||
<Button variant="link" onClick={clearFilters}>清除全部筛选</Button>
|
||
</>
|
||
) : (
|
||
<>还没有{typeMeta.label}母版。
|
||
<Button variant="link" onClick={openCreate}>新建{typeMeta.label}母版</Button>
|
||
,或到项目资产库把已有资产「上架到平台」。
|
||
</>
|
||
)}
|
||
</Empty>
|
||
) : view === 'list' ? (
|
||
/* 列表视图:一行一个母版,专为批量勾选与巡检设计 */
|
||
<div className="flex flex-col gap-1.5 min-w-0">
|
||
{rows.map((row: any, idx: number) => (
|
||
<article key={row.id}
|
||
className={cn('grid items-center gap-3 grid-cols-[auto_auto_minmax(200px,1fr)_auto_auto] '
|
||
+ 'p-[9px_12px] rounded-[10px] border border-emphasis '
|
||
+ 'bg-[linear-gradient(145deg,var(--c-bg-panel),var(--c-bg-sunken))] max-short:grid-cols-[auto_minmax(0,1fr)] max-short:[&_.row-media]:hidden',
|
||
isSelected(row) && 'border-accent-line shadow-[0_0_0_1px_var(--c-accent-tint)]',
|
||
row.duplicate_of?.length && 'border-warn-line')}>
|
||
<label className="contents max-short:hidden"
|
||
title={isSelected(row) ? '取消选择' : '勾选后可批量引入 / 打标签 / 删除(Shift 范围选择)'}>
|
||
<input type="checkbox" checked={isSelected(row)}
|
||
onClick={(e) => e.stopPropagation()}
|
||
onChange={(e) => toggleSelect(row, idx, (e.nativeEvent as MouseEvent).shiftKey)}
|
||
className="self-center flex-none w-[14px] h-[14px] m-0 accent-accent cursor-pointer" />
|
||
</label>
|
||
<Portrait name={row.name} sm />
|
||
<div className="row-main min-w-0">
|
||
<div className="flex items-center gap-[5px] flex-wrap">
|
||
<b className="text-label">{row.name}</b>
|
||
<span className={MUTED_MONO}>{row.code || `${type}-${row.id}`}</span>
|
||
{!!row.is_default && <Tag tone="ok">默认声线</Tag>}
|
||
{row.is_active === false && <Tag tone="bad">停用</Tag>}
|
||
{!!row.duplicate_of?.length && (
|
||
<Tag tone="bad"
|
||
title={`与 ${row.duplicate_of.map((d: any) => d.name || d.asset_name).join('、')} 同名或同代号,建议合并`}>
|
||
疑似重复
|
||
</Tag>
|
||
)}
|
||
{!row.media_count && <Tag tone="warn">待补素材</Tag>}
|
||
</div>
|
||
<p className="mt-[3px] mb-1 line-clamp-1 text-[10.5px] leading-[1.45] text-ink-3">
|
||
{row.persona_prompt || row.appearance || row.description || row.prompt || row.voice_profile || '尚未填写设定。'}
|
||
</p>
|
||
<TagGroup size="sm" className="mb-0 flex-nowrap overflow-hidden">
|
||
{(row.tags || []).slice(0, 4).map((tag: string) => (
|
||
<Chip key={tag} size="sm" title={`只看标签「${tag}」`}
|
||
onClick={() => patchFilters({ tag })}>{tag}</Chip>
|
||
))}
|
||
<ScopeTag row={row} />
|
||
<Tag title={`共 ${row.media_count} 个素材,占 ${fmtBytes(row.media_bytes)}`}>
|
||
{row.media_count} 素材 · {fmtBytes(row.media_bytes)}
|
||
</Tag>
|
||
<Tag>{row.style_version || row.version || 'v1'} · {fmtAgo(row.updated_at)}</Tag>
|
||
</TagGroup>
|
||
</div>
|
||
<div className="row-media flex items-center gap-[5px] shrink-0">
|
||
{stripOf(row, 5).map((media: any) => (
|
||
<MediaTile key={media.id} media={media} width="58px" size="xs" radius={6}
|
||
queue={itemsOf(row)} index={mediaIndex(row, media)}
|
||
onRemove={() => void deleteMedia(media)} />
|
||
))}
|
||
{(row.assets || []).filter(isAudio).slice(0, 2).map((media: any) => (
|
||
<div key={`a-${media.id}`} className="w-[160px] flex-none min-w-0">
|
||
<AudioPlay src={media.url} size="sm" compact label={media.kind_label}
|
||
durationMs={media.duration_ms} />
|
||
</div>
|
||
))}
|
||
{!row.assets?.length && <span className={cn(MUTED, 'text-tiny')}>暂无素材</span>}
|
||
</div>
|
||
<div className="flex flex-col gap-1 w-[132px] flex-none items-stretch [--ctl-h:var(--ctl-h-md)]">
|
||
<Button variant="primary" size="sm" onClick={() => openGenerate(row)}>
|
||
▤ {isVoice ? '生成试听' : 'AI 生成'}
|
||
</Button>
|
||
<div className="flex gap-1 [&>*]:flex-1">
|
||
<FilePick label="上传" title="选完即作为新版本登记到这个母版下"
|
||
onFiles={(files) => files.forEach((file) => void uploadFile(row, file, uploadKindFor(row)))} />
|
||
<Button variant="outline" size="sm" onClick={() => openImportSelection(row)}>引入</Button>
|
||
</div>
|
||
<div className="flex gap-1 [&>*]:flex-1">
|
||
<Button variant="outline" size="sm" onClick={() => openEdit(row)}>编辑</Button>
|
||
<Button variant="del" title="删除这个资源" onClick={() => setConfirmDelete(row)}>删除</Button>
|
||
</div>
|
||
</div>
|
||
</article>
|
||
))}
|
||
</div>
|
||
) : (
|
||
/* 网格视图:卡片信息最全,一屏两张 */
|
||
<Grid cols={2} gap={10} oneAt="mid">
|
||
{rows.map((row: any, idx: number) => {
|
||
const audios = (row.assets || []).filter(isAudio)
|
||
return (
|
||
<article key={row.id}
|
||
className={cn('relative flex flex-col min-w-0 p-[14px] rounded-[11px] border border-emphasis '
|
||
+ 'bg-[linear-gradient(145deg,var(--c-bg-panel),var(--c-bg-sunken))]',
|
||
isSelected(row) && 'border-accent-line shadow-[0_0_0_1px_var(--c-accent-tint)]',
|
||
row.duplicate_of?.length && 'border-warn-line')}>
|
||
<label className={PICK}
|
||
title={isSelected(row) ? '取消选择' : '勾选后可批量引入 / 打标签 / 删除(Shift 范围选择)'}>
|
||
<input type="checkbox" checked={isSelected(row)}
|
||
onClick={(e) => e.stopPropagation()}
|
||
onChange={(e) => toggleSelect(row, idx, (e.nativeEvent as MouseEvent).shiftKey)} />
|
||
</label>
|
||
<div className="flex items-start gap-2.5 pl-[22px] min-w-0">
|
||
<Portrait name={row.name} />
|
||
<div className="grow min-w-0">
|
||
<div className="flex items-center gap-[5px] flex-wrap">
|
||
<h3 className="m-0 text-ui truncate">{row.name}</h3>
|
||
{!!row.is_default && <Tag tone="ok">默认声线</Tag>}
|
||
{row.is_active === false && <Tag tone="bad">停用</Tag>}
|
||
{!!row.duplicate_of?.length && (
|
||
<Tag tone="bad"
|
||
title={`与 ${row.duplicate_of.map((d: any) => d.name || d.asset_name).join('、')} 同名或同代号,建议合并`}>
|
||
疑似重复
|
||
</Tag>
|
||
)}
|
||
{!row.media_count && <Tag tone="warn">待补素材</Tag>}
|
||
</div>
|
||
<div className={MUTED_MONO}>{row.code || `${type}-${row.id}`}</div>
|
||
</div>
|
||
<Button variant="outline" size="sm" onClick={() => openEdit(row)}>编辑</Button>
|
||
</div>
|
||
|
||
<p className={SUMMARY}>
|
||
{row.persona_prompt || row.appearance || row.description || row.prompt || row.voice_profile || '尚未填写设定。'}
|
||
</p>
|
||
|
||
<TagGroup size="sm" className="mb-0">
|
||
{(row.tags || []).slice(0, 5).map((tag: string) => (
|
||
<Chip key={tag} size="sm" title={`只看标签「${tag}」`}
|
||
onClick={() => patchFilters({ tag })}>{tag}</Chip>
|
||
))}
|
||
{type === 'human' && <Tag>{row.role || '角色'}</Tag>}
|
||
{type === 'human' && !!row.default_voice_name && (
|
||
<Tag title={`默认声线:${row.default_voice_name}`}>声线 · {row.default_voice_name}</Tag>
|
||
)}
|
||
{type === 'scene' && (
|
||
<Tag>{[row.lighting, row.time_of_day, row.palette].filter(Boolean).join(' · ') || '未设定光线'}</Tag>
|
||
)}
|
||
{type === 'voice' && <Tag>{row.provider || '生成时选模型'} · {row.language || 'zh-CN'}</Tag>}
|
||
<ScopeTag row={row} />
|
||
<Tag title={`共 ${row.media_count} 个素材,占 ${fmtBytes(row.media_bytes)}`}>
|
||
{row.media_count} 素材 · {fmtBytes(row.media_bytes)}
|
||
</Tag>
|
||
</TagGroup>
|
||
|
||
{!!stripOf(row).length && (
|
||
<div className="mt-[10px] grid grid-cols-4 gap-[5px] max-narrow:grid-cols-2 min-w-0 [&>*]:min-w-0">
|
||
{stripOf(row).map((media: any) => (
|
||
<MediaTile key={media.id} media={media} size="sm" radius={7}
|
||
queue={itemsOf(row)} index={mediaIndex(row, media)}
|
||
onRemove={() => void deleteMedia(media)} />
|
||
))}
|
||
</div>
|
||
)}
|
||
{audios.map((media: any) => {
|
||
const flag = timbreBadge(media)
|
||
const provenance = provenanceBadge(media)
|
||
return (
|
||
<div key={`audio-${media.id}`}
|
||
className="flex items-center gap-1 mt-1.5 min-w-0">
|
||
<div className="flex-1 min-w-0">
|
||
<AudioPlay src={media.url} size="sm" label={media.name || media.kind_label}
|
||
durationMs={media.duration_ms} hint={versionHint(media)} />
|
||
</div>
|
||
{flag && (
|
||
<Tag size="sm" tone={flag.tone} title={flag.title}
|
||
className="flex-none min-w-0 max-w-[40%] truncate">
|
||
◈ {flag.label}
|
||
</Tag>
|
||
)}
|
||
{!!provenance && (
|
||
<Tag size="sm" tone="warn" title={provenance}
|
||
className="flex-none min-w-0 max-w-[40%] truncate">
|
||
◌ AI 样本 · 非参考
|
||
</Tag>
|
||
)}
|
||
<Button variant="del" size="sm" square title="单独删除此音频(含全部历史版本)"
|
||
aria-label="删除这条音频" onClick={() => void deleteMedia(media)}>×</Button>
|
||
</div>
|
||
)
|
||
})}
|
||
{!row.assets?.length && (
|
||
<div className="mt-[10px] grid place-items-center min-h-[55px] px-2 rounded-[7px] border border-dashed border-line text-dim text-tiny text-center">
|
||
暂无素材:用下方「AI 生成」出图 / 出试听,或直接上传现成文件。
|
||
</div>
|
||
)}
|
||
|
||
<div className="mt-auto flex items-center gap-[5px] flex-wrap pt-[11px] border-t border-active [--ctl-h:var(--ctl-h-md)]">
|
||
<Button variant="primary" size="sm" onClick={() => openGenerate(row)}>
|
||
▤ {isVoice ? '生成试听' : 'AI 生成'}
|
||
</Button>
|
||
<Select size="sm" className="w-[105px]" ariaLabel="选择要上传的资产类型"
|
||
value={uploadKindFor(row)}
|
||
onChange={(next) => setUploadKinds((prev) => ({ ...prev, [keyOf(row)]: String(next) }))}
|
||
options={UPLOAD_KINDS[type].map((kind) => ({ value: kind, label: opt('asset_kinds', kind) }))} />
|
||
<FilePick label="上传" title="按左侧类型登记为新版本;同名素材会追加版本,不会新建一条"
|
||
onFiles={(files) => files.forEach((file) => void uploadFile(row, file, uploadKindFor(row)))} />
|
||
{isVoice && (
|
||
<RecordAudio label="录制" target={opt('asset_kinds', uploadKindFor(row))}
|
||
defaultName={recordDefaultName(row, uploadKindFor(row))}
|
||
names={existingNames(row.assets)}
|
||
hint="弹出小面板:录 → 试听 → 再决定存成哪条素材的哪个版本"
|
||
onPick={(file, picked) => void recordSample(row, file, picked)} />
|
||
)}
|
||
<Button variant="outline" size="sm" onClick={() => openImportSelection(row)}>引入项目 →</Button>
|
||
<Button variant="del" title="删除这个资源" onClick={() => setConfirmDelete(row)}>删除</Button>
|
||
<span className={STAMP}>
|
||
{row.style_version || row.version || 'v1'} · 更新于 {fmtAgo(row.updated_at)}
|
||
</span>
|
||
</div>
|
||
</article>
|
||
)
|
||
})}
|
||
</Grid>
|
||
)}
|
||
|
||
{view !== 'media' && rows.length > 0 && (
|
||
<Pager page={summary.page} pages={summary.pages} total={resultCount}
|
||
pageSize={filters.page_size} sizes={PAGE_SIZES}
|
||
onPageSize={(next) => patchFilters({ page_size: next })}
|
||
onPage={(next) => patchFilters({ page: next })} />
|
||
)}
|
||
{view === 'media' && wall.total > 0 && (
|
||
<Pager page={wall.page} pages={wall.pages} total={wall.total}
|
||
pageSize={filters.page_size} sizes={PAGE_SIZES}
|
||
onPageSize={(next) => patchFilters({ page_size: next })}
|
||
onPage={(next) => patchWall({ page: next })} />
|
||
)}
|
||
</Panel>
|
||
</section>
|
||
</div>
|
||
|
||
{/* ── 新建 / 编辑母版 ────────────────────────────────────────
|
||
抽屉而不是模态:这个表单最长有 11 个字段,模态里滚到一半就会把「保存」
|
||
挤出可视区;Drawer 的动作条钉在底部,永远点得到。 */}
|
||
<Drawer open={drawer} onClose={() => setDrawer(false)} label="编辑平台资产"
|
||
title={<span title="修改只影响平台母版;项目中的历史引入副本仍按快照独立存在。">
|
||
{editingId ? '编辑' : '新建'}{TYPE_META[form.type].label}母版
|
||
</span>}
|
||
actions={<>
|
||
<Button variant="primary" disabled={!!busy} onClick={() => void save()}>
|
||
{busy ? '处理中…' : '保存母版'}
|
||
</Button>
|
||
<Button variant="outline" onClick={() => setDrawer(false)}>取消</Button>
|
||
</>}>
|
||
<FormGrid>
|
||
{/* 长文本字段要有可写的面积,还要允许用户自己继续拉高(旧站 .drawer-body textarea) */}
|
||
<div className={TEXTAREA_TALL}>
|
||
<FormRow>
|
||
<Field label="名称" required>
|
||
<input value={form.name} placeholder="角色 / 场景 / 声线名称"
|
||
onChange={(e) => patchForm({ name: e.target.value })} />
|
||
</Field>
|
||
<Field label="代号">
|
||
<input value={form.code} placeholder="可留空"
|
||
onChange={(e) => patchForm({ code: e.target.value })} />
|
||
</Field>
|
||
<Field label="标签">
|
||
<input value={form.tags} placeholder="科幻 主角 冷色"
|
||
onChange={(e) => patchForm({ tags: e.target.value })} />
|
||
</Field>
|
||
</FormRow>
|
||
|
||
{form.type === 'human' && (
|
||
<>
|
||
<FormRow>
|
||
<Field label="定位">
|
||
<Select value={form.role} options={ROLES.map((r) => ({ value: r, label: r }))}
|
||
onChange={(next) => patchForm({ role: String(next) })} ariaLabel="角色定位" />
|
||
</Field>
|
||
<Field label="造型版本">
|
||
<input value={form.style_version}
|
||
onChange={(e) => patchForm({ style_version: e.target.value })} />
|
||
</Field>
|
||
<Field label="默认声线">
|
||
<Select value={form.default_voice_id}
|
||
options={[{ value: null, label: '不绑定' },
|
||
...voices.map((v: any) => ({ value: v.id, label: v.name }))]}
|
||
onChange={(next) => patchForm({ default_voice_id: next == null ? null : Number(next) })}
|
||
ariaLabel="默认声线" />
|
||
</Field>
|
||
</FormRow>
|
||
<FieldBlock label="外观">
|
||
<textarea value={form.appearance} rows={2} placeholder="五官、发型、体型、服装与配饰"
|
||
onChange={(e) => patchForm({ appearance: e.target.value })} />
|
||
</FieldBlock>
|
||
<FieldBlock label="性格与表演">
|
||
<textarea value={form.personality} rows={2}
|
||
onChange={(e) => patchForm({ personality: e.target.value })} />
|
||
</FieldBlock>
|
||
<FieldBlock label="一致性提示词">
|
||
<textarea value={form.persona_prompt} rows={3}
|
||
onChange={(e) => patchForm({ persona_prompt: e.target.value })} />
|
||
</FieldBlock>
|
||
<FormRow>
|
||
<Field label="声音描述">
|
||
<input value={form.voice_profile}
|
||
onChange={(e) => patchForm({ voice_profile: e.target.value })} />
|
||
</Field>
|
||
</FormRow>
|
||
</>
|
||
)}
|
||
|
||
{form.type === 'scene' && (
|
||
<>
|
||
<FormRow>
|
||
<Field label="光线">
|
||
<input value={form.lighting} onChange={(e) => patchForm({ lighting: e.target.value })} />
|
||
</Field>
|
||
<Field label="时间">
|
||
<input value={form.time_of_day}
|
||
onChange={(e) => patchForm({ time_of_day: e.target.value })} />
|
||
</Field>
|
||
<Field label="主色调">
|
||
<input value={form.palette} onChange={(e) => patchForm({ palette: e.target.value })} />
|
||
</Field>
|
||
</FormRow>
|
||
<FieldBlock label="场景描述">
|
||
<textarea value={form.description} rows={2}
|
||
onChange={(e) => patchForm({ description: e.target.value })} />
|
||
</FieldBlock>
|
||
<FieldBlock label="一致性提示词">
|
||
<textarea value={form.prompt} rows={3}
|
||
onChange={(e) => patchForm({ prompt: e.target.value })} />
|
||
</FieldBlock>
|
||
</>
|
||
)}
|
||
|
||
{form.type === 'voice' && (
|
||
<>
|
||
<FormRow>
|
||
<Field label="语言">
|
||
<input value={form.language} onChange={(e) => patchForm({ language: e.target.value })} />
|
||
</Field>
|
||
<Field label="性别">
|
||
<Select value={form.gender} options={GENDERS}
|
||
onChange={(next) => patchForm({ gender: String(next ?? '') })} ariaLabel="声线性别" />
|
||
</Field>
|
||
<Field label="语速">
|
||
<input type="number" min={0.5} max={2} step={0.05} value={form.tuning_speed}
|
||
onChange={(e) => patchForm({ tuning_speed: Number(e.target.value) })} />
|
||
</Field>
|
||
<Field label="效果" title={EFFECT_HINT}>
|
||
<Select value={form.tuning_effect} options={EFFECTS}
|
||
onChange={(next) => patchForm({ tuning_effect: String(next ?? '') })}
|
||
ariaLabel="声音效果" />
|
||
</Field>
|
||
<Check className="self-end h-(--ctl-h-md)" checked={form.is_default}
|
||
onChange={(next) => patchForm({ is_default: next })}>
|
||
设为平台默认声线
|
||
</Check>
|
||
</FormRow>
|
||
<FieldBlock label="音色描述">
|
||
<textarea value={form.description} rows={3}
|
||
onChange={(e) => patchForm({ description: e.target.value })} />
|
||
</FieldBlock>
|
||
<FormRow>
|
||
<Field label="版本">
|
||
<input value={form.version} onChange={(e) => patchForm({ version: e.target.value })} />
|
||
</Field>
|
||
</FormRow>
|
||
</>
|
||
)}
|
||
|
||
<FieldBlock label="备注">
|
||
<textarea value={form.notes} rows={2} onChange={(e) => patchForm({ notes: e.target.value })} />
|
||
</FieldBlock>
|
||
<ErrorText>{error}</ErrorText>
|
||
</div>
|
||
</FormGrid>
|
||
</Drawer>
|
||
|
||
{/* AS-1:AI 生成表单收进右侧抽屉。以前每张卡片里塞一个 600px 的表单,
|
||
三个人物就能把页面撑出三屏,现在卡片上只留「AI 生成」入口。
|
||
抽屉比默认档窄一半(980px):生成时要一边看现有素材一边调提示词,
|
||
整屏盖住就找不到「刚才那张图长什么样」了。 */}
|
||
{genDrawer && genTarget && (
|
||
<Drawer open onClose={() => setGenDrawer(false)} label="生成平台素材"
|
||
width="w-[min(980px,calc(100vw-64px))] max-mid:w-[min(760px,calc(100vw-24px))] max-short:w-screen"
|
||
title={genTarget.name}
|
||
sub={<span className={MONO}>
|
||
{genTarget.code || `${type}-${genTarget.id}`} · 现有 {genTarget.media_count || 0} 个素材
|
||
· {fmtBytes(genTarget.media_bytes)}
|
||
{!!genTarget.usage_count && ` · 已引入 ${genTarget.usage_count} 个项目`}
|
||
</span>}>
|
||
<div className="flex flex-col gap-3">
|
||
<Panel className="border-line-strong bg-card p-[10px]">
|
||
<FormGrid>
|
||
<Between tight className="mb-[10px] gap-x-[14px]">
|
||
<b className="text-caption">AI {isVoice ? '试听' : '母版生成'}</b>
|
||
<span className={cn(MUTED, 'text-tiny')}>{specCaps(genTarget).label || '模型注册表读取中…'}</span>
|
||
</Between>
|
||
|
||
<FormRow>
|
||
<Field label="模型">
|
||
<Select size="sm" value={modelRef(genTarget)} ariaLabel="生成模型"
|
||
placeholder={noModelHint(isVoice)}
|
||
onChange={(next) => setDraft(genTarget, { model: String(next) })}
|
||
options={[
|
||
{ value: '', label: noModelHint(isVoice), disabled: true },
|
||
...genModels.map((p: ModelRow) => ({
|
||
value: refOf(p),
|
||
label: `${p.display_name || `${p.provider}/${p.model}`}${p.is_default ? '(平台默认)' : ''}`
|
||
}))
|
||
]} />
|
||
</Field>
|
||
{!isVoice && (
|
||
<Field label="类型">
|
||
<Select size="sm" value={draft.kind} ariaLabel="生成素材类型"
|
||
onChange={(next) => selectAtmosphereReference(genTarget, String(next))}
|
||
options={KIND_CHOICES[isScene ? 'scene' : 'human']} />
|
||
</Field>
|
||
)}
|
||
</FormRow>
|
||
|
||
{isVoice && (
|
||
<FieldBlock label="试听文本" required>
|
||
<textarea rows={2} value={draft.sample_text}
|
||
title="这是要念出来的台词,不是声线设定;「音色描述」不会被当成台词。"
|
||
placeholder="输入一句要让模型朗读的台词,例如:我是俊杰,公司的产品专家。"
|
||
onChange={(e) => setDraft(genTarget, { sample_text: e.target.value })} />
|
||
</FieldBlock>
|
||
)}
|
||
|
||
{!isVoice && (
|
||
<>
|
||
<FormRow>
|
||
<Field label="分辨率档位">
|
||
<Select size="sm" value={draftTier(genTarget)} ariaLabel="分辨率档位"
|
||
onChange={(next) => setDraft(genTarget, { tier: String(next) })}
|
||
options={tierChoices(genTarget).map((tk: any) => ({
|
||
value: tk.value, label: `${tk.label}(长边 ${tk.edge}px)`
|
||
}))} />
|
||
</Field>
|
||
<Field label="画幅">
|
||
<Select size="sm" value={draftAspect(genTarget)} ariaLabel="画幅"
|
||
onChange={(next) => setDraft(genTarget, { aspect: String(next) })}
|
||
options={aspectChoices(genTarget).map((a: any) => ({ value: a.value, label: a.label }))} />
|
||
</Field>
|
||
</FormRow>
|
||
|
||
{/* 能力条:把选中模型真的支持什么摊开,而不是等用户提交后吃一个 400 */}
|
||
<Row tight className="gap-1 mb-[10px]">
|
||
{!!caps.resolutions.length && <Tag>档位 {caps.resolutions.join(' / ')}</Tag>}
|
||
{!!caps.aspectRatios.length && <Tag>画幅 {caps.aspectRatios.join(' / ')}</Tag>}
|
||
<Tag>输出 {canvasOf(genTarget).width}×{canvasOf(genTarget).height}</Tag>
|
||
{!!caps.maxReferenceImages && <Tag>参考图 ≤ {caps.maxReferenceImages}</Tag>}
|
||
{!caps.known && <Tag tone="bad">模型未注册</Tag>}
|
||
</Row>
|
||
|
||
<div className={REF_BOX}>
|
||
<FieldBlock label="参考图(可多选,留空即纯文生图)"
|
||
className="flex-1 min-w-[220px] mb-0">
|
||
<MultiSelect size="sm" value={draft.reference_media_ids}
|
||
ariaLabel={`${genTarget.name}:参考图`}
|
||
onChange={(ids) => pickReferences(genTarget, ids)}
|
||
options={imageReferenceOptions(genTarget).map((m: any) => ({
|
||
value: m.id, label: `${m.name || m.kind_label} · v${m.version}`
|
||
}))} />
|
||
</FieldBlock>
|
||
<FilePick accept="image/*" label="上传参考图" className={REF_PICK}
|
||
title="选完直接登记为该母版的一个新版本,随即可在上方勾选"
|
||
onFiles={(files) => files.forEach((f) => void uploadImageReference(genTarget, f))} />
|
||
<small className={REF_HINT}>
|
||
已选 {draft.reference_media_ids.length} / {specCaps(genTarget).maxReferenceImages || 1} 张。
|
||
定妆图、三视图或场景图可作一致性锚点;超出上限时按勾选顺序取前几张。
|
||
</small>
|
||
</div>
|
||
|
||
<FieldBlock label="补充提示" className="mt-[10px]">
|
||
<textarea rows={2} value={draft.prompt} placeholder="留空则自动使用母版设定"
|
||
onChange={(e) => setDraft(genTarget, { prompt: e.target.value })} />
|
||
</FieldBlock>
|
||
</>
|
||
)}
|
||
|
||
{isVoice && (
|
||
<div className={REF_BOX}>
|
||
<Field label="参考音色" width="grow" className="flex-1 min-w-[220px]">
|
||
<Select size="sm" value={draft.reference_media_id} ariaLabel="参考音色"
|
||
onChange={(next) => {
|
||
setDraft(genTarget, { reference_media_id: next == null ? null : Number(next) })
|
||
void loadVoiceReferenceStatus(genTarget)
|
||
}}
|
||
options={[
|
||
{ value: null, label: '自动(本声线 → 同性别声线 → 模型默认)' },
|
||
...referenceOptions(genTarget).map((m: any) => ({
|
||
value: m.id, label: `${m.name || m.kind_label} · v${m.version}`
|
||
}))
|
||
]} />
|
||
</Field>
|
||
<FilePick accept="audio/*" label="上传参考音色" className={REF_PICK}
|
||
title="上传后立即可勾选为本次克隆的参考"
|
||
onFiles={(files) => files.forEach((f) => void uploadReferenceFile(genTarget, f))} />
|
||
<RecordAudio label="录制参考音色" target="参考音色"
|
||
defaultName={defaultAssetName(genTarget.assets || [],
|
||
`${genTarget.name || '声线'}参考音色`, 'reference')}
|
||
names={existingNames(genTarget.assets)}
|
||
hint="弹出小面板:对着麦克风念几句话即可当作克隆参考,录完自动转成 WAV"
|
||
onPick={(file, meta) => void recordReference(genTarget, file, meta)} />
|
||
{voiceRefBusy && <div className={cn(REF_FULL, REF_STATUS, 'text-dim')}>正在确认这次会用谁的嗓子…</div>}
|
||
{!voiceRefBusy && voiceRefStatus && (
|
||
<div className={cn(REF_FULL, REF_STATUS,
|
||
!voiceRefStatus.ready && REF_BAD,
|
||
(voiceRefStatus.borrowed || voiceRefStatus.bound_generated) && REF_WARN)}>
|
||
<b>本次音色:{voiceRefStatus.note}</b>
|
||
{voiceRefStatus.bound_generated
|
||
? <small>
|
||
这条声线现在挂着的是<b>模型生成的试听样本</b>,不是真人录音:可以拿去给镜头配音,
|
||
但不能反过来当克隆参考,否则第一次生成错了性别,之后每次重试都会继续克隆那个错的嗓子。
|
||
上传一段{voiceRefStatus.gender_label}真人参考音频就能固定成这个角色自己的音色。
|
||
</small>
|
||
: <small>
|
||
设定性别:{voiceRefStatus.gender_label}。音色由参考音频决定,「性别 / 音色描述」只是标注——
|
||
要给这个角色一副自己的嗓子,请上传一段同性别参考音频。
|
||
</small>}
|
||
</div>
|
||
)}
|
||
<small className={REF_HINT}>
|
||
需要参考音频的模型(如 IndexTTS2)用参考音频做 zero-shot 音色克隆;
|
||
设定了性别却没有任何同性别参考时,平台会直接拒绝生成,而不是悄悄给你一个陌生人的嗓门。
|
||
</small>
|
||
</div>
|
||
)}
|
||
|
||
<Button variant="primary" size="sm"
|
||
disabled={!!busy || !genModels.length || !generationSpec(genTarget)
|
||
|| (isVoice && (!String(draft.sample_text || '').trim() || !voiceHasReference(genTarget)))}
|
||
onClick={() => void generate(genTarget)}>
|
||
{busy ? '处理中…' : (isVoice ? '◉ 生成试听样本' : '▧ 生成母版图像')}
|
||
</Button>
|
||
<ErrorText>{error}</ErrorText>
|
||
|
||
{/* 注册表不在首屏:所以这里必须解释「为什么模型下拉是空的」,
|
||
否则用户只会看到一个空下拉,以为平台没接模型。 */}
|
||
{registryError
|
||
? <small className={PROVIDER_WARN}>模型注册表读取失败:{registryError}</small>
|
||
: registryBusy
|
||
? <small className={PROVIDER_WARN}>正在读取模型注册表…</small>
|
||
: !genModels.length
|
||
? <small className={PROVIDER_WARN}>
|
||
当前没有已启用的真实{isVoice ? '声音' : '图像'}模型(mock 演练通道不出正式素材),请先到{' '}
|
||
<Link to="/models" className={LINK_CLS}>模型中心</Link> 启用。
|
||
</small>
|
||
: null}
|
||
</FormGrid>
|
||
</Panel>
|
||
|
||
{!!genTarget.assets?.length && (
|
||
<div className="flex flex-col gap-[7px] p-[10px] border border-line rounded-tile bg-card">
|
||
<SectionTitle className="mt-0"
|
||
title="生成结果作为该母版的 新版本 登记,旧版本仍可在预览器里逐版切换;项目里已锁定的快照不会自动改版。">
|
||
现有素材({genTarget.assets.length})
|
||
</SectionTitle>
|
||
<Grid gap={6} className="grid-cols-[repeat(auto-fill,minmax(76px,1fr))] items-center">
|
||
{genTarget.assets.filter((item: any) => isImage(item)).map((media: any) => (
|
||
<MediaThumb key={media.id} item={fromAsset(media)} size="xs" radius={6}
|
||
title={media.name || media.kind_label}
|
||
queue={itemsOf(genTarget)} index={mediaIndex(genTarget, media)} />
|
||
))}
|
||
</Grid>
|
||
{!!genTarget.assets.filter(isAudio).length && (
|
||
<div className="flex flex-col gap-[5px]">
|
||
{genTarget.assets.filter(isAudio).map((media: any) => (
|
||
<div key={`a-${media.id}`} className="w-full min-w-0">
|
||
<AudioPlay src={media.url} size="sm" label={media.kind_label}
|
||
durationMs={media.duration_ms} hint={versionHint(media)} />
|
||
</div>
|
||
))}
|
||
</div>
|
||
)}
|
||
</div>
|
||
)}
|
||
</div>
|
||
</Drawer>
|
||
)}
|
||
|
||
{/* ── 确认框:删除母版 ───────────────────────────────────────
|
||
动作为什么要单独确认:这里删的是「母版 + 它的全部媒体版本」,
|
||
而项目里引入过的快照副本不受影响 —— 这句话必须写在按钮之前。 */}
|
||
<Modal open={!!confirmDelete} onClose={() => setConfirmDelete(null)} width={520}
|
||
label="确认删除平台母版"
|
||
title={confirmDelete && <>删除{TYPE_META[confirmDelete.owner_type || type].label}母版?</>}
|
||
footer={<>
|
||
<Button variant="del" danger disabled={!!busy} onClick={() => void runDelete()}>确认删除</Button>
|
||
<Button variant="outline" disabled={!!busy} onClick={() => setConfirmDelete(null)}>取消</Button>
|
||
</>}>
|
||
<p className={IMPORT_SUBJECT}>
|
||
将从平台资产库移除 <b className="text-accent-bright">「{confirmDelete?.name}」</b>
|
||
以及其母版媒体文件的全部版本;项目内已引入的快照副本不受影响。
|
||
</p>
|
||
</Modal>
|
||
|
||
{/* ── 引入到项目:复制成快照,而不是建立引用 ───────────────── */}
|
||
<Modal open={importTargets.length > 0} onClose={() => setImportTargets([])}
|
||
label="引入到项目资产库"
|
||
title={<>引入到项目资产库{importTargets.length > 1 ? `(${importTargets.length} 个母版)` : ''}</>}
|
||
footer={<>
|
||
<Button variant="primary" disabled={!!busy || !importProjectId}
|
||
onClick={() => void importIntoProject()}>
|
||
{busy ? '引入中…' : '确认引入'}
|
||
</Button>
|
||
<Button variant="outline" onClick={() => setImportTargets([])}>取消</Button>
|
||
</>}>
|
||
<p className={IMPORT_SUBJECT}>
|
||
{importTargets.length > 1
|
||
? <>将把已选的 <b className="text-accent-bright">{importTargets.length} 个{typeMeta.label}母版</b>
|
||
——{importTargets.slice(0, 8).map((r: any) => `「${r.name}」`).join('、')}
|
||
{importTargets.length > 8 ? ' 等' : ''} ——
|
||
复制为项目内独立快照,母版后续改版不影响项目。</>
|
||
: <>将{typeMeta.label}母版 <b className="text-accent-bright">「{importSubject?.name}」</b>
|
||
复制为项目内独立快照,后续改动互不影响。</>}
|
||
</p>
|
||
<FieldBlock label="目标项目">
|
||
<Select value={importProjectId} disabled={!projects.length} ariaLabel="目标项目"
|
||
onChange={(next) => setImportProjectId(next == null ? null : Number(next))}
|
||
options={[
|
||
{ value: null, label: '请选择要引入的项目', disabled: true },
|
||
...projects.map((p: any) => ({ value: p.id, label: `《${p.name}》 · ${projectHint(p)}` }))
|
||
]} />
|
||
</FieldBlock>
|
||
{!projects.length && <p className={cn(MUTED, 'm-0 mt-2')}>还没有项目可引入,请先创建项目。</p>}
|
||
<ErrorText>{error}</ErrorText>
|
||
</Modal>
|
||
|
||
{/* AS-10:批量操作确认框 —— 先把「影响面」摊开,再让按钮可点 */}
|
||
<Modal open={batchDialog === 'tag'} onClose={() => setBatchDialog('')}
|
||
label="批量标签" title="批量调整标签"
|
||
footer={<>
|
||
<Button variant="primary" size="sm"
|
||
disabled={!!busy || (!batchTags.add.trim() && !batchTags.remove.trim())}
|
||
onClick={() => void runBatchTag()}>
|
||
{busy ? '处理中…' : '应用标签'}
|
||
</Button>
|
||
<Button variant="outline" size="sm" onClick={() => setBatchDialog('')}>取消</Button>
|
||
</>}>
|
||
<p className={IMPORT_SUBJECT}>
|
||
将对已选的 <b className="text-accent-bright">{selected.size} 个{typeMeta.label}母版</b>生效:
|
||
{selectedRows.slice(0, 8).map((r: any) => `「${r.name}」`).join('、')}
|
||
{selectedRows.length > 8 ? ' 等' : ''}。
|
||
追加是合并、移除按整词匹配,两边同名标签以移除为准。
|
||
</p>
|
||
<FormRow>
|
||
<Field label="追加标签">
|
||
<input value={batchTags.add} placeholder="逗号或空格分隔,例如:科幻 待打磨"
|
||
onChange={(e) => setBatchTags((prev) => ({ ...prev, add: e.target.value }))} />
|
||
</Field>
|
||
<Field label="移除标签">
|
||
<input value={batchTags.remove} placeholder="留空即不移除"
|
||
onChange={(e) => setBatchTags((prev) => ({ ...prev, remove: e.target.value }))} />
|
||
</Field>
|
||
</FormRow>
|
||
</Modal>
|
||
|
||
<Modal open={batchDialog === 'delete'} onClose={() => setBatchDialog('')}
|
||
label="批量删除母版"
|
||
title={<>删除 {selected.size} 个母版?</>}
|
||
footer={<>
|
||
<Button variant="del" danger disabled={!!busy} onClick={() => void runBatchDelete()}>
|
||
{busy ? '处理中…' : `确认删除 ${selected.size} 个母版`}
|
||
</Button>
|
||
<Button variant="outline" size="sm" disabled={!!busy} onClick={() => setBatchDialog('')}>取消</Button>
|
||
</>}>
|
||
<p className={IMPORT_SUBJECT}>
|
||
将移除这些母版及其媒体文件的<b>全部版本</b>;项目内已引入的快照副本与生成台账不受影响。
|
||
</p>
|
||
<ul className={DIALOG_LIST}>
|
||
{selectedRows.map((row: any) => (
|
||
<li key={row.id}>
|
||
<b>{row.name}</b>
|
||
<span className={MUTED_MONO}>{row.code || `${type}-${row.id}`}</span>
|
||
<Tag>{row.media_count || 0} 素材</Tag>
|
||
<Tag tone={row.usage_count ? 'warn' : 'default'}>
|
||
{row.usage_count ? `已引入 ${row.usage_count} 个项目` : '未被引用'}
|
||
</Tag>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
</Modal>
|
||
|
||
<Modal open={batchDialog === 'media-delete'} onClose={() => setBatchDialog('')}
|
||
label="批量删除素材"
|
||
title={<>删除 {selectedMedia.size} 个素材?</>}
|
||
footer={<>
|
||
<Button variant="del" danger disabled={!!busy} onClick={() => void runBatchMediaDelete()}>
|
||
{busy ? '处理中…' : `确认删除 ${selectedMedia.size} 个素材`}
|
||
</Button>
|
||
<Button variant="outline" size="sm" disabled={!!busy} onClick={() => setBatchDialog('')}>取消</Button>
|
||
</>}>
|
||
<p className={IMPORT_SUBJECT}>
|
||
素材删除是<b>连同全部历史版本一起移除</b>,母版本身与项目快照副本保留。
|
||
</p>
|
||
<ul className={DIALOG_LIST}>
|
||
{selectedMediaRows.slice(0, 30).map((media: any) => (
|
||
<li key={media.id}>
|
||
<b>{media.name || media.kind_label}</b>
|
||
<span className={cn(MUTED, 'text-tiny')}>{media.owner_name}</span>
|
||
<Tag>v{media.version}{media.version_count > 1 ? ` 共 ${media.version_count} 版` : ''}</Tag>
|
||
<Tag>{fmtBytes(media.size_bytes)}</Tag>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
{selectedMediaRows.length > 30 && (
|
||
<p className="mt-[7px] mb-0 text-faint text-tiny">另有 {selectedMediaRows.length - 30} 个素材未列出。</p>
|
||
)}
|
||
</Modal>
|
||
</div>
|
||
)
|
||
}
|
||
|
||
/* ── 页面私有皮肤 / 小组件 ──────────────────────────────────────────
|
||
只在这一页出现的形状不值得塞进 components/ui:抽出去之后它会变成
|
||
「只有资产库会跟着改」的公共 API。皮肤写成模块级常量,JSX 里只剩结构。
|
||
跨页复用的(Panel / Field / Grid / Tag …)一律走 components/ui。 */
|
||
|
||
/** 统计卡:整张卡就是筛选入口,所以它必须是 button 而不是 div(AS-7) */
|
||
function MetricCard({ label, value, hint, title, active, onClick, lead, warn }: {
|
||
label: string; value: number | string; hint?: ReactNode; title?: string
|
||
active?: boolean; onClick?: () => void; lead?: boolean; warn?: boolean
|
||
}) {
|
||
return (
|
||
<button type="button" title={title} onClick={onClick}
|
||
className={cn('relative overflow-hidden min-w-0 text-left min-h-[104px] p-[14px_16px] rounded-block '
|
||
+ 'border border-line bg-[linear-gradient(145deg,var(--c-bg-panel),var(--c-bg-card))] '
|
||
+ 'hover:border-accent-line transition-colors',
|
||
lead && 'bg-[linear-gradient(145deg,var(--c-bg-raised),var(--c-bg-panel))] border-warn-line',
|
||
warn && 'border-warn-line',
|
||
// 命中当前筛选时点亮描边 + 数字,用户才知道「这一屏数字就是现在这批」
|
||
active && 'border-success-line shadow-[inset_0_0_0_1px_var(--c-success-line)] [&>span:first-of-type]:text-success')}>
|
||
<span className="pointer-events-none absolute inset-0
|
||
bg-[radial-gradient(circle_at_106%_132%,var(--c-tint-accent),transparent_58%)]" />
|
||
<span className="relative block text-faint text-tiny tracking-[.7px]">{label}</span>
|
||
<strong className={cn('relative block my-[8px_3px] text-h1 leading-[1.05] text-ink',
|
||
lead && 'text-accent', warn && 'text-warn')}>{value}</strong>
|
||
{hint && <small className="relative block text-dim text-tiny">{hint}</small>}
|
||
</button>
|
||
)
|
||
}
|
||
|
||
/** 头像占位:没有定妆图时至少留一个「这里站着谁」的形体(圆角下宽上窄=肩线) */
|
||
function Portrait({ name, sm }: { name?: string; sm?: boolean }) {
|
||
return (
|
||
<span className={cn('grid place-items-center flex-none border border-accent-line bg-accent-tint text-accent',
|
||
sm ? 'w-[30px] h-[34px] text-[14px] rounded-[8px_8px_11px_11px]'
|
||
: 'w-[38px] h-[42px] text-[18px] rounded-[10px_10px_13px_13px]')}>
|
||
{name?.slice(0, 1)}
|
||
</span>
|
||
)
|
||
}
|
||
|
||
/** 引用状态:删除母版前最需要知道的一件事就是「有没有项目在用」 */
|
||
function ScopeTag({ row }: { row: any }) {
|
||
return row.usage_count
|
||
? <Tag tone="ok"
|
||
title={`已引入 ${row.usage_count} 个项目:${(row.usage || []).map((u: any) => u.project_name).join('、')}\n删除母版不会影响这些快照副本`}>
|
||
已引入 {row.usage_count} 个项目
|
||
</Tag>
|
||
: <Tag title="还没有任何项目引入过这个母版">未被项目引用</Tag>
|
||
}
|
||
|
||
/** 素材缩略图 + 右上角单独删除叉;图片走预览器队列,文件只有一块说明砖 */
|
||
function MediaTile({ media, size = 'sm', radius = 7, width, queue, index, onRemove }: {
|
||
media: any; size?: 'xs' | 'sm'; radius?: number; width?: string
|
||
queue?: MediaItem[]; index?: number; onRemove: () => void
|
||
}) {
|
||
return (
|
||
<div className="relative min-w-0" style={width ? { width } : undefined}>
|
||
{isImage(media)
|
||
? <MediaThumb item={fromAsset(media)} size={size} radius={radius}
|
||
title={media.name || media.kind_label} queue={queue} index={index} />
|
||
: <div className={cn(FILE_TILE, size === 'xs' ? 'min-h-[34px]' : 'min-h-[55px]')}>
|
||
<b>{media.kind_label}</b>
|
||
<span>{fmtBytes(media.size_bytes)}{size === 'sm' && ` · v${media.version}`}</span>
|
||
</div>}
|
||
<button type="button" className={MEDIA_REMOVE} title="单独删除此媒体(含全部历史版本)"
|
||
aria-label="删除这个素材" onClick={(e) => { e.stopPropagation(); onRemove() }}>×</button>
|
||
</div>
|
||
)
|
||
}
|
||
|
||
/** 缩略图左上角的勾选框:压在图上,所以自带一层半透明底板 */
|
||
const PICK = 'absolute left-2 top-2 z-[3] grid place-items-center w-[21px] h-[21px] m-0 p-0 rounded-[6px] '
|
||
+ 'bg-[color-mix(in_srgb,var(--c-bg-shell)_74%,transparent)] '
|
||
+ '[&>input]:w-[13px] [&>input]:h-[13px] [&>input]:m-0 [&>input]:p-0'
|
||
/** 缩略图右上角的删除叉:不能压住 MediaThumb 左下的版本角标 */
|
||
const MEDIA_REMOVE = 'absolute right-[3px] top-[3px] grid place-items-center w-5 h-5 p-0 rounded-full '
|
||
+ 'border border-danger-line text-danger-bright text-[15px] leading-none hover:bg-danger-line '
|
||
+ 'bg-[color-mix(in_srgb,var(--c-danger-tint2)_91%,transparent)]'
|
||
const FILE_TILE = 'flex flex-col justify-between p-[6px] rounded-[6px] bg-hover '
|
||
+ '[&>b]:text-ink-2 [&>b]:text-tiny [&>span]:text-dim [&>span]:text-tiny'
|
||
const SUMMARY = 'line-clamp-3 min-h-[46px] mt-[10px] mb-[7px] text-[10.5px] leading-[1.55] text-muted'
|
||
/** 卡片右下角的「哪一版 / 什么时候改的」:等宽 + 截断,不参与挤压标题 */
|
||
const STAMP = 'ml-auto min-w-0 max-w-[140px] truncate font-mono text-tiny text-dim'
|
||
/** 确认框里那段「动的是什么」:左边一条重色竖线,比整块描边更像一个引用块 */
|
||
const IMPORT_SUBJECT = 'my-4 p-[11px_12px] border-l-2 border-l-accent-deep bg-card text-muted text-tiny '
|
||
+ 'leading-[1.7] [&_b]:text-accent-bright'
|
||
/** 批量影响面清单:最多 258px 高,超出内部滚动,避免长列表把按钮顶出屏幕 */
|
||
const DIALOG_LIST = 'flex flex-col gap-[5px] max-h-[258px] overflow-y-auto m-0 p-0 list-none '
|
||
+ '[&>li]:flex [&>li]:items-center [&>li]:gap-[6px] [&>li]:flex-wrap [&>li]:p-[6px_8px] '
|
||
+ '[&>li]:border [&>li]:border-emphasis [&>li]:rounded-[7px] [&>li]:bg-card [&>li>b]:text-tiny'
|
||
const PROVIDER_WARN = 'block mt-[7px] p-[6px_7px] border border-warn-line rounded-chip bg-raised text-warn '
|
||
+ 'text-tiny leading-[1.5]'
|
||
/**
|
||
* 参考素材区(图 / 音共用)。
|
||
*
|
||
* 旧站是 grid-template-columns: minmax(0,1fr) auto 的两列定宽网格,
|
||
* 上传按钮 + 录音按钮挤在第二列里换行;换成会拐弯的 flex 行之后同一套 DOM
|
||
* 在手机(≤560)上自动降成一列,不需要再写断点。
|
||
*/
|
||
const REF_BOX = 'flex items-end flex-wrap gap-[7px] mt-[7px] p-2 border border-line-strong rounded-control bg-field'
|
||
/** 参考区里的上传按钮:绿色描边表示「这一步不会改母版本体,只是喂料」 */
|
||
const REF_PICK = 'justify-center border-accent-line text-success'
|
||
const REF_HINT = 'basis-full text-dim text-tiny leading-[1.5]'
|
||
/** 参考区里的整行元素(状态盒) */
|
||
const REF_FULL = 'basis-full'
|
||
const REF_STATUS = 'grid gap-1 p-[7px_8px] rounded-[6px] border border-line-strong bg-card text-[9.5px] '
|
||
+ '[&>b]:text-[10.5px] [&>b]:leading-[1.5] [&>small]:text-faint [&>small]:leading-[1.5]'
|
||
const REF_WARN = 'border-warn-line bg-warn-tint [&>b]:text-warn-bright'
|
||
const REF_BAD = 'border-danger-line bg-danger-tint [&>b]:text-danger'
|
||
|
||
/** 「没有可用模型」这句话在标签、占位符、警告里出现三次,措辞必须一致 */
|
||
const noModelHint = (voice: boolean) => `没有已启用的真实${voice ? '声音' : '图像'}模型`
|
||
/** 生成类型下拉:和上传类型同源,新增一类素材只改这张表 */
|
||
const KIND_CHOICES: Record<'human' | 'scene', { value: string; label: string }[]> = {
|
||
human: [{ value: 'portrait', label: '定妆图' }, { value: 'turnaround', label: '三视图' },
|
||
{ value: 'expression', label: '表情参考' }],
|
||
scene: [{ value: 'scene_image', label: '场景图' }, { value: 'reference', label: '氛围图' }]
|
||
}
|
||
const EFFECT_HINT = '「外星低吼」是 macOS 系统语音适配器的滤镜参数,IndexTTS2 等模型会忽略它;'
|
||
+ '后端整字典覆盖 tuning,已保留的采样率等参数不会被这次保存清掉。'
|