修复 media/ 忽略规则误伤前端组件:补回 components/media 六个组件、部署体检增加前端源码完整性计数

main
mula.liu 2026-11-01 18:59:46 +08:00
parent 13e1990888
commit 816cdc25b7
8 changed files with 1208 additions and 5 deletions

7
.gitignore vendored
View File

@ -25,7 +25,14 @@ venv/
# 根下 media/、在 backend/ 下启动时漂出来的 backend/media/、以后某个模块
# 自己建的 backend/app/services/media/……只锚根目录的话,漂出去的副本会被提交。
# 斜杠结尾只匹配**目录**,所以 media.py / media.ts 这类代码文件不受影响。
# 但「不受影响」只到文件为止:前端 React 迁移新增了一个**同名的代码目录**
# frontend/src/components/media/(MediaThumb / AudioPlay / RecordAudio / VersionPanel /
# MediaLightbox / WorkflowBar),裸 media/ 连它一起忽略,六个组件长期没进版本库、
# 部署包里也缺一层,而两道体检当时都看不见(一个只看 .vue,一个不数前端文件)。
# 这里不改成锚根 /media/:上面三条漂出保护更有价值,改用显式反选把代码目录捞回来。
# 以后再有叫 media/ 的代码目录,这里和 scripts/deploy.sh 的 --include 要一起加。
media/
!frontend/src/components/media/
# /models/:whisper.cpp 听写权重 ggml-small.bin(465M,server.sh install 会自动下载)
# 这个**必须带前导斜杠**、只锚仓库根:backend/app/models/ 是 ORM 代码目录,
# 写成裸 `models/` 会连它一起忽略掉(deploy.sh 的 --exclude 'models/' 就是这么炸的)。

View File

@ -0,0 +1,87 @@
import { type MouseEvent } from 'react'
import { cn } from '../../lib/cn'
import { fmtMs } from '../../lib/format'
import { pauseAudio, playAudio, seekAudio, useAudioStore, useIsPlaying } from '../../stores/audio'
import { openMedia } from '../../stores/preview'
/**
* 全站统一的音频控件(替代散落在 4 个页面里的原生 <audio controls>)。
* 共用 stores/audio.ts 里的单例音频引擎:在任何页面点播放,上一段都会自动停下。
*/
export type AudioPlayProps = {
src: string
label?: string
durationMs?: number | null
hint?: string
size?: 'sm' | 'md'
/** 单行紧凑模式:窄容器(列表行的素材区)里只留播放键 + 进度条 + 时长。
* 否则名称和时间会被挤成两三行,溢出边框压到下一行的控件上。 */
compact?: boolean
cover?: boolean
}
export function AudioPlay({ src, label = '', durationMs = null, hint = '', size = 'md', compact = false, cover = true }: AudioPlayProps) {
/** 只订阅标量:zustand v5 走 useSyncExternalStore,返回新对象会触发
* 「getSnapshot 必须稳定」告警并无限重渲染。 */
const active = useAudioStore((s) => !!src && s.src === src)
const position = useAudioStore((s) => (s.src === src ? s.position : 0))
const duration = useAudioStore((s) => (s.src === src ? s.duration : 0))
const playing = useIsPlaying(src)
const total = active && duration ? duration * 1000 : Number(durationMs || 0)
const progress = active && total ? Math.min(100, (position * 1000 / total) * 100) : 0
if (!src) return <span className="text-[10.5px] text-faint">无音频</span>
const toggle = () => (playing ? pauseAudio() : playAudio(src, label || '音频'))
const onScrub = (e: MouseEvent<HTMLDivElement>) => {
const box = e.currentTarget.getBoundingClientRect()
const ratio = Math.min(1, Math.max(0, (e.clientX - box.left) / box.width))
if (!active) playAudio(src, label || '音频')
seekAudio((total / 1000) * ratio)
}
const fullTime = `${active ? fmtMs(position * 1000) : '00:00.00'} / ${total ? fmtMs(total) : '—'}`
/** 紧凑模式(列表行)里「00:00.00 / 00:05.08」会把进度条挤成一条缝:
* 没在放就只显示时长,播起来才显示进度,窄容器里也留得下可拖的进度条。 */
const timeText = compact && !active ? (total ? fmtMs(total) : '—') : fullTime
return (
<div className={cn('flex items-center gap-2.5 p-[8px_10px] min-w-0 border border-line rounded-tile bg-sunken transition-colors hover:border-line-bright hover:bg-hover',
size === 'sm' && 'p-[5px_8px] gap-2',
compact && 'p-[4px_7px] gap-[7px]',
active && 'border-accent-line bg-accent-tint')}>
<button type="button" onClick={(e) => { e.stopPropagation(); toggle() }}
aria-label={(playing ? '暂停' : '播放') + (label || '音频')}
title={(playing ? '暂停' : '播放') + '(全站同时只播一条)'}
className={cn('flex-none grid place-items-center w-7 h-7 rounded-full bg-accent-fill text-on-accent text-tiny font-bold hover:bg-accent-fill-deep',
(size === 'sm' || compact) && 'w-[22px] h-[22px]', compact && 'w-5 h-5')}>
{playing ? '❚❚' : '▶'}
</button>
<div className="flex-1 min-w-0 overflow-hidden">
{!compact && <p className="m-0 text-caption font-semibold text-ink-2 truncate">{label || '音频'}</p>}
<div className="flex items-center gap-[7px] min-w-0 overflow-hidden">
<div role="slider" aria-label={`${label || '音频'} 播放进度`} aria-valuenow={Math.round(progress)}
onClick={(e) => { e.stopPropagation(); onScrub(e) }}
className={cn('relative flex-1 min-w-6 h-[5px] my-[5px] mb-1 rounded-pill bg-active cursor-pointer hover:bg-line-strong', compact && 'm-0')}>
<i className="absolute left-0 top-0 h-full rounded-pill bg-accent-fill" style={{ width: `${progress}%` }} />
</div>
{compact && <span className="flex-none font-mono text-tiny text-faint whitespace-nowrap tabular-nums" title={fullTime}>{timeText}</span>}
</div>
{!compact && (
<p className="m-0 flex gap-2 items-center text-tiny text-faint min-w-0 whitespace-nowrap">
<span className="flex-none font-mono tabular-nums whitespace-nowrap">{timeText}</span>
{!!hint && <span className="min-w-0 truncate" title={hint}>{hint}</span>}
</p>
)}
</div>
{cover && (
<button type="button" title="在统一预览器中打开"
onClick={(e) => { e.stopPropagation(); openMedia({ url: src, kind: 'audio', name: label || '音频' }) }}
className={cn('flex-none w-[22px] h-[22px] border border-line-strong rounded-[6px] bg-transparent text-ink-3 text-tiny hover:border-accent-line hover:text-accent-bright', compact && 'w-[18px] h-[18px]')}>
⤢
</button>
)}
</div>
)
}

View File

@ -0,0 +1,333 @@
/**
* 全局唯一的媒体预览器(挂在 App 外壳上,整个平台共用一个实例)。
* 能力:图片 / 视频 / 音频 / 文档占位、←→ 在打开它的队列里翻页、
* Esc 关闭、Space 播放暂停、历史版本切换、元数据、下载、新窗口打开。
*
* 实现约定:它读的是 preview store 的整体状态(不写选择器),
* 派生值统一交给 stores/preview.ts 里那批纯 select* 函数在渲染期计算 ——
* zustand 的选择器返回新对象会让每次 set 都触发重渲染,翻页时尤其明显。
*/
import { useEffect, useRef, useState } from 'react'
import { cn } from '../../lib/cn'
import { iconFor, kindLabel, type MediaItem } from '../../lib/media'
import {
canManageVersions,
choosePeer,
chooseVersion,
closePreview,
goTo,
selectChosenVersion,
selectCurrentMeta,
selectCurrentUrl,
selectPeerIndex,
selectPeers,
selectShown,
setCurrentVersion,
resetVersion,
step,
toggleInfo,
toggleVersionPanel,
usePreviewStore,
viewedVersion
} from '../../stores/preview'
import { pauseAudio, playAudio, stopAudio, toggleAudio, useAudioStore } from '../../stores/audio'
import { Button, Eyebrow, Tag } from '../ui'
import { Select } from '../forms'
import { VersionPanel } from './VersionPanel'
/** 格子上写「关键帧」就够,括注里的「(平台配音)/(模型原声)」留给 tooltip */
const shortLabel = (pb: MediaItem) => pb.kindLabel.replace(/[((].*?[))]/g, '').trim() || pb.kindLabel
export function MediaLightbox() {
const store = usePreviewStore()
const isOpen = store.isOpen
const item = selectShown(store)
const src = selectCurrentUrl(store)
const meta = selectCurrentMeta(store)
const peers = selectPeers(store)
const peerIndex = selectPeerIndex(store)
const chosenVersion = selectChosenVersion(store)
const audioPlaying = useAudioStore((s) => s.playing)
const audioSrc = useAudioStore((s) => s.src)
const audioPosition = useAudioStore((s) => s.position)
const audioDuration = useAudioStore((s) => s.duration)
const [failed, setFailed] = useState(false)
const [copied, setCopied] = useState('')
const videoRef = useRef<HTMLVideoElement | null>(null)
const kind = item?.kind || 'none'
const versions = item?.versions || []
const count = store.items.length
const position = store.index + 1
const canSwitchVersion = versions.length > 1
const peerCount = peers.length
/* 版本管理:设为当前 / 删除某版。入口只在这里,因为整个平台只有预览器
有完整版本下拉;平台资产库与项目素材库共用同一套动作。 */
const manage = canManageVersions(item)
const viewed = viewedVersion(item)
const isCurrentViewed = !!item && viewed?.version_no === item.version
const canMakeCurrent = manage && versions.length > 1 && !isCurrentViewed && viewed?.exists !== false
// 文件丢失的版本不能设为默认(切过去就是白图),但可以在版本管理里删掉——
// 后端在「设为默认」被文件丢失挡住时,给的建议正是「删除该版本后重新上传」。
const missingFile = viewed?.exists === false
const onlyOneVersion = '只有一个版本,如需清理请直接删除该素材'
/* 按钮灰掉时必须说清为什么灰:预览的就是默认版时,「设为默认」无事可做,
但「版本管理」照样能点开删别的版本。 */
const makeCurrentHint = !manage ? '这条素材不是平台母版或项目资产,暂不支持版本管理'
: versions.length < 2 ? onlyOneVersion
: missingFile ? '该版本文件已丢失,无法设为默认;可以先删掉它再重新上传'
: isCurrentViewed ? '这一版已经是当前默认,先在上方下拉切到别的版本,或打开版本管理逐版操作'
: ''
const downloadHref = src ? `${src}` : ''
/* 预览期间锁住背景页面滚动:否则滚轮会滚到身后的列表,
同时避免页面滚动条让 fixed 弹窗出现 1~2px 的横向跳动。 */
useEffect(() => {
if (!isOpen) return
const el = document.documentElement
const prev = el.style.overflow
el.style.overflow = 'hidden'
return () => { el.style.overflow = prev }
}, [isOpen])
/* 预览器打开时,这些按键归预览器:必须抢在页面快捷键之前消费掉,
否则一次 Esc 会同时关掉预览器和右栏检查器(页面自己也绑了 Esc)。 */
useEffect(() => {
if (!isOpen) return
function onKeydown(event: KeyboardEvent) {
const tag = (event.target as HTMLElement | null)?.tagName
if (tag && /^(INPUT|TEXTAREA|SELECT)$/.test(tag)) return
const s = usePreviewStore.getState()
const shown = selectShown(s)
const pb = selectPeers(s)
let handled = true
switch (event.key) {
case 'Escape': closePreview(); break
case 'ArrowRight': step(1); break
case 'ArrowLeft': step(-1); break
case ' ': {
const node = videoRef.current
const url = selectCurrentUrl(s)
if (shown?.kind === 'video' && node) {
if (node.paused) void node.play()
else node.pause()
} else if (shown?.kind === 'audio' && url) {
toggleAudio(url, shown.title || '')
} else handled = false
break
}
case 'Home': goTo(0); break
case 'End': goTo(s.items.length - 1); break
case 'i': case 'I': toggleInfo(); break
case '[': case ']':
if (pb.length > 1) choosePeer((selectPeerIndex(s) + (event.key === ']' ? 1 : -1) + pb.length) % pb.length)
else handled = false
break
default: handled = false
}
if (!handled) return
event.preventDefault()
event.stopImmediatePropagation()
}
window.addEventListener('keydown', onKeydown, true)
return () => window.removeEventListener('keydown', onKeydown, true)
}, [isOpen])
/* 换素材时清掉上一次的加载失败标记,否则新图也一直被判为「无法加载」。 */
useEffect(() => { setFailed(false) }, [src])
/* 关掉预览器时把公共音频引擎让出来,别让声音留在身后。 */
useEffect(() => () => {
const s = usePreviewStore.getState()
if (s.isOpen) {
const el = document.documentElement
el.style.overflow = ''
}
if (selectShown(s)?.kind === 'audio' && useAudioStore.getState().playing) pauseAudio()
}, [])
function makeCurrent() {
const no = viewed?.version_no
if (no) void setCurrentVersion(no)
}
function copyLink() {
if (!src) return
void navigator.clipboard?.writeText(location.origin + src).then(() => {
setCopied('链接已复制')
window.setTimeout(() => { setCopied('') }, 1600)
}).catch(() => { setCopied('复制失败') })
}
function onClosed() {
if (useAudioStore.getState().playing) stopAudio()
closePreview()
}
if (!isOpen || !item) return null
const playingThis = audioPlaying && audioSrc === src
const progress = audioDuration ? Math.min(100, (audioPosition / audioDuration) * 100) : 0
return (
<div role="dialog" aria-modal="true" aria-label={'预览 ' + item.title}
className="fixed inset-0 z-220 grid place-items-center p-[14px] max-nav:p-2">
<div className="absolute inset-0 bg-backdrop [backdrop-filter:blur(7px)_saturate(.92)]" onClick={onClosed}></div>
{/* 高度必须是确定值:.canvas img 的 max-height:100% 只有在父级高度确定时才生效,
否则舞台高度由图片原始比例反推,footer 会被挤出 overflow:hidden,
表现为「元数据被裁一半、下载按钮旁边像缺了个控件」。 */}
<div className="relative flex h-[calc(100dvh-28px)] max-h-[min(1180px,calc(100dvh-28px))] min-h-[min(420px,calc(100dvh-28px))] w-[min(1560px,100%)] max-nav:h-[calc(100dvh-16px)] max-nav:max-h-[calc(100dvh-16px)] flex-col overflow-hidden rounded-float border border-line-strong bg-panel shadow-[0_26px_70px_var(--c-backdrop-shadow)]">
<header className="flex shrink-0 items-start justify-between gap-3.5 border-b border-line bg-raise px-4 py-3">
<div className="min-w-0 grow [&_p]:m-0">
<Eyebrow>{item.group || item.kindLabel || kindLabel(kind)} · {kindLabel(kind)}</Eyebrow>
<h3 className="mt-[3px] truncate text-[15px] font-bold">{item.title}</h3>
{item.subtitle && <p className="mt-1 truncate text-caption text-faint">{item.subtitle}</p>}
</div>
<div className="flex max-nav:max-w-[52%] shrink flex-wrap items-center justify-end gap-x-2 gap-y-1.5 max-w-[70%]">
{peerCount > 1 && (
<div role="group" aria-label="切换本镜产物"
className="flex items-center gap-0.5 rounded-[9px] border border-line bg-sunken p-0.5">
{peers.map((pb, pi) => (
<button key={pb.key} type="button"
className={cn('rounded-[7px] border border-transparent px-[9px] py-1 text-caption whitespace-nowrap hover:text-ink hover:bg-raise',
pi === peerIndex ? 'border-line-strong bg-panel font-semibold text-ink' : 'text-dim')}
title={`查看本镜的${pb.kindLabel}(${pi + 1}/${peerCount},[ 与 ] 切换)`}
onClick={() => choosePeer(pi)}>{shortLabel(pb)}</button>
))}
</div>
)}
{count > 1 && <span className="rounded-[7px] border border-line bg-sunken px-2 py-1 font-mono text-caption text-ink-3">{position} / {count}</span>}
{canSwitchVersion && (
<label className="flex shrink-0 flex-row items-center gap-1.5 text-[10.5px] whitespace-nowrap text-faint">
<span>版本</span>
<Select
size="sm"
ariaLabel="切换历史版本"
className="w-[164px] min-w-[128px] max-w-[196px]"
value={chosenVersion}
onChange={(no) => chooseVersion(Number(no))}
options={versions.map((v) => ({
value: v.version_no,
label: `v${v.version_no}${v.version_no === item.version ? '(当前默认)' : ''}${v.exists === false ? '(文件缺失)' : ''}`
}))}
/>
{chosenVersion !== item.version && (
<Button variant="ghost" title="回到当前默认版本" onClick={resetVersion}>回默认</Button>
)}
</label>
)}
{manage && canSwitchVersion && (
<div className="flex shrink-0 items-center gap-1.5 whitespace-nowrap">
<Button variant="ghost" disabled={!canMakeCurrent || store.versionBusy}
className={cn(canMakeCurrent && !store.versionBusy && 'border-accent-line text-accent-bright hover:not-disabled:bg-accent-tint')}
onClick={makeCurrent}
title={makeCurrentHint || `把正在预览的 v${viewed?.version_no} 设为当前默认版本,平台母版与之后引入项目的素材都会跟着切`}>
{store.versionBusy ? '处理中…' : '★ 设为默认'}
</Button>
<Button variant="ghost" on={store.versionPanelOpen} onClick={() => toggleVersionPanel()}
title={store.versionPanelOpen ? '收起版本管理' : `逐版查看 / 设为默认 / 删除,共 ${versions.length} 版`}>
▤ 版本管理<span className="ml-[5px] rounded-chip bg-active px-1 text-tiny">{versions.length}</span>
</Button>
</div>
)}
<Button variant="ghost" onClick={toggleInfo} title={store.collapsed ? '显示元数据 (I)' : '收起元数据 (I)'}>
{store.collapsed ? 'ⓘ 信息' : 'ⓘ 收起'}
</Button>
<Button variant="ghost" onClick={onClosed} title="关闭 (Esc)">✕</Button>
</div>
</header>
<div className="relative flex min-h-0 grow items-stretch gap-1.5 bg-deepest p-2.5 max-nav:p-2">
{count > 1 && (
<button type="button" onClick={() => step(-1)} disabled={store.index <= 0} title="上一个 (←)"
className="absolute top-1/2 left-4 z-3 grid h-[42px] w-[42px] -translate-y-1/2 place-items-center rounded-full border border-backdrop-veil bg-backdrop-veil p-0 pb-0.5 text-[21px] leading-none text-ink backdrop-blur-[6px] shadow-[0_6px_20px_var(--c-backdrop-shadow)] max-nav:left-2.5 max-nav:h-[34px] max-nav:w-[34px] max-nav:text-[17px] hover:not-disabled:scale-106 hover:not-disabled:border-accent-fill hover:not-disabled:bg-accent-fill hover:not-disabled:text-on-accent disabled:opacity-34">‹</button>
)}
{/* canvas 必须自己撑满 stage 且行高确定(minmax(0,1fr)),
否则 auto 行会按图片原始高度撑开,百分比 max-height 解析为 none → 图片溢出裁切 */}
<div className="relative grid min-h-0 min-w-0 grow [grid-template:minmax(0,1fr)/minmax(0,1fr)] place-items-center">
{kind === 'image' && (
<img src={src} alt={item.title} onError={() => setFailed(true)}
className={cn('max-h-full max-w-full rounded-[8px] bg-black', failed && 'invisible')} />
)}
{kind === 'video' && (
<video ref={videoRef} src={src} poster={item.poster || undefined} controls autoPlay playsInline
onError={() => setFailed(true)}
className={cn('max-h-full max-w-full rounded-[8px] bg-black', failed && 'invisible')} />
)}
{kind === 'audio' && (
<div className="max-h-full w-[min(460px,100%)] max-w-full overflow-auto rounded-block border border-line bg-panel px-[18px] py-6 text-center">
<div className={cn('mx-auto mb-3 grid h-[74px] w-[74px] place-items-center rounded-full border border-accent-line bg-accent-tint text-[26px] text-accent-bright', playingThis && 'animate-spin-slow')}>{iconFor('audio')}</div>
<p className="mb-3 text-ui font-semibold">{item.title}</p>
<div role="slider" aria-label="播放进度" aria-valuenow={Math.round(audioDuration ? (audioPosition / audioDuration) * 100 : 0)}
className="h-[5px] overflow-hidden rounded-pill bg-active">
<i className="block h-full bg-accent-fill" style={{ width: `${progress}%` }}></i>
</div>
<div className="mt-3.5 flex items-center justify-center gap-2">
<button type="button" onClick={() => playAudio(src, item.title)} disabled={playingThis} title="播放 (Space)"
className="h-[30px] w-[34px] rounded-[8px] border border-line-strong bg-sunken text-[11px] text-ink disabled:opacity-35">▶</button>
<button type="button" onClick={() => pauseAudio()} disabled={!playingThis} title="暂停 (Space)"
className="h-[30px] w-[34px] rounded-[8px] border border-line-strong bg-sunken text-[11px] text-ink disabled:opacity-35">❚❚</button>
<span className="ml-1.5 font-mono text-[10.5px] text-faint">{(audioPosition || 0).toFixed(1)}s / {audioDuration ? audioDuration.toFixed(1) + 's' : '—'}</span>
</div>
</div>
)}
{kind !== 'image' && kind !== 'video' && kind !== 'audio' && (
<div className="max-h-full max-w-full overflow-auto text-center text-ink-3">
<b className="text-[34px] font-normal text-muted">{iconFor(kind)}</b>
<p className="my-2 text-ui">{item.title}</p>
<a className="inline-flex items-center rounded-[7px] bg-accent-fill px-[11px] py-[7px] text-[10.5px] text-on-accent no-underline" href={downloadHref} target="_blank" rel="noopener">打开 / 下载文件</a>
</div>
)}
{failed && (
<div className="absolute inset-0 grid place-content-center justify-items-center gap-1.5 p-5 text-center">
<b className="text-ui text-danger-bright">无法加载该媒体</b>
<small className="max-w-[60vw] break-all font-mono text-tiny text-faint">{item.path || src}</small>
<span className="text-label text-ink-3">可能是文件已被清理,或该 ffmpeg/服务进程无权读取。</span>
<a className="text-label text-accent-bright" href={downloadHref} target="_blank" rel="noopener">仍要在新窗口打开 ↗</a>
</div>
)}
</div>
{count > 1 && (
<button type="button" onClick={() => step(1)} disabled={store.index >= count - 1} title="下一个 (→)"
className="absolute top-1/2 right-4 z-3 grid h-[42px] w-[42px] -translate-y-1/2 place-items-center rounded-full border border-backdrop-veil bg-backdrop-veil p-0 pb-0.5 text-[21px] leading-none text-ink backdrop-blur-[6px] shadow-[0_6px_20px_var(--c-backdrop-shadow)] max-nav:right-2.5 max-nav:h-[34px] max-nav:w-[34px] max-nav:text-[17px] hover:not-disabled:scale-106 hover:not-disabled:border-accent-fill hover:not-disabled:bg-accent-fill hover:not-disabled:text-on-accent disabled:opacity-34">›</button>
)}
{manage && canSwitchVersion && store.versionPanelOpen && <VersionPanel onClose={() => toggleVersionPanel(false)} />}
</div>
<footer className="flex shrink-0 flex-wrap items-center justify-between gap-x-3 gap-y-2 border-t border-line bg-raise px-4 py-[11px]">
{!store.collapsed && (
<div className="scrollbar-slim flex min-h-0 min-w-0 max-h-[min(26vh,124px)] grow-[320] flex-wrap gap-x-5 gap-y-2 overflow-auto pr-1 max-nav:max-h-[84px] max-nav:basis-full">
{meta.map((f) => (
<span key={f.label} className="flex max-w-[min(430px,100%)] flex-col min-w-0 max-nav:max-w-full">
<i className="text-tiny font-bold tracking-[.7px] text-faint not-italic">{f.label}</i>
<b title={f.value} className="text-caption font-semibold leading-[1.45] text-ink-2 [overflow-wrap:anywhere]">{f.value}</b>
</span>
))}
</div>
)}
<div className="ml-auto flex min-h-(--ctl-h-md) shrink-0 flex-wrap items-center justify-end gap-2">
<span className="text-tiny text-faint">
{count > 1 ? <>← / → 上一镜 / 下一镜{peerCount > 1 && <> · [ / ] 换本镜产物</>} · Space 播放 · Esc 关闭</> : 'Esc 关闭 · I 切换信息'}
</span>
{copied && <Tag tone="accent">{copied}</Tag>}
{store.versionFeedback && <Tag tone={store.versionFeedback.tone === 'bad' ? 'bad' : 'ok'}>{store.versionFeedback.text}</Tag>}
<Button variant="ghost" onClick={copyLink}>复制链接</Button>
<Button variant="ghost" href={downloadHref} target="_blank" rel="noopener">新窗口</Button>
<Button variant="primary" href={downloadHref} download={item.downloadName} className="text-[10.5px] no-underline">下载</Button>
</div>
</footer>
</div>
</div>
)
}
export default MediaLightbox

View File

@ -0,0 +1,122 @@
import { useEffect, useState, type ReactNode } from 'react'
import { cn } from '../../lib/cn'
import { iconFor, kindLabel, normalize, placeholderFor, thumbUrl, THUMB_PX, type MediaItem } from '../../lib/media'
import { canManageVersions, openPreview, toggleVersionPanel } from '../../stores/preview'
import { AudioPlay } from './AudioPlay'
/**
* 全站统一的媒体缩略图。
*
* 之前每个页面各自写 <img class="mini"> / <video muted> / <audio controls>,
* 于是同一张关键帧在资产库里能放大、在时间线里是灰块。这里统一:
* 图片 → 后端缩略图 + 懒加载 + 失败占位;视频 → 后端抽帧当封面(失败才退回 <video>);
* 音频 → 统一 AudioPlay;其它 → 文件占位。
* 点击默认交给全局预览器(可带队列,实现 ←/→ 翻页),预览器看的仍是**原图/原视频**。
*/
export type MediaThumbProps = {
src?: string
item?: MediaItem | null
kind?: string
mime?: string
poster?: string
title?: string
size?: 'xs' | 'sm' | 'md' | 'lg'
width?: string | number
radius?: number
clickable?: boolean
badge?: ReactNode
queue?: any[]
index?: number
inlineAudio?: boolean
onOpen?: (item: MediaItem) => void
className?: string
}
const FRAME_H: Record<string, string> = { xs: 'h-[34px]', sm: 'h-16', md: 'h-[118px]', lg: 'h-[172px]' }
export function MediaThumb({
src = '', item = null, kind = '', mime = '', poster = '', title = '', size = 'md',
width = '100%', radius = 8, clickable = true, badge, queue, index = 0, inlineAudio = true, onOpen, className
}: MediaThumbProps) {
const [failed, setFailed] = useState(false)
const [posterFailed, setPosterFailed] = useState(false)
const media: MediaItem | null = item
|| (src ? normalize({ url: src, kind, mime, name: title }, { kind, poster }) : null)
const url = media?.url || ''
useEffect(() => { setFailed(false); setPosterFailed(false) }, [url])
const kindNow = media?.kind || 'none'
const cover = poster || media?.poster || ''
/** 卡片实际显示的像素宽(按 2x 屏放大)→ 只下载这一档缩略图,不再拉原图 */
const pixels = THUMB_PX[size] || 384
const imageSrc = thumbUrl(url, pixels)
/** 视频封面:有明确 poster(通常是关键帧)优先,否则用后端从视频里抽的一帧 */
const posterSrc = cover ? thumbUrl(cover, pixels) : imageSrc
const showFail = failed || !url
const label = title || media?.title || kindLabel(kindNow as any)
function click() {
if (!clickable || !media) return
openPreview(queue?.length ? queue : [media], queue?.length ? index : 0)
onOpen?.(media)
}
/* 多版素材的角标:以前只写「v4」,没人知道点它管理版本,甚至版本被删回
v1 时角标直接消失。这里改成「v4 · 4版」并让它直接把预览器的版本管理打开。 */
const versionCount = media?.versions?.length || 0
const manageable = versionCount > 1 && canManageVersions(media)
const showVer = versionCount > 1 || (media?.version || 1) > 1
const v = media?.version || 1
const verBadge = versionCount > 1 ? `v${v} · ${versionCount}版` : `v${v}`
if (kindNow === 'audio' && inlineAudio) {
return (
<div style={{ width }} className={cn('block min-w-0', className)}>
<AudioPlay src={url} label={label} durationMs={media?.raw?.duration_ms} size={size === 'xs' ? 'sm' : 'md'} />
</div>
)
}
return (
<div role={clickable ? 'button' : undefined} tabIndex={clickable ? 0 : undefined}
aria-label={clickable ? `放大查看:${label}` : undefined}
style={{ width }} onClick={click}
onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); click() } }}
className={cn('block min-w-0', clickable && 'cursor-pointer group', className)}>
<div className={cn('relative overflow-hidden bg-sunken border border-line w-full group-hover:border-accent-line group-hover:shadow-[0_0_0_2px_var(--c-accent-tint)]', FRAME_H[size] || FRAME_H.md)}
style={{ borderRadius: radius }}>
{kindNow === 'image' && !showFail && <img src={imageSrc} alt={label} loading="lazy" decoding="async" className="block w-full h-full object-cover" onError={() => setFailed(true)} />}
{kindNow === 'video' && !showFail && posterSrc && !posterFailed && <img src={posterSrc} alt={label} loading="lazy" decoding="async" className="block w-full h-full object-cover" onError={() => setPosterFailed(true)} />}
{kindNow === 'video' && !showFail && (!posterSrc || posterFailed) && <video src={url} muted playsInline preload="metadata" className="block w-full h-full object-cover" onError={() => setFailed(true)} />}
{showFail && (
<div className="absolute inset-0 grid place-content-center gap-[3px] justify-items-center text-center p-1.5 bg-sunken text-faint">
<b className="text-[15px] font-medium text-muted">{iconFor(kindNow as any)}</b>
<small className="text-tiny leading-[1.35]">{placeholderFor(kindNow as any)}</small>
</div>
)}
{kindNow === 'video' && !showFail && (
<span aria-hidden className={cn('absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 grid place-items-center rounded-full bg-[rgba(0,0,0,.58)] text-white text-tiny pointer-events-none',
size === 'md' || size === 'lg' ? 'w-[34px] h-[34px] text-body' : 'w-[26px] h-[26px]')}>▶</span>
)}
{kindNow === 'audio' && !inlineAudio && (
<span aria-hidden className="absolute left-1 top-1 text-tiny px-[5px] py-0.5 rounded-chip bg-scrim text-white max-w-[calc(100%-8px)] truncate">♫ {label}</span>
)}
{badge && <span className="absolute right-1 top-1 text-tiny px-[5px] py-0.5 rounded-chip bg-scrim text-white">{badge}</span>}
{showVer && (
<button type="button" onClick={(e) => {
e.stopPropagation()
if (!manageable) return
click()
toggleVersionPanel(true)
}}
title={manageable ? `共 ${versionCount} 个版本,点击管理(设为默认 / 删除)` : `当前 v${media?.version}`}
className={cn('absolute left-1 bottom-1 font-inherit text-tiny px-[5px] py-px rounded-chip bg-scrim text-white tracking-[.3px] leading-[1.45]',
manageable && 'cursor-pointer hover:bg-accent-fill hover:text-on-accent')}>
{verBadge}
</button>
)}
</div>
</div>
)
}

View File

@ -0,0 +1,414 @@
/**
* 「录一段音」:声音样本 / 克隆参考音色的第二个入口(第一个是上传文件)。
*
* 交互改成弹出小面板:录制 → 试听 → 保存三步在一个面板里走完。
* 之前控件是内联在表单行里的,录起来整行被撑开、试听条只有 96px,
* 录完连「存成哪条素材」都没得选,只能被动接受组件猜的文件名。
*
* React 侧注意:麦克风流、计时器、试听 objectURL 都是组件局部状态,
* 面板开着期间必须用 beginRecordingSheet() 把页面轮询按住 ——
* 列表被刷新重建会把本组件一起卸载,录音当场蒸发。
*/
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { cn } from '../../lib/cn'
import { fmtMs } from '../../lib/format'
import { beginRecordingSheet } from '../../stores/recording'
import {
MAX_RECORD_MS, MIC_WAIT_MS, MIN_RECOMMENDED_MS, MicUnavailableError, RecordingSession,
explainMicError, micErrorTag, micProbeHint, micResetCommand, micSettingsLinks, probeMicrophone,
recordingBlockedReason, recordingSupported, type MicProbe, type Recording
} from '../../lib/recorder'
import { AudioPlay } from './AudioPlay'
export type RecordPickMeta = {
durationMs: number
warning: string
name: string
setCurrent: boolean
fileSizeBytes: number
}
type Stage = 'idle' | 'recording' | 'preview'
/** 提示语里用 **包起来** 的部分渲染成粗体(不动 dangerouslySetInnerHTML,免得中文标点被当标签吞) */
function Segs({ text, className }: { text: string; className?: string }) {
const parts = text ? text.split('**') : []
return <p className={cn('m-0 text-[11px] leading-[1.6]', className)}>{parts.map((s, i) => i % 2 ? <b key={i}>{s}</b> : s)}</p>
}
export function RecordAudio({ label = '录制', target = '新版本', disabled = false, hint,
names = [], defaultName = '', onPick }: {
/** 触发按钮文案 */
label?: string
/** 这段录音最终会变成什么(保存按钮文案,和实际入库的登记类型保持一致) */
target?: string
disabled?: boolean
/** 面板顶部说明 */
hint?: string
/** 已存在的素材名:选它 = 追加为下一个版本,写新名 = 新建一条素材 */
names?: string[]
/** 默认存到哪条素材(不传用 target) */
defaultName?: string
onPick: (file: File, meta: RecordPickMeta) => void
}) {
const [open, setOpen] = useState(false)
const [stage, setStage] = useState<Stage>('idle')
const [elapsed, setElapsed] = useState(0)
const [level, setLevel] = useState(0)
const [error, setError] = useState('')
const [busy, setBusy] = useState('')
const [taking, setTaking] = useState<Recording | null>(null)
const [saveName, setSaveName] = useState('')
const [setCurrent, setSetCurrent] = useState(true)
const [awaiting, setAwaiting] = useState(0)
const [previewUrl, setPreviewUrl] = useState('')
const [probe, setProbe] = useState<MicProbe | null>(null)
const [copied, setCopied] = useState('')
const [rawError, setRawError] = useState('')
const sessionRef = useRef<RecordingSession | null>(null)
const meterRef = useRef<number | null>(null)
/** 一次「开始录制」的代次:关面板/清空后,迟到的授权结果必须作废 */
const runIdRef = useRef(0)
/** 本次录音里出现过的最高电平:几秒还是平的,说明声音根本没进来 */
const peakRef = useRef(0)
const previewRef = useRef('')
const bigRef = useRef<HTMLButtonElement | null>(null)
const primaryRef = useRef<HTMLButtonElement | null>(null)
/** 每个实例一个 datalist id:同屏多个录音入口时不能共用 */
const listId = useMemo(() => `rec-names-${Math.random().toString(36).slice(2, 8)}`, [])
const maxSec = Math.round(MAX_RECORD_MS / 1000)
const minSec = Math.round(MIN_RECOMMENDED_MS / 1000)
/** 已经在录、但一直没收到声音(选了错的输入设备、系统里静音、麦克风本身是坏的) */
const silent = stage === 'recording' && elapsed > 4_000 && peakRef.current < 0.03
const supported = recordingSupported()
const blocked = recordingBlockedReason()
const canStart = supported && !disabled && !busy
/** 探测还没回来时也要能出诊断码,这里单独留一份浏览器名 */
const browserNote = typeof navigator !== 'undefined' ? navigator.userAgent : ''
/** 体检已确认能录:把设备名直接回显出来,省得用户猜「到底有没有麦」 */
const micOk = !!probe?.authorized
/** 事前就能看出的毛病(系统里没麦克风 / 权限被设为阻止),没毛病时为空 */
const preflight = probe ? micProbeHint(probe) : ''
const micStatusText = !supported ? ''
: !probe ? '麦克风自检中…'
: probe.authorized ? `麦克风已就绪:${probe.devices[0]}`
: '麦克风未就绪:见下方说明'
/** macOS 把浏览器整个挡在门外时,唯一不需要重启浏览器的解法就是这条命令 */
const resetCmd = probe && !probe.authorized ? micResetCommand(probe) : ''
/** 系统隐私/声音设置的直达链接:只在「还没就绪」或「刚报过错」时露出来,就绪时不占地方 */
const settingsLinks = (!micOk || !!error) ? micSettingsLinks(probe) : []
const knownNames = useMemo(() => [...new Set((names || []).map((x) => String(x || '').trim()).filter(Boolean))], [names])
const clearMeter = useCallback(() => {
if (meterRef.current !== null) window.clearInterval(meterRef.current)
meterRef.current = null
setLevel(0)
}, [])
const revokePreview = useCallback(() => {
if (previewRef.current) URL.revokeObjectURL(previewRef.current)
previewRef.current = ''
setPreviewUrl('')
}, [])
const recheck = useCallback(async () => {
if (!recordingSupported()) { setProbe(null); return }
setProbe(await probeMicrophone())
}, [])
/* 面板开着就把页面轮询按住(见 stores/recording):卡片被刷新重建会连本组件一起卸载 */
useEffect(() => {
if (!open) return
const release = beginRecordingSheet()
return () => { release() }
}, [open])
/* 插了麦克风、改了系统权限都不用刷新页面:devicechange 挂在 mediaDevices 上(不是 window),
插入 USB 麦、系统改权限都会触发 */
useEffect(() => {
void recheck()
const onDeviceChange = () => { void recheck() }
navigator.mediaDevices?.addEventListener?.('devicechange', onDeviceChange)
return () => {
navigator.mediaDevices?.removeEventListener?.('devicechange', onDeviceChange)
clearMeter()
revokePreview()
sessionRef.current?.discard()
}
}, [recheck, clearMeter, revokePreview])
async function copyText(text: string, ok: string) {
if (!text) return
try {
await navigator.clipboard.writeText(text)
setCopied(ok)
} catch {
setCopied(text) // 剪贴板被挡(非安全上下文)时至少让人能手抄
}
window.setTimeout(() => { setCopied('') }, 6_000)
}
const copyReset = () => copyText(resetCmd, '命令已复制,粘到终端回车,然后回来点「重新检测」')
const copyDiag = () => copyText(`${location.origin} · ${browserNote} · ${rawError}`,
'诊断码已复制(地址 + 浏览器 + 原始报错),发给支持即可定位')
function close() {
if (stage === 'recording') abandon()
runIdRef.current += 1 // 录制还没起来就关面板:等的授权也别再认
setAwaiting(0)
setOpen(false)
}
/* 面板自身吃掉 Esc,别让它冒到页面/抽屉的快捷键上 */
useEffect(() => {
if (!open) return
function onKey(ev: KeyboardEvent) {
if (ev.key !== 'Escape') return
ev.stopPropagation()
close()
}
window.addEventListener('keydown', onKey, true)
return () => window.removeEventListener('keydown', onKey, true)
})
/** 打开面板:每次进来都是干净的「待录」状态,名字默认落到 target 对应的素材 */
function openSheet() {
setError('')
setRawError('')
setTaking(null)
revokePreview()
setElapsed(0)
setStage('idle')
setSaveName(String(defaultName || target || '录音').trim())
setSetCurrent(true)
setOpen(true)
void recheck()
requestAnimationFrame(() => bigRef.current?.focus())
}
async function start() {
const my = ++runIdRef.current
setError('')
setAwaiting(0)
let opened: RecordingSession | null = null
try {
opened = await RecordingSession.start(probe || await probeMicrophone(),
(ms) => { if (my === runIdRef.current) setAwaiting(ms) })
} catch (exc: any) {
if (my !== runIdRef.current) return // 等授权期间已经被关掉了,别把结论打到别的面板上
setAwaiting(0)
sessionRef.current = null
// recorder 抛的已经是中文结论;万一还是原始 DOMException,这里再兜一层
setError(exc instanceof MicUnavailableError
? exc.message
: explainMicError(exc, probe || await probeMicrophone()))
setRawError(exc instanceof MicUnavailableError ? micErrorTag(exc.cause) : micErrorTag(exc))
void recheck() // 报错往往意味着设备/权限刚变过,顺手刷新体检结果
return
}
if (my !== runIdRef.current) { opened?.discard(); return } // 授权框是迟到点出来的:麦克风立刻还给系统
setAwaiting(0)
sessionRef.current = opened
setTaking(null)
revokePreview()
setStage('recording')
setElapsed(0)
peakRef.current = 0
opened.onTick = (ms) => setElapsed(ms)
opened.setAutoStop(() => { void stop() })
meterRef.current = window.setInterval(() => {
const lv = sessionRef.current?.level() || 0
setLevel(lv)
peakRef.current = Math.max(peakRef.current, lv)
}, 60)
}
/** 停止采集并把 webm/opus 转成 WAV,成功后进入试听 */
async function stop() {
const active = sessionRef.current
if (!active) return
sessionRef.current = null
clearMeter()
setBusy('转码中…')
try {
const rec = await active.stop()
revokePreview()
const url = URL.createObjectURL(rec.blob)
previewRef.current = url
setPreviewUrl(url)
setTaking(rec)
setStage('preview')
requestAnimationFrame(() => primaryRef.current?.focus())
} catch (exc: any) {
active.discard()
setError(`录音转 WAV 失败:${exc?.message || exc}。可以先用系统录音笔录好再走上传。`)
setStage('idle')
} finally {
setBusy('')
}
}
/** 不要这段录音了:释放麦克风,回到未录状态 */
function abandon() {
runIdRef.current += 1 // 作废还在等授权的 getUserMedia
setAwaiting(0)
sessionRef.current?.discard()
sessionRef.current = null
clearMeter()
setTaking(null)
revokePreview()
setElapsed(0)
setError('')
setRawError('')
setStage('idle')
}
function safeFileName(name: string) {
return (String(name || '录音').replace(/[\\/:*?"<>|]+/g, '').trim() || '录音').slice(0, 40)
}
function confirmUpload() {
const rec = taking
if (!rec) return
const name = saveName.trim() || String(target || '录音')
const file = new File([rec.blob], `${safeFileName(name)}.wav`, { type: 'audio/wav' })
onPick(file, {
durationMs: rec.durationMs, warning: rec.warning, name,
setCurrent, fileSizeBytes: rec.blob.size,
})
sessionRef.current = null
setTaking(null)
revokePreview()
setElapsed(0)
setStage('idle')
setOpen(false)
}
const warning = taking?.warning || ''
return (
<>
<button type="button" disabled={!canStart} onClick={openSheet}
title={blocked || hint || '录一段真人声音'}
className={cn('inline-flex h-(--ctl-h-md) items-center gap-1 whitespace-nowrap rounded-[7px] border px-[9px] text-tiny',
stage === 'recording'
? 'border-danger-line bg-danger-tint text-danger'
: 'border-line-strong text-ink-2 hover:not-disabled:border-line-bright hover:not-disabled:bg-hover',
!canStart && 'opacity-35 cursor-not-allowed')}>
🎙 {supported ? label : '录音不可用'}
{stage === 'recording' && <span className="ml-1.5 [font-variant-numeric:tabular-nums]">{fmtMs(elapsed)}</span>}
</button>
{open && createPortal(
<div className="fixed inset-0 z-260 grid place-items-center bg-scrim p-4 backdrop-blur-[3px]"
onClick={(e) => { if (e.target === e.currentTarget) close() }}>
<section role="dialog" aria-modal="true" aria-label={`录制${target}`}
className="flex w-[min(430px,100%)] flex-col gap-2.5 rounded-float border border-line bg-panel p-3.5 shadow-[0_24px_60px_rgba(0,0,0,.42)]">
<header className="flex items-start justify-between gap-2.5">
<div>
<small className="text-tiny tracking-[.1em] text-faint">RECORD · {target}</small>
<h3 className="mt-[3px] text-[15px] font-bold">{stage === 'recording' ? '正在录制…' : stage === 'preview' ? '试听并保存' : '录一段声音'}</h3>
</div>
<button type="button" title="关闭(Esc)" onClick={close}
className="border-0 bg-transparent px-1 py-0.5 text-[14px] text-faint hover:text-ink">✕</button>
</header>
<ol className="m-0 flex list-none gap-1.5 p-0">
{(['idle', 'recording', 'preview'] as Stage[]).map((s, i) => (
<li key={s} className={cn('flex-1 rounded-[7px] border border-line bg-sunken py-[5px] text-center text-[10.5px] text-faint',
stage === s && 'border-accent-line bg-tint-accent text-accent-bright',
(s === 'idle' && stage !== 'idle') || (s === 'recording' && stage === 'preview') && 'border-success-line text-success')}>
{['① 录制', '② 试听', '③ 保存'][i]}
</li>
))}
</ol>
{blocked ? <Segs text={`✕ ${blocked}`} className="text-danger" /> : supported && (
<>
<p className={cn('m-0 flex flex-wrap items-center gap-2 rounded-[8px] border px-2 py-1.5 text-[11px]',
micOk ? 'border-success-line bg-success-tint text-success' : 'border-warn-line bg-warn-tint text-warn')}>
<span className="min-w-0 [overflow-wrap:anywhere]">{micOk ? '✓' : '⚠'} {micStatusText}</span>
<span className="grow"></span>
<button type="button" className="border-0 bg-transparent p-0 text-[10.5px] text-ink-3 underline whitespace-nowrap leading-[1.45] hover:text-accent-bright" onClick={() => void recheck()}>重新检测</button>
{resetCmd && <button type="button" className="border-0 bg-transparent p-0 text-[10.5px] text-ink-3 underline whitespace-nowrap leading-[1.45] hover:text-accent-bright" onClick={copyReset}>复制修复命令</button>}
{settingsLinks.map((l) => <a key={l.href} href={l.href} className="text-[10.5px] text-ink-3 underline underline-offset-2 whitespace-nowrap leading-[1.45] hover:text-accent-bright">{l.label}</a>)}
</p>
{copied && <p className="m-0 text-[10.5px] leading-[1.6] text-faint">{copied}</p>}
{!micOk && preflight && <Segs text={preflight} className="text-warn" />}
</>
)}
<div className={cn('flex flex-col items-center gap-2 rounded-[11px] border border-dashed border-line bg-sunken px-2.5 py-3',
stage === 'recording' && 'border-solid border-danger-line')}>
{stage !== 'recording' ? (
<button ref={bigRef} type="button" disabled={!canStart} onClick={start}
className="inline-flex h-12 items-center justify-center gap-2 rounded-pill border border-accent-line bg-accent-fill px-5 text-ui font-bold text-on-accent disabled:opacity-50 disabled:cursor-not-allowed">
🎙 {stage === 'idle' ? '开始录制' : '重新录制'}
</button>
) : (
<button ref={bigRef} type="button" onClick={() => void stop()}
className="inline-flex h-12 items-center justify-center gap-2 rounded-pill border border-danger-line bg-danger-tint px-5 text-ui font-bold text-danger">
<span className="inline-block h-[9px] w-[9px] animate-pulse-soft rounded-full bg-current"></span>停止录制
</button>
)}
<div className="flex flex-wrap items-center justify-center gap-2.5">
<b className="text-ui [font-variant-numeric:tabular-nums]">{fmtMs(elapsed)}</b>
{stage === 'recording' && (
<span title="麦克风电平" className="inline-flex h-[22px] w-[46px] items-end border border-line rounded-chip bg-shell p-0.5">
<i className="block w-full rounded-[3px] bg-accent-fill transition-[height] duration-75" style={{ height: `${Math.max(6, Math.round(level * 100))}%` }}></i>
</span>
)}
<span className="text-tiny text-faint">{stage === 'preview'
? '已录好,点下面的 ▶ 试听确认后再保存'
: `建议念满 ${minSec} 秒 · 上限 ${maxSec} 秒自动停止`}</span>
</div>
{silent && <p className="m-0 text-[11px] leading-[1.6] text-warn">已经录了 {Math.round(elapsed / 1000)} 秒还没收到声音:
麦克风可能被静音,或选错了输入设备。点「停止录制」后重录。</p>}
{awaiting > 0 && <p className="m-0 text-[11px] leading-[1.6] text-warn">⏳ 正在等系统授权(已等 {Math.ceil(awaiting / 1000)} 秒):
授权框{probe?.macos ? '在屏幕左下角,不在网页里' : '在地址栏左侧'},
看不到就把这个浏览器切到最前面再点一次;超过 {Math.round(MIC_WAIT_MS / 1000)} 秒没点会自动取消。</p>}
{busy && <p className="m-0 text-[10.5px] leading-[1.6] text-faint">转码中,请稍候…</p>}
{error && <Segs text={error} className="text-danger" />}
{error && rawError && (
<p className="-mt-0.5 flex flex-wrap items-center gap-[7px] text-tiny text-faint">浏览器原始报错 <code className="rounded-chip border border-line bg-sunken px-[5px] py-px font-mono">{rawError}</code>
<button type="button" className="border-0 bg-transparent p-0 text-[10.5px] text-ink-3 underline whitespace-nowrap leading-[1.45] hover:text-accent-bright" onClick={copyDiag}>复制诊断码</button></p>
)}
</div>
{stage === 'preview' && (
<div className="flex flex-col gap-2 rounded-[11px] bg-tint-accent p-2.5">
<AudioPlay src={previewUrl} label="刚才的录音" durationMs={taking?.durationMs || 0} size="sm" cover={false} />
{warning && <p className="m-0 text-[11px] leading-[1.6] text-warn">{warning}</p>}
<label className="m-0 flex flex-col gap-1 text-[11px]">存到哪条素材
<input value={saveName} list={listId} placeholder="素材名称"
title="选已有名称=追加成它的下一个版本(之后可删版本 / 设为当前版本);写新名称=新建一条素材"
onChange={(e) => setSaveName(e.target.value)} />
<datalist id={listId}>{knownNames.map((n) => <option key={n} value={n} />)}</datalist>
</label>
<label className="m-0 inline-flex w-fit cursor-pointer flex-row items-center gap-[7px] text-label text-ink-2">
<input type="checkbox" className="h-auto w-auto" checked={setCurrent} onChange={(e) => setSetCurrent(e.target.checked)} />保存后设为当前版本
</label>
</div>
)}
<footer className="flex items-center gap-2 [--ctl-h:var(--ctl-h-md)]">
<button type="button" className="inline-flex h-(--ctl-h-md) items-center gap-1 rounded-[7px] border border-line-strong px-[9px] text-tiny text-ink-2 disabled:opacity-35" disabled={stage === 'recording'} onClick={close}>取消</button>
{stage !== 'idle' && <button type="button" className="inline-flex h-(--ctl-h-md) items-center gap-1 rounded-[7px] border border-line-strong px-[9px] text-tiny text-ink-2" onClick={abandon}>清空重录</button>}
<span className="grow"></span>
{stage === 'recording' ? (
<button type="button" className="inline-flex h-(--ctl-h-md) items-center gap-1 rounded-[7px] border border-line-strong bg-line px-[9px] text-tiny text-ink" onClick={() => void stop()}>■ 停止并试听</button>
) : (
<button ref={primaryRef} type="button" disabled={stage !== 'preview' || !!busy || !saveName.trim()} onClick={confirmUpload}
className="inline-flex h-(--ctl-h-md) items-center gap-1 rounded-[7px] bg-accent-fill px-[9px] text-tiny text-on-accent disabled:opacity-35">✓ 存为{target}</button>
)}
</footer>
</section>
</div>,
document.body)}
</>
)
}
export default RecordAudio

View File

@ -0,0 +1,159 @@
/**
* 版本管理抽屉(挂在预览器右侧)。
*
* 之前「设为默认 / 删除某一版」只能先在预览器顶部下拉里逐版切换再点按钮,
* 入口太隐蔽:想删掉中间某一版,得先把它翻出来预览。这里把全部版本摊成一列,
* 每一行自带「设为默认 / 删除」,不用来回切版本。
* 动作复用 stores/preview.ts 里的 setCurrentVersion / deleteVersion —— 平台母版和
* 项目资产走的是两个接口,逻辑只有一份。
*/
import { cn } from '../../lib/cn'
import { fmtBytes, fmtTime } from '../../lib/format'
import { thumbUrl, type MediaItem, type MediaVersion } from '../../lib/media'
import {
chooseVersion,
deleteVersion,
selectCurrent,
setCurrentVersion,
usePreviewStore,
viewedVersion
} from '../../stores/preview'
import { Button, Eyebrow, Tag } from '../ui'
/** 新版本在上,和下拉里的顺序一致 */
function rowsOf(item: MediaItem): MediaVersion[] {
return [...(item.versions || [])].sort((a, b) => b.version_no - a.version_no)
}
function coverOf(url: string, kind: MediaItem['kind']) {
return kind === 'image' || kind === 'video' ? thumbUrl(url, 128) : ''
}
function infoOf(row: MediaVersion) {
const bits: string[] = []
if (row.width && row.height) bits.push(`${row.width}×${row.height}`)
if (row.size_bytes) bits.push(fmtBytes(row.size_bytes))
if (row.duration_ms) bits.push(`${Math.round(row.duration_ms / 100) / 10}s`)
return bits.join(' · ') || '—'
}
export function VersionPanel({ onClose }: { onClose: () => void }) {
const store = usePreviewStore()
const busy = store.versionBusy
const item = selectCurrent(store)
if (!item) return null
const kind = item.kind || 'none'
const rows = rowsOf(item)
const currentNo = item.version || 1
const previewing = viewedVersion(item)?.version_no || 0
const onlyOne = rows.length < 2
function makeCurrent(row: MediaVersion) {
if (row.exists === false || row.current) return
void setCurrentVersion(row.version_no)
}
function remove(row: MediaVersion) {
if (onlyOne) return
const fileNote = row.exists === false ? '该版本的文件已经不在磁盘上,这次只清理记录。' : '该版本的记录与文件会一并删除,不可恢复。'
const tail = row.current || row.version_no === currentNo ? '它正是当前默认版本,删除后自动回落到剩余最新版本。' : ''
const ask = `确认删除「${item!.title}」的 v${row.version_no}?${fileNote}${tail}`
if (window.confirm(ask)) void deleteVersion(row.version_no)
}
return (
<aside
role="complementary"
aria-label={'版本管理:' + item.title}
className="absolute inset-y-0 right-0 z-3 flex w-[min(400px,74%)] min-h-0 flex-col gap-2 border-l border-line-strong bg-panel p-[11px_12px] shadow-[-14px_0_30px_var(--c-shade-2)]"
>
<header className="flex shrink-0 items-start gap-2 [&_p]:m-0">
<div className="min-w-0 grow">
<Eyebrow>VERSIONS · 版本管理</Eyebrow>
<h4 className="mt-[2px] text-[13px] leading-[1.3] break-all">{item.title}</h4>
<p className="mt-1 text-tiny text-ink-3">
共 {rows.length} 版 · 当前默认 <b className="font-mono text-accent-bright">v{currentNo}</b>
</p>
</div>
<Button variant="ghost" title="关闭版本管理" onClick={onClose} className="w-[26px] min-w-[26px] px-0">✕</Button>
</header>
<p className="m-0 shrink-0 rounded-[8px] border border-line bg-sunken px-2 py-[7px] text-tiny leading-[1.55] text-ink-3">
<b className="text-ink-2">设为默认</b>:平台母版与之后引入项目的素材都取这一版;项目里已锁定的快照不会自动改版。<br />
<b className="text-ink-2">删除</b>:连同文件一起清理;若仍被生成记录引用,只删记录并保留文件。
</p>
<div className="scrollbar-slim -mx-1 min-h-0 grow overflow-auto px-1">
<div className="flex flex-col gap-1.5">
{rows.map((row) => {
const on = row.version_no === previewing
const isDef = row.version_no === currentNo
const gone = row.exists === false
const cover = coverOf(row.url, kind)
return (
<div
key={row.version_no}
className={cn(
'flex items-start gap-2 rounded-tile border bg-card p-[7px]',
on ? 'border-accent-line bg-accent-tint' : 'border-line',
isDef && 'border-l-2 border-l-accent-line',
gone && 'opacity-72'
)}
>
<button
type="button"
title={'预览 v' + row.version_no}
onClick={() => chooseVersion(row.version_no)}
className="grid h-10 w-[52px] shrink-0 place-items-center overflow-hidden rounded-[7px] border border-line bg-sunken p-0 text-[15px] text-muted [cursor:zoom-in]"
>
{cover
? <img src={cover} alt={'v' + row.version_no} loading="lazy" decoding="async" className="block h-full w-full object-cover" />
: <b>{kind === 'audio' ? '♫' : kind === 'video' ? '▶' : '▤'}</b>}
</button>
<div className="min-w-0 grow">
<div className="flex flex-wrap items-center gap-[5px]">
<b className="font-mono text-label font-bold text-ink">v{row.version_no}</b>
{isDef && <Tag tone="accent">当前默认</Tag>}
{on && <Tag>预览中</Tag>}
{gone && <Tag tone="bad">文件已丢失</Tag>}
</div>
<p className="mt-[3px] truncate font-mono text-tiny text-faint">{fmtTime(row.created_at)} · {infoOf(row)}</p>
{row.note && <p className="mt-[3px] truncate text-tiny text-ink-3">{row.note}</p>}
</div>
<div className="flex shrink-0 flex-col items-stretch gap-1">
<Button
variant="ghost"
disabled={on || busy}
title={on ? '已经在预览这一版' : '切到这一版看看'}
onClick={() => chooseVersion(row.version_no)}
className="w-[84px] justify-center"
>预览</Button>
<Button
variant="ghost"
disabled={isDef || row.exists === false || busy}
title={isDef ? '这一版已经是当前默认'
: row.exists === false ? '文件已丢失,无法设为默认,可以先删掉它' : '把这一版设为当前默认版本'}
onClick={() => makeCurrent(row)}
className={cn('w-[84px] justify-center', !isDef && !busy && 'border-accent-line text-accent-bright')}
>{busy ? '处理中…' : '★ 设为默认'}</Button>
<Button
variant="del"
disabled={onlyOne || busy}
title={onlyOne ? '只剩一个版本,如需清理请直接删除该素材' : '删除这一版(含文件),不可恢复'}
onClick={() => remove(row)}
className="w-[84px] justify-center"
>删除</Button>
</div>
</div>
)
})}
</div>
</div>
</aside>
)
}
export default VersionPanel

View File

@ -0,0 +1,64 @@
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { openNode, allNodesDone } from '../../lib/pipeline'
import { cn } from '../../lib/cn'
import { FlowCaption, Steps } from '../ui/Steps'
/**
* 12 节点流程条(GL-1)。
*
* 流程条比屏幕宽时以前只是「能横向滚」,但没有任何提示,
* 用户以为只有 8 个节点;而且当前节点常常在滚动区外。
* 现在:右缘渐隐提示还有内容 + 自动把「进行中 / 需处理」的节点滚进视野 +
* 节点 title 悬浮出完整说明(compact 模式也不会丢信息)。
*/
export function WorkflowBar({ workflow, compact, className }: {
workflow: any[] | null | undefined
compact?: boolean
className?: string
}) {
const stages = useMemo(() => workflow || [], [workflow])
const rail = useRef<HTMLDivElement | null>(null)
const [overflowing, setOverflowing] = useState(false)
const currentKey = openNode(stages)?.key || ''
const currentLabel = (stages as any[]).find((s) => s.key === currentKey)?.label || ''
const flowDone = allNodesDone(stages)
/** 只有真的需要滚的时候才显示渐隐,否则渐隐像渲染残留 */
const measure = () => {
const box = rail.current
if (box) setOverflowing(box.scrollWidth - box.clientWidth > 2)
}
useLayoutEffect(measure, [stages])
useEffect(() => {
const box = rail.current
if (typeof ResizeObserver === 'undefined' || !box) return
const ro = new ResizeObserver(measure)
ro.observe(box)
if (box.firstElementChild) ro.observe(box.firstElementChild)
return () => ro.disconnect()
}, [stages])
/** 把当前节点滚到可视区中间;只在流程变化时做一次,不打断用户手动滚动 */
useEffect(() => {
const box = rail.current
if (!box) return
const target = box.querySelector<HTMLElement>('[data-current="1"]')
if (!target) return
const left = target.offsetLeft - (box.clientWidth - target.clientWidth) / 2
box.scrollTo({ left: Math.max(0, left), behavior: 'smooth' })
measure()
}, [currentKey])
return (
<div className={cn('relative', className)}>
{overflowing && (
<>
<span aria-hidden className="pointer-events-none absolute top-0 right-0 bottom-4 w-[46px] rounded-[0_9px_9px_0] bg-[linear-gradient(90deg,rgba(0,0,0,0),var(--c-bg-panel))]" />
<span aria-hidden className="pointer-events-none absolute top-0 left-0 bottom-4 w-[22px] rounded-[9px_0_0_9px] bg-[linear-gradient(270deg,rgba(0,0,0,0),var(--c-bg-panel))]" />
</>
)}
<Steps ref={rail} nodes={stages} currentKey={currentKey} compact={compact} scrollSmooth />
{!!stages.length && <FlowCaption nodes={stages} current={currentKey ? currentLabel : ''} allDone={flowDone} />}
</div>
)
}

View File

@ -21,7 +21,7 @@
# .venv/ node_modules/ 跨机的二进制与依赖目录,必须在目标机重装
# .env 机器相关配置(ComfyUI 地址、数据库串),首装由 .env.example 生成
# .local/ reports/ .trash/ 日志、pid、验收证据、回收站
# .git/ 本目录不是 git 仓库;将来接上仓库也不该把历史搬上服务器
# .git/ 版本历史是开发机资产,服务器只需要工作树
#
# 上传用 rsync 而不是 scp:断网可续、只传差异,且 --delete 之外我们不删远端任何东西,
# 因为 /opt/nex_animation 里可能已经有 media/ 与 .env。解压目录与包同名,
@ -67,7 +67,8 @@ command -v rsync >/dev/null || die "缺少 rsync"
EX=(--exclude '.git/' --exclude '.github/' --exclude '.venv/' --exclude 'venv/'
--exclude 'node_modules/' --exclude '__pycache__/' --exclude '*.py[cod]'
--exclude '.pytest_cache/' --exclude '.mypy_cache/' --exclude '.ruff_cache/'
--exclude 'backend/tests/' --exclude 'media/'
--exclude 'backend/tests/'
--include 'frontend/src/components/media/' --exclude 'media/'
--exclude '/models/' --exclude 'frontend/dist/' --exclude '/.local/'
--exclude '/.trash/' --exclude '/reports/' --exclude '/dist/'
--exclude '*.db' --exclude '*.db-wal' --exclude '*.db-shm' --exclude '*.sqlite3'
@ -96,7 +97,8 @@ fi
D="$STAGE/nex_animation"
head2 "体检"
REQUIRED=(backend/app/main.py backend/app/models/__init__.py backend/requirements.txt
backend/Dockerfile frontend/package.json frontend/src/main.ts frontend/index.html
backend/Dockerfile frontend/package.json frontend/src/main.tsx frontend/index.html
frontend/vite.config.ts frontend/src/styles/tokens.css
scripts/server.sh scripts/dev.sh scripts/e2e_selfcheck.py .env.example
docker-compose.yml README.md)
for f in "${REQUIRED[@]}"; do
@ -119,6 +121,20 @@ if [ "$src_py" != "$pkg_py" ]; then
fi
ok "后端代码完整(backend/app ${pkg_py} 个 .py 全部入包)"
# 前端同理,而且更容易看漏:源码刚从 .vue 换成 .tsx,任何按扩展名写的 exclude /
# 体检都会「一条都不匹配」地静默通过。服务器上是 npm run build,src 少文件 = 构建失败
# 或者构建出一个缺页面的产物,所以按后端的同一套办法数一遍。
fe_files() { [ -d "$1" ] || return 0
(cd "$1" && find . -type f \( -name '*.ts' -o -name '*.tsx' -o -name '*.css' \) | sort); }
src_fe=$(fe_files "$ROOT/frontend/src" | wc -l | tr -d ' ')
pkg_fe=$(fe_files "$D/frontend/src" | wc -l | tr -d ' ')
if [ "$src_fe" != "$pkg_fe" ]; then
printf ' %sXX%s 前端代码不完整:源 %s 个,包里只有 %s 个\n' "$C_R" "$C_0" "$src_fe" "$pkg_fe" >&2
diff <(fe_files "$ROOT/frontend/src") <(fe_files "$D/frontend/src") | sed -n '1,20p' >&2
die "有 --exclude 误伤了 frontend/src 下的源码(检查上面 < 开头的行)"
fi
ok "前端代码完整(frontend/src ${pkg_fe} 个源文件全部入包)"
# 再往前一步:直接 import 一次。文件数对了不代表包能起来(少 __init__.py、
# 循环依赖、误排子包都会在这里现形),而它在开发机上只要一秒。
# 用临时 SQLite 库:默认 DATABASE_URL 指向 Postgres,开发机的 venv 里没装 psycopg。
@ -151,11 +167,12 @@ ok "开发产物已全部排除($(IFS=' '; echo "${FORBIDDEN[*]}"))"
# 起因是同一个坑——`models/` 少个前导斜杠,backend/app/models/ 整个 ORM 目录
# 就同时从包和仓库里消失了,而两边都不会报错。这里把全部后端/前端源文件
# 喂给 git check-ignore,任何命中都说明某条忽略规则写宽了。
# 用临时 git 目录跑:本目录当前还不是 git 仓库,--no-index 让它只看 .gitignore。
# 用临时 git 目录跑:--no-index + 独立 GIT_DIR 让它只看 .gitignore,
# 不受本仓库索引状态影响(换机器、CI 里跑结果都一样)。
if command -v git >/dev/null 2>&1; then
ign=$(mktemp -d "${TMPDIR:-/tmp}/nexign.XXXXXX"); git init -q "$ign"
find "$ROOT/backend/app" "$ROOT/frontend/src" -type f \
\( -name '*.py' -o -name '*.ts' -o -name '*.vue' -o -name '*.css' \) \
\( -name '*.py' -o -name '*.ts' -o -name '*.tsx' -o -name '*.css' \) \
-not -path '*/__pycache__/*' | sed "s|^$ROOT/||" | sort > "$ign/src.txt"
GIT_DIR="$ign/.git" GIT_WORK_TREE="$ROOT" \
git check-ignore --no-index --stdin < "$ign/src.txt" > "$ign/eaten.txt" || true