迁移应用外壳:AppBar / SideNav / AuthGate / 路由 + 页面占位,全量 typecheck + build 通过
parent
9467e1bb97
commit
93abe0ce7b
|
|
@ -1,8 +1,22 @@
|
|||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Nex Animation Studio</title>
|
||||
<meta name="color-scheme" content="dark light">
|
||||
<!-- 网络字体异步加载:@import 会把首屏阻塞在 fonts.googleapis.com 上(外网抖动时整页白屏)。
|
||||
preconnect 提前握手 + media="print" 让这张样式表不参与首次渲染,字体到位后自动切回。 -->
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="stylesheet" media="print" onload="this.media='all'"
|
||||
href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Noto+Sans+SC:wght@400;500;600;700&display=swap">
|
||||
</head><body><div id="app"></div><script type="module" src="/src/main.ts"></script></body></html>
|
||||
<script>
|
||||
/* 主题在首帧之前落地,避免深色页面先闪一下白底(React 挂载晚于这段内联脚本)。
|
||||
与 src/stores/theme.ts 共用同一把钥匙 nex-the:值缺失 = 跟随系统。 */
|
||||
(function () {
|
||||
var saved = null
|
||||
try { saved = localStorage.getItem('nex-the') } catch (e) { /* 隐私模式:按系统偏好渲染 */ }
|
||||
var mode = saved === 'dark' || saved === 'light'
|
||||
? saved
|
||||
: (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark')
|
||||
document.documentElement.dataset.theme = mode
|
||||
document.documentElement.style.colorScheme = mode
|
||||
})()
|
||||
</script>
|
||||
</head><body><div id="root"></div><script type="module" src="/src/main.tsx"></script></body></html>
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -5,18 +5,25 @@
|
|||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --host 0.0.0.0",
|
||||
"build": "vite build",
|
||||
"typecheck": "vue-tsc --noEmit --skipLibCheck",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"preview": "vite preview --host 0.0.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@vitejs/plugin-vue": "latest",
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@vitejs/plugin-react": "^5.2.0",
|
||||
"clsx": "^2.1.1",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1",
|
||||
"react-router-dom": "^7.18.5",
|
||||
"tailwind-merge": "^3.7.0",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"vite": "latest",
|
||||
"vue": "latest",
|
||||
"vue-router": "latest"
|
||||
"zustand": "^5.0.16"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.6.3",
|
||||
"vue-tsc": "^2.1.10"
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"typescript": "^5.6.3"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,583 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { RouteLocationNormalized, useRoute, useRouter } from 'vue-router'
|
||||
import { loadSystem, modules, store } from './store'
|
||||
import { pctx } from './project'
|
||||
import { statusLabel } from './format'
|
||||
import { openNode } from './pipeline'
|
||||
import { setTheme, theme } from './theme'
|
||||
import MediaLightbox from './components/MediaLightbox.vue'
|
||||
import { auth, canEdit, displayName, isAuthenticated, isAdmin, logout, roleLabel } from './auth'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const projectId = computed(() => (route.params.id ? String(route.params.id) : ''))
|
||||
const tick = ref(0)
|
||||
let timer: number | undefined
|
||||
|
||||
/** 登录页这类页面不套顶栏/侧栏外壳,也不去拉需要鉴权的系统状态 */
|
||||
const chromeless = computed(() => !!route.meta.public)
|
||||
|
||||
function stopPolling() {
|
||||
if (timer) window.clearInterval(timer)
|
||||
timer = undefined
|
||||
}
|
||||
|
||||
async function syncSystem() {
|
||||
if (chromeless.value || !isAuthenticated.value) { stopPolling(); return }
|
||||
await loadSystem()
|
||||
if (timer) return
|
||||
timer = window.setInterval(() => { void loadSystem(true) }, 30000)
|
||||
}
|
||||
|
||||
watch(() => [isAuthenticated.value, chromeless.value], () => { void syncSystem() }, { immediate: true })
|
||||
|
||||
const mustChangePassword = computed(() => !!auth.user?.must_change_password)
|
||||
const userInitial = computed(() => (displayName.value || '?').slice(0, 1).toUpperCase())
|
||||
/**
|
||||
* 顶栏「流程进度控制台」的数据源。
|
||||
* 不额外发请求:ProjectDetail 每 6 秒把项目详情写进 pctx,这里只读。
|
||||
* 但 pctx.id 在请求发出前就被赋值,项目 404(或已删除)时会残留上一个项目的数据,
|
||||
* 所以这里认「已经加载成功的那份项目数据自己的 id」,不认路由号。
|
||||
*/
|
||||
const proj = computed(() =>
|
||||
(projectId.value && pctx.project?.id === Number(projectId.value) ? pctx.project : null))
|
||||
const projectTitle = computed(() => proj.value?.name || (projectId.value ? '项目 #' + projectId.value : ''))
|
||||
/** 12 节点流程的分组,和后端 PIPELINE_STAGES 对齐;驳回时多出来的 revise 归入审核组 */
|
||||
const PIPE_GROUP: Record<string, string> = {
|
||||
create_project: 'prepare', import_storyboard: 'prepare', bind_assets: 'prepare',
|
||||
plan_tasks: 'plan', preflight: 'plan',
|
||||
dispatch: 'generate', generate: 'generate', save_output: 'generate',
|
||||
quality_check: 'review', review: 'review', revise: 'review',
|
||||
compose: 'deliver', export: 'deliver'
|
||||
}
|
||||
const PIPE_STATE: Record<string, string> = {
|
||||
done: '已完成', active: '进行中', failed: '需处理', pending: '待处理'
|
||||
}
|
||||
/** 轨道节点:正常 12 个,被驳回时后端会插一个 revise 变 13,所以一律按实际长度算 */
|
||||
const pipeNodes = computed(() => {
|
||||
const list: any[] = (proj.value ? pctx.workflow || [] : [])
|
||||
return list.map((n: any, i: number) => ({
|
||||
key: n.key,
|
||||
label: n.label || n.key,
|
||||
state: n.state || 'pending',
|
||||
detail: n.detail || '',
|
||||
groupEnd: i < list.length - 1 && PIPE_GROUP[list[i + 1].key] !== PIPE_GROUP[n.key]
|
||||
}))
|
||||
})
|
||||
const pipeTotal = computed(() => pipeNodes.value.length)
|
||||
const pipeDone = computed(() => pipeNodes.value.filter((n: any) => n.state === 'done').length)
|
||||
/**
|
||||
* 控制台的百分比说的是「轨道走到哪了」,直接由节点完成数算出,
|
||||
* 和旁边的轨道颜色一一对应。
|
||||
* 后端的 stats.progress_ratio 是「镜头审核合格比例」,口径不同,
|
||||
* 放在这里会出现「轨道 9 段绿、进度 0%」这种自相矛盾的画面。
|
||||
*/
|
||||
const pipePct = computed(() => (pipeTotal.value ? Math.round(pipeDone.value / pipeTotal.value * 100) + '%' : '—'))
|
||||
/** 详情还没回来(或项目已删除)时,轨道仍按 12 段虚位显示,不塌成一根长条 */
|
||||
const PIPE_GHOST = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map((i) => ({
|
||||
key: 'ghost' + i, label: '', state: 'pending', detail: '', groupEnd: i === 2 || i === 4 || i === 7 || i === 9
|
||||
}))
|
||||
const pipeRail = computed(() => (pipeNodes.value.length ? pipeNodes.value : PIPE_GHOST))
|
||||
const pipeCurrent = computed(() => {
|
||||
const ns = pipeNodes.value
|
||||
if (!ns.length) return null
|
||||
// 口径统一在 pipeline.ts:需处理 → 进行中 → 第一个没做完的;
|
||||
// 全部做完时不再有「当前节点」,不能再拿最后一个节点顶上来(那是一句反话)。
|
||||
const cur = openNode(ns)
|
||||
return cur || { label: '全部 ' + pipeTotal.value + ' 个节点已完成', state: 'done', detail: '', key: 'all-done', groupEnd: false }
|
||||
})
|
||||
/**
|
||||
* 整体色调跟着流程走:有节点需处理 → 红;全部完成 → 绿;机器正在干活 → accent。
|
||||
* 「正在干活」还要看项目状态:例如 12 个节点全绿只差最后导出时,
|
||||
* 后端把节点标成 pending、但项目其实是 composing,此时不该显示成灰色的空闲态。
|
||||
*/
|
||||
const IN_FLIGHT = ['generating', 'composing']
|
||||
const pipeTone = computed(() => {
|
||||
const ns = pipeNodes.value
|
||||
if (ns.some((n: any) => n.state === 'failed')) return 'failed'
|
||||
if (!ns.length) return 'idle'
|
||||
if (ns.every((n: any) => n.state === 'done')) return 'done'
|
||||
if (ns.some((n: any) => n.state === 'active') || IN_FLIGHT.includes(proj.value?.status)) return 'active'
|
||||
return 'pending'
|
||||
})
|
||||
const allDone = computed(() => pipeTotal.value > 0 && pipeDone.value === pipeTotal.value)
|
||||
/** 全部走完时不再叫「当前」,否则「当前 · 全部 12 个节点已完成」是句反话 */
|
||||
const pipeCurText = computed(() => (pipeCurrent.value
|
||||
? (allDone.value ? pipeCurrent.value.label : '当前 · ' + pipeCurrent.value.label) : ''))
|
||||
const pipeBadge = computed(() => (proj.value?.status ? statusLabel(proj.value.status) : ''))
|
||||
const pipeSummary = computed(() => '《' + projectTitle.value + '》流程进度 ' + pipePct.value
|
||||
+ ' · 已完成 ' + pipeDone.value + '/' + pipeTotal.value + ' 个节点'
|
||||
+ (pipeCurrent.value ? (allDone.value ? ' · ' : ' · 当前节点:') + pipeCurrent.value.label : ''))
|
||||
|
||||
|
||||
async function signOut() {
|
||||
closeMenu()
|
||||
await logout()
|
||||
stopPolling()
|
||||
await router.replace({ path: '/login', query: { loggedOut: '1' } })
|
||||
}
|
||||
|
||||
/** 从登录页返回时要能带上「原来是想去哪儿」 */
|
||||
function backTo(target: RouteLocationNormalized) {
|
||||
return target.fullPath
|
||||
}
|
||||
void tick; void backTo
|
||||
|
||||
/* ── 用户胶囊二级菜单 ───────────────────────────────────────── */
|
||||
const menuOpen = ref(false)
|
||||
const capEl = ref<HTMLElement | null>(null)
|
||||
function toggleMenu() { menuOpen.value = !menuOpen.value }
|
||||
function closeMenu() { menuOpen.value = false }
|
||||
function onDocDown(event: MouseEvent) {
|
||||
if (!menuOpen.value) return
|
||||
const host = capEl.value
|
||||
const target = event.target as Node | null
|
||||
if (host && target && host.contains(target)) return
|
||||
closeMenu()
|
||||
}
|
||||
/** 换页后菜单里的高亮项、角色都可能变,直接收起最省事 */
|
||||
watch(() => route.fullPath, closeMenu)
|
||||
|
||||
/** 环境自检不再常驻一列文字,只在真的有问题时到菜单里冒出来一次 */
|
||||
const envIssue = computed(() => {
|
||||
const h = store.health
|
||||
if (!h) return ''
|
||||
if (h.executor === 'celery' && !h.daemon?.running) return '调度守护未运行:新任务会一直排在队列里'
|
||||
if (!h.ffmpeg) return 'ffmpeg 缺失:时间线合成会被阻断'
|
||||
if (h.ffmpeg_capabilities && h.ffmpeg_capabilities.subtitle_burn === false) return 'ffmpeg 缺 libass:字幕将自动转成内嵌轨'
|
||||
return ''
|
||||
})
|
||||
|
||||
const isLight = computed(() => theme.applied === 'light')
|
||||
|
||||
function toggleTheme() {
|
||||
setTheme(isLight.value ? 'dark' : 'light')
|
||||
}
|
||||
|
||||
function onGlobalKey(event: KeyboardEvent) {
|
||||
if (event.key === 'Escape') { closeMenu(); return }
|
||||
if (event.key.toLowerCase() !== 'l' || !event.shiftKey || !(event.metaKey || event.ctrlKey) || event.altKey) return
|
||||
const el = event.target as HTMLElement | null
|
||||
if (el && /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName)) return
|
||||
event.preventDefault()
|
||||
toggleTheme()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener('keydown', onGlobalKey)
|
||||
document.addEventListener('mousedown', onDocDown, true)
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
stopPolling()
|
||||
window.removeEventListener('keydown', onGlobalKey)
|
||||
document.removeEventListener('mousedown', onDocDown, true)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="chromeless" class="bare">
|
||||
<router-view />
|
||||
<MediaLightbox />
|
||||
</div>
|
||||
<div v-else class="shell">
|
||||
<!-- ══ 顶部应用栏:品牌在左,账号胶囊 / 模式 / 手册等工具固定在右上 ══ -->
|
||||
<header class="appbar">
|
||||
<router-link class="brand" to="/" title="长视频编导平台 · 返回项目总览">
|
||||
<b aria-hidden="true">N</b>
|
||||
<span>长视频编导平台<small>NEX ANIMATION STUDIO</small></span>
|
||||
</router-link>
|
||||
|
||||
<!-- 流程进度控制台:顶栏居中两行 —— 项目名 + 状态 / 节点轨道 + 流程进度 + 当前节点 -->
|
||||
<router-link v-if="projectId" class="pipe" :class="`tone-${pipeTone}`"
|
||||
:to="`/projects/${projectId}/overview`" :title="pipeSummary + '(点击查看流程)'">
|
||||
<span class="pipe-top">
|
||||
<b class="pipe-name">{{ projectTitle }}</b>
|
||||
<em v-if="pipeBadge" class="pipe-badge">{{ pipeBadge }}</em>
|
||||
</span>
|
||||
<span class="pipe-flow">
|
||||
<span class="pipe-track" aria-hidden="true">
|
||||
<i v-for="n in pipeRail" :key="n.key" class="pipe-node" :class="[`s-${n.state}`, { split: n.groupEnd }]"
|
||||
:title="n.label ? n.label + ':' + (n.detail || PIPE_STATE[n.state] || n.state) : undefined"></i>
|
||||
</span>
|
||||
<small class="pipe-label">流程进度</small>
|
||||
<b class="pipe-pct">{{ pipePct }}</b>
|
||||
<small v-if="pipeCurrent" class="pipe-cur" :class="{ ok: allDone }">{{ pipeCurText }}</small>
|
||||
</span>
|
||||
</router-link>
|
||||
|
||||
<div class="tools">
|
||||
<a class="tool" href="/help.html" target="_blank" rel="noopener" title="使用手册 · 全流程操作截图(新窗口打开)">
|
||||
<i aria-hidden="true">🛈</i><span>手册</span>
|
||||
</a>
|
||||
<button class="tool" :class="{ 'theme-light': isLight }" @click="toggleTheme"
|
||||
:aria-label="'切换明暗主题,当前为' + (isLight ? '浅色' : '深色')"
|
||||
:title="'显示模式:' + (isLight ? '浅色' : '深色') + '(⌘/Ctrl+Shift+L 切换)'" >
|
||||
<i class="knob" aria-hidden="true">{{ isLight ? '☀' : '☾' }}</i><span>{{ isLight ? '浅色' : '深色' }}</span>
|
||||
</button>
|
||||
|
||||
<div v-if="auth.user" ref="capEl" class="capwrap">
|
||||
<button class="cap" :class="{ warn: mustChangePassword, open: menuOpen }"
|
||||
:aria-expanded="menuOpen" aria-haspopup="menu" @click="toggleMenu"
|
||||
:title="'账号菜单 · ' + displayName">
|
||||
<span class="cap-avatar" aria-hidden="true">{{ userInitial }}</span>
|
||||
<span class="cap-who">
|
||||
<b>{{ displayName }}</b>
|
||||
<small>{{ roleLabel(auth.user.role) }}<template v-if="auth.user.login_count"> · 第 {{ auth.user.login_count }} 次登录</template></small>
|
||||
</span>
|
||||
<span class="cap-caret" aria-hidden="true">⌄</span>
|
||||
</button>
|
||||
|
||||
<div v-if="menuOpen" class="cap-menu" role="menu">
|
||||
<div class="cap-head">
|
||||
<span class="cap-avatar" aria-hidden="true">{{ userInitial }}</span>
|
||||
<span class="cap-id">
|
||||
<b>{{ displayName }}</b>
|
||||
<small>{{ auth.user.username }}<template v-if="auth.user.email"> · {{ auth.user.email }}</template></small>
|
||||
</span>
|
||||
<em class="cap-roles">{{ roleLabel(auth.user.role) }}</em>
|
||||
</div>
|
||||
|
||||
<p v-if="mustChangePassword" class="cap-note">
|
||||
<router-link to="/account?must=1" role="menuitem" @click="closeMenu">初始密码尚未修改,点此设置新密码 →</router-link>
|
||||
</p>
|
||||
<p v-if="!canEdit" class="cap-note ro">观摩角色:只读,写操作会被后端拒绝</p>
|
||||
|
||||
<div class="cap-sep" role="separator"></div>
|
||||
|
||||
<router-link class="cap-item" to="/account" role="menuitem" title="账号信息、修改密码与登录设备">
|
||||
<i aria-hidden="true">◍</i><span>我的账号</span>
|
||||
</router-link>
|
||||
<router-link v-if="isAdmin" class="cap-item" to="/users" role="menuitem" title="账号、角色与配额">
|
||||
<i aria-hidden="true">▤</i><span>用户管理</span>
|
||||
</router-link>
|
||||
|
||||
<template v-if="envIssue">
|
||||
<div class="cap-sep" role="separator"></div>
|
||||
<p class="cap-note">{{ envIssue }}</p>
|
||||
</template>
|
||||
|
||||
<div class="cap-sep" role="separator"></div>
|
||||
|
||||
<button class="cap-item leave" role="menuitem" title="退出当前会话" @click="signOut">
|
||||
<i aria-hidden="true">⏻</i><span>退出登录</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- ══ 左侧导航:全局模块 + 当前项目节点(底部系统信息已按要求移除) ══ -->
|
||||
<aside>
|
||||
<nav class="nav">
|
||||
<router-link class="navitem" :class="{ chosen: route.path === '/' }" to="/"
|
||||
aria-label="项目总览" title="项目总览">
|
||||
<span class="navicon">⌂</span>
|
||||
<span>项目总览</span>
|
||||
</router-link>
|
||||
<router-link class="navitem" :class="{ chosen: route.path === '/assets' }" to="/assets"
|
||||
aria-label="平台资产库:人物 / 场景 / 声线母版" title="平台资产库 · 人物 / 场景 / 声线母版">
|
||||
<span class="navicon">✧</span>
|
||||
<span>平台资产库</span>
|
||||
</router-link>
|
||||
<router-link class="navitem" :class="{ chosen: route.path === '/models' }" to="/models"
|
||||
aria-label="模型管理中心:大模型 / 视频 / 图像 / 声音" title="模型管理中心 · 大模型 / 视频 / 图像 / 声音">
|
||||
<span class="navicon">◫</span>
|
||||
<span>模型管理中心</span>
|
||||
</router-link>
|
||||
</nav>
|
||||
|
||||
<template v-if="projectId">
|
||||
<div class="navtitle">
|
||||
<span>{{ projectTitle }}</span>
|
||||
<small v-if="pipeCurrent">{{ pipeCurrent.label }}</small>
|
||||
</div>
|
||||
<nav class="nav">
|
||||
<router-link v-for="m in modules" :key="m.label" class="navitem"
|
||||
:class="{ chosen: route.path === m.to(projectId) }" :to="m.to(projectId)"
|
||||
:aria-label="m.label + ':' + m.hint" :title="m.label + ' · ' + m.hint">
|
||||
<span class="navicon">{{ m.icon }}</span>
|
||||
<span>{{ m.label }}</span>
|
||||
</router-link>
|
||||
</nav>
|
||||
</template>
|
||||
</aside>
|
||||
|
||||
<main>
|
||||
<p v-if="store.error && !auth.offline && isAuthenticated" class="error" style="margin:0 0 14px">后端连接异常:{{ store.error }}</p>
|
||||
<router-view v-slot="{ Component }">
|
||||
<component :is="Component" :key="route.matched[0]?.path || route.path" />
|
||||
</router-view>
|
||||
</main>
|
||||
<MediaLightbox />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
/* ══════════════════════════════════════════════════════════════
|
||||
顶部应用栏
|
||||
· 结构:.shell 改成 flex-wrap:wrap,顶栏 flex:0 0 100% 独占第一行,
|
||||
侧栏与主内容留在第二行 —— 这样 style.css 里全部 .shell>aside /
|
||||
.shell>main 规则(含 ≤900/≤560 折叠轨道、宽度 calc(100% - 68px))
|
||||
继续生效,不必逐条搬运。
|
||||
· align-content:flex-start 必需:默认 stretch 会把多出来的竖向高度
|
||||
平摊给两行,短页面下顶栏会被拉成几百像素高。
|
||||
══════════════════════════════════════════════════════════════ */
|
||||
.bare { min-height: 100vh }
|
||||
.shell {
|
||||
/* 64 = 顶栏内边距 7×2 + 下边框 1 + 控制台 49px(17 + 4 + 16 + 内边距 10 + 边框 2)。
|
||||
侧栏 sticky、分镜检查器的 top 都取这个值,差 1px 就会露缝或压住内容,
|
||||
所以控制台两行都写死行高,不让字号/字体把顶栏顶高。 */
|
||||
--nex-bar: 64px;
|
||||
/* 顶栏控件统一高度(主题按钮 / 手册 / 账号胶囊):
|
||||
不再自定一档 37px,直接引用规范主尺寸,探针 CTL-H 才会与全站同判 */
|
||||
--nex-ctl: var(--ctl-h);
|
||||
display: flex; flex-wrap: wrap; align-content: flex-start; min-height: 100vh;
|
||||
}
|
||||
.shell>header.appbar {
|
||||
/* 66:高于分镜检查器(60),保证面板展开时右上角胶囊/模式始终可用;
|
||||
低于库抽屉模态(100)、灯箱(220)、下拉弹层(400),不打断真正的模态。 */
|
||||
flex: 0 0 100%; width: 100%; margin: 0; order: 0; z-index: 66;
|
||||
position: sticky; top: 0; display: flex; flex-wrap: nowrap; align-items: center; gap: 10px;
|
||||
min-height: var(--nex-bar); padding: 7px 16px;
|
||||
background: var(--c-bg-shell); border-bottom: 1px solid var(--c-bg-emphasis);
|
||||
}
|
||||
/* 顶栏里的品牌要压回一行高度:.brand 原型是侧栏用的(底部留白 30px、字号更小)
|
||||
flex:1 1 0 + min-width:max-content —— 品牌块与工具块各分一半剩余空间,
|
||||
中间的控制台因此严格落在「页面正中」,而不是「两块之间的正中」。 */
|
||||
.shell>header.appbar .brand {
|
||||
flex: 1 1 0; min-width: max-content; padding: 0; gap: 9px; font-size: 12px; letter-spacing: .6px;
|
||||
align-items: center; justify-content: flex-start;
|
||||
color: var(--c-text); text-decoration: none;
|
||||
}
|
||||
.shell>header.appbar .brand b { width: 31px; height: 31px; border-radius: 9px; font-size: 17px }
|
||||
.shell>header.appbar .brand small { margin-top: 3px; font-size: 10px; letter-spacing: .4px }
|
||||
/* ══ 流程进度控制台(取代原「当前项目 chip」)═══════════════════════
|
||||
· 位置:严格居中于页面。做法是品牌块与工具块都 flex:1 1 0 各占一半
|
||||
剩余空间(各自内容再贴左/贴右),控制台居中于两半之间 = 页面正中。
|
||||
不要用 margin-inline:auto:那样居中的是「品牌右缘↔工具左缘」这段
|
||||
空档的中点,工具区比品牌区宽 ~140px,控制台会整体偏左 70px。
|
||||
· 内容:第一行项目名 + 状态徽标;第二行 12~13 段节点轨道 + 流程进度(已完成节点/总节点)+ 当前节点。
|
||||
· 颜色:--pipe 是整块主色(左竖条 / 边框 / 百分比),随流程状态切换。
|
||||
· 任何断点都不撑破顶栏:外层 overflow:hidden,内部文本一律省略号。
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
.shell>header.appbar .pipe {
|
||||
--pipe: var(--c-accent); --pipe-tint: var(--c-accent-tint); --pipe-line: var(--c-accent-line);
|
||||
flex: 0 1 auto; min-width: 132px; max-width: 620px; margin: 0;
|
||||
position: relative; display: grid; gap: 4px; overflow: hidden;
|
||||
padding: 5px 14px 5px 15px;
|
||||
border: 1px solid var(--c-line-bright); border-radius: 12px;
|
||||
background: linear-gradient(96deg, var(--pipe-tint), var(--c-bg-sunken) 46%);
|
||||
color: var(--c-text); text-decoration: none;
|
||||
transition: border-color .18s ease, box-shadow .18s ease;
|
||||
}
|
||||
.shell>header.appbar .pipe:hover { border-color: var(--pipe-line); box-shadow: 0 0 0 1px var(--pipe-line) }
|
||||
/* 左侧状态竖条:扫一眼就知道项目是不是卡住了 */
|
||||
.shell>header.appbar .pipe::before {
|
||||
content: ""; position: absolute; left: 0; top: 0; bottom: 0; width: 3px; background: var(--pipe);
|
||||
}
|
||||
.shell>header.appbar .pipe.tone-active { --pipe: var(--c-accent); --pipe-tint: var(--c-accent-tint); --pipe-line: var(--c-accent-line) }
|
||||
.shell>header.appbar .pipe.tone-done { --pipe: var(--c-success); --pipe-tint: var(--c-success-tint); --pipe-line: var(--c-success-line) }
|
||||
.shell>header.appbar .pipe.tone-failed { --pipe: var(--c-danger); --pipe-tint: var(--c-danger-tint); --pipe-line: var(--c-danger-line) }
|
||||
.shell>header.appbar .pipe.tone-pending, .shell>header.appbar .pipe.tone-idle {
|
||||
--pipe: var(--c-text-faint); --pipe-tint: var(--c-bg-sunken); --pipe-line: var(--c-line-strong);
|
||||
}
|
||||
.shell>header.appbar .pipe-top { display: flex; align-items: center; gap: 7px; min-width: 0; height: 17px }
|
||||
.shell>header.appbar .pipe-name {
|
||||
min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
font-size: 12.5px; line-height: 17px; font-weight: 700; letter-spacing: .2px;
|
||||
}
|
||||
.shell>header.appbar .pipe-badge {
|
||||
flex: 0 0 auto; font-style: normal; font-size: 10px; font-weight: 700; padding: 0 7px;
|
||||
border-radius: 999px; border: 1px solid var(--pipe-line);
|
||||
background: var(--pipe-tint); color: var(--pipe);
|
||||
}
|
||||
.shell>header.appbar .pipe.tone-pending .pipe-badge, .shell>header.appbar .pipe.tone-idle .pipe-badge {
|
||||
border-color: var(--c-line); background: var(--c-bg-hover); color: var(--c-text-2);
|
||||
}
|
||||
/* 第二行:节点轨道 + 百分比 + 当前节点 */
|
||||
.shell>header.appbar .pipe-flow { display: flex; align-items: center; gap: 8px; min-width: 0; height: 16px }
|
||||
/* 轨道宽度写死:节点要能数得清。宁可整块按断点换档,也不让 12 段
|
||||
被 flex 压到 min-width 之后溢出轨道、盖到右边的百分比上。 */
|
||||
.shell>header.appbar .pipe-track {
|
||||
flex: 0 0 auto; width: 210px; height: 8px;
|
||||
display: flex; align-items: center; gap: 3px;
|
||||
}
|
||||
/* 未到达的节点用中性灰压暗,两个主题都要看得见(不能只靠 line 色) */
|
||||
.shell>header.appbar .pipe-node {
|
||||
flex: 1 1 0; min-width: 3px; height: 8px; border-radius: 2px;
|
||||
background: var(--c-text-faint); opacity: .34;
|
||||
}
|
||||
/* 阶段组之间留一道缝:准备 / 编排 / 生成 / 审核 / 成片 */
|
||||
.shell>header.appbar .pipe-node.split { margin-right: 7px }
|
||||
.shell>header.appbar .pipe-node.split:last-child { margin-right: 0 }
|
||||
.shell>header.appbar .pipe-node.s-done { background: var(--c-success); opacity: 1 }
|
||||
.shell>header.appbar .pipe-node.s-active { background: var(--c-accent); opacity: 1 }
|
||||
.shell>header.appbar .pipe-node.s-failed { background: var(--c-danger); opacity: 1 }
|
||||
/* 「正在做哪一段」是控制台最需要一眼看见的信息,但本平台两个主题的
|
||||
--c-accent 与 --c-success 都是青柠绿(#c5ee79 / #356309 vs #bce989 / #2c6510),
|
||||
光靠色相根本分不出「已完成」和「进行中」。所以进行中的节点另外加两层信号:
|
||||
更高的块 + 同色光环,深色浅色都成立;需处理同理用危险色。 */
|
||||
.shell>header.appbar .pipe-node.s-active {
|
||||
height: 13px; border-radius: 3px;
|
||||
box-shadow: 0 0 0 2px color-mix(in srgb, var(--c-accent) 26%, transparent),
|
||||
0 0 8px color-mix(in srgb, var(--c-accent) 45%, transparent);
|
||||
}
|
||||
.shell>header.appbar .pipe-node.s-failed {
|
||||
height: 13px; border-radius: 3px;
|
||||
box-shadow: 0 0 0 2px color-mix(in srgb, var(--c-danger) 26%, transparent),
|
||||
0 0 8px color-mix(in srgb, var(--c-danger) 45%, transparent);
|
||||
}
|
||||
.shell>header.appbar .pipe-node.s-active, .shell>header.appbar .pipe-node.s-failed {
|
||||
animation: nexpipe-pulse 1.5s ease-in-out infinite;
|
||||
}
|
||||
@keyframes nexpipe-pulse { 0%, 100% { opacity: 1 } 50% { opacity: .34 } }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.shell>header.appbar .pipe-node.s-active, .shell>header.appbar .pipe-node.s-failed { animation: none }
|
||||
}
|
||||
.shell>header.appbar .pipe-label { flex: 0 0 auto; font-size: 10px; color: var(--c-text-muted) }
|
||||
.shell>header.appbar .pipe-pct {
|
||||
flex: 0 0 auto; font-size: 13px; line-height: 16px; font-weight: 800; letter-spacing: .3px; color: var(--pipe);
|
||||
}
|
||||
.shell>header.appbar .pipe.tone-pending .pipe-pct, .shell>header.appbar .pipe.tone-idle .pipe-pct { color: var(--c-text-2) }
|
||||
.shell>header.appbar .pipe-cur {
|
||||
min-width: 0; flex: 0 1 auto; text-align: right;
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 16px;
|
||||
font-size: 10.5px; color: var(--c-text-faint);
|
||||
}
|
||||
/* 流程走完时这句话是好消息,用状态色而不是灰色 */
|
||||
.shell>header.appbar .pipe-cur.ok { color: var(--pipe) }
|
||||
|
||||
.shell>header.appbar .tools { flex: 1 1 0; display: flex; align-items: center; justify-content: flex-end; gap: 7px }
|
||||
.shell>header.appbar .tool {
|
||||
/* 顶栏控件等高:手册 / 主题按钮与账号胶囊共用 --nex-ctl(探针实测两者相差 6px 时被判定为排列不齐) */
|
||||
flex: 0 0 auto; display: flex; align-items: center; gap: 6px; height: var(--nex-ctl); padding: 0 9px;
|
||||
border: 1px solid var(--c-line); border-radius: 8px; background: transparent;
|
||||
color: var(--c-text-3); font-size: 11px; font-weight: 600; white-space: nowrap;
|
||||
text-decoration: none; cursor: pointer;
|
||||
}
|
||||
.shell>header.appbar .tool:hover { border-color: var(--c-line-bright); background: var(--c-bg-hover); color: var(--c-text) }
|
||||
.shell>header.appbar .tool i { font-style: normal; font-size: 12px; color: var(--c-text-muted) }
|
||||
.shell>header.appbar .tool:hover i { color: var(--c-accent) }
|
||||
.shell>header.appbar .tool .knob {
|
||||
display: grid; place-items: center; width: 17px; height: 17px; border-radius: 6px;
|
||||
background: var(--c-accent-fill); color: var(--c-on-accent); font-size: 10px;
|
||||
transition: transform .2s ease;
|
||||
}
|
||||
.shell>header.appbar .tool.theme-light .knob { transform: rotate(-18deg) }
|
||||
|
||||
/* ── 用户胶囊 ── */
|
||||
.shell>header.appbar .capwrap { position: relative; flex: 0 0 auto }
|
||||
.shell>header.appbar .cap {
|
||||
position: relative; display: flex; align-items: center; gap: 8px; height: var(--nex-ctl);
|
||||
padding: 0 8px 0 4px; border: 1px solid var(--c-line); border-radius: 999px;
|
||||
background: var(--c-bg-sunken); color: var(--c-text-2); cursor: pointer; text-align: left;
|
||||
}
|
||||
.shell>header.appbar .cap:hover, .shell>header.appbar .cap.open {
|
||||
border-color: var(--c-line-bright); background: var(--c-bg-hover); color: var(--c-text);
|
||||
}
|
||||
.shell>header.appbar .cap.warn { border-color: var(--c-warn-line) }
|
||||
.shell>header.appbar .cap-avatar {
|
||||
position: relative; display: grid; place-items: center; flex: 0 0 auto;
|
||||
width: 27px; height: 27px; border-radius: 999px;
|
||||
background: var(--c-accent-fill); color: var(--c-on-accent); font-size: 12px; font-weight: 700;
|
||||
}
|
||||
/* 待改密码的提醒不能只藏在菜单里:胶囊上先挂一个角标。
|
||||
角标挂在胶囊而不是头像上——头像是 27px 的正圆,绝对定位的角标会把它自己的
|
||||
scrollWidth 撑到 30px(内容并没有被裁,但等于凭空多出一个横向溢出元素)。 */
|
||||
.shell>header.appbar .cap.warn::after {
|
||||
content: '!'; position: absolute; top: -3px; right: -2px; width: 14px; height: 14px;
|
||||
display: grid; place-items: center; border-radius: 999px; font-size: 10px; font-weight: 700;
|
||||
background: var(--c-warn-fill); color: var(--c-warn-ink);
|
||||
}
|
||||
.shell>header.appbar .cap-who { min-width: 0; max-width: 132px; display: grid; line-height: 1.25 }
|
||||
.shell>header.appbar .cap-who b, .shell>header.appbar .cap-who small {
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
}
|
||||
.shell>header.appbar .cap-who b { font-size: 11.5px }
|
||||
.shell>header.appbar .cap-who small { color: var(--c-text-faint); font-size: 10px }
|
||||
.shell>header.appbar .cap-caret { flex: 0 0 auto; font-size: 11px; color: var(--c-text-faint); transition: transform .18s ease }
|
||||
.shell>header.appbar .cap.open .cap-caret { transform: rotate(180deg) }
|
||||
|
||||
/* ── 二级菜单:账号 / 用户管理 / 退出登录都收在这里 ── */
|
||||
.shell>header.appbar .cap-menu {
|
||||
position: absolute; right: 0; top: calc(100% + 8px); z-index: 70; width: 262px;
|
||||
display: grid; gap: 2px; padding: 9px; border: 1px solid var(--c-line-strong); border-radius: 12px;
|
||||
background: var(--c-bg-panel); box-shadow: 0 18px 44px rgba(0, 0, 0, .44);
|
||||
}
|
||||
.shell>header.appbar .cap-head {
|
||||
display: flex; align-items: center; gap: 9px; padding: 3px 4px 9px;
|
||||
border-bottom: 1px solid var(--c-line-soft);
|
||||
}
|
||||
.shell>header.appbar .cap-id { min-width: 0; display: grid; gap: 2px }
|
||||
.shell>header.appbar .cap-id b { font-size: 12.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap }
|
||||
.shell>header.appbar .cap-id small {
|
||||
color: var(--c-text-faint); font-size: 10px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
}
|
||||
.shell>header.appbar .cap-roles {
|
||||
margin-left: auto; flex: 0 0 auto; font-style: normal; font-size: 10px; padding: 2px 6px;
|
||||
border-radius: 999px; background: var(--c-bg-hover); color: var(--c-text-2);
|
||||
}
|
||||
.shell>header.appbar .cap-item {
|
||||
display: flex; align-items: center; gap: 9px; width: 100%; min-height: 32px; padding: 7px 9px;
|
||||
border: 1px solid transparent; border-radius: 8px; background: transparent; cursor: pointer;
|
||||
color: var(--c-text-2); font-size: 12px; text-align: left; text-decoration: none;
|
||||
}
|
||||
.shell>header.appbar .cap-item:hover { border-color: var(--c-line); background: var(--c-bg-hover); color: var(--c-text) }
|
||||
.shell>header.appbar .cap-item i { flex: 0 0 auto; width: 15px; text-align: center; font-style: normal; font-size: 12px; color: var(--c-text-muted) }
|
||||
.shell>header.appbar .cap-item:hover i { color: var(--c-accent) }
|
||||
.shell>header.appbar .cap-item.leave, .shell>header.appbar .cap-item.leave i { color: var(--c-danger) }
|
||||
.shell>header.appbar .cap-item.leave:hover {
|
||||
border-color: var(--c-danger-line); background: var(--c-danger-tint); color: var(--c-danger-bright);
|
||||
}
|
||||
.shell>header.appbar .cap-item.leave:hover i { color: var(--c-danger-bright) }
|
||||
.shell>header.appbar .cap-note {
|
||||
margin: 0; padding: 7px 9px; border-radius: 8px; font-size: 10px; line-height: 1.5;
|
||||
overflow-wrap: anywhere; background: var(--c-warn-tint); color: var(--c-warn-bright);
|
||||
}
|
||||
.shell>header.appbar .cap-note a { color: inherit; text-decoration: underline }
|
||||
.shell>header.appbar .cap-note.ro { background: var(--c-bg-hover); color: var(--c-text-faint) }
|
||||
.shell>header.appbar .cap-sep { height: 1px; margin: 5px 2px; background: var(--c-line-soft) }
|
||||
|
||||
/* ══ 侧栏:只剩导航,粘在顶栏下方自己滚 ══ */
|
||||
.shell>aside {
|
||||
position: sticky; top: var(--nex-bar); height: calc(100vh - var(--nex-bar));
|
||||
overflow-y: auto; scrollbar-width: none;
|
||||
}
|
||||
.shell>aside::-webkit-scrollbar { display: none }
|
||||
.shell>aside .nav { flex: 0 0 auto }
|
||||
|
||||
/* ══ 顶栏逐级降级:文字 → 图标,始终单行,绝不横向溢出 ══ */
|
||||
@media (max-width: 900px) {
|
||||
.shell>header.appbar { gap: 8px; padding: 7px 11px }
|
||||
.shell>header.appbar .brand { padding: 0; justify-content: flex-start }
|
||||
.shell>header.appbar .brand span { display: none }
|
||||
}
|
||||
@media (max-width: 820px) {
|
||||
.shell>header.appbar .tool { width: 31px; padding: 0; justify-content: center }
|
||||
.shell>header.appbar .tool span { display: none }
|
||||
}
|
||||
/* 控制台逐级降级:当前节点 → 状态徽标/文字标签 → 只剩轨道 + 百分比 */
|
||||
@media (max-width: 1180px) {
|
||||
.shell>header.appbar .pipe { max-width: 452px }
|
||||
.shell>header.appbar .pipe-track { width: 176px }
|
||||
.shell>header.appbar .pipe-cur { display: none }
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.shell>header.appbar .pipe { max-width: 420px; padding: 5px 11px 5px 12px }
|
||||
.shell>header.appbar .pipe-track { width: 150px }
|
||||
}
|
||||
@media (max-width: 640px) {
|
||||
.shell>header.appbar .pipe { max-width: 258px; min-width: 118px }
|
||||
/* 窄屏收缝:12 段 × 3px + 11 条缝 + 4 道组缝 = 104,轨道低于这个宽度节点就会挤出去 */
|
||||
.shell>header.appbar .pipe-track { width: 110px; gap: 2px }
|
||||
.shell>header.appbar .pipe-node.split { margin-right: 3px }
|
||||
.shell>header.appbar .pipe-badge, .shell>header.appbar .pipe-label { display: none }
|
||||
}
|
||||
@media (max-width: 560px) {
|
||||
.shell>header.appbar .pipe { max-width: 196px; gap: 3px; min-width: 132px }
|
||||
.shell>header.appbar .pipe-track { width: 78px }
|
||||
.shell>header.appbar .cap { width: var(--nex-ctl); height: var(--nex-ctl); padding: 0; justify-content: center }
|
||||
.shell>header.appbar .cap-who, .shell>header.appbar .cap-caret { display: none }
|
||||
}
|
||||
</style>
|
||||
|
|
@ -0,0 +1,140 @@
|
|||
/**
|
||||
* 应用外壳:顶栏 + 侧栏 + 主内容,以及登录守卫、标题、系统状态轮询。
|
||||
*
|
||||
* · 登录页这类 chromeless 页面不套顶栏/侧栏,也不去拉需要鉴权的系统状态。
|
||||
* · 守卫沿用旧版规则:只在第一次导航时打一次 /api/auth/state,之后靠 401 回调
|
||||
* 把快照清空;后端连不上(offline)或管理员关掉鉴权时不要把人家去登录页——
|
||||
* 否则网络抖一下就得重新登录。
|
||||
*/
|
||||
import { Suspense, useEffect, useRef, useState, type ReactNode } from 'react'
|
||||
import { Navigate, Outlet, useLocation, useMatches } from 'react-router-dom'
|
||||
import { Loading, Notice } from '../components/ui'
|
||||
import { authState, refreshState, useAuthStore, useIsAuthenticated } from '../stores/auth'
|
||||
import { loadSystem, useSystemStore } from '../stores/system'
|
||||
import { toggleTheme } from '../stores/theme'
|
||||
import { useProjectStore } from '../stores/project'
|
||||
import MediaLightbox from '../components/media/MediaLightbox'
|
||||
import AppBar from './layout/AppBar'
|
||||
import SideNav from './layout/SideNav'
|
||||
import NoticeToast from './layout/NoticeToast'
|
||||
import type { RouteHandle } from './router'
|
||||
|
||||
/** 主内容宽度 = 100% - 侧栏宽度,两处的断点必须一起改 */
|
||||
const MAIN = 'mx-auto w-[calc(100%-230px)] min-w-0 max-w-[1800px] flex-1 self-start p-[27px] max-nav:w-[calc(100%-68px)] max-nav:p-[18px] max-narrow:w-[calc(100%-66px)] max-narrow:p-[14px_10px_24px]'
|
||||
|
||||
/**
|
||||
* 鉴权闸门(旧 router.beforeEach 的等价物)。
|
||||
*
|
||||
* 做成组件而不是 loader:会话状态在 zustand 里,任何请求拿到 401 都会清空快照,
|
||||
* 组件订阅 store 后自然把人送回登录页,不需要再手工触发一次导航。
|
||||
*/
|
||||
function AuthGate({ admin, children }: { admin?: boolean; children: ReactNode }) {
|
||||
const { checked, enabled, user, offline } = useAuthStore()
|
||||
const location = useLocation()
|
||||
useEffect(() => {
|
||||
if (!authState().checked) void refreshState()
|
||||
}, [])
|
||||
|
||||
if (!checked) return <Loading>正在确认登录状态</Loading>
|
||||
if (offline || !enabled) return <>{children}</>
|
||||
if (!user) {
|
||||
return <Navigate to={'/login?next=' + encodeURIComponent(location.pathname + location.search)} replace />
|
||||
}
|
||||
if (admin && user.role !== 'admin') return <Navigate to="/" replace />
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const matches = useMatches()
|
||||
const location = useLocation()
|
||||
/* 越深的路由越具体:标题取最后一个声明了 title 的匹配项 */
|
||||
const handle = matches.reduce<RouteHandle>((acc, m) => ({ ...acc, ...(m.handle as RouteHandle | undefined) }), {})
|
||||
const projectId = matches.reduce((acc, m) => (m.params.id ? String(m.params.id) : acc), '')
|
||||
const chromeless = !!handle.public
|
||||
const auth = useAuthStore()
|
||||
const isAuthenticated = useIsAuthenticated()
|
||||
const systemError = useSystemStore((s) => s.error)
|
||||
const project = useProjectStore((s) => s.project)
|
||||
const pollRef = useRef<number | undefined>(undefined)
|
||||
const [ready, setReady] = useState(() => authState().checked)
|
||||
|
||||
/* 未鉴权路由在快照回来之前不渲染内容,避免先闪一屏 401 报错再跳登录页 */
|
||||
useEffect(() => {
|
||||
if (authState().checked) return
|
||||
void refreshState().then(() => setReady(true))
|
||||
}, [])
|
||||
|
||||
/* 文档标题:旧版在 afterEach 里做,这里等价地在 handle 变化时做 */
|
||||
useEffect(() => {
|
||||
if (handle.title) document.title = `${handle.title} · Nex Animation Studio`
|
||||
}, [handle.title])
|
||||
|
||||
/* 系统状态:30 秒一次,只在「已登录且不是登录页」时跑,省掉匿名请求 */
|
||||
useEffect(() => {
|
||||
if (chromeless || !isAuthenticated) {
|
||||
if (pollRef.current) window.clearInterval(pollRef.current)
|
||||
pollRef.current = undefined
|
||||
return
|
||||
}
|
||||
void loadSystem()
|
||||
if (pollRef.current) return
|
||||
pollRef.current = window.setInterval(() => { void loadSystem(true) }, 30000)
|
||||
return () => {
|
||||
if (pollRef.current) window.clearInterval(pollRef.current)
|
||||
pollRef.current = undefined
|
||||
}
|
||||
}, [chromeless, isAuthenticated])
|
||||
|
||||
/* 全局快捷键:⌘/Ctrl+Shift+L 切明暗;输入框里打字时不抢键 */
|
||||
useEffect(() => {
|
||||
function onKey(event: KeyboardEvent) {
|
||||
if (event.key.toLowerCase() !== 'l' || !event.shiftKey || !(event.metaKey || event.ctrlKey) || event.altKey) return
|
||||
const el = event.target as HTMLElement | null
|
||||
if (el && /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName)) return
|
||||
event.preventDefault()
|
||||
toggleTheme()
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [])
|
||||
|
||||
/* 认「加载成功的那份项目数据自己的 id」,项目 404 时不残留上一个项目的名字 */
|
||||
const proj = projectId && project?.id === Number(projectId) ? project : null
|
||||
const projectTitle = proj?.name || (projectId ? '项目 #' + projectId : '')
|
||||
|
||||
if (chromeless) {
|
||||
/* 已经登录就不再停在登录页 */
|
||||
if (location.pathname === '/login' && auth.checked && auth.user && !auth.offline) return <Navigate to="/" replace />
|
||||
return (
|
||||
<div className="min-h-screen">
|
||||
<Suspense fallback={<Loading>页面加载中</Loading>}>
|
||||
<Outlet />
|
||||
</Suspense>
|
||||
<MediaLightbox />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!ready) return <Loading className="min-h-screen">正在确认登录状态</Loading>
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen flex-wrap content-start">
|
||||
<AppBar projectId={projectId} />
|
||||
<SideNav projectId={projectId} projectTitle={projectTitle} />
|
||||
<main className={MAIN}>
|
||||
{systemError && !auth.offline && isAuthenticated && (
|
||||
<Notice danger className="mb-[14px]">后端连接异常:{systemError}</Notice>
|
||||
)}
|
||||
<AuthGate admin={handle.admin}>
|
||||
{/* 换顶级路由时整块重挂:避免上一个页面的本地状态(筛选条件、抽屉)
|
||||
串到下一个页面。同一项目内切页签时顶级路由没变,不会重挂。 */}
|
||||
<Suspense fallback={<Loading>页面加载中</Loading>}>
|
||||
<Outlet key={matches[1]?.id || location.pathname} />
|
||||
</Suspense>
|
||||
</AuthGate>
|
||||
</main>
|
||||
<MediaLightbox />
|
||||
<NoticeToast />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
/**
|
||||
* 顶部应用栏:品牌在左,流程控制台居中,账号胶囊 / 模式 / 手册固定在右上。
|
||||
*
|
||||
* · 结构:外壳是 flex-wrap:wrap 的容器,顶栏 flex:0 0 100% 独占第一行,
|
||||
* 侧栏与主内容留在第二行 —— 这样侧栏/主区的 sticky 与 calc() 宽度
|
||||
* 规则继续生效,不必逐条搬运。
|
||||
* · align-content:flex-start 必需:默认 stretch 会把多出来的竖向高度
|
||||
* 平摊给两行,短页面下顶栏会被拉成几百像素高。
|
||||
* · 品牌块与工具块都 flex:1 1 0 各占一半剩余空间(内容再各自贴左/贴右),
|
||||
* 中间的控制台因此严格落在「页面正中」。不要用 margin-inline:auto:
|
||||
* 那样居中的是「品牌右缘↔工具左缘」这段空档的中点,工具区比品牌区宽
|
||||
* ~140px,控制台会整体偏左 70px。
|
||||
* · z-66:高于分镜检查器(60),保证面板展开时右上角胶囊/模式始终可用;
|
||||
* 低于抽屉(100)、灯箱(220)、下拉弹层(400),不打断真正的模态。
|
||||
*/
|
||||
import { NavLink } from 'react-router-dom'
|
||||
import { cn } from '../../lib/cn'
|
||||
import { toggleTheme, useAppliedTheme } from '../../stores/theme'
|
||||
import PipelineConsole from './PipelineConsole'
|
||||
import UserMenu from './UserMenu'
|
||||
|
||||
/** 顶栏控件(手册 / 主题 / 胶囊)统一高度取 --nex-ctl,即规范主尺寸 */
|
||||
const TOOL = 'group flex h-(--nex-ctl) flex-none items-center gap-1.5 rounded-[8px] border border-line bg-transparent px-[9px] text-body font-semibold text-ink-3 whitespace-nowrap no-underline hover:border-line-bright hover:bg-hover hover:text-ink max-nav:justify-center max-nav:w-(--nex-ctl) max-nav:px-0 max-nav:[&>span]:hidden'
|
||||
|
||||
export function AppBar({ projectId }: { projectId: string }) {
|
||||
const isLight = useAppliedTheme() === 'light'
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-66 flex min-h-(--nex-bar) w-full flex-none basis-full flex-nowrap items-center gap-2.5 border-b border-emphasis bg-shell px-4 py-[7px]">
|
||||
<NavLink to="/" title="长视频编导平台 · 返回项目总览"
|
||||
className="flex flex-[1_1_0] min-w-max items-center justify-start gap-[9px] text-body tracking-[.6px] text-ink no-underline">
|
||||
<b aria-hidden="true" className="grid h-[31px] w-[31px] place-items-center rounded-tile bg-accent-fill text-[17px] text-on-accent">N</b>
|
||||
<span className="max-nav:hidden">长视频编导平台
|
||||
<small className="mt-[3px] block text-tiny font-normal tracking-[.4px] text-faint">NEX ANIMATION STUDIO</small>
|
||||
</span>
|
||||
</NavLink>
|
||||
|
||||
{projectId && <PipelineConsole projectId={projectId} />}
|
||||
|
||||
<div className="flex flex-[1_1_0] items-center justify-end gap-[7px]">
|
||||
<a className={cn(TOOL)} href="/help.html" target="_blank" rel="noopener" title="使用手册 · 全流程操作截图(新窗口打开)">
|
||||
<i aria-hidden="true" className="text-ui not-italic text-muted group-hover:text-accent">🛈</i><span>手册</span>
|
||||
</a>
|
||||
<button type="button" className={cn(TOOL, 'cursor-pointer')} onClick={toggleTheme}
|
||||
aria-label={'切换明暗主题,当前为' + (isLight ? '浅色' : '深色')}
|
||||
title={'显示模式:' + (isLight ? '浅色' : '深色') + '(⌘/Ctrl+Shift+L 切换)'}>
|
||||
<i aria-hidden="true"
|
||||
className={cn('grid h-[17px] w-[17px] place-items-center rounded-[6px] bg-accent-fill text-tiny text-on-accent transition-transform duration-[180ms]',
|
||||
isLight && 'rotate-[-18deg]')}>{isLight ? '☀' : '☾'}</i>
|
||||
<span>{isLight ? '浅色' : '深色'}</span>
|
||||
</button>
|
||||
<UserMenu />
|
||||
</div>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
|
||||
export default AppBar
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
/**
|
||||
* 全局操作提示。
|
||||
*
|
||||
* 旧版的 notify() 把文字写进项目共享状态,只有项目详情页顶部会显示,
|
||||
* 资产库 / 模型中心里点完按钮悄无声息。现在挂在 App 外壳上,
|
||||
* 右下堆叠、6 秒自动消失,任何模块调 notify() 都看得见。
|
||||
*/
|
||||
import { cn } from '../../lib/cn'
|
||||
import { useNoticeStore } from '../../stores/notice'
|
||||
|
||||
export function NoticeToast() {
|
||||
const items = useNoticeStore((s) => s.items)
|
||||
const dismiss = useNoticeStore((s) => s.dismiss)
|
||||
if (!items.length) return null
|
||||
return (
|
||||
<div className="pointer-events-none fixed bottom-4 right-4 z-240 flex w-[min(420px,calc(100vw-32px))] flex-col gap-2">
|
||||
{items.map((n) => (
|
||||
<div key={n.id}
|
||||
className={cn('pointer-events-auto flex items-start gap-2 rounded-[8px] border px-3 py-[11px] text-body shadow-pop animate-fade-in',
|
||||
n.tone === 'bad'
|
||||
? 'border-danger-line bg-danger-tint text-danger-bright'
|
||||
: 'border-accent-line bg-accent-tint-2 text-accent-bright')}>
|
||||
<span className="min-w-0 grow [overflow-wrap:anywhere]">{n.text}</span>
|
||||
<button type="button" onClick={() => dismiss(n.id)} title="关闭提示"
|
||||
className="shrink-0 border-0 bg-transparent p-0 text-caption text-inherit opacity-60 hover:opacity-100">✕</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default NoticeToast
|
||||
|
|
@ -0,0 +1,153 @@
|
|||
/**
|
||||
* 顶栏「流程进度控制台」:项目名 + 状态 / 12~13 段节点轨道 + 流程进度 + 当前节点。
|
||||
*
|
||||
* 数据源不额外发请求:ProjectDetail 每 6 秒把项目详情写进 useProjectStore,
|
||||
* 这里只读。但 pctx.id 在请求发出前就被赋值,项目 404(或已删除)时会残留
|
||||
* 上一个项目的数据,所以这里认「已经加载成功的那份项目数据自己的 id」,不认路由号。
|
||||
*
|
||||
* 布局约定:品牌块与工具块各 flex:1 1 0,控制台夹在正中 = 页面正中。
|
||||
* 不要改成 margin-inline:auto:那居中的是「品牌右缘↔工具左缘」空档的中点,
|
||||
* 工具区比品牌区宽约 140px,整块会偏左 70px。
|
||||
*/
|
||||
import { NavLink } from 'react-router-dom'
|
||||
import { cn } from '../../lib/cn'
|
||||
import { statusLabel } from '../../lib/format'
|
||||
import { openNode, stageNote } from '../../lib/pipeline'
|
||||
import { useProjectStore } from '../../stores/project'
|
||||
|
||||
/** 12 节点流程的分组,和后端 PIPELINE_STAGES 对齐;驳回时多出来的 revise 归入审核组 */
|
||||
const PIPE_GROUP: Record<string, string> = {
|
||||
create_project: 'prepare', import_storyboard: 'prepare', bind_assets: 'prepare',
|
||||
plan_tasks: 'plan', preflight: 'plan',
|
||||
dispatch: 'generate', generate: 'generate', save_output: 'generate',
|
||||
quality_check: 'review', review: 'review', revise: 'review',
|
||||
compose: 'deliver', export: 'deliver'
|
||||
}
|
||||
const PIPE_STATE: Record<string, string> = {
|
||||
done: '已完成', active: '进行中', failed: '需处理', pending: '待处理'
|
||||
}
|
||||
/** 「正在干活」的项目状态:节点可能还是 pending,但后端其实在合成 / 生成 */
|
||||
const IN_FLIGHT = ['generating', 'composing']
|
||||
/** 详情还没回来(或项目已删除)时,轨道仍按 12 段虚位显示,不塌成一根长条 */
|
||||
const PIPE_GHOST = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map((i) => ({
|
||||
key: 'ghost' + i, label: '', state: 'pending', detail: '', groupEnd: i === 2 || i === 4 || i === 7 || i === 9
|
||||
}))
|
||||
const PIPE_COLOR: Record<string, string> = {
|
||||
active: 'var(--c-accent)', done: 'var(--c-success)', failed: 'var(--c-danger)',
|
||||
pending: 'var(--c-text-faint)', idle: 'var(--c-text-faint)'
|
||||
}
|
||||
const PIPE_TINT: Record<string, string> = {
|
||||
active: 'var(--c-accent-tint)', done: 'var(--c-success-tint)', failed: 'var(--c-danger-tint)',
|
||||
pending: 'var(--c-bg-sunken)', idle: 'var(--c-bg-sunken)'
|
||||
}
|
||||
const NODE_STATE: Record<string, string> = {
|
||||
done: 'bg-success opacity-100',
|
||||
active: 'bg-accent opacity-100 h-[13px] rounded-[3px] animate-pulse-soft',
|
||||
failed: 'bg-danger opacity-100 h-[13px] rounded-[3px] animate-pulse-soft',
|
||||
pending: 'bg-faint opacity-34'
|
||||
}
|
||||
|
||||
export function PipelineConsole({ projectId }: { projectId: string }) {
|
||||
const project = useProjectStore((s) => s.project)
|
||||
const workflow = useProjectStore((s) => s.workflow)
|
||||
/* 认「加载成功的那份数据自己的 id」,不认路由号 */
|
||||
const proj = projectId && project?.id === Number(projectId) ? project : null
|
||||
if (!projectId) return null
|
||||
|
||||
const list = proj ? workflow || [] : []
|
||||
/** 轨道节点:正常 12 个,被驳回时后端会插一个 revise 变 13,所以一律按实际长度算 */
|
||||
const pipeNodes = list.map((n: any, i: number) => ({
|
||||
key: n.key,
|
||||
label: n.label || n.key,
|
||||
state: n.state || 'pending',
|
||||
detail: n.detail || '',
|
||||
groupEnd: i < list.length - 1 && PIPE_GROUP[list[i + 1].key] !== PIPE_GROUP[n.key]
|
||||
}))
|
||||
const pipeTotal = pipeNodes.length
|
||||
const pipeDone = pipeNodes.filter((n) => n.state === 'done').length
|
||||
/**
|
||||
* 控制台的百分比说的是「轨道走到哪了」,直接由节点完成数算出,
|
||||
* 和旁边的轨道颜色一一对应。
|
||||
* 后端的 stats.progress_ratio 是「镜头审核合格比例」,口径不同,
|
||||
* 放在这里会出现「轨道 9 段绿、进度 0%」这种自相矛盾的画面。
|
||||
*/
|
||||
const pipePct = pipeTotal ? Math.round(pipeDone / pipeTotal * 100) + '%' : '—'
|
||||
const pipeRail = pipeNodes.length ? pipeNodes : PIPE_GHOST
|
||||
// 口径统一在 lib/pipeline.ts:需处理 → 进行中 → 第一个没做完的;
|
||||
// 全部做完时不再有「当前节点」,不能再拿最后一个节点顶上来(那是一句反话)。
|
||||
const pipeCurrent = pipeNodes.length
|
||||
? openNode(pipeNodes) || { label: '全部 ' + pipeTotal + ' 个节点已完成', state: 'done', detail: '', key: 'all-done' }
|
||||
: null
|
||||
/**
|
||||
* 整体色调跟着流程走:有节点需处理 → 红;全部完成 → 绿;机器正在干活 → accent。
|
||||
* 「正在干活」还要看项目状态:例如 12 个节点全绿只差最后导出时,
|
||||
* 后端把节点标成 pending、但项目其实是 composing,此时不该显示成灰色的空闲态。
|
||||
*/
|
||||
const pipeTone = pipeNodes.some((n) => n.state === 'failed') ? 'failed'
|
||||
: !pipeNodes.length ? 'idle'
|
||||
: pipeNodes.every((n) => n.state === 'done') ? 'done'
|
||||
: pipeNodes.some((n) => n.state === 'active') || IN_FLIGHT.includes(proj?.status) ? 'active'
|
||||
: 'pending'
|
||||
const allDone = pipeTotal > 0 && pipeDone === pipeTotal
|
||||
/** 全部走完时不再叫「当前」,否则「当前 · 全部 12 个节点已完成」是句反话 */
|
||||
const pipeCurText = pipeCurrent ? (allDone ? pipeCurrent.label : '当前 · ' + pipeCurrent.label) : ''
|
||||
const projectTitle = proj?.name || '项目 #' + projectId
|
||||
const color = PIPE_COLOR[pipeTone]
|
||||
const muted = pipeTone === 'pending' || pipeTone === 'idle'
|
||||
|
||||
const summary = '《' + projectTitle + '》流程进度 ' + pipePct
|
||||
+ ' · 已完成 ' + pipeDone + '/' + pipeTotal + ' 个节点'
|
||||
+ (pipeCurrent ? (allDone ? ' · ' : ' · 当前节点:') + pipeCurrent.label : '')
|
||||
|
||||
return (
|
||||
<NavLink to={`/projects/${projectId}/overview`} title={summary + '(点击查看流程)'}
|
||||
className={cn('relative grid min-w-[132px] max-w-[620px] flex-[0_1_auto] gap-1 overflow-hidden rounded-block border border-line-bright bg-[linear-gradient(96deg,var(--pipe-tint),var(--c-bg-sunken)_46%)] py-[5px] pl-[15px] pr-[14px] text-ink no-underline transition-[border-color,box-shadow] duration-[180ms] hover:border-[var(--pipe-line)] hover:shadow-[0_0_0_1px_var(--pipe-line)] max-mid:max-w-[452px] max-nav:max-w-[420px] max-nav:pl-[12px] max-nav:pr-[11px] max-tiny:max-w-[258px] max-tiny:min-w-[118px] max-narrow:min-w-[132px] max-narrow:max-w-[196px] max-narrow:gap-[3px]',
|
||||
muted ? '' : 'border-[var(--pipe-line)]')}
|
||||
style={{ ['--pipe' as any]: color, ['--pipe-tint' as any]: PIPE_TINT[pipeTone], ['--pipe-line' as any]: color }}>
|
||||
<span className="absolute inset-y-0 left-0 w-[3px] bg-[var(--pipe)]" aria-hidden="true"></span>
|
||||
|
||||
<span className="flex h-[17px] min-w-0 items-center gap-[7px]">
|
||||
<b className="min-w-0 truncate text-[12.5px] font-bold leading-[17px] tracking-[.2px]">{projectTitle}</b>
|
||||
{proj?.status && (
|
||||
<em className={cn('flex-none rounded-pill border px-[7px] text-tiny font-bold not-italic',
|
||||
muted ? 'border-line bg-hover text-ink-2' : 'border-[var(--pipe-line)] bg-[var(--pipe-tint)] text-[var(--pipe)] max-tiny:hidden')}>
|
||||
{statusLabel(proj.status)}
|
||||
</em>
|
||||
)}
|
||||
</span>
|
||||
|
||||
<span className="flex h-4 min-w-0 items-center gap-2">
|
||||
{/* 轨道宽度写死:节点要能数得清。宁可整块按断点换档,也不让 12 段
|
||||
被 flex 压到 min-width 之后溢出轨道、盖到右边的百分比上。 */}
|
||||
<span className="flex h-2 w-[210px] flex-none items-center gap-[3px] max-mid:w-[176px] max-nav:w-[150px] max-tiny:w-[110px] max-tiny:gap-0.5 max-narrow:w-[78px]" aria-hidden="true">
|
||||
{pipeRail.map((n) => (
|
||||
<i key={n.key} title={n.label ? n.label + ':' + (n.detail || PIPE_STATE[n.state] || n.state) : undefined}
|
||||
className={cn('h-2 min-w-[3px] flex-1 basis-0 rounded-[2px]', NODE_STATE[n.state] || NODE_STATE.pending,
|
||||
n.groupEnd && 'mr-[7px] last:mr-0 max-tiny:mr-[3px]')} />
|
||||
))}
|
||||
</span>
|
||||
<small className="flex-none text-tiny text-muted max-tiny:hidden">流程进度</small>
|
||||
<b className={cn('flex-none text-ui font-extrabold leading-4 tracking-[.3px]', muted && 'text-ink-2')} style={{ color: muted ? undefined : color }}>{pipePct}</b>
|
||||
{pipeCurrent && (
|
||||
<small className={cn('min-w-0 flex-[0_1_auto] truncate text-right leading-4 text-[10.5px] text-faint max-mid:hidden', allDone && 'text-[var(--pipe)]')}>
|
||||
{pipeCurText}
|
||||
</small>
|
||||
)}
|
||||
</span>
|
||||
</NavLink>
|
||||
)
|
||||
}
|
||||
|
||||
export default PipelineConsole
|
||||
|
||||
/**
|
||||
* 侧栏项目名下那一行「当前节点」。
|
||||
* 和顶栏控制台同一口径(lib/pipeline.ts),两处不能各算各的。
|
||||
*/
|
||||
export function useCurrentStageNote(projectId: string): string {
|
||||
const project = useProjectStore((s) => s.project)
|
||||
const workflow = useProjectStore((s) => s.workflow)
|
||||
const proj = projectId && project?.id === Number(projectId) ? project : null
|
||||
if (!proj) return ''
|
||||
return stageNote(proj, workflow && workflow.length ? workflow : proj.workflow)
|
||||
}
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
/**
|
||||
* 左侧导航:全局模块 + 当前项目的 7 个环节。
|
||||
*
|
||||
* · 折叠轨道(≤900px)只留图标:中文标签放不下一行,两行换行会把 nav 撑到
|
||||
* 比视口还高,看起来像「按钮消失」,因此标签交给 title / aria-label。
|
||||
* · 折叠宽度沿用旧样式表里真正生效的那一档(68px / ≤560 66px),
|
||||
* 主内容区宽度是 calc(100% - 同一个数),两处必须一起改。
|
||||
* · sticky top 取 --nex-bar:旧样式表尾部又写了一遍 top:0,
|
||||
* 会把第一个图标藏到顶栏底下,这里统一按顶栏高度让开。
|
||||
*/
|
||||
import type { ReactNode } from 'react'
|
||||
import { NavLink, useLocation } from 'react-router-dom'
|
||||
import { cn } from '../../lib/cn'
|
||||
import { modules } from '../../stores/system'
|
||||
import { useCurrentStageNote } from './PipelineConsole'
|
||||
|
||||
const NAV_ITEM = cn(
|
||||
'flex items-center gap-2.5 rounded-[8px] px-[9px] py-[10px] text-body font-medium text-ink-3 no-underline',
|
||||
'hover:bg-hover hover:text-ink max-nav:justify-center max-nav:gap-0 max-nav:min-h-[38px] max-nav:px-[2px] max-nav:py-[9px] max-nav:text-center'
|
||||
)
|
||||
const NAV_ICON = 'w-[18px] flex-none text-center text-ui text-muted max-nav:w-auto max-nav:text-[16px]'
|
||||
const NAV_LABEL = 'max-nav:hidden'
|
||||
|
||||
function NavItem({ to, icon, label, hint, chosen }: {
|
||||
to: string; icon: ReactNode; label: string; hint?: string; chosen: boolean
|
||||
}) {
|
||||
const text = hint ? `${label}:${hint}` : label
|
||||
return (
|
||||
<NavLink to={to} aria-label={text} title={text}
|
||||
className={cn(NAV_ITEM, chosen && 'bg-active text-accent shadow-[inset_2px_0_0_var(--c-accent)] [&_.navicon]:text-accent')}>
|
||||
<span className={cn(NAV_ICON, 'navicon')}>{icon}</span>
|
||||
<span className={NAV_LABEL}>{label}</span>
|
||||
</NavLink>
|
||||
)
|
||||
}
|
||||
|
||||
export function SideNav({ projectId, projectTitle }: { projectId: string; projectTitle: string }) {
|
||||
const { pathname } = useLocation()
|
||||
const stageNote = projectId ? useCurrentStageNote(projectId) : ''
|
||||
|
||||
return (
|
||||
<aside className={cn(
|
||||
'sticky top-(--nex-bar) flex h-[calc(100vh-var(--nex-bar))] w-[230px] flex-none flex-col overflow-y-auto',
|
||||
'border-r border-emphasis bg-shell px-[14px] py-6 scrollbar-none',
|
||||
'max-nav:w-[68px] max-nav:px-[6px] max-nav:py-4 max-narrow:w-[66px] max-narrow:px-[5px] max-narrow:py-3'
|
||||
)}>
|
||||
<nav className="mb-[18px] flex flex-col gap-[3px] flex-none max-nav:mb-3 max-nav:gap-1.5">
|
||||
<NavItem to="/" icon="⌂" label="项目总览" chosen={pathname === '/'} />
|
||||
<NavItem to="/assets" icon="✧" label="平台资产库" hint="人物 / 场景 / 声线母版" chosen={pathname === '/assets'} />
|
||||
<NavItem to="/models" icon="◫" label="模型管理中心" hint="大模型 / 视频 / 图像 / 声音" chosen={pathname === '/models'} />
|
||||
</nav>
|
||||
|
||||
{projectId && (
|
||||
<>
|
||||
<div className="mt-1.5 border-t border-line-soft px-2 pb-2 pt-4 text-tiny font-bold tracking-[1.2px] text-faint max-nav:hidden">
|
||||
<span className="block truncate">{projectTitle}</span>
|
||||
{stageNote && <small className="mt-[5px] block normal-case tracking-normal font-normal text-dim">{stageNote}</small>}
|
||||
</div>
|
||||
<nav className="flex flex-col gap-[3px] flex-none max-nav:gap-1.5">
|
||||
{modules.map((m) => {
|
||||
const to = m.to(projectId)
|
||||
return <NavItem key={m.label} to={to} icon={m.icon} label={m.label} hint={m.hint} chosen={pathname === to} />
|
||||
})}
|
||||
</nav>
|
||||
</>
|
||||
)}
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
|
||||
export default SideNav
|
||||
|
|
@ -0,0 +1,123 @@
|
|||
/**
|
||||
* 顶栏账号胶囊:头像 + 角色 + 二级菜单(我的账号 / 用户管理 / 退出登录)。
|
||||
*
|
||||
* 环境自检不再常驻一列文字,只在真的有问题时到菜单里冒出来一次。
|
||||
* 换页后菜单里的高亮项、角色都可能变,直接收起最省事。
|
||||
*/
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Link, NavLink, useLocation, useNavigate } from 'react-router-dom'
|
||||
import { cn } from '../../lib/cn'
|
||||
import {
|
||||
logout, roleLabel, useAuthStore, useCanEdit, useDisplayName, useIsAdmin
|
||||
} from '../../stores/auth'
|
||||
import { useSystemStore } from '../../stores/system'
|
||||
import { useOutsideClick } from '../../hooks'
|
||||
|
||||
const ITEM = 'flex min-h-[32px] w-full items-center gap-[9px] rounded-[8px] border border-transparent bg-transparent px-[9px] py-[7px] text-left text-body text-ink-2 no-underline hover:border-line hover:bg-hover hover:text-ink'
|
||||
const ICON = 'w-[15px] flex-none text-center text-body text-muted'
|
||||
|
||||
/** 环境自检结论:有问题才说,没问题时菜单里不占位置 */
|
||||
function envIssueOf(health: any): string {
|
||||
if (!health) return ''
|
||||
if (health.executor === 'celery' && !health.daemon?.running) return '调度守护未运行:新任务会一直排在队列里'
|
||||
if (!health.ffmpeg) return 'ffmpeg 缺失:时间线合成会被阻断'
|
||||
if (health.ffmpeg_capabilities && health.ffmpeg_capabilities.subtitle_burn === false) return 'ffmpeg 缺 libass:字幕将自动转成内嵌轨'
|
||||
return ''
|
||||
}
|
||||
|
||||
export function UserMenu() {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const user = useAuthStore((s) => s.user)
|
||||
const displayName = useDisplayName()
|
||||
const isAdmin = useIsAdmin()
|
||||
const canEdit = useCanEdit()
|
||||
const health = useSystemStore((s) => s.health)
|
||||
const [open, setOpen] = useState(false)
|
||||
const hostRef = useRef<HTMLDivElement | null>(null)
|
||||
const close = useCallback(() => setOpen(false), [])
|
||||
|
||||
useOutsideClick(hostRef, close, open)
|
||||
/* 换页后菜单里的高亮项、角色都可能变,直接收起最省事 */
|
||||
useEffect(close, [location.pathname, close])
|
||||
|
||||
if (!user) return null
|
||||
const mustChangePassword = !!user.must_change_password
|
||||
const initial = (displayName || '?').slice(0, 1).toUpperCase()
|
||||
const envIssue = envIssueOf(health)
|
||||
|
||||
async function signOut() {
|
||||
close()
|
||||
await logout()
|
||||
await navigate({ pathname: '/login', search: '?loggedOut=1' }, { replace: true })
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={hostRef} className="relative flex-none">
|
||||
<button type="button" onClick={() => setOpen(!open)} aria-expanded={open} aria-haspopup="menu"
|
||||
title={'账号菜单 · ' + displayName}
|
||||
className={cn('relative flex h-(--nex-ctl) items-center gap-2 rounded-pill border bg-sunken pl-1 pr-2 text-left text-ink-2 hover:border-line-bright hover:bg-hover hover:text-ink',
|
||||
mustChangePassword ? 'border-warn-line' : 'border-line', open && 'border-line-bright bg-hover text-ink')}>
|
||||
<span aria-hidden="true" className="grid h-[27px] w-[27px] flex-none place-items-center rounded-pill bg-accent-fill text-body font-bold text-on-accent">{initial}</span>
|
||||
<span className="grid max-w-[132px] min-w-0 leading-[1.25] max-narrow:hidden [&_b]:truncate [&_small]:truncate">
|
||||
<b className="text-label">{displayName}</b>
|
||||
<small className="text-tiny text-faint">{roleLabel(user.role)}{user.login_count ? ` · 第 ${user.login_count} 次登录` : ''}</small>
|
||||
</span>
|
||||
<span aria-hidden="true" className="flex-none text-caption text-faint transition-transform duration-[180ms]" style={{ transform: open ? 'rotate(180deg)' : undefined }}>⌄</span>
|
||||
{/* 待改密码的提醒不能只藏在菜单里:胶囊上先挂一个角标。
|
||||
角标挂在胶囊而不是头像上——头像是 27px 的正圆,绝对定位的角标会把
|
||||
它自己的 scrollWidth 撑到 30px(内容没被裁,但等于凭空多出横向溢出)。 */}
|
||||
{mustChangePassword && (
|
||||
<span aria-hidden="true" className="absolute -right-0.5 -top-[3px] grid h-[14px] w-[14px] place-items-center rounded-pill bg-warn-fill text-tiny font-bold text-warn-ink">!</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<div role="menu" className="absolute right-0 top-[calc(100%+8px)] z-70 grid w-[262px] gap-0.5 rounded-block border border-line-strong bg-panel p-[9px] shadow-[0_18px_44px_rgba(0,0,0,.44)]">
|
||||
<div className="flex items-center gap-[9px] border-b border-line-soft px-1 pb-[9px] pt-[3px]">
|
||||
<span aria-hidden="true" className="grid h-[27px] w-[27px] flex-none place-items-center rounded-pill bg-accent-fill text-body font-bold text-on-accent">{initial}</span>
|
||||
<span className="grid min-w-0 gap-0.5">
|
||||
<b className="truncate text-[12.5px]">{displayName}</b>
|
||||
<small className="truncate text-tiny text-faint">{user.username}{user.email ? ` · ${user.email}` : ''}</small>
|
||||
</span>
|
||||
<em className="ml-auto flex-none rounded-pill bg-hover px-[6px] py-0.5 text-tiny not-italic text-ink-2">{roleLabel(user.role)}</em>
|
||||
</div>
|
||||
|
||||
{mustChangePassword && (
|
||||
<p className="m-0 rounded-[8px] bg-warn-tint px-[9px] py-[7px] text-tiny leading-[1.5] text-warn-bright [overflow-wrap:anywhere]">
|
||||
<Link to="/account?must=1" role="menuitem" onClick={close} className="text-inherit underline">初始密码尚未修改,点此设置新密码 →</Link>
|
||||
</p>
|
||||
)}
|
||||
{!canEdit && <p className="m-0 rounded-[8px] bg-hover px-[9px] py-[7px] text-tiny leading-[1.5] text-faint">观摩角色:只读,写操作会被后端拒绝</p>}
|
||||
|
||||
<div role="separator" className="my-[5px] mx-0.5 h-px bg-line-soft"></div>
|
||||
|
||||
<NavLink to="/account" role="menuitem" title="账号信息、修改密码与登录设备" className={ITEM} onClick={close}>
|
||||
<i className={ICON}>◍</i><span>我的账号</span>
|
||||
</NavLink>
|
||||
{isAdmin && (
|
||||
<NavLink to="/users" role="menuitem" title="账号、角色与配额" className={ITEM} onClick={close}>
|
||||
<i className={ICON}>▤</i><span>用户管理</span>
|
||||
</NavLink>
|
||||
)}
|
||||
|
||||
{envIssue && (
|
||||
<>
|
||||
<div role="separator" className="my-[5px] mx-0.5 h-px bg-line-soft"></div>
|
||||
<p className="m-0 rounded-[8px] bg-warn-tint px-[9px] py-[7px] text-tiny leading-[1.5] text-warn-bright [overflow-wrap:anywhere]">{envIssue}</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div role="separator" className="my-[5px] mx-0.5 h-px bg-line-soft"></div>
|
||||
|
||||
<button type="button" role="menuitem" title="退出当前会话" onClick={signOut}
|
||||
className={cn(ITEM, 'text-danger [&_i]:text-danger hover:border-danger-line hover:bg-danger-tint hover:text-danger-bright hover:[&_i]:text-danger-bright')}>
|
||||
<i className={ICON}>⏻</i><span>退出登录</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default UserMenu
|
||||
|
|
@ -0,0 +1,101 @@
|
|||
/**
|
||||
* 路由表。
|
||||
*
|
||||
* 路由级懒加载:以前所有视图静态 import,打开「平台资产库」也要先把
|
||||
* 分镜 / 资产 / 模型中心一整套模块下载并编译完(开发模式首屏 77 个请求 / 4.7MB,
|
||||
* 其中 1.9MB 是这次根本用不到的页面)。现在只保留入口页(项目列表)同步加载,
|
||||
* 其余按路由切分:点进哪个页面才拉哪个页面的 chunk,构建产物也跟着按路由分包。
|
||||
*
|
||||
* 鉴权守卫做在 App 的 <AuthGate> 里(会话状态在 zustand,组件订阅比 loader 更省事),
|
||||
* 这里只声明每条路由的元信息 handle。
|
||||
*/
|
||||
import { lazy } from 'react'
|
||||
import { createBrowserRouter, Navigate } from 'react-router-dom'
|
||||
import App from './App'
|
||||
import Dashboard from '../pages/Dashboard'
|
||||
|
||||
/** 侧栏里一定点得到的相邻页:首屏渲染完在空闲时提前拉好 */
|
||||
const loadAssetLibrary = () => import('../pages/AssetLibrary')
|
||||
const loadModelCenter = () => import('../pages/ModelCenter')
|
||||
const loadProjectDetail = () => import('../pages/ProjectDetail')
|
||||
const loadOverview = () => import('../pages/project/Overview')
|
||||
const loadLibrary = () => import('../pages/project/Library')
|
||||
const loadStoryboard = () => import('../pages/project/Storyboard')
|
||||
const loadDispatch = () => import('../pages/project/Dispatch')
|
||||
const loadReview = () => import('../pages/project/Review')
|
||||
const loadTimeline = () => import('../pages/project/Timeline')
|
||||
const loadDelivery = () => import('../pages/project/Delivery')
|
||||
const loadLogin = () => import('../pages/Login')
|
||||
const loadAccount = () => import('../pages/Account')
|
||||
const loadUserAdmin = () => import('../pages/UserAdmin')
|
||||
|
||||
const AssetLibrary = lazy(loadAssetLibrary)
|
||||
const ModelCenter = lazy(loadModelCenter)
|
||||
const ProjectDetail = lazy(loadProjectDetail)
|
||||
const Overview = lazy(loadOverview)
|
||||
const Library = lazy(loadLibrary)
|
||||
const Storyboard = lazy(loadStoryboard)
|
||||
const Dispatch = lazy(loadDispatch)
|
||||
const Review = lazy(loadReview)
|
||||
const Timeline = lazy(loadTimeline)
|
||||
const Delivery = lazy(loadDelivery)
|
||||
const Login = lazy(loadLogin)
|
||||
const Account = lazy(loadAccount)
|
||||
const UserAdmin = lazy(loadUserAdmin)
|
||||
|
||||
/** 挂在每条路由上的元信息:App 用 useMatches() 读取 */
|
||||
export type RouteHandle = { title?: string; public?: boolean; admin?: boolean }
|
||||
|
||||
const withHandle = (title: string, extra: RouteHandle = {}): RouteHandle => ({ title, ...extra })
|
||||
|
||||
export const router = createBrowserRouter([
|
||||
{
|
||||
path: '/',
|
||||
element: <App />,
|
||||
children: [
|
||||
{ index: true, element: <Dashboard />, handle: withHandle('项目') },
|
||||
{ path: 'assets', element: <AssetLibrary />, handle: withHandle('平台资产库') },
|
||||
{ path: 'models', element: <ModelCenter />, handle: withHandle('模型管理中心') },
|
||||
{
|
||||
path: 'projects/:id',
|
||||
element: <ProjectDetail />,
|
||||
handle: withHandle('项目工作台'),
|
||||
children: [
|
||||
{ index: true, element: <Navigate to="overview" replace /> },
|
||||
{ path: 'overview', element: <Overview />, handle: withHandle('流程概览') },
|
||||
{ path: 'library', element: <Library />, handle: withHandle('资产管理') },
|
||||
{ path: 'storyboard', element: <Storyboard />, handle: withHandle('分镜与脚本') },
|
||||
{ path: 'dispatch', element: <Dispatch />, handle: withHandle('调度中心') },
|
||||
{ path: 'review', element: <Review />, handle: withHandle('质检与审核') },
|
||||
{ path: 'timeline', element: <Timeline />, handle: withHandle('时间线合成') },
|
||||
{ path: 'delivery', element: <Delivery />, handle: withHandle('导出与成本') }
|
||||
]
|
||||
},
|
||||
{ path: 'login', element: <Login />, handle: withHandle('登录', { public: true }) },
|
||||
{ path: 'account', element: <Account />, handle: withHandle('我的账号') },
|
||||
{ path: 'users', element: <UserAdmin />, handle: withHandle('用户管理', { admin: true }) },
|
||||
{ path: '*', element: <Navigate to="/" replace /> }
|
||||
]
|
||||
}
|
||||
])
|
||||
|
||||
/**
|
||||
* 空闲预取:首屏渲染完成后,把「侧边栏里一定能点到」的相邻页面 chunk 提前拉好,
|
||||
* 这样懒加载不会让用户在真正切换时等一次网络往返。
|
||||
* 只在浏览器空闲时做,绝不和首屏的图片/接口抢带宽。
|
||||
*/
|
||||
let warmed = false
|
||||
export function warmupRoutes() {
|
||||
if (warmed) return
|
||||
warmed = true
|
||||
const run = () => {
|
||||
loadAssetLibrary().catch(() => undefined)
|
||||
loadModelCenter().catch(() => undefined)
|
||||
loadProjectDetail().catch(() => undefined)
|
||||
}
|
||||
const w = window as any
|
||||
if (typeof w.requestIdleCallback === 'function') w.requestIdleCallback(run, { timeout: 4000 })
|
||||
else window.setTimeout(run, 1500)
|
||||
}
|
||||
|
||||
export default router
|
||||
|
|
@ -1,120 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* 全站统一的音频控件(替代散落在 4 个页面里的原生 <audio controls>)。
|
||||
* 共用 media.ts 里的单例音频引擎:在任何页面点播放,上一段都会自动停下。
|
||||
*/
|
||||
import { computed } from 'vue'
|
||||
import { audioEngine, isPlaying, pauseAudio, playAudio, seekAudio } from '../media'
|
||||
import { fmtMs } from '../format'
|
||||
import { openMedia } from '../preview'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
src: string
|
||||
label?: string
|
||||
durationMs?: number | null
|
||||
hint?: string
|
||||
size?: 'sm' | 'md'
|
||||
/** 单行紧凑模式:窄容器(列表行的素材区)里只留播放键 + 进度条 + 时长。
|
||||
* 否则名称和时间会被挤成两三行,溢出边框压到下一行的控件上。 */
|
||||
compact?: boolean
|
||||
cover?: boolean
|
||||
}>(), {
|
||||
label: '', durationMs: null, hint: '', size: 'md', compact: false, cover: true
|
||||
})
|
||||
|
||||
const active = computed(() => !!props.src && audioEngine.src === props.src)
|
||||
const playing = computed(() => isPlaying(props.src))
|
||||
const total = computed(() => (active.value && audioEngine.duration ? audioEngine.duration * 1000
|
||||
: Number(props.durationMs || 0)))
|
||||
const progress = computed(() => {
|
||||
if (!active.value || !total.value) return 0
|
||||
return Math.min(100, (audioEngine.position * 1000 / total.value) * 100)
|
||||
})
|
||||
|
||||
function toggle() {
|
||||
if (!props.src) return
|
||||
if (playing.value) pauseAudio()
|
||||
else playAudio(props.src, props.label || '音频')
|
||||
}
|
||||
|
||||
function onScrub(event: MouseEvent) {
|
||||
if (!props.src) return
|
||||
const box = (event.currentTarget as HTMLElement).getBoundingClientRect()
|
||||
const ratio = Math.min(1, Math.max(0, (event.clientX - box.left) / box.width))
|
||||
if (!active.value) playAudio(props.src, props.label || '音频')
|
||||
seekAudio((total.value / 1000) * ratio)
|
||||
}
|
||||
|
||||
function open() {
|
||||
openMedia({ url: props.src, kind: 'audio', name: props.label || '音频' })
|
||||
}
|
||||
|
||||
const fullTime = computed(() =>
|
||||
`${active.value ? fmtMs(audioEngine.position * 1000) : '00:00.00'} / ${total.value ? fmtMs(total.value) : '—'}`)
|
||||
/** 紧凑模式(列表行)里「00:00.00 / 00:05.08」会把进度条挤成一条缝:
|
||||
* 没在放就只显示时长,播起来才显示进度,窄容器里也留得下可拖的进度条。 */
|
||||
const timeText = computed(() => (props.compact && !active.value
|
||||
? (total.value ? fmtMs(total.value) : '—')
|
||||
: fullTime.value))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="aplay" :class="[size, { on: active, compact }]" v-if="src">
|
||||
<button class="btn" :class="{ spin: playing }" @click.stop="toggle"
|
||||
:aria-label="(playing ? '暂停' : '播放') + (label || '音频')"
|
||||
:title="(playing ? '暂停' : '播放') + '(全站同时只播一条)'">
|
||||
{{ playing ? '❚❚' : '▶' }}
|
||||
</button>
|
||||
<div class="mid">
|
||||
<p v-if="!compact" class="name" :title="label || src">{{ label || '音频' }}</p>
|
||||
<div class="line">
|
||||
<div class="track" @click.stop="onScrub" role="slider" :aria-label="(label || '音频') + ' 播放进度'"
|
||||
:aria-valuenow="Math.round(progress)">
|
||||
<i :style="{ width: progress + '%' }"></i>
|
||||
</div>
|
||||
<span v-if="compact" class="mono time" :title="fullTime">{{ timeText }}</span>
|
||||
</div>
|
||||
<p v-if="!compact" class="ap-sub">
|
||||
<span class="mono">{{ timeText }}</span>
|
||||
<span v-if="hint" class="hint" :title="hint">{{ hint }}</span>
|
||||
</p>
|
||||
</div>
|
||||
<button v-if="cover" class="cover" @click.stop="open" title="在统一预览器中打开">⤢</button>
|
||||
</div>
|
||||
<span v-else class="aplay-none">无音频</span>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.aplay {
|
||||
display: flex; align-items: center; gap: 10px; padding: 8px 10px; min-width: 0;
|
||||
border: 1px solid var(--c-line); border-radius: 9px; background: var(--c-bg-sunken);
|
||||
transition: border-color .15s ease, background .15s ease;
|
||||
}
|
||||
.aplay:hover { border-color: var(--c-line-bright); background: var(--c-bg-hover) }
|
||||
.aplay.on { border-color: var(--c-accent-line); background: var(--c-accent-tint) }
|
||||
.aplay.sm { padding: 5px 8px; gap: 8px }
|
||||
.btn {
|
||||
display: grid; place-items: center; width: 28px; height: 28px; flex: 0 0 auto; border: 0;
|
||||
border-radius: 50%; background: var(--c-accent-fill); color: var(--c-on-accent);
|
||||
font-size: 10px; font-weight: 700;
|
||||
}
|
||||
.sm .btn { width: 22px; height: 22px; font-size: 10px }
|
||||
.btn:hover { background: var(--c-accent-fill-deep) }
|
||||
.mid { flex: 1; min-width: 0; overflow: hidden }
|
||||
.line { display: flex; align-items: center; gap: 7px; min-width: 0; overflow: hidden }
|
||||
.time { flex: 0 0 auto; font-size: 10px; color: var(--c-text-faint); white-space: nowrap; font-variant-numeric: tabular-nums }
|
||||
.aplay.compact { padding: 4px 7px; gap: 7px }
|
||||
.compact .btn { width: 20px; height: 20px; font-size: 10px }
|
||||
.compact .cover { width: 18px; height: 18px; font-size: 10px }
|
||||
.name { margin: 0; font-size: 11px; font-weight: 600; color: var(--c-text-2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis }
|
||||
.track { position: relative; flex: 1 1 auto; min-width: 24px; height: 5px; margin: 5px 0 4px; border-radius: 99px; background: var(--c-bg-active); cursor: pointer }
|
||||
.compact .track { margin: 0 }
|
||||
.track i { position: absolute; left: 0; top: 0; height: 100%; border-radius: 99px; background: var(--c-accent-fill) }
|
||||
.track:hover { background: var(--c-line-strong) }
|
||||
.ap-sub { margin: 0; padding: 0; border-top: 0; display: flex; gap: 8px; align-items: center; font-size: 10px; color: var(--c-text-faint); min-width: 0; white-space: nowrap }
|
||||
.ap-sub .mono { flex: 0 0 auto; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-variant-numeric: tabular-nums; white-space: nowrap }
|
||||
.ap-sub .hint { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap }
|
||||
.cover { flex: 0 0 auto; width: 22px; height: 22px; border: 1px solid var(--c-line-strong); border-radius: 6px; background: transparent; color: var(--c-text-3); font-size: 10px }
|
||||
.cover:hover { border-color: var(--c-accent-line); color: var(--c-accent-bright) }
|
||||
.aplay-none { font-size: 10.5px; color: var(--c-text-faint) }
|
||||
</style>
|
||||
|
|
@ -1,62 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* 全站统一的自动刷新驱动器 —— **它不渲染任何界面**。
|
||||
*
|
||||
* 这个位置先后有过三代形态:
|
||||
* 1. 「☑ 自动刷新」+「↻ 刷新」两个控件:默认不勾,出片时用户得自己盯着手动点;
|
||||
* 2. 去掉开关与按钮,只留「最近刷新 hh:mm:ss」;
|
||||
* 3. 现在:连时间戳也撤掉。数据到点自己刷新是平台的责任,不需要用户在每个页面
|
||||
* 页头读一行时钟来确认数据新不新,于是本组件只剩轮询逻辑本身。
|
||||
*
|
||||
* 用法:把刷新周期与「该不该跳过这一轮」交给它,它在 `@refresh` 里喊父组件重新拉数。
|
||||
* · `every` —— 轮询周期(毫秒);由别处(如项目 store 每 6 秒)负责刷新的页面不挂本组件;
|
||||
* · `busy` —— 正在请求 / 正在生成时跳过本轮,不抢占;
|
||||
* · `paused` —— 表单抽屉、确认弹窗里有没保存的内容时跳过本轮;
|
||||
* · 标签页切到后台不发请求;切回来发现已经过期一个周期,立刻补一次。
|
||||
*/
|
||||
import { onBeforeUnmount, onMounted, watch } from 'vue'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
busy?: boolean
|
||||
/** 自动刷新周期(毫秒) */
|
||||
every?: number
|
||||
/** 页面有未保存的表单 / 弹窗时暂停轮询 */
|
||||
paused?: boolean
|
||||
}>(), { busy: false, every: 15000, paused: false })
|
||||
const emit = defineEmits<{ (e: 'refresh'): void }>()
|
||||
|
||||
let timer: number | undefined
|
||||
let lastAttempt = 0
|
||||
|
||||
function tick() {
|
||||
if (props.busy || props.paused || !props.every || document.hidden) return
|
||||
lastAttempt = Date.now()
|
||||
emit('refresh')
|
||||
}
|
||||
|
||||
function onVisible() {
|
||||
if (document.hidden) return
|
||||
// 回到前台:数据已经过期一个周期以上就马上补一次,不等下一个 interval
|
||||
if (Date.now() - lastAttempt >= props.every) tick()
|
||||
}
|
||||
|
||||
// every 可以是算式(例如交付页「导出中 4 秒、空闲 15 秒」),变了就换定时器
|
||||
function rearm() {
|
||||
if (timer) { window.clearInterval(timer); timer = undefined }
|
||||
if (props.every) timer = window.setInterval(tick, props.every)
|
||||
}
|
||||
watch(() => props.every, rearm)
|
||||
|
||||
onMounted(() => {
|
||||
// 挂载前父组件已经拉过首屏,别在切回标签页的瞬间再补一次重复请求
|
||||
lastAttempt = Date.now()
|
||||
rearm()
|
||||
document.addEventListener('visibilitychange', onVisible)
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
if (timer) window.clearInterval(timer)
|
||||
document.removeEventListener('visibilitychange', onVisible)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template><!-- 无界面:只负责按周期发出 refresh 事件 --></template>
|
||||
|
|
@ -1,38 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* 全站唯一的「显示 / 隐藏密码」图标。
|
||||
*
|
||||
* 之前每处密码框自己画一份 SVG,样式和状态都各写各的(有的还是「显示 / 隐藏」文字按钮,
|
||||
* 用户看不出那是个开关)。这里统一成三态图标:读取中(转圈)/ 正在显示(斜线眼)/ 已隐藏(睁眼),
|
||||
* SecretInput(输入框内)与模型管理卡片(掩码行)共用,保证外观与手感完全一致。
|
||||
*/
|
||||
withDefaults(defineProps<{ shown?: boolean; loading?: boolean }>(), {
|
||||
shown: false, loading: false,
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<svg v-if="loading" class="spin" viewBox="0 0 24 24" width="15" height="15" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true">
|
||||
<path d="M21 12a9 9 0 1 1-9-9" />
|
||||
</svg>
|
||||
<svg v-else-if="shown" viewBox="0 0 24 24" width="15" height="15" fill="none"
|
||||
stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<path d="M3 3l18 18" />
|
||||
<path d="M10.6 5.2A9.9 9.9 0 0 1 12 5c5 0 9 4.5 10 7-.4 1-1.6 3-3.5 4.6" />
|
||||
<path d="M6.3 7.1C4.2 8.6 2.8 10.8 2 12c1 2.5 5 7 10 7 1.6 0 3-.4 4.3-1.1" />
|
||||
<path d="M9.9 9.9a3 3 0 0 0 4.2 4.2" />
|
||||
</svg>
|
||||
<svg v-else viewBox="0 0 24 24" width="15" height="15" fill="none"
|
||||
stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<path d="M2 12c1-2.5 5-7 10-7s9 4.5 10 7c-1 2.5-5 7-10 7S3 14.5 2 12z" />
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 读取明文时的转圈:动画跟图标放在一起,父组件不需要再复制一份 keyframes */
|
||||
.spin { animation: eye-spin .8s linear infinite; transform-origin: 50% 50%; }
|
||||
@keyframes eye-spin { to { transform: rotate(360deg) } }
|
||||
@media (prefers-reduced-motion: reduce) { .spin { animation-duration: 1.8s } }
|
||||
</style>
|
||||
|
|
@ -1,379 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* 全站统一「多选下拉」控件(替代原生 <select multiple> 的系统列表外观)。
|
||||
*
|
||||
* 与 FSelect 同一套做法:内部保留一个**隐藏的** <select multiple> 承载选项与
|
||||
* v-model / :value 语义,可见部分为自绘触发器 + Teleport 弹层(复选列表)。
|
||||
* 因此调用点只需换标签,原有 @change="fn($event)" 里读 event.target.selectedOptions
|
||||
* 的写法依旧可用——change 事件由隐藏 select 发出并冒泡到根节点。
|
||||
*/
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, useId, watch } from 'vue'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue?: any[]
|
||||
disabled?: boolean
|
||||
ariaLabel?: string
|
||||
placeholder?: string
|
||||
/** 选项超过该数量时自动显示过滤框 */
|
||||
searchThreshold?: number
|
||||
size?: 'sm' | 'md'
|
||||
}>(), {
|
||||
modelValue: () => [], disabled: false, ariaLabel: '', placeholder: '未选择',
|
||||
searchThreshold: 7, size: 'md'
|
||||
})
|
||||
const emit = defineEmits<{ (e: 'update:modelValue', value: any[]): void }>()
|
||||
|
||||
/** 绑给隐藏 select;Vue 的 vModelSelect 负责数组 ↔ selected 的映射 */
|
||||
const inner = computed({
|
||||
get: () => (Array.isArray(props.modelValue) ? props.modelValue : []),
|
||||
set: (v: any[]) => emit('update:modelValue', v)
|
||||
})
|
||||
|
||||
type Row = { text: string; disabled: boolean; selected: boolean }
|
||||
const native = ref<HTMLSelectElement | null>(null)
|
||||
const triggerEl = ref<HTMLButtonElement | null>(null)
|
||||
const popEl = ref<HTMLDivElement | null>(null)
|
||||
const listEl = ref<HTMLDivElement | null>(null)
|
||||
const searchEl = ref<HTMLInputElement | null>(null)
|
||||
|
||||
const uid = useId()
|
||||
const open = ref(false)
|
||||
const rows = ref<Row[]>([])
|
||||
const query = ref('')
|
||||
const active = ref(-1)
|
||||
const shown = ref('')
|
||||
const count = ref(0)
|
||||
const pop = ref({ left: 0, top: 0, width: 0, drop: true, maxH: 264 })
|
||||
|
||||
/** 过滤后的可见行(保留原始下标,操作时直接映射回 option) */
|
||||
const view = computed(() => {
|
||||
const q = query.value.trim().toLowerCase()
|
||||
return rows.value
|
||||
.map((r, i) => ({ r, i }))
|
||||
.filter((x) => !q || x.r.text.toLowerCase().includes(q))
|
||||
})
|
||||
const selectableInView = computed(() => view.value.filter((x) => !x.r.disabled).length)
|
||||
|
||||
let observer: MutationObserver | null = null
|
||||
let lastSig = ''
|
||||
let scheduled = 0
|
||||
|
||||
function snapshot(): boolean {
|
||||
const el = native.value
|
||||
if (!el) return false
|
||||
const list: Row[] = Array.from(el.options).map((o) => ({
|
||||
text: (o.textContent || '').replace(/\s+/g, ' ').trim() || o.value,
|
||||
disabled: o.disabled || !!o.parentElement?.hasAttribute('disabled'),
|
||||
selected: o.selected
|
||||
}))
|
||||
// 选项来自父级插槽:无条件写回会形成 MutationObserver → 重渲染 死循环,用签名去重。
|
||||
const sig = list.map((r) => (r.disabled ? '1' : '0') + (r.selected ? 's' : '-') + r.text).join('\u0001')
|
||||
if (sig === lastSig) return false
|
||||
lastSig = sig
|
||||
rows.value = list
|
||||
const picked = list.filter((r) => r.selected).map((r) => r.text)
|
||||
count.value = picked.length
|
||||
if (!picked.length) shown.value = ''
|
||||
else {
|
||||
const joined = picked.join('、')
|
||||
shown.value = joined.length <= 30 ? joined : `${picked[0]} 等 ${picked.length} 项`
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function observe() {
|
||||
observer?.disconnect()
|
||||
if (scheduled) window.clearTimeout(scheduled)
|
||||
const el = native.value
|
||||
if (!el) return
|
||||
observer = new MutationObserver(() => {
|
||||
if (scheduled) return
|
||||
scheduled = window.setTimeout(() => {
|
||||
scheduled = 0
|
||||
if (snapshot() && open.value) place()
|
||||
}, 0)
|
||||
})
|
||||
observer.observe(el, { childList: true, subtree: true, characterData: true, attributes: true })
|
||||
}
|
||||
|
||||
let measureCtx: CanvasRenderingContext2D | null = null
|
||||
function contentWidth() {
|
||||
if (!measureCtx) measureCtx = document.createElement('canvas').getContext('2d')
|
||||
if (!measureCtx) return 0
|
||||
measureCtx.font = '12px "DM Sans", "Noto Sans SC", system-ui, sans-serif'
|
||||
let max = 0
|
||||
for (const r of rows.value) max = Math.max(max, measureCtx.measureText(r.text).width)
|
||||
return Math.ceil(max) + 62
|
||||
}
|
||||
|
||||
function place() {
|
||||
const el = triggerEl.value
|
||||
if (!el) return
|
||||
const r = el.getBoundingClientRect()
|
||||
const avail = Math.max(160, innerWidth - 24)
|
||||
const width = Math.min(Math.max(Math.max(r.width, contentWidth()), Math.min(190, avail)), 440, avail)
|
||||
const below = innerHeight - r.bottom - 14
|
||||
const above = r.top - 14
|
||||
const drop = below >= 210 || below >= above
|
||||
pop.value = {
|
||||
left: Math.min(Math.max(8, r.left), Math.max(8, innerWidth - width - 8)),
|
||||
top: drop ? r.bottom + 6 : r.top - 6,
|
||||
width,
|
||||
drop,
|
||||
maxH: Math.max(150, Math.min(320, drop ? below : above))
|
||||
}
|
||||
}
|
||||
|
||||
/** 弹层高度要渲染后才知道:按真实 rect 纠正,必要时翻边/贴边 */
|
||||
function clampToViewport() {
|
||||
const el = popEl.value
|
||||
if (!el) return
|
||||
const rect = el.getBoundingClientRect()
|
||||
const trig = triggerEl.value?.getBoundingClientRect()
|
||||
let { top } = pop.value
|
||||
if (rect.bottom > innerHeight - 8 || rect.top < 8) {
|
||||
const h = rect.height
|
||||
if (pop.value.drop && innerHeight - (trig ? trig.bottom + 6 : rect.bottom) < h && (trig ? trig.top - 14 : 0) > h) {
|
||||
top = (trig?.top ?? rect.top) - 6
|
||||
pop.value = { ...pop.value, drop: false }
|
||||
} else if (!pop.value.drop && rect.top < 8) top = (trig?.bottom ?? rect.bottom) + 6
|
||||
if (top + h > innerHeight - 8) top = innerHeight - 8 - h
|
||||
if (top < 8) top = 8
|
||||
pop.value = { ...pop.value, top }
|
||||
}
|
||||
}
|
||||
|
||||
function scrollActiveIntoView() {
|
||||
listEl.value?.querySelector<HTMLElement>('[data-act="1"]')?.scrollIntoView({ block: 'nearest' })
|
||||
}
|
||||
|
||||
/** 原生 select 是写入的唯一入口:改 selected 后派发 input/change,Vue 与父级 @change 都能收到 */
|
||||
function commit() {
|
||||
const el = native.value
|
||||
if (!el) return
|
||||
el.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
el.dispatchEvent(new Event('change', { bubbles: true }))
|
||||
nextTick(() => { snapshot(); if (open.value) place() })
|
||||
}
|
||||
|
||||
function toggleIndex(i: number) {
|
||||
const el = native.value
|
||||
const opt = el?.options[i]
|
||||
if (!el || !opt || opt.disabled) return
|
||||
opt.selected = !opt.selected
|
||||
commit()
|
||||
}
|
||||
|
||||
function setInView(selected: boolean) {
|
||||
const el = native.value
|
||||
if (!el) return
|
||||
let changed = false
|
||||
for (const x of view.value) {
|
||||
if (x.r.disabled || x.r.selected === selected) continue
|
||||
el.options[x.i].selected = selected
|
||||
changed = true
|
||||
}
|
||||
if (changed) commit()
|
||||
}
|
||||
|
||||
async function toggle(force?: boolean) {
|
||||
if (props.disabled) return
|
||||
open.value = force ?? !open.value
|
||||
if (!open.value) { query.value = ''; return }
|
||||
snapshot()
|
||||
place()
|
||||
await nextTick()
|
||||
const first = view.value.findIndex((x) => x.r.selected)
|
||||
const fallback = view.value.findIndex((x) => !x.r.disabled)
|
||||
active.value = first >= 0 ? first : fallback
|
||||
clampToViewport()
|
||||
scrollActiveIntoView()
|
||||
if (props.searchThreshold > 0 && rows.value.length > props.searchThreshold) searchEl.value?.focus()
|
||||
else triggerEl.value?.focus({ preventScroll: true })
|
||||
}
|
||||
|
||||
function onSearchKeydown(e: KeyboardEvent) {
|
||||
// 输入框自己消化这些键,否则冒泡到弹层的 @keydown 会二次执行(方向键走两格、回车来回切换)
|
||||
if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(e.key)) { e.preventDefault(); e.stopPropagation(); move(e.key) }
|
||||
else if (e.key === 'Enter') {
|
||||
e.preventDefault(); e.stopPropagation()
|
||||
if (active.value >= 0) toggleIndex(active.value)
|
||||
} else if (e.key === 'Escape') {
|
||||
e.stopPropagation(); void toggle(false); triggerEl.value?.focus({ preventScroll: true })
|
||||
}
|
||||
}
|
||||
|
||||
function move(key: string) {
|
||||
const list = view.value
|
||||
if (!list.length) return
|
||||
let pos = list.findIndex((x) => x.i === active.value)
|
||||
const step = (delta: number) => {
|
||||
for (let n = 0; n < list.length; n++) {
|
||||
pos = (pos + delta + list.length) % list.length
|
||||
if (!list[pos].r.disabled) return
|
||||
}
|
||||
}
|
||||
if (key === 'ArrowDown') step(1)
|
||||
else if (key === 'ArrowUp') step(-1)
|
||||
else if (key === 'Home') pos = 0
|
||||
else if (key === 'End') pos = list.length - 1
|
||||
active.value = list[pos]?.i ?? -1
|
||||
nextTick(scrollActiveIntoView)
|
||||
}
|
||||
|
||||
function onKeydown(e: KeyboardEvent) {
|
||||
// 过滤输入框的按键由 onSearchKeydown 处理,避免双份响应
|
||||
if ((e.target as HTMLElement | null)?.tagName === 'INPUT') return
|
||||
if (e.key === 'Escape') {
|
||||
if (open.value) { e.preventDefault(); e.stopPropagation(); void toggle(false) }
|
||||
return
|
||||
}
|
||||
if (e.key === 'Tab') { open.value = false; return }
|
||||
if (['ArrowDown', 'ArrowUp'].includes(e.key)) {
|
||||
e.preventDefault()
|
||||
if (!open.value) { void toggle(true); return }
|
||||
move(e.key === 'ArrowDown' ? 'ArrowDown' : 'ArrowUp')
|
||||
return
|
||||
}
|
||||
if (['Enter', ' ', 'Spacebar'].includes(e.key)) {
|
||||
e.preventDefault()
|
||||
if (open.value) { if (active.value >= 0) toggleIndex(active.value) } else void toggle(true)
|
||||
}
|
||||
}
|
||||
|
||||
function onPointerDown(e: PointerEvent) {
|
||||
if (!open.value) return
|
||||
const t = e.target as Node
|
||||
if (triggerEl.value?.contains(t) || popEl.value?.contains(t)) return
|
||||
void toggle(false)
|
||||
}
|
||||
|
||||
function reposition() { if (open.value) place() }
|
||||
|
||||
onMounted(() => {
|
||||
snapshot()
|
||||
observe()
|
||||
document.addEventListener('pointerdown', onPointerDown, true)
|
||||
window.addEventListener('resize', reposition)
|
||||
window.addEventListener('scroll', reposition, true)
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
observer?.disconnect()
|
||||
document.removeEventListener('pointerdown', onPointerDown, true)
|
||||
window.removeEventListener('resize', reposition)
|
||||
window.removeEventListener('scroll', reposition, true)
|
||||
})
|
||||
watch(() => props.modelValue, () => { nextTick(() => snapshot()) })
|
||||
watch(() => props.disabled, (v) => { if (v) open.value = false })
|
||||
watch(query, () => { active.value = view.value.find((x) => !x.r.disabled)?.i ?? -1; nextTick(scrollActiveIntoView) })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span class="fselect fmulti" :class="['s-' + size, { open, disabled: !!disabled }]">
|
||||
<select ref="native" v-model="inner" multiple class="fselect-native" :disabled="disabled" tabindex="-1"
|
||||
aria-hidden="true"><slot /></select>
|
||||
|
||||
<button ref="triggerEl" type="button" class="fselect-trigger" :disabled="disabled"
|
||||
:aria-label="ariaLabel || undefined" aria-haspopup="listbox" :aria-expanded="open ? 'true' : 'false'"
|
||||
:aria-activedescendant="open && active >= 0 ? uid + '-o' + active : undefined"
|
||||
@click="toggle()" @keydown="onKeydown">
|
||||
<span v-if="count" class="fmulti-count">{{ count }}</span>
|
||||
<span class="fselect-text" :class="{ ph: !shown }">{{ shown || placeholder }}</span>
|
||||
<svg class="fselect-caret" :class="{ up: open }" viewBox="0 0 20 20" aria-hidden="true">
|
||||
<path d="M5.5 7.5 10 12l4.5-4.5" fill="none" stroke="currentColor" stroke-width="1.7"
|
||||
stroke-linecap="round" stroke-linejoin="round" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<Teleport to="body">
|
||||
<div v-if="open" ref="popEl" class="fselect-pop fmulti-pop"
|
||||
:style="{ left: pop.left + 'px', top: pop.top + 'px', width: pop.width + 'px',
|
||||
maxHeight: pop.maxH + 'px', transform: pop.drop ? 'none' : 'translateY(-100%)' }"
|
||||
role="listbox" aria-multiselectable="true" :aria-label="ariaLabel || undefined"
|
||||
@mousedown.stop @keydown="onKeydown">
|
||||
<div class="fmulti-bar">
|
||||
<input v-if="rows.length > searchThreshold" ref="searchEl" v-model="query" class="fmulti-search"
|
||||
type="search" placeholder="过滤选项…" :aria-label="(ariaLabel || '选项') + ':过滤'"
|
||||
@keydown="onSearchKeydown" />
|
||||
<span class="fmulti-tally">{{ count ? `已选 ${count} 项` : '未选择' }}</span>
|
||||
<button type="button" class="fmulti-act" :disabled="!selectableInView" @click="setInView(true)">全选</button>
|
||||
<button type="button" class="fmulti-act" :disabled="!count" @click="setInView(false)">清空</button>
|
||||
</div>
|
||||
<div ref="listEl" class="fselect-list">
|
||||
<div v-for="(x, n) in view" :key="x.i" :id="uid + '-o' + x.i" class="fselect-item fmulti-item"
|
||||
:class="{ on: x.r.selected, act: x.i === active, off: x.r.disabled }"
|
||||
:data-act="x.i === active ? '1' : '0'" role="option" :aria-selected="x.r.selected ? 'true' : 'false'"
|
||||
@mouseenter="active = x.i" @click="toggleIndex(x.i)">
|
||||
<span class="fmulti-box" :class="{ on: x.r.selected }" aria-hidden="true">
|
||||
<svg v-if="x.r.selected" viewBox="0 0 12 12"><path d="M2.6 6.3 4.9 8.6 9.4 3.7" fill="none"
|
||||
stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" /></svg>
|
||||
</span>
|
||||
<span class="txt">{{ x.r.text }}</span>
|
||||
</div>
|
||||
<div v-if="!view.length" class="fselect-none">{{ rows.length ? '没有匹配的选项' : '无可选项' }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
/* 多选下拉:复用 FSelect 的视觉语言(触发器 + Teleport 弹层),
|
||||
因为 FSelect 的触发器样式是 scoped 的,这里在 .fmulti 作用域内自带一份。 */
|
||||
.fmulti .fselect-native {
|
||||
position: absolute; inset: 0; width: 100%; height: 100%; margin: 0; padding: 0;
|
||||
border: 0; background: none; opacity: 0; pointer-events: none; appearance: none; font-size: 16px
|
||||
}
|
||||
.fmulti .fselect-trigger {
|
||||
appearance: none; -webkit-appearance: none;
|
||||
display: flex; align-items: center; gap: 8px; width: 100%; min-width: 0;
|
||||
/* 高度由全局 --ctl-h 决定(见 style.css 控件高度体系),纵向 padding 归零,
|
||||
这样同一个视觉行里的下拉与输入框/按钮严格等高、中心线一致。 */
|
||||
height: var(--ctl-h); padding: 0 10px; border-radius: 7px; text-align: left;
|
||||
border: 1px solid var(--c-line-strong); background: var(--c-bg-input); color: var(--c-text);
|
||||
font-size: 12px; line-height: 1.35; transition: border-color .14s, background .14s, box-shadow .14s
|
||||
}
|
||||
.fmulti.s-sm .fselect-trigger { padding-inline: 8px; font-size: 11px; border-radius: 6px }
|
||||
.fmulti .fselect-text { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap }
|
||||
.fmulti .fselect-text.ph { color: var(--c-text-faint) }
|
||||
.fmulti .fselect-caret { flex: 0 0 auto; width: 15px; height: 15px; color: var(--c-text-muted); transition: transform .16s, color .14s }
|
||||
.fmulti .fselect-caret.up { transform: rotate(180deg); color: var(--c-accent-bright) }
|
||||
.fmulti .fselect-trigger:hover:not(:disabled) { border-color: var(--c-line-bright); background: var(--c-bg-hover) }
|
||||
.fmulti.open .fselect-trigger, .fmulti .fselect-trigger:focus-visible {
|
||||
outline: none; border-color: var(--c-accent-deep); box-shadow: 0 0 0 3px var(--c-accent-tint)
|
||||
}
|
||||
.fmulti.disabled { opacity: .5 }
|
||||
.fmulti .fselect-trigger:disabled { cursor: not-allowed }
|
||||
.fmulti-count {
|
||||
flex: 0 0 auto; min-width: 17px; height: 17px; padding: 0 5px; border-radius: 9px;
|
||||
display: grid; place-items: center; background: var(--c-accent-fill); color: var(--c-on-accent);
|
||||
font-size: 10px; font-weight: 700; line-height: 1
|
||||
}
|
||||
|
||||
/* 弹层 Teleport 到 body → 必须全局样式 */
|
||||
.fmulti-pop { flex-direction: column }
|
||||
.fmulti-bar {
|
||||
flex: 0 0 auto; display: flex; align-items: center; gap: 6px; padding: 7px 8px;
|
||||
border-bottom: 1px solid var(--c-line); background: var(--c-bg-raise)
|
||||
}
|
||||
.fmulti-search {
|
||||
flex: 1 1 auto; min-width: 0; padding: 5px 8px; font-size: 11px; border-radius: 6px;
|
||||
border: 1px solid var(--c-line-strong); background: var(--c-bg-input); color: var(--c-text)
|
||||
}
|
||||
.fmulti-search:focus { outline: none; border-color: var(--c-accent-deep) }
|
||||
.fmulti-search::-webkit-search-cancel-button { -webkit-appearance: none }
|
||||
.fmulti-tally { flex: 0 0 auto; font-size: 10px; color: var(--c-text-faint) }
|
||||
.fmulti-act {
|
||||
flex: 0 0 auto; padding: 4px 7px; border-radius: 6px; font-size: 10px;
|
||||
border: 1px solid var(--c-line-strong); background: var(--c-bg-hover); color: var(--c-text-2)
|
||||
}
|
||||
.fmulti-act:hover:not(:disabled) { border-color: var(--c-line-bright); color: var(--c-text) }
|
||||
.fmulti-act:disabled { opacity: .4; cursor: not-allowed }
|
||||
.fmulti-box {
|
||||
flex: 0 0 14px; width: 14px; height: 14px; margin-top: 1px; border-radius: 4px;
|
||||
display: grid; place-items: center; border: 1px solid var(--c-line-bright); color: var(--c-on-accent)
|
||||
}
|
||||
.fmulti-box svg { width: 11px; height: 11px }
|
||||
.fmulti-box.on { background: var(--c-accent-fill); border-color: var(--c-accent-fill) }
|
||||
.fselect-item.fmulti-item.on { color: var(--c-text) }
|
||||
</style>
|
||||
|
|
@ -1,392 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* 全站统一下拉控件(替代原生 <select> 的系统外观)。
|
||||
*
|
||||
* 做法:内部保留一个**隐藏的** <select> 作为「唯一数据源」——选项、disabled、
|
||||
* v-model 语义(含 :value="null"、数字值、对象值)全部沿用 Vue 的原生指令,
|
||||
* 可见部分则是自绘的触发器 + Teleport 弹层,因此:
|
||||
* · 现有 71 处调用只需把标签换成 <FSelect>,v-model / @change="fn($event)" 不用改;
|
||||
* · 弹层挂到 body,抽屉/滚动容器不会裁切它,深浅主题一致;
|
||||
* · 键盘(↑↓ Home End Enter Esc 首字母定位)与 ARIA 行为齐备。
|
||||
*/
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, useId, watch } from 'vue'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue?: any
|
||||
disabled?: boolean
|
||||
ariaLabel?: string
|
||||
placeholder?: string
|
||||
/** 选项超过该数量时自动显示过滤框(与 FMultiSelect 一致) */
|
||||
searchThreshold?: number
|
||||
/** sm 用于表格行内/工具条,md 用于表单 */
|
||||
size?: 'sm' | 'md'
|
||||
}>(), {
|
||||
modelValue: undefined, disabled: false, ariaLabel: '', placeholder: '请选择',
|
||||
searchThreshold: 8, size: 'md'
|
||||
})
|
||||
const emit = defineEmits<{ (e: 'update:modelValue', value: any): void }>()
|
||||
|
||||
/** 双向绑定透传给隐藏的原生 select,由 Vue 的 vModelSelect 负责值↔选项匹配 */
|
||||
const inner = computed({
|
||||
get: () => props.modelValue,
|
||||
set: (v) => emit('update:modelValue', v)
|
||||
})
|
||||
|
||||
const native = ref<HTMLSelectElement | null>(null)
|
||||
const triggerEl = ref<HTMLButtonElement | null>(null)
|
||||
const popEl = ref<HTMLDivElement | null>(null)
|
||||
const listEl = ref<HTMLDivElement | null>(null)
|
||||
const searchEl = ref<HTMLInputElement | null>(null)
|
||||
|
||||
const uid = useId()
|
||||
const open = ref(false)
|
||||
const query = ref('')
|
||||
const items = ref<{ text: string; disabled: boolean }[]>([])
|
||||
const selIndex = ref(-1)
|
||||
const active = ref(-1)
|
||||
const shown = ref('')
|
||||
const pop = ref({ left: 0, top: 0, width: 0, drop: true, maxH: 264 })
|
||||
|
||||
let observer: MutationObserver | null = null
|
||||
let lastSig = ''
|
||||
let scheduled = 0
|
||||
|
||||
function snapshot(): boolean {
|
||||
const el = native.value
|
||||
if (!el) return false
|
||||
const rows = Array.from(el.options).map((o) => ({
|
||||
text: (o.textContent || '').replace(/\s+/g, ' ').trim() || o.value,
|
||||
disabled: o.disabled || !!o.parentElement?.hasAttribute('disabled')
|
||||
}))
|
||||
const sel = el.selectedIndex
|
||||
// 关键:选项数据来自父级插槽,本组件每次重渲染都会重新生成这些 vnode。
|
||||
// 若 snapshot() 无条件写入新数组,就会形成「MutationObserver → 重渲染 → 新记录」的死循环,
|
||||
// 所以用签名去重:只有内容真的变了才写入响应式状态。
|
||||
const sig = rows.map((r) => (r.disabled ? '1' : '0') + r.text).join('\u0001') + '\u0002' + sel
|
||||
if (sig === lastSig) return false
|
||||
lastSig = sig
|
||||
items.value = rows
|
||||
selIndex.value = sel
|
||||
shown.value = sel >= 0 ? (rows[sel]?.text || '') : ''
|
||||
return true
|
||||
}
|
||||
|
||||
/** 过滤后的可见项下标(保留原始 index,选择时直接映射回 option) */
|
||||
const view = computed(() => {
|
||||
const q = query.value.trim().toLowerCase()
|
||||
const all = items.value.map((_, i) => i)
|
||||
return q ? all.filter((i) => items.value[i].text.toLowerCase().includes(q)) : all
|
||||
})
|
||||
const searchable = computed(() => props.searchThreshold > 0 && items.value.length > props.searchThreshold)
|
||||
|
||||
/** 选项由 v-for 渲染,父级异步加载后会变化 → 用 MutationObserver 兜住所有情况 */
|
||||
function observe() {
|
||||
observer?.disconnect()
|
||||
if (scheduled) window.clearTimeout(scheduled)
|
||||
const el = native.value
|
||||
if (!el) return
|
||||
observer = new MutationObserver(() => {
|
||||
if (scheduled) return
|
||||
scheduled = window.setTimeout(() => {
|
||||
scheduled = 0
|
||||
snapshot()
|
||||
if (open.value) place()
|
||||
}, 0)
|
||||
})
|
||||
observer.observe(el, { childList: true, subtree: true, characterData: true, attributes: true })
|
||||
}
|
||||
|
||||
let measureCtx: CanvasRenderingContext2D | null = null
|
||||
/** 弹层宽度:既不窄于触发器,也要放得下最长的选项(最多 380px / 视口宽 - 24) */
|
||||
function contentWidth() {
|
||||
if (!measureCtx) {
|
||||
const cvs = document.createElement('canvas')
|
||||
measureCtx = cvs.getContext('2d')
|
||||
}
|
||||
if (!measureCtx) return 0
|
||||
measureCtx.font = '12px "DM Sans", "Noto Sans SC", system-ui, sans-serif'
|
||||
let max = 0
|
||||
for (const it of items.value) max = Math.max(max, measureCtx.measureText(it.text).width)
|
||||
return Math.ceil(max) + 44
|
||||
}
|
||||
|
||||
function place() {
|
||||
const el = triggerEl.value
|
||||
if (!el) return
|
||||
const r = el.getBoundingClientRect()
|
||||
const avail = Math.max(160, innerWidth - 24)
|
||||
const wanted = Math.max(r.width, contentWidth())
|
||||
const width = Math.min(Math.max(wanted, Math.min(168, avail)), 420, avail)
|
||||
const below = innerHeight - r.bottom - 14
|
||||
const above = r.top - 14
|
||||
const drop = below >= 190 || below >= above
|
||||
pop.value = {
|
||||
left: Math.min(Math.max(8, r.left), Math.max(8, innerWidth - width - 8)),
|
||||
top: drop ? r.bottom + 6 : r.top - 6,
|
||||
width,
|
||||
drop,
|
||||
maxH: Math.max(132, Math.min(300, drop ? below : above))
|
||||
}
|
||||
}
|
||||
|
||||
/** 弹层实际高度要渲染后才知道:这里按真实 rect 纠正,必要时翻边/贴边 */
|
||||
function clampToViewport() {
|
||||
const el = popEl.value
|
||||
if (!el) return
|
||||
const rect = el.getBoundingClientRect()
|
||||
let { top } = pop.value
|
||||
if (rect.bottom > innerHeight - 8 || rect.top < 8) {
|
||||
const h = rect.height
|
||||
const belowSpace = innerHeight - elTriggerBottom()
|
||||
if (pop.value.drop && belowSpace < h && rect.top - 14 > h) top = (triggerEl.value?.getBoundingClientRect().top ?? rect.top) - 6
|
||||
else if (!pop.value.drop && rect.top < 8) top = (triggerEl.value?.getBoundingClientRect().bottom ?? rect.bottom) + 6
|
||||
if (top + h > innerHeight - 8) top = innerHeight - 8 - h
|
||||
if (top < 8) top = 8
|
||||
pop.value = { ...pop.value, top }
|
||||
}
|
||||
}
|
||||
function elTriggerBottom() {
|
||||
const t = triggerEl.value?.getBoundingClientRect()
|
||||
return t ? t.bottom + 6 : rectSafeBottom()
|
||||
}
|
||||
function rectSafeBottom() { return innerHeight - 12 }
|
||||
|
||||
function scrollActiveIntoView() {
|
||||
const box = listEl.value?.querySelector<HTMLElement>('[data-act="1"]')
|
||||
box?.scrollIntoView({ block: 'nearest' })
|
||||
}
|
||||
|
||||
async function toggle(force?: boolean) {
|
||||
if (props.disabled) return
|
||||
open.value = force ?? !open.value
|
||||
if (!open.value) {
|
||||
if (query.value) query.value = ''
|
||||
return
|
||||
}
|
||||
snapshot()
|
||||
query.value = ''
|
||||
active.value = selIndex.value >= 0 ? selIndex.value : items.value.findIndex((i) => !i.disabled)
|
||||
place()
|
||||
await nextTick()
|
||||
clampToViewport()
|
||||
scrollActiveIntoView()
|
||||
if (searchable.value) searchEl.value?.focus({ preventScroll: true })
|
||||
else triggerEl.value?.focus({ preventScroll: true })
|
||||
}
|
||||
|
||||
function choose(i: number) {
|
||||
const el = native.value
|
||||
const opt = el?.options[i]
|
||||
if (!el || !opt || opt.disabled) return
|
||||
el.selectedIndex = i
|
||||
el.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
el.dispatchEvent(new Event('change', { bubbles: true }))
|
||||
snapshot()
|
||||
open.value = false
|
||||
triggerEl.value?.focus({ preventScroll: true })
|
||||
}
|
||||
|
||||
function move(delta: number) {
|
||||
if (!items.value.length) return
|
||||
if (!open.value) { void toggle(true); return }
|
||||
const list = view.value
|
||||
if (!list.length) return
|
||||
let pos = Math.max(0, list.indexOf(active.value))
|
||||
for (let n = 0; n < list.length; n++) {
|
||||
pos = (pos + delta + list.length) % list.length
|
||||
if (!items.value[list[pos]].disabled) break
|
||||
}
|
||||
active.value = list[pos]
|
||||
void nextTick(scrollActiveIntoView)
|
||||
}
|
||||
|
||||
let typeBuf = ''
|
||||
let typeTimer = 0
|
||||
function typeAhead(ch: string) {
|
||||
typeBuf += ch.toLowerCase()
|
||||
window.clearTimeout(typeTimer)
|
||||
typeTimer = window.setTimeout(() => { typeBuf = '' }, 420)
|
||||
const hit = view.value.find((i) => items.value[i].text.toLowerCase().startsWith(typeBuf))
|
||||
if (hit !== undefined) { active.value = hit; void nextTick(scrollActiveIntoView) }
|
||||
}
|
||||
|
||||
function onKeydown(e: KeyboardEvent) {
|
||||
// 过滤输入框自己处理方向键/回车(见 onSearchKeydown),这里只服务触发器
|
||||
if ((e.target as HTMLElement | null)?.tagName === 'INPUT') return
|
||||
if (e.key === 'Escape') { if (open.value) { e.preventDefault(); e.stopPropagation(); open.value = false } return }
|
||||
if (e.key === 'Tab') { open.value = false; return }
|
||||
if (['ArrowDown', 'ArrowUp'].includes(e.key)) { e.preventDefault(); move(e.key === 'ArrowDown' ? 1 : -1); return }
|
||||
if (e.key === 'Home' || e.key === 'End') {
|
||||
if (!open.value) return
|
||||
e.preventDefault()
|
||||
const list = view.value
|
||||
if (!list.length) return
|
||||
const order = e.key === 'Home' ? list : [...list].reverse()
|
||||
const hit = order.find((i) => !items.value[i].disabled)
|
||||
active.value = hit ?? list[0]
|
||||
void nextTick(scrollActiveIntoView)
|
||||
return
|
||||
}
|
||||
if (['Enter', ' ', 'Spacebar'].includes(e.key)) {
|
||||
e.preventDefault()
|
||||
if (open.value) choose(active.value)
|
||||
else void toggle(true)
|
||||
return
|
||||
}
|
||||
if (e.key.length === 1 && !e.metaKey && !e.ctrlKey && !e.altKey) {
|
||||
if (!open.value) { void toggle(true); return }
|
||||
typeAhead(e.key)
|
||||
}
|
||||
}
|
||||
|
||||
function onSearchKeydown(e: KeyboardEvent) {
|
||||
if (['ArrowDown', 'ArrowUp'].includes(e.key)) { e.preventDefault(); e.stopPropagation(); move(e.key === 'ArrowDown' ? 1 : -1) }
|
||||
else if (e.key === 'Home' || e.key === 'End') { e.stopPropagation() }
|
||||
else if (['Enter', ' ', 'Spacebar'].includes(e.key)) {
|
||||
if (e.key === 'Enter' && active.value >= 0) { e.preventDefault(); e.stopPropagation(); choose(active.value) }
|
||||
} else if (e.key === 'Escape') { e.stopPropagation(); void toggle(false); triggerEl.value?.focus({ preventScroll: true }) }
|
||||
}
|
||||
|
||||
function onPointerDown(e: PointerEvent) {
|
||||
if (!open.value) return
|
||||
const t = e.target as Node
|
||||
if (triggerEl.value?.contains(t) || popEl.value?.contains(t)) return
|
||||
open.value = false
|
||||
}
|
||||
|
||||
function reposition() { if (open.value) place() }
|
||||
|
||||
onMounted(() => {
|
||||
snapshot()
|
||||
observe()
|
||||
document.addEventListener('pointerdown', onPointerDown, true)
|
||||
window.addEventListener('resize', reposition)
|
||||
window.addEventListener('scroll', reposition, true)
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
observer?.disconnect()
|
||||
document.removeEventListener('pointerdown', onPointerDown, true)
|
||||
window.removeEventListener('resize', reposition)
|
||||
window.removeEventListener('scroll', reposition, true)
|
||||
})
|
||||
watch(() => props.modelValue, () => { snapshot() })
|
||||
watch(() => props.disabled, (v) => { if (v) open.value = false })
|
||||
watch(query, () => {
|
||||
active.value = view.value.find((i) => !items.value[i].disabled) ?? -1
|
||||
void nextTick(scrollActiveIntoView)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span class="fselect" :class="['s-' + size, { open, disabled: !!disabled }]">
|
||||
<!-- 隐藏原生 select:只为承载 options 与 v-model 指令语义,不参与视觉 -->
|
||||
<select ref="native" v-model="inner" class="fselect-native" :disabled="disabled" tabindex="-1"
|
||||
aria-hidden="true"><slot /></select>
|
||||
|
||||
<button ref="triggerEl" type="button" class="fselect-trigger" :disabled="disabled"
|
||||
:aria-label="ariaLabel || undefined" aria-haspopup="listbox" :aria-expanded="open ? 'true' : 'false'"
|
||||
:aria-activedescendant="open && active >= 0 ? uid + '-o' + active : undefined"
|
||||
@click="toggle()" @keydown="onKeydown">
|
||||
<span class="fselect-text" :class="{ ph: !shown }">{{ shown || placeholder }}</span>
|
||||
<svg class="fselect-caret" :class="{ up: open }" viewBox="0 0 20 20" aria-hidden="true">
|
||||
<path d="M5.5 7.5 10 12l4.5-4.5" fill="none" stroke="currentColor" stroke-width="1.7"
|
||||
stroke-linecap="round" stroke-linejoin="round" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<Teleport to="body">
|
||||
<div v-if="open" ref="popEl" class="fselect-pop"
|
||||
:class="{ 'fs-filtered': searchable }"
|
||||
:style="{ left: pop.left + 'px', top: pop.top + 'px', width: pop.width + 'px',
|
||||
maxHeight: pop.maxH + 'px', transform: pop.drop ? 'none' : 'translateY(-100%)' }"
|
||||
role="listbox" :aria-label="ariaLabel || undefined"
|
||||
:aria-activedescendant="open && active >= 0 ? uid + '-o' + active : undefined"
|
||||
@mousedown.stop @keydown="onKeydown">
|
||||
<div v-if="searchable" class="fs-filterbar">
|
||||
<input ref="searchEl" v-model="query" class="fs-filter" type="search" placeholder="过滤选项…"
|
||||
:aria-label="(ariaLabel || '选项') + ':过滤'" @keydown="onSearchKeydown" />
|
||||
<span class="fs-tally">{{ view.length === items.length ? `${items.length} 项` : `${view.length} / ${items.length} 项` }}</span>
|
||||
</div>
|
||||
<div ref="listEl" class="fselect-list">
|
||||
<div v-for="i in view" :key="i" :id="uid + '-o' + i" class="fselect-item"
|
||||
:class="{ on: i === selIndex, act: i === active, off: items[i].disabled }"
|
||||
:data-act="i === active ? '1' : '0'" role="option" :aria-selected="i === selIndex ? 'true' : 'false'"
|
||||
@mouseenter="active = i" @click="choose(i)">
|
||||
<span class="tick" :class="{ show: i === selIndex }" aria-hidden="true">✓</span>
|
||||
<span class="txt">{{ items[i].text }}</span>
|
||||
</div>
|
||||
<div v-if="!items.length" class="fselect-none">无可选项</div>
|
||||
<div v-else-if="!view.length" class="fselect-none">没有匹配的选项</div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.fselect { position: relative; display: inline-flex; width: 100%; min-width: 0; vertical-align: middle }
|
||||
.fselect-native {
|
||||
position: absolute; inset: 0; width: 100%; height: 100%; margin: 0; padding: 0;
|
||||
border: 0; background: none; opacity: 0; pointer-events: none; appearance: none; font-size: 16px
|
||||
}
|
||||
.fselect-trigger {
|
||||
appearance: none; -webkit-appearance: none;
|
||||
display: flex; align-items: center; gap: 8px; width: 100%; min-width: 0;
|
||||
/* 高度由全局 --ctl-h 决定(见 style.css 控件高度体系),纵向 padding 归零,
|
||||
这样同一个视觉行里的下拉与输入框/按钮严格等高、中心线一致。 */
|
||||
height: var(--ctl-h); padding: 0 10px; border-radius: 7px; text-align: left;
|
||||
border: 1px solid var(--c-line-strong); background: var(--c-bg-input); color: var(--c-text);
|
||||
font-size: 12px; line-height: 1.35; transition: border-color .14s, background .14s, box-shadow .14s
|
||||
}
|
||||
.s-sm .fselect-trigger { padding-inline: 8px; font-size: 11px; border-radius: 6px }
|
||||
.fselect-text { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap }
|
||||
.fselect-text.ph { color: var(--c-text-faint) }
|
||||
.fselect-caret { flex: 0 0 auto; width: 15px; height: 15px; color: var(--c-text-muted); transition: transform .16s, color .14s }
|
||||
.fselect-caret.up { transform: rotate(180deg); color: var(--c-accent-bright) }
|
||||
.fselect-trigger:hover:not(:disabled) { border-color: var(--c-line-bright); background: var(--c-bg-hover) }
|
||||
.fselect.open .fselect-trigger, .fselect-trigger:focus-visible {
|
||||
outline: none; border-color: var(--c-accent-deep); box-shadow: 0 0 0 3px var(--c-accent-tint)
|
||||
}
|
||||
.fselect.disabled { opacity: .5 }
|
||||
.fselect-trigger:disabled { cursor: not-allowed }
|
||||
</style>
|
||||
|
||||
<style>
|
||||
/* 弹层被 Teleport 到 body,必须用全局样式(不能 scoped) */
|
||||
.fselect-pop {
|
||||
z-index: 400; position: fixed; display: flex; overflow: hidden;
|
||||
border: 1px solid var(--c-line-strong); border-radius: 10px;
|
||||
background: var(--c-bg-panel); box-shadow: 0 18px 44px var(--c-shade-3);
|
||||
animation: fselect-in .12s ease-out
|
||||
}
|
||||
@keyframes fselect-in { from { opacity: 0; transform: translateY(-4px) } }
|
||||
.fselect-pop[style*="translateY(-100%)"] { animation: fselect-in-up .12s ease-out }
|
||||
.fselect-pop.fs-filtered { flex-direction: column }
|
||||
.fs-filterbar {
|
||||
flex: 0 0 auto; display: flex; align-items: center; gap: 7px; padding: 7px 8px;
|
||||
border-bottom: 1px solid var(--c-line); background: var(--c-bg-raise)
|
||||
}
|
||||
.fs-filter {
|
||||
flex: 1 1 auto; min-width: 0; padding: 5px 8px; font-size: 11px; border-radius: 6px;
|
||||
border: 1px solid var(--c-line-strong); background: var(--c-bg-input); color: var(--c-text)
|
||||
}
|
||||
.fs-filter:focus { outline: none; border-color: var(--c-accent-deep); box-shadow: 0 0 0 2px var(--c-accent-tint) }
|
||||
.fs-filter::-webkit-search-cancel-button { -webkit-appearance: none }
|
||||
.fs-tally { flex: 0 0 auto; font-size: 10px; color: var(--c-text-faint); white-space: nowrap }
|
||||
@keyframes fselect-in-up { from { opacity: 0 } }
|
||||
.fselect-list { flex: 1 1 auto; max-height: inherit; overflow: auto; padding: 5px }
|
||||
.fselect-item {
|
||||
display: flex; align-items: flex-start; gap: 7px; padding: 7px 8px; border-radius: 7px;
|
||||
font-size: 12px; line-height: 1.45; color: var(--c-text-2); cursor: pointer
|
||||
}
|
||||
.fselect-item .tick { flex: 0 0 12px; width: 12px; margin-top: 1px; font-size: 11px; color: var(--c-accent-bright); opacity: 0 }
|
||||
.fselect-item .tick.show { opacity: 1 }
|
||||
.fselect-item .txt { min-width: 0; overflow-wrap: anywhere }
|
||||
.fselect-item.act { background: var(--c-bg-hover); color: var(--c-text) }
|
||||
.fselect-item.on { color: var(--c-accent-bright); background: var(--c-accent-tint) }
|
||||
.fselect-item.on.act { background: var(--c-accent-tint2) }
|
||||
.fselect-item.off { opacity: .4; cursor: not-allowed }
|
||||
.fselect-none { padding: 10px; font-size: 11px; color: var(--c-text-faint); text-align: center }
|
||||
.fselect-pop ::-webkit-scrollbar { width: 8px }
|
||||
.fselect-pop ::-webkit-scrollbar-thumb { background: var(--c-line-strong); border-radius: 8px }
|
||||
</style>
|
||||
|
|
@ -1,328 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* 全局唯一的媒体预览器(挂在 App.vue 上,整个平台共用一个实例)。
|
||||
* 能力:图片 / 视频 / 音频 / 文档占位、←→ 在打开它的队列里翻页、
|
||||
* Esc 关闭、Space 播放暂停、历史版本切换、元数据、下载、新窗口打开。
|
||||
*/
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { audioEngine, iconFor, kindLabel, pauseAudio, playAudio, stopAudio, toggleAudio, type MediaItem } from '../media'
|
||||
import { canManageVersions, choosePeer, chooseVersion, chosenVersion, close, collapsed, currentMeta, currentUrl, count, goTo, hasNext, hasPrev, isOpen, peerIndex, peers, position, resetVersion, setCurrentVersion, shown, step, toggleInfo, toggleVersionPanel, versionBusy, versionFeedback, versionPanelOpen, viewedVersion } from '../preview'
|
||||
import FSelect from './FSelect.vue'
|
||||
import VersionPanel from './VersionPanel.vue'
|
||||
|
||||
const failed = ref(false)
|
||||
const videoEl = ref<HTMLVideoElement | null>(null)
|
||||
const copied = ref('')
|
||||
|
||||
/** 展示的是 `shown`(当前镜头当前选中的那个产物),不是队列项本身 */
|
||||
const item = shown
|
||||
const src = currentUrl
|
||||
const meta = currentMeta
|
||||
const kind = computed(() => item.value?.kind || 'none')
|
||||
const versions = computed(() => item.value?.versions || [])
|
||||
const canSwitchVersion = computed(() => versions.value.length > 1)
|
||||
|
||||
/* 版本管理:设为当前 / 删除某版。入口只在这里,因为整个平台只有预览器
|
||||
有完整版本下拉;平台资产库与项目素材库共用同一套动作。 */
|
||||
const manage = computed(() => canManageVersions(item.value))
|
||||
const viewed = computed(() => viewedVersion(item.value))
|
||||
const isCurrentViewed = computed(() => !!item.value && viewed.value?.version_no === item.value.version)
|
||||
const canMakeCurrent = computed(() =>
|
||||
manage.value && versions.value.length > 1 && !isCurrentViewed.value && viewed.value?.exists !== false)
|
||||
// 文件丢失的版本不能设为默认(切过去就是白图),但可以在版本管理里删掉——
|
||||
// 后端在「设为默认」被文件丢失挡住时,给的建议正是「删除该版本后重新上传」。
|
||||
const missingFile = computed(() => viewed.value?.exists === false)
|
||||
const onlyOneVersion = '只有一个版本,如需清理请直接删除该素材'
|
||||
/* 按钮灰掉时必须说清为什么灰:预览的就是默认版时,「设为默认」无事可做,
|
||||
但「版本管理」照样能点开删别的版本。 */
|
||||
const makeCurrentHint = computed(() => {
|
||||
if (!manage.value) return '这条素材不是平台母版或项目资产,暂不支持版本管理'
|
||||
if (versions.value.length < 2) return onlyOneVersion
|
||||
if (missingFile.value) return '该版本文件已丢失,无法设为默认;可以先删掉它再重新上传'
|
||||
if (isCurrentViewed.value) return '这一版已经是当前默认,先在上方下拉切到别的版本,或打开版本管理逐版操作'
|
||||
return ''
|
||||
})
|
||||
|
||||
function makeCurrent() {
|
||||
const no = viewed.value?.version_no
|
||||
if (no) void setCurrentVersion(no)
|
||||
}
|
||||
|
||||
const downloadHref = computed(() => (src.value ? `${src.value}` : ''))
|
||||
|
||||
/** 预览器打开时,这些按键归预览器:必须抢在页面快捷键之前消费掉,
|
||||
* 否则一次 Esc 会同时关掉预览器和右栏检查器(页面自己也绑了 Esc)。 */
|
||||
function onKeydown(event: KeyboardEvent) {
|
||||
if (!isOpen.value) return
|
||||
const tag = (event.target as HTMLElement | null)?.tagName
|
||||
if (tag && /^(INPUT|TEXTAREA|SELECT)$/.test(tag)) return
|
||||
let handled = true
|
||||
switch (event.key) {
|
||||
case 'Escape': close(); break
|
||||
case 'ArrowRight': step(1); break
|
||||
case 'ArrowLeft': step(-1); break
|
||||
case ' ': space(); break
|
||||
case 'Home': goTo(0); break
|
||||
case 'End': goTo(count.value - 1); break
|
||||
case 'i': case 'I': toggleInfo(); break
|
||||
case '[': case ']': if (peerCount.value > 1) choosePeer((peerIndex.value + (event.key === ']' ? 1 : -1) + peerCount.value) % peerCount.value); else handled = false; break
|
||||
default: handled = false
|
||||
}
|
||||
if (!handled) return
|
||||
event.preventDefault()
|
||||
event.stopImmediatePropagation()
|
||||
}
|
||||
|
||||
const peerCount = computed(() => peers.value.length)
|
||||
/** 格子上写「关键帧」就够,括注里的「(平台配音)/(模型原声)」留给 tooltip */
|
||||
const shortLabel = (pb: MediaItem) => pb.kindLabel.replace(/[((].*?[))]/g, '').trim() || pb.kindLabel
|
||||
|
||||
function space() {
|
||||
if (kind.value === 'video' && videoEl.value) {
|
||||
if (videoEl.value.paused) void videoEl.value.play()
|
||||
else videoEl.value.pause()
|
||||
return
|
||||
}
|
||||
if (kind.value === 'audio' && src.value) toggleAudio(src.value, item.value?.title || '')
|
||||
}
|
||||
|
||||
watch(src, () => { failed.value = false })
|
||||
|
||||
/** 预览期间锁住背景页面滚动:否则滚轮会滚到身后的列表,
|
||||
* 同时避免页面滚动条让 fixed 弹窗出现 1~2px 的横向跳动。 */
|
||||
let prevOverflow = ''
|
||||
function setScrollLock(lock: boolean) {
|
||||
const el = document.documentElement
|
||||
if (lock) {
|
||||
prevOverflow = el.style.overflow
|
||||
el.style.overflow = 'hidden'
|
||||
} else {
|
||||
el.style.overflow = prevOverflow
|
||||
prevOverflow = ''
|
||||
}
|
||||
}
|
||||
watch(isOpen, (v) => setScrollLock(v), { immediate: true })
|
||||
|
||||
onMounted(() => window.addEventListener('keydown', onKeydown, true))
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('keydown', onKeydown, true)
|
||||
if (isOpen.value) setScrollLock(false)
|
||||
if (kind.value === 'audio' && audioEngine.playing) pauseAudio()
|
||||
})
|
||||
|
||||
function copyLink() {
|
||||
if (!src.value) return
|
||||
void navigator.clipboard?.writeText(location.origin + src.value).then(() => {
|
||||
copied.value = '链接已复制'
|
||||
window.setTimeout(() => { copied.value = '' }, 1600)
|
||||
}).catch(() => { copied.value = '复制失败' })
|
||||
}
|
||||
|
||||
function onClosed() {
|
||||
if (audioEngine.playing) stopAudio()
|
||||
close()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="isOpen && item" class="lb" role="dialog" aria-modal="true" :aria-label="'预览 ' + item.title">
|
||||
<div class="scrim" @click="onClosed"></div>
|
||||
<div class="box">
|
||||
<header class="lb-head">
|
||||
<div class="titles">
|
||||
<p class="eyebrow">{{ item.group || item.kindLabel || kindLabel(kind) }} · {{ kindLabel(kind) }}</p>
|
||||
<h3>{{ item.title }}</h3>
|
||||
<p v-if="item.subtitle" class="sub">{{ item.subtitle }}</p>
|
||||
</div>
|
||||
<div class="head-right">
|
||||
<div v-if="peerCount > 1" class="switch" role="group" aria-label="切换本镜产物">
|
||||
<button v-for="(pb, pi) in peers" :key="pb.key" :class="{ on: pi === peerIndex }"
|
||||
:title="`查看本镜的${pb.kindLabel}(${pi + 1}/${peerCount},[ 与 ] 切换)`"
|
||||
@click="choosePeer(pi)">{{ shortLabel(pb) }}</button>
|
||||
</div>
|
||||
<span v-if="count > 1" class="counter mono">{{ position }} / {{ count }}</span>
|
||||
<label v-if="canSwitchVersion" class="verpick">
|
||||
<span>版本</span>
|
||||
<FSelect :model-value="chosenVersion" @change="chooseVersion(Number(($event.target as HTMLSelectElement).value))">
|
||||
<option v-for="v in versions" :key="v.version_no" :value="v.version_no">
|
||||
v{{ v.version_no }}{{ v.version_no === item.version ? '(当前默认)' : '' }}{{ v.exists === false ? '(文件缺失)' : '' }}
|
||||
</option>
|
||||
</FSelect>
|
||||
<button class="ghost tiny" v-if="chosenVersion !== item.version" @click="resetVersion"
|
||||
title="回到当前默认版本">回默认</button>
|
||||
</label>
|
||||
<div v-if="manage && canSwitchVersion" class="verops">
|
||||
<button class="ghost star" @click="makeCurrent" :disabled="!canMakeCurrent || versionBusy"
|
||||
:title="makeCurrentHint || `把正在预览的 v${viewed?.version_no} 设为当前默认版本,平台母版与之后引入项目的素材都会跟着切`">
|
||||
{{ versionBusy ? '处理中…' : '★ 设为默认' }}
|
||||
</button>
|
||||
<button class="ghost" :class="{ on: versionPanelOpen }" @click="toggleVersionPanel()"
|
||||
:title="versionPanelOpen ? '收起版本管理' : `逐版查看 / 设为默认 / 删除,共 ${versions.length} 版`">
|
||||
▤ 版本管理<span class="vn">{{ versions.length }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<button class="ghost" @click="toggleInfo" :title="collapsed ? '显示元数据 (I)' : '收起元数据 (I)'">{{ collapsed ? 'ⓘ 信息' : 'ⓘ 收起' }}</button>
|
||||
<button class="ghost" @click="onClosed" title="关闭 (Esc)">✕</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="stage">
|
||||
<button v-if="count > 1" class="nav prev" @click="step(-1)" :disabled="!hasPrev" title="上一个 (←)">‹</button>
|
||||
<div class="canvas" :class="'k-' + kind">
|
||||
<img v-if="kind === 'image'" :src="src" :alt="item.title" :class="{ hide: failed }"
|
||||
@error="failed = true" />
|
||||
<video v-else-if="kind === 'video'" ref="videoEl" :src="src" :poster="item.poster || undefined"
|
||||
controls autoplay playsinline :class="{ hide: failed }" @error="failed = true"></video>
|
||||
<div v-else-if="kind === 'audio'" class="audio-stage">
|
||||
<div class="disc" :class="{ spin: audioEngine.playing && audioEngine.src === src }">{{ iconFor('audio') }}</div>
|
||||
<p class="an">{{ item.title }}</p>
|
||||
<div class="abar" role="slider" aria-label="播放进度"
|
||||
:aria-valuenow="Math.round(audioEngine.duration ? (audioEngine.position / audioEngine.duration) * 100 : 0)">
|
||||
<i :style="{ width: (audioEngine.duration ? Math.min(100, (audioEngine.position / audioEngine.duration) * 100) : 0) + '%' }"></i>
|
||||
</div>
|
||||
<div class="actrl">
|
||||
<button class="big" @click="playAudio(src, item.title)" :disabled="audioEngine.playing && audioEngine.src === src" title="播放 (Space)">▶</button>
|
||||
<button class="big" @click="pauseAudio" :disabled="!(audioEngine.playing && audioEngine.src === src)" title="暂停 (Space)">❚❚</button>
|
||||
<span class="mono atime">{{ (audioEngine.position || 0).toFixed(1) }}s / {{ audioEngine.duration ? audioEngine.duration.toFixed(1) + 's' : '—' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="doc-stage">
|
||||
<b>{{ iconFor(kind) }}</b>
|
||||
<p>{{ item.title }}</p>
|
||||
<a class="primary" :href="downloadHref" target="_blank" rel="noopener">打开 / 下载文件</a>
|
||||
</div>
|
||||
<div v-if="failed" class="oops">
|
||||
<b>无法加载该媒体</b>
|
||||
<small class="mono">{{ item.path || src }}</small>
|
||||
<span>可能是文件已被清理,或该 ffmpeg/服务进程无权读取。</span>
|
||||
<a :href="downloadHref" target="_blank" rel="noopener">仍要在新窗口打开 ↗</a>
|
||||
</div>
|
||||
</div>
|
||||
<button v-if="count > 1" class="nav next" @click="step(1)" :disabled="!hasNext" title="下一个 (→)">›</button>
|
||||
<VersionPanel v-if="manage && canSwitchVersion && versionPanelOpen" @close="toggleVersionPanel(false)" />
|
||||
</div>
|
||||
|
||||
<footer class="lb-foot">
|
||||
<div v-if="!collapsed" class="metas">
|
||||
<span v-for="f in meta" :key="f.label" class="mfield">
|
||||
<i>{{ f.label }}</i><b :title="f.value">{{ f.value }}</b>
|
||||
</span>
|
||||
</div>
|
||||
<div class="acts">
|
||||
<span v-if="count > 1" class="keys muted">← / → 上一镜 / 下一镜<span v-if="peerCount > 1"> · [ / ] 换本镜产物</span> · Space 播放 · Esc 关闭</span>
|
||||
<span v-else class="keys muted">Esc 关闭 · I 切换信息</span>
|
||||
<span v-if="copied" class="tag ok">{{ copied }}</span>
|
||||
<span v-if="versionFeedback" class="tag" :class="versionFeedback.tone">{{ versionFeedback.text }}</span>
|
||||
<button class="ghost" @click="copyLink">复制链接</button>
|
||||
<a class="ghost" :href="downloadHref" target="_blank" rel="noopener">新窗口</a>
|
||||
<a class="primary" :href="downloadHref" :download="item.downloadName">下载</a>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.lb { position: fixed; inset: 0; z-index: 220; display: grid; place-items: center; padding: 14px }
|
||||
/* 灯箱会从抽屉(z=100)、对话框(z=150)里被打开,层级必须高于它们,否则预览被母面板盖住。
|
||||
背景用 --c-backdrop 而不是 --c-scrim:亮色主题的 scrim 只有 38% 浓度,
|
||||
铺满整屏时页面会从四周透出来,看起来像「弹窗之间有一条没画完的白带」。 */
|
||||
.scrim { position: absolute; inset: 0; background: var(--c-backdrop); backdrop-filter: blur(7px) saturate(.92) }
|
||||
.box {
|
||||
position: relative; display: flex; flex-direction: column;
|
||||
width: min(1560px, 100%);
|
||||
/* 高度必须是确定值:.canvas img 的 max-height:100% 只有在父级高度确定时才生效,
|
||||
否则舞台高度由图片原始比例反推,footer 会被挤出 .box 的 overflow:hidden,
|
||||
表现为「元数据被裁一半、下载按钮旁边像缺了个控件」。 */
|
||||
height: calc(100vh - 28px); height: calc(100dvh - 28px);
|
||||
max-height: min(1180px, calc(100vh - 28px)); max-height: min(1180px, calc(100dvh - 28px));
|
||||
min-height: min(420px, calc(100vh - 28px)); min-height: min(420px, calc(100dvh - 28px));
|
||||
background: var(--c-bg-panel);
|
||||
border: 1px solid var(--c-line-strong); border-radius: 14px; overflow: hidden;
|
||||
box-shadow: 0 26px 70px var(--c-backdrop-shadow);
|
||||
}
|
||||
.lb-head { display: flex; gap: 14px; align-items: flex-start; justify-content: space-between; padding: 12px 16px; margin: 0; border-bottom: 1px solid var(--c-line); background: var(--c-bg-raise); flex: 0 0 auto }
|
||||
/* 全局 header/label/.sub/p 的默认外边距会把这些子元素撑高,逐项归零 */
|
||||
.lb-head p { margin: 0 }
|
||||
.titles .sub { border-top: 0; padding-top: 0; margin: 4px 0 0 }
|
||||
.titles { flex: 1 1 auto; min-width: 0 }
|
||||
.titles h3 { margin: 3px 0 0; font-size: 15px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 100% }
|
||||
.titles .sub { margin: 4px 0 0; font-size: 11px; color: var(--c-text-faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 100% }
|
||||
.head-right { display: flex; align-items: center; gap: 6px 8px; flex: 0 1 auto; flex-wrap: wrap; justify-content: flex-end; max-width: 70% }
|
||||
/* 本镜产物切换:镜头是翻页单位,产物在这一格里换,不再占掉 ←/→ */
|
||||
.switch { display: flex; align-items: center; gap: 2px; padding: 2px; border: 1px solid var(--c-line); border-radius: 9px; background: var(--c-bg-sunken) }
|
||||
.switch button { border: 0; background: transparent; color: var(--c-text-dim); font-size: 11px; padding: 4px 9px; border-radius: 7px; cursor: pointer; white-space: nowrap }
|
||||
.switch button:hover { color: var(--c-text); background: var(--c-bg-raise) }
|
||||
.switch button.on { color: var(--c-text); background: var(--c-bg-panel); border: 1px solid var(--c-line-strong); font-weight: 600 }
|
||||
.counter { font-size: 11px; color: var(--c-text-3); padding: 4px 8px; border: 1px solid var(--c-line); border-radius: 7px; background: var(--c-bg-sunken) }
|
||||
.verpick { display: flex; flex-direction: row; margin: 0; align-items: center; gap: 6px; font-size: 10.5px; color: var(--c-text-faint); flex: 0 0 auto; white-space: nowrap }
|
||||
.verpick :deep(.fselect) { width: auto; min-width: 128px; max-width: 196px }
|
||||
.verpick :deep(.fselect-trigger) { padding-inline: 7px; font-size: 10.5px; border-radius: 6px }
|
||||
.verpick :deep(.fselect-caret) { width: 13px; height: 13px }
|
||||
/* 头部所有控件(版本下拉、元数据、关闭)统一走全局紧凑高度:
|
||||
✕ / ⓘ 这类字形行盒比文字高,用 padding 撑高度一定会差 2~3px */
|
||||
.ghost:hover { border-color: var(--c-line-bright); background: var(--c-bg-hover) }
|
||||
.ghost:disabled { opacity: .35; cursor: not-allowed }
|
||||
.verops { display: flex; align-items: center; gap: 6px; flex: 0 0 auto; white-space: nowrap }
|
||||
/* 「设为默认 / 版本管理」是这次要让人找到的入口,字号不能比正文还小 */
|
||||
.verops .ghost.star { color: var(--c-accent-bright); border-color: var(--c-accent-line) }
|
||||
.verops .ghost.star:hover:not(:disabled) { background: var(--c-accent-tint) }
|
||||
.verops .ghost.on { border-color: var(--c-accent-line-bright, var(--c-accent-line)); background: var(--c-accent-tint); color: var(--c-accent-bright) }
|
||||
.verops .vn { margin-left: 5px; padding: 0 4px; border-radius: 5px; background: var(--c-bg-active); color: var(--c-text-3); font-size: 10px }
|
||||
.stage { position: relative; flex: 1 1 auto; min-height: 0; display: flex; align-items: stretch; gap: 6px; padding: 10px; background: var(--c-bg-deepest) }
|
||||
/* canvas 必须自己撑满 stage 且行高确定(minmax(0,1fr)),
|
||||
否则 auto 行会按图片原始高度撑开,百分比 max-height 解析为 none → 图片溢出裁切 */
|
||||
.canvas { position: relative; flex: 1 1 auto; min-width: 0; min-height: 0; display: grid;
|
||||
grid-template: minmax(0, 1fr) / minmax(0, 1fr); place-items: center }
|
||||
.canvas img, .canvas video { max-width: 100%; max-height: 100%; border-radius: 8px; background: #000 }
|
||||
.canvas .audio-stage, .canvas .doc-stage { max-width: 100%; max-height: 100%; overflow: auto }
|
||||
.canvas.k-audio img, .canvas.k-audio video { display: none }
|
||||
.hide { visibility: hidden }
|
||||
/* 翻页按钮脱离 flex 交叉轴:flex 行高由未拉伸的 56px 参与计算,align-self:center 会偏上 9px */
|
||||
.nav { position: absolute; z-index: 3; top: 50%; transform: translateY(-50%); width: 42px; height: 42px;
|
||||
display: grid; place-items: center; line-height: 1; padding: 0 0 2px; color: var(--c-text);
|
||||
border: 1px solid var(--c-backdrop-veil); border-radius: 50%; background: var(--c-backdrop-veil);
|
||||
backdrop-filter: blur(6px); box-shadow: 0 6px 20px var(--c-backdrop-shadow);
|
||||
font-size: 21px; transition: background .16s, border-color .16s, transform .16s }
|
||||
.nav.prev { left: 16px }
|
||||
.nav.next { right: 16px }
|
||||
.nav:hover:not(:disabled) { background: var(--c-accent-fill); border-color: var(--c-accent-fill); color: var(--c-on-accent); transform: translateY(-50%) scale(1.06) }
|
||||
.nav:disabled { opacity: .34; cursor: not-allowed }
|
||||
.audio-stage { width: min(460px, 100%); text-align: center; padding: 24px 18px; border: 1px solid var(--c-line); border-radius: 12px; background: var(--c-bg-panel) }
|
||||
.disc { width: 74px; height: 74px; margin: 0 auto 12px; border-radius: 50%; display: grid; place-items: center; font-size: 26px; background: var(--c-accent-tint); border: 1px solid var(--c-accent-line); color: var(--c-accent-bright) }
|
||||
.disc.spin { animation: spin 3.6s linear infinite }
|
||||
@keyframes spin { to { transform: rotate(360deg) } }
|
||||
.an { font-size: 13px; font-weight: 600; margin: 0 0 12px }
|
||||
.abar { height: 5px; border-radius: 99px; background: var(--c-bg-active); overflow: hidden }
|
||||
.abar i { display: block; height: 100%; background: var(--c-accent-fill) }
|
||||
.actrl { display: flex; align-items: center; justify-content: center; gap: 8px; margin-top: 14px }
|
||||
.big { width: 34px; height: 30px; border-radius: 8px; border: 1px solid var(--c-line-strong); background: var(--c-bg-sunken); color: var(--c-text); font-size: 11px }
|
||||
.big:disabled { opacity: .35; cursor: not-allowed }
|
||||
.atime { font-size: 10.5px; color: var(--c-text-faint); margin-left: 6px }
|
||||
.doc-stage { text-align: center; color: var(--c-text-3) }
|
||||
.doc-stage b { font-size: 34px; font-weight: 400; color: var(--c-text-muted) }
|
||||
.doc-stage p { margin: 8px 0 14px; font-size: 13px }
|
||||
.oops { position: absolute; inset: 0; display: grid; place-content: center; justify-items: center; gap: 6px; text-align: center; padding: 20px }
|
||||
.oops b { font-size: 13px; color: var(--c-danger-bright) }
|
||||
.oops small { font-size: 10px; color: var(--c-text-faint); word-break: break-all; max-width: 60vw }
|
||||
.oops span { font-size: 11px; color: var(--c-text-3) }
|
||||
.oops a { font-size: 11px; color: var(--c-accent-bright) }
|
||||
.lb-foot { display: flex; gap: 8px 12px; align-items: center; justify-content: space-between; padding: 11px 16px; border-top: 1px solid var(--c-line); background: var(--c-bg-raise); flex-wrap: wrap; flex: 0 0 auto }
|
||||
.metas { display: flex; gap: 8px 20px; flex-wrap: wrap; flex: 1 1 320px; min-width: 0; max-height: min(26vh, 124px); overflow: auto; padding-right: 4px }
|
||||
.mfield { display: flex; flex-direction: column; min-width: 0; max-width: min(430px, 100%) }
|
||||
.mfield i { font-style: normal; font-size: 10px; letter-spacing: .7px; color: var(--c-text-faint); font-weight: 700 }
|
||||
.mfield b { font-size: 11px; color: var(--c-text-2); font-weight: 600; line-height: 1.45; overflow-wrap: anywhere }
|
||||
.acts { display: flex; align-items: center; gap: 8px; margin-left: auto; flex: 0 0 auto; min-height: 31px; flex-wrap: wrap; justify-content: flex-end }
|
||||
.acts .primary { padding: 7px 11px; border-radius: 7px; font-size: 10.5px; text-decoration: none; display: inline-flex; align-items: center }
|
||||
.keys { font-size: 10px }
|
||||
@media (max-width: 900px) {
|
||||
.lb { padding: 8px }
|
||||
.box { height: calc(100vh - 16px); height: calc(100dvh - 16px); max-height: calc(100vh - 16px); max-height: calc(100dvh - 16px) }
|
||||
.head-right { max-width: 52% }
|
||||
.metas { flex-basis: 100%; max-height: 84px }
|
||||
.mfield { max-width: 100% }
|
||||
.stage { padding: 8px }
|
||||
.nav { width: 34px; height: 34px; font-size: 17px }
|
||||
.nav.prev { left: 10px } .nav.next { right: 10px }
|
||||
}
|
||||
</style>
|
||||
|
|
@ -1,168 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* 全站统一的媒体缩略图。
|
||||
*
|
||||
* 之前每个页面各自写 <img class="mini"> / <video muted> / <audio controls>,
|
||||
* 于是同一张关键帧在资产库里能放大、在时间线里是灰块。这里统一:
|
||||
* 图片 → 后端缩略图 + 懒加载 + 失败占位;视频 → 后端抽帧当封面(失败才退回 <video>);
|
||||
* 音频 → 统一 AudioPlay;其它 → 文件占位。
|
||||
* 点击默认交给全局预览器(可带队列,实现 ←/→ 翻页),预览器看的仍是**原图/原视频**。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { iconFor, kindLabel, normalize, placeholderFor, thumbUrl, THUMB_PX, type MediaItem } from '../media'
|
||||
import { canManageVersions, openPreview, versionPanelOpen } from '../preview'
|
||||
import AudioPlay from './AudioPlay.vue'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
src?: string
|
||||
item?: MediaItem | null
|
||||
kind?: string
|
||||
mime?: string
|
||||
poster?: string
|
||||
title?: string
|
||||
size?: 'xs' | 'sm' | 'md' | 'lg'
|
||||
width?: string
|
||||
radius?: number
|
||||
clickable?: boolean
|
||||
badge?: string
|
||||
queue?: any[]
|
||||
index?: number
|
||||
inlineAudio?: boolean
|
||||
}>(), {
|
||||
src: '', item: null, kind: '', mime: '', poster: '', title: '',
|
||||
size: 'md', width: '100%', radius: 8, clickable: true, badge: '',
|
||||
queue: undefined, index: 0, inlineAudio: true
|
||||
})
|
||||
|
||||
const emit = defineEmits<{ (e: 'open', item: MediaItem): void }>()
|
||||
|
||||
const failed = ref(false)
|
||||
const posterFailed = ref(false)
|
||||
const resolved = computed<MediaItem | null>(() => {
|
||||
if (props.item) return props.item
|
||||
if (!props.src) return null
|
||||
return normalize({ url: props.src, kind: props.kind, mime: props.mime, name: props.title },
|
||||
{ kind: props.kind, poster: props.poster })
|
||||
})
|
||||
const kind = computed(() => resolved.value?.kind || 'none')
|
||||
const url = computed(() => resolved.value?.url || '')
|
||||
const cover = computed(() => props.poster || resolved.value?.poster || '')
|
||||
|
||||
/** 卡片实际显示的像素宽(按 2x 屏放大)→ 只下载这一档缩略图,不再拉原图 */
|
||||
const pixels = computed(() => THUMB_PX[props.size] || 384)
|
||||
const imageSrc = computed(() => thumbUrl(url.value, pixels.value))
|
||||
/** 视频封面:有明确 poster(通常是关键帧)优先,否则用后端从视频里抽的一帧 */
|
||||
const posterSrc = computed(() => (cover.value ? thumbUrl(cover.value, pixels.value) : imageSrc.value))
|
||||
|
||||
watch(url, () => { failed.value = false; posterFailed.value = false })
|
||||
|
||||
const media = computed(() => resolved.value)
|
||||
const isImage = computed(() => kind.value === 'image')
|
||||
const isVideo = computed(() => kind.value === 'video')
|
||||
const isAudio = computed(() => kind.value === 'audio')
|
||||
const showFail = computed(() => failed.value || !url.value)
|
||||
|
||||
function click() {
|
||||
if (!props.clickable) return
|
||||
const target = media.value
|
||||
if (!target) return
|
||||
if (props.queue && props.queue.length) openPreview(props.queue, props.index)
|
||||
else openPreview([target], 0)
|
||||
emit('open', target)
|
||||
}
|
||||
|
||||
const label = computed(() => props.title || media.value?.title || kindLabel(kind.value))
|
||||
|
||||
/* 多版素材的角标:以前只写「v4」,没人知道点它管理版本,甚至版本被删回
|
||||
v1 时角标直接消失。这里改成「v4 · 4版」并让它直接把预览器的版本管理打开。 */
|
||||
const versionCount = computed(() => media.value?.versions?.length || 0)
|
||||
const manageable = computed(() => versionCount.value > 1 && canManageVersions(media.value))
|
||||
const showVer = computed(() => versionCount.value > 1 || (media.value?.version || 1) > 1)
|
||||
const verBadge = computed(() => {
|
||||
const v = media.value?.version || 1
|
||||
return versionCount.value > 1 ? `v${v} · ${versionCount.value}版` : `v${v}`
|
||||
})
|
||||
|
||||
function openVersions(event: MouseEvent) {
|
||||
event.stopPropagation()
|
||||
if (!manageable.value) return
|
||||
click()
|
||||
versionPanelOpen.value = true
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="mt" :class="[size, { click: clickable }]" :style="{ width }"
|
||||
:role="clickable ? 'button' : undefined" :tabindex="clickable ? 0 : undefined"
|
||||
:aria-label="clickable ? '放大查看:' + label : undefined"
|
||||
@click="click"
|
||||
@keydown.enter.prevent="click">
|
||||
<template v-if="isAudio && inlineAudio">
|
||||
<AudioPlay :src="url" :label="label" :duration-ms="media?.raw?.duration_ms" :size="size === 'xs' ? 'sm' : 'md'" />
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="frame" :style="{ borderRadius: radius + 'px' }">
|
||||
<img v-if="isImage && !showFail" :src="imageSrc" :alt="label" loading="lazy" decoding="async"
|
||||
@error="failed = true" />
|
||||
<img v-else-if="isVideo && !showFail && posterSrc && !posterFailed" :src="posterSrc" :alt="label"
|
||||
loading="lazy" decoding="async" @error="posterFailed = true" />
|
||||
<video v-else-if="isVideo && !showFail" :src="url" muted playsinline preload="metadata"
|
||||
@error="failed = true"></video>
|
||||
<div v-if="showFail" class="fail">
|
||||
<b>{{ iconFor(kind) }}</b>
|
||||
<small>{{ placeholderFor(kind) }}</small>
|
||||
</div>
|
||||
<span v-if="isVideo && !showFail" class="play" aria-hidden="true">▶</span>
|
||||
<span v-if="isAudio" class="audiochip" aria-hidden="true">♫ {{ label }}</span>
|
||||
<slot name="badge">
|
||||
<span v-if="badge" class="badge">{{ badge }}</span>
|
||||
</slot>
|
||||
<button v-if="showVer" class="ver" :class="{ link: manageable }" type="button"
|
||||
:title="manageable ? `共 ${versionCount} 个版本,点击管理(设为默认 / 删除)` : `当前 v${media?.version}`"
|
||||
@click.stop="openVersions">{{ verBadge }}</button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.mt { display: block; min-width: 0 }
|
||||
.mt.click { cursor: pointer }
|
||||
.frame {
|
||||
position: relative; overflow: hidden; background: var(--c-bg-sunken);
|
||||
border: 1px solid var(--c-line); width: 100%;
|
||||
}
|
||||
.xs .frame { height: 34px }
|
||||
.sm .frame { height: 64px }
|
||||
.md .frame { height: 118px }
|
||||
.lg .frame { height: 172px }
|
||||
.frame img, .frame video { display: block; width: 100%; height: 100%; object-fit: cover }
|
||||
.mt.click:hover .frame { border-color: var(--c-accent-line); box-shadow: 0 0 0 2px var(--c-accent-tint) }
|
||||
.fail {
|
||||
position: absolute; inset: 0; display: grid; place-content: center; gap: 3px; justify-items: center;
|
||||
text-align: center; padding: 6px; background: var(--c-bg-sunken); color: var(--c-text-faint);
|
||||
}
|
||||
.fail b { font-size: 15px; font-weight: 500; color: var(--c-text-muted) }
|
||||
.fail small { font-size: 10px; line-height: 1.35 }
|
||||
.play {
|
||||
position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%);
|
||||
display: grid; place-items: center; width: 26px; height: 26px; border-radius: 50%;
|
||||
background: rgba(0, 0, 0, .58); color: #fff; font-size: 10px; pointer-events: none;
|
||||
}
|
||||
.md .play, .lg .play { width: 34px; height: 34px; font-size: 12px }
|
||||
.badge {
|
||||
position: absolute; right: 4px; top: 4px; font-size: 10px; padding: 2px 5px; border-radius: 5px;
|
||||
background: var(--c-scrim); color: #fff;
|
||||
}
|
||||
.ver {
|
||||
position: absolute; left: 4px; bottom: 4px; font: inherit; font-size: 10px; padding: 1px 5px; border-radius: 5px;
|
||||
background: var(--c-scrim); color: #fff; letter-spacing: .3px; line-height: 1.45;
|
||||
}
|
||||
.ver.link { cursor: pointer }
|
||||
.ver.link:hover { background: var(--c-accent-fill); color: var(--c-on-accent) }
|
||||
.audiochip {
|
||||
position: absolute; left: 4px; top: 4px; font-size: 10px; padding: 2px 5px; border-radius: 5px;
|
||||
background: var(--c-scrim); color: #fff; max-width: calc(100% - 8px);
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -1,439 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* 「录一段音」:声音样本 / 克隆参考音色的第二个入口(第一个是上传文件)。
|
||||
*
|
||||
* 交互改成弹出小面板:录制 → 试听 → 保存三步在一个面板里走完。
|
||||
* 之前控件是内联在表单行里的,录起来整行被撑开、试听条只有 96px,
|
||||
* 录完连「存成哪条素材」都没得选,只能被动接受组件猜的文件名。
|
||||
*/
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
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 '../recorder'
|
||||
import { fmtMs } from '../format'
|
||||
import { beginRecordingSheet } from '../recordingGuard'
|
||||
import AudioPlay from './AudioPlay.vue'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
/** 触发按钮文案 */
|
||||
label?: string
|
||||
/** 这段录音最终会变成什么(保存按钮文案,和实际入库的登记类型保持一致) */
|
||||
target?: string
|
||||
disabled?: boolean
|
||||
/** 面板顶部说明 */
|
||||
hint?: string
|
||||
/** 已存在的素材名:选它 = 追加为下一个版本,写新名 = 新建一条素材 */
|
||||
names?: string[]
|
||||
/** 默认存到哪条素材(不传用 target) */
|
||||
defaultName?: string
|
||||
}>(), {
|
||||
label: '录制', target: '新版本', disabled: false, names: () => [], defaultName: '',
|
||||
hint: '用麦克风录一段真人声音,录完自动转成 WAV 上传',
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'pick', file: File, meta: {
|
||||
durationMs: number; warning: string; name: string; setCurrent: boolean;
|
||||
fileSizeBytes: number
|
||||
}): void
|
||||
}>()
|
||||
|
||||
type Stage = 'idle' | 'recording' | 'preview'
|
||||
const open = ref(false)
|
||||
const stage = ref<Stage>('idle')
|
||||
const elapsed = ref(0)
|
||||
const level = ref(0)
|
||||
const error = ref('')
|
||||
const busy = ref('')
|
||||
const taking = ref<Recording | null>(null)
|
||||
const saveName = ref('')
|
||||
const setCurrent = ref(true)
|
||||
let session: RecordingSession | null = null
|
||||
let meter: number | null = null
|
||||
/** 一次「开始录制」的代次:关面板/清空后,迟到的授权结果必须作废 */
|
||||
let runId = 0
|
||||
/** 正在等系统授权框时的已等毫秒(0 = 没在等) */
|
||||
const awaiting = ref(0)
|
||||
/** 本次录音里出现过的最高电平:几秒还是平的,说明声音根本没进来 */
|
||||
let peakSeen = 0
|
||||
const previewUrl = ref('')
|
||||
/** 面板开着就把页面轮询按住(见 recordingGuard):卡片被刷新重建会连本组件一起卸载 */
|
||||
let releaseSheet: (() => void) | null = null
|
||||
watch(open, (v) => {
|
||||
if (v) releaseSheet = releaseSheet || beginRecordingSheet()
|
||||
else if (releaseSheet) { releaseSheet(); releaseSheet = null }
|
||||
})
|
||||
/** 每个实例一个 datalist id:同屏多个录音入口时不能共用 */
|
||||
const listId = `rec-names-${Math.random().toString(36).slice(2, 8)}`
|
||||
|
||||
const maxSec = computed(() => Math.round(MAX_RECORD_MS / 1000))
|
||||
const minSec = computed(() => Math.round(MIN_RECOMMENDED_MS / 1000))
|
||||
/** 已经在录、但一直没收到声音(选了错的输入设备、系统里静音、麦克风本身是坏的) */
|
||||
const silent = computed(() => stage.value === 'recording' && elapsed.value > 4_000 && peakSeen < 0.03)
|
||||
const supported = computed(() => recordingSupported())
|
||||
const blocked = computed(() => recordingBlockedReason())
|
||||
const canStart = computed(() => supported.value && !props.disabled && !busy.value)
|
||||
/** 麦克风体检结果(未探测时为 null);探测本身不打扰用户,也不拦止录音 */
|
||||
const probe = ref<MicProbe | null>(null)
|
||||
/** 探测还没回来时也要能出诊断码,这里单独留一份浏览器名 */
|
||||
const browserNote = ref(typeof navigator !== 'undefined' ? navigator.userAgent : '')
|
||||
/** 事前就能看出的毛病(系统里没麦克风 / 权限被设为阻止),没毛病时为空 */
|
||||
const preflight = computed(() => (probe.value ? micProbeHint(probe.value) : ''))
|
||||
/** 体检已确认能录:把设备名直接回显出来,省得用户猜「到底有没有麦」 */
|
||||
const micOk = computed(() => !!probe.value?.authorized)
|
||||
const micStatusText = computed(() => {
|
||||
if (!supported.value) return ''
|
||||
if (!probe.value) return '麦克风自检中…'
|
||||
if (probe.value.authorized) return `麦克风已就绪:${probe.value.devices[0]}`
|
||||
return '麦克风未就绪:见下方说明'
|
||||
})
|
||||
/** macOS 把浏览器整个挡在门外时,唯一不需要重启浏览器的解法就是这条命令 */
|
||||
const resetCmd = computed(() => (probe.value && !probe.value.authorized ? micResetCommand(probe.value) : ''))
|
||||
const copied = ref('')
|
||||
/** 提示语里用 **包起来** 的部分渲染成粗体(不动 v-html,免得中文标点被当标签吞) */
|
||||
function segs(text: string): string[] {
|
||||
return text ? text.split('**') : []
|
||||
}
|
||||
const preflightSegs = computed(() => segs(preflight.value))
|
||||
const errorSegs = computed(() => segs(error.value))
|
||||
|
||||
async function copyText(text: string, ok: string) {
|
||||
if (!text) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
copied.value = ok
|
||||
} catch {
|
||||
copied.value = text // 剪贴板被挡(非安全上下文)时至少让人能手抄
|
||||
}
|
||||
window.setTimeout(() => { copied.value = '' }, 6_000)
|
||||
}
|
||||
function copyReset() { return copyText(resetCmd.value, '命令已复制,粘到终端回车,然后回来点「重新检测」') }
|
||||
function copyDiag() {
|
||||
return copyText(`${location.origin} · ${browserNote.value} · ${rawError.value}`,
|
||||
'诊断码已复制(地址 + 浏览器 + 原始报错),发给支持即可定位')
|
||||
}
|
||||
/** 浏览器原始报错标记:中文结论之外再给一行 name · message,截图就能定位分支 */
|
||||
const rawError = ref('')
|
||||
/** 系统隐私/声音设置的直达链接:只在「还没就绪」或「刚报过错」时露出来,就绪时不占地方 */
|
||||
const settingsLinks = computed(() => (!micOk.value || !!error.value ? micSettingsLinks(probe.value) : []))
|
||||
|
||||
const knownNames = computed(() => [...new Set((props.names || []).map((x) => String(x || '').trim()).filter(Boolean))])
|
||||
|
||||
async function recheck() {
|
||||
if (!supported.value) { probe.value = null; return }
|
||||
probe.value = await probeMicrophone()
|
||||
}
|
||||
|
||||
/** 插了麦克风、改了系统权限都不用刷新页面:设备一变就重新体检 */
|
||||
function onDeviceChange() { void recheck() }
|
||||
|
||||
function onKey(ev: KeyboardEvent) {
|
||||
if (ev.key === 'Escape' && open.value) { ev.stopPropagation(); close() }
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void recheck()
|
||||
// devicechange 挂在 mediaDevices 上(不是 window):插入 USB 麦、系统改权限都会触发
|
||||
navigator.mediaDevices?.addEventListener?.('devicechange', onDeviceChange)
|
||||
window.addEventListener('keydown', onKey, true)
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
navigator.mediaDevices?.removeEventListener?.('devicechange', onDeviceChange)
|
||||
window.removeEventListener('keydown', onKey, true)
|
||||
})
|
||||
const timeText = computed(() => fmtMs(elapsed.value))
|
||||
const barHeight = computed(() => `${Math.max(6, Math.round(level.value * 100))}%`)
|
||||
const warning = computed(() => taking.value?.warning || '')
|
||||
|
||||
function clearMeter() {
|
||||
if (meter !== null) window.clearInterval(meter)
|
||||
meter = null
|
||||
level.value = 0
|
||||
}
|
||||
|
||||
function revokePreview() {
|
||||
if (previewUrl.value) URL.revokeObjectURL(previewUrl.value)
|
||||
previewUrl.value = ''
|
||||
}
|
||||
|
||||
/** 打开面板:每次进来都是干净的「待录」状态,名字默认落到 target 对应的素材 */
|
||||
function openSheet() {
|
||||
error.value = ''
|
||||
rawError.value = ''
|
||||
taking.value = null
|
||||
revokePreview()
|
||||
elapsed.value = 0
|
||||
stage.value = 'idle'
|
||||
saveName.value = String(props.defaultName || props.target || '录音').trim()
|
||||
setCurrent.value = true
|
||||
open.value = true
|
||||
void recheck()
|
||||
void nextTick(() => document.querySelector<HTMLButtonElement>('.rec-sheet .rec-big')?.focus())
|
||||
}
|
||||
|
||||
function close() {
|
||||
if (stage.value === 'recording') abandon()
|
||||
runId += 1 // 录制还没起来就关面板:等的授权也别再认
|
||||
awaiting.value = 0
|
||||
open.value = false
|
||||
}
|
||||
|
||||
async function start() {
|
||||
const my = ++runId
|
||||
error.value = ''
|
||||
awaiting.value = 0
|
||||
let opened: RecordingSession | null = null
|
||||
try {
|
||||
opened = await RecordingSession.start(probe.value || await probeMicrophone(),
|
||||
(ms) => { if (my === runId) awaiting.value = ms })
|
||||
} catch (exc: any) {
|
||||
if (my !== runId) return // 等授权期间已经被关掉了,别把结论打到别的面板上
|
||||
awaiting.value = 0
|
||||
session = null
|
||||
// recorder 抛的已经是中文结论;万一还是原始 DOMException,这里再兜一层
|
||||
error.value = exc instanceof MicUnavailableError
|
||||
? exc.message
|
||||
: explainMicError(exc, probe.value || await probeMicrophone())
|
||||
rawError.value = exc instanceof MicUnavailableError ? micErrorTag(exc.cause) : micErrorTag(exc)
|
||||
void recheck() // 报错往往意味着设备/权限刚变过,顺手刷新体检结果
|
||||
return
|
||||
}
|
||||
if (my !== runId) { opened?.discard(); return } // 授权框是迟到点出来的:麦克风立刻还给系统
|
||||
awaiting.value = 0
|
||||
session = opened
|
||||
taking.value = null
|
||||
revokePreview()
|
||||
stage.value = 'recording'
|
||||
elapsed.value = 0
|
||||
peakSeen = 0
|
||||
session.onTick = (ms) => { elapsed.value = ms }
|
||||
session.setAutoStop(() => { void stop() })
|
||||
meter = window.setInterval(() => {
|
||||
level.value = session?.level() || 0
|
||||
peakSeen = Math.max(peakSeen, level.value)
|
||||
}, 60)
|
||||
}
|
||||
|
||||
/** 停止采集并把 webm/opus 转成 WAV,成功后进入试听 */
|
||||
async function stop() {
|
||||
const active = session
|
||||
if (!active) return
|
||||
session = null
|
||||
clearMeter()
|
||||
busy.value = '转码中…'
|
||||
try {
|
||||
taking.value = await active.stop()
|
||||
revokePreview()
|
||||
previewUrl.value = URL.createObjectURL(taking.value.blob)
|
||||
stage.value = 'preview'
|
||||
void nextTick(() => document.querySelector<HTMLButtonElement>('.rec-sheet .primary')?.focus())
|
||||
} catch (exc: any) {
|
||||
active.discard()
|
||||
error.value = `录音转 WAV 失败:${exc?.message || exc}。可以先用系统录音笔录好再走上传。`
|
||||
stage.value = 'idle'
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
/** 不要这段录音了:释放麦克风,回到未录状态 */
|
||||
function abandon() {
|
||||
runId += 1 // 作废还在等授权的 getUserMedia
|
||||
awaiting.value = 0
|
||||
session?.discard()
|
||||
session = null
|
||||
clearMeter()
|
||||
taking.value = null
|
||||
revokePreview()
|
||||
elapsed.value = 0
|
||||
error.value = ''
|
||||
rawError.value = ''
|
||||
stage.value = 'idle'
|
||||
}
|
||||
|
||||
function safeFileName(name: string) {
|
||||
return (String(name || '录音').replace(/[\\/:*?"<>|]+/g, '').trim() || '录音').slice(0, 40)
|
||||
}
|
||||
|
||||
function confirmUpload() {
|
||||
const rec = taking.value
|
||||
if (!rec) return
|
||||
const name = saveName.value.trim() || String(props.target || '录音')
|
||||
const file = new File([rec.blob], `${safeFileName(name)}.wav`, { type: 'audio/wav' })
|
||||
emit('pick', file, {
|
||||
durationMs: rec.durationMs, warning: rec.warning, name,
|
||||
setCurrent: setCurrent.value, fileSizeBytes: rec.blob.size,
|
||||
})
|
||||
session = null
|
||||
taking.value = null
|
||||
revokePreview()
|
||||
elapsed.value = 0
|
||||
stage.value = 'idle'
|
||||
open.value = false
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
session?.discard()
|
||||
clearMeter()
|
||||
revokePreview()
|
||||
releaseSheet?.() // 面板随列表一起没了:把轮询放开
|
||||
releaseSheet = null
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button class="outline tiny rec-trigger" :class="{ recording: stage === 'recording' }"
|
||||
:disabled="!canStart" :title="blocked || hint || '录一段真人声音'" @click="openSheet">
|
||||
🎙 {{ supported ? label : '录音不可用' }}<span v-if="stage === 'recording'" class="live">{{ timeText }}</span>
|
||||
</button>
|
||||
|
||||
<Teleport to="body">
|
||||
<div v-if="open" class="rec-mask" @click.self="close">
|
||||
<section class="rec-sheet" role="dialog" aria-modal="true" :aria-label="`录制${target}`">
|
||||
<header class="rec-head">
|
||||
<div><small class="rec-eyebrow">RECORD · {{ target }}</small>
|
||||
<h3>{{ stage === 'recording' ? '正在录制…' : (stage === 'preview' ? '试听并保存' : '录一段声音') }}</h3></div>
|
||||
<button class="rec-x" title="关闭(Esc)" @click="close">✕</button>
|
||||
</header>
|
||||
|
||||
<ol class="rec-steps">
|
||||
<li :class="{ on: stage === 'idle', done: stage !== 'idle' }">① 录制</li>
|
||||
<li :class="{ on: stage === 'recording', done: stage === 'preview' }">② 试听</li>
|
||||
<li :class="{ on: stage === 'preview' }">③ 保存</li>
|
||||
</ol>
|
||||
|
||||
<p v-if="blocked" class="rec-bad">✕ {{ blocked }}</p>
|
||||
<template v-else-if="supported">
|
||||
<p class="rec-microw" :class="micOk ? 'ok' : 'warn'">
|
||||
<span class="rec-status">{{ micOk ? '✓' : '⚠' }} {{ micStatusText }}</span>
|
||||
<span class="rec-grow"></span>
|
||||
<button class="rec-link" @click="recheck">重新检测</button>
|
||||
<button v-if="resetCmd" class="rec-link" @click="copyReset">复制修复命令</button>
|
||||
<a v-for="l in settingsLinks" :key="l.href" class="rec-link" :href="l.href">{{ l.label }}</a>
|
||||
</p>
|
||||
<p v-if="copied" class="rec-note">{{ copied }}</p>
|
||||
<p v-if="!micOk && preflight" class="rec-warn"><template v-for="(s, i) in preflightSegs"
|
||||
:key="i"><b v-if="i % 2">{{ s }}</b><template v-else>{{ s }}</template></template></p>
|
||||
</template>
|
||||
|
||||
<div class="rec-stage" :class="stage">
|
||||
<button v-if="stage !== 'recording'" class="rec-big" :disabled="!canStart" @click="start">
|
||||
🎙 {{ stage === 'idle' ? '开始录制' : '重新录制' }}
|
||||
</button>
|
||||
<button v-else class="rec-big stop" @click="stop"><span class="rec-dot"></span>停止录制</button>
|
||||
<div class="rec-meta">
|
||||
<b class="rec-time">{{ timeText }}</b>
|
||||
<span v-if="stage === 'recording'" class="rec-meter" title="麦克风电平"><i :style="{ height: barHeight }"></i></span>
|
||||
<span class="rec-limit">{{ stage === 'preview'
|
||||
? '已录好,点下面的 ▶ 试听确认后再保存'
|
||||
: `建议念满 ${minSec} 秒 · 上限 ${maxSec} 秒自动停止` }}</span>
|
||||
</div>
|
||||
<p v-if="silent" class="rec-warn">已经录了 {{ Math.round(elapsed / 1000) }} 秒还没收到声音:
|
||||
麦克风可能被静音,或选错了输入设备。点「停止录制」后重录。</p>
|
||||
<p v-if="awaiting" class="rec-warn">⏳ 正在等系统授权(已等 {{ Math.ceil(awaiting / 1000) }} 秒):
|
||||
授权框{{ probe?.macos ? '在屏幕左下角,不在网页里' : '在地址栏左侧' }},
|
||||
看不到就把这个浏览器切到最前面再点一次;超过
|
||||
{{ Math.round(MIC_WAIT_MS / 1000) }} 秒没点会自动取消。</p>
|
||||
<p v-if="busy" class="rec-note">转码中,请稍候…</p>
|
||||
<p v-if="error" class="rec-bad"><template v-for="(s, i) in errorSegs" :key="i">
|
||||
<b v-if="i % 2">{{ s }}</b><template v-else>{{ s }}</template></template></p>
|
||||
<p v-if="error && rawError" class="rec-raw">浏览器原始报错 <code>{{ rawError }}</code>
|
||||
<button class="rec-link" @click="copyDiag">复制诊断码</button></p>
|
||||
</div>
|
||||
|
||||
<div v-if="stage === 'preview'" class="rec-save">
|
||||
<AudioPlay :src="previewUrl" label="刚才的录音" :duration-ms="taking?.durationMs || 0"
|
||||
size="sm" :cover="false" />
|
||||
<p v-if="warning" class="rec-warn">{{ warning }}</p>
|
||||
<label class="rec-field">存到哪条素材
|
||||
<input v-model="saveName" :list="listId" placeholder="素材名称" title="选已有名称=追加成它的下一个版本(之后可删版本 / 设为当前版本);写新名称=新建一条素材" />
|
||||
<datalist :id="listId"><option v-for="n in knownNames" :key="n" :value="n" /></datalist>
|
||||
</label>
|
||||
<label class="rec-check"><input v-model="setCurrent" type="checkbox" />保存后设为当前版本</label>
|
||||
</div>
|
||||
|
||||
<footer class="rec-foot">
|
||||
<button class="outline tiny" :disabled="stage === 'recording'" @click="close">取消</button>
|
||||
<button v-if="stage !== 'idle'" class="outline tiny" @click="abandon">清空重录</button>
|
||||
<span class="rec-grow"></span>
|
||||
<button v-if="stage === 'recording'" class="secondary tiny" @click="stop">■ 停止并试听</button>
|
||||
<button v-else class="primary tiny" :disabled="stage !== 'preview' || !!busy || !saveName.trim()"
|
||||
@click="confirmUpload">✓ 存为{{ target }}</button>
|
||||
</footer>
|
||||
</section>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.rec-trigger { white-space: nowrap }
|
||||
.rec-trigger.recording { border-color: var(--c-danger-line); background: var(--c-danger-tint); color: var(--c-danger) }
|
||||
.rec-trigger .live { margin-left: 6px; font-variant-numeric: tabular-nums }
|
||||
|
||||
.rec-mask { position: fixed; inset: 0; z-index: 260; display: grid; place-items: center; padding: 16px;
|
||||
background: var(--c-scrim); backdrop-filter: blur(3px) }
|
||||
.rec-sheet { width: min(430px, 100%); display: flex; flex-direction: column; gap: 10px; padding: 14px;
|
||||
border: 1px solid var(--c-line); border-radius: 14px; background: var(--c-bg-panel);
|
||||
box-shadow: 0 24px 60px rgba(0, 0, 0, .42) }
|
||||
.rec-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 10px }
|
||||
.rec-head h3 { margin: 3px 0 0; font-size: 15px }
|
||||
.rec-eyebrow { font-size: 10px; letter-spacing: .1em; color: var(--c-text-faint) }
|
||||
.rec-x { border: 0; background: none; color: var(--c-text-faint); font-size: 14px; cursor: pointer; padding: 2px 4px }
|
||||
.rec-x:hover { color: var(--c-text) }
|
||||
|
||||
.rec-steps { display: flex; gap: 6px; list-style: none; margin: 0; padding: 0 }
|
||||
.rec-steps li { flex: 1; text-align: center; font-size: 10.5px; padding: 5px 0; border-radius: 7px;
|
||||
border: 1px solid var(--c-line); color: var(--c-text-faint); background: var(--c-bg-sunken) }
|
||||
.rec-steps li.on { border-color: var(--c-accent-line); color: var(--c-accent-bright); background: var(--c-tint-info) }
|
||||
.rec-steps li.done { color: var(--c-success); border-color: var(--c-success-line) }
|
||||
|
||||
.rec-stage { display: flex; flex-direction: column; align-items: center; gap: 8px; padding: 12px 10px;
|
||||
border: 1px dashed var(--c-line); border-radius: 11px; background: var(--c-bg-sunken) }
|
||||
.rec-stage.recording { border-color: var(--c-danger-line); border-style: solid }
|
||||
/* 面板主操作钮:比 --ctl-h 大一档(48px),录音时要点准,不能只按普通按钮档位算。
|
||||
已登记在 docs/UI规范.md §1.2.1 例外清单。 */
|
||||
.rec-big { display: inline-flex; align-items: center; justify-content: center; gap: 8px;
|
||||
height: 48px; padding: 0 20px; border-radius: 999px;
|
||||
border: 1px solid var(--c-accent-line); background: var(--c-accent-fill); color: var(--c-on-accent);
|
||||
font-size: 13px; font-weight: 700; cursor: pointer }
|
||||
.rec-big:disabled { opacity: .5; cursor: not-allowed }
|
||||
.rec-big.stop { border-color: var(--c-danger-line); background: var(--c-danger-tint); color: var(--c-danger) }
|
||||
.rec-dot { width: 9px; height: 9px; border-radius: 50%; background: currentColor; animation: rec-pulse 1s ease-in-out infinite }
|
||||
@keyframes rec-pulse { 0%, 100% { opacity: 1 } 50% { opacity: .2 } }
|
||||
.rec-meta { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; justify-content: center }
|
||||
.rec-time { font-size: 13px; font-variant-numeric: tabular-nums }
|
||||
.rec-limit { font-size: 10px; color: var(--c-text-faint) }
|
||||
.rec-meter { display: inline-flex; align-items: flex-end; width: 46px; height: 22px; padding: 2px;
|
||||
border: 1px solid var(--c-line); border-radius: 5px; background: var(--c-bg-shell) }
|
||||
.rec-meter i { display: block; width: 100%; border-radius: 3px; background: var(--c-accent-fill); transition: height .06s linear }
|
||||
|
||||
.rec-save { display: flex; flex-direction: column; gap: 8px; padding: 10px; border-radius: 11px; background: var(--c-tint-info) }
|
||||
/* 全局 label{flex-direction:column;margin:10px 0}:这两条不显式覆盖,
|
||||
勾选框会掉到文字上面、还多出 20px 上下空白,「存到哪条素材」也被撑得很松。 */
|
||||
.rec-field { display: flex; flex-direction: column; gap: 4px; font-size: 11px; margin: 0 }
|
||||
.rec-check { display: inline-flex; flex-direction: row; align-items: center; gap: 7px; width: fit-content;
|
||||
margin: 0; font-size: 11.5px; color: var(--c-text-2); cursor: pointer }
|
||||
.rec-check input { width: auto; height: auto; accent-color: var(--c-accent-fill) }
|
||||
.rec-foot { display: flex; align-items: center; gap: 8px }
|
||||
.rec-grow { flex: 1 }
|
||||
.rec-note { margin: 0; font-size: 10.5px; line-height: 1.6; color: var(--c-text-faint) }
|
||||
/* 麦克风自检行:常驻一行,就绪时绿色回显设备名,没就绪时把「复制修复命令」摆在手边 */
|
||||
.rec-microw { display: flex; flex-direction: row; align-items: center; gap: 8px; margin: 0;
|
||||
padding: 6px 8px; border-radius: 8px; font-size: 11px; border: 1px solid var(--c-line); flex-wrap: wrap }
|
||||
.rec-microw.ok { color: var(--c-success); border-color: var(--c-success-line); background: var(--c-success-tint) }
|
||||
.rec-microw.warn { color: var(--c-warn); border-color: var(--c-warn-line); background: var(--c-warn-tint) }
|
||||
.rec-status { min-width: 0; overflow-wrap: anywhere }
|
||||
.rec-warn { margin: 0; font-size: 11px; line-height: 1.6; color: var(--c-warn) }
|
||||
.rec-bad { margin: 0; font-size: 11px; line-height: 1.6; color: var(--c-danger) }
|
||||
/* 这些是行内文字链接,不是控件:nowrap 保证标签不被挤成两行(两行 15px 行盒 = 30px,
|
||||
会被控件档位审计当成「野高度」),放不下时由 .rec-microw 整行换行 */
|
||||
.rec-link { border: 0; background: none; color: var(--c-text-3); font-size: 10.5px; text-decoration: underline;
|
||||
padding: 0; white-space: nowrap; line-height: 1.45 }
|
||||
.rec-link:hover { color: var(--c-accent-bright) }
|
||||
a.rec-link { text-underline-offset: 2px }
|
||||
/* 原始报错留痕:中文结论之外再给一行可复制的诊断码,远程定位不用再猜 */
|
||||
.rec-raw { display: flex; align-items: center; gap: 7px; flex-wrap: wrap; margin: -2px 0 0;
|
||||
font-size: 10px; color: var(--c-text-faint) }
|
||||
.rec-raw code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
padding: 1px 5px; border-radius: 5px; background: var(--c-bg-sunken); border: 1px solid var(--c-line) }
|
||||
</style>
|
||||
|
|
@ -1,126 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* 全站统一的「密码 / 密钥」输入框。
|
||||
*
|
||||
* 之前四套写法各不相同:登录页和模型管理是「显示 / 隐藏」文字按钮(看不出是开关)、
|
||||
* 我的账号三个密码框压根没有开关(只能盲打)、用户管理直接 type="text" 常显。
|
||||
* 这里收敛成一个组件,规则统一:
|
||||
* · 右侧一个**眼睛图标**按钮(不是文字),点击即在密文 / 明文之间切换;
|
||||
* · 切换是真切换:input 的 type 在 password / text 之间改,浏览器会立刻重绘明文;
|
||||
* · 按下图标不抢输入框焦点(mousedown.prevent),光标位置和已选文本都不丢;
|
||||
* · 传 revealUrl 时,编辑已保存的密钥(后端只回掩码、输入框是空的)点一下图标会
|
||||
* 向后端取回真实明文并显示出来——解决「点了显示却什么都没有」。
|
||||
* 取回的明文只在「显示」期间留在输入框里:一旦切回隐藏且用户没改动,就还原成空,
|
||||
* 保存时依旧按「留空保持原密钥」的契约走,不会把明文再写回去。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import * as api from '../api'
|
||||
import EyeIcon from './EyeIcon.vue'
|
||||
|
||||
defineOptions({ inheritAttrs: false })
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue?: string
|
||||
id?: string
|
||||
placeholder?: string
|
||||
autocomplete?: string
|
||||
maxlength?: number | string
|
||||
disabled?: boolean
|
||||
/** 已经保存过密钥(用于区分「新建时留空」与「编辑时未改动」) */
|
||||
hasSaved?: boolean
|
||||
/** 取回明文的接口;不传就只做本地密文/明文切换 */
|
||||
revealUrl?: string
|
||||
}>(), {
|
||||
modelValue: '', id: '', placeholder: '••••••••', autocomplete: 'current-password',
|
||||
maxlength: 200, disabled: false, hasSaved: false, revealUrl: '',
|
||||
})
|
||||
const emit = defineEmits<{ (e: 'update:modelValue', value: string): void }>()
|
||||
|
||||
const shown = ref(false)
|
||||
const loading = ref(false)
|
||||
const stored = ref('')
|
||||
/** 输入框当前内容是不是「刚从后端取回的明文」——是的话隐藏时清回去 */
|
||||
const seeded = ref(false)
|
||||
const failed = ref('')
|
||||
|
||||
const display = computed(() => props.modelValue)
|
||||
|
||||
watch(() => props.modelValue, (value) => {
|
||||
// 用户改动过内容就别再自动清空,否则会把人家编辑了一半的密钥抹掉
|
||||
if (seeded.value && value !== stored.value) seeded.value = false
|
||||
})
|
||||
|
||||
async function reveal() {
|
||||
if (loading.value) return
|
||||
if (shown.value) {
|
||||
if (seeded.value && props.modelValue === stored.value) emit('update:modelValue', '')
|
||||
seeded.value = false
|
||||
shown.value = false
|
||||
return
|
||||
}
|
||||
// 编辑态且输入框为空 → 后端存的那把才是用户想看的,取回来再显示
|
||||
if (!props.modelValue && props.revealUrl && props.hasSaved && !stored.value) {
|
||||
loading.value = true
|
||||
failed.value = ''
|
||||
try {
|
||||
const data: any = await api.get(props.revealUrl)
|
||||
stored.value = String(data?.api_key || '')
|
||||
if (stored.value) { emit('update:modelValue', stored.value); seeded.value = true }
|
||||
else failed.value = '这条模型没有保存密钥'
|
||||
} catch (exc: any) {
|
||||
failed.value = exc?.message || String(exc)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
shown.value = true
|
||||
}
|
||||
|
||||
const hint = computed(() => {
|
||||
if (loading.value) return '正在读取已保存的密钥…'
|
||||
if (shown.value) return '隐藏密码'
|
||||
return props.revealUrl && props.hasSaved && !props.modelValue
|
||||
? '显示密码:读取已保存的明文' : '显示密码'
|
||||
})
|
||||
|
||||
defineExpose({ shown, stored, failed })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span class="secret">
|
||||
<input :id="id || undefined" :value="display"
|
||||
:type="shown ? 'text' : 'password'" :placeholder="placeholder"
|
||||
:autocomplete="autocomplete" :maxlength="maxlength" :disabled="disabled"
|
||||
:aria-describedby="failed ? `${id || 'secret'}-hint` : undefined"
|
||||
v-bind="$attrs"
|
||||
@input="emit('update:modelValue', ($event.target as HTMLInputElement).value)" />
|
||||
<button class="eye" type="button" :class="{ on: shown, busy: loading }" :disabled="disabled"
|
||||
:aria-label="hint" :aria-pressed="shown" :title="hint"
|
||||
@mousedown.prevent="() => {}" @click="reveal">
|
||||
<EyeIcon :shown="shown" :loading="loading" />
|
||||
</button>
|
||||
<small v-if="failed" :id="`${id || 'secret'}-hint`" class="secret-hint">{{ failed }}</small>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.secret {
|
||||
--secret-eye-right: 34px;
|
||||
--secret-pad: 62px;
|
||||
position: relative; display: block; width: 100%; min-width: 0 }
|
||||
/* Chrome 128+ / Edge 会在密码框**最右侧**画自己的「钥匙(选择已保存的密码)」图标,
|
||||
正好压在原来的眼睛上:用户点上去弹的是浏览器下拉,密码永远显示不出来。
|
||||
这里不依赖厂商私有伪元素,直接给浏览器图标留出 34px 通道,把眼睛挪到它左边,
|
||||
并让出等宽的 padding,保证两种图标谁都不遮谁、谁都能点。 */
|
||||
.secret input { padding-right: var(--secret-pad) }
|
||||
.secret .eye {
|
||||
position: absolute; right: var(--secret-eye-right); top: 50%; transform: translateY(-50%);
|
||||
width: 26px; height: 26px; padding: 0; display: grid; place-items: center; cursor: pointer;
|
||||
border: 1px solid var(--c-line); border-radius: 6px;
|
||||
background: var(--c-bg-raise); color: var(--c-text-3);
|
||||
}
|
||||
.secret .eye:hover { color: var(--c-text); border-color: var(--c-line-strong) }
|
||||
.secret .eye.on { color: var(--c-accent-bright); border-color: var(--c-accent-line); background: var(--c-accent-tint2) }
|
||||
.secret .eye:focus-visible { outline: 2px solid var(--c-accent-deep); outline-offset: 1px }
|
||||
.secret-hint { display: block; margin-top: 5px; color: var(--c-warn-bright); font-size: 10px }
|
||||
</style>
|
||||
|
|
@ -1,148 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* 版本管理抽屉(挂在预览器右侧)。
|
||||
*
|
||||
* 之前「设为默认 / 删除某一版」只能先在预览器顶部下拉里逐版切换再点按钮,
|
||||
* 入口太隐蔽:想删掉中间某一版,得先把它翻出来预览。这里把全部版本摊成一列,
|
||||
* 每一行自带「设为默认 / 删除」,不用来回切版本。
|
||||
* 动作复用 preview.ts 里的 setCurrentVersion / deleteVersion —— 平台母版和
|
||||
* 项目资产走的是两个接口,逻辑只有一份。
|
||||
*/
|
||||
import { computed } from 'vue'
|
||||
import { fmtBytes, fmtTime } from '../format'
|
||||
import { thumbUrl } from '../media'
|
||||
import { chooseVersion, current, deleteVersion, setCurrentVersion, versionBusy, versionChoice, viewedVersion } from '../preview'
|
||||
|
||||
const emit = defineEmits<{ (e: 'close'): void }>()
|
||||
|
||||
const item = current
|
||||
const kind = computed(() => item.value?.kind || 'none')
|
||||
/** 新版本在上,和下拉里的顺序一致 */
|
||||
const rows = computed(() => [...(item.value?.versions || [])].sort((a, b) => b.version_no - a.version_no))
|
||||
const currentNo = computed(() => item.value?.version || 1)
|
||||
const chosen = computed(() => (item.value ? versionChoice.value[item.value.key] || currentNo.value : 0))
|
||||
const previewing = computed(() => viewedVersion(item.value)?.version_no || 0)
|
||||
const onlyOne = computed(() => rows.value.length < 2)
|
||||
|
||||
function coverOf(url: string) {
|
||||
return kind.value === 'image' || kind.value === 'video' ? thumbUrl(url, 128) : ''
|
||||
}
|
||||
|
||||
function infoOf(row: any) {
|
||||
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(' · ') || '—'
|
||||
}
|
||||
|
||||
function preview(row: any) {
|
||||
chooseVersion(row.version_no)
|
||||
}
|
||||
|
||||
function makeCurrent(row: any) {
|
||||
if (row.exists === false || row.current) return
|
||||
void setCurrentVersion(row.version_no)
|
||||
}
|
||||
|
||||
function remove(row: any) {
|
||||
if (!item.value || onlyOne.value) return
|
||||
const fileNote = row.exists === false ? '该版本的文件已经不在磁盘上,这次只清理记录。' : '该版本的记录与文件会一并删除,不可恢复。'
|
||||
const tail = row.current || row.version_no === currentNo.value ? '它正是当前默认版本,删除后自动回落到剩余最新版本。' : ''
|
||||
const ask = `确认删除「${item.value.title}」的 v${row.version_no}?${fileNote}${tail}`
|
||||
if (window.confirm(ask)) void deleteVersion(row.version_no)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside v-if="item" class="vp" role="complementary" :aria-label="'版本管理:' + item.title">
|
||||
<header class="vp-head">
|
||||
<div class="grow">
|
||||
<p class="eyebrow">VERSIONS · 版本管理</p>
|
||||
<h4>{{ item.title }}</h4>
|
||||
<p class="cnt">共 {{ rows.length }} 版 · 当前默认 <b class="mono">v{{ currentNo }}</b></p>
|
||||
</div>
|
||||
<button class="ghost tiny" title="关闭版本管理" @click="emit('close')">✕</button>
|
||||
</header>
|
||||
|
||||
<p class="vp-note">
|
||||
<b>设为默认</b>:平台母版与之后引入项目的素材都取这一版;项目里已锁定的快照不会自动改版。<br />
|
||||
<b>删除</b>:连同文件一起清理;若仍被生成记录引用,只删记录并保留文件。
|
||||
</p>
|
||||
|
||||
<div class="vp-list">
|
||||
<div v-for="row in rows" :key="row.version_no" class="vp-row"
|
||||
:class="{ on: row.version_no === previewing, def: row.version_no === currentNo, gone: row.exists === false }">
|
||||
<button class="vp-thumb" :title="'预览 v' + row.version_no" @click="preview(row)">
|
||||
<img v-if="coverOf(row.url)" :src="coverOf(row.url)" :alt="'v' + row.version_no" loading="lazy" decoding="async" />
|
||||
<b v-else>{{ kind === 'audio' ? '♫' : kind === 'video' ? '▶' : '▤' }}</b>
|
||||
</button>
|
||||
<div class="vp-main">
|
||||
<div class="vp-line">
|
||||
<b class="mono vp-no">v{{ row.version_no }}</b>
|
||||
<span v-if="row.version_no === currentNo" class="tag ok">当前默认</span>
|
||||
<span v-if="row.version_no === previewing" class="tag">预览中</span>
|
||||
<span v-if="row.exists === false" class="tag bad">文件已丢失</span>
|
||||
</div>
|
||||
<p class="vp-meta mono">{{ fmtTime(row.created_at) }} · {{ infoOf(row) }}</p>
|
||||
<p v-if="row.note" class="vp-note-line">{{ row.note }}</p>
|
||||
</div>
|
||||
<div class="vp-acts">
|
||||
<button class="ghost tiny" :disabled="row.version_no === previewing || versionBusy"
|
||||
:title="row.version_no === previewing ? '已经在预览这一版' : '切到这一版看看'"
|
||||
@click="preview(row)">预览</button>
|
||||
<button class="ghost tiny star" :disabled="row.version_no === currentNo || row.exists === false || versionBusy"
|
||||
:title="row.version_no === currentNo ? '这一版已经是当前默认'
|
||||
: (row.exists === false ? '文件已丢失,无法设为默认,可以先删掉它' : '把这一版设为当前默认版本')"
|
||||
@click="makeCurrent(row)">{{ versionBusy ? '处理中…' : '★ 设为默认' }}</button>
|
||||
<button class="btn-del" :disabled="onlyOne || versionBusy"
|
||||
:title="onlyOne ? '只剩一个版本,如需清理请直接删除该素材' : '删除这一版(含文件),不可恢复'"
|
||||
@click="remove(row)">删除</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</aside>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 抽屉贴在预览舞台右侧:不遮挡顶部的版本下拉,也不改弹窗整体尺寸 */
|
||||
.vp {
|
||||
position: absolute; z-index: 3; top: 0; right: 0; bottom: 0; width: min(400px, 74%);
|
||||
display: flex; flex-direction: column; min-height: 0; gap: 8px; padding: 11px 12px;
|
||||
border-left: 1px solid var(--c-line-strong); background: var(--c-bg-panel);
|
||||
box-shadow: -14px 0 30px var(--c-shade-2);
|
||||
}
|
||||
.vp-head { display: flex; gap: 8px; align-items: flex-start; flex: 0 0 auto }
|
||||
.vp-head p { margin: 0 }
|
||||
.vp-head h4 { margin: 2px 0 0; font-size: 13px; line-height: 1.3; word-break: break-all }
|
||||
.grow { flex: 1 1 auto; min-width: 0 }
|
||||
.cnt { margin: 4px 0 0; font-size: 10px; color: var(--c-text-3) }
|
||||
.cnt b { color: var(--c-accent-bright) }
|
||||
.vp-note { margin: 0; flex: 0 0 auto; padding: 7px 8px; border: 1px solid var(--c-line); border-radius: 8px;
|
||||
background: var(--c-bg-sunken); font-size: 10px; line-height: 1.55; color: var(--c-text-3) }
|
||||
.vp-note b { color: var(--c-text-2) }
|
||||
.vp-list { flex: 1 1 auto; min-height: 0; overflow: auto; display: flex; flex-direction: column; gap: 6px;
|
||||
margin: 0 -4px; padding: 0 4px }
|
||||
.vp-row { display: flex; gap: 8px; align-items: flex-start; padding: 7px; border: 1px solid var(--c-line);
|
||||
border-radius: 9px; background: var(--c-bg-card) }
|
||||
.vp-row.on { border-color: var(--c-accent-line); background: var(--c-accent-tint) }
|
||||
.vp-row.def { border-left: 2px solid var(--c-accent-line) }
|
||||
.vp-row.gone { opacity: .72 }
|
||||
.vp-thumb { flex: 0 0 auto; width: 52px; height: 40px; padding: 0; overflow: hidden; border: 1px solid var(--c-line);
|
||||
border-radius: 7px; background: var(--c-bg-sunken); color: var(--c-text-muted); font-size: 15px;
|
||||
display: grid; place-items: center; cursor: zoom-in }
|
||||
.vp-thumb img { width: 100%; height: 100%; object-fit: cover; display: block }
|
||||
.vp-main { flex: 1 1 auto; min-width: 0 }
|
||||
.vp-line { display: flex; align-items: center; gap: 5px; flex-wrap: wrap }
|
||||
.vp-no { font-size: 11.5px; font-weight: 700; color: var(--c-text) }
|
||||
.vp-meta { margin: 3px 0 0; font-size: 10px; color: var(--c-text-faint); overflow: hidden; text-overflow: ellipsis; white-space: nowrap }
|
||||
.vp-note-line { margin: 3px 0 0; font-size: 10px; color: var(--c-text-3); overflow: hidden; text-overflow: ellipsis; white-space: nowrap }
|
||||
.vp-acts { display: flex; flex-direction: column; gap: 4px; flex: 0 0 auto; align-items: stretch }
|
||||
.vp-acts .ghost, .vp-acts .btn-del { justify-content: center; width: 84px }
|
||||
.tag { font-size: 10px; padding: 1px 5px; border-radius: 5px; border: 1px solid var(--c-line-strong);
|
||||
color: var(--c-text-3); background: var(--c-bg-sunken) }
|
||||
.tag.ok { color: var(--c-accent-bright); border-color: var(--c-accent-line); background: var(--c-accent-tint) }
|
||||
.tag.bad { color: var(--c-danger-bright); border-color: var(--c-danger-line) }
|
||||
.muted { color: var(--c-text-faint) }
|
||||
</style>
|
||||
|
|
@ -1,112 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* 12 节点流程条(GL-1)。
|
||||
*
|
||||
* 流程条比屏幕宽时以前只是「能横向滚」,但没有任何提示,
|
||||
* 用户以为只有 8 个节点;而且当前节点常常在滚动区外。
|
||||
* 现在:右缘渐隐提示还有内容 + 自动把「进行中 / 需处理」的节点滚进视野 +
|
||||
* 节点 title 悬浮出完整说明(compact 模式也不会丢信息)。
|
||||
*/
|
||||
import { computed, nextTick, onMounted, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { allNodesDone, openNode } from '../pipeline'
|
||||
|
||||
const props = defineProps<{ workflow: any[] | null | undefined; compact?: boolean }>()
|
||||
|
||||
const stages = computed(() => props.workflow || [])
|
||||
const rail = ref<HTMLElement | null>(null)
|
||||
const stateLabel: Record<string, string> = {
|
||||
done: '完成', failed: '需处理', active: '进行中', pending: '待处理'
|
||||
}
|
||||
function icon(state: string, index: number) {
|
||||
if (state === 'done') return '✓'
|
||||
if (state === 'failed') return '!'
|
||||
if (state === 'active') return '▶'
|
||||
return String(index + 1)
|
||||
}
|
||||
/** 后端没有计数的节点显示中文状态;有计数的节点显示 done/total 并夹住分母 */
|
||||
function progress(node: any) {
|
||||
if (node.done === null || node.done === undefined) return stateLabel[node.state] || node.state
|
||||
return `${Math.min(node.done, node.total)}/${node.total}`
|
||||
}
|
||||
const currentKey = computed(() => openNode(stages.value)?.key || '')
|
||||
const flowDone = computed(() => allNodesDone(stages.value))
|
||||
const currentLabel = computed(() => (stages.value.find((s: any) => s.key === currentKey.value) || {}).label || '')
|
||||
const doneCount = computed(() => stages.value.filter((s: any) => s.state === 'done').length)
|
||||
function hint(node: any) {
|
||||
return [`${node.label}(${stateLabel[node.state] || node.state})`, node.detail].filter(Boolean).join(' — ')
|
||||
}
|
||||
|
||||
/** 流程条是否真的需要横向滚动:只有需要滚的时候才显示两侧渐隐,否则渐隐像渲染残留 */
|
||||
const overflowing = ref(false)
|
||||
let ro: ResizeObserver | null = null
|
||||
function measure() {
|
||||
const box = rail.value
|
||||
if (!box) return
|
||||
overflowing.value = box.scrollWidth - box.clientWidth > 2
|
||||
}
|
||||
onMounted(() => {
|
||||
measure()
|
||||
if (typeof ResizeObserver !== 'undefined' && rail.value) {
|
||||
ro = new ResizeObserver(measure)
|
||||
ro.observe(rail.value)
|
||||
if (rail.value.firstElementChild) ro.observe(rail.value.firstElementChild)
|
||||
}
|
||||
})
|
||||
onBeforeUnmount(() => { ro?.disconnect(); ro = null })
|
||||
|
||||
/** 把当前节点滚到可视区中间;只在流程变化时做一次,不打断用户手动滚动 */
|
||||
async function revealCurrent() {
|
||||
await nextTick()
|
||||
const box = rail.value
|
||||
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()
|
||||
}
|
||||
onMounted(() => { void revealCurrent() })
|
||||
watch(currentKey, () => { void revealCurrent() })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="rail-wrap" :class="{ scrollable: overflowing }">
|
||||
<div ref="rail" class="steps" role="list">
|
||||
<div v-for="(s, i) in stages" :key="s.key" class="step" :class="s.state" role="listitem"
|
||||
:data-current="s.key === currentKey ? '1' : undefined" :title="hint(s)">
|
||||
<div class="stephead">
|
||||
<span class="stepnum">{{ icon(s.state, i) }}</span>
|
||||
<span>{{ progress(s) }}</span>
|
||||
</div>
|
||||
<div class="steplabel">{{ s.label }}</div>
|
||||
<div v-if="!compact" class="stepdetail">{{ s.detail }}</div>
|
||||
</div>
|
||||
<div v-if="!stages.length" class="step pending">
|
||||
<div class="steplabel">暂无流程数据</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="stages.length" class="rail-caption">
|
||||
<small class="val">已完成 {{ doneCount }} / {{ stages.length }} 个节点<template v-if="currentKey"> · 当前:{{ currentLabel }}</template><template v-else-if="flowDone"> · 流程已全部完成</template></small>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.rail-wrap { position: relative; }
|
||||
/* 右缘渐隐:明确告诉用户流程条还能往右滚 */
|
||||
.rail-wrap.scrollable::after {
|
||||
content: ""; position: absolute; top: 0; right: 0; bottom: 16px; width: 46px;
|
||||
pointer-events: none; border-radius: 0 9px 9px 0;
|
||||
background: linear-gradient(90deg, rgba(0, 0, 0, 0), var(--c-bg-panel));
|
||||
}
|
||||
.rail-wrap.scrollable::before {
|
||||
content: ""; position: absolute; top: 0; left: 0; bottom: 16px; width: 22px;
|
||||
pointer-events: none; border-radius: 9px 0 0 9px;
|
||||
background: linear-gradient(270deg, rgba(0, 0, 0, 0), var(--c-bg-panel));
|
||||
}
|
||||
.steps { scroll-behavior: smooth; scrollbar-width: thin; }
|
||||
.step { cursor: default; }
|
||||
.step[data-current="1"] { box-shadow: 0 0 0 1px var(--c-accent-line); }
|
||||
.rail-caption { margin-top: 2px; }
|
||||
.rail-caption small { color: var(--c-text-muted); font-size: 10px; }
|
||||
</style>
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
import { CARET_PATH, caretCls } from './parts'
|
||||
|
||||
/** 统一的下拉箭头(Select / MultiSelect 共用一份几何) */
|
||||
export function Caret({ open, className }: { open: boolean; className?: string }) {
|
||||
return (
|
||||
<svg className={caretCls(open) + (className ? ' ' + className : '')} viewBox="0 0 20 20" aria-hidden="true">
|
||||
<path d={CARET_PATH} fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
/**
|
||||
* 全站唯一的「显示 / 隐藏密码」图标:读取中(转圈)/ 正在显示(斜线眼)/ 已隐藏(睁眼)。
|
||||
* SecretInput(输入框内)与模型管理卡片(掩码行)共用,保证外观与手感完全一致。
|
||||
*/
|
||||
export function EyeIcon({ shown = false, loading = false, size = 15 }: { shown?: boolean; loading?: boolean; size?: number }) {
|
||||
if (loading) {
|
||||
return (
|
||||
<svg className="animate-spin-slow" style={{ transformOrigin: '50% 50%' }} viewBox="0 0 24 24" width={size} height={size}
|
||||
fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true">
|
||||
<path d="M21 12a9 9 0 1 1-9-9" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
if (shown) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor"
|
||||
strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
||||
<path d="M3 3l18 18" />
|
||||
<path d="M10.6 5.2A9.9 9.9 0 0 1 12 5c5 0 9 4.5 10 7-.4 1-1.6 3-3.5 4.6" />
|
||||
<path d="M6.3 7.1C4.2 8.6 2.8 10.8 2 12c1 2.5 5 7 10 7 1.6 0 3-.4 4.3-1.1" />
|
||||
<path d="M9.9 9.9a3 3 0 0 0 4.2 4.2" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor"
|
||||
strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
||||
<path d="M2 12c1-2.5 5-7 10-7s9 4.5 10 7c-1 2.5-5 7-10 7S3 14.5 2 12z" />
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,185 @@
|
|||
import { useEffect, useId, useMemo, useRef, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { cn } from '../../lib/cn'
|
||||
import { sameValue, summaryOf, toOptions, type OptionLike } from './options'
|
||||
import { contentWidth, usePopup } from './use-popup'
|
||||
import { filterBarCls, itemCls, listCls, noneCls, popCls, triggerCls } from './parts'
|
||||
import { Caret } from './Caret'
|
||||
|
||||
/**
|
||||
* 全站统一「多选下拉」(替代原生 <select multiple> 的系统列表外观)。
|
||||
* 与 Select 同一套视觉语言:复选列表 + 全选/清空 + 过滤框。
|
||||
* 回显超过 30 字退化成「首项 等 N 项」,否则触发器会被撑出整行。
|
||||
*/
|
||||
export type MultiSelectProps = {
|
||||
value: any[] | null | undefined
|
||||
onChange: (next: any[]) => void
|
||||
options: OptionLike[] | null | undefined
|
||||
disabled?: boolean
|
||||
placeholder?: string
|
||||
searchThreshold?: number
|
||||
size?: 'sm' | 'md'
|
||||
ariaLabel?: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function MultiSelect({
|
||||
value, onChange, options, disabled, placeholder = '未选择', searchThreshold = 7,
|
||||
size = 'md', ariaLabel, className
|
||||
}: MultiSelectProps) {
|
||||
const picked = useMemo(() => (Array.isArray(value) ? value : []), [value])
|
||||
const opts = useMemo(() => toOptions(options), [options])
|
||||
const uid = useId()
|
||||
const cw = useMemo(() => contentWidth(opts.map((o) => o.label), 62), [opts])
|
||||
const { open, setOpen, triggerRef, popRef, box } = usePopup({ minW: 190, maxW: 440, listMinH: 210, maxHCap: 320, contentW: cw, disabled })
|
||||
const listRef = useRef<HTMLDivElement | null>(null)
|
||||
const searchRef = useRef<HTMLInputElement | null>(null)
|
||||
const [query, setQuery] = useState('')
|
||||
const [active, setActive] = useState(-1)
|
||||
|
||||
const isSelected = (v: any) => picked.some((p) => sameValue(p, v))
|
||||
const labels = opts.filter((o) => isSelected(o.value)).map((o) => o.label)
|
||||
const shown = summaryOf(labels)
|
||||
const count = labels.length
|
||||
|
||||
const view = useMemo(() => {
|
||||
const q = query.trim().toLowerCase()
|
||||
return opts.map((_, i) => i).filter((i) => !q || opts[i].label.toLowerCase().includes(q))
|
||||
}, [opts, query])
|
||||
const selectableInView = view.filter((i) => !opts[i].disabled).length
|
||||
const searchable = searchThreshold > 0 && opts.length > searchThreshold
|
||||
|
||||
const scrollActive = () => listRef.current?.querySelector<HTMLElement>('[data-act="1"]')?.scrollIntoView({ block: 'nearest' })
|
||||
useEffect(() => { if (open) queueMicrotask(scrollActive) }, [open, active])
|
||||
useEffect(() => {
|
||||
if (query) setActive(view.find((i) => !opts[i].disabled) ?? -1)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [query])
|
||||
|
||||
function commit(next: any[]) {
|
||||
onChange(next)
|
||||
if (open) queueMicrotask(scrollActive)
|
||||
}
|
||||
|
||||
function toggleIndex(i: number) {
|
||||
const o = opts[i]
|
||||
if (!o || o.disabled) return
|
||||
commit(isSelected(o.value) ? picked.filter((p) => !sameValue(p, o.value)) : [...picked, o.value])
|
||||
}
|
||||
|
||||
function setInView(selected: boolean) {
|
||||
const inView = view.map((i) => opts[i].value)
|
||||
if (selected) {
|
||||
const next = [...picked]
|
||||
for (const v of inView) if (!picked.some((p) => sameValue(p, v))) next.push(v)
|
||||
commit(next)
|
||||
} else {
|
||||
commit(picked.filter((p) => !inView.some((v) => sameValue(v, p))))
|
||||
}
|
||||
}
|
||||
|
||||
function toggle(force?: boolean) {
|
||||
if (disabled) return
|
||||
const next = force ?? !open
|
||||
if (!next) { setQuery(''); setOpen(false); triggerRef.current?.focus({ preventScroll: true }); return }
|
||||
setQuery('')
|
||||
const first = view.findIndex((i) => isSelected(opts[i].value))
|
||||
setActive(first >= 0 ? first : view.find((i) => !opts[i].disabled) ?? -1)
|
||||
setOpen(true)
|
||||
queueMicrotask(() => { if (searchable) searchRef.current?.focus({ preventScroll: true }); else triggerRef.current?.focus({ preventScroll: true }) })
|
||||
}
|
||||
|
||||
function move(key: 'ArrowDown' | 'ArrowUp' | 'Home' | 'End') {
|
||||
if (!view.length) return
|
||||
let pos = view.indexOf(active)
|
||||
const step = (delta: number) => {
|
||||
for (let n = 0; n < view.length; n++) {
|
||||
pos = (pos + delta + view.length) % view.length
|
||||
if (!opts[view[pos]].disabled) return
|
||||
}
|
||||
}
|
||||
if (key === 'ArrowDown') step(1)
|
||||
else if (key === 'ArrowUp') step(-1)
|
||||
else if (key === 'Home') pos = 0
|
||||
else pos = view.length - 1
|
||||
setActive(view[pos] ?? -1)
|
||||
}
|
||||
|
||||
function onKeydown(e: React.KeyboardEvent) {
|
||||
if ((e.target as HTMLElement | null)?.tagName === 'INPUT') return
|
||||
if (e.key === 'Escape') { if (open) { e.preventDefault(); e.stopPropagation(); toggle(false) } return }
|
||||
if (e.key === 'Tab') { setOpen(false); return }
|
||||
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
|
||||
e.preventDefault()
|
||||
if (!open) { toggle(true); return }
|
||||
move(e.key)
|
||||
return
|
||||
}
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault()
|
||||
if (open) { if (active >= 0) toggleIndex(active) } else toggle(true)
|
||||
}
|
||||
}
|
||||
|
||||
function onSearchKeydown(e: React.KeyboardEvent) {
|
||||
if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(e.key)) { e.preventDefault(); e.stopPropagation(); move(e.key as any) }
|
||||
else if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); if (active >= 0) toggleIndex(active) }
|
||||
else if (e.key === 'Escape') { e.stopPropagation(); toggle(false) }
|
||||
}
|
||||
|
||||
return (
|
||||
<span className={cn('relative inline-flex w-full min-w-0 align-middle', open && 'z-[401]', className)}>
|
||||
<button ref={triggerRef} type="button" disabled={disabled} aria-label={ariaLabel || undefined}
|
||||
aria-haspopup="listbox" aria-expanded={open}
|
||||
aria-activedescendant={open && active >= 0 ? `${uid}-o${active}` : undefined}
|
||||
className={triggerCls({ open, size, disabled })}
|
||||
onClick={() => toggle()} onKeyDown={onKeydown}>
|
||||
{!!count && (
|
||||
<span className="flex-none min-w-[17px] h-[17px] px-[5px] rounded-pill grid place-items-center bg-accent-fill text-on-accent text-tiny font-bold leading-none">{count}</span>
|
||||
)}
|
||||
<span className={cn('flex-1 min-w-0 truncate whitespace-nowrap', !shown && 'text-faint')}>{shown || placeholder}</span>
|
||||
<Caret open={open} />
|
||||
</button>
|
||||
{open && box && createPortal(
|
||||
<div ref={popRef} role="listbox" aria-multiselectable aria-label={ariaLabel || undefined}
|
||||
className={popCls}
|
||||
style={{ left: box.left, top: box.top, width: box.width, maxHeight: box.maxH, transform: box.drop ? undefined : 'translateY(-100%)' }}
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
onKeyDown={onKeydown}>
|
||||
<div className={filterBarCls}>
|
||||
{searchable && (
|
||||
<input ref={searchRef} type="search" value={query} placeholder="过滤选项…"
|
||||
aria-label={`${ariaLabel || '选项'}:过滤`}
|
||||
className="flex-1 min-w-0 h-auto py-[5px] px-2 text-caption rounded-[6px] border border-line-strong bg-field text-ink outline-none focus:border-accent-deep [&::-webkit-search-cancel-button]:appearance-none"
|
||||
onChange={(e) => setQuery(e.target.value)} onKeyDown={onSearchKeydown} />
|
||||
)}
|
||||
<span className="flex-none text-tiny text-faint">{count ? `已选 ${count} 项` : '未选择'}</span>
|
||||
<button type="button" className="flex-none p-[4px_7px] rounded-[6px] text-tiny border border-line-strong bg-hover text-ink-2 disabled:opacity-40 disabled:cursor-not-allowed hover:not-disabled:border-line-bright hover:not-disabled:text-ink"
|
||||
disabled={!selectableInView} onClick={() => setInView(true)}>全选</button>
|
||||
<button type="button" className="flex-none p-[4px_7px] rounded-[6px] text-tiny border border-line-strong bg-hover text-ink-2 disabled:opacity-40 disabled:cursor-not-allowed hover:not-disabled:border-line-bright hover:not-disabled:text-ink"
|
||||
disabled={!count} onClick={() => setInView(false)}>清空</button>
|
||||
</div>
|
||||
<div ref={listRef} className={listCls}>
|
||||
{view.map((i) => {
|
||||
const o = opts[i]
|
||||
const on = isSelected(o.value)
|
||||
return (
|
||||
<div key={`${o.value}-${i}`} id={`${uid}-o${i}`} role="option" aria-selected={on}
|
||||
data-act={i === active ? '1' : '0'}
|
||||
className={itemCls({ on, act: i === active, off: o.disabled, multi: true })}
|
||||
onMouseEnter={() => setActive(i)}
|
||||
onClick={() => toggleIndex(i)}>
|
||||
<span className={cn('flex-none w-[14px] h-[14px] mt-px rounded-[4px] grid place-items-center border text-on-accent',
|
||||
on ? 'bg-accent-fill border-accent-fill' : 'border-line-bright')}>
|
||||
{on && <svg viewBox="0 0 12 12" className="w-[11px] h-[11px]"><path d="M2.6 6.3 4.9 8.6 9.4 3.7" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" /></svg>}
|
||||
</span>
|
||||
<span className="min-w-0 break-anywhere">{o.label}</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{!view.length && <div className={noneCls}>{opts.length ? '没有匹配的选项' : '无可选项'}</div>}
|
||||
</div>
|
||||
</div>, document.body)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,96 @@
|
|||
import { useEffect, useState, type InputHTMLAttributes } from 'react'
|
||||
import { cn } from '../../lib/cn'
|
||||
import * as api from '../../api/client'
|
||||
import { EyeIcon } from './EyeIcon'
|
||||
|
||||
/**
|
||||
* 全站统一的「密码 / 密钥」输入框。
|
||||
*
|
||||
* 之前四套写法各不相同:登录页和模型管理是「显示 / 隐藏」文字按钮(看不出是开关)、
|
||||
* 我的账号三个密码框压根没有开关(只能盲打)、用户管理直接 type="text" 常显。
|
||||
* 规则统一:右侧眼睛图标切换密文/明文;按下图标不抢输入框焦点(onMouseDown.preventDefault),
|
||||
* 光标位置和已选文本都不丢。
|
||||
* 传 revealUrl 时,编辑已保存的密钥(后端只回掩码、输入框是空的)点一下图标会向后端取回
|
||||
* 真实明文——解决「点了显示却什么都没有」。取回的明文只在「显示」期间留在输入框里:
|
||||
* 一旦切回隐藏且用户没改动就还原成空,保存时仍按「留空保持原密钥」的契约走。
|
||||
*/
|
||||
export type SecretInputProps = {
|
||||
value?: string
|
||||
onChange?: (next: string) => void
|
||||
id?: string
|
||||
placeholder?: string
|
||||
autocomplete?: string
|
||||
maxLength?: number
|
||||
disabled?: boolean
|
||||
/** 已经保存过密钥(用于区分「新建时留空」与「编辑时未改动」) */
|
||||
hasSaved?: boolean
|
||||
/** 取回明文的接口;不传就只做本地密文/明文切换 */
|
||||
revealUrl?: string
|
||||
className?: string
|
||||
} & Omit<InputHTMLAttributes<HTMLInputElement>, 'value' | 'onChange' | 'id' | 'placeholder' | 'disabled' | 'className'>
|
||||
|
||||
export function SecretInput({
|
||||
value = '', onChange, id, placeholder = '••••••••', autocomplete = 'current-password',
|
||||
maxLength = 200, disabled, hasSaved, revealUrl, className, ...rest
|
||||
}: SecretInputProps) {
|
||||
const [shown, setShown] = useState(false)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [stored, setStored] = useState('')
|
||||
/** 输入框当前内容是不是「刚从后端取回的明文」——是的话隐藏时清回去 */
|
||||
const [seeded, setSeeded] = useState(false)
|
||||
const [failed, setFailed] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
// 用户改动过内容就别再自动清空,否则会把人家编辑了一半的密钥抹掉
|
||||
if (seeded && value !== stored) setSeeded(false)
|
||||
}, [value, stored, seeded])
|
||||
|
||||
async function reveal() {
|
||||
if (loading) return
|
||||
if (shown) {
|
||||
if (seeded && value === stored) onChange?.('')
|
||||
setSeeded(false)
|
||||
setShown(false)
|
||||
return
|
||||
}
|
||||
if (!value && revealUrl && hasSaved && !stored) {
|
||||
setLoading(true)
|
||||
setFailed('')
|
||||
try {
|
||||
const data: any = await api.get(revealUrl)
|
||||
const key = String(data?.api_key || '')
|
||||
setStored(key)
|
||||
if (key) { onChange?.(key); setSeeded(true) }
|
||||
else setFailed('这条模型没有保存密钥')
|
||||
} catch (exc: any) {
|
||||
setFailed(exc?.message || String(exc))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
setShown(true)
|
||||
}
|
||||
|
||||
const hint = loading ? '正在读取已保存的密钥…'
|
||||
: shown ? '隐藏密码'
|
||||
: (revealUrl && hasSaved && !value ? '显示密码:读取已保存的明文' : '显示密码')
|
||||
|
||||
return (
|
||||
<span className={cn('relative block w-full min-w-0', className)}>
|
||||
<input id={id} value={value} type={shown ? 'text' : 'password'} placeholder={placeholder}
|
||||
autoComplete={autocomplete} maxLength={maxLength} disabled={disabled}
|
||||
aria-describedby={failed ? `${id || 'secret'}-hint` : undefined}
|
||||
className="pr-[62px]"
|
||||
onChange={(e) => onChange?.(e.target.value)} {...rest} />
|
||||
<button type="button" aria-label={hint} aria-pressed={shown} title={hint} disabled={disabled}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={reveal}
|
||||
className={cn('absolute right-[34px] top-1/2 -translate-y-1/2 w-[26px] h-[26px] p-0 grid place-items-center',
|
||||
'border rounded-[6px] bg-raise text-ink-3 border-line hover:text-ink hover:border-line-strong',
|
||||
shown && 'text-accent-bright border-accent-line bg-accent-tint-2')}>
|
||||
<EyeIcon shown={shown} loading={loading} />
|
||||
</button>
|
||||
{failed && <small id={`${id || 'secret'}-hint`} className="block mt-[5px] text-warn-bright text-tiny">{failed}</small>}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,191 @@
|
|||
import { useEffect, useId, useMemo, useRef, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { cn } from '../../lib/cn'
|
||||
import { sameValue, summaryOf, toOptions, type OptionLike, type SelectOption } from './options'
|
||||
import { contentWidth, usePopup } from './use-popup'
|
||||
import { filterBarCls, filterInputCls, itemCls, listCls, noneCls, popCls, tickCls, triggerCls } from './parts'
|
||||
import { Caret } from './Caret'
|
||||
|
||||
/**
|
||||
* 全站统一下拉控件(替代原生 <select> 的系统外观)。
|
||||
*
|
||||
* 可见部分是自绘触发器 + 挂到 body 的弹层:抽屉、表格、滚动容器都不会裁切它,
|
||||
* 深浅主题一致。键盘(↑↓ Home End Enter Esc 首字母定位)与 ARIA 齐备;
|
||||
* 选项超过阈值自动出现过滤框,否则长列表只能靠滚动条盲摸。
|
||||
* 弹层宽度按最长选项量出来,既不裁字也不会比触发器还窄。
|
||||
*/
|
||||
export type SelectProps = {
|
||||
value: any
|
||||
onChange: (next: any) => void
|
||||
options: OptionLike[] | null | undefined
|
||||
disabled?: boolean
|
||||
placeholder?: string
|
||||
/** 选项超过该数量时自动显示过滤框(与 MultiSelect 一致) */
|
||||
searchThreshold?: number
|
||||
/** sm 用于表格行内/工具条,md 用于表单 */
|
||||
size?: 'sm' | 'md'
|
||||
ariaLabel?: string
|
||||
className?: string
|
||||
id?: string
|
||||
name?: string
|
||||
}
|
||||
|
||||
export function Select({
|
||||
value, onChange, options, disabled, placeholder = '请选择', searchThreshold = 8,
|
||||
size = 'md', ariaLabel, className, id, name
|
||||
}: SelectProps) {
|
||||
const opts = useMemo(() => toOptions(options), [options])
|
||||
const uid = useId()
|
||||
const { open, setOpen, triggerRef, popRef, box } = usePopup({
|
||||
minW: 168, maxW: 420, listMinH: 190, maxHCap: 300,
|
||||
contentW: useMemo(() => contentWidth(opts.map((o) => o.label), 44), [opts]),
|
||||
disabled
|
||||
})
|
||||
const listRef = useRef<HTMLDivElement | null>(null)
|
||||
const searchRef = useRef<HTMLInputElement | null>(null)
|
||||
const [query, setQuery] = useState('')
|
||||
const [active, setActive] = useState(-1)
|
||||
|
||||
const selIndex = useMemo(() => opts.findIndex((o) => sameValue(o.value, value)), [opts, value])
|
||||
const shown = selIndex >= 0 ? opts[selIndex].label : ''
|
||||
const view = useMemo(() => {
|
||||
const q = query.trim().toLowerCase()
|
||||
const all = opts.map((_, i) => i)
|
||||
return q ? all.filter((i) => opts[i].label.toLowerCase().includes(q)) : all
|
||||
}, [opts, query])
|
||||
const searchable = searchThreshold > 0 && opts.length > searchThreshold
|
||||
|
||||
const scrollActive = () => {
|
||||
listRef.current?.querySelector<HTMLElement>('[data-act="1"]')?.scrollIntoView({ block: 'nearest' })
|
||||
}
|
||||
useEffect(() => { if (open) queueMicrotask(scrollActive) }, [open, active])
|
||||
useEffect(() => {
|
||||
if (query) setActive(view.find((i) => !opts[i].disabled) ?? -1)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [query])
|
||||
|
||||
function toggle(force?: boolean) {
|
||||
if (disabled) return
|
||||
const next = force ?? !open
|
||||
if (!next) { setQuery(''); setOpen(false); triggerRef.current?.focus({ preventScroll: true }); return }
|
||||
setQuery('')
|
||||
setActive(selIndex >= 0 ? selIndex : opts.findIndex((o) => !o.disabled))
|
||||
setOpen(true)
|
||||
queueMicrotask(() => { if (searchable) searchRef.current?.focus({ preventScroll: true }); else triggerRef.current?.focus({ preventScroll: true }) })
|
||||
}
|
||||
|
||||
function choose(i: number) {
|
||||
const o = opts[i]
|
||||
if (!o || o.disabled) return
|
||||
onChange(o.value)
|
||||
setOpen(false)
|
||||
setQuery('')
|
||||
triggerRef.current?.focus({ preventScroll: true })
|
||||
}
|
||||
|
||||
function move(delta: number) {
|
||||
if (!opts.length) return
|
||||
if (!open) { toggle(true); return }
|
||||
if (!view.length) return
|
||||
let pos = Math.max(0, view.indexOf(active))
|
||||
for (let n = 0; n < view.length; n++) {
|
||||
pos = (pos + delta + view.length) % view.length
|
||||
if (!opts[view[pos]].disabled) break
|
||||
}
|
||||
setActive(view[pos])
|
||||
}
|
||||
|
||||
let typeBuf = ''
|
||||
let typeTimer = 0
|
||||
function typeAhead(ch: string) {
|
||||
typeBuf += ch.toLowerCase()
|
||||
window.clearTimeout(typeTimer)
|
||||
typeTimer = window.setTimeout(() => { typeBuf = '' }, 420)
|
||||
const hit = view.find((i) => opts[i].label.toLowerCase().startsWith(typeBuf))
|
||||
if (hit !== undefined) setActive(hit)
|
||||
}
|
||||
|
||||
function onKeydown(e: React.KeyboardEvent) {
|
||||
if ((e.target as HTMLElement | null)?.tagName === 'INPUT') return
|
||||
if (e.key === 'Escape') { if (open) { e.preventDefault(); e.stopPropagation(); setOpen(false) } return }
|
||||
if (e.key === 'Tab') { setOpen(false); return }
|
||||
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); move(e.key === 'ArrowDown' ? 1 : -1); return }
|
||||
if (e.key === 'Home' || e.key === 'End') {
|
||||
if (!open) return
|
||||
e.preventDefault()
|
||||
const order = e.key === 'Home' ? view : [...view].reverse()
|
||||
setActive(order.find((i) => !opts[i].disabled) ?? view[0] ?? -1)
|
||||
return
|
||||
}
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault()
|
||||
if (open) choose(active)
|
||||
else toggle(true)
|
||||
return
|
||||
}
|
||||
if (e.key.length === 1 && !e.metaKey && !e.ctrlKey && !e.altKey) {
|
||||
if (!open) { toggle(true); return }
|
||||
typeAhead(e.key)
|
||||
}
|
||||
}
|
||||
|
||||
function onSearchKeydown(e: React.KeyboardEvent) {
|
||||
// 过滤框自己消化这些键,否则冒泡到弹层会二次执行(方向键走两格、回车来回切换)
|
||||
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); e.stopPropagation(); move(e.key === 'ArrowDown' ? 1 : -1) }
|
||||
else if (e.key === 'Home' || e.key === 'End') { e.stopPropagation() }
|
||||
else if (e.key === 'Enter') {
|
||||
if (active >= 0) { e.preventDefault(); e.stopPropagation(); choose(active) }
|
||||
} else if (e.key === 'Escape') { e.stopPropagation(); toggle(false) }
|
||||
}
|
||||
|
||||
return (
|
||||
<span className={cn('relative inline-flex w-full min-w-0 align-middle', open && 'z-[401]', className)}>
|
||||
<button ref={triggerRef} type="button" id={id} disabled={disabled} aria-label={ariaLabel || undefined}
|
||||
aria-haspopup="listbox" aria-expanded={open} data-name={name}
|
||||
aria-activedescendant={open && active >= 0 ? `${uid}-o${active}` : undefined}
|
||||
className={triggerCls({ open, size, disabled })}
|
||||
onClick={() => toggle()} onKeyDown={onKeydown}>
|
||||
<span className={cn('flex-1 min-w-0 truncate whitespace-nowrap', !shown && 'text-faint')}>{shown || placeholder}</span>
|
||||
<Caret open={open} />
|
||||
</button>
|
||||
{open && box && createPortal(
|
||||
<div ref={popRef} role="listbox" aria-label={ariaLabel || undefined}
|
||||
className={popCls}
|
||||
style={{ left: box.left, top: box.top, width: box.width, maxHeight: box.maxH, transform: box.drop ? undefined : 'translateY(-100%)' }}
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
onKeyDown={onKeydown}>
|
||||
{searchable && (
|
||||
<div className={filterBarCls}>
|
||||
<input ref={searchRef} type="search" value={query} className={filterInputCls} placeholder="过滤选项…"
|
||||
aria-label={`${ariaLabel || '选项'}:过滤`}
|
||||
onChange={(e) => setQuery(e.target.value)} onKeyDown={onSearchKeydown} />
|
||||
<span className="flex-none text-tiny text-faint whitespace-nowrap">
|
||||
{view.length === opts.length ? `${opts.length} 项` : `${view.length} / ${opts.length} 项`}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div ref={listRef} className={listCls}>
|
||||
{view.map((i) => {
|
||||
const o: SelectOption = opts[i]
|
||||
return (
|
||||
<div key={`${o.value}-${i}`} id={`${uid}-o${i}`} role="option" aria-selected={sameValue(o.value, value)}
|
||||
data-act={i === active ? '1' : '0'}
|
||||
className={itemCls({ on: sameValue(o.value, value), act: i === active, off: o.disabled })}
|
||||
onMouseEnter={() => setActive(i)}
|
||||
onClick={() => choose(i)}>
|
||||
<span className={tickCls} style={{ opacity: sameValue(o.value, value) ? 1 : 0 }} aria-hidden>✓</span>
|
||||
<span className="min-w-0 break-anywhere">{o.label}</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{!opts.length && <div className={noneCls}>无可选项</div>}
|
||||
{!!opts.length && !view.length && <div className={noneCls}>没有匹配的选项</div>}
|
||||
</div>
|
||||
</div>, document.body)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** 常用出口:把字典/枚举直接转成 options */
|
||||
export { toOptions, sameValue, summaryOf }
|
||||
export type { SelectOption }
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
export * from './options'
|
||||
export * from './Select'
|
||||
export * from './MultiSelect'
|
||||
export * from './SecretInput'
|
||||
export * from './EyeIcon'
|
||||
export * from './Caret'
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
/**
|
||||
* 下拉选项的统一形状。
|
||||
*
|
||||
* 旧站的下拉把选项写在插槽里的原生 <option> 上,靠一个隐藏的 select 承载
|
||||
* v-model 语义——那是 Vue 特有的兼容手法。React 侧没有这个问题,
|
||||
* 直接把 options 当数据传进来:可搜索、可虚拟化、可来自接口的任意数组。
|
||||
*/
|
||||
export type SelectOption = { value: any; label: string; disabled?: boolean }
|
||||
export type OptionLike = SelectOption | string | number | null | undefined
|
||||
|
||||
function labelOf(v: unknown) {
|
||||
return String(v ?? '').replace(/\s+/g, ' ').trim()
|
||||
}
|
||||
|
||||
/** 允许 `['主角','配角']` 这种最省事的写法,也允许标准 {value,label} */
|
||||
export function toOptions(list: OptionLike[] | null | undefined): SelectOption[] {
|
||||
return (list || [])
|
||||
.filter((it) => it !== null && it !== undefined && it !== '')
|
||||
.map((it: any) => {
|
||||
if (typeof it === 'object') {
|
||||
return { value: it.value, label: labelOf(it.label ?? it.name ?? it.text ?? it.value) || String(it.value ?? ''), disabled: !!it.disabled }
|
||||
}
|
||||
return { value: it, label: labelOf(it) }
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 值比较:接口回来的 id 是 number,表单里存的是 string,
|
||||
* 直接 === 会让「选中项」在重渲染后丢失(旧站靠原生 select 的类型转换掩盖了这点)。
|
||||
*/
|
||||
export function sameValue(a: any, b: any): boolean {
|
||||
if (a === b) return true
|
||||
if (a === null || a === undefined || b === null || b === undefined) return false
|
||||
return String(a) === String(b)
|
||||
}
|
||||
|
||||
/** 触发器上那一行回显:太长就退化成「首项 等 N 项」,避免把整行控件撑高 */
|
||||
export function summaryOf(labels: string[], emptyText = ''): string {
|
||||
if (!labels.length) return emptyText
|
||||
const joined = labels.join('、')
|
||||
return joined.length <= 30 ? joined : `${labels[0]} 等 ${labels.length} 项`
|
||||
}
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
import { cn } from '../../lib/cn'
|
||||
|
||||
/**
|
||||
* Select / MultiSelect 共用的皮肤。
|
||||
*
|
||||
* 两个控件的形状几乎一样(触发器 + body 弹层 + 选项行),旧站因此复制了
|
||||
* 一整份 scoped 样式,改一处必须改两处;这里把类名收成常量。
|
||||
* 高度仍然只来自 --ctl-h(容器决定主尺寸还是紧凑尺寸),组件内部不写死 px。
|
||||
*/
|
||||
export const triggerCls = (o: { open: boolean; size: 'sm' | 'md'; disabled?: boolean; className?: string }) => cn(
|
||||
'appearance-none flex items-center gap-2 w-full min-w-0 h-(--ctl-h) px-[10px] rounded-control text-left',
|
||||
'border border-line-strong bg-field text-ink text-body leading-[1.35] outline-none',
|
||||
'transition-[border-color,background,box-shadow] duration-150 disabled:cursor-not-allowed',
|
||||
'hover:not-disabled:border-line-bright hover:not-disabled:bg-hover',
|
||||
o.size === 'sm' && 'px-2 text-tiny rounded-[6px]',
|
||||
o.disabled && 'opacity-50',
|
||||
o.open && 'border-accent-deep shadow-[0_0_0_3px_var(--c-accent-tint)]',
|
||||
o.className
|
||||
)
|
||||
|
||||
export const popCls = 'fixed z-[400] flex flex-col overflow-hidden border border-line-strong rounded-[10px] bg-panel shadow-pop animate-fade-in'
|
||||
|
||||
export const listCls = 'flex-1 min-h-0 overflow-auto scrollbar-slim p-[5px]'
|
||||
|
||||
export const itemCls = (o: { on?: boolean; act?: boolean; off?: boolean; multi?: boolean }) => cn(
|
||||
'flex items-start gap-[7px] p-[7px_8px] rounded-[7px] text-body leading-[1.45] text-ink-2 cursor-pointer',
|
||||
o.act && 'bg-hover text-ink',
|
||||
o.on && (o.multi ? 'text-ink' : 'text-accent-bright bg-accent-tint'),
|
||||
o.on && o.act && !o.multi && 'bg-accent-tint-2',
|
||||
o.off && 'opacity-40 cursor-not-allowed'
|
||||
)
|
||||
|
||||
export const filterBarCls = 'flex-none flex items-center gap-[7px] p-[7px_8px] border-b border-line bg-raise'
|
||||
|
||||
export const filterInputCls = 'flex-1 min-w-0 h-auto py-[5px] px-2 text-caption rounded-[6px] border border-line-strong bg-field text-ink focus:border-accent-deep'
|
||||
|
||||
export const noneCls = 'p-[10px] text-center text-caption text-faint'
|
||||
|
||||
/** 下拉箭头:展开时翻转并点亮,用户永远知道面板是开还是关 */
|
||||
export function caretCls(open: boolean) {
|
||||
return cn('flex-none w-[15px] h-[15px] text-muted transition-transform duration-150', open && 'rotate-180 text-accent-bright')
|
||||
}
|
||||
|
||||
export const CARET_PATH = 'M5.5 7.5 10 12l4.5-4.5'
|
||||
|
||||
export const tickCls = 'flex-none w-3 shrink-0 mt-px text-[11px] text-accent-bright'
|
||||
|
|
@ -0,0 +1,109 @@
|
|||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||
|
||||
/**
|
||||
* 弹层定位:触发器 + 挂到 body 的下拉面板(Select / MultiSelect 共用)。
|
||||
*
|
||||
* 为什么要算这么多:抽屉、滚动容器、表格 overflow:hidden 都会把就地渲染的弹层裁掉;
|
||||
* 贴底时不翻边就露出一两条选项。位置只在打开时算一次 + 跟随 scroll/resize 重算,
|
||||
* 真实高度渲染完再按 rect 纠正(必要时翻边/贴边)。
|
||||
*/
|
||||
export type PopupBox = { left: number; top: number; width: number; drop: boolean; maxH: number }
|
||||
|
||||
let measureCtx: CanvasRenderingContext2D | null = null
|
||||
/** 弹层宽度:既不窄于触发器,也要放得下最长的选项 */
|
||||
export function contentWidth(texts: string[], pad: number): number {
|
||||
if (typeof document === 'undefined') return 0
|
||||
if (!measureCtx) measureCtx = document.createElement('canvas').getContext('2d')
|
||||
if (!measureCtx) return 0
|
||||
measureCtx.font = '12px "DM Sans", "Noto Sans SC", system-ui, sans-serif'
|
||||
let max = 0
|
||||
for (const t of texts) max = Math.max(max, measureCtx.measureText(t).width)
|
||||
return Math.ceil(max) + pad
|
||||
}
|
||||
|
||||
export function usePopup(opts: {
|
||||
minW: number
|
||||
maxW: number
|
||||
contentW: number
|
||||
/** 低于这个剩余空间就往上翻边 */
|
||||
listMinH: number
|
||||
maxHCap: number
|
||||
disabled?: boolean
|
||||
}) {
|
||||
const { minW, maxW, contentW: cw, listMinH, maxHCap, disabled } = opts
|
||||
const triggerRef = useRef<HTMLButtonElement | null>(null)
|
||||
const popRef = useRef<HTMLDivElement | null>(null)
|
||||
const [open, setOpen] = useState(false)
|
||||
const [box, setBox] = useState<PopupBox | null>(null)
|
||||
|
||||
const place = useCallback(() => {
|
||||
const el = triggerRef.current
|
||||
if (!el) return
|
||||
const r = el.getBoundingClientRect()
|
||||
const avail = Math.max(160, window.innerWidth - 24)
|
||||
const width = Math.min(Math.max(Math.max(r.width, cw), Math.min(minW, avail)), maxW, avail)
|
||||
const below = window.innerHeight - r.bottom - 14
|
||||
const above = r.top - 14
|
||||
const drop = below >= listMinH || below >= above
|
||||
setBox({
|
||||
left: Math.min(Math.max(8, r.left), Math.max(8, window.innerWidth - width - 8)),
|
||||
top: drop ? r.bottom + 6 : r.top - 6,
|
||||
width,
|
||||
drop,
|
||||
maxH: Math.max(listMinH, Math.min(maxHCap, drop ? below : above))
|
||||
})
|
||||
}, [cw, minW, maxW, listMinH, maxHCap])
|
||||
|
||||
/** 渲染完成后按真实高度纠正:只有这里知道面板到底有多高 */
|
||||
const clamp = useCallback(() => {
|
||||
const el = popRef.current
|
||||
const trig = triggerRef.current?.getBoundingClientRect()
|
||||
if (!el || !trig || !box) return
|
||||
const rect = el.getBoundingClientRect()
|
||||
const h = rect.height
|
||||
let top = box.top
|
||||
if (rect.bottom > window.innerHeight - 8 || rect.top < 8) {
|
||||
let drop = box.drop
|
||||
if (drop && window.innerHeight - (trig.bottom + 6) < h && trig.top - 14 > h) { top = trig.top - 6; drop = false }
|
||||
else if (!drop && rect.top < 8) { top = trig.bottom + 6; drop = true }
|
||||
if (top + h > window.innerHeight - 8) top = window.innerHeight - 8 - h
|
||||
if (top < 8) top = 8
|
||||
setBox({ ...box, top, drop })
|
||||
}
|
||||
}, [box])
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!open) return
|
||||
place()
|
||||
}, [open, place])
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!open) return
|
||||
clamp()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [open, box?.maxH, box?.width, box?.left])
|
||||
|
||||
useEffect(() => {
|
||||
if (disabled && open) setOpen(false)
|
||||
}, [disabled, open])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const onPointerDown = (e: PointerEvent) => {
|
||||
const t = e.target as Node
|
||||
if (triggerRef.current?.contains(t) || popRef.current?.contains(t)) return
|
||||
setOpen(false)
|
||||
}
|
||||
const reposition = () => place()
|
||||
document.addEventListener('pointerdown', onPointerDown, true)
|
||||
window.addEventListener('resize', reposition)
|
||||
window.addEventListener('scroll', reposition, true)
|
||||
return () => {
|
||||
document.removeEventListener('pointerdown', onPointerDown, true)
|
||||
window.removeEventListener('resize', reposition)
|
||||
window.removeEventListener('scroll', reposition, true)
|
||||
}
|
||||
}, [open, place])
|
||||
|
||||
return { open, setOpen, triggerRef, popRef, box }
|
||||
}
|
||||
|
|
@ -0,0 +1,85 @@
|
|||
import { type AnchorHTMLAttributes, type ButtonHTMLAttributes, type ReactNode, type Ref, forwardRef } from 'react'
|
||||
import { cn } from '../../lib/cn'
|
||||
|
||||
/**
|
||||
* 全站唯一的按钮。
|
||||
*
|
||||
* 为什么只有这一个组件:旧站同一颗「取消」在四个页面分别是 .secondary / .outline /
|
||||
* .ghost / 裸 button,padding 各自写死,同一行里量出 31/34/36/38 四种高度。
|
||||
* 现在高度只有两档,且**由所在容器决定**:容器用 [--ctl-h:var(--ctl-h-md)]
|
||||
* 声明自己是紧凑档(工具条、筛选条、卡片动作行),按钮写 h-(--ctl-h) 自动跟随。
|
||||
* 页面要更矮不要加 padding,把外层换成 <Ctlbar> / <ChipBar> 就行。
|
||||
*
|
||||
* 变体语义(不要凭手感挑):
|
||||
* primary 一个区域里唯一的主动作(保存 / 开始生成)
|
||||
* secondary 有底的次动作
|
||||
* outline 中性动作、与主按钮并排的「取消」
|
||||
* ghost 紧凑行里的轻动作(抽屉、灯箱、卡片角)
|
||||
* add / del 成组列表里的「加一行 / 删一行」,不是页面级主操作
|
||||
* link 文字链样式的动作(表格行内),仍然是控件、与同行等高
|
||||
*/
|
||||
export type ButtonVariant = 'primary' | 'secondary' | 'outline' | 'ghost' | 'add' | 'del' | 'link'
|
||||
export type ButtonSize = 'sm' | 'md' | 'lg'
|
||||
|
||||
const BASE = 'inline-flex items-center justify-center gap-1.5 rounded-control border border-transparent '
|
||||
+ 'font-semibold whitespace-nowrap shrink-0 select-none h-(--ctl-h) px-[13px] text-[11px] leading-[1.2] '
|
||||
+ 'transition-[background,border-color,color,filter] duration-150 '
|
||||
+ 'disabled:opacity-35 disabled:cursor-not-allowed'
|
||||
|
||||
const VARIANTS: Record<ButtonVariant, string> = {
|
||||
primary: 'bg-accent-fill text-on-accent hover:not-disabled:brightness-[1.09] active:not-disabled:translate-y-px',
|
||||
secondary: 'bg-line text-ink border-line-strong hover:not-disabled:bg-raise',
|
||||
outline: 'bg-transparent text-ink-2 border-line-strong hover:not-disabled:bg-hover',
|
||||
ghost: 'bg-transparent text-ink-2 border-line-strong rounded-[7px] px-[9px] text-tiny h-(--ctl-h-md) '
|
||||
+ 'hover:not-disabled:border-line-bright hover:not-disabled:bg-hover',
|
||||
add: 'bg-accent-fill text-on-accent rounded-[8px] px-[10px] text-[11px] h-(--ctl-h-md) min-w-(--ctl-h-md) shadow-raise '
|
||||
+ 'hover:not-disabled:brightness-[1.09] active:not-disabled:translate-y-px',
|
||||
del: 'bg-danger-tint-2 text-danger-bright border-danger-line rounded-[8px] px-[10px] text-[11px] h-(--ctl-h-md) min-w-(--ctl-h-md) '
|
||||
+ 'hover:not-disabled:bg-danger hover:not-disabled:border-danger hover:not-disabled:text-danger-ink',
|
||||
link: 'border-transparent bg-transparent text-success text-body px-0 h-auto min-h-(--ctl-h-md) '
|
||||
+ 'hover:not-disabled:underline disabled:opacity-40'
|
||||
}
|
||||
|
||||
const SIZES: Record<ButtonSize, string> = {
|
||||
sm: 'h-(--ctl-h-md) px-[9px] text-tiny gap-[5px]',
|
||||
md: '',
|
||||
lg: 'h-(--ctl-h-main) text-body'
|
||||
}
|
||||
|
||||
type CommonProps = {
|
||||
variant?: ButtonVariant
|
||||
size?: ButtonSize
|
||||
/** 只有一个符号(× / +)时保持正方形,热区不小于控件高度 */
|
||||
square?: boolean
|
||||
/** 危险语义的描边/幽灵按钮 */
|
||||
danger?: boolean
|
||||
/** 选中态(筛选、分段开关) */
|
||||
on?: boolean
|
||||
children?: ReactNode
|
||||
className?: string
|
||||
}
|
||||
|
||||
type ButtonProps = CommonProps & ButtonHTMLAttributes<HTMLButtonElement> & { href?: undefined }
|
||||
type AnchorProps = CommonProps & AnchorHTMLAttributes<HTMLAnchorElement> & { href: string }
|
||||
|
||||
export const Button = forwardRef<HTMLButtonElement | HTMLAnchorElement, ButtonProps | AnchorProps>(
|
||||
function Button({ variant = 'secondary', size = 'md', square, danger, on, className, children, ...rest }: any, ref) {
|
||||
const classes = cn(
|
||||
BASE,
|
||||
VARIANTS[variant as ButtonVariant],
|
||||
size !== 'md' && SIZES[size as ButtonSize],
|
||||
square && 'w-(--ctl-h) px-0 text-ui',
|
||||
danger && variant === 'outline' && 'text-danger-bright border-danger-line hover:not-disabled:bg-danger-tint-2',
|
||||
danger && variant === 'ghost' && 'text-danger-bright border-danger-line',
|
||||
danger && variant === 'del' && 'bg-danger border-danger text-danger-ink shadow-raise',
|
||||
on && 'border-accent-line bg-accent-tint text-accent-bright',
|
||||
className
|
||||
)
|
||||
/* ref 是「按钮或链接」的联合类型,到这里没法收窄,交给 DOM 元素自己判断 */
|
||||
const nodeRef = ref as Ref<any> | undefined
|
||||
if (rest.href !== undefined) {
|
||||
return <a ref={nodeRef} className={classes} {...(rest as AnchorProps)}>{children}</a>
|
||||
}
|
||||
return <button ref={nodeRef} type="button" className={classes} {...(rest as ButtonProps)}>{children}</button>
|
||||
}
|
||||
)
|
||||
|
|
@ -0,0 +1,188 @@
|
|||
import type { ReactNode } from 'react'
|
||||
import { cn } from '../../lib/cn'
|
||||
|
||||
/**
|
||||
* 控件栏体系(docs/UI规范.md §1~§5 的唯一实现)。
|
||||
*
|
||||
* 症状:筛选栏 / 工具条 / 抽屉字段里「标签在上、控件在下」,一个字段吃掉整行;
|
||||
* 同一行搜索框 38、下拉 31、复选框 16,中心线各走各的;chip 行贴住下方面板。
|
||||
* 做法:布局只在这几个组件里定义,页面只给内容——
|
||||
* <Ctlbar> 含控件的横条(一行、垂直居中、紧凑高度、下边距 12)
|
||||
* <Field> 行内标签字段(标签在左、控件在右;grow / wide / narrow 调宽)
|
||||
* <BarRight> 需要右靠的一组控件(替代写在控件上的 margin-left:auto)
|
||||
* <ChipBar> chip 行(与下方内容强制呼吸 12px)
|
||||
* <FormRow> 短字段栅格(auto-fit 自己降列,页面不写 @media)
|
||||
* <Pager> 分页条(page_size 唯一的家)
|
||||
* 高度一律不写在控件上:容器把 --ctl-h 压到紧凑档,行内控件跟着一起降。
|
||||
*/
|
||||
|
||||
const LABEL = 'flex flex-row items-center gap-1.5 m-0 text-muted text-tiny tracking-[.3px] whitespace-nowrap'
|
||||
/** 控件吃满标签右侧宽度;标签文字本身不拉伸(否则被挤成两行) */
|
||||
const LABEL_CHILD = '[&>label]:flex [&>label]:flex-row [&>label]:items-center [&>label]:gap-1.5 [&>label]:m-0 '
|
||||
+ '[&>label]:text-muted [&>label]:text-tiny [&>label]:tracking-[.3px] [&>label]:whitespace-nowrap'
|
||||
|
||||
const FIELD_INNER = '[&>*]:min-w-0 [&>*]:flex-1 [&_span:first-child]:flex-none [&_input[type=checkbox]]:flex-none [&_input[type=checkbox]]:w-auto [&_input[type=radio]]:flex-none'
|
||||
|
||||
export function Ctlbar({ children, className, as: As = 'div' }: { children: ReactNode; className?: string; as?: any }) {
|
||||
return (
|
||||
<As className={cn('[--ctl-h:var(--ctl-h-md)] flex items-center flex-wrap gap-y-2 gap-x-[10px] min-w-0 mb-3',
|
||||
'[&>*]:min-w-0', LABEL_CHILD, className)}>
|
||||
{children}
|
||||
</As>
|
||||
)
|
||||
}
|
||||
|
||||
/** 卡片内部的动作行:布局同 Ctlbar,但不带 12px 下边距(否则卡片里凭空多一段空白) */
|
||||
export function CardActions({ children, className }: { children: ReactNode; className?: string }) {
|
||||
return (
|
||||
<div className={cn('[--ctl-h:var(--ctl-h-md)] flex items-center flex-wrap gap-y-2 gap-x-[10px] min-w-0 [&>*]:min-w-0', className)}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function BarRight({ children, className }: { children: ReactNode; className?: string }) {
|
||||
return <div className={cn('ml-auto flex items-center gap-2 flex-wrap min-w-0', className)}>{children}</div>
|
||||
}
|
||||
|
||||
type FieldWidth = 'default' | 'grow' | 'narrow' | 'wide' | 'full'
|
||||
const WIDTHS: Record<FieldWidth, string> = {
|
||||
default: 'basis-[170px] shrink grow-0',
|
||||
grow: 'basis-[240px] grow shrink',
|
||||
narrow: 'basis-[122px] shrink grow-0',
|
||||
/** .wide = 「宽字段」而不是「吃满整行」:1360px 抽屉里的下拉会撑到整行 89% */
|
||||
wide: 'basis-[330px] grow shrink max-w-[min(460px,58%)]',
|
||||
full: 'basis-full grow shrink'
|
||||
}
|
||||
|
||||
/** 行内标签字段:`<Field label="类型">…</Field>`;stack 场景交给 <FormRow stack> 统一翻向 */
|
||||
export function Field({ label, required, children, width = 'default', className, hint }: {
|
||||
label?: ReactNode; required?: boolean; children: ReactNode; width?: FieldWidth; className?: string; hint?: ReactNode
|
||||
}) {
|
||||
return (
|
||||
<label className={cn(LABEL, FIELD_INNER, WIDTHS[width], 'min-w-0', className)}>
|
||||
{label && <span className="flex-none">{label}{required && <Req />}</span>}
|
||||
{children}
|
||||
{hint}
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
||||
/** 必填星号:和标签文字同一个 flex item,否则列方向 label 会把「*」顶到下一行 */
|
||||
export function Req() {
|
||||
return <b className="text-danger font-bold ml-[2px]">*</b>
|
||||
}
|
||||
|
||||
/** 长字段(标签在上):抽屉/对话框里的多行文本、上传区用这个 */
|
||||
export function FieldBlock({ label, required, children, className }: {
|
||||
label?: ReactNode; required?: boolean; children: ReactNode; className?: string
|
||||
}) {
|
||||
return (
|
||||
<label className={cn('flex flex-col gap-[5px] mb-[10px] min-w-0', className)}>
|
||||
<span className="flex items-center gap-1 text-muted text-tiny tracking-[.3px] flex-wrap whitespace-nowrap">
|
||||
{label}{required && <Req />}
|
||||
</span>
|
||||
{children}
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
||||
/** 短字段栅格:列数由容器决定,页面不写 @media;stack 把标签退回控件上方 */
|
||||
export function FormRow({ children, cols, tight, stack, className }: {
|
||||
children: ReactNode
|
||||
cols?: 2 | 3 | 4 | 6
|
||||
tight?: boolean
|
||||
stack?: boolean
|
||||
className?: string
|
||||
}) {
|
||||
const tracks = cols === undefined ? 'repeat(auto-fit,minmax(190px,1fr))'
|
||||
: cols === 6 ? 'repeat(6,minmax(78px,1fr))'
|
||||
: `repeat(${cols},minmax(0,1fr))`
|
||||
return (
|
||||
<div className={cn('grid mb-[10px] min-w-0 [&>*]:min-w-0',
|
||||
cols === undefined && 'max-[1180px]:grid-cols-2',
|
||||
(cols === 3 || cols === 4) && 'max-[1180px]:grid-cols-2',
|
||||
(cols === 4 || cols === 6) && 'max-[900px]:grid-cols-2',
|
||||
stack && 'gap-y-[10px] [&>*]:flex-col [&>*]:items-stretch [&>*]:gap-[5px] [&>*]:flex-none [&>*]:w-auto [&>*:not(span)]:w-full',
|
||||
className)}
|
||||
style={{ gridTemplateColumns: tracks, gap: tight ? 8 : undefined }}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** chip / 标签行(规范 §2):与下方内容强制呼吸 12px */
|
||||
export function ChipBar({ children, label, className, top }: { children: ReactNode; label?: ReactNode; className?: string; top?: boolean }) {
|
||||
return (
|
||||
<div className={cn('[--ctl-h:var(--ctl-h-md)] flex items-center gap-1.5 flex-wrap mb-3 min-w-0', top && 'mt-3', className)}>
|
||||
{label && <span className="flex-none text-muted text-tiny tracking-[.6px] font-bold">{label}</span>}
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 筛选/开关胶囊(.chip) */
|
||||
export function Chip({ active, children, onClick, className, title, disabled, as = 'button', href }: {
|
||||
active?: boolean; children: ReactNode; onClick?: () => void; className?: string; title?: string
|
||||
disabled?: boolean; as?: 'button' | 'a'; href?: string
|
||||
}) {
|
||||
const classes = cn('inline-flex items-center justify-center gap-[5px] h-(--ctl-h-md) px-2 text-tiny rounded-pill '
|
||||
+ 'border whitespace-nowrap shrink-0 no-underline transition-colors duration-150',
|
||||
active ? 'bg-accent-fill border-accent-fill text-on-accent font-bold'
|
||||
: 'bg-raise border-line-strong text-ink-3 hover:bg-active hover:text-ink',
|
||||
disabled && 'opacity-40 cursor-not-allowed', className)
|
||||
if (as === 'a') return <a href={href} title={title} className={classes}>{children}</a>
|
||||
return <button type="button" title={title} disabled={disabled} onClick={onClick} className={classes}>{children}</button>
|
||||
}
|
||||
|
||||
/** 选中态胶囊 + 移除叉(多选回显) */
|
||||
export function TagChip({ children, onRemove, className }: { children: ReactNode; onRemove?: () => void; className?: string }) {
|
||||
return (
|
||||
<span className={cn('inline-flex items-center justify-center gap-[5px] h-(--ctl-h-md) px-[9px] text-tiny rounded-pill '
|
||||
+ 'border bg-accent-fill border-accent-fill text-on-accent font-bold whitespace-nowrap shrink-0', className)}>
|
||||
{children}
|
||||
{onRemove && (
|
||||
<button type="button" onClick={onRemove} aria-label="移除"
|
||||
className="grid place-items-center w-[17px] h-[17px] ml-[5px] p-0 flex-none border-0 rounded-full bg-[color-mix(in_srgb,var(--c-on-accent)_20%,transparent)] text-inherit text-[12px] leading-none hover:bg-danger hover:text-danger-ink">×</button>
|
||||
)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** 分页条(规范 §5):page_size 唯一的家,筛选栏里不再出现「每页」 */
|
||||
export function Pager({ page, pages, total, pageSize, onPageSize, onPage, extra }: {
|
||||
page: number; pages: number; total?: number; pageSize?: number
|
||||
onPageSize?: (size: number) => void; onPage: (page: number) => void; extra?: ReactNode
|
||||
}) {
|
||||
const last = Math.max(1, pages)
|
||||
return (
|
||||
<div className="[--ctl-h:var(--ctl-h-md)] flex items-center justify-center gap-[10px] flex-wrap mt-3 text-dim text-tiny">
|
||||
<button type="button" className="h-(--ctl-h-md) px-2 rounded-control border border-line-strong bg-raise text-ink-3 text-tiny disabled:opacity-35"
|
||||
disabled={page <= 1} onClick={() => onPage(page - 1)}>上一页</button>
|
||||
<span>{page} / {last}{total !== undefined ? ` · 共 ${total} 条` : ''}</span>
|
||||
<button type="button" className="h-(--ctl-h-md) px-2 rounded-control border border-line-strong bg-raise text-ink-3 text-tiny disabled:opacity-35"
|
||||
disabled={page >= last} onClick={() => onPage(page + 1)}>下一页</button>
|
||||
{onPageSize && (
|
||||
<label className="flex items-center gap-1.5 m-0 text-muted text-tiny whitespace-nowrap">
|
||||
<span className="flex-none">每页</span>
|
||||
<select value={pageSize} onChange={(e) => onPageSize(Number(e.target.value))} className="w-auto min-w-[64px]">
|
||||
{[12, 20, 24, 30, 48, 60, 120].map((n) => <option key={n} value={n}>{n}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{extra}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 复选(.check):勾选框 + 文案,整块可点 */
|
||||
export function Check({ checked, onChange, children, disabled, className }: {
|
||||
checked: boolean; onChange: (next: boolean) => void; children: ReactNode; disabled?: boolean; className?: string
|
||||
}) {
|
||||
return (
|
||||
<label className={cn('inline-flex flex-row items-center gap-[7px] text-caption text-ink-3 cursor-pointer flex-none whitespace-nowrap', className)}>
|
||||
<input type="checkbox" className="w-auto" checked={checked} disabled={disabled} onChange={(e) => onChange(e.target.checked)} />
|
||||
{children}
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,118 @@
|
|||
import { useEffect, type ReactNode } from 'react'
|
||||
import { cn } from '../../lib/cn'
|
||||
|
||||
/**
|
||||
* 浮层:抽屉(右滑全高)与居中模态。
|
||||
*
|
||||
* 旧站每个页面各抄一份 .drawer-backdrop + .drawer + .drawer-x,
|
||||
* 三处 padding、两处宽度、四种关闭条件互不相同;抽屉内控件高度也因此
|
||||
* 各写各的 --ctl-h(历史散落在 MediaLightbox / AssetLibrary / ModelCenter)。
|
||||
* 现在宽度、留白、高度档只在这里有一份,页面只提供内容。
|
||||
*/
|
||||
|
||||
/** Esc 关闭 + 锁定背后页面滚动(多个浮层叠加时用引用计数,关掉一个不会误放开) */
|
||||
function useOverlay(open: boolean, onClose: () => void, closeOnEsc = true) {
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
if (closeOnEsc) {
|
||||
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') { e.stopPropagation(); onClose() } }
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}
|
||||
return undefined
|
||||
}, [open, onClose, closeOnEsc])
|
||||
}
|
||||
|
||||
let locked = 0
|
||||
function useScrollLock(open: boolean) {
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
locked += 1
|
||||
const prev = document.body.style.overflow
|
||||
document.body.style.overflow = 'hidden'
|
||||
return () => {
|
||||
locked = Math.max(0, locked - 1)
|
||||
if (locked === 0) document.body.style.overflow = prev
|
||||
}
|
||||
}, [open])
|
||||
}
|
||||
|
||||
export function Drawer({ open, onClose, eyebrow, title, sub, children, actions, wide, closeOnBackdrop = true, label }: {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
/** 眉标(ASSET · 人物 / EDIT MODEL) */
|
||||
eyebrow?: ReactNode
|
||||
title: ReactNode
|
||||
sub?: ReactNode
|
||||
children: ReactNode
|
||||
/** 底部动作条;不传就不渲染这一行 */
|
||||
actions?: ReactNode
|
||||
/** 超长表单抽屉:宽档 1360px(默认)已是上限,此参数留给更窄的场景 */
|
||||
wide?: boolean
|
||||
closeOnBackdrop?: boolean
|
||||
label?: string
|
||||
}) {
|
||||
useOverlay(open, onClose)
|
||||
useScrollLock(open)
|
||||
if (!open) return null
|
||||
return (
|
||||
<div className="fixed inset-0 z-[100] flex justify-end bg-scrim backdrop-blur-[4px]"
|
||||
onMouseDown={(e) => { if (closeOnBackdrop && e.target === e.currentTarget) onClose() }}>
|
||||
<section role="dialog" aria-modal="true" aria-label={typeof label === 'string' ? label : undefined}
|
||||
className={cn('flex flex-col min-w-0 h-screen border-l border-line-strong bg-shell shadow-drawer',
|
||||
'w-[min(1360px,calc(100vw-20px))] max-[1440px]:w-[calc(100vw-16px)] max-[820px]:w-screen')}>
|
||||
<header className="flex-none flex justify-between items-start gap-[14px] p-[20px_24px_15px] max-[820px]:p-[20px_14px_15px] border-b border-[--c-bg-emphasis] bg-[linear-gradient(120deg,var(--c-bg-raised),var(--c-bg-panel)_55%)]">
|
||||
<div className="min-w-0">
|
||||
{eyebrow && <small className="text-tiny tracking-[1.6px] text-muted font-bold">{eyebrow}</small>}
|
||||
<h2 className="text-lg font-bold mt-[5px] mb-0">{title}</h2>
|
||||
{sub && <p className="mt-[5px] mb-0 text-tiny text-dim leading-[1.6]">{sub}</p>}
|
||||
</div>
|
||||
<button type="button" aria-label="关闭" onClick={onClose}
|
||||
className="flex-none grid place-items-center w-(--ctl-h-md) h-(--ctl-h-md) border border-line-strong rounded-tile bg-card text-ink-2 text-ui hover:border-[--c-accent-deep] hover:text-accent-bright hover:bg-accent-tint">✕</button>
|
||||
</header>
|
||||
<div className="flex-1 min-w-0 overflow-y-auto scrollbar-slim p-[20px_24px_24px] max-[820px]:p-[20px_14px_14px] [scrollbar-gutter:stable]">
|
||||
{children}
|
||||
</div>
|
||||
{actions && (
|
||||
<footer className="flex-none flex items-center gap-2 p-[14px_24px] max-[820px]:p-[14px] border-t border-line bg-raised [--ctl-h:var(--ctl-h-md)]">
|
||||
{actions}
|
||||
</footer>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 居中模态:只放一两句确认文案 + 两个动作;长表单请用 Drawer */
|
||||
export function Modal({ open, onClose, title, children, footer, width = 560, closeOnBackdrop = true, label }: {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
title?: ReactNode
|
||||
children: ReactNode
|
||||
footer?: ReactNode
|
||||
width?: number
|
||||
closeOnBackdrop?: boolean
|
||||
label?: string
|
||||
}) {
|
||||
useOverlay(open, onClose)
|
||||
useScrollLock(open)
|
||||
if (!open) return null
|
||||
return (
|
||||
<div className="fixed inset-0 z-[110] grid place-items-center p-4 bg-scrim backdrop-blur-[4px]"
|
||||
onMouseDown={(e) => { if (closeOnBackdrop && e.target === e.currentTarget) onClose() }}>
|
||||
<section role="dialog" aria-modal="true" aria-label={label}
|
||||
style={{ maxWidth: width }}
|
||||
className="w-full max-w-full bg-shell border border-line-strong rounded-float shadow-pop overflow-hidden max-h-[calc(100vh-32px)] flex flex-col">
|
||||
{title && (
|
||||
<header className="flex-none flex items-center justify-between gap-3 p-[14px_18px] border-b border-[--c-bg-emphasis] bg-[linear-gradient(120deg,var(--c-bg-raised),var(--c-bg-panel)_55%)]">
|
||||
<h2 className="text-md font-bold m-0">{title}</h2>
|
||||
<button type="button" aria-label="关闭" onClick={onClose}
|
||||
className="flex-none grid place-items-center w-(--ctl-h-md) h-(--ctl-h-md) border border-line-strong rounded-tile bg-card text-ink-2 text-ui hover:text-accent-bright hover:bg-accent-tint">✕</button>
|
||||
</header>
|
||||
)}
|
||||
<div className="flex-1 min-w-0 overflow-y-auto scrollbar-slim p-[18px] [scrollbar-gutter:stable]">{children}</div>
|
||||
{footer && <footer className="flex-none flex items-center justify-end gap-2 p-[12px_18px] border-t border-line bg-raised [--ctl-h:var(--ctl-h-md)]">{footer}</footer>}
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,164 @@
|
|||
import type { CSSProperties, ReactNode } from 'react'
|
||||
import { cn } from '../../lib/cn'
|
||||
|
||||
/** 面板:站内唯一的「有边框的内容块」。窄屏自动收窄内边距(旧站每个页面自己写一遍)。 */
|
||||
export function Panel({ children, className, style, pad = true }: {
|
||||
children?: ReactNode; className?: string; style?: CSSProperties; pad?: boolean
|
||||
}) {
|
||||
return (
|
||||
<section style={style} className={cn('bg-panel border border-line rounded-block p-[18px] max-[560px]:p-[13px] min-w-0', pad && '', className)}>
|
||||
{children}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/** 面板头:标题 + 右侧动作。窄列必须允许换行,否则筛选控件会把面板内容顶出边界。 */
|
||||
export function PanelHead({ title, sub, right, className }: {
|
||||
title?: ReactNode; sub?: ReactNode; right?: ReactNode; className?: string
|
||||
}) {
|
||||
return (
|
||||
<div className={cn('flex justify-between items-center gap-3 flex-wrap mb-[18px] min-w-0 [&>*]:min-w-0', className)}>
|
||||
<div className="min-w-0">
|
||||
{title && <h3 className="m-0 text-title font-bold">{title}</h3>}
|
||||
{sub && <p className="mt-[5px] mb-0 text-caption text-dim leading-[1.6]">{sub}</p>}
|
||||
</div>
|
||||
{right && <div className="flex items-center gap-2 flex-wrap min-w-0">{right}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 眉标(面板上方那行全大写小字) */
|
||||
export function Eyebrow({ children, className }: { children: ReactNode; className?: string }) {
|
||||
return <div className={cn('text-tiny tracking-[1.6px] text-muted font-bold', className)}>{children}</div>
|
||||
}
|
||||
|
||||
/** 小标题 + 右侧动作(.small-label / .sect-act:增删按钮一律贴在标题行右端) */
|
||||
export function SectionTitle({ children, action, className }: { children: ReactNode; action?: ReactNode; className?: string }) {
|
||||
return (
|
||||
<div className={cn('flex items-center gap-2 flex-wrap text-tiny text-faint tracking-[.6px] font-bold mt-[14px] mb-2', className)}>
|
||||
<span>{children}</span>
|
||||
{action && <span className="ml-auto inline-flex items-center gap-2 [--ctl-h:var(--ctl-h-md)]">{action}</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 指标卡 */
|
||||
export function Stat({ label, value, hint, className }: { label: ReactNode; value: ReactNode; hint?: ReactNode; className?: string }) {
|
||||
return (
|
||||
<div className={cn('bg-panel border border-line rounded-block p-[18px] min-w-0 max-[560px]:p-[13px]', className)}>
|
||||
<small className="block text-muted text-tiny">{label}</small>
|
||||
<b className="block text-num mt-[9px] font-bold max-[560px]:text-num-sm break-words">{value}</b>
|
||||
{hint && <small className="block text-faint text-tiny mt-[6px]">{hint}</small>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 指标卡栅格:4 → 2 → 1 由容器自己降列,页面不写 @media */
|
||||
export function StatGrid({ children, cols = 4, className }: { children: ReactNode; cols?: number; className?: string }) {
|
||||
return (
|
||||
<div className={cn('grid gap-3 mb-[17px] grid-cols-[repeat(var(--cols),minmax(0,1fr))] max-[1100px]:grid-cols-2 max-[560px]:gap-2', className)}
|
||||
style={{ ['--cols' as string]: cols }}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 进度条(.bar / .bar i) */
|
||||
export function ProgressBar({ value, bad, className }: { value: number; bad?: boolean; className?: string }) {
|
||||
const pct = Math.max(0, Math.min(100, Number(value) || 0))
|
||||
return (
|
||||
<span className={cn('inline-block h-[5px] bg-active rounded-pill overflow-hidden min-w-[60px] align-middle', className)}>
|
||||
<i className={cn('block h-full', bad ? 'bg-danger' : 'bg-accent-fill')} style={{ width: `${pct}%` }} />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export function Divider({ className }: { className?: string }) {
|
||||
return <div className={cn('h-px bg-active my-4', className)} />
|
||||
}
|
||||
|
||||
export function Empty({ children = '暂无数据', className }: { children?: ReactNode; className?: string }) {
|
||||
return <div className={cn('border border-dashed border-line-strong rounded-tile p-7 text-center text-faint', className)}>{children}</div>
|
||||
}
|
||||
|
||||
export function Loading({ children = '读取中…', className }: { children?: ReactNode; className?: string }) {
|
||||
return <div className={cn('p-[26px] text-center text-faint text-body', className)}>{children}</div>
|
||||
}
|
||||
|
||||
export function Spinner({ className }: { className?: string }) {
|
||||
return <i aria-hidden className={cn('inline-block w-[11px] h-[11px] border-2 border-line-bright border-t-accent rounded-full animate-spin-slow align-[-1px]', className)} />
|
||||
}
|
||||
|
||||
/** 提示条:成功用默认(青柠底),错误用 danger;只放一句人话,长说明收进抽屉 */
|
||||
export function Notice({ children, danger, className, onClose }: {
|
||||
children: ReactNode; danger?: boolean; className?: string; onClose?: () => void
|
||||
}) {
|
||||
if (!children) return null
|
||||
return (
|
||||
<div className={cn('flex items-start gap-2 p-[11px] rounded-[8px] border mb-4 text-[11.5px] leading-[1.6] break-words break-anywhere',
|
||||
danger ? 'border-danger-line bg-danger-tint text-danger-bright' : 'border-accent-line bg-accent-tint-2 text-accent-bright',
|
||||
className)}>
|
||||
<div className="min-w-0 flex-1">{children}</div>
|
||||
{onClose && (
|
||||
<button onClick={onClose} aria-label="关闭提示"
|
||||
className="shrink-0 border-0 bg-transparent text-inherit text-ui leading-none p-0 opacity-70 hover:opacity-100">×</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 数据回显(.val)与条件告警(.linehint):规范 §7 G2 —— 版面不放成段解释文字 */
|
||||
export function Value({ children, muted, className }: { children: ReactNode; muted?: boolean; className?: string }) {
|
||||
return <div className={cn('text-caption text-ink-2 leading-[1.6] break-anywhere', muted && 'text-faint', className)}>{children}</div>
|
||||
}
|
||||
|
||||
export function LineHint({ children, className }: { children: ReactNode; className?: string }) {
|
||||
return <div className={cn('flex items-baseline gap-1.5 text-[10.5px] leading-[1.5] text-warn mt-[6px]', className)}>{children}</div>
|
||||
}
|
||||
|
||||
/** 等宽小字(路径 / id / 枚举码) */
|
||||
export function Mono({ children, className, title }: { children: ReactNode; className?: string; title?: string }) {
|
||||
return <span title={title} className={cn('font-mono text-[10.5px] tracking-[-.2px]', className)}>{children}</span>
|
||||
}
|
||||
|
||||
/** 文字链(.link):导航用 <Link>,这里只给「打开外部资源 / 下载」 */
|
||||
export function ExtLink({ href, children, className, download }: { href: string; children: ReactNode; className?: string; download?: boolean | string }) {
|
||||
return <a href={href} download={download} target="_blank" rel="noreferrer" className={cn('text-success text-caption no-underline hover:underline', className)}>{children}</a>
|
||||
}
|
||||
|
||||
/** 卡片行(.cardrow):标题 + 说明 + 右侧动作,列表里重复项的统一骨架 */
|
||||
export function CardRow({ title, children, right, className, tone = 'border' }: {
|
||||
title?: ReactNode; children?: ReactNode; right?: ReactNode; className?: string; tone?: 'border' | 'plain'
|
||||
}) {
|
||||
return (
|
||||
<div className={cn('flex justify-between gap-3 items-start py-3', tone === 'border' && 'border-b border-active last:border-b-0', className)}>
|
||||
<div className="min-w-0 flex-1">
|
||||
{title && <h4 className="m-0 mb-1 text-[12.5px] font-semibold">{title}</h4>}
|
||||
{children && <div className="[&_p]:m-[3px]_0 [&_p]:text-caption [&_p]:text-muted [&_p]:leading-[1.55]">{children}</div>}
|
||||
</div>
|
||||
{right && <div className="flex items-center gap-2 shrink-0 [--ctl-h:var(--ctl-h-md)]">{right}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 元信息一行(.meta) */
|
||||
export function Meta({ children, className }: { children: ReactNode; className?: string }) {
|
||||
return <div className={cn('flex gap-[9px] items-center text-muted text-tiny flex-wrap min-w-0', className)}>{children}</div>
|
||||
}
|
||||
|
||||
/** 行内动作组(.actions) */
|
||||
export function Actions({ children, className }: { children: ReactNode; className?: string }) {
|
||||
return <div className={cn('flex items-center gap-[7px] flex-wrap mt-2 min-w-0 [--ctl-h:var(--ctl-h-md)]', className)}>{children}</div>
|
||||
}
|
||||
|
||||
/** 通用栅格:.grid(4) .grid2 .grid3 .grid4 —— 1fr 轨道配 min-w-0,防止内容把列顶宽 */
|
||||
export function Grid({ children, cols = 4, gap = 12, className, min = 0 }: {
|
||||
children: ReactNode; cols?: number | string; gap?: number; className?: string; min?: number
|
||||
}) {
|
||||
return (
|
||||
<div className={cn('grid min-w-0 [&>*]:min-w-0', className)}
|
||||
style={{ gridTemplateColumns: `repeat(${cols},minmax(${min}px,1fr))`, gap }}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
import { type ReactNode } from 'react'
|
||||
import { cn } from '../../lib/cn'
|
||||
|
||||
/**
|
||||
* 事件流行 / 校验结果行。
|
||||
*
|
||||
* 两者形状不同,不能互相套:事件流的时间、操作人、正文是定列的(54px +
|
||||
* 姓名 + 正文),而预检结果的条数与文案长短都不固定,套定列栅格会让裸文本
|
||||
* 去抢列宽。所以一个走 grid、一个走 flex-wrap。
|
||||
*/
|
||||
export function LogRow({ time, who, children, level, className, onClick }: {
|
||||
time: ReactNode; who?: ReactNode; children: ReactNode; level?: string; className?: string; onClick?: () => void
|
||||
}) {
|
||||
return (
|
||||
<div onClick={onClick}
|
||||
className={cn('grid grid-cols-[54px_minmax(86px,108px)_minmax(0,1fr)] gap-[9px] p-[8px_2px] border-b border-line-soft text-body max-[560px]:grid-cols-[50px_minmax(0,1fr)_66px]',
|
||||
onClick && 'cursor-pointer',
|
||||
level === 'error' && 'text-danger',
|
||||
(level === 'warning' || level === 'warn') && 'text-warn', className)}>
|
||||
<time className="text-tiny text-dim">{time}</time>
|
||||
<span className="text-tiny text-muted leading-[1.35] break-anywhere">{who}</span>
|
||||
<p className="m-0 text-ink-2 leading-[1.5] break-anywhere">{children}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 事件流容器:日志可以很长,超过 460px 自己滚 */
|
||||
export function LogBox({ children, className, maxHeight = 460 }: { children: ReactNode; className?: string; maxHeight?: number | false }) {
|
||||
return (
|
||||
<div className={cn('flex flex-col overflow-auto scrollbar-slim', className)}
|
||||
style={maxHeight ? { maxHeight } : undefined}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function IssueRow({ level, children, className }: { level?: string; children: ReactNode; className?: string }) {
|
||||
return (
|
||||
<div className={cn('flex flex-row flex-wrap items-center gap-[7px] p-[8px_2px] border-b border-line-soft text-body leading-[1.5]',
|
||||
level === 'error' && 'text-danger',
|
||||
(level === 'warning' || level === 'warn') && 'text-warn', className)}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
import { type ReactNode } from 'react'
|
||||
import { cn } from '../../lib/cn'
|
||||
|
||||
/**
|
||||
* 数值滑杆 + 当前值。
|
||||
*
|
||||
* 旧站滑杆散在 ModelCenter / Timeline 里各自写 height:5px + accent-color,
|
||||
* 值只出现在 label 里,拖动时看不到反馈。这里把「值」和「尺子」绑在一起。
|
||||
*/
|
||||
export function Slider({ value, min = 0, max = 1, step = 0.01, onChange, label, hint, format, disabled, className }: {
|
||||
value: number
|
||||
min?: number
|
||||
max?: number
|
||||
step?: number
|
||||
onChange: (next: number) => void
|
||||
label?: ReactNode
|
||||
hint?: ReactNode
|
||||
format?: (v: number) => ReactNode
|
||||
disabled?: boolean
|
||||
className?: string
|
||||
}) {
|
||||
return (
|
||||
<label className={cn('flex items-center gap-2 min-w-0', className)}>
|
||||
{label && <span className="flex-none text-caption text-muted whitespace-nowrap">{label}</span>}
|
||||
<input type="range" min={min} max={max} step={step} value={value} disabled={disabled}
|
||||
onChange={(e) => onChange(Number(e.target.value))}
|
||||
className="min-w-0 flex-1 h-[5px] p-0 m-0 border-0 accent-[--c-accent-fill]" />
|
||||
<b className="flex-none w-[42px] text-right text-body font-mono text-ink-2 tabular-nums">
|
||||
{format ? format(value) : value}
|
||||
</b>
|
||||
{hint && <span className="flex-none text-tiny text-faint">{hint}</span>}
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,68 @@
|
|||
import type { ReactNode } from 'react'
|
||||
import { cn } from '../../lib/cn'
|
||||
import { statusLabel, statusTone } from '../../lib/format'
|
||||
|
||||
/**
|
||||
* 状态胶囊。
|
||||
*
|
||||
* 旧站用 `:class="statusClass(x)"` 把 CSS 类名字符串拼进 markup,色调含义藏在
|
||||
* format.ts 的返回值里;React 侧改成显式的 tone:色调怎么配色只在这里有一份,
|
||||
* 页面只负责把业务枚举翻译成 tone(lib/format.ts 的 statusTone())。
|
||||
*/
|
||||
export type Tone = 'completed' | 'failed' | 'running' | 'queued' | ''
|
||||
|
||||
const TONES: Record<Tone, string> = {
|
||||
completed: 'bg-accent-tint-2 text-success',
|
||||
failed: 'bg-danger-tint text-danger',
|
||||
running: 'bg-warn-tint text-warn-bright',
|
||||
queued: 'bg-info-tint text-info',
|
||||
'': 'bg-active text-ink-2'
|
||||
}
|
||||
|
||||
export function Status({ value, tone, children, className }: {
|
||||
value?: string | null
|
||||
tone?: Tone
|
||||
children?: ReactNode
|
||||
className?: string
|
||||
}) {
|
||||
const resolved: Tone = tone ?? (value ? statusTone(value) : '')
|
||||
return (
|
||||
<span className={cn('text-tiny rounded-chip px-1.5 py-[3px] whitespace-nowrap inline-flex items-center gap-1',
|
||||
TONES[resolved], className)}>
|
||||
{children ?? statusLabel(value)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** 语义标签(.tag / .tag.ok / .bad / .warn / .info):比 Status 更轻,用于「这是什么东西」而不是「进行到哪」 */
|
||||
export type TagTone = 'default' | 'ok' | 'bad' | 'warn' | 'info' | 'accent' | 'mono'
|
||||
|
||||
const TAG_TONES: Record<TagTone, string> = {
|
||||
default: 'bg-line-soft text-ink-3 border-line',
|
||||
ok: 'bg-success-tint text-success border-success-line',
|
||||
bad: 'bg-danger-tint-2 text-danger border-danger-line',
|
||||
warn: 'bg-warn-tint text-warn border-warn-line',
|
||||
info: 'bg-info-tint text-info border-info-line',
|
||||
accent: 'bg-accent-tint text-accent-bright border-accent-line',
|
||||
mono: 'bg-line-soft text-ink-3 border-line font-mono'
|
||||
}
|
||||
|
||||
export function Tag({ tone = 'default', children, className, title }: {
|
||||
tone?: TagTone
|
||||
children?: ReactNode
|
||||
className?: string
|
||||
title?: string
|
||||
}) {
|
||||
return <span title={title} className={cn('text-tiny px-1.5 py-0.5 rounded-chip border whitespace-nowrap inline-flex items-center gap-1', TAG_TONES[tone], className)}>{children}</span>
|
||||
}
|
||||
|
||||
/** 信息行小圆点徽标(数字气泡) */
|
||||
export function Badge({ children, tone = 'default', className }: { children: ReactNode; tone?: 'default' | 'ok' | 'bad' | 'warn'; className?: string }) {
|
||||
const tones = {
|
||||
default: 'bg-raise text-ink-2 border-line-strong',
|
||||
ok: 'bg-success-tint text-success border-success-line',
|
||||
bad: 'bg-danger-tint text-danger border-danger-line',
|
||||
warn: 'bg-warn-tint text-warn border-warn-line'
|
||||
}
|
||||
return <span className={cn('inline-flex items-center gap-1 rounded-pill border px-2 py-[1px] text-tiny font-semibold', tones[tone], className)}>{children}</span>
|
||||
}
|
||||
|
|
@ -0,0 +1,107 @@
|
|||
import { type ReactNode, type Ref } from 'react'
|
||||
import { cn } from '../../lib/cn'
|
||||
|
||||
/**
|
||||
* 流程节点条里的「一格」(全站唯一一份:WorkflowBar 与项目列表、概览共用)。
|
||||
*
|
||||
* 节点状态口径来自 lib/pipeline.ts:done / active / failed / pending。
|
||||
* 「当前节点」只有 openNode() 一个算法——以前五个地方各算各的,草稿项目会喊
|
||||
* 「当前 · 导出完整视频」,流程全绿之后还在喊最后一个节点名(明明已经交付)。
|
||||
*/
|
||||
export const STATE_LABEL: Record<string, string> = {
|
||||
done: '完成', failed: '需处理', active: '进行中', pending: '待处理'
|
||||
}
|
||||
|
||||
export function stepIcon(state: string, index: number): string {
|
||||
if (state === 'done') return '✓'
|
||||
if (state === 'failed') return '!'
|
||||
if (state === 'active') return '▶'
|
||||
return String(index + 1)
|
||||
}
|
||||
|
||||
/** 后端没有计数的节点显示中文状态;有计数的节点显示 done/total 并夹住分母 */
|
||||
export function nodeProgress(node: any): string {
|
||||
if (node?.done === null || node?.done === undefined) return STATE_LABEL[node?.state] || String(node?.state ?? '')
|
||||
return `${Math.min(node.done, node.total)}/${node.total}`
|
||||
}
|
||||
|
||||
export function nodeHint(node: any): string {
|
||||
return [`${node.label}(${STATE_LABEL[node.state] || node.state})`, node.detail].filter(Boolean).join(' — ')
|
||||
}
|
||||
|
||||
const NUM: Record<string, string> = {
|
||||
done: 'bg-accent-fill text-on-accent',
|
||||
active: 'bg-accent-fill text-on-accent',
|
||||
failed: 'bg-danger text-danger-ink',
|
||||
pending: 'bg-active text-muted'
|
||||
}
|
||||
|
||||
export function Step({ node, index, current, compact, onClick, className }: {
|
||||
node: any
|
||||
index: number
|
||||
current?: boolean
|
||||
compact?: boolean
|
||||
onClick?: (node: any) => void
|
||||
className?: string
|
||||
}) {
|
||||
const st = node.state === 'done' ? 'done' : node.state === 'failed' ? 'failed' : node.state === 'active' ? 'active' : 'pending'
|
||||
return (
|
||||
<div role="listitem" title={nodeHint(node)} data-current={current ? '1' : undefined}
|
||||
onClick={onClick ? () => onClick(node) : undefined}
|
||||
className={cn('flex-1 basis-[118px] min-w-[96px] bg-panel border rounded-tile p-[9px_10px] relative min-w-0 transition-colors',
|
||||
onClick && 'cursor-pointer',
|
||||
current && 'shadow-[0_0_0_1px_var(--c-accent-line)]',
|
||||
st === 'done' && 'border-success-line bg-raised',
|
||||
st === 'active' && 'border-success-line bg-accent-tint shadow-[inset_0_0_0_1px_var(--c-success-line)]',
|
||||
st === 'failed' && 'border-danger-line bg-panel',
|
||||
st === 'pending' && 'border-[--c-bg-active] opacity-70', className)}>
|
||||
<div className={cn('flex items-center gap-[6px] text-[10.5px]', st === 'done' ? 'text-success' : 'text-ink-3')}>
|
||||
<span className={cn('grid place-items-center w-4 h-4 rounded-full text-tiny flex-none', NUM[st])}>{stepIcon(node.state, index)}</span>
|
||||
<span className="min-w-0 truncate">{nodeProgress(node)}</span>
|
||||
</div>
|
||||
<div className={cn('text-body font-semibold mt-[6px] leading-[1.35] line-clamp-2',
|
||||
st === 'active' ? 'text-accent-bright' : st === 'failed' ? 'text-danger-bright' : 'text-ink-2')}>
|
||||
{node.label}
|
||||
</div>
|
||||
{!compact && (
|
||||
<div className="text-tiny text-faint mt-1 leading-[1.4] min-h-[14px] line-clamp-2 break-anywhere">{node.detail}</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function Steps({ nodes, currentKey, compact, onStep, className, id, scrollSmooth, ref }: {
|
||||
nodes: any[]
|
||||
currentKey?: string
|
||||
compact?: boolean
|
||||
onStep?: (node: any, at: number) => void
|
||||
className?: string
|
||||
id?: string
|
||||
scrollSmooth?: boolean
|
||||
/** 横向滚动容器:WorkflowBar 需要量它、并把当前节点滚进视野 */
|
||||
ref?: Ref<HTMLDivElement>
|
||||
}) {
|
||||
const list = nodes || []
|
||||
return (
|
||||
<div ref={ref} id={id} role="list"
|
||||
className={cn('flex gap-[6px] overflow-x-auto scrollbar-slim p-[4px_2px_10px]', scrollSmooth && 'scroll-smooth', className)}>
|
||||
{(list.length ? list : [{ state: 'pending', label: '暂无流程数据' }]).map((n: any, at: number) => (
|
||||
<Step key={n.key ?? at} node={n} index={at} compact={compact} current={!!currentKey && n.key === currentKey}
|
||||
onClick={onStep && list.length ? (node) => onStep(node, at) : undefined} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 流程条底部那一行「已完成 x / y · 当前:xxx」;全绿时不再报最后一个节点名 */
|
||||
export function FlowCaption({ nodes, current, allDone, className }: {
|
||||
nodes: any[]; current?: ReactNode; allDone?: boolean; className?: string
|
||||
}) {
|
||||
const done = (nodes || []).filter((s: any) => s.state === 'done').length
|
||||
return (
|
||||
<div className={cn('mt-[2px] text-tiny text-muted', className)}>
|
||||
已完成 {done} / {nodes.length} 个节点
|
||||
{current ? <> · 当前:{current}</> : allDone ? <> · 流程已全部完成</> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
import type { ReactNode } from 'react'
|
||||
import { cn } from '../../lib/cn'
|
||||
|
||||
/**
|
||||
* 表格。
|
||||
*
|
||||
* 表头 sticky、单元格描边、行悬停底色都收在 <Table> 上(用 [&_th] 之类的子选择器),
|
||||
* 页面因此可以继续写原生 thead/tr/td,不必再 import 一套单元格组件。
|
||||
* 超宽的表格交给外层 TableBox 横向滚动,而不是把整页顶出屏幕。
|
||||
*/
|
||||
export function TableBox({ children, className, maxHeight = 520 }: { children: ReactNode; className?: string; maxHeight?: number | false }) {
|
||||
return (
|
||||
<div className={cn('min-w-0 overflow-auto border border-active rounded-tile [scrollbar-gutter:stable]', className)}
|
||||
style={maxHeight ? { maxHeight } : undefined}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function Table({ children, className, minWidth = 720 }: { children: ReactNode; className?: string; minWidth?: number }) {
|
||||
return (
|
||||
<table className={cn('w-full border-collapse text-label min-w-0',
|
||||
'[&_th]:text-left [&_th]:text-tiny [&_th]:tracking-[.8px] [&_th]:text-faint [&_th]:font-bold [&_th]:px-2 [&_th]:py-[7px]',
|
||||
'[&_th]:border-b [&_th]:border-line [&_th]:whitespace-nowrap [&_th]:bg-shell [&_th]:sticky [&_th]:top-0 [&_th]:z-[1]',
|
||||
'[&_td]:px-2 [&_td]:py-[9px] [&_td]:border-b [&_td]:border-line-soft [&_td]:align-middle',
|
||||
'[&_tbody_tr:hover>td]:bg-panel',
|
||||
className)}>
|
||||
{children}
|
||||
</table>
|
||||
)
|
||||
}
|
||||
|
||||
/** 窄屏时的兜底:表格至少多宽由调用方说清楚(旧站统一 720px) */
|
||||
export function WideTable({ children, className, minWidth = 720 }: { children: ReactNode; className?: string; minWidth?: number }) {
|
||||
return (
|
||||
<TableBox>
|
||||
<div style={{ minWidth }} className="max-[560px]:min-w-[720px]">
|
||||
<Table className={className}>{children}</Table>
|
||||
</div>
|
||||
</TableBox>
|
||||
)
|
||||
}
|
||||
|
||||
/** 单元格对齐辅助:居中 / 右对齐 / 可折行长文本 */
|
||||
export const cellCenter = 'text-center'
|
||||
export const cellRight = 'text-right'
|
||||
export const cellWrap = 'max-w-[340px] whitespace-normal leading-[1.5] break-anywhere'
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
import { type ReactNode } from 'react'
|
||||
import { cn } from '../../lib/cn'
|
||||
|
||||
/**
|
||||
* 分段页签 / 视图切换。
|
||||
*
|
||||
* 旧站 .inspector-tabs>button 与 .view-btn 都是裸 button 靠页面 padding 撑高度,
|
||||
* 量出来 32px(两档之外)。这里统一吃 --ctl-h-md,页面只留配色。
|
||||
*/
|
||||
export function Tabs<T extends string>({ value, onChange, items, className }: {
|
||||
value: T
|
||||
onChange: (next: T) => void
|
||||
items: { value: T; label: ReactNode; hint?: string; count?: number }[]
|
||||
className?: string
|
||||
}) {
|
||||
return (
|
||||
<div className={cn('inline-flex items-center gap-1 flex-wrap p-1 bg-card border border-line rounded-tile [--ctl-h:var(--ctl-h-md)]', className)}>
|
||||
{items.map((it) => {
|
||||
const on = it.value === value
|
||||
return (
|
||||
<button key={it.value} type="button" title={it.hint} onClick={() => onChange(it.value)}
|
||||
className={cn('inline-flex items-center justify-center gap-1 h-(--ctl-h) px-2 rounded-control text-tiny leading-[1.2] border transition-colors',
|
||||
on ? 'bg-accent-fill border-accent-fill text-on-accent font-bold'
|
||||
: 'bg-transparent border-transparent text-ink-3 hover:bg-hover hover:text-ink')}>
|
||||
{it.label}
|
||||
{it.count !== undefined && <span className={cn('text-caption', on ? 'opacity-75' : 'text-faint')}>{it.count}</span>}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 网格 / 列表视图切换(.view-btn) */
|
||||
export function ViewBtn({ active, onClick, children, title, className }: {
|
||||
active?: boolean; onClick?: () => void; children: ReactNode; title?: string; className?: string
|
||||
}) {
|
||||
return (
|
||||
<button type="button" title={title} onClick={onClick}
|
||||
className={cn('inline-flex items-center justify-center gap-[5px] h-(--ctl-h-md) px-[9px] rounded-control border text-tiny leading-[1.2]',
|
||||
active ? 'bg-accent-tint border-accent-line text-accent-bright font-bold'
|
||||
: 'bg-raise border-line-strong text-ink-3 hover:bg-active hover:text-ink', className)}>
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { cn } from '../../lib/cn'
|
||||
|
||||
/** 开关(是/否二选一):勾选框表达不了「立刻生效」的开关语义,这里给一颗明确的滑块 */
|
||||
export function Toggle({ checked, onChange, disabled, label, className }: {
|
||||
checked: boolean; onChange: (next: boolean) => void; disabled?: boolean; label?: string; className?: string
|
||||
}) {
|
||||
return (
|
||||
<label className={cn('inline-flex flex-row items-center gap-2 text-caption text-ink-3 cursor-pointer flex-none whitespace-nowrap', disabled && 'opacity-40 cursor-not-allowed', className)}>
|
||||
<button type="button" role="switch" aria-checked={checked} disabled={disabled}
|
||||
onClick={() => onChange(!checked)}
|
||||
className={cn('relative w-[34px] h-[19px] flex-none rounded-pill border transition-colors',
|
||||
checked ? 'bg-accent-fill border-accent-fill' : 'bg-active border-line-strong')}>
|
||||
<i className={cn('absolute top-[2px] w-[13px] h-[13px] rounded-full bg-card transition-[left]', checked ? 'left-[17px]' : 'left-[2px]')} />
|
||||
</button>
|
||||
{label}
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
export * from './Button'
|
||||
export * from './Status'
|
||||
export * from './Panel'
|
||||
export * from './Controls'
|
||||
export * from './Table'
|
||||
export * from './Overlay'
|
||||
export * from './Steps'
|
||||
export * from './Rows'
|
||||
export * from './Tabs'
|
||||
export * from './Toggle'
|
||||
export * from './Slider'
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
export * from './use-async'
|
||||
export * from './use-polling'
|
||||
export * from './use-outside-click'
|
||||
export * from './use-local-storage'
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
/**
|
||||
* 一次「读接口 → 渲染」的标准生命周期。
|
||||
*
|
||||
* 页面里 90% 的数据获取都是同一个形状:进页面拉一次、点按钮重新拉、
|
||||
* 失败就把 detail 显示出来。写成 Hook 后每个页面少了六行样板,
|
||||
* 更重要的是「组件卸载后不再 setState」这件事只在这里处理一次。
|
||||
*/
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
export type UseAsyncOptions = {
|
||||
/** 默认 true:挂载即执行。纯手动触发(表单提交)时传 false */
|
||||
immediate?: boolean
|
||||
/** 首帧占位值,避免 `data?.map` 之类到处判空 */
|
||||
initial?: any
|
||||
}
|
||||
|
||||
export function useAsync<T = any>(fn: () => Promise<T>, options: UseAsyncOptions = {}) {
|
||||
const { immediate = true, initial = null } = options
|
||||
const [data, setData] = useState<T | null>(initial)
|
||||
const [loading, setLoading] = useState(immediate)
|
||||
const [error, setError] = useState('')
|
||||
const alive = useRef(true)
|
||||
const latest = useRef(fn)
|
||||
latest.current = fn
|
||||
|
||||
useEffect(() => {
|
||||
alive.current = true
|
||||
return () => { alive.current = false }
|
||||
}, [])
|
||||
|
||||
const run = useCallback(async (): Promise<T | null> => {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
const result = await latest.current()
|
||||
if (!alive.current) return null
|
||||
setData(result)
|
||||
return result
|
||||
} catch (exc: any) {
|
||||
if (alive.current) setError(exc?.message || String(exc))
|
||||
return null
|
||||
} finally {
|
||||
if (alive.current) setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (immediate) void run()
|
||||
// 只在挂载时跑一次:依赖变化后的重拉由调用方显式 run()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
return { data, setData, loading, error, setError, run }
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
import { useEffect, useRef } from 'react'
|
||||
|
||||
/**
|
||||
* 自动刷新轮询 —— 旧站它是渲染不出任何界面的 <AutoRefresh/> 组件,
|
||||
* 因为要借用生命周期;React 里钩子本来就是生命周期,于是改成 useAutoRefresh。
|
||||
*
|
||||
* · `every` —— 轮询周期(毫秒);由别处(如项目 store 每 6 秒)负责刷新的页面不挂它;
|
||||
* · `busy` —— 正在请求 / 正在生成时跳过本轮,不抢占;
|
||||
* · `paused` —— 表单抽屉、确认弹窗里有没保存的内容时跳过本轮;
|
||||
* · 标签页切到后台不发请求;切回来发现已经过期一个周期,立刻补一次。
|
||||
*
|
||||
* 数据到点自己刷新是平台的责任,页面上不需要留一行时钟让用户确认数据新不新。
|
||||
*/
|
||||
export function useAutoRefresh(onRefresh: () => void, every = 15000, busy = false, paused = false) {
|
||||
const lastAttempt = useRef(Date.now())
|
||||
const cb = useRef(onRefresh)
|
||||
cb.current = onRefresh
|
||||
const gate = useRef({ busy, paused, every })
|
||||
gate.current = { busy, paused, every }
|
||||
|
||||
useEffect(() => {
|
||||
let timer = 0
|
||||
const tick = () => {
|
||||
const g = gate.current
|
||||
if (g.busy || g.paused || !g.every || document.hidden) return
|
||||
lastAttempt.current = Date.now()
|
||||
cb.current()
|
||||
}
|
||||
const onVisible = () => {
|
||||
if (document.hidden) return
|
||||
// 回到前台:数据已经过期一个周期以上就马上补一次,不等下一个 interval
|
||||
if (Date.now() - lastAttempt.current >= gate.current.every) tick()
|
||||
}
|
||||
// 挂载前父组件已经拉过首屏,别在切回标签页的瞬间再补一次重复请求
|
||||
lastAttempt.current = Date.now()
|
||||
if (every) timer = window.setInterval(tick, every)
|
||||
document.addEventListener('visibilitychange', onVisible)
|
||||
return () => {
|
||||
if (timer) window.clearInterval(timer)
|
||||
document.removeEventListener('visibilitychange', onVisible)
|
||||
}
|
||||
}, [every])
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
/**
|
||||
* 持久化的本地偏好(列宽、开关、上次选的筛选条件)。
|
||||
*
|
||||
* localStorage 在隐私模式 / 配额满时会抛错,读写都要包起来:
|
||||
* 一个偏好记不住不值得让整个页面白屏。
|
||||
*/
|
||||
import { useCallback, useState } from 'react'
|
||||
|
||||
export function readLocal<T = any>(key: string, fallback: T): T {
|
||||
try {
|
||||
const raw = localStorage.getItem(key)
|
||||
if (raw === null) return fallback
|
||||
return JSON.parse(raw) as T
|
||||
} catch {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
export function writeLocal(key: string, value: unknown) {
|
||||
try {
|
||||
if (value === undefined || value === null) localStorage.removeItem(key)
|
||||
else localStorage.setItem(key, JSON.stringify(value))
|
||||
} catch {
|
||||
/* 记不住就算了,当场生效即可 */
|
||||
}
|
||||
}
|
||||
|
||||
export function useLocalStorage<T = any>(key: string, fallback: T) {
|
||||
const [value, setValue] = useState<T>(() => readLocal<T>(key, fallback))
|
||||
const update = useCallback((next: T | ((prev: T) => T)) => {
|
||||
setValue((prev) => {
|
||||
const resolved = typeof next === 'function' ? (next as (p: T) => T)(prev) : next
|
||||
writeLocal(key, resolved)
|
||||
return resolved
|
||||
})
|
||||
}, [key])
|
||||
return [value, update] as const
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
/** 点击(或 Esc)落在 ref 之外时回调:下拉、弹出菜单、抽屉的统一收口方式 */
|
||||
import { useEffect, type RefObject } from 'react'
|
||||
|
||||
export function useOutsideClick(ref: RefObject<HTMLElement | null>, onOutside: () => void, active = true) {
|
||||
useEffect(() => {
|
||||
if (!active) return
|
||||
const onDown = (event: MouseEvent | TouchEvent) => {
|
||||
const node = ref.current
|
||||
if (!node) return
|
||||
if (!node.contains(event.target as Node)) onOutside()
|
||||
}
|
||||
const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') onOutside() }
|
||||
document.addEventListener('mousedown', onDown)
|
||||
document.addEventListener('touchstart', onDown)
|
||||
document.addEventListener('keydown', onKey)
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', onDown)
|
||||
document.removeEventListener('touchstart', onDown)
|
||||
document.removeEventListener('keydown', onKey)
|
||||
}
|
||||
}, [ref, onOutside, active])
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
/**
|
||||
* 轮询:把「setInterval + 最新回调 + 暂停条件」收在一处。
|
||||
*
|
||||
* paused 是这里的关键参数:弹窗打开、正有人在录音时暂停,
|
||||
* 否则刷新一重建列表,抽屉里刚填一半的表单会被连根拔掉。
|
||||
*/
|
||||
import { useEffect, useRef } from 'react'
|
||||
|
||||
export function usePolling(tick: () => void, intervalMs = 6000, paused = false, enabled = true) {
|
||||
const latest = useRef(tick)
|
||||
latest.current = tick
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || intervalMs <= 0) return
|
||||
const timer = window.setInterval(() => {
|
||||
if (!paused && document.visibilityState === 'visible') latest.current()
|
||||
}, intervalMs)
|
||||
return () => window.clearInterval(timer)
|
||||
}, [intervalMs, paused, enabled])
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
import { clsx, type ClassValue } from 'clsx'
|
||||
import { extendTailwindMerge } from 'tailwind-merge'
|
||||
|
||||
/**
|
||||
* 合并 className:后面的类覆盖前面的(`<Button className="w-full">` 才压得住组件默认值)。
|
||||
*
|
||||
* 为什么要 extendTailwindMerge:tailwind-merge 内置的是 Tailwind 默认调色板/字阶,
|
||||
* 它不认识 tokens.css 里定义的语义名。默认配置下 `text-body`(字号)会被误判成
|
||||
* 「文字颜色」,于是 `text-body text-muted` 只留最后一个——字号莫名丢失。
|
||||
* 这里把本站的字阶与圆角登记回对应分组,冲突判定才和真实 CSS 一致。
|
||||
* ⚠️ 改了 tokens.css 里的 --text-* / --radius-* 名单,要同步改这里。
|
||||
*/
|
||||
const twMerge = extendTailwindMerge({
|
||||
extend: {
|
||||
classGroups: {
|
||||
'font-size': [
|
||||
'text-tiny', 'text-caption', 'text-label', 'text-body', 'text-ui', 'text-title',
|
||||
'text-md', 'text-h2', 'text-lg', 'text-num-sm', 'text-num', 'text-h1', 'text-3xl', 'text-display'
|
||||
],
|
||||
'rounded': ['rounded-chip', 'rounded-control', 'rounded-tile', 'rounded-block', 'rounded-float', 'rounded-pill']
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export function cn(...inputs: ClassValue[]): string {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { store } from './store'
|
||||
import { systemMeta } from '../stores/system'
|
||||
|
||||
/** 通用格式化 / 枚举文案工具 */
|
||||
export const emptyText = '—'
|
||||
|
|
@ -134,7 +134,7 @@ const OPTION_FALLBACK: Record<string, [string, string][]> = {
|
|||
*/
|
||||
export function opt(optionKey: string, value?: string | null, fallback = ''): string {
|
||||
if (!value) return fallback || emptyText
|
||||
const list = store.meta?.options?.[optionKey] || []
|
||||
const list = systemMeta()?.options?.[optionKey] || []
|
||||
const hit = list.find((item: any) => item.value === value)
|
||||
if (hit) return hit.label
|
||||
const pair = (OPTION_FALLBACK[optionKey] || []).find(([k]) => k === value)
|
||||
|
|
@ -172,8 +172,14 @@ export function statusLabel(value?: string | null) {
|
|||
return EXTRA_LABELS[value] || value
|
||||
}
|
||||
|
||||
export function statusClass(value?: string | null) {
|
||||
if (!value) return 'status'
|
||||
/**
|
||||
* 状态 → 语义色调(`completed | failed | running | queued | ''`)。
|
||||
*
|
||||
* React 侧不再返回 `class="status xxx"` 字符串:色调由 <Status tone=…> 决定,
|
||||
* 组件不认识具体枚举,页面也不写颜色,见 src/components/ui/Status.tsx。
|
||||
*/
|
||||
export function statusTone(value?: string | null): 'completed' | 'failed' | 'running' | 'queued' | '' {
|
||||
if (!value) return ''
|
||||
const okList = ['succeeded', 'completed', 'approved', 'passed', 'done', 'ready', 'qc_passed', 'generated', 'delivered']
|
||||
const badList = ['failed', 'rejected', 'cancelled', 'blocked', 'error']
|
||||
const runList = ['running', 'retrying', 'composing', 'generating', 'dispatched']
|
||||
|
|
@ -182,7 +188,7 @@ export function statusClass(value?: string | null) {
|
|||
: badList.includes(value) ? 'failed'
|
||||
: runList.includes(value) ? 'running'
|
||||
: queueList.includes(value) ? 'queued' : ''
|
||||
return `status ${kind}`.trim()
|
||||
return kind as 'completed' | 'failed' | 'running' | 'queued' | ''
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ 事件流文案
|
||||
|
|
@ -11,7 +11,6 @@
|
|||
* 2. 音频引擎:全站共用一个 HTMLAudioElement,播放新的自动停掉旧的;
|
||||
* 3. 展示文案:kind 中文、元数据行、下载文件名、失败占位。
|
||||
*/
|
||||
import { reactive } from 'vue'
|
||||
import { fmtBytes, fmtMs, fmtTime, opt } from './format'
|
||||
|
||||
export type MediaKind = 'image' | 'video' | 'audio' | 'doc' | 'none'
|
||||
|
|
@ -373,83 +372,4 @@ export function dedupe(items: MediaItem[]) {
|
|||
return true
|
||||
})
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ *
|
||||
* 全站共享的音频引擎:任意页面播放新音频时,上一段自动停止。
|
||||
* ------------------------------------------------------------------ */
|
||||
export const audioEngine = reactive({
|
||||
src: '',
|
||||
label: '',
|
||||
playing: false,
|
||||
position: 0,
|
||||
duration: 0,
|
||||
volume: 1,
|
||||
})
|
||||
|
||||
let el: HTMLAudioElement | null = null
|
||||
|
||||
function ensureAudio(): HTMLAudioElement {
|
||||
if (el) return el
|
||||
el = new window.Audio()
|
||||
el.preload = 'metadata'
|
||||
el.addEventListener('loadedmetadata', () => { audioEngine.duration = Number.isFinite(el!.duration) ? el!.duration : 0 })
|
||||
el.addEventListener('timeupdate', () => { audioEngine.position = el!.currentTime })
|
||||
el.addEventListener('play', () => { audioEngine.playing = true })
|
||||
el.addEventListener('pause', () => { audioEngine.playing = false })
|
||||
el.addEventListener('ended', () => { audioEngine.playing = false; audioEngine.position = 0 })
|
||||
el.addEventListener('error', () => { audioEngine.playing = false; audioEngine.duration = 0 })
|
||||
return el
|
||||
}
|
||||
|
||||
export function isPlaying(url?: string | null) {
|
||||
return !!url && audioEngine.src === url && audioEngine.playing
|
||||
}
|
||||
|
||||
export function playAudio(url: string, label = '') {
|
||||
if (!url) return
|
||||
const node = ensureAudio()
|
||||
if (audioEngine.src !== url) {
|
||||
node.src = url
|
||||
audioEngine.src = url
|
||||
audioEngine.position = 0
|
||||
audioEngine.duration = 0
|
||||
}
|
||||
audioEngine.label = label
|
||||
void node.play().catch(() => { audioEngine.playing = false })
|
||||
}
|
||||
|
||||
export function pauseAudio() {
|
||||
ensureAudio().pause()
|
||||
audioEngine.playing = false
|
||||
}
|
||||
|
||||
export function toggleAudio(url: string, label = '') {
|
||||
if (isPlaying(url)) pauseAudio()
|
||||
else playAudio(url, label)
|
||||
}
|
||||
|
||||
export function stopAudio() {
|
||||
if (!el) return
|
||||
el.pause()
|
||||
el.removeAttribute('src')
|
||||
el.load()
|
||||
audioEngine.src = ''
|
||||
audioEngine.label = ''
|
||||
audioEngine.playing = false
|
||||
audioEngine.position = 0
|
||||
audioEngine.duration = 0
|
||||
}
|
||||
|
||||
export function seekAudio(seconds: number) {
|
||||
const node = ensureAudio()
|
||||
if (!Number.isFinite(seconds)) return
|
||||
node.currentTime = Math.max(0, seconds)
|
||||
audioEngine.position = seconds
|
||||
}
|
||||
|
||||
export function setVolume(value: number) {
|
||||
const node = ensureAudio()
|
||||
const v = Math.min(1, Math.max(0, value))
|
||||
node.volume = v
|
||||
audioEngine.volume = v
|
||||
}
|
||||
/* 音频播放引擎在 src/stores/audio.ts:它要驱动 React 重渲染,不再是纯函数。 */
|
||||
|
|
@ -3,8 +3,8 @@
|
|||
* 用户如果明确勾了「不设为当前版本」,就在这里把指针退回上一版,
|
||||
* 免得录一段试音就把线上正在用的声线顶掉。
|
||||
*/
|
||||
import * as api from './api'
|
||||
import { notify } from './project'
|
||||
import * as api from '../api/client'
|
||||
import { notify } from '../stores/notice'
|
||||
|
||||
const BASE: Record<string, (id: any, no: number) => string> = {
|
||||
platform: (id, no) => `/api/platform/media/${id}/versions/${no}`,
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
import { createApp } from 'vue'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
import { initTheme } from './theme'
|
||||
import './theme.css'
|
||||
import './style.css'
|
||||
|
||||
initTheme()
|
||||
createApp(App).use(router).mount('#app')
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
/**
|
||||
* 入口:先把主题落到 <html> 上(index.html 里还有一段同款内联脚本,
|
||||
* 作用是「首帧之前」;这里负责之后用户切换主题的生效),再挂载路由。
|
||||
*
|
||||
* 没套 StrictMode:音频引擎、麦克风、轮询都是模块级单例,
|
||||
* StrictMode 的双调用会在开发模式下把它们启停两次,排查问题时极具迷惑性。
|
||||
*/
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { RouterProvider } from 'react-router-dom'
|
||||
import { initTheme } from './stores/theme'
|
||||
import { router, warmupRoutes } from './app/router'
|
||||
import './styles/index.css'
|
||||
|
||||
initTheme()
|
||||
createRoot(document.getElementById('root')!).render(<RouterProvider router={router} />)
|
||||
|
||||
/* 首屏之后预热相邻页面的 chunk(内部走 requestIdleCallback,不抢首屏带宽) */
|
||||
warmupRoutes()
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
/** 待迁移:我的账号(占位,见 .local/vue-ref/src/views/Account.vue) */
|
||||
export default function Account() {
|
||||
return <div className="p-[26px] text-center text-faint text-body">我的账号 迁移中…</div>
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
/** 待迁移:平台资产库(占位,见 .local/vue-ref/src/views/AssetLibrary.vue) */
|
||||
export default function AssetLibrary() {
|
||||
return <div className="p-[26px] text-center text-faint text-body">平台资产库 迁移中…</div>
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
/** 待迁移:项目总览(占位,见 .local/vue-ref/src/views/Dashboard.vue) */
|
||||
export default function Dashboard() {
|
||||
return <div className="p-[26px] text-center text-faint text-body">项目总览 迁移中…</div>
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
/** 待迁移:登录(占位,见 .local/vue-ref/src/views/Login.vue) */
|
||||
export default function Login() {
|
||||
return <div className="p-[26px] text-center text-faint text-body">登录 迁移中…</div>
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
/** 待迁移:模型管理中心(占位,见 .local/vue-ref/src/views/ModelCenter.vue) */
|
||||
export default function ModelCenter() {
|
||||
return <div className="p-[26px] text-center text-faint text-body">模型管理中心 迁移中…</div>
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
/* 待迁移:项目工作台(占位,见 .local/vue-ref/src/views/ProjectDetail.vue) */
|
||||
import { Outlet } from 'react-router-dom'
|
||||
|
||||
export default function ProjectDetail() {
|
||||
return (
|
||||
<div>
|
||||
项目工作台迁移中…
|
||||
<Outlet />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
/** 待迁移:用户管理(占位,见 .local/vue-ref/src/views/UserAdmin.vue) */
|
||||
export default function UserAdmin() {
|
||||
return <div className="p-[26px] text-center text-faint text-body">用户管理 迁移中…</div>
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
/** 待迁移:导出与成本(占位,见 .local/vue-ref/src/views/tabs/Delivery.vue) */
|
||||
export default function Delivery() {
|
||||
return <div className="p-[26px] text-center text-faint text-body">导出与成本 迁移中…</div>
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
/** 待迁移:调度中心(占位,见 .local/vue-ref/src/views/tabs/Dispatch.vue) */
|
||||
export default function Dispatch() {
|
||||
return <div className="p-[26px] text-center text-faint text-body">调度中心 迁移中…</div>
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
/** 待迁移:资产管理(占位,见 .local/vue-ref/src/views/tabs/Library.vue) */
|
||||
export default function Library() {
|
||||
return <div className="p-[26px] text-center text-faint text-body">资产管理 迁移中…</div>
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
/** 待迁移:流程概览(占位,见 .local/vue-ref/src/views/tabs/Overview.vue) */
|
||||
export default function Overview() {
|
||||
return <div className="p-[26px] text-center text-faint text-body">流程概览 迁移中…</div>
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
/** 待迁移:质检与审核(占位,见 .local/vue-ref/src/views/tabs/Review.vue) */
|
||||
export default function Review() {
|
||||
return <div className="p-[26px] text-center text-faint text-body">质检与审核 迁移中…</div>
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
/** 待迁移:分镜与脚本(占位,见 .local/vue-ref/src/views/tabs/Storyboard.vue) */
|
||||
export default function Storyboard() {
|
||||
return <div className="p-[26px] text-center text-faint text-body">分镜与脚本 迁移中…</div>
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
/** 待迁移:时间线合成(占位,见 .local/vue-ref/src/views/tabs/TimelineTab.vue) */
|
||||
export default function Timeline() {
|
||||
return <div className="p-[26px] text-center text-faint text-body">时间线合成 迁移中…</div>
|
||||
}
|
||||
|
|
@ -1,67 +0,0 @@
|
|||
import { reactive, ref, watch } from 'vue'
|
||||
import * as api from './api'
|
||||
import { active } from './store'
|
||||
import { recordingBusy } from './recordingGuard'
|
||||
|
||||
/** 项目详情共享状态(父组件加载,各 Tab 复用/触发刷新) */
|
||||
export const pctx = reactive<{
|
||||
id: number | null
|
||||
project: any
|
||||
workflow: any[]
|
||||
stats: any
|
||||
loading: boolean
|
||||
error: string
|
||||
notice: string
|
||||
polling: boolean
|
||||
lastLoad: number
|
||||
}>({ id: null, project: null, workflow: [], stats: null, loading: true, error: '', notice: '', polling: true, lastLoad: 0 })
|
||||
|
||||
let timer: number | undefined
|
||||
|
||||
export async function loadProject(id: number, silent = true) {
|
||||
pctx.id = id
|
||||
if (!silent) pctx.loading = true
|
||||
try {
|
||||
const data = await api.get(`/api/projects/${id}`)
|
||||
pctx.project = data
|
||||
pctx.workflow = data.workflow || []
|
||||
pctx.stats = data.stats || null
|
||||
pctx.error = ''
|
||||
pctx.lastLoad = Date.now()
|
||||
active.project = data
|
||||
} catch (exc: any) {
|
||||
pctx.error = exc.message
|
||||
} finally {
|
||||
pctx.loading = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 项目概况(4 张指标卡 + 12 节点流程条)的折叠状态。
|
||||
* 放在共享层而不是 ProjectDetail 私有:「分镜与脚本」正文最重(看板 + 编辑抽屉),
|
||||
* 工作台自己也得有办法让上面那两屏立刻让位。偏好记 localStorage,跨页签保持。 */
|
||||
const BRIEF_KEY = 'nex.project.brief.open'
|
||||
const savedBrief = localStorage.getItem(BRIEF_KEY)
|
||||
export const briefOpen = ref(savedBrief === null ? true : savedBrief === '1')
|
||||
watch(briefOpen, (open) => localStorage.setItem(BRIEF_KEY, open ? '1' : '0'))
|
||||
|
||||
export function startPolling(id: number, intervalMs = 6000) {
|
||||
stopPolling()
|
||||
timer = window.setInterval(() => {
|
||||
// 正有人在录音就跳过这一轮:刷新会重建资产卡片,卡片里的录音面板跟着卸载,
|
||||
// 麦克风和刚录的波形一起没(录完关闭面板后下一轮自然恢复)
|
||||
if (pctx.polling && !recordingBusy.value && pctx.id === id) loadProject(id)
|
||||
}, intervalMs)
|
||||
}
|
||||
|
||||
export function stopPolling() {
|
||||
if (timer) { window.clearInterval(timer); timer = undefined }
|
||||
}
|
||||
|
||||
/** 变更类操作后统一刷新项目状态 */
|
||||
export const refresh = () => (pctx.id ? loadProject(pctx.id) : Promise.resolve())
|
||||
|
||||
/** 顶部提示条,短暂显示 */
|
||||
export function notify(message: string) {
|
||||
pctx.notice = message
|
||||
window.setTimeout(() => { if (pctx.notice === message) pctx.notice = '' }, 6000)
|
||||
}
|
||||
|
|
@ -1,28 +0,0 @@
|
|||
/**
|
||||
* 「有人在录音」的全局计数。
|
||||
*
|
||||
* 录音面板(RecordAudio)是挂在素材卡片里的小组件,麦克风流、已录波形、试听 URL
|
||||
* 全是它的局部状态。卡片一旦在轮询刷新中被换掉,组件卸载,`onBeforeUnmount` 会
|
||||
* 把麦克风还给系统、这段录音当场蒸发 —— 用户举着麦克风说了半分钟,回来发现面板
|
||||
* 没了。所以轮询必须知道「现在正有人在录」,把这一轮让过去。
|
||||
*
|
||||
* 放模块级而不是组件级:面板可以同时开着好几个(平台声线卡 + 生成抽屉各一个),
|
||||
* 任何一个开着都得让轮询停下来。
|
||||
*/
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
const openSheets = ref(0)
|
||||
|
||||
/** 页面用它把自动刷新暂停掉:`paused="modalOpen || recordingBusy"` */
|
||||
export const recordingBusy = computed(() => openSheets.value > 0)
|
||||
|
||||
/** 面板打开时登记,返回释放函数(关闭 / 卸载时必须调用,否则轮询永远醒不过来) */
|
||||
export function beginRecordingSheet(): () => void {
|
||||
openSheets.value += 1
|
||||
let released = false
|
||||
return () => {
|
||||
if (released) return
|
||||
released = true
|
||||
openSheets.value = Math.max(0, openSheets.value - 1)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,85 +0,0 @@
|
|||
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
|
||||
import Dashboard from './views/Dashboard.vue'
|
||||
import { auth, refreshState } from './auth'
|
||||
|
||||
/**
|
||||
* 路由级懒加载。
|
||||
*
|
||||
* 之前 11 个视图全部静态 import:打开「平台资产库」也要先把
|
||||
* 分镜(317kB)/资产(256kB)/模型中心(176kB)……一整套模块下载并编译完
|
||||
* ——开发模式下首屏 77 个请求 / 4.7MB,其中 1.9MB 是这次根本用不到的页面。
|
||||
* 现在只保留入口页(项目列表)同步加载,其余按路由切分:
|
||||
* 点进哪个页面才拉哪个页面的 chunk,构建产物也跟着变成按路由分包。
|
||||
*/
|
||||
const routes: RouteRecordRaw[] = [
|
||||
{ path: '/', name: 'dashboard', component: Dashboard, meta: { title: '项目' } },
|
||||
{ path: '/assets', name: 'assets', component: () => import('./views/AssetLibrary.vue'), meta: { title: '平台资产库' } },
|
||||
{ path: '/models', name: 'models', component: () => import('./views/ModelCenter.vue'), meta: { title: '模型管理中心' } },
|
||||
{
|
||||
path: '/projects/:id',
|
||||
component: () => import('./views/ProjectDetail.vue'),
|
||||
props: true,
|
||||
children: [
|
||||
{ path: '', redirect: (to: any) => `/projects/${to.params.id}/overview` },
|
||||
{ path: 'overview', name: 'overview', component: () => import('./views/tabs/Overview.vue'), meta: { title: '流程概览' } },
|
||||
{ path: 'library', name: 'library', component: () => import('./views/tabs/Library.vue'), meta: { title: '资产管理' } },
|
||||
{ path: 'storyboard', name: 'storyboard', component: () => import('./views/tabs/Storyboard.vue'), meta: { title: '分镜与脚本' } },
|
||||
{ path: 'dispatch', name: 'dispatch', component: () => import('./views/tabs/Dispatch.vue'), meta: { title: '调度中心' } },
|
||||
{ path: 'review', name: 'review', component: () => import('./views/tabs/Review.vue'), meta: { title: '质检与审核' } },
|
||||
{ path: 'timeline', name: 'timeline', component: () => import('./views/tabs/TimelineTab.vue'), meta: { title: '时间线合成' } },
|
||||
{ path: 'delivery', name: 'delivery', component: () => import('./views/tabs/Delivery.vue'), meta: { title: '导出与成本' } }
|
||||
]
|
||||
},
|
||||
{ path: '/login', name: 'login', component: () => import('./views/Login.vue'), meta: { title: '登录', public: true } },
|
||||
{ path: '/account', name: 'account', component: () => import('./views/Account.vue'), meta: { title: '我的账号' } },
|
||||
{ path: '/users', name: 'users', component: () => import('./views/UserAdmin.vue'), meta: { title: '用户管理', admin: true } },
|
||||
{ path: '/:pathMatch(.*)*', redirect: '/' }
|
||||
]
|
||||
|
||||
const router = createRouter({ history: createWebHistory(), routes })
|
||||
|
||||
/**
|
||||
* 登录守卫。
|
||||
*
|
||||
* 后端默认开启鉴权(未登录时所有 /api/* 都是 401),所以进入任何业务路由之前
|
||||
* 先确认「当前是谁」:
|
||||
* - 只在第一次导航时打一次 /api/auth/state,之后靠 401 回调把快照清空;
|
||||
* - 后端连不上(auth.offline)或管理员把鉴权关掉,都不要把人赶到登录页——
|
||||
* 否则网络抖一下就得重新登录;
|
||||
* - meta.admin 的页面(用户管理)只有管理员能进,其他人送回项目总览。
|
||||
*/
|
||||
router.beforeEach(async (to) => {
|
||||
if (to.meta.public) {
|
||||
// 已经登录就不再停在登录页
|
||||
if (to.path === '/login' && auth.checked && auth.user && !auth.offline) return { path: '/' }
|
||||
return true
|
||||
}
|
||||
if (!auth.checked) await refreshState()
|
||||
if (auth.offline || !auth.enabled) return true
|
||||
if (!auth.user) return { path: '/login', query: { next: to.fullPath } }
|
||||
if (to.meta.admin && auth.user.role !== 'admin') return { path: '/' }
|
||||
return true
|
||||
})
|
||||
|
||||
router.afterEach((to) => {
|
||||
const title = to.meta.title
|
||||
if (typeof title === 'string' && title) document.title = `${title} · Nex Animation Studio`
|
||||
})
|
||||
|
||||
/**
|
||||
* 空闲预取:首屏渲染完成后,把「侧边栏里一定能点到」的相邻页面 chunk 提前拉好,
|
||||
* 这样懒加载不会让用户在真正切换时等一次网络往返。
|
||||
* 只在浏览器空闲时做,绝不和首屏的图片/接口抢带宽。
|
||||
*/
|
||||
const warmup = ['./views/AssetLibrary.vue', './views/ModelCenter.vue', './views/ProjectDetail.vue']
|
||||
let warmed = false
|
||||
router.afterEach(() => {
|
||||
if (warmed) return
|
||||
warmed = true
|
||||
const run = () => warmup.forEach((p) => { void import(/* @vite-ignore */ p) })
|
||||
const w = window as any
|
||||
if (typeof w.requestIdleCallback === 'function') w.requestIdleCallback(run, { timeout: 4000 })
|
||||
else setTimeout(run, 1500)
|
||||
})
|
||||
|
||||
export default router
|
||||
|
|
@ -0,0 +1,96 @@
|
|||
/**
|
||||
* 全站共享的音频引擎:任意页面播放新音频时,上一段自动停止。
|
||||
*
|
||||
* 只有一个 HTMLAudioElement,播放状态写进 zustand,播放按钮 / 进度条 / 时间线
|
||||
* 都从这里读,因此不会出现「两个地方同时在响」或「别处已经在播、这张卡片还显示▶」。
|
||||
*/
|
||||
import { create } from 'zustand'
|
||||
|
||||
export type AudioState = {
|
||||
src: string
|
||||
label: string
|
||||
playing: boolean
|
||||
position: number
|
||||
duration: number
|
||||
volume: number
|
||||
set: (patch: Partial<AudioState>) => void
|
||||
}
|
||||
|
||||
export const useAudioStore = create<AudioState>((set) => ({
|
||||
src: '',
|
||||
label: '',
|
||||
playing: false,
|
||||
position: 0,
|
||||
duration: 0,
|
||||
volume: 1,
|
||||
set: (patch) => set(patch)
|
||||
}))
|
||||
|
||||
const S = () => useAudioStore.getState()
|
||||
|
||||
let el: HTMLAudioElement | null = null
|
||||
|
||||
function ensureAudio(): HTMLAudioElement {
|
||||
if (el) return el
|
||||
el = new window.Audio()
|
||||
el.preload = 'metadata'
|
||||
el.addEventListener('loadedmetadata', () => { S().set({ duration: Number.isFinite(el!.duration) ? el!.duration : 0 }) })
|
||||
el.addEventListener('timeupdate', () => { S().set({ position: el!.currentTime }) })
|
||||
el.addEventListener('play', () => { S().set({ playing: true }) })
|
||||
el.addEventListener('pause', () => { S().set({ playing: false }) })
|
||||
el.addEventListener('ended', () => { S().set({ playing: false, position: 0 }) })
|
||||
el.addEventListener('error', () => { S().set({ playing: false, duration: 0 }) })
|
||||
return el
|
||||
}
|
||||
|
||||
export function isPlaying(url?: string | null) {
|
||||
const s = S()
|
||||
return !!url && s.src === url && s.playing
|
||||
}
|
||||
|
||||
/** 组件内订阅「这一条正在播」:返回布尔,不会制造新对象 */
|
||||
export const useIsPlaying = (url?: string | null) =>
|
||||
useAudioStore((s) => !!url && s.src === url && s.playing)
|
||||
|
||||
export function playAudio(url: string, label = '') {
|
||||
if (!url) return
|
||||
const node = ensureAudio()
|
||||
if (S().src !== url) {
|
||||
node.src = url
|
||||
S().set({ src: url, position: 0, duration: 0 })
|
||||
}
|
||||
S().set({ label })
|
||||
void node.play().catch(() => { S().set({ playing: false }) })
|
||||
}
|
||||
|
||||
export function pauseAudio() {
|
||||
ensureAudio().pause()
|
||||
S().set({ playing: false })
|
||||
}
|
||||
|
||||
export function toggleAudio(url: string, label = '') {
|
||||
if (isPlaying(url)) pauseAudio()
|
||||
else playAudio(url, label)
|
||||
}
|
||||
|
||||
export function stopAudio() {
|
||||
if (!el) return
|
||||
el.pause()
|
||||
el.removeAttribute('src')
|
||||
el.load()
|
||||
S().set({ src: '', label: '', playing: false, position: 0, duration: 0 })
|
||||
}
|
||||
|
||||
export function seekAudio(seconds: number) {
|
||||
const node = ensureAudio()
|
||||
if (!Number.isFinite(seconds)) return
|
||||
node.currentTime = Math.max(0, seconds)
|
||||
S().set({ position: seconds })
|
||||
}
|
||||
|
||||
export function setVolume(value: number) {
|
||||
const node = ensureAudio()
|
||||
const v = Math.min(1, Math.max(0, value))
|
||||
node.volume = v
|
||||
S().set({ volume: v })
|
||||
}
|
||||
|
|
@ -1,11 +1,11 @@
|
|||
/**
|
||||
* 账号状态(登录/角色/会话)。
|
||||
* 账号状态(登录 / 角色 / 会话)。
|
||||
*
|
||||
* 后端把会话放在 HttpOnly Cookie 里,所以前端只持有「当前是谁」这一份展示用快照;
|
||||
* 刷新页面靠 /api/auth/state 复原,不往 localStorage 塞 token。
|
||||
*/
|
||||
import { computed, reactive } from 'vue'
|
||||
import * as api from './api'
|
||||
import { create } from 'zustand'
|
||||
import * as api from '../api/client'
|
||||
|
||||
export type AuthUser = {
|
||||
id: number
|
||||
|
|
@ -26,7 +26,7 @@ export type AuthUser = {
|
|||
|
||||
export const ROLE_LABELS: Record<string, string> = { admin: '管理员', editor: '制作', viewer: '观摩' }
|
||||
|
||||
export const auth = reactive<{
|
||||
export type AuthState = {
|
||||
checked: boolean
|
||||
enabled: boolean
|
||||
user: AuthUser | null
|
||||
|
|
@ -35,13 +35,31 @@ export const auth = reactive<{
|
|||
offline: boolean
|
||||
/** 后端建议预填的用户名(首次部署只有种子 admin) */
|
||||
hint: string
|
||||
}>({ checked: false, enabled: true, user: null, error: '', offline: false, hint: '' })
|
||||
set: (patch: Partial<AuthState>) => void
|
||||
}
|
||||
|
||||
export const isAuthenticated = computed(() => !auth.enabled || !!auth.user)
|
||||
export const isAdmin = computed(() => auth.user?.role === 'admin')
|
||||
export const useAuthStore = create<AuthState>((set) => ({
|
||||
checked: false,
|
||||
enabled: true,
|
||||
user: null,
|
||||
error: '',
|
||||
offline: false,
|
||||
hint: '',
|
||||
set: (patch) => set(patch)
|
||||
}))
|
||||
|
||||
/** 非组件环境(路由守卫)读快照 */
|
||||
export const authState = () => useAuthStore.getState()
|
||||
|
||||
/* ── 派生值:全部做成「选择器 Hook」,返回原始值,避免每次渲染产生新对象 ── */
|
||||
export const useIsAuthenticated = () => useAuthStore((s) => !s.enabled || !!s.user)
|
||||
export const useIsAdmin = () => useAuthStore((s) => s.user?.role === 'admin')
|
||||
/** 观摩角色只能看:写操作在前端先禁掉,后端仍会独立拒绝 */
|
||||
export const canEdit = computed(() => ['admin', 'editor'].includes(String(auth.user?.role || '')))
|
||||
export const displayName = computed(() => auth.user?.display_name || auth.user?.username || '')
|
||||
export const useCanEdit = () => useAuthStore((s) => ['admin', 'editor'].includes(String(s.user?.role || '')))
|
||||
export const useDisplayName = () => useAuthStore((s) => s.user?.display_name || s.user?.username || '')
|
||||
|
||||
export const isAdminOf = (user: AuthUser | null) => user?.role === 'admin'
|
||||
export const canEditOf = (user: AuthUser | null) => ['admin', 'editor'].includes(String(user?.role || ''))
|
||||
|
||||
export function roleLabel(role: string) {
|
||||
return ROLE_LABELS[role] || role || '—'
|
||||
|
|
@ -49,36 +67,33 @@ export function roleLabel(role: string) {
|
|||
|
||||
/** 任何请求拿到 401 都说明会话没了:清掉快照,路由守卫会把人送去登录页 */
|
||||
export function markUnauthorized() {
|
||||
if (auth.user) auth.user = null
|
||||
auth.checked = true
|
||||
useAuthStore.getState().set({ user: null, checked: true })
|
||||
}
|
||||
|
||||
api.setUnauthorizedHandler(markUnauthorized)
|
||||
|
||||
export async function refreshState(): Promise<AuthUser | null> {
|
||||
const set = useAuthStore.getState().set
|
||||
try {
|
||||
const data = await api.get('/api/auth/state')
|
||||
auth.enabled = data?.auth_enabled !== false
|
||||
auth.user = data?.user || null
|
||||
auth.hint = String(data?.login_hint?.username || '')
|
||||
auth.offline = false
|
||||
auth.error = ''
|
||||
set({
|
||||
enabled: data?.auth_enabled !== false,
|
||||
user: data?.user || null,
|
||||
hint: String(data?.login_hint?.username || ''),
|
||||
offline: false,
|
||||
error: ''
|
||||
})
|
||||
} catch (exc: any) {
|
||||
auth.offline = true
|
||||
auth.error = exc?.message || String(exc)
|
||||
set({ offline: true, error: exc?.message || String(exc) })
|
||||
} finally {
|
||||
auth.checked = true
|
||||
useAuthStore.getState().set({ checked: true })
|
||||
}
|
||||
return auth.user
|
||||
return useAuthStore.getState().user
|
||||
}
|
||||
|
||||
export async function login(username: string, password: string) {
|
||||
const data = await api.post('/api/auth/login', { username: username.trim(), password })
|
||||
auth.user = data.user
|
||||
auth.enabled = true
|
||||
auth.offline = false
|
||||
auth.error = ''
|
||||
auth.checked = true
|
||||
useAuthStore.getState().set({ user: data.user, enabled: true, offline: false, error: '', checked: true })
|
||||
return data
|
||||
}
|
||||
|
||||
|
|
@ -86,12 +101,11 @@ export async function logout() {
|
|||
try {
|
||||
await api.post('/api/auth/logout')
|
||||
} finally {
|
||||
auth.user = null
|
||||
auth.checked = true
|
||||
useAuthStore.getState().set({ user: null, checked: true })
|
||||
}
|
||||
}
|
||||
|
||||
/** 改密/改资料之后同步快照 */
|
||||
export function setUser(user: AuthUser | null) {
|
||||
auth.user = user
|
||||
useAuthStore.getState().set({ user })
|
||||
}
|
||||
|
|
@ -6,10 +6,14 @@
|
|||
* 各页面表单必须以下面这些函数为唯一取值来源,禁止再写死 provider 名、
|
||||
* 分辨率档位和帧率列表——否则用户能选出模型根本不支持的组合,
|
||||
* 生成结果要么被后端悄悄降档,要么直接 400。
|
||||
*
|
||||
* React 侧的写法:注册表放在 zustand 里(页面靠 useRegistry() 订阅加载状态),
|
||||
* 下面这些派生函数一律在渲染期同步读快照,保持「纯函数」调用形态,
|
||||
* 视图里因此不需要 useEffect 去算分辨率档位。
|
||||
*/
|
||||
import { reactive } from 'vue'
|
||||
import * as api from './api'
|
||||
import { store } from './store'
|
||||
import { create } from 'zustand'
|
||||
import * as api from '../api/client'
|
||||
import { systemMeta } from './system'
|
||||
|
||||
export type ModelRow = {
|
||||
id: number
|
||||
|
|
@ -35,26 +39,45 @@ export type ModelRow = {
|
|||
config?: Record<string, any>
|
||||
}
|
||||
|
||||
export const registry = reactive<{ rows: ModelRow[]; defaults: Record<string, string>; loaded: boolean; busy: boolean; error: string }>({
|
||||
rows: [], defaults: {}, loaded: false, busy: false, error: ''
|
||||
})
|
||||
export type ModelRegistry = {
|
||||
rows: ModelRow[]
|
||||
defaults: Record<string, string>
|
||||
loaded: boolean
|
||||
busy: boolean
|
||||
error: string
|
||||
set: (patch: Partial<ModelRegistry>) => void
|
||||
}
|
||||
|
||||
export const useModelsStore = create<ModelRegistry>((set) => ({
|
||||
rows: [], defaults: {}, loaded: false, busy: false, error: '',
|
||||
set: (patch) => set(patch)
|
||||
}))
|
||||
|
||||
/** 渲染期订阅注册表(rows 变化时表单档位才会重算) */
|
||||
export const useRegistry = <T,>(pick: (s: ModelRegistry) => T): T => useModelsStore(pick)
|
||||
|
||||
/** 派生函数的统一取数入口:同步读快照,不产生订阅 */
|
||||
const S = () => useModelsStore.getState()
|
||||
|
||||
/** 拉取注册表(默认缓存;页面刷新按钮可传 force) */
|
||||
export async function loadModels(force = false): Promise<ModelRow[]> {
|
||||
if (registry.loaded && !force) return registry.rows
|
||||
registry.busy = true
|
||||
const set = useModelsStore.getState().set
|
||||
if (S().loaded && !force) return S().rows
|
||||
set({ busy: true })
|
||||
try {
|
||||
const data = await api.get('/api/providers')
|
||||
registry.rows = (data?.providers || []) as ModelRow[]
|
||||
registry.defaults = data?.defaults || {}
|
||||
registry.loaded = true
|
||||
registry.error = ''
|
||||
set({
|
||||
rows: (data?.providers || []) as ModelRow[],
|
||||
defaults: data?.defaults || {},
|
||||
loaded: true,
|
||||
error: ''
|
||||
})
|
||||
} catch (exc: any) {
|
||||
registry.error = exc?.message || String(exc)
|
||||
set({ error: exc?.message || String(exc) })
|
||||
} finally {
|
||||
registry.busy = false
|
||||
set({ busy: false })
|
||||
}
|
||||
return registry.rows
|
||||
return S().rows
|
||||
}
|
||||
|
||||
export const isMock = (row?: ModelRow | null) =>
|
||||
|
|
@ -75,7 +98,7 @@ export function parseRef(ref?: string | null): [string, string] {
|
|||
* - includeMock=true 时把 mock 演练通道排在最后,并保留标签提示
|
||||
*/
|
||||
export function modelsOf(mediaType: string, includeMock = true): ModelRow[] {
|
||||
const rows = registry.rows.filter((r) => r.media_type === mediaType && r.enabled)
|
||||
const rows = S().rows.filter((r) => r.media_type === mediaType && r.enabled)
|
||||
const real = rows.filter((r) => !isMock(r))
|
||||
const mocks = rows.filter(isMock)
|
||||
return includeMock ? [...real, ...mocks] : real
|
||||
|
|
@ -87,8 +110,8 @@ export function modelsOf(mediaType: string, includeMock = true): ModelRow[] {
|
|||
*/
|
||||
export function defaultFor(mediaType: string, includeMock = true): ModelRow | null {
|
||||
const rows = modelsOf(mediaType, includeMock)
|
||||
const dp = registry.defaults[`${mediaType}_provider`] || ''
|
||||
const dm = registry.defaults[`${mediaType}_model`] || ''
|
||||
const dp = S().defaults[`${mediaType}_provider`] || ''
|
||||
const dm = S().defaults[`${mediaType}_model`] || ''
|
||||
return (dp && rows.find((r) => r.provider === dp && r.model === dm))
|
||||
|| rows.find((r) => r.is_default && r.available)
|
||||
|| rows.find((r) => r.available)
|
||||
|
|
@ -99,12 +122,12 @@ export function defaultFor(mediaType: string, includeMock = true): ModelRow | nu
|
|||
export function findByRef(ref?: string | null): ModelRow | null {
|
||||
const [p, m] = parseRef(ref)
|
||||
if (!p) return null
|
||||
return registry.rows.find((r) => r.provider === p && r.model === m) || null
|
||||
return S().rows.find((r) => r.provider === p && r.model === m) || null
|
||||
}
|
||||
|
||||
export function findByPair(provider?: string | null, model?: string | null): ModelRow | null {
|
||||
if (!provider) return null
|
||||
if (model) return registry.rows.find((r) => r.provider === provider && r.model === model) || null
|
||||
if (model) return S().rows.find((r) => r.provider === provider && r.model === model) || null
|
||||
return modelsOf('video').find((r) => r.provider === provider) || null
|
||||
}
|
||||
|
||||
|
|
@ -167,7 +190,7 @@ export const capsOfRef = (ref?: string | null) => capsOf(...parseRef(ref))
|
|||
* 用户以为选 1080p 会多花一倍卡时,就不选了;以为是原生 1080p,又会嫌画质不够。
|
||||
*/
|
||||
export function resolutionChoices(provider?: string | null, model?: string | null): { value: string; label: string; canvas: number[]; upscaled?: boolean }[] {
|
||||
const all = (store.meta?.options?.resolution || []) as any[]
|
||||
const all = (systemMeta()?.options?.resolution || []) as any[]
|
||||
const caps = capsOf(provider, model)
|
||||
const native = caps.resolutions
|
||||
const upscaledOnly = caps.upscaleTo.filter((v) => !native.includes(v))
|
||||
|
|
@ -209,7 +232,7 @@ export function imageTiers(provider?: string | null, model?: string | null): { v
|
|||
/** 画幅下拉:注册表声明优先,未声明时退回 /api/meta 的通用画幅 */
|
||||
export function imageAspectChoices(provider?: string | null, model?: string | null): { value: string; label: string }[] {
|
||||
const allowed = capsOf(provider, model).aspectRatios
|
||||
const all = (store.meta?.options?.aspect_ratio || []) as any[]
|
||||
const all = (systemMeta()?.options?.aspect_ratio || []) as any[]
|
||||
if (allowed.length) {
|
||||
const picked = all.filter((o) => allowed.includes(o.value))
|
||||
return (picked.length ? picked : allowed).map((o) => (typeof o === 'string' ? { value: o, label: o } : o))
|
||||
|
|
@ -240,7 +263,7 @@ export function capabilityHint(provider?: string | null, model?: string | null,
|
|||
const warn: string[] = []
|
||||
// 「跟随平台默认」= 没有显式 provider,后端会回落到注册表默认模型,不是错误;
|
||||
// 注册表还没拉到时同样不能报错,否则每个表单打开都会闪一条红色误报。
|
||||
if (!provider || !registry.loaded) return []
|
||||
if (!provider || !S().loaded) return []
|
||||
if (!caps.known) return ['注册表里还没有这个模型,保存后派发会失败,请先在模型中心注册。']
|
||||
if (caps.mock) return ['当前选的是 mock 演练通道,只产出占位视频,不能用于正式出片。']
|
||||
const deliverable = [...caps.resolutions, ...caps.upscaleTo]
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
/**
|
||||
* 全局操作提示(替代旧 project.ts 里的 pctx.notice)。
|
||||
*
|
||||
* 以前 notify() 写在项目共享状态上,只有项目详情页顶部那条横幅会显示它:
|
||||
* 资产库、模型中心里点「已存为 v3」之类的提示因此悄无声息。
|
||||
* 现在提到全局,挂在 App 外壳上的 <NoticeToast/> 负责渲染,任何模块都能调 notify()。
|
||||
*/
|
||||
import { create } from 'zustand'
|
||||
|
||||
export type NoticeTone = 'ok' | 'bad'
|
||||
export type NoticeItem = { id: number; text: string; tone: NoticeTone }
|
||||
|
||||
type NoticeState = {
|
||||
items: NoticeItem[]
|
||||
push: (text: string, tone?: NoticeTone, ttl?: number) => void
|
||||
dismiss: (id: number) => void
|
||||
}
|
||||
|
||||
let seq = 0
|
||||
|
||||
const useNoticeStore = create<NoticeState>((set) => ({
|
||||
items: [],
|
||||
push: (text, tone = 'ok', ttl = 6000) => {
|
||||
if (!text) return
|
||||
const id = ++seq
|
||||
set((s) => ({ items: [...s.items.slice(-3), { id, text, tone }] }))
|
||||
window.setTimeout(() => set((s) => ({ items: s.items.filter((n) => n.id !== id) })), ttl)
|
||||
},
|
||||
dismiss: (id) => set((s) => ({ items: s.items.filter((n) => n.id !== id) }))
|
||||
}))
|
||||
|
||||
/** 成功提示(沿用旧签名:绝大多数调用点只有一个字符串参数) */
|
||||
export function notify(message: string) {
|
||||
useNoticeStore.getState().push(message)
|
||||
}
|
||||
|
||||
/** 失败/警告提示 */
|
||||
export function notifyBad(message: string) {
|
||||
useNoticeStore.getState().push(message, 'bad')
|
||||
}
|
||||
|
||||
export { useNoticeStore }
|
||||
|
|
@ -2,28 +2,56 @@
|
|||
* 全局唯一的多媒体预览器状态。
|
||||
*
|
||||
* 用法:
|
||||
* import { openPreview } from '../preview'
|
||||
* import { openPreview, openMedia } from '../stores/preview'
|
||||
* openPreview(queue, index) // 支持 ←/→ 在该队列内翻页
|
||||
* openMedia(asset) // 单个素材,自动包成 1 项队列
|
||||
*
|
||||
* MediaLightbox.vue 在 App.vue 里挂载一次,键盘(Esc / ← / → / Space)由它接管,
|
||||
* 这样每个页面都不再需要自己的 lightbox 与 esc 监听。
|
||||
* <MediaLightbox/> 在 App 外壳里挂载一次,键盘(Esc / ← / → / Space)由它接管,
|
||||
* 这样每个页面都不再需要自己的灯箱与 esc 监听。
|
||||
*
|
||||
* 派生值(shown / peers / currentUrl / currentMeta)在这里写成「接收 state 的纯函数」:
|
||||
* 灯箱订阅整个 state 后在渲染期直接调用,既不用 useMemo 也不会踩到
|
||||
* useSyncExternalStore「快照必须稳定引用」的坑。
|
||||
*/
|
||||
import { computed, ref } from 'vue'
|
||||
import { envelope, post, unwrap } from './api'
|
||||
import { dedupe, fromAsset, normalize, type MediaItem, type MediaVersion } from './media'
|
||||
import { fmtBytes } from './format'
|
||||
import { create } from 'zustand'
|
||||
import { envelope, post, unwrap } from '../api/client'
|
||||
import { dedupe, fromAsset, normalize, type MediaItem, type MediaVersion, type MetaField } from '../lib/media'
|
||||
import { fmtBytes } from '../lib/format'
|
||||
|
||||
export const items = ref<MediaItem[]>([])
|
||||
export const index = ref(0)
|
||||
export const isOpen = ref(false)
|
||||
export const collapsed = ref(false)
|
||||
/** 每个素材当前查看的版本号(默认取 item.version) */
|
||||
export const versionChoice = ref<Record<string, number>>({})
|
||||
export type PreviewState = {
|
||||
items: MediaItem[]
|
||||
index: number
|
||||
isOpen: boolean
|
||||
collapsed: boolean
|
||||
/** 每个素材当前查看的版本号(默认取 item.version) */
|
||||
versionChoice: Record<string, number>
|
||||
/** 同一镜头内选了哪个产物(关键帧 / 审片预览 / 生成视频 / 配音),按 `group` 记住 */
|
||||
peerChoice: Record<string, number>
|
||||
/** 预览器右侧「版本管理」抽屉的开关:列表页的角标可以直接把它打开 */
|
||||
versionPanelOpen: boolean
|
||||
versionBusy: boolean
|
||||
versionFeedback: { text: string; tone: 'ok' | 'bad' } | null
|
||||
set: (patch: Partial<PreviewState>) => void
|
||||
}
|
||||
|
||||
export const current = computed<MediaItem | null>(() => items.value[index.value] || null)
|
||||
/** 同一镜头内选了哪个产物(关键帧 / 审片预览 / 生成视频 / 配音),按 `group` 记住 */
|
||||
export const peerChoice = ref<Record<string, number>>({})
|
||||
export const usePreviewStore = create<PreviewState>((set) => ({
|
||||
items: [],
|
||||
index: 0,
|
||||
isOpen: false,
|
||||
collapsed: false,
|
||||
versionChoice: {},
|
||||
peerChoice: {},
|
||||
versionPanelOpen: false,
|
||||
versionBusy: false,
|
||||
versionFeedback: null,
|
||||
set: (patch) => set(patch)
|
||||
}))
|
||||
|
||||
const S = () => usePreviewStore.getState()
|
||||
|
||||
/* ── 派生值 ─────────────────────────────────────────────────────────────── */
|
||||
|
||||
export const selectCurrent = (s: PreviewState): MediaItem | null => s.items[s.index] || null
|
||||
|
||||
/**
|
||||
* 真正展示在屏幕上的那一条。
|
||||
|
|
@ -31,48 +59,45 @@ export const peerChoice = ref<Record<string, number>>({})
|
|||
* 队列里一镜只占一格(见 `media.fromShotGroup`),所以 ←/→ 是**换镜头**;
|
||||
* 想看同一镜的别的产物用顶部分段控件,选完记住,来回翻不会跳回默认。
|
||||
*/
|
||||
export const shown = computed<MediaItem | null>(() => {
|
||||
const item = current.value
|
||||
export function selectShown(s: PreviewState): MediaItem | null {
|
||||
const item = selectCurrent(s)
|
||||
if (!item) return null
|
||||
const list = item.peers || []
|
||||
if (list.length < 2) return item
|
||||
const at = peerChoice.value[item.group] ?? item.peer ?? 0
|
||||
const at = s.peerChoice[item.group] ?? item.peer ?? 0
|
||||
return list[at] || item
|
||||
})
|
||||
}
|
||||
|
||||
/** 当前镜头有哪些产物可切;少于 2 个就不给切换控件 */
|
||||
export const peers = computed<MediaItem[]>(() => {
|
||||
const list = current.value?.peers || []
|
||||
export const selectPeers = (s: PreviewState): MediaItem[] => {
|
||||
const list = selectCurrent(s)?.peers || []
|
||||
return list.length > 1 ? list : []
|
||||
})
|
||||
export const peerIndex = computed(() => {
|
||||
const item = current.value
|
||||
if (!item || !peers.value.length) return 0
|
||||
const at = peerChoice.value[item.group] ?? item.peer ?? 0
|
||||
return Math.min(Math.max(0, at), peers.value.length - 1)
|
||||
})
|
||||
export function choosePeer(at: number) {
|
||||
const item = current.value
|
||||
if (!item) return
|
||||
peerChoice.value = { ...peerChoice.value, [item.group]: at }
|
||||
}
|
||||
|
||||
export function selectPeerIndex(s: PreviewState): number {
|
||||
const item = selectCurrent(s)
|
||||
const peers = selectPeers(s)
|
||||
if (!item || !peers.length) return 0
|
||||
const at = s.peerChoice[item.group] ?? item.peer ?? 0
|
||||
return Math.min(Math.max(0, at), peers.length - 1)
|
||||
}
|
||||
|
||||
/** 当前实际展示的地址:选中了历史版本就用历史版本的 url */
|
||||
export const currentUrl = computed(() => {
|
||||
const item = shown.value
|
||||
export function selectCurrentUrl(s: PreviewState): string {
|
||||
const item = selectShown(s)
|
||||
if (!item) return ''
|
||||
const chosen = versionChoice.value[item.key]
|
||||
const chosen = s.versionChoice[item.key]
|
||||
if (chosen) {
|
||||
const hit = item.versions.find((v) => v.version_no === chosen)
|
||||
if (hit) return hit.url
|
||||
}
|
||||
return item.url
|
||||
})
|
||||
}
|
||||
|
||||
export const currentMeta = computed(() => {
|
||||
const item = shown.value
|
||||
export function selectCurrentMeta(s: PreviewState): MetaField[] {
|
||||
const item = selectShown(s)
|
||||
if (!item) return []
|
||||
const chosen = versionChoice.value[item.key]
|
||||
const chosen = s.versionChoice[item.key]
|
||||
if (!chosen) return item.meta
|
||||
const hit = item.versions.find((v) => v.version_no === chosen)
|
||||
if (!hit) return item.meta
|
||||
|
|
@ -86,20 +111,26 @@ export const currentMeta = computed(() => {
|
|||
...(hit.note ? [{ label: '备注', value: hit.note }] : []),
|
||||
{ label: '存储路径', value: hit.path || hit.url },
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
export const count = computed(() => items.value.length)
|
||||
export const position = computed(() => index.value + 1)
|
||||
export const hasPrev = computed(() => items.value.length > 1)
|
||||
export const hasNext = computed(() => items.value.length > 1)
|
||||
export const selectChosenVersion = (s: PreviewState): number => {
|
||||
const item = selectShown(s)
|
||||
return item ? s.versionChoice[item.key] || item.version : 1
|
||||
}
|
||||
|
||||
export const usePreviewOpen = () => usePreviewStore((s) => s.isOpen)
|
||||
|
||||
/* ── 队列操作 ───────────────────────────────────────────────────────────── */
|
||||
|
||||
function openQueue(list: MediaItem[], start = 0) {
|
||||
const queue = dedupe(list.filter(Boolean))
|
||||
if (!queue.length) return
|
||||
items.value = queue
|
||||
index.value = Math.min(Math.max(0, start), queue.length - 1)
|
||||
isOpen.value = true
|
||||
collapsed.value = false
|
||||
S().set({
|
||||
items: queue,
|
||||
index: Math.min(Math.max(0, start), queue.length - 1),
|
||||
isOpen: true,
|
||||
collapsed: false
|
||||
})
|
||||
}
|
||||
|
||||
/** 打开一组媒体,从第 index 项开始 */
|
||||
|
|
@ -138,59 +169,55 @@ export function openTogether(list: any[], target: any, mapper?: (s: any) => Medi
|
|||
openQueue(queue, at < 0 ? 0 : at)
|
||||
}
|
||||
|
||||
export function close() {
|
||||
isOpen.value = false
|
||||
versionChoice.value = {}
|
||||
peerChoice.value = {}
|
||||
versionPanelOpen.value = false
|
||||
export function closePreview() {
|
||||
S().set({ isOpen: false, versionChoice: {}, peerChoice: {}, versionPanelOpen: false })
|
||||
}
|
||||
|
||||
export function step(delta: number) {
|
||||
if (!items.value.length) return
|
||||
index.value = (index.value + delta + items.value.length) % items.value.length
|
||||
versionPanelOpen.value = false
|
||||
const s = S()
|
||||
if (!s.items.length) return
|
||||
s.set({ index: (s.index + delta + s.items.length) % s.items.length, versionPanelOpen: false })
|
||||
}
|
||||
|
||||
export function goTo(i: number) {
|
||||
if (i >= 0 && i < items.value.length) index.value = i
|
||||
const s = S()
|
||||
if (i >= 0 && i < s.items.length) s.set({ index: i })
|
||||
}
|
||||
|
||||
export function chooseVersion(no: number) {
|
||||
const item = current.value
|
||||
const s = S()
|
||||
const item = selectCurrent(s)
|
||||
if (!item) return
|
||||
versionChoice.value = { ...versionChoice.value, [item.key]: no }
|
||||
s.set({ versionChoice: { ...s.versionChoice, [item.key]: no } })
|
||||
}
|
||||
|
||||
export function resetVersion() {
|
||||
const item = current.value
|
||||
const s = S()
|
||||
const item = selectCurrent(s)
|
||||
if (!item) return
|
||||
const next = { ...versionChoice.value }
|
||||
const next = { ...s.versionChoice }
|
||||
delete next[item.key]
|
||||
versionChoice.value = next
|
||||
s.set({ versionChoice: next })
|
||||
}
|
||||
|
||||
export const chosenVersion = computed(() => {
|
||||
const item = shown.value
|
||||
return item ? versionChoice.value[item.key] || item.version : 1
|
||||
})
|
||||
export function choosePeer(at: number) {
|
||||
const s = S()
|
||||
const item = selectCurrent(s)
|
||||
if (!item) return
|
||||
s.set({ peerChoice: { ...s.peerChoice, [item.group]: at } })
|
||||
}
|
||||
|
||||
export function toggleInfo() {
|
||||
collapsed.value = !collapsed.value
|
||||
S().set({ collapsed: !S().collapsed })
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 版本管理
|
||||
// 「设为当前版本 / 删除某个版本」是素材级操作,但入口在全局预览器里
|
||||
// (只有那里有完整的版本下拉),所以状态与请求都放在这个共享模块,
|
||||
// 平台资产库与项目素材库用的是同一套逻辑,只是打的接口不同。
|
||||
/** 预览器右侧「版本管理」抽屉的开关:列表页的角标可以直接把它打开 */
|
||||
export const versionPanelOpen = ref(false)
|
||||
|
||||
export function toggleVersionPanel(force?: boolean) {
|
||||
versionPanelOpen.value = force === undefined ? !versionPanelOpen.value : force
|
||||
S().set({ versionPanelOpen: force === undefined ? !S().versionPanelOpen : force })
|
||||
}
|
||||
|
||||
export const versionBusy = ref(false)
|
||||
export const versionFeedback = ref<{ text: string; tone: 'ok' | 'bad' } | null>(null)
|
||||
/* ── 版本管理:与页面无关,所以下游两个素材库共用一套逻辑,只是打的接口不同 ── */
|
||||
|
||||
export const versionBusy = () => S().versionBusy
|
||||
|
||||
const ENDPOINTS: Record<string, (id: number | string, no: number) => string> = {
|
||||
platform: (id, no) => `/api/platform/media/${id}/versions/${no}`,
|
||||
|
|
@ -206,14 +233,14 @@ export function canManageVersions(item: MediaItem | null): boolean {
|
|||
/** 正在预览的那一版(没手动选就是当前默认版) */
|
||||
export function viewedVersion(item: MediaItem | null): MediaVersion | null {
|
||||
if (!item) return null
|
||||
const chosen = versionChoice.value[item.key]
|
||||
const chosen = S().versionChoice[item.key]
|
||||
return item.versions.find((v) => v.version_no === (chosen || item.version)) || null
|
||||
}
|
||||
|
||||
function notify(text: string, tone: 'ok' | 'bad') {
|
||||
versionFeedback.value = { text, tone }
|
||||
function feedback(text: string, tone: 'ok' | 'bad') {
|
||||
S().set({ versionFeedback: { text, tone } })
|
||||
window.setTimeout(() => {
|
||||
if (versionFeedback.value?.text === text) versionFeedback.value = null
|
||||
if (S().versionFeedback?.text === text) S().set({ versionFeedback: null })
|
||||
}, 4200)
|
||||
}
|
||||
|
||||
|
|
@ -221,12 +248,14 @@ function notify(text: string, tone: 'ok' | 'bad') {
|
|||
function applyMedia(media: any) {
|
||||
const rebuilt = fromAsset(media)
|
||||
if (!rebuilt) return
|
||||
const at = items.value.findIndex((i) => i.key === rebuilt.key)
|
||||
const s = S()
|
||||
const at = s.items.findIndex((i) => i.key === rebuilt.key)
|
||||
if (at < 0) return
|
||||
items.value.splice(at, 1, rebuilt)
|
||||
const chosen = { ...versionChoice.value }
|
||||
delete chosen[rebuilt.key] // 版本变了,回到新的当前默认版
|
||||
versionChoice.value = chosen
|
||||
const items = [...s.items]
|
||||
items.splice(at, 1, rebuilt)
|
||||
const versionChoice = { ...s.versionChoice }
|
||||
delete versionChoice[rebuilt.key] // 版本变了,回到新的当前默认版
|
||||
s.set({ items, versionChoice })
|
||||
}
|
||||
|
||||
function announce(item: MediaItem, action: string, detail: any) {
|
||||
|
|
@ -243,58 +272,54 @@ function voiceTail(result: any): string {
|
|||
|
||||
/** 把某一版设为当前版本(下游取图、引入项目都会跟着切) */
|
||||
export async function setCurrentVersion(versionNo?: number): Promise<boolean> {
|
||||
const item = current.value
|
||||
const s = S()
|
||||
const item = selectCurrent(s)
|
||||
const build = ENDPOINTS[String(item?.scope || '')]
|
||||
if (!item || !build) {
|
||||
notify('该素材不支持版本管理', 'bad')
|
||||
feedback('该素材不支持版本管理', 'bad')
|
||||
return false
|
||||
}
|
||||
const no = Number(versionNo ?? chosenVersion.value) || 0
|
||||
versionBusy.value = true
|
||||
const no = Number(versionNo ?? selectChosenVersion(s)) || 0
|
||||
s.set({ versionBusy: true })
|
||||
try {
|
||||
const result: any = await post(`${build(item.id, no)}/current`, { actor: 'web' })
|
||||
applyMedia(result?.media)
|
||||
notify(result?.changed === false
|
||||
feedback(result?.changed === false
|
||||
? `v${no} 已经是当前版本`
|
||||
: `已将 v${result?.current_version ?? no} 设为当前版本${voiceTail(result)}`, 'ok')
|
||||
announce(item, 'current', { version: result?.current_version, previous: result?.previous_version })
|
||||
return true
|
||||
} catch (exc: any) {
|
||||
notify(`设为当前版本失败:${exc?.message || exc}`, 'bad')
|
||||
feedback(`设为当前版本失败:${exc?.message || exc}`, 'bad')
|
||||
return false
|
||||
} finally {
|
||||
versionBusy.value = false
|
||||
S().set({ versionBusy: false })
|
||||
}
|
||||
}
|
||||
|
||||
/** 删除某一版:记录 + 文件一起清,删的正是当前版本时后端自动回落 */
|
||||
export async function deleteVersion(versionNo?: number): Promise<boolean> {
|
||||
const item = current.value
|
||||
const s = S()
|
||||
const item = selectCurrent(s)
|
||||
const build = ENDPOINTS[String(item?.scope || '')]
|
||||
if (!item || !build) {
|
||||
notify('该素材不支持版本管理', 'bad')
|
||||
feedback('该素材不支持版本管理', 'bad')
|
||||
return false
|
||||
}
|
||||
const no = Number(versionNo ?? chosenVersion.value) || 0
|
||||
versionBusy.value = true
|
||||
const no = Number(versionNo ?? selectChosenVersion(s)) || 0
|
||||
s.set({ versionBusy: true })
|
||||
try {
|
||||
// 走 envelope 而不是 api.del:删除要带 JSON 请求体记录操作者,del() 只能拼 query
|
||||
const result: any = unwrap(await envelope('DELETE', build(item.id, no), { actor: 'web' }))
|
||||
applyMedia(result?.media)
|
||||
const tail = result?.file_removed ? '文件已清理' : (result?.file_kept_reason || '文件已保留')
|
||||
notify(`已删除 v${no}${result?.was_current ? `,当前版本回落到 v${result?.current_version}` : ''}(${tail})${voiceTail(result)}`, 'ok')
|
||||
feedback(`已删除 v${no}${result?.was_current ? `,当前版本回落到 v${result?.current_version}` : ''}(${tail})${voiceTail(result)}`, 'ok')
|
||||
announce(item, 'deleted', { version: no, current: result?.current_version })
|
||||
return true
|
||||
} catch (exc: any) {
|
||||
notify(`删除版本失败:${exc?.message || exc}`, 'bad')
|
||||
feedback(`删除版本失败:${exc?.message || exc}`, 'bad')
|
||||
return false
|
||||
} finally {
|
||||
versionBusy.value = false
|
||||
S().set({ versionBusy: false })
|
||||
}
|
||||
}
|
||||
|
||||
export const previewState = {
|
||||
items, index, isOpen, collapsed, current, currentUrl, currentMeta,
|
||||
count, position, hasPrev, hasNext, chosenVersion,
|
||||
versionBusy, versionFeedback, versionPanelOpen
|
||||
}
|
||||
|
|
@ -0,0 +1,100 @@
|
|||
/**
|
||||
* 项目详情共享状态(父组件加载,各页签复用 / 触发刷新)。
|
||||
*
|
||||
* 12 节点进度、指标卡、轮询都只在这里有一份:页签点完「派发」之后调 refresh(),
|
||||
* 顶栏流程控制台和概览页同时更新,不需要互相通报。
|
||||
*/
|
||||
import { create } from 'zustand'
|
||||
import * as api from '../api/client'
|
||||
import { isRecordingBusy } from './recording'
|
||||
|
||||
export type ProjectState = {
|
||||
id: number | null
|
||||
project: any
|
||||
workflow: any[]
|
||||
stats: any
|
||||
loading: boolean
|
||||
error: string
|
||||
polling: boolean
|
||||
lastLoad: number
|
||||
/** 侧栏 / 顶栏要显示「当前项目」,父组件加载成功后写这里 */
|
||||
activeProject: any
|
||||
set: (patch: Partial<ProjectState>) => void
|
||||
}
|
||||
|
||||
export const useProjectStore = create<ProjectState>((set) => ({
|
||||
id: null,
|
||||
project: null,
|
||||
workflow: [],
|
||||
stats: null,
|
||||
loading: true,
|
||||
error: '',
|
||||
polling: true,
|
||||
lastLoad: 0,
|
||||
activeProject: null,
|
||||
set: (patch) => set(patch)
|
||||
}))
|
||||
|
||||
export const projectState = () => useProjectStore.getState()
|
||||
|
||||
export async function loadProject(id: number, silent = true) {
|
||||
const set = useProjectStore.getState().set
|
||||
set({ id })
|
||||
if (!silent) set({ loading: true })
|
||||
try {
|
||||
const data = await api.get(`/api/projects/${id}`)
|
||||
set({
|
||||
project: data,
|
||||
workflow: data.workflow || [],
|
||||
stats: data.stats || null,
|
||||
error: '',
|
||||
lastLoad: Date.now(),
|
||||
activeProject: data
|
||||
})
|
||||
} catch (exc: any) {
|
||||
set({ error: exc?.message || String(exc) })
|
||||
} finally {
|
||||
set({ loading: false })
|
||||
}
|
||||
}
|
||||
|
||||
let timer: number | undefined
|
||||
|
||||
export function startPolling(id: number, intervalMs = 6000) {
|
||||
stopPolling()
|
||||
timer = window.setInterval(() => {
|
||||
const s = useProjectStore.getState()
|
||||
// 正有人在录音就跳过这一轮:刷新会重建资产卡片,卡片里的录音面板跟着卸载,
|
||||
// 麦克风和刚录的波形一起没(录完关闭面板后下一轮自然恢复)
|
||||
if (s.polling && !isRecordingBusy() && s.id === id) void loadProject(id)
|
||||
}, intervalMs)
|
||||
}
|
||||
|
||||
export function stopPolling() {
|
||||
if (timer) { window.clearInterval(timer); timer = undefined }
|
||||
}
|
||||
|
||||
/** 变更类操作后统一刷新项目状态 */
|
||||
export const refresh = () => {
|
||||
const id = useProjectStore.getState().id
|
||||
return id ? loadProject(id) : Promise.resolve()
|
||||
}
|
||||
|
||||
/* ── 项目概况(4 张指标卡 + 12 节点流程条)的折叠状态 ──────────────────────
|
||||
放在共享层而不是 ProjectDetail 私有:「分镜与脚本」正文最重(看板 + 编辑抽屉),
|
||||
工作台自己也得有办法让上面那两屏立刻让位。偏好记 localStorage,跨页签保持。 */
|
||||
const BRIEF_KEY = 'nex.project.brief.open'
|
||||
|
||||
function initialBrief(): boolean {
|
||||
let saved: string | null = null
|
||||
try { saved = localStorage.getItem(BRIEF_KEY) } catch { return true }
|
||||
return saved === null ? true : saved === '1'
|
||||
}
|
||||
|
||||
export const useBriefStore = create<{ open: boolean; set: (open: boolean) => void }>((set) => ({
|
||||
open: initialBrief(),
|
||||
set: (open) => {
|
||||
set({ open })
|
||||
try { localStorage.setItem(BRIEF_KEY, open ? '1' : '0') } catch { /* 隐私模式:当场生效即可 */ }
|
||||
}
|
||||
}))
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
/**
|
||||
* 「有人在录音」的全局计数。
|
||||
*
|
||||
* 录音面板(RecordAudio)是挂在素材卡片里的小组件,麦克风流、已录波形、试听 URL
|
||||
* 全是它的局部状态。卡片一旦在轮询刷新中被换掉,组件卸载,清理逻辑会把麦克风
|
||||
* 还给系统、这段录音当场蒸发 —— 用户举着麦克风说了半分钟,回来发现面板没了。
|
||||
* 所以轮询必须知道「现在正有人在录」,把这一轮让过去。
|
||||
*
|
||||
* 放全局而不是组件级:面板可以同时开着好几个(平台声线卡 + 生成抽屉各一个),
|
||||
* 任何一个开着都得让轮询停下来。
|
||||
*/
|
||||
import { create } from 'zustand'
|
||||
|
||||
const useRecordingStore = create<{ open: number; step: (delta: number) => void }>((set) => ({
|
||||
open: 0,
|
||||
step: (delta) => set((s) => ({ open: Math.max(0, s.open + delta) }))
|
||||
}))
|
||||
|
||||
/** 页面用它把自动刷新暂停掉:`<AutoRefresh paused={modalOpen || recordingBusy} />` */
|
||||
export const useRecordingBusy = () => useRecordingStore((s) => s.open > 0)
|
||||
|
||||
/** 同步读取(轮询回调里没有 Hook 环境) */
|
||||
export const isRecordingBusy = () => useRecordingStore.getState().open > 0
|
||||
|
||||
/** 面板打开时登记,返回释放函数(关闭 / 卸载时必须调用,否则轮询永远醒不过来) */
|
||||
export function beginRecordingSheet(): () => void {
|
||||
useRecordingStore.getState().step(1)
|
||||
let released = false
|
||||
return () => {
|
||||
if (released) return
|
||||
released = true
|
||||
useRecordingStore.getState().step(-1)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,18 +1,38 @@
|
|||
import { reactive } from 'vue'
|
||||
import * as api from './api'
|
||||
/**
|
||||
* 全局系统信息(/api/meta + /health)与常用枚举。
|
||||
*
|
||||
* meta 是「后端到底支持什么」的唯一来源(画幅、分辨率、素材类型、节点动作…),
|
||||
* 表单枚举一律走 options(),不要在页面里抄一份中文标签。
|
||||
*/
|
||||
import { create } from 'zustand'
|
||||
import * as api from '../api/client'
|
||||
|
||||
/** 全局系统信息(/api/meta + /health)与常用枚举 */
|
||||
export const store = reactive<{ meta: any; health: any; loaded: boolean; error: string; busy: boolean }>({
|
||||
type SystemState = {
|
||||
meta: any
|
||||
health: any
|
||||
loaded: boolean
|
||||
error: string
|
||||
busy: boolean
|
||||
/** 后端连不上时顶栏显示「离线」而不是红色故障 */
|
||||
set: (patch: Partial<SystemState>) => void
|
||||
}
|
||||
|
||||
export const useSystemStore = create<SystemState>((set) => ({
|
||||
meta: null,
|
||||
health: null,
|
||||
loaded: false,
|
||||
error: '',
|
||||
busy: false
|
||||
})
|
||||
busy: false,
|
||||
set: (patch) => set(patch)
|
||||
}))
|
||||
|
||||
/** 非组件环境(lib/format.ts、lib/models.ts)取 meta 的唯一入口 */
|
||||
export const systemMeta = (): any => useSystemStore.getState().meta
|
||||
|
||||
export async function loadSystem(force = false) {
|
||||
const store = useSystemStore.getState()
|
||||
if (store.loaded && !force) return store.meta
|
||||
store.busy = true
|
||||
store.set({ busy: true })
|
||||
try {
|
||||
const [meta, health] = await Promise.all([api.get('/api/meta'), api.get('/health')])
|
||||
// /health 必须返回 JSON 对象。若开发服务器没把它代理到后端,
|
||||
|
|
@ -21,20 +41,17 @@ export async function loadSystem(force = false) {
|
|||
if (!health || typeof health !== 'object' || typeof health.status !== 'string') {
|
||||
throw new Error('健康检查返回格式异常:/health 未指向后端(请检查 vite.config.ts 代理)')
|
||||
}
|
||||
store.meta = meta
|
||||
store.health = health
|
||||
store.loaded = true
|
||||
store.error = ''
|
||||
useSystemStore.getState().set({ meta, health, loaded: true, error: '' })
|
||||
} catch (exc: any) {
|
||||
store.error = exc?.message || String(exc)
|
||||
useSystemStore.getState().set({ error: exc?.message || String(exc) })
|
||||
} finally {
|
||||
store.busy = false
|
||||
useSystemStore.getState().set({ busy: false })
|
||||
}
|
||||
return store.meta
|
||||
return useSystemStore.getState().meta
|
||||
}
|
||||
|
||||
export function options(key: string): { value: string; label: string }[] {
|
||||
return (store.meta?.options && store.meta.options[key]) || []
|
||||
return (systemMeta()?.options && systemMeta().options[key]) || []
|
||||
}
|
||||
|
||||
export const presets: string[] = [
|
||||
|
|
@ -54,9 +71,7 @@ export const presetLabel: Record<string, string> = {
|
|||
uhd_4k: '超清 4K'
|
||||
}
|
||||
|
||||
/** 当前打开的项目(供顶栏项目 chip 与侧栏分组标题展示) */
|
||||
export const active = reactive<{ project: any }>({ project: null })
|
||||
|
||||
/** 项目详情的七个页签 = 侧栏项目分组(顺序即业务流程顺序,别按字母排) */
|
||||
export const modules: { to: (id: number | string) => string; icon: string; label: string; hint: string }[] = [
|
||||
{ to: (id) => `/projects/${id}/overview`, icon: '◎', label: '流程概览', hint: '总控台 / 全节点进度' },
|
||||
{ to: (id) => `/projects/${id}/library`, icon: '☺', label: '资产管理', hint: '人物 / 声音 / 场景' },
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
/**
|
||||
* 明暗主题:默认跟随系统,用户切换后记住选择。
|
||||
*
|
||||
* 颜色全部走 styles/tokens.css 里的 --c-* 令牌,切换只改 <html data-theme>,
|
||||
* 组件不参与;因此这里只负责「决定并落地 data-theme」。
|
||||
* 钥匙 nex-the 与 index.html 里的首帧脚本共用(值缺失 = 跟随系统)。
|
||||
*/
|
||||
import { create } from 'zustand'
|
||||
|
||||
export type ThemeMode = 'dark' | 'light'
|
||||
|
||||
const KEY = 'nex-the'
|
||||
const QUERY = '(prefers-color-scheme: light)'
|
||||
|
||||
type ThemeState = {
|
||||
mode: ThemeMode
|
||||
followSystem: boolean
|
||||
applied: ThemeMode
|
||||
set: (patch: Partial<ThemeState>) => void
|
||||
}
|
||||
|
||||
export const useThemeStore = create<ThemeState>((set) => ({
|
||||
mode: 'dark',
|
||||
followSystem: true,
|
||||
applied: 'dark',
|
||||
set: (patch) => set(patch)
|
||||
}))
|
||||
|
||||
export const useAppliedTheme = () => useThemeStore((s) => s.applied)
|
||||
|
||||
function systemMode(): ThemeMode {
|
||||
return typeof window !== 'undefined' && window.matchMedia?.(QUERY).matches ? 'light' : 'dark'
|
||||
}
|
||||
|
||||
export function applyTheme() {
|
||||
const { followSystem, mode: picked } = useThemeStore.getState()
|
||||
const mode = followSystem ? systemMode() : picked
|
||||
// DOM 不是响应式的,applied 回写进 store 才能让图标(☀ / ☾)跟着翻
|
||||
useThemeStore.getState().set({ applied: mode, mode })
|
||||
document.documentElement.dataset.theme = mode
|
||||
document.documentElement.style.colorScheme = mode
|
||||
const meta = document.querySelector('meta[name="color-scheme"]')
|
||||
if (meta) meta.setAttribute('content', mode)
|
||||
const bg = document.querySelector('meta[name="theme-color"]')
|
||||
if (bg) bg.setAttribute('content', mode === 'light' ? '#f0f4f8' : '#0d1117')
|
||||
}
|
||||
|
||||
export function setTheme(mode: ThemeMode, options: { followSystem?: boolean } = {}) {
|
||||
const followSystem = options.followSystem ?? false
|
||||
useThemeStore.getState().set({ followSystem, mode })
|
||||
try {
|
||||
if (followSystem) localStorage.removeItem(KEY)
|
||||
else localStorage.setItem(KEY, mode)
|
||||
} catch {
|
||||
/* 隐私模式下 localStorage 会抛错,主题当场生效即可 */
|
||||
}
|
||||
applyTheme()
|
||||
}
|
||||
|
||||
/** 深浅切换(顶栏那颗按钮用):从「跟随系统」切走时以当前实际生效值为准 */
|
||||
export function toggleTheme() {
|
||||
const s = useThemeStore.getState()
|
||||
setTheme(s.applied === 'light' ? 'dark' : 'light')
|
||||
}
|
||||
|
||||
export function initTheme() {
|
||||
let saved: string | null = null
|
||||
try { saved = localStorage.getItem(KEY) } catch { /* ignore */ }
|
||||
if (saved === 'dark' || saved === 'light') {
|
||||
useThemeStore.getState().set({ mode: saved, followSystem: false })
|
||||
} else {
|
||||
useThemeStore.getState().set({ mode: systemMode(), followSystem: true })
|
||||
}
|
||||
applyTheme()
|
||||
window.matchMedia?.(QUERY).addEventListener?.('change', () => {
|
||||
if (useThemeStore.getState().followSystem) applyTheme()
|
||||
})
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,64 @@
|
|||
/* ══════════════════════════════════════════════════════════════════════════
|
||||
元素级默认值(Tailwind base 层)
|
||||
-----------------------------------------------------------------------------
|
||||
这里只管「裸元素长什么样」:页面里直接写 <input> / <label> / <h2> 也能拿到
|
||||
设计系统的尺子和配色;一旦某个地方需要不一样,加工具类就能盖掉
|
||||
(utilities 层排在 base 之后,不需要再靠 !important 和特指度打架)。
|
||||
重复出现的组合(按钮、控件栏、面板、抽屉…)不要加在这里,
|
||||
去 src/components/ui 里做成组件,样式以工具类形式写在组件内部。
|
||||
══════════════════════════════════════════════════════════════════════════ */
|
||||
@layer base {
|
||||
html { -webkit-text-size-adjust: 100% }
|
||||
|
||||
body {
|
||||
@apply bg-app text-ink text-ui;
|
||||
font-family: var(--font-sans);
|
||||
}
|
||||
|
||||
/* 站内最小可读字号:<small> 的原生实现是 font-size:smaller(÷1.2),
|
||||
套在 10~11px 的容器里会掉到 8.3px,中文只剩一团墨点。
|
||||
元素选择器优先级最低,比它大的场景仍按父级 0.8 倍缩放。 */
|
||||
small { font-size: max(0.8em, 10px) }
|
||||
|
||||
h1 { @apply text-h1 font-bold; margin: 6px 0 0 }
|
||||
h2 { @apply text-h2 font-bold; margin: 5px 0 0 }
|
||||
h3 { @apply text-title font-bold; margin: 0 0 14px }
|
||||
|
||||
button, input, textarea, select { font: inherit }
|
||||
/* 按钮文案不折行:CJK 在窄列里会被切成两行行盒,撑出「野高度」(UI规范 §1.2)。
|
||||
卡片式按钮是热区不是控件,需要折行时用 whitespace-normal 显式豁免。 */
|
||||
button { cursor: pointer; white-space: nowrap }
|
||||
button:disabled { cursor: not-allowed }
|
||||
|
||||
/* 单行控件定高(--ctl-h 由所在容器决定),文字交给浏览器垂直居中 */
|
||||
input:not([type=checkbox]):not([type=radio]):not([type=file]):not([type=range]):not([type=color]),
|
||||
select,
|
||||
textarea {
|
||||
@apply w-full rounded-control border border-line-strong bg-field px-3 text-body text-ink outline-none;
|
||||
transition: border-color .14s ease;
|
||||
}
|
||||
input:not([type=checkbox]):not([type=radio]):not([type=file]):not([type=range]):not([type=color]),
|
||||
select { height: var(--ctl-h); padding-block: 0 }
|
||||
textarea { min-height: var(--ctl-h); resize: vertical; line-height: 1.65 }
|
||||
input:focus, textarea:focus, select:focus { border-color: var(--c-accent-deep) }
|
||||
input:disabled, textarea:disabled, select:disabled { @apply bg-sunken text-faint; opacity: .7 }
|
||||
select { appearance: none; -webkit-appearance: none }
|
||||
|
||||
/* 勾选类控件不参与定高,跟随系统强调色改成主色 */
|
||||
input[type=checkbox], input[type=radio] { width: auto; accent-color: var(--c-accent-fill) }
|
||||
|
||||
/* 键盘焦点必须始终可见(与鼠标 :focus 分开,点按钮不出现描边) */
|
||||
:focus-visible { outline: 2px solid var(--c-accent); outline-offset: 2px }
|
||||
|
||||
/* 数值滑杆:轨道和滑块都用令牌,两个主题都看得见 */
|
||||
input[type=range] { accent-color: var(--c-accent-fill); width: 100% }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after {
|
||||
scroll-behavior: auto !important;
|
||||
animation-duration: .01ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
transition-duration: .01ms !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
/* 样式入口:令牌 → 元素默认值。工具类由 Tailwind 在编译期按源码里的实际用量生成。 */
|
||||
@import "tailwindcss";
|
||||
@import "./tokens.css";
|
||||
@import "./base.css";
|
||||
|
||||
/* 弹层里滚动的地方(下拉面板、抽屉、日志流)用细描边滚动条,
|
||||
避免出现一条系统默认的粗白条压在深色面板上。 */
|
||||
@utility scrollbar-slim {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--c-line-strong) transparent;
|
||||
&::-webkit-scrollbar { width: 8px; height: 8px }
|
||||
&::-webkit-scrollbar-thumb { background: var(--c-line-strong); border-radius: 8px }
|
||||
&::-webkit-scrollbar-track { background: transparent }
|
||||
}
|
||||
|
||||
/* 隐藏滚动条但保留滚动(侧栏折叠轨道用)。 */
|
||||
@utility scrollbar-none {
|
||||
scrollbar-width: none;
|
||||
&::-webkit-scrollbar { display: none }
|
||||
}
|
||||
|
|
@ -0,0 +1,333 @@
|
|||
/* ══════════════════════════════════════════════════════════════════════════
|
||||
设计令牌 · 全站唯一的「颜色 / 尺子」定义处(docs/UI规范.md §0 的那三块基础设施)
|
||||
-----------------------------------------------------------------------------
|
||||
两层结构,别混:
|
||||
① `--c-*` 原始值:深色写在 :root,浅色写在 [data-theme="light"]。
|
||||
切换主题只改 <html data-theme>(src/stores/theme.ts),组件不参与。
|
||||
② `@theme` 把原始值映射成 Tailwind 命名空间(--color-* / --text-* / …),
|
||||
于是页面里写的是语义类名 bg-panel、text-muted、rounded-block,
|
||||
拿到的值是 var(--color-panel) → var(--c-bg-panel):var 在用例处解析,
|
||||
主题一翻,全部工具类跟着翻,不需要重渲染。
|
||||
新增一个视觉概念时的规矩:先在 ① 补值(两个主题都要),再在 ② 起个语义名。
|
||||
页面里出现 text-[#123456] 这种硬编码色 = 绕过了令牌体系,按返工处理。
|
||||
══════════════════════════════════════════════════════════════════════════ */
|
||||
|
||||
:root {
|
||||
--c-bg-deepest: #0b1116;
|
||||
--c-bg-app: #0d1117;
|
||||
--c-bg-input: #0e141a;
|
||||
--c-bg-sunken: #0f161d;
|
||||
--c-bg-card: #10171e;
|
||||
--c-bg-shell: #111820;
|
||||
--c-bg-panel: #141b23;
|
||||
--c-bg-raised: #18211a;
|
||||
--c-bg-hover: #1e2932;
|
||||
--c-bg-raise: #202b35;
|
||||
--c-bg-active: #243039;
|
||||
--c-bg-emphasis: #283540;
|
||||
--c-line-soft: #212c35;
|
||||
--c-line: #293640;
|
||||
--c-line-strong: #35434e;
|
||||
--c-line-bright: #4b5a64;
|
||||
--c-text: #e9edf2;
|
||||
--c-text-2: #c3ced7;
|
||||
--c-text-3: #adb9c3;
|
||||
--c-text-muted: #a1adb7;
|
||||
--c-text-faint: #96a2ad;
|
||||
--c-text-dim: #99a5b0;
|
||||
--c-on-accent: #18200f;
|
||||
--c-accent: #c5ee79;
|
||||
--c-accent-bright: #dff9a7;
|
||||
--c-accent-deep: #9acb60;
|
||||
--c-accent-fill: #c5ee79;
|
||||
--c-accent-fill-deep: #9acb60;
|
||||
--c-accent-tint: #1a2410;
|
||||
--c-accent-tint2: #263b28;
|
||||
--c-accent-line: #465840;
|
||||
--c-accent-ink: #18200f;
|
||||
--c-danger: #f0a59c;
|
||||
--c-danger-bright: #ffb9b0;
|
||||
--c-danger-tint: #482927;
|
||||
--c-danger-tint2: #3c2320;
|
||||
--c-danger-line: #6b3630;
|
||||
--c-danger-ink: #2a1210;
|
||||
--c-warn: #f0cf8e;
|
||||
--c-warn-bright: #f2d18b;
|
||||
--c-warn-fill: #f0cf8e;
|
||||
--c-warn-ink: #302108;
|
||||
--c-warn-tint: #3b3320;
|
||||
--c-warn-line: #584c2c;
|
||||
--c-info: #9bcdf1;
|
||||
--c-info-tint: #233649;
|
||||
--c-info-line: #2f4a5e;
|
||||
--c-success: #bce989;
|
||||
--c-success-tint: #22371f;
|
||||
--c-success-line: #3d5c33;
|
||||
--c-pink: #e5a4d0;
|
||||
--c-sky: #79c8ef;
|
||||
--c-pure-white: #ffffff;
|
||||
--c-pure-black: #000000;
|
||||
--c-scrim: rgba(4, 8, 11, .74);
|
||||
--c-scrim-soft: rgba(9, 13, 17, .82);
|
||||
/* 媒体预览(灯箱)用的观看背景:两种主题都压得够暗,让画面本身成为主体 */
|
||||
--c-backdrop: rgba(2, 5, 8, .82);
|
||||
--c-backdrop-shadow: rgba(0, 0, 0, .55);
|
||||
--c-backdrop-veil: rgba(9, 14, 20, .62);
|
||||
--c-tint-success: rgba(38, 63, 32, .92);
|
||||
--c-tint-info: rgba(99, 132, 255, .10);
|
||||
--c-tint-accent: rgba(197, 238, 121, .16);
|
||||
--c-hairline: rgba(111, 135, 116, .24);
|
||||
--c-shade-1: rgba(0, 0, 0, .16);
|
||||
--c-shade-2: rgba(0, 0, 0, .24);
|
||||
--c-shade-3: rgba(0, 0, 0, .42);
|
||||
}
|
||||
|
||||
[data-theme="light"] {
|
||||
--c-bg-deepest: #e7edf4;
|
||||
--c-bg-app: #f0f4f8;
|
||||
--c-bg-input: #fbfcfe;
|
||||
--c-bg-sunken: #eef2f7;
|
||||
--c-bg-card: #f6f8fb;
|
||||
--c-bg-shell: #ffffff;
|
||||
--c-bg-panel: #ffffff;
|
||||
--c-bg-raised: #eef4ea;
|
||||
--c-bg-hover: #e9eff6;
|
||||
--c-bg-raise: #e2e9f1;
|
||||
--c-bg-active: #dae3ec;
|
||||
--c-bg-emphasis: #cfd9e3;
|
||||
--c-line-soft: #e9eef4;
|
||||
--c-line: #dbe3ea;
|
||||
--c-line-strong: #c3ccd6;
|
||||
--c-line-bright: #aab5bf;
|
||||
--c-text: #111a22;
|
||||
--c-text-2: #2c3946;
|
||||
--c-text-3: #3f4c58;
|
||||
--c-text-muted: #4d5762;
|
||||
--c-text-faint: #535d68;
|
||||
--c-text-dim: #555f6a;
|
||||
--c-on-accent: #18200f;
|
||||
--c-accent: #356309;
|
||||
--c-accent-bright: #2f5a08;
|
||||
--c-accent-deep: #3f6810;
|
||||
--c-accent-fill: #b9e277;
|
||||
--c-accent-fill-deep: #9bd34f;
|
||||
--c-accent-tint: #f3fbe6;
|
||||
--c-accent-tint2: #e6f5cf;
|
||||
--c-accent-line: #b3d78d;
|
||||
--c-accent-ink: #18200f;
|
||||
--c-danger: #b3261e;
|
||||
--c-danger-bright: #8f1710;
|
||||
--c-danger-tint: #fceae8;
|
||||
--c-danger-tint2: #f8d9d5;
|
||||
--c-danger-line: #e6b6b0;
|
||||
--c-danger-ink: #fceae8;
|
||||
--c-warn: #7d4a00;
|
||||
--c-warn-bright: #653c00;
|
||||
--c-warn-fill: #f2c96f;
|
||||
--c-warn-ink: #382506;
|
||||
--c-warn-tint: #fdf3dd;
|
||||
--c-warn-line: #e4cd9c;
|
||||
--c-info: #0a5a90;
|
||||
--c-info-tint: #e6f2fb;
|
||||
--c-info-line: #b6d7f0;
|
||||
--c-success: #2c6510;
|
||||
--c-success-tint: #e9f6df;
|
||||
--c-success-line: #bfe0a8;
|
||||
--c-pink: #96326e;
|
||||
--c-sky: #0a5a90;
|
||||
--c-pure-white: #ffffff;
|
||||
--c-pure-black: #000000;
|
||||
--c-scrim: rgba(30, 41, 52, .52);
|
||||
--c-scrim-soft: rgba(255, 255, 255, .82);
|
||||
--c-backdrop: rgba(20, 28, 38, .58);
|
||||
--c-backdrop-shadow: rgba(8, 14, 22, .30);
|
||||
--c-backdrop-veil: rgba(24, 32, 42, .55);
|
||||
--c-tint-success: rgba(233, 246, 223, .92);
|
||||
--c-tint-info: rgba(11, 97, 155, .10);
|
||||
--c-tint-accent: rgba(95, 156, 26, .12);
|
||||
--c-hairline: rgba(120, 140, 120, .30);
|
||||
--c-shade-1: rgba(15, 23, 32, .06);
|
||||
--c-shade-2: rgba(15, 23, 32, .10);
|
||||
--c-shade-3: rgba(15, 23, 32, .16);
|
||||
}
|
||||
|
||||
/* ── 控件高度体系(全站唯一,先读这段再改任何控件样式)──────────────────────
|
||||
症状:同一个视觉行里按钮 38、下拉 31、输入框 34,中心线错开。
|
||||
根因:控件高度靠各自 padding 撑,补丁散落在十几个文件里。
|
||||
做法:控件一律 h-(--ctl-h) 定高;容器只声明自己是哪一档
|
||||
([Ctlbar] / [ChipBar] 用 Tailwind 任意属性写 --ctl-h:var(--ctl-h-md)),
|
||||
行内所有控件随之等高。要改尺寸只改下面两个值。
|
||||
· 主尺寸 --ctl-h-main = 38px:表单字段、页面级主按钮
|
||||
· 紧凑 --ctl-h-md = 31px:工具条、筛选条、卡片动作行、chip / 分段开关
|
||||
触摸档(≤560px)只抬这两档令牌,页面不许自己写 min-height/padding 补丁。 */
|
||||
:root {
|
||||
--ctl-h-main: 38px;
|
||||
--ctl-h-md: 31px;
|
||||
--ctl-h: var(--ctl-h-main);
|
||||
/* 顶栏高度:侧栏 sticky、分镜检查器的 top 都取这个值,差 1px 就露缝。
|
||||
64 = 顶栏内边距 7×2 + 下边框 1 + 流程控制台 49(17 + 4 + 16 + 内边距 10 + 边框 2)。 */
|
||||
--nex-bar: 64px;
|
||||
--nex-ctl: var(--ctl-h);
|
||||
}
|
||||
@media (max-width: 560px) {
|
||||
:root { --ctl-h-main: 40px; --ctl-h-md: 36px }
|
||||
}
|
||||
|
||||
/* Tailwind v4 主题层:先清掉默认调色板/字阶,只留设计系统的语义名,
|
||||
这样「页面上出现一个没登记的颜色/字号」在类名上就看得出来。 */
|
||||
@theme {
|
||||
--color-*: initial;
|
||||
--text-*: initial;
|
||||
--radius-*: initial;
|
||||
--shadow-*: initial;
|
||||
|
||||
/* 表面(由暗到亮)与描边 */
|
||||
--color-deepest: var(--c-bg-deepest);
|
||||
--color-app: var(--c-bg-app);
|
||||
--color-field: var(--c-bg-input);
|
||||
--color-sunken: var(--c-bg-sunken);
|
||||
--color-card: var(--c-bg-card);
|
||||
--color-shell: var(--c-bg-shell);
|
||||
--color-panel: var(--c-bg-panel);
|
||||
--color-raised: var(--c-bg-raised);
|
||||
--color-hover: var(--c-bg-hover);
|
||||
--color-raise: var(--c-bg-raise);
|
||||
--color-active: var(--c-bg-active);
|
||||
--color-emphasis: var(--c-bg-emphasis);
|
||||
--color-line-soft: var(--c-line-soft);
|
||||
--color-line: var(--c-line);
|
||||
--color-line-strong: var(--c-line-strong);
|
||||
--color-line-bright: var(--c-line-bright);
|
||||
|
||||
/* 文字:ink 是正文,往下逐级变淡 */
|
||||
--color-ink: var(--c-text);
|
||||
--color-ink-2: var(--c-text-2);
|
||||
--color-ink-3: var(--c-text-3);
|
||||
--color-muted: var(--c-text-muted);
|
||||
--color-faint: var(--c-text-faint);
|
||||
--color-dim: var(--c-text-dim);
|
||||
--color-on-accent: var(--c-accent-ink);
|
||||
|
||||
/* 主色(青柠)与语义色 */
|
||||
--color-accent: var(--c-accent);
|
||||
--color-accent-bright: var(--c-accent-bright);
|
||||
--color-accent-deep: var(--c-accent-deep);
|
||||
--color-accent-fill: var(--c-accent-fill);
|
||||
--color-accent-fill-deep: var(--c-accent-fill-deep);
|
||||
--color-accent-tint: var(--c-accent-tint);
|
||||
--color-accent-tint-2: var(--c-accent-tint2);
|
||||
--color-accent-line: var(--c-accent-line);
|
||||
--color-danger: var(--c-danger);
|
||||
--color-danger-bright: var(--c-danger-bright);
|
||||
--color-danger-tint: var(--c-danger-tint);
|
||||
--color-danger-tint-2: var(--c-danger-tint2);
|
||||
--color-danger-line: var(--c-danger-line);
|
||||
--color-danger-ink: var(--c-danger-ink);
|
||||
--color-warn: var(--c-warn);
|
||||
--color-warn-bright: var(--c-warn-bright);
|
||||
--color-warn-fill: var(--c-warn-fill);
|
||||
--color-warn-ink: var(--c-warn-ink);
|
||||
--color-warn-tint: var(--c-warn-tint);
|
||||
--color-warn-line: var(--c-warn-line);
|
||||
--color-info: var(--c-info);
|
||||
--color-info-tint: var(--c-info-tint);
|
||||
--color-info-line: var(--c-info-line);
|
||||
--color-success: var(--c-success);
|
||||
--color-success-tint: var(--c-success-tint);
|
||||
--color-success-line: var(--c-success-line);
|
||||
--color-pink: var(--c-pink);
|
||||
--color-sky: var(--c-sky);
|
||||
--color-white: var(--c-pure-white);
|
||||
--color-black: var(--c-pure-black);
|
||||
|
||||
/* 浮层 / 遮罩 */
|
||||
--color-scrim: var(--c-scrim);
|
||||
--color-scrim-soft: var(--c-scrim-soft);
|
||||
--color-backdrop: var(--c-backdrop);
|
||||
--color-backdrop-shadow: var(--c-backdrop-shadow);
|
||||
--color-backdrop-veil: var(--c-backdrop-veil);
|
||||
--color-tint-success: var(--c-tint-success);
|
||||
--color-tint-info: var(--c-tint-info);
|
||||
--color-tint-accent: var(--c-tint-accent);
|
||||
--color-hairline: var(--c-hairline);
|
||||
--color-shade-1: var(--c-shade-1);
|
||||
--color-shade-2: var(--c-shade-2);
|
||||
--color-shade-3: var(--c-shade-3);
|
||||
|
||||
/* 字阶:10px 是站内最小可读字号(中文低于 10px 只剩一团墨点) */
|
||||
--default-font-family: var(--font-sans);
|
||||
--font-sans: 'DM Sans', 'Noto Sans SC', -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
|
||||
--text-tiny: 10px;
|
||||
--text-tiny--line-height: 1.5;
|
||||
--text-caption: 11px;
|
||||
--text-caption--line-height: 1.55;
|
||||
--text-label: 11.5px;
|
||||
--text-label--line-height: 1.5;
|
||||
--text-body: 12px;
|
||||
--text-body--line-height: 1.6;
|
||||
--text-ui: 13px;
|
||||
--text-ui--line-height: 1.6;
|
||||
--text-title: 14px;
|
||||
--text-title--line-height: 1.5;
|
||||
--text-md: 16px;
|
||||
--text-md--line-height: 1.45;
|
||||
--text-h2: 17px;
|
||||
--text-h2--line-height: 1.4;
|
||||
--text-lg: 20px;
|
||||
--text-lg--line-height: 1.35;
|
||||
--text-num-sm: 21px;
|
||||
--text-num-sm--line-height: 1.2;
|
||||
--text-num: 24px;
|
||||
--text-num--line-height: 1.2;
|
||||
--text-h1: 25px;
|
||||
--text-h1--line-height: 1.25;
|
||||
--text-3xl: 32px;
|
||||
--text-3xl--line-height: 1.25;
|
||||
--text-display: 42px;
|
||||
--text-display--line-height: 1.25;
|
||||
|
||||
/* 圆角 */
|
||||
--radius-chip: 5px;
|
||||
--radius-control: 7px;
|
||||
--radius-tile: 9px;
|
||||
--radius-block: 12px;
|
||||
--radius-float: 14px;
|
||||
--radius-pill: 999px;
|
||||
|
||||
/* 阴影:只区分「贴层浮起 / 弹出菜单 / 抽屉」三档 */
|
||||
--shadow-raise: 0 1px 2px var(--c-shade-1);
|
||||
--shadow-pop: 0 18px 44px var(--c-backdrop-shadow);
|
||||
--shadow-drawer: -25px 0 80px var(--c-shade-2);
|
||||
|
||||
/* 断点:沿用旧站已经调好的六档,名字按「这一档在收什么」取。
|
||||
页面不要再自己写 @media(1180px) 这类魔法数字(UI规范 §0)。
|
||||
huge 1440 超宽屏开始收窄
|
||||
mid 1180 右栏检查器落到下方、控制台收起当前节点
|
||||
mid2 1100 两栏布局转一栏
|
||||
nav 900 侧栏收成图标轨、顶栏品牌只剩徽标
|
||||
short 820 顶栏工具收成图标
|
||||
tiny 640 顶栏控制台收起徽标与文字标签
|
||||
narrow 560 手机档:控件升到 40/36px */
|
||||
--breakpoint-huge: 1440px;
|
||||
--breakpoint-mid: 1180px;
|
||||
--breakpoint-mid2: 1100px;
|
||||
--breakpoint-nav: 900px;
|
||||
--breakpoint-short: 820px;
|
||||
--breakpoint-tiny: 640px;
|
||||
--breakpoint-narrow: 560px;
|
||||
|
||||
/* 动效 */
|
||||
--animate-spin-slow: nex-spin .8s linear infinite;
|
||||
--animate-pulse-soft: nex-pulse 1.6s ease-in-out infinite;
|
||||
/* 弹层出现:只做淡入。面板向上翻边时靠 transform:translateY(-100%) 定位,
|
||||
位移类动画会和它打架(面板会跳一下)。 */
|
||||
--animate-fade-in: nex-fade-in .12s ease-out;
|
||||
}
|
||||
|
||||
@keyframes nex-spin { to { transform: rotate(360deg) } }
|
||||
@keyframes nex-fade-in { from { opacity: 0 } }
|
||||
@keyframes nex-pulse { 50% { opacity: .45 } }
|
||||
|
||||
/* 浅色变体:极少数「同一元素两个主题形状不同」的场合用 light:,
|
||||
能用令牌解决的不要用它(令牌已经跟着 data-theme 翻了)。 */
|
||||
@custom-variant light (&:where([data-theme="light"], [data-theme="light"] *));
|
||||
|
|
@ -1,161 +0,0 @@
|
|||
/* 主题令牌:深色为默认值,[data-theme="light"] 覆盖为浅色。 */
|
||||
:root {
|
||||
--c-bg-deepest: #0b1116;
|
||||
--c-bg-app: #0d1117;
|
||||
--c-bg-input: #0e141a;
|
||||
--c-bg-sunken: #0f161d;
|
||||
--c-bg-card: #10171e;
|
||||
--c-bg-shell: #111820;
|
||||
--c-bg-panel: #141b23;
|
||||
--c-bg-raised: #18211a;
|
||||
--c-bg-hover: #1e2932;
|
||||
--c-bg-raise: #202b35;
|
||||
--c-bg-active: #243039;
|
||||
--c-bg-emphasis: #283540;
|
||||
--c-line-soft: #212c35;
|
||||
--c-line: #293640;
|
||||
--c-line-strong: #35434e;
|
||||
--c-line-bright: #4b5a64;
|
||||
--c-text: #e9edf2;
|
||||
--c-text-2: #c3ced7;
|
||||
--c-text-3: #adb9c3;
|
||||
--c-text-muted: #a1adb7;
|
||||
--c-text-faint: #96a2ad;
|
||||
--c-text-dim: #99a5b0;
|
||||
--c-on-accent: #18200f;
|
||||
--c-accent: #c5ee79;
|
||||
--c-accent-bright: #dff9a7;
|
||||
--c-accent-deep: #9acb60;
|
||||
--c-accent-fill: #c5ee79;
|
||||
--c-accent-fill-deep: #9acb60;
|
||||
--c-accent-tint: #1a2410;
|
||||
--c-accent-tint2: #263b28;
|
||||
--c-accent-line: #465840;
|
||||
--c-accent-ink: #18200f;
|
||||
--c-danger: #f0a59c;
|
||||
--c-danger-bright: #ffb9b0;
|
||||
--c-danger-tint: #482927;
|
||||
--c-danger-tint2: #3c2320;
|
||||
--c-danger-line: #6b3630;
|
||||
--c-danger-ink: #2a1210;
|
||||
--c-warn: #f0cf8e;
|
||||
--c-warn-bright: #f2d18b;
|
||||
--c-warn-fill: #f0cf8e;
|
||||
--c-warn-ink: #302108;
|
||||
--c-warn-tint: #3b3320;
|
||||
--c-warn-line: #584c2c;
|
||||
--c-info: #9bcdf1;
|
||||
--c-info-tint: #233649;
|
||||
--c-info-line: #2f4a5e;
|
||||
--c-success: #bce989;
|
||||
--c-success-tint: #22371f;
|
||||
--c-success-line: #3d5c33;
|
||||
--c-pink: #e5a4d0;
|
||||
--c-sky: #79c8ef;
|
||||
--c-pure-white: #ffffff;
|
||||
--c-pure-black: #000000;
|
||||
--c-scrim: rgba(4, 8, 11, .74);
|
||||
--c-scrim-soft: rgba(9, 13, 17, .82);
|
||||
/* 媒体预览(灯箱)用的观看背景:两种主题都压得够暗,让画面本身成为主体 */
|
||||
--c-backdrop: rgba(2, 5, 8, .82);
|
||||
--c-backdrop-shadow: rgba(0, 0, 0, .55);
|
||||
--c-backdrop-veil: rgba(9, 14, 20, .62);
|
||||
--c-tint-success: rgba(38, 63, 32, .92);
|
||||
--c-tint-info: rgba(99, 132, 255, .10);
|
||||
--c-tint-accent: rgba(197, 238, 121, .16);
|
||||
--c-hairline: rgba(111, 135, 116, .24);
|
||||
--c-shade-1: rgba(0, 0, 0, .16);
|
||||
--c-shade-2: rgba(0, 0, 0, .24);
|
||||
--c-shade-3: rgba(0, 0, 0, .42);
|
||||
}
|
||||
[data-theme="light"] {
|
||||
--c-bg-deepest: #e7edf4;
|
||||
--c-bg-app: #f0f4f8;
|
||||
--c-bg-input: #fbfcfe;
|
||||
--c-bg-sunken: #eef2f7;
|
||||
--c-bg-card: #f6f8fb;
|
||||
--c-bg-shell: #ffffff;
|
||||
--c-bg-panel: #ffffff;
|
||||
--c-bg-raised: #eef4ea;
|
||||
--c-bg-hover: #e9eff6;
|
||||
--c-bg-raise: #e2e9f1;
|
||||
--c-bg-active: #dae3ec;
|
||||
--c-bg-emphasis: #cfd9e3;
|
||||
--c-line-soft: #e9eef4;
|
||||
--c-line: #dbe3ea;
|
||||
--c-line-strong: #c3ccd6;
|
||||
--c-line-bright: #aab5bf;
|
||||
--c-text: #111a22;
|
||||
--c-text-2: #2c3946;
|
||||
--c-text-3: #3f4c58;
|
||||
--c-text-muted: #4d5762;
|
||||
--c-text-faint: #535d68;
|
||||
--c-text-dim: #555f6a;
|
||||
--c-on-accent: #18200f;
|
||||
--c-accent: #356309;
|
||||
--c-accent-bright: #2f5a08;
|
||||
--c-accent-deep: #3f6810;
|
||||
--c-accent-fill: #b9e277;
|
||||
--c-accent-fill-deep: #9bd34f;
|
||||
--c-accent-tint: #f3fbe6;
|
||||
--c-accent-tint2: #e6f5cf;
|
||||
--c-accent-line: #b3d78d;
|
||||
--c-accent-ink: #18200f;
|
||||
--c-danger: #b3261e;
|
||||
--c-danger-bright: #8f1710;
|
||||
--c-danger-tint: #fceae8;
|
||||
--c-danger-tint2: #f8d9d5;
|
||||
--c-danger-line: #e6b6b0;
|
||||
--c-danger-ink: #fceae8;
|
||||
--c-warn: #7d4a00;
|
||||
--c-warn-bright: #653c00;
|
||||
--c-warn-fill: #f2c96f;
|
||||
--c-warn-ink: #382506;
|
||||
--c-warn-tint: #fdf3dd;
|
||||
--c-warn-line: #e4cd9c;
|
||||
--c-info: #0a5a90;
|
||||
--c-info-tint: #e6f2fb;
|
||||
--c-info-line: #b6d7f0;
|
||||
--c-success: #2c6510;
|
||||
--c-success-tint: #e9f6df;
|
||||
--c-success-line: #bfe0a8;
|
||||
--c-pink: #96326e;
|
||||
--c-sky: #0a5a90;
|
||||
--c-pure-white: #ffffff;
|
||||
--c-pure-black: #000000;
|
||||
--c-scrim: rgba(30, 41, 52, .52);
|
||||
--c-scrim-soft: rgba(255, 255, 255, .82);
|
||||
--c-backdrop: rgba(20, 28, 38, .58);
|
||||
--c-backdrop-shadow: rgba(8, 14, 22, .30);
|
||||
--c-backdrop-veil: rgba(24, 32, 42, .55);
|
||||
--c-tint-success: rgba(233, 246, 223, .92);
|
||||
--c-tint-info: rgba(11, 97, 155, .10);
|
||||
--c-tint-accent: rgba(95, 156, 26, .12);
|
||||
--c-hairline: rgba(120, 140, 120, .30);
|
||||
--c-shade-1: rgba(15, 23, 32, .06);
|
||||
--c-shade-2: rgba(15, 23, 32, .10);
|
||||
--c-shade-3: rgba(15, 23, 32, .16);
|
||||
}
|
||||
|
||||
/* 视图里反复用到的四个简写别名,提到根上定义。
|
||||
原来它们只写在 .model-center / .asset-library 自己手上,而「配置抽屉」是 Teleport 到
|
||||
body 的,拿不到这些自定义属性:抽屉里 .tokens button.on 的 background 会解析成空值,
|
||||
深色主题下变成「透明底 + 近黑字」,选中的 Max Tokens 看起来像没选中,滑杆和复选框
|
||||
的 accent-color 也一起失效。放在 :root 上,任何脱离组件子树的浮层都能继承。 */
|
||||
:root,
|
||||
[data-theme="light"] {
|
||||
--line: var(--c-line);
|
||||
--panel: var(--c-bg-panel);
|
||||
--lime: var(--c-accent);
|
||||
--lime-fill: var(--c-accent-fill);
|
||||
}
|
||||
|
||||
/* ---------- 站内最小可读字号下限 ----------
|
||||
浏览器对 <small> 的实现是 font-size:smaller(÷1.2),所以只要外层已经是一个
|
||||
10~11px 的小字容器(侧栏导航标题、卡片 meta、抽屉说明),<small> 就会掉到 8.3px,
|
||||
两层嵌套更是压到 6.9px:中文在这个尺寸下只剩一团墨点。之前全站另有 82 处写死
|
||||
8/8.5/9/9.5px 的标签,已全部提到设计系统的微字号基准 10px(.tiny/.status/.meta
|
||||
用的就是这个值)。这里再补一条兜底:任何 <small> 都不许低于 10px,
|
||||
比它大的场景仍然按父级的 0.8 倍缩放,标题里的小字不会被强行放大。
|
||||
元素选择器优先级最低,不会盖过任何带 class 的显式字号。 */
|
||||
small { font-size: max(0.8em, 10px) }
|
||||
|
|
@ -1,62 +0,0 @@
|
|||
/**
|
||||
* 明暗主题:默认跟随系统,用户切换后记住选择。
|
||||
*
|
||||
* 颜色全部走 theme.css 里的 --c-* 令牌,切换只改 <html data-theme>,
|
||||
* 不需要重新渲染组件;因此这里只负责「决定并落地 data-theme」。
|
||||
*/
|
||||
import { reactive, watch } from 'vue'
|
||||
|
||||
export type ThemeMode = 'dark' | 'light'
|
||||
|
||||
const KEY = 'nex-the'
|
||||
const QUERY = '(prefers-color-scheme: light)'
|
||||
|
||||
export const theme = reactive<{ mode: ThemeMode; followSystem: boolean; applied: ThemeMode }>({
|
||||
mode: 'dark',
|
||||
followSystem: true,
|
||||
applied: 'dark'
|
||||
})
|
||||
|
||||
function systemMode(): ThemeMode {
|
||||
return typeof window !== 'undefined' && window.matchMedia?.(QUERY).matches ? 'light' : 'dark'
|
||||
}
|
||||
|
||||
export function applyTheme() {
|
||||
const mode = theme.followSystem ? systemMode() : theme.mode
|
||||
theme.applied = mode // 组件用 computed 读它,DOM 本身不是响应式的
|
||||
document.documentElement.dataset.theme = mode
|
||||
document.documentElement.style.colorScheme = mode
|
||||
const meta = document.querySelector('meta[name="color-scheme"]')
|
||||
if (meta) meta.setAttribute('content', mode)
|
||||
const bg = document.querySelector('meta[name="theme-color"]')
|
||||
if (bg) bg.setAttribute('content', mode === 'light' ? '#f0f4f8' : '#0d1117')
|
||||
}
|
||||
|
||||
export function setTheme(mode: ThemeMode, options: { followSystem?: boolean } = {}) {
|
||||
theme.followSystem = options.followSystem ?? false
|
||||
theme.mode = mode
|
||||
try {
|
||||
if (options.followSystem) localStorage.removeItem(KEY)
|
||||
else localStorage.setItem(KEY, mode)
|
||||
} catch {
|
||||
/* 隐私模式下 localStorage 会抛错,主题当场生效即可 */
|
||||
}
|
||||
applyTheme()
|
||||
}
|
||||
|
||||
export function initTheme() {
|
||||
let saved: string | null = null
|
||||
try { saved = localStorage.getItem(KEY) } catch { /* ignore */ }
|
||||
if (saved === 'dark' || saved === 'light') {
|
||||
theme.mode = saved
|
||||
theme.followSystem = false
|
||||
} else {
|
||||
theme.mode = systemMode()
|
||||
theme.followSystem = true
|
||||
}
|
||||
applyTheme()
|
||||
window.matchMedia?.(QUERY).addEventListener?.('change', () => {
|
||||
if (theme.followSystem) { theme.mode = systemMode(); applyTheme() }
|
||||
})
|
||||
watch(() => [theme.mode, theme.followSystem], applyTheme)
|
||||
}
|
||||
|
|
@ -1,163 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import AutoRefresh from '../components/AutoRefresh.vue'
|
||||
import SecretInput from '../components/SecretInput.vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import * as api from '../api'
|
||||
import { auth, login, roleLabel, setUser } from '../auth'
|
||||
import { fmtAgo, fmtTime } from '../format'
|
||||
|
||||
const route = useRoute()
|
||||
const mustChange = computed(() => route.query.must === '1' || !!auth.user?.must_change_password)
|
||||
const busy = ref('')
|
||||
const error = ref('')
|
||||
const notice = ref('')
|
||||
const sessions = ref<any[]>([])
|
||||
|
||||
const profile = reactive({ display_name: '', email: '' })
|
||||
/** 资料改过没保存 / 改密框里有字 → 暂停轮询,别把用户刚敲的内容冲掉 */
|
||||
let savedSnapshot = ''
|
||||
const formTouched = computed(() => savedSnapshot !== JSON.stringify({ ...profile })
|
||||
|| Boolean(pwd.current_password || pwd.new_password || pwd.confirm))
|
||||
const pwd = reactive({ current_password: '', new_password: '', confirm: '' })
|
||||
|
||||
const role = computed(() => roleLabel(auth.user?.role || ''))
|
||||
const rulesHint = '至少 8 位,且不能只有一类字符(字母 / 数字 / 符号至少两种)'
|
||||
|
||||
async function load() {
|
||||
error.value = ''
|
||||
try {
|
||||
const data = await api.get('/api/auth/me')
|
||||
const user = data.user || auth.user
|
||||
setUser(user)
|
||||
profile.display_name = user?.display_name || ''
|
||||
profile.email = user?.email || ''
|
||||
sessions.value = data.sessions || []
|
||||
savedSnapshot = JSON.stringify({ ...profile })
|
||||
} catch (exc: any) {
|
||||
error.value = exc?.message || String(exc)
|
||||
}
|
||||
}
|
||||
|
||||
async function saveProfile() {
|
||||
busy.value = '保存资料'
|
||||
error.value = ''
|
||||
notice.value = ''
|
||||
try {
|
||||
setUser(await api.patch('/api/auth/me', { ...profile }))
|
||||
notice.value = '资料已更新。'
|
||||
} catch (exc: any) { error.value = exc?.message || String(exc) }
|
||||
finally { busy.value = '' }
|
||||
}
|
||||
|
||||
async function changePassword() {
|
||||
error.value = ''
|
||||
notice.value = ''
|
||||
if (!pwd.current_password || !pwd.new_password) { error.value = '请填写当前密码与新密码'; return }
|
||||
if (pwd.new_password !== pwd.confirm) { error.value = '两次输入的新密码不一致'; return }
|
||||
busy.value = '修改密码'
|
||||
try {
|
||||
const data = await api.post('/api/auth/password', {
|
||||
current_password: pwd.current_password, new_password: pwd.new_password
|
||||
})
|
||||
setUser(data.user || null)
|
||||
Object.assign(pwd, { current_password: '', new_password: '', confirm: '' })
|
||||
notice.value = `密码已更新,其它 ${data.revoked_sessions ?? 0} 个登录会话已注销。`
|
||||
await load()
|
||||
} catch (exc: any) { error.value = exc?.message || String(exc) }
|
||||
finally { busy.value = '' }
|
||||
}
|
||||
|
||||
/** 首次登录的种子账号:改完密码就地重新签一次会话,确保 Cookie 属性是最新的 */
|
||||
async function relogin() {
|
||||
if (!auth.user?.username || !pwd.new_password) return
|
||||
try { await login(auth.user.username, pwd.new_password) } catch { /* 已经改完,重签失败不拦人 */ }
|
||||
}
|
||||
|
||||
async function revoke(row: any) {
|
||||
busy.value = '注销会话'
|
||||
error.value = ''
|
||||
try {
|
||||
await api.del(`/api/auth/sessions/${row.id}`)
|
||||
sessions.value = sessions.value.filter((item) => item.id !== row.id)
|
||||
notice.value = `已注销「${row.label}」的登录会话。`
|
||||
} catch (exc: any) { error.value = exc?.message || String(exc) }
|
||||
finally { busy.value = '' }
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<header>
|
||||
<div><small class="eyebrow">MY ACCOUNT</small><h1>我的账号</h1></div>
|
||||
<span class="tag" :class="{ info: auth.user?.role === 'admin' }">{{ role }}</span>
|
||||
</header>
|
||||
|
||||
<p v-if="mustChange" class="notice">这个账号还在使用初始密码,请先修改密码再开始制作。</p>
|
||||
<p v-if="notice" class="notice">{{ notice }}</p>
|
||||
<p v-if="error" class="error" style="font-size:11px;margin:0 0 14px">{{ error }}</p>
|
||||
|
||||
<div class="layout">
|
||||
<div class="right">
|
||||
<section class="panel">
|
||||
<div class="panel-head"><div><small class="eyebrow">PROFILE</small><h2>基本资料</h2></div></div>
|
||||
<div class="frow">
|
||||
<label class="fld"><span>登录名</span><input :value="auth.user?.username" disabled /></label>
|
||||
<label class="fld"><span>显示名</span><input v-model="profile.display_name" maxlength="80" placeholder="同事看到的名字" /></label>
|
||||
<label class="fld"><span>邮箱</span><input v-model="profile.email" maxlength="160" placeholder="用于通知,可留空" /></label>
|
||||
<label class="fld"><span>角色</span><input :value="role + '(由管理员分配)'" disabled /></label>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button class="primary" :disabled="!!busy" @click="saveProfile">保存资料</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-head"><div><small class="eyebrow">PASSWORD</small><h2>修改密码</h2></div></div>
|
||||
<div class="frow">
|
||||
<label class="fld"><span>当前密码</span><SecretInput v-model="pwd.current_password" autocomplete="current-password"
|
||||
placeholder="输入当前密码" /></label>
|
||||
<label class="fld"><span>新密码</span><SecretInput v-model="pwd.new_password" :title="rulesHint" autocomplete="new-password"
|
||||
placeholder="至少 8 位,建议混合字母与数字" /></label>
|
||||
<label class="fld"><span>确认新密码</span><SecretInput v-model="pwd.confirm" autocomplete="new-password" placeholder="再输入一次新密码"
|
||||
@keyup.enter="changePassword" /></label>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button title="改密后其它设备的会话会自动注销,本机保留。" class="primary" :disabled="!!busy" @click="changePassword">修改密码</button>
|
||||
<button class="outline" :disabled="!!busy || !pwd.new_password || pwd.new_password !== pwd.confirm"
|
||||
@click="relogin">用新密码重新登录本机</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="right">
|
||||
<section class="panel">
|
||||
<div class="panel-head"><div><small class="eyebrow">SESSIONS</small><h2>登录设备</h2></div>
|
||||
<AutoRefresh :busy="!!busy" :every="45000" :paused="!!busy || formTouched" @refresh="load()" /></div>
|
||||
<div v-if="!sessions.length" class="empty">只有一个当前会话,没有其它设备在线。</div>
|
||||
<div v-else class="sess">
|
||||
<div v-for="row in sessions" :key="row.id" class="sessrow">
|
||||
<div class="grow">
|
||||
<b>{{ row.current ? '当前会话' : row.label }}</b>
|
||||
<p class="muted">{{ row.ip || '未知 IP' }} · 活跃于 {{ fmtAgo(row.last_seen_at) }} · {{ fmtTime(row.expires_at) }} 过期</p>
|
||||
</div>
|
||||
<button v-if="!row.current" class="outline tiny" :disabled="!!busy" @click="revoke(row)">注销</button>
|
||||
<span v-else class="tag">使用中</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.sess { display: flex; flex-direction: column }
|
||||
.sessrow { display: flex; align-items: center; gap: 10px; padding: 11px 0; border-bottom: 1px solid var(--c-line) }
|
||||
.sessrow:last-child { border-bottom: 0 }
|
||||
.sessrow > div { min-width: 0 }
|
||||
.sessrow button { flex: 0 0 auto; white-space: nowrap }
|
||||
.sessrow b { font-size: 12px }
|
||||
.sessrow p { margin: 4px 0 0 }
|
||||
.grow { flex: 1 1 auto; min-width: 0 }
|
||||
</style>
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -1,524 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import * as api from '../api'
|
||||
import { store } from '../store'
|
||||
import { EVENT_LEVELS, eventLabel, eventLevelKey, fmtAgo, fmtMoney, fmtTime, opt, pct, statusClass, statusLabel } from '../format'
|
||||
import {
|
||||
capsOf, capabilityHint, defaultFor, deliveryResolutions, isMock, loadModels, modelsOf,
|
||||
parseRef, refOf, resolutionChoices, fpsChoices
|
||||
} from '../models'
|
||||
import { stageNote } from '../pipeline'
|
||||
import { fromAsset, isAudio as audioOf, isImage as imageOf } from '../media'
|
||||
import { notify } from '../project'
|
||||
import WorkflowBar from '../components/WorkflowBar.vue'
|
||||
import MediaThumb from '../components/MediaThumb.vue'
|
||||
import AutoRefresh from '../components/AutoRefresh.vue'
|
||||
import FSelect from '../components/FSelect.vue'
|
||||
|
||||
const router = useRouter()
|
||||
const projects = ref<any[]>([])
|
||||
const events = ref<any[]>([])
|
||||
const loading = ref(true)
|
||||
const error = ref('')
|
||||
const keyword = ref('')
|
||||
const statusFilter = ref('')
|
||||
const creating = ref(false)
|
||||
/** 全局动态过滤(DB-4):级别 + 关键字,只看异常时不必在 40 条流水里翻 */
|
||||
const eventLevel = ref('')
|
||||
const eventKeyword = ref('')
|
||||
|
||||
const form = reactive({
|
||||
name: '', description: '', genre: '', target_duration: 120, aspect_ratio: '16:9',
|
||||
resolution: '720p', fps: 24, style_guide: '', global_negative_prompt: '',
|
||||
default_provider: '', default_model: '', default_transition: 'cut'
|
||||
})
|
||||
|
||||
const statuses = computed<string[]>(() => store.meta?.project_statuses || [])
|
||||
/** 视频模型决定可用档位:新建时就按注册表给默认值,不再让用户手填 provider 字符串 */
|
||||
const videoModels = computed(() => modelsOf('video'))
|
||||
const videoRef = computed({
|
||||
get: () => (form.default_provider ? `${form.default_provider}|${form.default_model}` : ''),
|
||||
set: (v: string) => {
|
||||
const [provider, model] = parseRef(v)
|
||||
form.default_provider = provider
|
||||
form.default_model = model
|
||||
const caps = capsOf(provider, model)
|
||||
if (caps.fps > 0) form.fps = caps.fps
|
||||
// 档位不在模型能力里才回落,且只回落到「原生能出」的最高档:
|
||||
// 放大交付档(1080p)是合法选项,不能一换模型就被静默踢回 720p。
|
||||
const deliverable = deliveryResolutions(provider, model)
|
||||
if (deliverable.length && !deliverable.includes(form.resolution)) {
|
||||
const native = caps.resolutions.length ? caps.resolutions : deliverable
|
||||
form.resolution = native[native.length - 1]
|
||||
}
|
||||
}
|
||||
})
|
||||
/* 新建项目必须落到注册表里真实存在的模型:留空虽然会被后端回落成平台默认,
|
||||
但表单按空 provider 查能力时会报「注册表里还没有这个模型」,用户以为保存后必然派发失败。
|
||||
这里直接预置平台默认模型(优先真实通道,演练环境才回落 mock),少一个选项也少一次误判。 */
|
||||
const preferredVideoModel = computed(() => defaultFor('video', false) || defaultFor('video'))
|
||||
watch(preferredVideoModel, (row) => {
|
||||
if (!row || form.default_provider) return
|
||||
videoRef.value = refOf(row)
|
||||
}, { immediate: true })
|
||||
|
||||
const videoCaps = computed(() => capsOf(form.default_provider, form.default_model || null))
|
||||
const resOptions = computed(() => resolutionChoices(form.default_provider, form.default_model || null))
|
||||
const fpsOptions = computed(() => fpsChoices(form.default_provider, form.default_model || null))
|
||||
const modelWarnings = computed(() => capabilityHint(
|
||||
form.default_provider, form.default_model || null, form.resolution, form.fps, form.aspect_ratio))
|
||||
const durationRule = computed(() => {
|
||||
const { minDuration, maxDuration } = videoCaps.value
|
||||
if (!minDuration && !maxDuration) return '模型未声明单镜时长区间'
|
||||
return `总时长按镜头累加;单镜需在 ${minDuration}–${maxDuration} 秒内`
|
||||
})
|
||||
const filtered = computed(() => {
|
||||
const q = keyword.value.trim().toLowerCase()
|
||||
return projects.value.filter((p) => {
|
||||
if (statusFilter.value && p.status !== statusFilter.value) return false
|
||||
if (!q) return true
|
||||
return `${p.name} ${p.description} ${p.genre}`.toLowerCase().includes(q)
|
||||
})
|
||||
})
|
||||
const shownEvents = computed(() => {
|
||||
const needle = eventKeyword.value.trim().toLowerCase()
|
||||
return events.value.filter((e: any) => {
|
||||
if (eventLevel.value && eventLevelKey(e.level) !== eventLevel.value) return false
|
||||
if (!needle) return true
|
||||
return `${e.message || ''} ${e.action || ''} ${eventLabel(e.action)}`.toLowerCase().includes(needle)
|
||||
})
|
||||
})
|
||||
const levelCounts = computed(() => {
|
||||
const counts: Record<string, number> = {}
|
||||
for (const e of events.value) {
|
||||
const key = eventLevelKey(e.level)
|
||||
counts[key] = (counts[key] || 0) + 1
|
||||
}
|
||||
return counts
|
||||
})
|
||||
|
||||
const totals = computed(() => ({
|
||||
all: projects.value.length,
|
||||
active: projects.value.filter((p) => ['generating', 'reviewing', 'composing', 'storyboard', 'binding'].includes(p.status)).length,
|
||||
delivered: projects.value.filter((p) => p.status === 'delivered').length,
|
||||
cost: projects.value.reduce((sum, p) => sum + Number(p.stats?.cost?.total_cost || 0), 0),
|
||||
// 币种来自成本台账本身(/api/meta 里没有 currency 这个字段)
|
||||
currency: projects.value.find((p) => p.stats?.cost?.currency)?.stats?.cost?.currency || 'CNY'
|
||||
}))
|
||||
|
||||
/* ── 新建项目时直接勾选要引入的资源库母版 ─────────────────────────────
|
||||
资源库里的人物定妆图 / 场景母图 / 角色声线是跨项目复用的,但以前必须先建项目、
|
||||
再跳到资源库页面逐条「引入到项目」,新项目的第一镜总是零素材起步。
|
||||
这里勾好后随创建请求一起提交(platform_assets),后端逐条引入并回报失败原因。 */
|
||||
type LibType = 'human' | 'scene' | 'voice'
|
||||
const LIB_TYPES: { value: LibType; label: string }[] = [
|
||||
{ value: 'human', label: '人物' }, { value: 'scene', label: '场景' }, { value: 'voice', label: '声线' }
|
||||
]
|
||||
const libOpen = ref(false)
|
||||
const libType = ref<LibType>('human')
|
||||
const libQuery = ref('')
|
||||
const libRows = ref<Record<LibType, any[]>>({ human: [], scene: [], voice: [] })
|
||||
const libLoading = ref(false)
|
||||
const libError = ref('')
|
||||
const libLoaded = ref<Record<LibType, boolean>>({ human: false, scene: false, voice: false })
|
||||
/** 选中项保存完整行:切到别的分类后,已选人物还要能显示名字与缩略图 */
|
||||
const picked = ref<Record<string, any>>({})
|
||||
const libKey = (row: any) => `${row.owner_type}:${row.asset_id ?? row.id}`
|
||||
const pickedRows = computed(() => Object.values(picked.value))
|
||||
const pickedCount = computed(() => pickedRows.value.length)
|
||||
const pickedByType = computed(() => {
|
||||
const grouped: Record<string, any[]> = { human: [], scene: [], voice: [] }
|
||||
for (const row of pickedRows.value) (grouped[row.owner_type] ||= []).push(row)
|
||||
return grouped
|
||||
})
|
||||
const libShown = computed(() => {
|
||||
const needle = libQuery.value.trim().toLowerCase()
|
||||
return (libRows.value[libType.value] || []).filter((row: any) => {
|
||||
if (!needle) return true
|
||||
const media = (row.assets || []).map((m: any) => m.kind).join(' ')
|
||||
return `${row.name} ${row.code || ''} ${(row.tags || []).join(' ')} ${media}`
|
||||
.toLowerCase().includes(needle)
|
||||
})
|
||||
})
|
||||
const coverOf = (row: any) => (row?.assets || []).find((m: any) => imageOf(m)) || null
|
||||
const audioOfRow = (row: any) => (row?.assets || []).find((m: any) => audioOf(m)) || null
|
||||
const subLabel = (row: any) => row.owner_type === 'human'
|
||||
? [row.role, row.default_voice_name && `声线:${row.default_voice_name}`].filter(Boolean).join(' · ')
|
||||
: (row.owner_type === 'scene' ? (row.time_of_day || row.lighting || row.description || '')
|
||||
: [row.gender, row.language, row.provider].filter(Boolean).join(' · '))
|
||||
|
||||
async function loadLibrary(force = false) {
|
||||
const kind = libType.value
|
||||
if (libLoading.value || (libLoaded.value[kind] && !force)) return
|
||||
libLoading.value = true
|
||||
libError.value = ''
|
||||
try {
|
||||
const data = await api.get('/api/platform/assets', { owner_type: kind, status: 'active', sort: 'updated', page_size: 0 })
|
||||
libRows.value = { ...libRows.value, [kind]: data.items || [] }
|
||||
libLoaded.value = { ...libLoaded.value, [kind]: true }
|
||||
} catch (exc: any) {
|
||||
libError.value = exc.message
|
||||
} finally {
|
||||
libLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function toggleLibrary() {
|
||||
libOpen.value = !libOpen.value
|
||||
if (libOpen.value) loadLibrary()
|
||||
}
|
||||
|
||||
function pickType(kind: LibType) {
|
||||
libType.value = kind
|
||||
loadLibrary()
|
||||
}
|
||||
|
||||
function togglePick(row: any) {
|
||||
const key = libKey(row)
|
||||
const next = { ...picked.value }
|
||||
if (next[key]) delete next[key]
|
||||
else next[key] = { owner_type: row.owner_type, asset_id: row.id, name: row.name,
|
||||
type_label: row.type_label, role: row.role, gender: row.gender }
|
||||
picked.value = next
|
||||
}
|
||||
|
||||
function resetLibrary() {
|
||||
picked.value = {}
|
||||
libOpen.value = false
|
||||
libQuery.value = ''
|
||||
}
|
||||
|
||||
async function load() {
|
||||
error.value = ''
|
||||
loadModels()
|
||||
try {
|
||||
const [list, evs] = await Promise.all([
|
||||
api.get('/api/projects', { status: statusFilter.value, q: keyword.value }),
|
||||
api.get('/api/events', { limit: 40 })
|
||||
])
|
||||
projects.value = list.projects || []
|
||||
events.value = evs.events || []
|
||||
} catch (exc: any) {
|
||||
error.value = exc.message
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (!form.name.trim()) { error.value = '请填写项目名称'; return }
|
||||
if (videoCaps.value.known && videoCaps.value.mock) {
|
||||
error.value = '当前选的是 mock 演练通道,正式项目请选择真实视频模型'
|
||||
return
|
||||
}
|
||||
try {
|
||||
const assets = pickedRows.value.map((row: any) => ({ owner_type: row.owner_type, asset_id: row.asset_id }))
|
||||
const created = await api.post('/api/projects', { ...form, platform_assets: assets })
|
||||
const failures: any[] = created?.import_failures || []
|
||||
const imported: any[] = created?.imported_assets || []
|
||||
creating.value = false
|
||||
resetLibrary()
|
||||
if (failures.length) {
|
||||
notify(`已引入 ${imported.length} 个资源,${failures.length} 个失败:`
|
||||
+ failures.slice(0, 2).map((f: any) => f.detail).join(';')
|
||||
+ (failures.length > 2 ? ' …' : ''))
|
||||
} else if (imported.length) {
|
||||
notify(`已引入资源库母版 ${imported.length} 个,可直接绑定到镜头`)
|
||||
}
|
||||
await router.push(`/projects/${created.id}/overview`)
|
||||
} catch (exc: any) {
|
||||
error.value = exc.message
|
||||
}
|
||||
}
|
||||
|
||||
async function removeProject(p: any) {
|
||||
if (!confirm(`确认删除项目《${p.name}》?该操作不可恢复。`)) return
|
||||
try {
|
||||
await api.del(`/api/projects/${p.id}`, { purge_files: true })
|
||||
await load()
|
||||
} catch (exc: any) { error.value = exc.message }
|
||||
}
|
||||
|
||||
/* 规范 §4 / R6:筛选即时生效,不放「筛选」按钮(与「队列自动刷新不加按钮」同源)。
|
||||
输入停顿 300ms 再回源,避免每敲一个字打一次接口。 */
|
||||
let searchTimer: number | undefined
|
||||
watch([keyword, statusFilter], () => {
|
||||
window.clearTimeout(searchTimer)
|
||||
searchTimer = window.setTimeout(load, 300)
|
||||
})
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<header>
|
||||
<div>
|
||||
<small class="eyebrow">01 / PROJECTS</small>
|
||||
<h1>项目总览</h1>
|
||||
</div>
|
||||
<div class="row">
|
||||
<AutoRefresh :every="20000" :paused="creating" @refresh="load()" />
|
||||
<button class="primary" @click="creating = !creating">{{ creating ? '收起' : '+ 新建长视频项目' }}</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<p v-if="error" class="error" style="margin-bottom:14px">{{ error }}</p>
|
||||
|
||||
<form v-if="creating" class="panel" style="margin-bottom:18px" @submit.prevent="submit">
|
||||
<div class="between" style="margin-bottom:12px">
|
||||
<h3 style="margin:0" title="流程第 ① 步:创建视频项目">新建长视频项目</h3>
|
||||
</div>
|
||||
<div class="frow">
|
||||
<label class="fld"><span>项目名称 <b class="req">*</b></span><input v-model="form.name" placeholder="例如:星海纪元 · 第一集" /></label>
|
||||
<label class="fld"><span>题材</span><input v-model="form.genre" placeholder="科幻 / 悬疑 / 都市" /></label>
|
||||
<label class="fld"><span>目标总时长(秒)</span><input v-model.number="form.target_duration" type="number" min="1" :title="durationRule" /></label>
|
||||
<label class="fld"><span>默认转场</span><FSelect v-model="form.default_transition"><option v-for="o in store.meta?.options?.transition || []" :value="o.value">{{ o.label }}</option></FSelect></label>
|
||||
</div>
|
||||
<div class="frow">
|
||||
<label class="fld"><span>默认视频模型</span><FSelect v-model="videoRef" :title="`生成模式 ${videoCaps.modes.map((m) => opt('mode', m)).join(' / ') || '未声明'};后续可在项目设置里改`">
|
||||
<option v-for="row in videoModels" :key="row.id" :value="refOf(row)">
|
||||
{{ row.display_name || `${row.provider} · ${row.model}` }}{{ row.available ? '' : '(未就绪)' }}{{ isMock(row) ? '(演练通道)' : '' }}
|
||||
</option>
|
||||
</FSelect></label>
|
||||
<label class="fld"><span>画幅</span><FSelect v-model="form.aspect_ratio"><option v-for="o in store.meta?.options?.aspect_ratio || []" :value="o.value">{{ o.label }}</option></FSelect></label>
|
||||
<label class="fld"><span>分辨率</span><FSelect v-model="form.resolution"><option v-for="o in resOptions" :value="o.value">{{ o.label }}</option></FSelect></label>
|
||||
<label class="fld"><span>帧率</span><FSelect v-model.number="form.fps"><option v-for="f in fpsOptions" :value="f">{{ f }} fps</option></FSelect></label>
|
||||
<label class="fld"><span>全局负面提示词</span><input v-model="form.global_negative_prompt" placeholder="文字水印,画面抖动,肢体畸变" /></label>
|
||||
</div>
|
||||
<div class="frow">
|
||||
<label class="field"><span class="lbl">项目简介</span><textarea v-model="form.description" rows="2"></textarea></label>
|
||||
<label class="field"><span class="lbl">全局风格指南(拼接到每个镜头提示词)</span><textarea v-model="form.style_guide" rows="2" placeholder="赛博朋克国风,冷色调,电影质感"></textarea></label>
|
||||
</div>
|
||||
<div class="libpick">
|
||||
<div class="row libtogglebar">
|
||||
<button title="可选:把资源库里现成的人物定妆图、场景母图、角色声线直接带进新项目。引入的是母版当前版本的副本:人物会连带默认声线与定妆图,场景带母图,声线带音色样本;之后资源库里升级版本不会自动改写项目内的资产。" type="button" class="btn-add" @click="toggleLibrary">
|
||||
{{ libOpen ? '收起资源库' : (pickedCount ? `已选 ${pickedCount} 个资源` : '+ 从资源库引入人物 / 场景 / 声线') }}
|
||||
</button>
|
||||
<span v-if="pickedCount" class="tag ok">创建时自动引入 {{ pickedCount }} 个母版</span>
|
||||
</div>
|
||||
<div v-if="libOpen" class="libbox">
|
||||
<div class="lib-bar">
|
||||
<span v-for="t in LIB_TYPES" :key="t.value" class="chip libchip" :class="{ on: libType === t.value }"
|
||||
@click="pickType(t.value)">{{ t.label }}<em v-if="pickedByType[t.value]?.length"> {{ pickedByType[t.value].length }}</em></span>
|
||||
<label class="fld grow"><span>搜索</span><input v-model="libQuery" placeholder="名称 / 编号 / 标签" /></label>
|
||||
<button type="button" class="outline tiny" :disabled="libLoading" @click="loadLibrary(true)">刷新</button>
|
||||
</div>
|
||||
<p v-if="libError" class="error">{{ libError }}</p>
|
||||
<div v-else-if="libLoading && !libShown.length" class="muted libempty">正在读取资源库…</div>
|
||||
<div v-else-if="!libShown.length" class="muted libempty">
|
||||
资源库里还没有{{ LIB_TYPES.find((t) => t.value === libType)?.label }}母版。可以先建项目,之后到「资源库」页面引入。
|
||||
</div>
|
||||
<div v-else class="lib-grid">
|
||||
<button v-for="row in libShown" :key="row.owner_type + row.id" type="button" class="libcard"
|
||||
:class="{ on: !!picked[`${row.owner_type}:${row.id}`] }" @click="togglePick(row)">
|
||||
<span class="libthumb">
|
||||
<MediaThumb v-if="coverOf(row)" :item="fromAsset(coverOf(row))" size="xs" width="52px" :radius="6" />
|
||||
<b v-else class="libicon">{{ audioOfRow(row) ? '♪' : '◻' }}</b>
|
||||
</span>
|
||||
<span class="libmeta">
|
||||
<b>{{ row.name }}</b>
|
||||
<small class="muted">{{ subLabel(row) || row.type_label }}</small>
|
||||
<small class="muted">{{ (row.assets || []).length }} 个素材<template v-if="row.usage_count"> · 已用于 {{ row.usage_count }} 个项目</template></small>
|
||||
</span>
|
||||
<span class="libcheck">{{ picked[`${row.owner_type}:${row.id}`] ? '✓' : '' }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="pickedCount" class="libpicked">
|
||||
<small class="eyebrow">将引入</small>
|
||||
<span v-for="row in pickedRows" :key="'p' + row.owner_type + row.asset_id" class="chip on libchip">
|
||||
{{ row.type_label }}·{{ row.name }}<button class="chip-x" type="button" :title="`不再引入 ${row.name}`" aria-label="不再引入该资源" @click.stop="togglePick(row)">×</button>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chipbar capsline">
|
||||
<span class="chip">可用档位 {{ videoCaps.resolutions.join(' / ') || '未声明' }}</span>
|
||||
<span class="chip">帧率 {{ videoCaps.fps || '未声明' }}fps</span>
|
||||
<span class="chip">单镜 {{ videoCaps.minDuration || '?' }}–{{ videoCaps.maxDuration || '?' }} 秒</span>
|
||||
<span class="chip">参考图上限 {{ videoCaps.maxReferenceImages || '未声明' }}</span>
|
||||
</div>
|
||||
<p v-for="(w, i) in modelWarnings" :key="'w' + i" class="error">{{ w }}</p>
|
||||
<div class="actions">
|
||||
<button class="primary" type="submit">创建并进入项目</button>
|
||||
<button class="outline" type="button" @click="creating = false">取消</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div class="stats">
|
||||
<div class="stat"><small>项目总数</small><b>{{ totals.all }}</b></div>
|
||||
<div class="stat"><small>制作中</small><b>{{ totals.active }}</b></div>
|
||||
<div class="stat"><small>已交付</small><b>{{ totals.delivered }}</b></div>
|
||||
<div class="stat"><small>累计成本</small><b>{{ fmtMoney(totals.cost, totals.currency) }}</b></div>
|
||||
</div>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-head">
|
||||
<div><small class="eyebrow">PIPELINE</small><h2>项目列表</h2></div>
|
||||
<div class="ctlbar searchbar">
|
||||
<label class="fld grow"><span>搜索</span><input v-model="keyword" aria-label="搜索项目" placeholder="名称 / 简介 / 题材" /></label>
|
||||
<label class="fld narrow"><span>状态</span><FSelect v-model="statusFilter" aria-label="项目状态筛选">
|
||||
<option value="">全部状态</option>
|
||||
<option v-for="s in statuses" :value="s">{{ statusLabel(s) }}</option>
|
||||
</FSelect></label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="loading"><span class="spin"></span> 正在读取项目…</div>
|
||||
<div v-else-if="!filtered.length" class="empty">还没有项目。点击右上角「新建长视频项目」开始。</div>
|
||||
<div v-else class="tablebox dash-table">
|
||||
<table class="tbl">
|
||||
<thead>
|
||||
<tr><th>项目</th><th>状态</th><th>流程节点</th><th class="r">镜头</th><th class="r">进度</th><th class="r">时长</th><th class="r">成本</th><th class="r">操作</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="p in filtered" :key="p.id">
|
||||
<td class="wrap">
|
||||
<div class="proj-cell">
|
||||
<div class="proj-cover">
|
||||
<MediaThumb v-if="p.cover_url" :src="p.cover_url" size="xs" width="72px" :radius="6"
|
||||
:title="`${p.name} 首帧`" />
|
||||
<span v-else class="cover-none" :title="p.shot_count ? '已有镜头,但还没有生成任何画面' : '还没有导入分镜'">
|
||||
{{ p.shot_count ? '▷' : '+' }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="grow">
|
||||
<router-link class="link" :to="`/projects/${p.id}/overview`"><b>{{ p.name }}</b></router-link>
|
||||
<div class="muted">{{ p.aspect_ratio }} · {{ p.resolution }} · {{ p.fps }}fps<span v-if="p.genre"> · {{ p.genre }}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td><span :class="statusClass(p.status)">{{ statusLabel(p.status) }}</span></td>
|
||||
<td class="wrap">{{ stageNote(p) }}</td>
|
||||
<td class="r">{{ p.stats?.shots || 0 }}<span class="muted"> / 合格 {{ p.stats?.shots_approved || 0 }}</span></td>
|
||||
<td class="r" style="min-width:96px">
|
||||
<div class="bar"><i :style="{ width: Math.round((p.stats?.progress_ratio || 0) * 100) + '%' }"></i></div>
|
||||
<small class="muted">{{ pct(p.stats?.progress_ratio) }}</small>
|
||||
</td>
|
||||
<td class="r mono">{{ (p.stats?.planned_duration || 0).toFixed(0) }}s</td>
|
||||
<td class="r mono">{{ fmtMoney(p.stats?.cost?.total_cost) }}</td>
|
||||
<td class="r">
|
||||
<div class="row" style="justify-content:flex-end">
|
||||
<router-link class="link" :to="`/projects/${p.id}/overview`">进入 →</router-link>
|
||||
<button class="btn-del" title="删除这个项目" @click="removeProject(p)">删除</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div v-if="!loading && filtered.length" class="project-cards">
|
||||
<article v-for="p in filtered" :key="'card-' + p.id" class="project-card">
|
||||
<div class="card-top">
|
||||
<MediaThumb v-if="p.cover_url" :src="p.cover_url" size="xs" width="56px" :radius="6"
|
||||
:title="`${p.name} 首帧`" />
|
||||
<router-link class="link" :to="`/projects/${p.id}/overview`"><b>{{ p.name }}</b></router-link>
|
||||
<span :class="statusClass(p.status)">{{ statusLabel(p.status) }}</span>
|
||||
</div>
|
||||
<div class="muted">{{ p.aspect_ratio }} · {{ p.resolution }} · {{ p.fps }}fps<span v-if="p.genre"> · {{ p.genre }}</span></div>
|
||||
<div class="card-stage"><span>流程节点</span><b>{{ stageNote(p) }}</b></div>
|
||||
<div class="card-kpis">
|
||||
<span>镜头 <b>{{ p.stats?.shots || 0 }}</b> / 合格 {{ p.stats?.shots_approved || 0 }}</span>
|
||||
<span>时长 <b>{{ (p.stats?.planned_duration || 0).toFixed(0) }}s</b></span>
|
||||
<span>进度 <b>{{ pct(p.stats?.progress_ratio) }}</b></span>
|
||||
<span>成本 <b>{{ fmtMoney(p.stats?.cost?.total_cost) }}</b></span>
|
||||
</div>
|
||||
<div class="bar"><i :style="{ width: Math.round((p.stats?.progress_ratio || 0) * 100) + '%' }"></i></div>
|
||||
<div class="actions">
|
||||
<router-link class="outline tiny" :to="`/projects/${p.id}/overview`">进入项目 →</router-link>
|
||||
<button class="btn-del" title="删除这个项目" @click="removeProject(p)">删除</button>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="dash-side">
|
||||
<section class="panel">
|
||||
<div class="panel-head"><div><small class="eyebrow">STAGE FLOW</small><h2 title="平台按 12 个节点推进:创建项目 → 导入分镜 → 绑定资产 → 生成任务清单 → 检查素材 → 队列调度 → 调用模型 → 保存产物 → 质量检查 → 人工审核 → 时间线合成 → 导出成片。被驳回的镜头会回到「修改提示词 → 重新生成」。">流程节点</h2></div></div>
|
||||
<div class="divider"></div>
|
||||
<div class="small-label" style="margin-top:0">示例项目流程<span class="val">{{ filtered[0]?.name || '暂无项目' }}</span></div>
|
||||
<WorkflowBar v-if="filtered[0]?.workflow" :workflow="filtered[0].workflow" compact />
|
||||
<p v-else class="empty">创建项目后可在这里看到实时节点进度。</p>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-head"><div><small class="eyebrow">EVENTS</small><h2>全局动态</h2></div></div>
|
||||
<div class="event-filter">
|
||||
<span v-for="lv in EVENT_LEVELS" :key="lv.value" class="chip"
|
||||
:class="{ on: eventLevel === lv.value }" @click="eventLevel = lv.value">
|
||||
{{ lv.label }}<em v-if="lv.value && levelCounts[lv.value]"> {{ levelCounts[lv.value] }}</em>
|
||||
</span>
|
||||
<label class="fld grow"><span>搜索</span><input v-model="eventKeyword" class="event-search" aria-label="搜索事件" placeholder="事件内容 / 动作" /></label>
|
||||
</div>
|
||||
<div class="log">
|
||||
<div v-for="e in shownEvents" :key="e.id" class="logrow" :class="eventLevelKey(e.level)">
|
||||
<time :title="fmtTime(e.created_at)">{{ fmtAgo(e.created_at) }}</time>
|
||||
<span class="who mono" :title="e.action">{{ eventLabel(e.action) }}</span>
|
||||
<p>{{ e.message }}<span v-if="e.project_id" class="muted"> · 项目#{{ e.project_id }}</span></p>
|
||||
</div>
|
||||
<div v-if="!events.length" class="muted">暂无事件</div>
|
||||
<div v-else-if="!shownEvents.length" class="muted">当前筛选条件下没有事件。
|
||||
<button class="outline tiny" @click="eventLevel = ''; eventKeyword = ''">清除筛选</button></div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 新建项目时的资源库选择器:卡片式多选,缩略图 + 名称 + 摘要,避免「只有一个下拉框却看不见素材」 */
|
||||
.libpick { margin: 2px 0 12px; }
|
||||
.libtogglebar { gap: 10px; align-items: center; }
|
||||
.libbox { margin-top: 10px; padding: 12px; border: 1px solid var(--c-bg-emphasis); border-radius: 10px;
|
||||
background: var(--c-bg-panel); }
|
||||
.lib-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-bottom: 10px; }
|
||||
.lib-bar .fld.grow { max-width: 260px; }
|
||||
.libchip em { color: var(--c-accent); font-style: normal; }
|
||||
.lib-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(212px, 1fr)); gap: 8px;
|
||||
max-height: 268px; overflow: auto; padding-right: 2px; }
|
||||
.libcard { display: flex; align-items: center; gap: 9px; padding: 8px; text-align: left; cursor: pointer;
|
||||
border: 1px solid var(--c-line); border-radius: 9px; background: var(--c-bg-card); color: inherit; }
|
||||
.libcard:hover { border-color: var(--c-line-strong); }
|
||||
.libcard.on { border-color: var(--c-accent); box-shadow: 0 0 0 1px var(--c-accent) inset; }
|
||||
.libthumb { flex: 0 0 auto; width: 52px; height: 40px; display: grid; place-items: center; overflow: hidden;
|
||||
border-radius: 6px; background: var(--c-bg-emphasis); }
|
||||
.libicon { color: var(--c-text-muted); font-size: 17px; }
|
||||
.libmeta { min-width: 0; display: grid; gap: 1px; flex: 1 1 auto; }
|
||||
.libmeta b { font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.libmeta small { font-size: 10px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.libcheck { flex: 0 0 auto; width: 18px; color: var(--c-accent); font-weight: 700; }
|
||||
.libpicked { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-top: 10px; }
|
||||
.libpicked .eyebrow { margin-right: 2px; }
|
||||
.libempty { padding: 14px 2px; font-size: 11px; }
|
||||
.dash-side { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; margin-top: 16px; align-items: start; }
|
||||
.dash-table .tbl { min-width: 940px; }
|
||||
@media (max-width:1080px) { .dash-side { grid-template-columns: minmax(0, 1fr); } }
|
||||
.dash-table td { white-space: nowrap; }
|
||||
.dash-table td.wrap { white-space: normal; }
|
||||
.dash-table .bar { margin-bottom: 3px; }
|
||||
.proj-cell { display: flex; align-items: center; gap: 10px; min-width: 0; }
|
||||
.proj-cover { flex: 0 0 auto; width: 72px; }
|
||||
.cover-none { display: grid; place-items: center; width: 72px; height: 41px;
|
||||
border: 1px dashed var(--c-line-strong); border-radius: 6px;
|
||||
color: var(--c-text-muted); background: var(--c-bg-panel); font-size: 14px; }
|
||||
/* 布局(一行 / 等高 / 间距)来自 style.css 的 .ctlbar 体系,这里只留皮肤 */
|
||||
.event-filter .chip em { color: var(--c-accent); font-style: normal; }
|
||||
.project-cards { display: none; }
|
||||
@media (max-width: 560px) {
|
||||
.dash-table { display: none; }
|
||||
.project-cards { display: grid; gap: 9px; }
|
||||
.project-card { padding: 12px; border: 1px solid var(--c-bg-emphasis); border-radius: 10px; background: var(--c-bg-card); }
|
||||
.card-top { display: flex; align-items: flex-start; justify-content: space-between; gap: 8px; margin-bottom: 5px; }
|
||||
.card-top .link { flex: 1 1 auto; }
|
||||
.card-top .link { color: var(--c-text); font-size: 12px; }
|
||||
.card-stage { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; margin: 10px 0 8px; }
|
||||
.card-stage span { color: var(--c-text-muted); font-size: 10px; }
|
||||
.card-stage b { color: var(--c-text-2); font-size: 11px; text-align: right; }
|
||||
.card-kpis { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 5px 12px; margin-bottom: 8px; color: var(--c-text-muted); font-size: 10px; }
|
||||
.card-kpis b { color: var(--c-text-2); }
|
||||
.project-card .actions { margin-top: 10px; }
|
||||
.project-card .actions .outline { text-decoration: none; }
|
||||
}
|
||||
</style>
|
||||
|
|
@ -1,113 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import SecretInput from '../components/SecretInput.vue'
|
||||
import { auth, login } from '../auth'
|
||||
import { setTheme, theme } from '../theme'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const form = reactive({ username: '', password: '' })
|
||||
const busy = ref(false)
|
||||
const error = ref('')
|
||||
const justLoggedOut = computed(() => route.query.loggedOut === '1')
|
||||
|
||||
const isLight = computed(() => theme.applied === 'light')
|
||||
|
||||
onMounted(() => {
|
||||
// 首次部署时库里只有一个种子账号,后端会把用户名带下来,省得用户猜
|
||||
if (!form.username && auth.hint) form.username = auth.hint
|
||||
const field = document.querySelector('#login-user') as HTMLInputElement | null
|
||||
if (field) field.focus()
|
||||
})
|
||||
|
||||
async function submit() {
|
||||
if (busy.value) return
|
||||
if (!form.username.trim() || !form.password) {
|
||||
error.value = '请输入用户名和密码'
|
||||
return
|
||||
}
|
||||
busy.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const data = await login(form.username, form.password)
|
||||
const next = String(route.query.next || '').trim()
|
||||
if (data?.user?.must_change_password) {
|
||||
await router.replace({ path: '/account', query: { must: '1' } })
|
||||
return
|
||||
}
|
||||
await router.replace(next && next.startsWith('/') && !next.startsWith('//') ? next : '/')
|
||||
} catch (exc: any) {
|
||||
error.value = exc?.message || String(exc)
|
||||
form.password = ''
|
||||
;(document.querySelector('#login-pass') as HTMLInputElement | null)?.focus()
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="login-stage">
|
||||
<button class="login-theme" @click="setTheme(isLight ? 'dark' : 'light')"
|
||||
:aria-label="'切换明暗主题,当前为' + (isLight ? '浅色' : '深色')">
|
||||
{{ isLight ? '☀ 浅色' : '☾ 深色' }}
|
||||
</button>
|
||||
|
||||
<form class="login-card" @submit.prevent="submit">
|
||||
<div class="brand">
|
||||
<b>N</b>
|
||||
<span>长视频编导平台<small>NEX ANIMATION STUDIO</small></span>
|
||||
</div>
|
||||
<h1 title="账号决定你能做什么:管理员管模型与账号,制作可以跑生产,观摩只读。">登录以继续</h1>
|
||||
|
||||
<p v-if="justLoggedOut" class="tip">已退出登录。</p>
|
||||
<p v-if="auth.offline" class="bad">后端连接不上:{{ auth.error || '请确认服务已启动' }}</p>
|
||||
<p v-if="error" class="bad">{{ error }}</p>
|
||||
|
||||
<label class="field"><span class="lbl">用户名</span>
|
||||
<input id="login-user" v-model="form.username" autocomplete="username"
|
||||
:placeholder="'如 ' + (auth.user?.username || 'admin')" spellcheck="false" />
|
||||
</label>
|
||||
<label class="field"><span class="lbl">密码</span>
|
||||
<SecretInput id="login-pass" v-model="form.password" autocomplete="current-password"
|
||||
placeholder="输入密码后点右侧图标可查看" @keyup.enter="submit" />
|
||||
</label>
|
||||
|
||||
<button class="primary submit" type="submit" :disabled="busy">
|
||||
{{ busy ? '正在验证…' : '登录' }}
|
||||
</button>
|
||||
<p class="foot">忘记密码请联系平台管理员在「用户管理」里重置。</p>
|
||||
</form>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.login-stage {
|
||||
min-height: 100vh; display: grid; place-items: center; padding: 24px;
|
||||
background:
|
||||
radial-gradient(900px 420px at 50% -8%, var(--c-accent-tint2), transparent 70%),
|
||||
var(--c-bg-app)
|
||||
}
|
||||
.login-theme {
|
||||
position: fixed; top: 18px; right: 20px; display: inline-flex; align-items: center;
|
||||
height: var(--ctl-h-md); padding: 0 11px; font-size: 11px;
|
||||
border: 1px solid var(--c-line); border-radius: 8px;
|
||||
background: var(--c-bg-sunken); color: var(--c-text-2)
|
||||
}
|
||||
.login-card {
|
||||
width: min(392px, 100%); background: var(--c-bg-panel); border: 1px solid var(--c-line);
|
||||
border-radius: 14px; padding: 26px 24px 22px; box-shadow: 0 24px 60px var(--c-shade-3)
|
||||
}
|
||||
.brand { display: flex; align-items: center; gap: 10px; padding: 0 0 18px; font-size: 11px;
|
||||
letter-spacing: 1px; font-weight: bold; color: var(--c-text-2) }
|
||||
.brand b { display: grid; place-items: center; width: 37px; height: 37px;
|
||||
background: var(--c-accent-fill); color: var(--c-on-accent); border-radius: 11px; font-size: 22px }
|
||||
.brand small { display: block; color: var(--c-text-faint); font-size: 10px; margin-top: 5px; font-weight: normal }
|
||||
h1 { font-size: 21px; margin: 0 0 18px }
|
||||
.submit { width: 100%; margin-top: 16px }
|
||||
.tip, .bad { font-size: 11px; border-radius: 8px; padding: 9px 10px; margin: 0 0 4px }
|
||||
.tip { background: var(--c-info-tint); color: var(--c-info); border: 1px solid var(--c-line) }
|
||||
.bad { background: var(--c-danger-tint); color: var(--c-danger); border: 1px solid var(--c-danger-line) }
|
||||
.foot { font-size: 10.5px; color: var(--c-text-faint); margin: 14px 0 0; text-align: center }
|
||||
</style>
|
||||
|
|
@ -1,866 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
|
||||
import * as api from '../api'
|
||||
import { active } from '../store'
|
||||
import AutoRefresh from '../components/AutoRefresh.vue'
|
||||
import { fmtAgo, fmtSeconds } from '../format'
|
||||
import SecretInput from '../components/SecretInput.vue'
|
||||
import EyeIcon from '../components/EyeIcon.vue'
|
||||
import FSelect from '../components/FSelect.vue'
|
||||
import { auth } from '../auth'
|
||||
|
||||
const error = ref('')
|
||||
const notice = ref('')
|
||||
const busy = ref('')
|
||||
const providers = ref<any[]>([])
|
||||
const mediaTypes = ref<any[]>([])
|
||||
const adapters = ref<Record<string, string[]>>({})
|
||||
const projectId = ref<number | null>(null)
|
||||
const selectedType = ref('llm')
|
||||
const showForm = ref(false)
|
||||
const showAdvanced = ref(false)
|
||||
/** 编辑中的模型是否已保存密钥:决定「眼睛」图标要不要向后端取明文 */
|
||||
const editingHasKey = ref(false)
|
||||
/** 卡片上已展开明文的密钥(id → 明文)。列表只回掩码,点图标才按 id 取一次明文。 */
|
||||
const revealedKeys = reactive<Record<number, string>>({})
|
||||
const keyRevealing = ref<number | null>(null)
|
||||
/** 取明文是管理员接口(后端还会留审计痕),观摩/制作账号点了也拿不到,图标直接标灰 */
|
||||
const canRevealKey = computed(() => !auth.enabled || auth.user?.role === 'admin')
|
||||
const editingId = ref<number | null>(null)
|
||||
const probing = ref<number | null>(null)
|
||||
const probe = ref<any>(null)
|
||||
const keyword = ref('')
|
||||
|
||||
/* 分类以 /api/providers 的 media_types 为唯一来源;本地表只做首屏兜底。
|
||||
旧的「文本兼容」分类已经并入大模型,不要再在前端凭空造出来。 */
|
||||
const FALLBACK_TYPES = ['llm', 'video', 'image', 'tts']
|
||||
const typeMeta: Record<string, any> = {
|
||||
llm: { label: '大模型', icon: '✦', color: 'var(--c-accent)', hint: '推理 / 提示词补全(图像生成请使用独立图像模型)' },
|
||||
video: { label: '视频模型', icon: '▷', color: 'var(--c-sky)', hint: '文生视频 / 图生视频 / 首尾帧' },
|
||||
image: { label: '图像模型', icon: '▧', color: 'var(--c-warn)', hint: '定妆图 / 场景图 / 关键帧' },
|
||||
tts: { label: '声音模型', icon: '◉', color: 'var(--c-pink)', hint: 'IndexTTS2 / 配音 / 音色克隆' },
|
||||
}
|
||||
const types = computed<string[]>(() => mediaTypes.value.length
|
||||
? mediaTypes.value.map((row: any) => row.value)
|
||||
: FALLBACK_TYPES)
|
||||
|
||||
const tokenOptions = [4096, 8192, 16384, 32768]
|
||||
const qwenSigmas = '1.0, 0.978453, 0.95418, 0.926626, 0.89508, 0.845148, 0.704534, 0.414568, 0'
|
||||
|
||||
const form = reactive<any>({})
|
||||
const loadedConfig = ref<Record<string, any>>({})
|
||||
const loadedParams = ref<Record<string, any>>({})
|
||||
|
||||
function cloneJson<T>(value: T): T {
|
||||
return JSON.parse(JSON.stringify(value ?? {}))
|
||||
}
|
||||
|
||||
const currentRows = computed(() => providers.value.filter((row) => {
|
||||
if (row.media_type !== selectedType.value) return false
|
||||
const q = keyword.value.trim().toLowerCase()
|
||||
return !q || `${row.display_name} ${row.provider} ${row.model} ${row.model_code} ${row.adapter}`.toLowerCase().includes(q)
|
||||
}))
|
||||
const selectedMeta = computed(() => mediaTypes.value.find((m) => m.value === selectedType.value) || typeMeta[selectedType.value])
|
||||
const enabledCount = computed(() => providers.value.filter((row) => row.enabled).length)
|
||||
const availableCount = computed(() => providers.value.filter((row) => row.enabled && row.available).length)
|
||||
const faultInjected = computed(() => providers.value.filter((row) => Number(row.fault_injection || 0) > 0))
|
||||
const dispatchLink = computed(() => projectId.value ? `/projects/${projectId.value}/dispatch` : '')
|
||||
const comfyBase = computed(() => providers.value.find((row) => row.adapter?.startsWith('comfyui') && row.config?.base_url)?.config.base_url || '')
|
||||
|
||||
function railMeta(type: string) {
|
||||
const local = typeMeta[type] || {}
|
||||
const remote = mediaTypes.value.find((row: any) => row.value === type) || {}
|
||||
return {
|
||||
label: remote.label || local.label || type,
|
||||
icon: remote.icon || local.icon || '◇',
|
||||
color: local.color || 'var(--c-text-3)',
|
||||
hint: local.hint || remote.description || '',
|
||||
}
|
||||
}
|
||||
function countOf(type: string) { return providers.value.filter((row) => row.media_type === type).length }
|
||||
|
||||
/* MC-2:模型卡显示真实调用量,数据来自生成台账(全平台累计,含失败重试) */
|
||||
function usageOf(row: any) {
|
||||
const u = row?.usage || {}
|
||||
return {
|
||||
calls: Number(u.calls || 0),
|
||||
seconds: Number(u.seconds || 0),
|
||||
assets: Number(u.assets || 0),
|
||||
cost: Number(u.cost || 0),
|
||||
last: u.last_used || '',
|
||||
}
|
||||
}
|
||||
function usageParts(row: any) {
|
||||
const u = usageOf(row)
|
||||
const parts: string[] = []
|
||||
parts.push(u.calls ? `调用 ${u.calls} 次` : '尚无调用记录')
|
||||
if (u.assets) parts.push(`产出 ${u.assets} 个素材`)
|
||||
if (u.seconds > 0.01) parts.push(`累计耗时 ${fmtSeconds(u.seconds)}`)
|
||||
if (u.cost > 0) parts.push(`成本 ${u.cost.toFixed(2)}`)
|
||||
if (u.last) parts.push(`最近 ${fmtAgo(u.last)}`)
|
||||
return parts
|
||||
}
|
||||
const usageTotal = computed(() => {
|
||||
const sum = providers.value.reduce((acc, row) => {
|
||||
const u = usageOf(row)
|
||||
acc.calls += u.calls
|
||||
acc.assets += u.assets
|
||||
acc.seconds += u.seconds
|
||||
return acc
|
||||
}, { calls: 0, assets: 0, seconds: 0 })
|
||||
return sum
|
||||
})
|
||||
function defaultOf(type: string) { return providers.value.find((row) => row.media_type === type && row.is_default) }
|
||||
|
||||
function blank(type = selectedType.value) {
|
||||
return {
|
||||
provider: type === 'llm' ? 'dashscope' : 'comfyui',
|
||||
model: '', display_name: '', media_type: type,
|
||||
adapter: type === 'llm' ? 'http_llm' : type === 'tts' ? 'comfyui_tts' : type === 'image' ? 'comfyui_image' : 'comfyui',
|
||||
enabled: true, is_default: false, model_code: '', timeout_seconds: 120,
|
||||
api_key: '', clear_api_key: false,
|
||||
max_concurrency: 1, requests_per_minute: 30, burst: 1,
|
||||
modes: type === 'video' ? 't2v, i2v, fl' : type === 'llm' ? 'chat, prompt' : type === 'image' ? 't2i' : 'voice',
|
||||
resolutions: type === 'video' ? '480p, 720p' : type === 'image' ? '1024p, 2k' : '',
|
||||
aspect_ratios: type === 'video' || type === 'image' ? '16:9, 9:16, 1:1, 4:3' : '',
|
||||
min_duration: type === 'video' ? 5 : 0, max_duration: type === 'video' ? 15 : 0,
|
||||
max_reference_images: type === 'llm' ? 0 : type === 'tts' ? 1 : type === 'video' ? 6 : 1,
|
||||
price_per_second: 0, price_per_1k_chars: 0, currency: 'CNY',
|
||||
base_url: type === 'llm' ? 'https://coding.dashscope.aliyuncs.com/v1' : comfyBase.value,
|
||||
endpoint: '', temperature: 0.7, top_p: 0.9, max_tokens: 16384,
|
||||
unet: type === 'image' ? 'qwen-image-2.1-turbo-Q4_K_M.gguf' : 'MiniMax-H3-REF2VA-Q4_K_M.gguf',
|
||||
clip: type === 'image' ? 'qwen3vl_8b_int8_convrot.safetensors' : 'qwen3vl-32B-MiniMax-H3-Q4_K_M.gguf',
|
||||
vae: type === 'image' ? 'qwen_image_2.1_vae_bf16.safetensors' : 'minimax_h3_video_vae_fp16.safetensors',
|
||||
audio_vae: 'minimax_h3_audio_vae_fp32.safetensors',
|
||||
clip_type: type === 'image' ? 'qwen_image' : 'minimax',
|
||||
workflow: type === 'image' ? 'qwen_image_2_1_turbo' : type === 'tts' ? 'indextts2' : 'minimax_h3',
|
||||
steps: type === 'image' ? 8 : 20, cfg: 1, sampler: type === 'image' ? 'euler' : 'res_multistep',
|
||||
sigmas: type === 'image' ? qwenSigmas : '', fps: 24,
|
||||
tts_model: 'IndexTTS-2', download_from: 'modelscope',
|
||||
reference_audio: 'nex_tts_reference.wav',
|
||||
notes: '',
|
||||
}
|
||||
}
|
||||
|
||||
function resetForm(type = selectedType.value) {
|
||||
editingId.value = null
|
||||
Object.assign(form, blank(type))
|
||||
loadedConfig.value = {}
|
||||
loadedParams.value = {}
|
||||
form.extra_config = '{}'
|
||||
form.extra_params = '{}'
|
||||
showAdvanced.value = false
|
||||
editingHasKey.value = false
|
||||
}
|
||||
|
||||
async function load() {
|
||||
busy.value = '读取模型注册表'
|
||||
try {
|
||||
const [data, projects] = await Promise.all([
|
||||
api.get('/api/providers'),
|
||||
api.get('/api/projects', { brief: 1 }).catch(() => ({ projects: [] })),
|
||||
])
|
||||
providers.value = data.providers || []
|
||||
// 重新拉列表 = 配置可能已经变了,卡片上展开的明文一并收回,避免显示过期的密钥
|
||||
for (const id of Object.keys(revealedKeys)) delete revealedKeys[Number(id)]
|
||||
mediaTypes.value = data.media_types || []
|
||||
adapters.value = data.adapters || {}
|
||||
projectId.value = active.project?.id || projects.projects?.[0]?.id || null
|
||||
error.value = ''
|
||||
} catch (exc: any) {
|
||||
error.value = exc.message
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
function addModel() {
|
||||
resetForm()
|
||||
showForm.value = true
|
||||
notice.value = ''
|
||||
}
|
||||
|
||||
function editModel(row: any) {
|
||||
resetForm(row.media_type)
|
||||
editingId.value = row.id
|
||||
editingHasKey.value = !!row.has_api_key
|
||||
const cfg = row.config || {}
|
||||
const params = row.default_params || {}
|
||||
// row/config 来自 Vue 的响应式代理,structuredClone 在这里会抛 DataCloneError。
|
||||
loadedConfig.value = cloneJson(cfg)
|
||||
loadedParams.value = cloneJson(params)
|
||||
const models = cfg.models || {}
|
||||
if (row.media_type === 'llm') delete loadedConfig.value.image
|
||||
Object.assign(form, {
|
||||
provider: row.provider || '', model: row.model || '', display_name: row.display_name || '',
|
||||
media_type: row.media_type, adapter: row.adapter, enabled: row.enabled, is_default: row.is_default,
|
||||
model_code: row.model_code || '', timeout_seconds: row.timeout_seconds || 120,
|
||||
api_key: '', clear_api_key: false,
|
||||
max_concurrency: row.max_concurrency || 1, requests_per_minute: row.requests_per_minute || 1,
|
||||
burst: row.burst || 1, modes: (row.modes || []).join(', '),
|
||||
resolutions: (row.resolutions || []).join(', '), aspect_ratios: (row.aspect_ratios || []).join(', '),
|
||||
min_duration: row.min_duration || 0, max_duration: row.max_duration || 0,
|
||||
max_reference_images: row.max_reference_images || 0,
|
||||
price_per_second: row.price_per_second || 0, price_per_1k_chars: row.price_per_1k_chars || 0,
|
||||
currency: row.currency || 'CNY',
|
||||
base_url: cfg.base_url || '', endpoint: cfg.url || '',
|
||||
temperature: params.temperature ?? cfg.temperature ?? 0.7,
|
||||
top_p: params.top_p ?? cfg.top_p ?? 0.9,
|
||||
max_tokens: params.max_tokens ?? cfg.max_tokens ?? 16384,
|
||||
unet: models.unet || '', clip: models.clip || '', vae: models.video_vae || models.vae || '',
|
||||
audio_vae: models.audio_vae || '', clip_type: models.clip_type || cfg.clip_type || 'minimax',
|
||||
workflow: cfg.workflow || form.workflow, steps: cfg.steps || form.steps,
|
||||
cfg: cfg.cfg ?? form.cfg, sampler: cfg.sampler || form.sampler, sigmas: cfg.sigmas || form.sigmas,
|
||||
fps: cfg.fps || 24, tts_model: cfg.model || (row.media_type === 'tts' ? row.model : form.tts_model),
|
||||
download_from: cfg.download_from || 'modelscope', reference_audio: cfg.reference_audio || 'nex_tts_reference.wav',
|
||||
notes: row.notes || '',
|
||||
})
|
||||
form.extra_config = JSON.stringify(loadedConfig.value, null, 2)
|
||||
form.extra_params = JSON.stringify(loadedParams.value, null, 2)
|
||||
showForm.value = true
|
||||
probe.value = null
|
||||
}
|
||||
|
||||
function onTypeChange() {
|
||||
const available = adapters.value[form.media_type] || []
|
||||
if (!available.includes(form.adapter)) form.adapter = available[0] || ''
|
||||
}
|
||||
|
||||
function list(value: string) {
|
||||
return String(value || '').split(/[,,\s]+/).map((item) => item.trim()).filter(Boolean)
|
||||
}
|
||||
|
||||
function parsedObject(value: string, label: string) {
|
||||
const parsed = JSON.parse(value || '{}')
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
throw new Error(`${label} 必须是 JSON 对象`)
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
function toggleAdvanced() {
|
||||
showAdvanced.value = !showAdvanced.value
|
||||
if (showAdvanced.value && !form.extra_config) {
|
||||
form.extra_config = JSON.stringify(loadedConfig.value, null, 2)
|
||||
}
|
||||
if (showAdvanced.value && !form.extra_params) {
|
||||
form.extra_params = JSON.stringify(loadedParams.value, null, 2)
|
||||
}
|
||||
}
|
||||
|
||||
function buildConfig() {
|
||||
const config: any = cloneJson(loadedConfig.value || {})
|
||||
const base = String(form.base_url || '').trim().replace(/\/$/, '')
|
||||
if (base) config.base_url = base
|
||||
else delete config.base_url
|
||||
if (form.endpoint) config.url = String(form.endpoint).trim()
|
||||
else delete config.url
|
||||
|
||||
if (form.media_type === 'llm') {
|
||||
config.model = form.model
|
||||
for (const key of ['image', 'temperature', 'top_p', 'max_tokens']) delete config[key]
|
||||
} else if (form.media_type === 'video') {
|
||||
config.workflow = form.workflow
|
||||
config.models = {
|
||||
...(config.models || {}),
|
||||
unet: form.unet, clip: form.clip, clip_type: form.clip_type,
|
||||
video_vae: form.vae, audio_vae: form.audio_vae,
|
||||
}
|
||||
config.steps = Number(form.steps)
|
||||
config.sampler = form.sampler
|
||||
config.fps = Number(form.fps)
|
||||
} else if (form.media_type === 'image') {
|
||||
config.workflow = form.workflow
|
||||
config.models = { unet: form.unet, clip: form.clip, vae: form.vae }
|
||||
config.steps = Number(form.steps)
|
||||
config.cfg = Number(form.cfg)
|
||||
config.sampler = form.sampler
|
||||
config.sigmas = form.sigmas
|
||||
} else if (form.media_type === 'tts') {
|
||||
config.workflow = form.workflow
|
||||
config.model = form.tts_model
|
||||
config.download_from = form.download_from
|
||||
config.reference_audio = form.reference_audio
|
||||
}
|
||||
if (String(form.adapter).startsWith('comfyui')) config.resource_group = config.resource_group || 'comfyui:9200'
|
||||
return config
|
||||
}
|
||||
|
||||
function buildDefaultParams() {
|
||||
const params: any = cloneJson(loadedParams.value || {})
|
||||
if (form.media_type === 'llm') {
|
||||
params.temperature = Number(form.temperature)
|
||||
params.top_p = Number(form.top_p)
|
||||
params.max_tokens = Number(form.max_tokens)
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!form.provider.trim() || !form.model.trim()) {
|
||||
error.value = '模型标识与供应商标识不能为空'
|
||||
return
|
||||
}
|
||||
if (!form.display_name.trim()) form.display_name = form.model
|
||||
if (String(form.adapter).startsWith('http') && !form.base_url.trim()) {
|
||||
error.value = 'HTTP 接口需要填写 Base URL'
|
||||
return
|
||||
}
|
||||
let config: any
|
||||
let params: any
|
||||
try {
|
||||
if (showAdvanced) {
|
||||
Object.assign(loadedConfig.value, parsedObject(form.extra_config, 'config JSON'))
|
||||
Object.assign(loadedParams.value, parsedObject(form.extra_params, 'default_params JSON'))
|
||||
} else if (editingId.value) {
|
||||
// config 是整份回传的:表单打开后若配置被脚本/他人改过(例如按硬件调优 megapixels),
|
||||
// 直接保存会把打开那一刻的旧快照写回去,优化被静默打回。未展开高级 JSON 时
|
||||
// 用户只改了表单里的字段,因此以服务端当前值为底,避免旧快照覆盖新配置。
|
||||
await load()
|
||||
const fresh: any = providers.value.find((item: any) => item.id === editingId.value)
|
||||
if (fresh) {
|
||||
loadedConfig.value = { ...(fresh.config || {}) }
|
||||
loadedParams.value = { ...(fresh.default_params || {}) }
|
||||
}
|
||||
}
|
||||
config = buildConfig()
|
||||
params = buildDefaultParams()
|
||||
} catch (exc: any) {
|
||||
error.value = `高级 JSON 格式错误:${exc.message}`
|
||||
return
|
||||
}
|
||||
const body: any = {
|
||||
provider: form.provider.trim(), model: form.model.trim(), display_name: form.display_name.trim(),
|
||||
media_type: form.media_type, adapter: form.adapter, enabled: form.enabled,
|
||||
is_default: form.is_default, model_code: form.model_code.trim(),
|
||||
timeout_seconds: Number(form.timeout_seconds) || 120,
|
||||
max_concurrency: Number(form.max_concurrency) || 1,
|
||||
requests_per_minute: Number(form.requests_per_minute) || 1,
|
||||
burst: Number(form.burst) || 1, modes: list(form.modes), resolutions: list(form.resolutions),
|
||||
aspect_ratios: list(form.aspect_ratios), min_duration: Number(form.min_duration),
|
||||
max_duration: Number(form.max_duration), max_reference_images: Number(form.max_reference_images),
|
||||
price_per_second: Number(form.price_per_second), price_per_1k_chars: Number(form.price_per_1k_chars),
|
||||
currency: form.currency, default_params: params, config, notes: form.notes,
|
||||
}
|
||||
if (form.api_key.trim()) body.api_key = form.api_key.trim()
|
||||
if (form.clear_api_key) body.clear_api_key = true
|
||||
busy.value = editingId.value ? '保存模型配置' : '登记模型'
|
||||
error.value = ''
|
||||
try {
|
||||
if (editingId.value) await api.patch(`/api/providers/${editingId.value}`, body)
|
||||
else await api.post('/api/providers', body)
|
||||
notice.value = `${body.display_name} 已保存`
|
||||
showForm.value = false
|
||||
await load()
|
||||
} catch (exc: any) {
|
||||
error.value = exc.message
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function patch(row: any, body: any, label: string) {
|
||||
busy.value = label
|
||||
error.value = ''
|
||||
try {
|
||||
await api.patch(`/api/providers/${row.id}`, body)
|
||||
await load()
|
||||
} catch (exc: any) {
|
||||
error.value = exc.message
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(row: any) {
|
||||
if (!confirm(`确认删除模型「${row.display_name || row.model}」?`)) return
|
||||
busy.value = '删除模型'
|
||||
try {
|
||||
await api.del(`/api/providers/${row.id}`)
|
||||
notice.value = '模型已删除'
|
||||
await load()
|
||||
} catch (exc: any) {
|
||||
error.value = exc.message
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function runProbe(row: any) {
|
||||
probing.value = row.id
|
||||
probe.value = null
|
||||
error.value = ''
|
||||
try {
|
||||
probe.value = { model: row, ...(await api.get(`/api/providers/${row.id}/probe`)) }
|
||||
} catch (exc: any) {
|
||||
error.value = exc.message
|
||||
} finally {
|
||||
probing.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function modelFiles(row: any): string[] {
|
||||
const models = row.config?.models || {}
|
||||
return Object.values(models).filter(
|
||||
(value: any): value is string => typeof value === 'string' && /\.(gguf|safetensors|pt|pth)$/i.test(value))
|
||||
}
|
||||
|
||||
function keyLabel(row: any) {
|
||||
if (row.media_type === 'llm') return row.has_api_key ? row.api_key_masked : '未配置 API Key'
|
||||
if (row.adapter?.startsWith('comfyui')) return row.config?.base_url || '未配置 ComfyUI'
|
||||
return row.config?.base_url || row.config?.url || row.adapter
|
||||
}
|
||||
|
||||
/** 卡片上这一行现在显示的内容:已点开的显示真实密钥,否则显示掩码 */
|
||||
function keyValue(row: any) {
|
||||
return revealedKeys[row.id] || keyLabel(row)
|
||||
}
|
||||
|
||||
function keyEyeLabel(row: any) {
|
||||
if (revealedKeys[row.id]) return '隐藏密钥'
|
||||
if (!canRevealKey.value) return '密钥明文仅管理员可查看'
|
||||
return '显示密钥:读取已保存的明文'
|
||||
}
|
||||
|
||||
async function toggleKey(row: any) {
|
||||
if (revealedKeys[row.id]) {
|
||||
delete revealedKeys[row.id]
|
||||
return
|
||||
}
|
||||
if (!canRevealKey.value) {
|
||||
error.value = '密钥明文只有管理员能查看,可在「模型身份与调度」里改写'
|
||||
return
|
||||
}
|
||||
keyRevealing.value = row.id
|
||||
try {
|
||||
const data: any = await api.get(`/api/providers/${row.id}/api-key`)
|
||||
const plain = String(data?.api_key || '')
|
||||
if (plain) revealedKeys[row.id] = plain
|
||||
else error.value = `「${row.display_name || row.model}」没有保存密钥`
|
||||
} catch (exc: any) {
|
||||
error.value = exc?.message || '读取密钥明文失败'
|
||||
} finally {
|
||||
keyRevealing.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function closeForm() {
|
||||
showForm.value = false
|
||||
probe.value = null
|
||||
}
|
||||
|
||||
function onKey(ev: KeyboardEvent) {
|
||||
if (ev.key === 'Escape' && showForm.value) {
|
||||
const target = ev.target as HTMLElement
|
||||
if (!['INPUT', 'TEXTAREA', 'SELECT'].includes(target?.tagName || '')) closeForm()
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => { resetForm(selectedType.value); load(); window.addEventListener('keydown', onKey) })
|
||||
onBeforeUnmount(() => window.removeEventListener('keydown', onKey))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="model-center">
|
||||
<header class="hero">
|
||||
<div>
|
||||
<small class="eyebrow">MODEL CONTROL PLANE · 9200 LOCAL / API HYBRID</small>
|
||||
<h1 title="本地 H3、Qwen-Image 与 IndexTTS2 共用一张 GPU;大模型通过 OpenAI 兼容接口接入。配置按能力拆分,密钥只加密保存并以掩码回显。">模型控制台</h1>
|
||||
</div>
|
||||
<div class="row">
|
||||
<router-link v-if="dispatchLink" class="outline model-link" :to="dispatchLink">任务调度 →</router-link>
|
||||
<button class="primary" @click="addModel">+ 添加{{ railMeta(selectedType).label }}</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<p v-if="error" class="error banner">{{ error }}</p>
|
||||
<p v-if="notice" class="notice">{{ notice }}</p>
|
||||
|
||||
<div class="summary">
|
||||
<div><span>全库模型配置</span><b>{{ providers.length }}</b><small>{{ types.length }} 类能力 · 所有项目共用,与当前项目无关</small></div>
|
||||
<div><span>已启用</span><b>{{ enabledCount }}<i>/{{ providers.length }}</i></b><small>只有启用项会被工作流与调度选用</small></div>
|
||||
<div :class="{ warn: availableCount < enabledCount }"><span>启用且可达</span><b>{{ availableCount }}<i>/{{ enabledCount }}</i></b><small>{{ availableCount < enabledCount ? `另有 ${enabledCount - availableCount} 个启用模型探测失败,见卡片状态` : '全部启用模型均通过连接探测' }}</small></div>
|
||||
<div class="accent"><span>当前默认 · {{ railMeta(selectedType).label }}</span><b>{{ defaultOf(selectedType)?.display_name || '未设置' }}</b><small>台账累计 {{ usageTotal.calls }} 次调用 · {{ usageTotal.assets }} 个素材 · {{ fmtSeconds(usageTotal.seconds) }}</small></div>
|
||||
</div>
|
||||
|
||||
<p v-if="faultInjected.length" class="notice">
|
||||
⚠ 故障注入未复位:<b>{{ faultInjected.map((r) => `${r.provider}/${r.model} ${(Number(r.fault_injection) * 100).toFixed(0)}%`).join('、') }}</b>
|
||||
—— 该能力当前会被人为判失败(演练用),确认后可在配置里把失败率改回 0。
|
||||
</p>
|
||||
|
||||
<div class="workspace">
|
||||
<aside class="type-rail">
|
||||
<button v-for="type in types" :key="type" class="type-button"
|
||||
:class="{ on: selectedType === type }"
|
||||
@click="selectedType = type; showForm = false; probe = null">
|
||||
<span class="type-icon" :style="{ color: railMeta(type).color }">{{ railMeta(type).icon }}</span>
|
||||
<span><b>{{ railMeta(type).label }}</b><small>{{ railMeta(type).hint }}</small></span>
|
||||
<em>{{ countOf(type) }}</em>
|
||||
</button>
|
||||
<div class="rail-note">
|
||||
<b title="H3 / Qwen-Image / IndexTTS2 统一归属 comfyui:9200 ,平台会在模型适配器层持有 GPU 锁,避免显存争抢。">同卡串行</b>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<section class="catalog">
|
||||
<div class="catalog-head">
|
||||
<div>
|
||||
<small class="eyebrow">{{ selectedType.toUpperCase() }} MODELS</small>
|
||||
<h2 :title="selectedMeta?.description">{{ selectedMeta?.label }}</h2>
|
||||
</div>
|
||||
<div class="ctlbar">
|
||||
<label class="fld grow"><span>搜索</span>
|
||||
<input v-model="keyword" aria-label="搜索模型" placeholder="名称 / 模型标识 / 编码" />
|
||||
</label>
|
||||
<AutoRefresh :busy="!!busy" :every="30000" :paused="showForm" @refresh="load()" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="!currentRows.length" class="empty">
|
||||
当前能力还没有配置。添加后即可在资产生成、分镜与调度中选择。
|
||||
</div>
|
||||
<div v-else class="model-grid">
|
||||
<article v-for="row in currentRows" :key="row.id" class="model-card" :class="{ disabled: !row.enabled }">
|
||||
<div class="card-top">
|
||||
<div class="model-avatar" :style="{ color: railMeta(row.media_type).color }">{{ railMeta(row.media_type).icon }}</div>
|
||||
<div class="grow">
|
||||
<div class="title-line">
|
||||
<h3>{{ row.display_name || row.model }}</h3>
|
||||
<span v-if="row.is_default" class="pill lime">默认</span>
|
||||
<span class="pill" :class="row.enabled ? (row.available ? 'ok' : 'warn') : 'bad'">
|
||||
{{ !row.enabled ? '已停用' : row.available ? '就绪' : '未就绪' }}
|
||||
</span>
|
||||
<span v-if="Number(row.fault_injection || 0) > 0" class="pill bad">
|
||||
故障注入 {{ (Number(row.fault_injection) * 100).toFixed(0) }}%
|
||||
</span>
|
||||
</div>
|
||||
<div class="model-id mono">{{ row.model }}</div>
|
||||
<div class="sub-id mono">{{ row.provider }} · {{ row.model_code || '未设置编码' }} · {{ row.adapter }}</div>
|
||||
</div>
|
||||
<button class="outline tiny" @click="editModel(row)">配置</button>
|
||||
</div>
|
||||
|
||||
<div class="endpoint">
|
||||
<span>{{ row.media_type === 'llm' ? 'Endpoint / Key' : '资源地址 / 参考' }}</span>
|
||||
<div class="endpoint-value">
|
||||
<b class="mono" :class="{ plain: !!revealedKeys[row.id] }"
|
||||
:title="keyValue(row)">{{ keyValue(row) }}</b>
|
||||
<button v-if="row.has_api_key" class="key-eye" type="button"
|
||||
:class="{ on: !!revealedKeys[row.id] }" :disabled="keyRevealing === row.id"
|
||||
:aria-pressed="!!revealedKeys[row.id]" :aria-label="keyEyeLabel(row)"
|
||||
:title="keyEyeLabel(row)" @click="toggleKey(row)">
|
||||
<EyeIcon :shown="!!revealedKeys[row.id]" :loading="keyRevealing === row.id" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="modelFiles(row).length" class="file-stack">
|
||||
<span v-for="file in modelFiles(row).slice(0, 3)" :key="file" class="file-chip mono" :title="file">{{ file }}</span>
|
||||
</div>
|
||||
<div class="chipbar chips">
|
||||
<span v-for="mode in (row.modes || []).slice(0, 5)" :key="mode" class="chip">{{ mode }}</span>
|
||||
<span v-if="row.timeout_seconds" class="chip">超时 {{ row.timeout_seconds }}s</span>
|
||||
<span v-if="row.max_concurrency" class="chip">并发 {{ row.max_concurrency }}</span>
|
||||
</div>
|
||||
|
||||
<p v-if="row.notes" class="notes">{{ row.notes }}</p>
|
||||
<div class="usage" :class="{ idle: !usageOf(row).calls }"
|
||||
title="统计来自生成台账,为全平台累计(含历史项目与失败重试);只读,不影响配置">
|
||||
<span class="usage-icon">▤</span>
|
||||
<span v-for="(part, idx) in usageParts(row)" :key="part" class="usage-part">
|
||||
<b v-if="idx === 0">{{ part }}</b><template v-else>{{ part }}</template>
|
||||
</span>
|
||||
</div>
|
||||
<div class="card-actions">
|
||||
<label class="check"><input type="checkbox" :checked="row.enabled"
|
||||
@change="patch(row, { enabled: !row.enabled }, row.enabled ? '停用模型' : '启用模型')" />启用</label>
|
||||
<button class="outline tiny" :disabled="row.is_default" @click="patch(row, { is_default: true }, '设为默认')">
|
||||
{{ row.is_default ? '当前默认' : '设为默认' }}
|
||||
</button>
|
||||
<button class="outline tiny" :disabled="probing === row.id" @click="runProbe(row)">
|
||||
{{ probing === row.id ? '探测中…' : '检测连接' }}
|
||||
</button>
|
||||
<button class="btn-del" title="删除这个模型" @click="remove(row)">删除</button>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<div v-if="probe" class="probe">
|
||||
<div class="between">
|
||||
<div class="row">
|
||||
<span class="pill" :class="(probe.reachable ?? probe.available) ? 'ok' : 'bad'">
|
||||
{{ (probe.reachable ?? probe.available)
|
||||
? (probe.available ? '服务与节点就绪' : '服务可达,节点不完整')
|
||||
: '连接失败' }}
|
||||
</span>
|
||||
<b>{{ probe.model.display_name || probe.model.model }}</b>
|
||||
</div>
|
||||
<button class="outline tiny" @click="probe = null">关闭</button>
|
||||
</div>
|
||||
<p>{{ probe.message || '—' }}</p>
|
||||
<div v-if="probe.queue" class="chipbar chips">
|
||||
<span class="chip">运行 {{ probe.queue.running }}</span>
|
||||
<span class="chip">排队 {{ probe.queue.pending }}</span>
|
||||
</div>
|
||||
<div v-if="probe.nodes" class="chipbar chips">
|
||||
<span v-for="(ok, node) in probe.nodes" :key="node" class="chip" :class="{ on: ok }">{{ node }} {{ ok ? '✓' : '缺' }}</span>
|
||||
</div>
|
||||
<div v-if="probe.files" class="probe-files">
|
||||
<div v-for="(items, kind) in probe.files" :key="kind">
|
||||
<span>{{ kind }}</span>
|
||||
<code>{{ (items || []).slice(0, 8).join(' · ') || '—' }}</code>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<Teleport to="body">
|
||||
<div v-if="showForm" class="drawer-backdrop" @click.self="closeForm">
|
||||
<section class="drawer">
|
||||
<header class="drawer-head">
|
||||
<div>
|
||||
<small class="eyebrow">{{ editingId ? 'EDIT MODEL' : 'REGISTER MODEL' }}</small>
|
||||
<h2 :title="railMeta(form.media_type).hint">{{ editingId ? '编辑' : '添加' }}{{ railMeta(form.media_type).label }}</h2>
|
||||
</div>
|
||||
<button class="outline tiny" @click="closeForm">关闭 Esc</button>
|
||||
</header>
|
||||
|
||||
<form class="drawer-body" @submit.prevent="save">
|
||||
<template v-if="form.media_type === 'llm'">
|
||||
<div class="section-title"><b>供应商连接</b><span>OpenAI 兼容协议</span></div>
|
||||
<label class="field"><span class="lbl">Base URL <b class="req">*</b></span>
|
||||
<input v-model="form.base_url" placeholder="https://coding.dashscope.aliyuncs.com/v1" />
|
||||
</label>
|
||||
<label class="field"><span class="lbl">API Key</span>
|
||||
<SecretInput title="列表只回显掩码;点右侧图标会向后端取一次真实密钥并显示(仅管理员,留痕)。" v-model="form.api_key" :has-saved="editingHasKey"
|
||||
:reveal-url="editingId ? `/api/providers/${editingId}/api-key` : ''"
|
||||
:placeholder="editingId ? '留空保持原密钥;填写即覆盖' : 'sk-…'"
|
||||
autocomplete="new-password" />
|
||||
</label>
|
||||
<label v-if="editingId && form.api_key === ''" class="check subtle"><input v-model="form.clear_api_key" type="checkbox" />清除已保存的 API Key</label>
|
||||
|
||||
<div class="section-title"><b>生成参数</b><span>与常见大模型控制台一致</span></div>
|
||||
<div class="slider-grid">
|
||||
<label class="slider-field">
|
||||
<span>Temperature <b>{{ Number(form.temperature).toFixed(1) }}</b></span>
|
||||
<input v-model.number="form.temperature" type="range" min="0" max="2" step="0.1" />
|
||||
<small><i>0</i><i>0.7</i><i>1</i><i>2</i></small>
|
||||
</label>
|
||||
<label class="slider-field">
|
||||
<span>Top P <b>{{ Number(form.top_p).toFixed(2) }}</b></span>
|
||||
<input v-model.number="form.top_p" type="range" min="0" max="1" step="0.01" />
|
||||
<small><i>0</i><i>0.5</i><i>0.9</i><i>1</i></small>
|
||||
</label>
|
||||
</div>
|
||||
<div class="tokens">
|
||||
<span>Max Tokens</span>
|
||||
<button v-for="n in tokenOptions" :key="n" type="button" :class="{ on: Number(form.max_tokens) === n }"
|
||||
@click="form.max_tokens = n">{{ n / 1024 }}K</button>
|
||||
</div>
|
||||
|
||||
</template>
|
||||
|
||||
<template v-else-if="form.media_type === 'video' || form.media_type === 'image'">
|
||||
<div class="section-title"><b>{{ form.media_type === 'video' ? 'ComfyUI 视频工作流' : 'Qwen-Image 本地工作流' }}</b><span>9200 单卡</span></div>
|
||||
<label class="field"><span class="lbl">ComfyUI Base URL</span><input v-model="form.base_url" placeholder="http://10.100.53.199:9200" /></label>
|
||||
<div class="frow cols2 stack">
|
||||
<label class="fld"><span>{{ form.media_type === 'video' ? '扩散模型(UNET GGUF)' : 'GGUF 扩散模型' }}</span><input v-model="form.unet" /></label>
|
||||
<label class="fld"><span>文本编码器</span><input v-model="form.clip" /></label>
|
||||
<label class="fld"><span>{{ form.media_type === 'video' ? '视频 VAE' : '图像 VAE' }}</span><input v-model="form.vae" /></label>
|
||||
<label v-if="form.media_type === 'video'" class="fld"><span>音频 VAE</span><input v-model="form.audio_vae" /></label>
|
||||
<label class="fld"><span>CLIP 类型</span><input v-model="form.clip_type" /></label>
|
||||
<label class="fld"><span>工作流模板</span><input v-model="form.workflow" /></label>
|
||||
<label class="fld"><span>采样器</span><input v-model="form.sampler" /></label>
|
||||
<label class="fld"><span>步数</span><input v-model.number="form.steps" type="number" min="1" /></label>
|
||||
<label v-if="form.media_type === 'image'" class="fld"><span>CFG</span><input v-model.number="form.cfg" type="number" step="0.1" /></label>
|
||||
<label class="fld"><span>FPS</span><input v-model.number="form.fps" type="number" min="1" /></label>
|
||||
</div>
|
||||
<label v-if="form.media_type === 'image'" class="field"><span class="lbl">固定 Sigma 序列</span>
|
||||
<textarea v-model="form.sigmas" rows="2" class="mono" />
|
||||
</label>
|
||||
</template>
|
||||
|
||||
<template v-else-if="form.media_type === 'tts'">
|
||||
<div class="section-title"><b>IndexTTS2 本地推理</b><span>Zero-shot 音色克隆</span></div>
|
||||
<label class="field"><span class="lbl">ComfyUI Base URL</span><input v-model="form.base_url" placeholder="http://10.100.53.199:9200" /></label>
|
||||
<div class="frow cols2 stack">
|
||||
<label class="fld"><span>模型目录标识</span><input v-model="form.tts_model" /></label>
|
||||
<label class="fld"><span>模型来源</span><FSelect v-model="form.download_from"><option value="modelscope">ModelScope</option><option value="huggingface">HuggingFace</option><option value="local">仅本地</option></FSelect></label>
|
||||
<label class="fld"><span>工作流模板</span><input v-model="form.workflow" /></label>
|
||||
<label title="声线资产中的「供应商音色 ID」可填 ComfyUI input 文件名,或客户端本地音频路径;平台会自动上传本地参考音频。" class="fld"><span>参考音频</span><input v-model="form.reference_audio" /></label>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div class="section-title"><b>旧版文本接口</b><span>兼容保留</span></div>
|
||||
<label class="field"><span class="lbl">Base URL</span><input v-model="form.base_url" /></label>
|
||||
<label class="field"><span class="lbl">自定义端点</span><input v-model="form.endpoint" placeholder="可留空,默认 /chat/completions" /></label>
|
||||
</template>
|
||||
|
||||
<div class="section-title"><b>模型身份与调度</b><span>所有能力通用,仅在此处填写一次</span></div>
|
||||
<div class="frow cols3 stack">
|
||||
<label class="field"><span class="lbl">显示名称 <b class="req">*</b></span><input v-model="form.display_name" /></label>
|
||||
<label class="fld"><span>供应商标识</span><input v-model="form.provider" /></label>
|
||||
<label class="fld"><span>适配器</span><FSelect v-model="form.adapter"><option v-for="a in (adapters[form.media_type] || [])" :key="a" :value="a">{{ a }}</option></FSelect></label>
|
||||
<label class="field"><span class="lbl">模型标识 <b class="req">*</b></span><input v-model="form.model" /></label>
|
||||
<label class="field"><span class="lbl">模型编码 <b class="req">*</b></span><input v-model="form.model_code" /></label>
|
||||
<label class="fld"><span>超时(秒)</span><input v-model.number="form.timeout_seconds" type="number" min="1" /></label>
|
||||
</div>
|
||||
<div class="frow cols4 stack tight">
|
||||
<label class="fld"><span>并发</span><input v-model.number="form.max_concurrency" type="number" min="1" /></label>
|
||||
<label class="fld"><span>RPM</span><input v-model.number="form.requests_per_minute" type="number" min="1" /></label>
|
||||
<label v-if="form.media_type !== 'llm' && form.media_type !== 'image'" class="fld"><span>最短时长</span><input v-model.number="form.min_duration" type="number" step="0.5" /></label>
|
||||
<label v-if="form.media_type !== 'llm' && form.media_type !== 'image'" class="fld"><span>最长时长</span><input v-model.number="form.max_duration" type="number" step="0.5" /></label>
|
||||
</div>
|
||||
<div class="toggles">
|
||||
<label class="check"><input v-model="form.enabled" type="checkbox" />启用模型</label>
|
||||
<label class="check"><input v-model="form.is_default" type="checkbox" />设为该能力默认</label>
|
||||
</div>
|
||||
<label class="field"><span class="lbl">备注</span><textarea v-model="form.notes" rows="2" placeholder="模型约束、显存策略或接入说明" /></label>
|
||||
|
||||
<button type="button" class="advanced-toggle" @click="toggleAdvanced">
|
||||
{{ showAdvanced ? '收起高级 JSON' : '展开高级 JSON / 原始适配器参数' }}
|
||||
</button>
|
||||
<div v-if="showAdvanced" class="frow advanced">
|
||||
<label class="field"><span class="lbl">config JSON</span><textarea v-model="form.extra_config" rows="8" class="mono" spellcheck="false" /></label>
|
||||
<label class="field"><span class="lbl">default_params JSON</span><textarea v-model="form.extra_params" rows="6" class="mono" spellcheck="false" /></label>
|
||||
</div>
|
||||
|
||||
<div class="drawer-actions">
|
||||
<button class="primary" type="submit" :disabled="!!busy">{{ editingId ? '保存配置' : '创建模型' }}</button>
|
||||
<button class="outline" type="button" @click="closeForm">取消</button>
|
||||
<span v-if="busy" class="muted"><span class="spin"></span> {{ busy }}…</span>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
</Teleport>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.model-center { --lime: var(--c-accent); --lime-fill: var(--c-accent-fill); --line: var(--c-line); --panel: var(--c-bg-panel); }
|
||||
.hero { align-items: flex-start; margin-bottom: 18px; }
|
||||
.model-link { text-decoration: none; }
|
||||
.banner { padding: 10px 12px; border: 1px solid var(--c-danger-line); background: var(--c-danger-ink); border-radius: 8px; }
|
||||
.summary { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; margin-bottom: 14px; }
|
||||
.summary > div { position: relative; overflow: hidden; background: linear-gradient(145deg, var(--c-bg-panel), var(--c-bg-shell)); border: 1px solid var(--line); border-radius: 12px; padding: 14px 16px; min-height: 92px; }
|
||||
.summary > div::after { content: ''; position: absolute; inset: 0; pointer-events: none; background: radial-gradient(circle at 106% 132%, var(--c-tint-accent), transparent 58%); }
|
||||
.summary span { display: block; color: var(--c-text-faint); font-size: 10px; letter-spacing: .4px; }
|
||||
.summary b { display: block; color: var(--c-text); font-size: 24px; margin: 7px 0 2px; line-height: 1.1; }
|
||||
.summary small { color: var(--c-text-dim); font-size: 10px; }
|
||||
.summary .accent { border-color: var(--c-success-line); background: linear-gradient(145deg, var(--c-bg-raised), var(--c-bg-panel)); }
|
||||
.summary b i { color: var(--c-text-faint); font-size: 14px; font-style: normal; font-weight: 500; margin-left: 3px; }
|
||||
.summary.warn { border-color: var(--c-warn-line); background: linear-gradient(145deg, var(--c-warn-tint), var(--c-bg-shell)); }
|
||||
.summary.warn b { color: var(--c-warn-bright); }
|
||||
.summary .accent b { color: var(--c-accent-bright); font-size: 17px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.workspace { display: grid; grid-template-columns: 236px minmax(0, 1fr); gap: 13px; align-items: start; }
|
||||
.type-rail { position: sticky; top: 14px; display: flex; flex-direction: column; gap: 6px; padding: 8px; background: var(--c-bg-card); border: 1px solid var(--line); border-radius: 13px; }
|
||||
.type-button { display: flex; align-items: center; gap: 10px; width: 100%; text-align: left; color: var(--c-text-3); border: 1px solid transparent; background: transparent; border-radius: 9px; padding: 11px 9px; }
|
||||
.type-button:hover { background: var(--c-bg-panel); }
|
||||
.type-button.on { background: var(--c-bg-raised); border-color: var(--c-success-line); box-shadow: inset 3px 0 0 var(--lime); }
|
||||
.type-icon { display: grid; place-items: center; width: 29px; height: 29px; border-radius: 8px; background: var(--c-line-soft); flex-shrink: 0; font-size: 15px; }
|
||||
.type-button b { display: block; font-size: 12px; }
|
||||
.type-button small { display: block; color: var(--c-text-dim); font-size: 10px; margin-top: 3px; line-height: 1.3; }
|
||||
.type-button em { margin-left: auto; color: var(--c-warn-bright); font-style: normal; font-size: 17px; }
|
||||
.rail-note { border-top: 1px solid var(--c-bg-active); padding: 19px 7px 5px; }
|
||||
.rail-note b { color: var(--c-accent); font-size: 10px; }
|
||||
.catalog { min-width: 0; background: var(--c-bg-shell); border: 1px solid var(--line); border-radius: 13px; padding: 16px; }
|
||||
.catalog-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 16px; margin-bottom: 14px; }
|
||||
.catalog-head h2 { font-size: 19px; margin: 4px 0 0; }
|
||||
.catalog-head p { color: var(--c-text-faint); font-size: 11px; line-height: 1.5; margin: 6px 0 0; }
|
||||
/* 搜索框属于页头工具条,统一走紧凑尺寸(31px),与其它页面搜索框一致 */
|
||||
.model-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
|
||||
.model-card { display: flex; flex-direction: column; min-height: 230px; padding: 14px; border: 1px solid var(--c-bg-emphasis); border-radius: 11px; background: linear-gradient(145deg, var(--c-bg-panel), var(--c-bg-sunken)); transition: border-color .15s, transform .15s; }
|
||||
.model-card:hover { border-color: var(--c-line-bright); transform: translateY(-1px); }
|
||||
.model-card.disabled { opacity: .62; }
|
||||
.card-top { display: flex; align-items: flex-start; gap: 10px; }
|
||||
.model-avatar { display: grid; place-items: center; width: 36px; height: 36px; border-radius: 9px; background: var(--c-line-soft); font-size: 17px; flex-shrink: 0; }
|
||||
.title-line { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
||||
.title-line h3 { margin: 0; font-size: 13px; }
|
||||
.model-id { color: var(--c-text); font-size: 11.5px; margin-top: 5px; overflow-wrap: anywhere; }
|
||||
.sub-id { color: var(--c-text-dim); margin-top: 3px; }
|
||||
.pill { display: inline-flex; align-items: center; font-size: 10px; border-radius: 99px; border: 1px solid var(--c-line-strong); color: var(--c-text-3); padding: 2px 6px; white-space: nowrap; }
|
||||
.pill.ok { color: var(--c-accent-bright); background: var(--c-success-tint); border-color: var(--c-success-line); }
|
||||
.pill.warn { color: var(--c-warn); background: var(--c-warn-tint); border-color: var(--c-warn-line); }
|
||||
.pill.bad { color: var(--c-danger); background: var(--c-danger-tint2); border-color: var(--c-danger-line); }
|
||||
.pill.lime { color: var(--c-on-accent); background: var(--lime-fill); border-color: var(--lime-fill); font-weight: 700; }
|
||||
.usage { margin-top: auto; display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; padding: 8px 10px; border: 1px dashed var(--c-line-strong); border-radius: 8px; background: var(--c-bg-sunken); color: var(--c-text-3); font-size: 10px; }
|
||||
.usage.idle { color: var(--c-text-dim); font-style: normal; }
|
||||
.usage-icon { color: var(--c-accent); }
|
||||
.usage-part + .usage-part::before { content: '·'; margin-right: 8px; color: var(--c-text-faint); }
|
||||
.usage b { color: var(--c-accent-bright); font-weight: 600; }
|
||||
.usage.idle b { color: var(--c-text-dim); font-weight: 500; }
|
||||
.endpoint { margin-top: 12px; padding: 9px 10px; border-radius: 8px; background: var(--c-bg-input); border: 1px solid var(--c-line-soft); }
|
||||
.endpoint span { display: block; color: var(--c-text-dim); font-size: 10px; }
|
||||
.endpoint-value { display: flex; align-items: center; gap: 6px; min-width: 0; margin-top: 4px; }
|
||||
.endpoint-value b { display: block; flex: 1 1 auto; min-width: 0; color: var(--c-text-3); font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
/* 展开明文后允许换行:密钥 40+ 字符,省略号等于没显示 */
|
||||
.endpoint b.plain { color: var(--c-text); white-space: normal; overflow: visible; text-overflow: clip; overflow-wrap: anywhere; }
|
||||
.key-eye { flex: 0 0 auto; width: 24px; height: 24px; padding: 0; display: grid; place-items: center; cursor: pointer;
|
||||
border: 1px solid var(--c-line); border-radius: 6px; background: var(--c-bg-raise); color: var(--c-text-3); }
|
||||
.key-eye:hover { color: var(--c-text); border-color: var(--c-line-strong) }
|
||||
.key-eye.on { color: var(--c-accent-bright); border-color: var(--c-accent-line); background: var(--c-accent-tint2) }
|
||||
.key-eye:disabled { opacity: .6; cursor: progress }
|
||||
.key-eye:focus-visible { outline: 2px solid var(--c-accent-deep); outline-offset: 1px }
|
||||
.file-stack { display: flex; flex-direction: column; gap: 3px; margin-top: 8px; }
|
||||
.file-chip { display: block; color: var(--c-text-faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: 10px; }
|
||||
.notes { margin: 9px 0 0; color: var(--c-text-faint); font-size: 10px; line-height: 1.5; }
|
||||
.card-actions { display: flex; align-items: center; gap: 5px; flex-wrap: wrap; border-top: 1px solid var(--c-bg-active); margin-top: auto; padding-top: 9px; }
|
||||
.card-actions .check { margin-right: auto; }
|
||||
.danger { color: var(--c-danger); }
|
||||
.probe { margin-top: 12px; padding: 13px; border-radius: 10px; border: 1px solid var(--c-accent-line); background: var(--c-bg-card); }
|
||||
.probe p { margin: 8px 0; color: var(--c-text-3); font-size: 11px; line-height: 1.55; }
|
||||
.probe-files { display: flex; flex-direction: column; gap: 5px; margin-top: 10px; }
|
||||
.probe-files > div { display: grid; grid-template-columns: 80px minmax(0, 1fr); gap: 8px; }
|
||||
.probe-files span { color: var(--c-text-dim); font-size: 10px; text-transform: uppercase; }
|
||||
.probe-files code { color: var(--c-text-3); font-size: 10px; overflow-wrap: anywhere; }
|
||||
|
||||
.section-title { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; margin: 24px 0 10px; padding-bottom: 7px; border-bottom: 1px solid var(--c-bg-emphasis); }
|
||||
.section-title:first-child { margin-top: 0; }
|
||||
.section-title b { color: var(--c-text); font-size: 12px; }
|
||||
.section-title span { color: var(--c-text-dim); font-size: 10px; }
|
||||
.slider-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 24px; padding: 8px 3px; }
|
||||
.slider-field > span { display: flex; justify-content: space-between; color: var(--c-text-3); font-size: 11px; }
|
||||
.slider-field > span b { color: var(--c-accent-bright); }
|
||||
.slider-field input[type="range"] { height: 5px; padding: 0; margin: 0; accent-color: var(--lime-fill); border: 0; background: var(--c-line-strong); }
|
||||
.slider-field small { display: flex; justify-content: space-between; color: var(--c-text-dim); font-size: 10px; }
|
||||
.slider-field small i { font-style: normal; }
|
||||
.tokens { display: flex; align-items: center; gap: 7px; margin-top: 12px; }
|
||||
.tokens > span { color: var(--c-text-muted); font-size: 11px; margin-right: 8px; }
|
||||
.tokens button { display: inline-flex; align-items: center; height: var(--ctl-h-md); padding: 0 17px; border: 1px solid var(--c-line-strong); background: var(--c-bg-input); color: var(--c-text-3); border-radius: 999px; font-size: 10px; }
|
||||
.tokens button.on { background: var(--lime-fill); border-color: var(--lime-fill); color: var(--c-on-accent); font-weight: 700; }
|
||||
.switch-row { display: flex; justify-content: space-between; align-items: center; gap: 20px; border: 1px solid var(--c-line); border-radius: 9px; padding: 11px 13px; background: var(--c-bg-sunken); }
|
||||
.switch-row b { display: block; color: var(--c-text-2); font-size: 11px; }
|
||||
.switch-row small { display: block; color: var(--c-text-dim); font-size: 10px; margin-top: 3px; }
|
||||
.switch-row input, .toggles input, .check input { width: auto; accent-color: var(--lime-fill); }
|
||||
.toggles { display: flex; gap: 20px; margin: 12px 0 5px; }
|
||||
.advanced-toggle { display: inline-flex; align-items: center; justify-content: center; width: 100%; height: var(--ctl-h-md); margin: 18px 0 0; border: 1px dashed var(--c-line-strong); background: transparent; color: var(--c-text-muted); border-radius: 8px; padding: 0 9px; font-size: 10px; }
|
||||
/* 高级 JSON 两块的比例是本页特有的,栅格本身仍来自 .frow */
|
||||
.advanced { grid-template-columns: 1.3fr 1fr; }
|
||||
.drawer-actions { position: sticky; z-index: 3; bottom: 0; display: flex; align-items: center; gap: 8px; margin: 22px -24px 0; padding: 14px 24px; border-top: 1px solid var(--c-line); background: var(--c-bg-shell); box-shadow: 0 -14px 26px var(--c-shade-2); }
|
||||
/* 滚动容器留了 24px 下内边距,sticky 按钮条会停在它上方,
|
||||
于是最后一段表单内容从按钮条底下露出一条被裁切的字,看起来像渲染错乱。
|
||||
把滚动区下内边距交给按钮条承担,按钮条贴住视口底边,缝隙消失。 */
|
||||
.drawer-body { padding-bottom: 0 }
|
||||
.drawer-actions { padding-bottom: 20px }
|
||||
@media (max-width: 1180px) {
|
||||
.summary { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.model-grid { grid-template-columns: 1fr; }
|
||||
.workspace { grid-template-columns: 190px minmax(0, 1fr); }
|
||||
}
|
||||
@media (max-width: 820px) {
|
||||
.workspace { grid-template-columns: 1fr; }
|
||||
.type-rail { position: static; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.rail-note { grid-column: 1 / -1; }
|
||||
.catalog-head { flex-direction: column; }
|
||||
.slider-grid, .advanced { grid-template-columns: 1fr; }
|
||||
.summary { grid-template-columns: 1fr; }
|
||||
.drawer { width: 100vw; }
|
||||
}
|
||||
@media (max-width: 560px) {
|
||||
.summary { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.summary > div { min-height: 82px; padding: 12px; }
|
||||
}
|
||||
</style>
|
||||
|
|
@ -1,143 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import * as api from '../api'
|
||||
import { briefOpen, loadProject, pctx, startPolling, stopPolling } from '../project'
|
||||
import { fmtMoney, pct, statusClass, statusLabel } from '../format'
|
||||
import { allNodesDone, stageNote } from '../pipeline'
|
||||
import WorkflowBar from '../components/WorkflowBar.vue'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const id = computed(() => Number(route.params.id))
|
||||
const error = ref('')
|
||||
const confirming = ref(false)
|
||||
/** GL-1:项目概况(4 张指标卡 + 12 节点流程条)在桌面端同样要能收起。
|
||||
* 以前只有 ≤900px 才折叠,正文被顶出首屏 ≈470px,每个页签都要先滚一屏废话。
|
||||
* 折叠状态记在 localStorage,跨页签、跨会话保持用户的偏好。 */
|
||||
/* 折叠状态本身搬到 project.ts(briefOpen):分镜工作台也要能收起这块概况,
|
||||
两处按钮共用同一份偏好,不会各说各话。 */
|
||||
const summaryOpen = briefOpen
|
||||
|
||||
const project = computed(() => pctx.project)
|
||||
const stats = computed(() => pctx.stats || {})
|
||||
const nextStep = computed(() => pctx.workflow.find((s: any) => s.state === 'active' || s.state === 'failed'))
|
||||
/** 流程走完的项目不再报「当前节点:导出完整视频」,否则和旁边的「已交付」自相矛盾 */
|
||||
const flowDone = computed(() => allNodesDone(pctx.workflow))
|
||||
const flowNote = computed(() => stageNote(project.value, pctx.workflow))
|
||||
|
||||
async function load(fresh = false) {
|
||||
error.value = ''
|
||||
// loadProject 自己会把失败写进 pctx.error,页面无需再报「正在刷新」
|
||||
await loadProject(id.value, !fresh)
|
||||
}
|
||||
|
||||
async function removeProject() {
|
||||
try {
|
||||
await api.del(`/api/projects/${id.value}`, { purge_files: true })
|
||||
await router.push('/')
|
||||
} catch (exc: any) { error.value = exc.message }
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await load(true)
|
||||
startPolling(id.value)
|
||||
})
|
||||
onBeforeUnmount(stopPolling)
|
||||
watch(id, () => load(true))
|
||||
// 项目切换时保持用户的折叠偏好(偏好是全局的,不是每个项目一套)
|
||||
watch(id, () => { confirming.value = false })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<div v-if="pctx.loading && !project" class="loading"><span class="spin"></span> 正在载入项目…</div>
|
||||
|
||||
<template v-else-if="project">
|
||||
<header>
|
||||
<div>
|
||||
<div class="row">
|
||||
<router-link class="link" to="/">← 项目总览</router-link>
|
||||
<span :class="statusClass(project.status)">{{ statusLabel(project.status) }}</span>
|
||||
<span v-if="flowDone" class="tag ok">{{ flowNote }}</span>
|
||||
<span v-else class="tag info">当前节点:{{ flowNote || project.stage_label }}</span>
|
||||
</div>
|
||||
<h1>{{ project.name }}</h1>
|
||||
</div>
|
||||
<div class="row">
|
||||
<!-- 项目状态由 project.ts 每 6 秒轮询,页面无需再单独刷新 -->
|
||||
<button class="btn-del lg" title="删除整个项目:分镜、任务与已生成素材一起清除" @click="confirming = !confirming">⌫ 删除项目</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<p v-if="error || pctx.error" class="error" style="margin-bottom:12px">{{ error || pctx.error }}</p>
|
||||
<p v-if="pctx.notice" class="notice">{{ pctx.notice }}</p>
|
||||
|
||||
<div v-if="confirming" class="notice danger">
|
||||
<div class="between">
|
||||
<span>删除《{{ project.name }}》会同时清除分镜、任务与已生成素材,确认?</span>
|
||||
<div class="row">
|
||||
<button class="outline tiny" @click="confirming = false">取消</button>
|
||||
<button class="btn-del solid lg" @click="removeProject">确认删除</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button class="project-brief-toggle" :aria-expanded="summaryOpen" @click="summaryOpen = !summaryOpen">
|
||||
<span>项目概况</span>
|
||||
<small>{{ statusLabel(project.status) }} · 镜头 {{ stats.shots_approved || 0 }}/{{ stats.shots || 0 }} · 合格 {{ pct(stats.progress_ratio) }}
|
||||
· 任务 {{ stats.tasks_active || 0 }}/{{ stats.tasks || 0 }} · 成本 {{ fmtMoney(stats.cost?.total_cost, stats.cost?.currency) }}</small>
|
||||
<b>{{ summaryOpen ? '收起概况' : '展开概况' }} {{ summaryOpen ? '⌃' : '⌄' }}</b>
|
||||
</button>
|
||||
|
||||
<div class="project-brief" :class="{ open: summaryOpen }">
|
||||
<div class="stats">
|
||||
<div class="stat"><small>镜头(合格/总数)</small><b>{{ stats.shots_approved || 0 }}<span class="muted" style="font-size:14px"> / {{ stats.shots || 0 }}</span></b>
|
||||
<small>{{ statusLabel('failed') }} {{ stats.shots_failed || 0 }} · {{ stats.shots_rejected || 0 }} 驳回</small></div>
|
||||
<div class="stat"><small>时长(计划/已生成)</small><b style="font-size:20px">{{ (stats.planned_duration || 0).toFixed(1) }}s<span class="muted" style="font-size:13px"> / {{ (stats.generated_duration || 0).toFixed(1) }}s</span></b>
|
||||
<small>镜头合格进度 {{ pct(stats.progress_ratio) }}</small></div>
|
||||
<div class="stat"><small>任务(活跃/总数)</small><b>{{ stats.tasks_active || 0 }}<span class="muted" style="font-size:14px"> / {{ stats.tasks || 0 }}</span></b>
|
||||
<small>{{ Object.entries(stats.task_status || {}).map(([k, v]) => `${statusLabel(k)} ${v}`).join(' · ') || '暂无任务' }}</small></div>
|
||||
<div class="stat"><small>成本 / 成片</small><b style="font-size:20px">{{ fmtMoney(stats.cost?.total_cost, stats.cost?.currency) }}</b>
|
||||
<small>{{ (stats.exports || []).length }} 个导出记录</small></div>
|
||||
</div>
|
||||
|
||||
<section class="panel" style="margin-bottom:18px">
|
||||
<div class="panel-head">
|
||||
<div><small class="eyebrow">PIPELINE · 12 节点业务流程</small><h2>流程进度</h2></div>
|
||||
<span v-if="nextStep" class="val">下一步:{{ nextStep.label }} — {{ nextStep.detail }}</span>
|
||||
</div>
|
||||
<WorkflowBar :workflow="pctx.workflow" />
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<router-view />
|
||||
</template>
|
||||
|
||||
<div v-else class="empty">未找到项目 #{{ id }},可能已被删除。<router-link class="link" to="/">返回项目总览</router-link></div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 折叠条在所有断点都可用:收起后这一行本身就是紧凑摘要,正文直接顶到首屏 */
|
||||
.project-brief-toggle {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin: 0 0 14px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--c-line-strong);
|
||||
border-radius: 9px;
|
||||
background: var(--c-bg-panel);
|
||||
color: var(--c-text-2);
|
||||
text-align: left;
|
||||
}
|
||||
.project-brief-toggle:hover { border-color: var(--c-accent-line); background: var(--c-bg-card); }
|
||||
.project-brief-toggle span { flex: 0 0 auto; font-weight: 700; font-size: 11px; }
|
||||
.project-brief-toggle small { min-width: 0; flex: 1; color: var(--c-text-muted); font-size: 10px;
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.project-brief-toggle b { flex: 0 0 auto; color: var(--c-accent); font-size: 10px; white-space: nowrap; }
|
||||
.project-brief:not(.open) { display: none; }
|
||||
.project-brief.open { margin-bottom: 18px; }
|
||||
</style>
|
||||
|
|
@ -1,305 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import SecretInput from '../components/SecretInput.vue'
|
||||
import * as api from '../api'
|
||||
import { auth, roleLabel } from '../auth'
|
||||
import { fmtAgo, fmtTime } from '../format'
|
||||
import FSelect from '../components/FSelect.vue'
|
||||
import AutoRefresh from '../components/AutoRefresh.vue'
|
||||
|
||||
const users = ref<any[]>([])
|
||||
const roles = ref<{ value: string; label: string }[]>([])
|
||||
const audit = ref<any[]>([])
|
||||
const counts = ref<any>({})
|
||||
const error = ref('')
|
||||
const notice = ref('')
|
||||
const busy = ref('')
|
||||
const keyword = ref('')
|
||||
const roleFilter = ref('')
|
||||
const selectedId = ref<number | null>(null)
|
||||
|
||||
const create = reactive({ username: '', password: '', display_name: '', email: '', role: 'editor', note: '' })
|
||||
const edit = reactive({ display_name: '', email: '', role: 'editor', is_active: true, note: '' })
|
||||
const reset = reactive({ password: '', must_change: true, revoke_sessions: true })
|
||||
|
||||
const roleOptions = computed(() => roles.value.length
|
||||
? roles.value
|
||||
: ['admin', 'editor', 'viewer'].map((v) => ({ value: v, label: roleLabel(v) })))
|
||||
const selected = computed(() => users.value.find((row) => row.id === selectedId.value) || null)
|
||||
/**
|
||||
* 账号列表到点自动刷新,页头不放任何刷新控件。但自动刷新不能把管理员
|
||||
* 正在敲的表单冲掉:syncEdit() 会用服务端值重写 edit/reset 两个表单,
|
||||
* 因此只要这三块里有没保存的内容,就暂停轮询,保存完自动恢复。
|
||||
*/
|
||||
const formDirty = computed(() => {
|
||||
const row = selected.value
|
||||
const edited = !!row && (
|
||||
edit.display_name !== (row.display_name || '') || edit.email !== (row.email || '')
|
||||
|| edit.role !== (row.role || 'editor') || edit.is_active !== !!row.is_active
|
||||
|| edit.note !== (row.note || ''))
|
||||
return edited || !!reset.password
|
||||
|| !!(create.username || create.password || create.display_name || create.email || create.note)
|
||||
})
|
||||
const visible = computed(() => {
|
||||
const q = keyword.value.trim().toLowerCase()
|
||||
return users.value.filter((row) => {
|
||||
if (roleFilter.value && row.role !== roleFilter.value) return false
|
||||
if (!q) return true
|
||||
return [row.username, row.display_name, row.email, row.note].join(' ').toLowerCase().includes(q)
|
||||
})
|
||||
})
|
||||
|
||||
function flash(msg: string) {
|
||||
notice.value = msg
|
||||
window.setTimeout(() => { if (notice.value === msg) notice.value = '' }, 4000)
|
||||
}
|
||||
|
||||
async function load(silent = true) {
|
||||
if (!silent) busy.value = '读取账号'
|
||||
error.value = ''
|
||||
try {
|
||||
const [list, trail] = await Promise.all([
|
||||
api.get('/api/users'),
|
||||
api.get('/api/users/audit', { limit: 60 })
|
||||
])
|
||||
users.value = list.items || []
|
||||
roles.value = list.roles || roles.value
|
||||
counts.value = list.counts || {}
|
||||
audit.value = trail.items || []
|
||||
if (!users.value.some((row: any) => row.id === selectedId.value)) {
|
||||
selectedId.value = users.value[0]?.id ?? null
|
||||
}
|
||||
syncEdit()
|
||||
} catch (exc: any) {
|
||||
error.value = exc?.message || String(exc)
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
function syncEdit() {
|
||||
const row = selected.value
|
||||
if (!row) return
|
||||
Object.assign(edit, {
|
||||
display_name: row.display_name || '', email: row.email || '',
|
||||
role: row.role || 'editor', is_active: !!row.is_active, note: row.note || ''
|
||||
})
|
||||
Object.assign(reset, { password: '', must_change: true, revoke_sessions: true })
|
||||
}
|
||||
|
||||
function pick(row: any) {
|
||||
selectedId.value = row.id
|
||||
syncEdit()
|
||||
}
|
||||
|
||||
async function createUser() {
|
||||
if (!create.username.trim() || !create.password) { error.value = '用户名和密码都不能为空'; return }
|
||||
busy.value = '新建账号'
|
||||
error.value = ''
|
||||
try {
|
||||
const made = await api.post('/api/users', { ...create, username: create.username.trim() })
|
||||
const name = made?.username || create.username.trim()
|
||||
Object.assign(create, { username: '', password: '', display_name: '', email: '', note: '' })
|
||||
selectedId.value = made?.id ?? null
|
||||
await load()
|
||||
flash(`账号已创建:${name}`)
|
||||
} catch (exc: any) { error.value = exc?.message || String(exc) }
|
||||
finally { busy.value = '' }
|
||||
}
|
||||
|
||||
async function saveEdit() {
|
||||
const row = selected.value
|
||||
if (!row) return
|
||||
busy.value = '保存账号'
|
||||
error.value = ''
|
||||
try {
|
||||
await api.patch(`/api/users/${row.id}`, { ...edit })
|
||||
await load()
|
||||
flash(`账号「${row.username}」已更新`)
|
||||
} catch (exc: any) { error.value = exc?.message || String(exc) }
|
||||
finally { busy.value = '' }
|
||||
}
|
||||
|
||||
async function resetPassword() {
|
||||
const row = selected.value
|
||||
if (!row || !reset.password) { error.value = '请先填写新密码'; return }
|
||||
busy.value = '重置密码'
|
||||
error.value = ''
|
||||
try {
|
||||
await api.post(`/api/users/${row.id}/password`, { ...reset })
|
||||
Object.assign(reset, { password: '' })
|
||||
await load()
|
||||
flash(`已重置「${row.username}」的密码${reset.revoke_sessions ? ',并注销其全部会话' : ''}`)
|
||||
} catch (exc: any) { error.value = exc?.message || String(exc) }
|
||||
finally { busy.value = '' }
|
||||
}
|
||||
|
||||
async function kickSessions() {
|
||||
const row = selected.value
|
||||
if (!row) return
|
||||
busy.value = '注销会话'
|
||||
try {
|
||||
const data = await api.post(`/api/users/${row.id}/sessions/revoke`)
|
||||
await load()
|
||||
flash(`已注销「${row.username}」的 ${data?.revoked ?? 0} 个会话`)
|
||||
} catch (exc: any) { error.value = exc?.message || String(exc) }
|
||||
finally { busy.value = '' }
|
||||
}
|
||||
|
||||
async function disable() {
|
||||
const row = selected.value
|
||||
if (!row) return
|
||||
if (!window.confirm(`停用「${row.display_name || row.username}」?停用后该账号无法登录,历史操作记录仍会保留。`)) return
|
||||
busy.value = '停用账号'
|
||||
try {
|
||||
await api.del(`/api/users/${row.id}`)
|
||||
await load()
|
||||
flash(`账号「${row.username}」已停用`)
|
||||
} catch (exc: any) { error.value = exc?.message || String(exc) }
|
||||
finally { busy.value = '' }
|
||||
}
|
||||
|
||||
onMounted(() => load(false))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<header>
|
||||
<div><small class="eyebrow">ACCESS CONTROL</small><h1>用户管理</h1></div>
|
||||
<AutoRefresh :busy="!!busy" :every="30000" :paused="formDirty" @refresh="load()" />
|
||||
</header>
|
||||
|
||||
<p v-if="notice" class="notice">{{ notice }}</p>
|
||||
<p v-if="error" class="error" style="font-size:11px;margin:0 0 14px">{{ error }}</p>
|
||||
|
||||
<div class="stats">
|
||||
<div class="stat"><small>账号总数</small><b>{{ counts.total ?? users.length }}</b></div>
|
||||
<div class="stat"><small>管理员</small><b>{{ counts.admins ?? 0 }}</b></div>
|
||||
<div class="stat"><small>已停用</small><b>{{ counts.disabled ?? 0 }}</b></div>
|
||||
<div class="stat"><small>待改初始密码</small><b>{{ counts.pending_password ?? 0 }}</b></div>
|
||||
<div class="stat"><small>活跃会话</small><b>{{ counts.sessions ?? 0 }}</b></div>
|
||||
</div>
|
||||
|
||||
<div class="layout">
|
||||
<div class="right">
|
||||
<section class="panel">
|
||||
<div class="panel-head">
|
||||
<div><small class="eyebrow">ACCOUNTS</small><h2>账号列表</h2></div>
|
||||
<div class="ctlbar filters">
|
||||
<label class="fld grow"><span>搜索</span><input v-model="keyword" class="search" placeholder="用户名 / 姓名 / 邮箱" /></label>
|
||||
<label class="fld narrow"><span>角色</span><FSelect v-model="roleFilter" size="sm" aria-label="按角色筛选">
|
||||
<option value="">全部角色</option>
|
||||
<option v-for="r in roleOptions" :key="r.value" :value="r.value">{{ r.label }}</option>
|
||||
</FSelect></label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tablebox">
|
||||
<table class="tbl">
|
||||
<thead><tr><th>账号</th><th>角色</th><th>状态</th><th>最近登录</th><th class="r">会话</th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="row in visible" :key="row.id" :class="{ chosen: row.id === selectedId }"
|
||||
@click="pick(row)">
|
||||
<td>
|
||||
<b>{{ row.display_name || row.username }}</b>
|
||||
<p class="muted mono">{{ row.username }}<span v-if="row.email"> · {{ row.email }}</span></p>
|
||||
</td>
|
||||
<td><span class="tag" :class="{ info: row.role === 'admin' }">{{ row.role_label || roleLabel(row.role) }}</span></td>
|
||||
<td><span class="tag" :class="{ off: !row.is_active }">{{ row.is_active ? '正常' : '已停用' }}</span>
|
||||
<p v-if="row.must_change_password" class="muted">未改初始密码</p></td>
|
||||
<td><span>{{ row.last_login_at ? fmtAgo(row.last_login_at) : '从未登录' }}</span>
|
||||
<p class="muted">{{ row.login_count || 0 }} 次{{ row.last_login_ip ? ' · ' + row.last_login_ip : '' }}</p></td>
|
||||
<td class="r">{{ row.active_sessions || 0 }}</td>
|
||||
</tr>
|
||||
<tr v-if="!visible.length"><td colspan="5"><div class="empty">没有匹配的账号。</div></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-head"><div><small class="eyebrow">NEW ACCOUNT</small><h2>新建账号</h2></div></div>
|
||||
<div class="frow">
|
||||
<label class="fld"><span>用户名 <b class="req">*</b></span><input v-model="create.username" maxlength="60" placeholder="登录用,小写字母/数字" /></label>
|
||||
<label class="fld"><span>显示名</span><input v-model="create.display_name" maxlength="80" /></label>
|
||||
<label class="fld"><span>邮箱</span><input v-model="create.email" maxlength="160" /></label>
|
||||
<label title="管理员管账号与模型配置;制作可建项目跑生产;观摩只读。" class="fld"><span>角色</span><FSelect v-model="create.role"><option v-for="r in roleOptions" :key="r.value" :value="r.value">{{ r.label }}</option></FSelect></label>
|
||||
<label class="fld"><span>初始密码 <b class="req">*</b></span><SecretInput v-model="create.password" maxlength="200" autocomplete="new-password" placeholder="至少 8 位,首次登录要求修改" /></label>
|
||||
<label class="fld"><span>备注</span><input v-model="create.note" maxlength="200" placeholder="例如:外包配音,仅本项目" /></label>
|
||||
</div>
|
||||
<div class="actions"><button class="primary" :disabled="!!busy" @click="createUser">创建账号</button></div>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-head"><div><small class="eyebrow">AUDIT</small><h2 title="登录 / 改密 / 停用都会留痕">账号操作流水</h2></div></div>
|
||||
<div v-if="!audit.length" class="empty">还没有账号操作记录。</div>
|
||||
<div v-else class="audit">
|
||||
<div v-for="row in audit" :key="row.id" class="auditrow">
|
||||
<span class="mono when">{{ fmtTime(row.created_at) }}</span>
|
||||
<span class="who">{{ row.actor || 'system' }}</span>
|
||||
<span class="msg">{{ row.message }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="right">
|
||||
<section v-if="selected" class="panel">
|
||||
<div class="panel-head"><div><small class="eyebrow">DETAIL</small>
|
||||
<h2>{{ selected.display_name || selected.username }}</h2></div>
|
||||
<span class="tag mono">#{{ selected.id }}</span></div>
|
||||
<div class="frow">
|
||||
<label class="fld"><span>显示名</span><input v-model="edit.display_name" maxlength="80" /></label>
|
||||
<label class="fld"><span>邮箱</span><input v-model="edit.email" maxlength="160" /></label>
|
||||
<label class="fld"><span>角色</span><FSelect v-model="edit.role" :disabled="selected.id === auth.user?.id"
|
||||
:title="selected.id === auth.user?.id ? '不能修改自己的角色' : ''">
|
||||
<option v-for="r in roleOptions" :key="r.value" :value="r.value">{{ r.label }}</option>
|
||||
</FSelect></label>
|
||||
<label class="check"><input v-model="edit.is_active" type="checkbox" />允许登录</label>
|
||||
</div>
|
||||
<label class="field"><span class="lbl">备注</span><textarea v-model="edit.note" rows="2" maxlength="200"></textarea></label>
|
||||
<div class="actions">
|
||||
<button class="primary" :disabled="!!busy" @click="saveEdit">保存</button>
|
||||
<button class="outline" :disabled="!!busy || !selected.is_active" @click="disable">停用账号</button>
|
||||
</div>
|
||||
|
||||
<div class="sub">
|
||||
<h3>重置密码</h3>
|
||||
<label class="field"><span class="lbl">新密码 <b class="req">*</b></span>
|
||||
<SecretInput v-model="reset.password" maxlength="200" autocomplete="new-password" placeholder="留空不可提交" />
|
||||
</label>
|
||||
<div class="ctlbar">
|
||||
<label class="check"><input v-model="reset.must_change" type="checkbox" />要求该账号下次登录改密</label>
|
||||
<label class="check"><input v-model="reset.revoke_sessions" type="checkbox" />同时注销该账号全部会话</label>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button class="secondary" :disabled="!!busy || !reset.password" @click="resetPassword">重置密码</button>
|
||||
<button class="outline" :disabled="!!busy" @click="kickSessions">仅注销会话</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section v-else class="panel"><div class="empty">在左侧选择一个账号开始管理。</div></section>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 统计卡一共 5 项:给 5 列,别让第 5 张孤零零掉到第二行 */
|
||||
.stats { grid-template-columns: repeat(5, minmax(0, 1fr)); }
|
||||
@media (max-width:1280px) { .stats { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
|
||||
@media (max-width:820px) { .stats { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
|
||||
.tablebox { overflow: auto; max-height: 460px }
|
||||
.tablebox tbody tr { cursor: pointer; border-bottom: 1px solid var(--c-line) }
|
||||
.tablebox tbody tr:hover { background: var(--c-bg-hover) }
|
||||
.tablebox tbody tr.chosen { background: var(--c-accent-tint) }
|
||||
.tablebox td { vertical-align: top; padding: 9px 8px }
|
||||
.tablebox b { font-size: 12px }
|
||||
.tablebox p { margin: 3px 0 0 }
|
||||
.tag.off { background: var(--c-danger-tint); color: var(--c-danger) }
|
||||
.audit { display: flex; flex-direction: column; gap: 2px; max-height: 320px; overflow: auto }
|
||||
.auditrow { display: grid; grid-template-columns: 132px 74px minmax(0, 1fr); gap: 9px; padding: 7px 0;
|
||||
border-bottom: 1px solid var(--c-line); font-size: 11px; align-items: baseline }
|
||||
.auditrow:last-child { border-bottom: 0 }
|
||||
.auditrow .when { color: var(--c-text-faint); font-size: 10px }
|
||||
.auditrow .who { color: var(--c-accent-bright); font-weight: 600; overflow-wrap: anywhere }
|
||||
.auditrow .msg { color: var(--c-text-2); overflow-wrap: anywhere }
|
||||
</style>
|
||||
|
|
@ -1,307 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* 导出与成本(图2 节点 ⑫ compose → export)
|
||||
* 出片走任务队列:合成失败可重试,成片留档 + 成本台账 + 生成记录(可复现提示词)
|
||||
*/
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import * as api from '../../api'
|
||||
import { notify, pctx, refresh } from '../../project'
|
||||
import { presetLabel, presets, store } from '../../store'
|
||||
import { fmtAgo, fmtBytes, fmtMs, fmtMoney, fmtSeconds, fmtTime, statusClass, statusLabel } from '../../format'
|
||||
import { fromExport } from '../../media'
|
||||
import { openPreview } from '../../preview'
|
||||
import MediaThumb from '../../components/MediaThumb.vue'
|
||||
import FSelect from '../../components/FSelect.vue'
|
||||
import AutoRefresh from '../../components/AutoRefresh.vue'
|
||||
|
||||
const error = ref('')
|
||||
const busy = ref('')
|
||||
const exportList = ref<any[]>([])
|
||||
const costs = ref<any>(null)
|
||||
const costItems = ref<any[]>([])
|
||||
const generations = ref<any[]>([])
|
||||
const report = ref<any>(null)
|
||||
const timelines = ref<any[]>([])
|
||||
const showAllCost = ref(false)
|
||||
|
||||
const composeForm = reactive({ presets: ['web_1080p'] as string[], name: '', subtitle_mode: '', timeline_id: '' as string, priority: 2 })
|
||||
|
||||
const currency = computed(() => costs.value?.currency || 'CNY')
|
||||
const busyExports = computed(() => exportList.value.filter((e) => ['queued', 'running', 'pending'].includes(e.status)))
|
||||
const succeeded = computed(() => exportList.value.filter((e) => e.status === 'succeeded'))
|
||||
const presetHints: Record<string, string> = {
|
||||
draft_720p: '1280×720 · CRF28 · veryfast(试片最快)',
|
||||
vertical_720p: '720×1280 · CRF24 · medium(9:16 竖屏试片)',
|
||||
web_1080p: '1920×1080 · CRF21 · medium(平台投放默认)',
|
||||
vertical_1080p: '1080×1920 · CRF21 · medium(9:16 竖屏投放)',
|
||||
hq_1080p: '1920×1080 · CRF18 · slow(高质量)',
|
||||
uhd_4k: '3840×2160 · CRF18 · slow(超清,耗时最长)'
|
||||
}
|
||||
|
||||
async function load(silent = true) {
|
||||
if (!pctx.id) return
|
||||
if (!silent) busy.value = '读取交付数据'
|
||||
try {
|
||||
const [ex, cs, gen, rep, tl] = await Promise.all([
|
||||
api.get(`/api/projects/${pctx.id}/exports`),
|
||||
api.get(`/api/projects/${pctx.id}/costs`),
|
||||
api.get(`/api/projects/${pctx.id}/generations`),
|
||||
api.get(`/api/projects/${pctx.id}/timeline/report`).catch(() => null),
|
||||
api.get(`/api/projects/${pctx.id}/timelines`).catch(() => ({ timelines: [] }))
|
||||
])
|
||||
exportList.value = ex.exports || []
|
||||
costs.value = cs.cost
|
||||
// /costs 把计费明细放在顶层 items,不在 cost 里;之前取 cs.cost.items 永远是空的
|
||||
costItems.value = cs.items || []
|
||||
generations.value = gen.generations || []
|
||||
report.value = rep?.report || null
|
||||
timelines.value = tl.timelines || []
|
||||
error.value = ''
|
||||
} catch (exc: any) { error.value = exc.message }
|
||||
finally { busy.value = '' }
|
||||
}
|
||||
|
||||
async function run(label: string, fn: () => Promise<any>, message?: (res: any) => string) {
|
||||
busy.value = label
|
||||
error.value = ''
|
||||
try {
|
||||
const res = await fn()
|
||||
const text = message ? message(res) : ''
|
||||
if (text) notify(text)
|
||||
await Promise.all([load(), refresh()])
|
||||
return res
|
||||
} catch (exc: any) { error.value = exc.message; return null }
|
||||
finally { busy.value = '' }
|
||||
}
|
||||
|
||||
/** 出片:多选预设时依次入队(同一时间线复用,避免逐个点击等页面刷新) */
|
||||
async function compose() {
|
||||
const chosen = composeForm.presets.length ? composeForm.presets : ['web_1080p']
|
||||
busy.value = chosen.length > 1 ? `依次合成 ${chosen.length} 个预设` : '合成导出中'
|
||||
error.value = ''
|
||||
const done: string[] = []
|
||||
const queued: number[] = []
|
||||
const bad: string[] = []
|
||||
try {
|
||||
for (const preset of chosen) {
|
||||
try {
|
||||
const r = await api.post(`/api/projects/${pctx.id}/compose`, {
|
||||
preset,
|
||||
name: chosen.length === 1 ? composeForm.name.trim() : '',
|
||||
subtitle_mode: composeForm.subtitle_mode || null,
|
||||
timeline_id: composeForm.timeline_id ? Number(composeForm.timeline_id) : null,
|
||||
priority: composeForm.priority
|
||||
})
|
||||
const list = r?.exports || []
|
||||
const ok = list.filter((e: any) => e.status === 'succeeded')
|
||||
if (ok.length) done.push(`${presetLabel[preset] || preset}:${ok[0].name}(${fmtMs(ok[0].duration_ms)} · ${fmtBytes(ok[0].size_bytes)})`)
|
||||
else if (!list.length) queued.push(r?.task_id)
|
||||
else bad.push(`${presetLabel[preset] || preset}:${list[0]?.error_message || statusLabel(list[0]?.status)}`)
|
||||
} catch (exc: any) { bad.push(`${presetLabel[preset] || preset}:${exc.message}`) }
|
||||
}
|
||||
await Promise.all([load(), refresh()])
|
||||
const parts: string[] = []
|
||||
if (done.length) parts.push(done.join(';'))
|
||||
if (queued.length) parts.push(`${queued.length} 个合成任务已入队(#${queued.join('、#')}),等待 worker 执行`)
|
||||
if (bad.length) parts.push(`未完成 ${bad.length} 个:${bad.join(';')}`)
|
||||
if (parts.length) notify(parts.join('。'))
|
||||
} finally { busy.value = '' }
|
||||
}
|
||||
|
||||
/** 导出成片 → 统一预览队列(点任意一行都能 ←/→ 翻所有成片) */
|
||||
const exportItems = computed<any[]>(() => exportList.value.map((rec) => fromExport(rec)).filter(Boolean))
|
||||
function previewExport(rec: any) {
|
||||
const at = exportItems.value.findIndex((m) => m.raw?.id === rec.id)
|
||||
openPreview(exportItems.value, at < 0 ? 0 : at)
|
||||
}
|
||||
|
||||
const retryExport = (rec: any) => run('重试导出', () => api.post(`/api/tasks/${rec.task_id}/retry`, {}), () => `合成任务 #${rec.task_id} 已重新入队`)
|
||||
|
||||
function togglePreset(p: string) {
|
||||
const at = composeForm.presets.indexOf(p)
|
||||
if (at >= 0) composeForm.presets.splice(at, 1)
|
||||
else composeForm.presets.push(p)
|
||||
}
|
||||
|
||||
function download(rec: any) {
|
||||
return api.href(`/api/exports/${rec.id}/download`)
|
||||
}
|
||||
|
||||
const shownCostItems = computed(() => (showAllCost.value ? costItems.value : costItems.value.slice(0, 12)))
|
||||
|
||||
onMounted(() => { void load(false) })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="tabstack">
|
||||
<div class="between" style="margin-bottom:12px">
|
||||
<div class="row">
|
||||
<span class="chip">成片 {{ succeeded.length }} / {{ exportList.length }}</span>
|
||||
<span class="chip">累计成本 {{ fmtMoney(costs?.total_cost, currency) }}</span>
|
||||
<span class="chip">生成 {{ costs?.generations?.count ?? 0 }} 次 / {{ (costs?.generations?.seconds ?? 0).toFixed(1) }}s</span>
|
||||
<span class="chip">待结算预估 {{ fmtMoney(costs?.estimated_pending, currency) }}</span>
|
||||
<span v-if="report" class="tag" :class="report.ready ? 'ok' : 'bad'">{{ report.ready ? '时间线可导出' : '时间线有阻塞' }}</span>
|
||||
</div>
|
||||
<div class="row">
|
||||
<span v-if="busy" class="muted"><span class="spin"></span> {{ busy }}…</span>
|
||||
<AutoRefresh :busy="!!busy" :every="busyExports.length ? 4000 : 15000" :paused="!!busy" @refresh="load()" />
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="error" class="error" style="margin-bottom:12px">{{ error }}</p>
|
||||
<p v-if="report && !report.ready" class="error" style="margin-bottom:12px">
|
||||
时间线尚未就绪,导出会被拒绝(409):<span v-for="(x, i) in report.issues.filter((y: any) => y.level === 'error')" :key="i">{{ x.message }} </span>
|
||||
<router-link class="link" :to="`/projects/${pctx.id}/timeline`">前往时间线修复 ↗</router-link></p>
|
||||
|
||||
<!-- ===== 出片 ===== -->
|
||||
<div class="grid2">
|
||||
<section class="panel">
|
||||
<div class="panel-head"><div><small class="eyebrow">PIPELINE · 导出成片</small><h2>合成导出</h2></div></div>
|
||||
<div class="chipbar">
|
||||
<span class="chipbar-label">出片预设(可多选,依次入队)</span>
|
||||
<button v-for="p in (store.meta?.presets || presets)" :key="p" type="button" class="chip"
|
||||
:class="{ on: composeForm.presets.includes(p) }"
|
||||
:aria-pressed="composeForm.presets.includes(p)"
|
||||
:title="presetHints[p]"
|
||||
@click="togglePreset(p)">{{ presetLabel[p] || p }}</button>
|
||||
</div>
|
||||
<div class="frow">
|
||||
<label class="fld"><span>时间线</span><FSelect v-model="composeForm.timeline_id">
|
||||
<option value="">当前时间线</option>
|
||||
<option v-for="t in timelines" :key="t.id" :value="String(t.id)">v{{ t.version }} · {{ t.name }}({{ fmtMs(t.total_duration_ms) }})</option>
|
||||
</FSelect></label>
|
||||
<label class="fld"><span>字幕</span><FSelect v-model="composeForm.subtitle_mode">
|
||||
<option value="">跟随时间线设置(默认内嵌软字幕轨)</option>
|
||||
<option value="embed">内嵌软字幕轨(可开关)</option>
|
||||
<option value="burn">烧录进画面(硬字幕)</option>
|
||||
<option value="both">烧录 + 内嵌</option>
|
||||
<option value="sidecar">只出外挂 SRT</option>
|
||||
<option value="off">不输出字幕</option>
|
||||
</FSelect></label>
|
||||
<label class="fld narrow"><span>优先级</span><input v-model.number="composeForm.priority" type="number" min="0" max="9" /></label>
|
||||
<label class="fld"><span>成片名称(可选)</span><input v-model="composeForm.name" placeholder="留空自动命名:项目名-时间线-时间戳" /></label>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button class="primary" :disabled="!!busy || !report || !report.ready || !composeForm.presets.length" @click="compose"
|
||||
:title="report && report.ready ? `将依次合成 ${composeForm.presets.length} 个预设` : '时间线未就绪时不允许出片'">▶ 开始合成导出{{ composeForm.presets.length > 1 ? `(${composeForm.presets.length} 个预设)` : '' }}</button>
|
||||
<router-link class="link" :to="`/projects/${pctx.id}/timeline`">先检查时间线 ↗</router-link>
|
||||
</div>
|
||||
<p v-if="store.health?.ffmpeg_capabilities && !store.health.ffmpeg_capabilities.subtitle_burn" class="linehint">
|
||||
⚠ 本机 ffmpeg 缺 libass(无 subtitles/ass 滤镜),烧录模式会自动降级为内嵌软字幕轨;
|
||||
装好完整版后设 FFMPEG_BIN 指向它即可。当前使用:{{ store.health.ffmpeg_capabilities.ffmpeg_path || '未探测' }}。</p>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-head"><div><small class="eyebrow">COST LEDGER</small><h2>成本台账</h2></div>
|
||||
<span class="muted">{{ costs?.records ?? 0 }} 条计费记录</span></div>
|
||||
<div class="stats" style="grid-template-columns:repeat(2,1fr);margin-bottom:12px">
|
||||
<div class="stat"><small>已发生成本</small><b>{{ fmtMoney(costs?.total_cost, currency) }}</b></div>
|
||||
<div class="stat"><small>待生成预估</small><b>{{ fmtMoney(costs?.estimated_pending, currency) }}</b></div>
|
||||
</div>
|
||||
<div class="tablebox" style="max-height:170px">
|
||||
<table class="tbl">
|
||||
<thead><tr><th>维度</th><th>取值</th><th class="r">金额</th><th class="r">记录数</th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="row in (costs?.by_kind || [])" :key="'k' + row.key">
|
||||
<td class="muted">任务类型</td><td>{{ statusLabel(row.key) }}</td>
|
||||
<td class="r mono">{{ fmtMoney(row.cost, currency) }}</td><td class="r mono">{{ row.count }}</td></tr>
|
||||
<tr v-for="row in (costs?.by_provider || [])" :key="'p' + row.key">
|
||||
<td class="muted">Provider</td><td class="mono">{{ row.key }}</td>
|
||||
<td class="r mono">{{ fmtMoney(row.cost, currency) }}</td><td class="r mono">{{ row.count }}</td></tr>
|
||||
<tr v-for="row in (costs?.by_model || [])" :key="'m' + row.key">
|
||||
<td class="muted">模型</td><td class="mono">{{ row.key }}</td>
|
||||
<td class="r mono">{{ fmtMoney(row.cost, currency) }}</td><td class="r mono">{{ row.count }}</td></tr>
|
||||
<tr v-if="!costs?.by_model?.length"><td colspan="4" class="muted" style="text-align:center;padding:16px;line-height:1.7">
|
||||
暂无计费明细:本项目使用自建模型,但未在模型管理中心配置单价,服务端因此不会写入计费记录;
|
||||
「待生成预估」只统计排队中 / 执行中 / 已规划的任务,全部跑完后自然归零。<br />
|
||||
可量化的投入见下方<b>生成记录</b>({{ costs?.generations?.count ?? 0 }} 次调用 / {{ (costs?.generations?.seconds ?? 0).toFixed(1) }} 秒)。
|
||||
<router-link class="link" to="/models">去配置模型单价 ↗</router-link></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<!-- ===== 成片列表 ===== -->
|
||||
<section class="panel">
|
||||
<div class="panel-head"><div><small class="eyebrow">EXPORTS</small><h2 title="点「▶ 预览」在统一预览器中播放,多份成片可用左右方向键连续比对、Esc 关闭;出片参数 H.264 high profile · yuv420p · AAC 48kHz 双声道 · faststart,逐预设调整 CRF 与 x264 preset。">成片记录</h2></div>
|
||||
<span class="muted">媒体由后端 <span class="mono">/media</span> 直出,下载走 <span class="mono">/api/exports/:id/download</span></span></div>
|
||||
<div class="tablebox" style="max-height:420px">
|
||||
<table class="tbl">
|
||||
<thead><tr><th class="c">#</th><th>名称 / 预设</th><th>状态</th><th class="c">规格</th><th class="r">时长</th><th class="r">大小</th><th class="r">耗时</th><th>校验和</th><th class="r">操作</th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="rec in exportList" :key="rec.id">
|
||||
<td class="c mono">{{ rec.id }}</td>
|
||||
<td><div class="row" style="align-items:flex-start;gap:9px;flex-wrap:nowrap">
|
||||
<MediaThumb :item="exportItems[exportItems.findIndex((m) => m.raw?.id === rec.id)]" size="xs" width="60px"
|
||||
:queue="exportItems" :index="exportItems.findIndex((m) => m.raw?.id === rec.id)" :radius="5" />
|
||||
<div class="grow"><b>{{ rec.name }}</b><div class="muted mono">{{ rec.preset }} · timeline#{{ rec.timeline_id }} · task#{{ rec.task_id || '—' }}</div>
|
||||
<div v-if="rec.error_message" class="error">{{ rec.error_message }}</div></div></div></td>
|
||||
<td><span :class="statusClass(rec.status)">{{ statusLabel(rec.status) }}</span>
|
||||
<div v-if="rec.subtitle_burned" class="subline" style="display:block"><span class="tag info">已烧字幕</span></div></td>
|
||||
<td class="c mono">{{ rec.width || '?' }}×{{ rec.height || '?' }}<span v-if="rec.fps"> @{{ rec.fps }}</span></td>
|
||||
<td class="r mono">{{ fmtMs(rec.duration_ms) }}</td>
|
||||
<td class="r mono">{{ fmtBytes(rec.size_bytes) }}</td>
|
||||
<td class="r mono muted">{{ rec.elapsed_ms ? (rec.elapsed_ms / 1000).toFixed(1) + 's' : '—' }}</td>
|
||||
<td class="mono muted" :title="rec.checksum ? '完整校验和为文件 SHA-256 前 32 位(上传超过 16MB 时按流式截断计算)' : '未记录校验和'">{{ (rec.checksum || '').slice(0, 10) || '—' }}</td>
|
||||
<td class="r">
|
||||
<div class="row" style="justify-content:flex-end">
|
||||
<button v-if="rec.status === 'succeeded'" class="outline tiny" @click="previewExport(rec)">▶ 预览</button>
|
||||
<a v-if="rec.status === 'succeeded'" class="link" :href="download(rec)">下载 ↗</a>
|
||||
<button v-else-if="rec.task_id && ['failed', 'cancelled'].includes(rec.status)" class="outline tiny" @click="retryExport(rec)">重试</button>
|
||||
<span v-else class="muted">—</span>
|
||||
</div></td>
|
||||
</tr>
|
||||
<tr v-if="!exportList.length"><td colspan="9" class="muted" style="text-align:center;padding:22px">还没有成片。先在时间线页通过交付预检,再回到这里出片。</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ===== 生成记录 ===== -->
|
||||
<section class="panel">
|
||||
<div class="panel-head"><div><small class="eyebrow">GENERATION LOG</small><h2>生成记录(可复现)</h2></div>
|
||||
<div class="row"><span class="muted">{{ generations.length }} 条</span>
|
||||
<button class="outline tiny" @click="showAllCost = !showAllCost">{{ showAllCost ? '收起明细' : '展开计费明细' }}</button></div></div>
|
||||
<div class="tablebox" style="max-height:360px">
|
||||
<table class="tbl">
|
||||
<thead><tr><th class="c">#</th><th>镜头 / 类型</th><th>Provider / 模型</th><th>提示词</th><th class="r">时长</th><th class="r">成本</th><th class="c">尝试</th><th class="c">时间</th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="g in generations" :key="g.id">
|
||||
<td class="c mono">{{ g.id }}</td>
|
||||
<td class="mono">shot#{{ g.shot_id || '—' }}<div class="muted">{{ statusLabel(g.kind) }}</div></td>
|
||||
<td class="mono muted">{{ g.provider }}/{{ g.model }}</td>
|
||||
<td class="wrap">{{ (g.prompt || '').slice(0, 130) }}<span v-if="(g.prompt || '').length > 130">…</span>
|
||||
<div v-if="g.params && Object.keys(g.params).length" class="muted mono">{{ JSON.stringify(g.params).slice(0, 120) }}</div>
|
||||
<div v-if="g.asset_paths?.length" class="muted mono">参考素材 {{ g.asset_paths.length }} 个 · job {{ g.provider_job_id || '—' }}</div></td>
|
||||
<td class="r mono">{{ fmtSeconds(g.duration_seconds) }}</td>
|
||||
<td class="r mono">{{ fmtMoney(g.cost, g.currency || currency) }}</td>
|
||||
<td class="c mono">{{ g.attempts }}</td>
|
||||
<td class="c mono muted" :title="fmtTime(g.created_at)">{{ fmtAgo(g.created_at) }}</td>
|
||||
</tr>
|
||||
<tr v-if="!generations.length"><td colspan="8" class="muted" style="text-align:center;padding:22px">暂无生成记录。</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div v-if="showAllCost && costItems.length" class="tablebox" style="max-height:280px;margin-top:12px">
|
||||
<table class="tbl">
|
||||
<thead><tr><th class="c">#</th><th>类型</th><th>Provider / 模型</th><th class="r">数量</th><th class="r">单价</th><th class="r">金额</th><th class="c">时间</th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="it in shownCostItems" :key="it.id">
|
||||
<td class="c mono">{{ it.id }}</td><td>{{ statusLabel(it.kind) }}</td>
|
||||
<td class="mono muted">{{ it.provider }}/{{ it.model }}</td>
|
||||
<td class="r mono">{{ it.quantity }} {{ it.unit }}</td>
|
||||
<td class="r mono">{{ fmtMoney(it.unit_price, it.currency || currency) }}</td>
|
||||
<td class="r mono">{{ fmtMoney(it.cost, it.currency || currency) }}</td>
|
||||
<td class="c mono muted">{{ fmtTime(it.created_at) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.subline { display: block; margin-top: 3px; }
|
||||
.th-sub { font-weight: 400; letter-spacing: 0; color: var(--c-text-faint); font-size: 10px; margin-top: 2px }
|
||||
</style>
|
||||
|
|
@ -1,345 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import * as api from '../../api'
|
||||
import { notify, pctx, refresh } from '../../project'
|
||||
import { fmtAgo, fmtMoney, statusClass, statusLabel } from '../../format'
|
||||
import { store } from '../../store'
|
||||
import FSelect from '../../components/FSelect.vue'
|
||||
import AutoRefresh from '../../components/AutoRefresh.vue'
|
||||
|
||||
const route = useRoute()
|
||||
const error = ref('')
|
||||
const busy = ref('')
|
||||
const plan = ref<any>(null)
|
||||
const queue = ref<any>(null)
|
||||
const tasks = ref<any[]>([])
|
||||
/** 任务状态枚举只认后端 /api/meta(TaskStatus.ALL):状态机加一档,筛选就该跟着长,
|
||||
* 不能再靠这里抄一遍 —— 抄漏的那档会在列表里出现却筛不出来。 */
|
||||
const taskStatusOptions = computed<string[]>(
|
||||
() => (store.meta?.task_statuses as string[])
|
||||
|| ['planned', 'queued', 'running', 'retrying', 'waiting_review', 'succeeded', 'failed', 'cancelled', 'skipped'])
|
||||
const statusFilter = ref('')
|
||||
const drain = ref(true)
|
||||
|
||||
const opts = reactive({ shot_ids: [] as number[], force: false, allow_unready: false, priority: 5, with_voiceover: true })
|
||||
const dispatchOpts = reactive({ limit: 32, timeout: 900 })
|
||||
const counts = computed(() => queue.value?.counts || {})
|
||||
/** 执行方式是平台内部实现细节,界面只说人话:任务现在怎么跑、什么时候能看到结果 */
|
||||
const EXEC_LABEL: Record<string, string> = { inline: '平台内即时执行', celery: '后台任务队列' }
|
||||
const executorLabel = computed(() => {
|
||||
const e = queue.value?.executor
|
||||
return e ? (EXEC_LABEL[e] || e) : '未知'
|
||||
})
|
||||
const activeCount = computed(() => ['queued', 'running', 'retrying', 'planned'].reduce((sum, k) => sum + (counts.value[k] || 0), 0))
|
||||
/** 心跳停更的「进行中」:执行体可能已经没了(服务被杀 / 平台热重载),界面必须说破。 */
|
||||
const staleTasks = computed(() => tasks.value.filter((t: any) => t.stale))
|
||||
const livenessLabel = computed(() => {
|
||||
const sec = Number(tasks.value.find((t: any) => t.stale)?.stale_after_seconds || 0)
|
||||
return sec >= 60 ? `${Math.round(sec / 60)} 分钟` : `${sec} 秒`
|
||||
})
|
||||
|
||||
/** 心跳年龄说成人话:「12 分钟」比「742 秒」更能判断该不该干预。 */
|
||||
function fmtAge(sec?: number | null) {
|
||||
if (sec === null || sec === undefined) return '从未心跳'
|
||||
if (sec < 60) return `${sec} 秒`
|
||||
const m = Math.round(sec / 60)
|
||||
return m < 60 ? `${m} 分钟` : `${Math.floor(m / 60)} 小时 ${m % 60} 分`
|
||||
}
|
||||
const enqueueable = computed(() => (plan.value?.shots || []).filter((s: any) => s.action !== 'skip'))
|
||||
const voiceoverable = computed(() => (plan.value?.voiceovers || []).filter((v: any) => v.action !== 'skip'))
|
||||
/** 清单动作:后端是三态 enqueue / skip / needs_attention,别把「阻塞」显示成「跳过」 */
|
||||
const ACTION_LABELS: Record<string, string> = {
|
||||
enqueue: '待入队', skip: '跳过', needs_attention: '预检阻塞'
|
||||
}
|
||||
const actionLabel = (a: string) => ACTION_LABELS[a] || a || '—'
|
||||
|
||||
async function load(silent = true) {
|
||||
if (!pctx.id) return
|
||||
if (!silent) busy.value = '读取队列'
|
||||
try {
|
||||
const [pl, qu, tk] = await Promise.all([
|
||||
// 清单必须按当前这几个开关去问后端:后端算 skip/enqueue 看的正是 force/allow_unready。
|
||||
// 以前固定不带 force 去读,已生成或已审核合格的镜头永远显示「跳过」,
|
||||
// 加上下面 skip 行不许勾选,用户从分镜点「重新生成」过来就一个都选不动。
|
||||
api.get(`/api/projects/${pctx.id}/tasklist`,
|
||||
{ force: opts.force, allow_unready: opts.allow_unready }),
|
||||
api.get(`/api/projects/${pctx.id}/queue`),
|
||||
api.get('/api/tasks', { project_id: pctx.id, status: statusFilter.value }),
|
||||
])
|
||||
plan.value = pl.plan
|
||||
queue.value = qu
|
||||
tasks.value = tk.tasks || []
|
||||
error.value = ''
|
||||
} catch (exc: any) { error.value = exc.message }
|
||||
finally { busy.value = '' }
|
||||
}
|
||||
|
||||
async function run(label: string, fn: () => Promise<any>, message?: (res: any) => string) {
|
||||
busy.value = label
|
||||
error.value = ''
|
||||
try {
|
||||
const res = await fn()
|
||||
const text = message ? message(res) : ''
|
||||
if (text) notify(text)
|
||||
await Promise.all([load(), refresh()])
|
||||
return res
|
||||
} catch (exc: any) { error.value = exc.message; return null }
|
||||
finally { busy.value = '' }
|
||||
}
|
||||
|
||||
const enqueue = () => run('生成任务并入队', () => api.post(`/api/projects/${pctx.id}/tasks`, {
|
||||
shot_ids: opts.shot_ids.length ? opts.shot_ids : null, force: opts.force, allow_unready: opts.allow_unready,
|
||||
priority: opts.priority, with_voiceover: opts.with_voiceover, actor: 'studio'
|
||||
}), (r) => `已入队 ${r?.created?.count ?? 0} 个任务(其中配音 ${(r?.created?.voiceovers || []).length},`
|
||||
+ `跳过 ${(r?.created?.skipped || []).length} —— 跳过原因见清单「动作」列` + blockedNote(r))
|
||||
|
||||
const buildVoiceover = () => run('生成配音任务', () => api.post(`/api/projects/${pctx.id}/voiceover`, {
|
||||
shot_ids: null, only_missing: true, priority: 4
|
||||
}), (r) => `已创建 ${r?.count ?? 0} 条配音任务`)
|
||||
|
||||
const doDispatch = () => run(drain.value ? '派发并排空队列' : '派发任务', () => api.post(`/api/projects/${pctx.id}/dispatch`, {
|
||||
limit: dispatchOpts.limit, drain: drain.value, timeout: dispatchOpts.timeout
|
||||
}), (r) => drain.value
|
||||
? `本轮派发 ${r?.dispatched?.count ?? 0} 个,排空期间跑完 `
|
||||
+ `${r?.drained?.completed_during_drain ?? 0} 个(终态累计 ${r?.drained?.completed ?? 0})`
|
||||
+ (r?.drained?.remaining ? `,仍在队列 ${r.drained.remaining} 个` : ',队列已清空')
|
||||
+ (r?.drained?.timed_out ? '(等待超时,可加大「排空等待」或再点一次)' : '')
|
||||
+ (r?.drained?.stalled
|
||||
? `;已停滞:${(r.drained.stalled_detail?.blocked || []).map((b: any) => `${b.provider_model} ${b.reason}`).join(';')}`
|
||||
: '')
|
||||
+ blockedNote(r)
|
||||
: `已派发 ${r?.dispatched?.count ?? 0} 个任务${blockedNote(r)}`)
|
||||
|
||||
const retryFailed = () => run('重排失败任务', () => api.post(`/api/projects/${pctx.id}/tasks/retry-failed`, { reset_attempts: true }), (r) => `重新入队 ${r?.count ?? 0} 个失败任务`)
|
||||
const cancelActive = () => run('取消进行中的任务', () => api.post(`/api/projects/${pctx.id}/tasks/cancel-active`, { reason: '人工在调度中心取消' }), (r) => `已取消 ${r?.count ?? 0} 个任务`)
|
||||
const resume = () => run('断点续跑', () => api.post(`/api/projects/${pctx.id}/resume`, {}), (r) => `恢复中断任务 ${r?.resume?.count ?? 0} 个,本进程已接手 ${(r?.recovered_here || []).length} 个`)
|
||||
|
||||
/** 派发/入队返回的 blocked[]:模型停用或并发·RPM 额度用尽时说明「为什么没动」 */
|
||||
function blockedNote(r: any) {
|
||||
const blocked = r?.dispatched?.blocked || []
|
||||
return blocked.length ? `;${blocked.length} 个模型暂不可派发:`
|
||||
+ blocked.map((b: any) => `${b.provider_model}(${b.reason})`).join(';') : ''
|
||||
}
|
||||
|
||||
const retryTask = (t: any) => run('重试任务', () => api.post(`/api/tasks/${t.id}/retry`, {}), () => `任务 #${t.id} 已重新入队`)
|
||||
const cancelTask = (t: any) => run('取消任务', () => api.post(`/api/tasks/${t.id}/cancel`, { reason: '人工取消' }), () => `任务 #${t.id} 已取消`)
|
||||
|
||||
function toggleShot(id: number) {
|
||||
const i = opts.shot_ids.indexOf(id)
|
||||
if (i >= 0) opts.shot_ids.splice(i, 1)
|
||||
else opts.shot_ids.push(id)
|
||||
}
|
||||
|
||||
let booting = false
|
||||
/** 勾选「强制重建 / 放行未就绪」后清单要重算,否则「动作」列还是按旧开关显示跳过 */
|
||||
watch(() => [opts.force, opts.allow_unready], () => { if (!booting) void load() })
|
||||
|
||||
onMounted(async () => {
|
||||
// 分镜工作台卡片上的「▷ 生成 / ↻ 重生成」带 ?shot= 过来时,预勾选该镜头,避免误伤整批。
|
||||
// 带 force=1 说明来意就是**重做这一镜**:它的产物已经存在,后端默认判 skip,
|
||||
// 不先把强制打开,这一镜在清单里根本选不动。
|
||||
const want = Number(route.query.shot || 0)
|
||||
booting = true
|
||||
try {
|
||||
if (want && Number(route.query.force || 0)) opts.force = true
|
||||
await load(false)
|
||||
} finally { booting = false }
|
||||
const row = (plan.value?.shots || []).find((s: any) => s.shot_id === want)
|
||||
if (!row) return
|
||||
if (row.action === 'skip') {
|
||||
opts.shot_ids = [want]
|
||||
notify(`镜头 #${row.order_index} 暂不需要生成:${row.reason}。勾上「强制重建任务」就能只重做它`)
|
||||
} else {
|
||||
opts.shot_ids = [want]
|
||||
notify(`已勾选镜头 #${row.order_index},点「入队所选」即可只生成这一镜`)
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<div class="between" style="margin-bottom:12px">
|
||||
<div class="row">
|
||||
<span class="tag info">任务执行:{{ executorLabel }}</span>
|
||||
<span v-for="(v, k) in counts" :key="k" class="chip">{{ statusLabel(String(k)) }} {{ v }}</span>
|
||||
<span v-if="!activeCount" class="muted">队列空闲</span>
|
||||
</div>
|
||||
<div class="row">
|
||||
<span v-if="busy" class="muted"><span class="spin"></span> {{ busy }}…</span>
|
||||
<AutoRefresh :busy="!!busy" :every="4000" :paused="!activeCount" @refresh="load()" />
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="error" class="error" style="margin-bottom:12px">{{ error }}</p>
|
||||
|
||||
<!-- ===== 任务清单(图2 节点④ plan_tasks) ===== -->
|
||||
<div class="layout" style="margin-bottom:16px">
|
||||
<section class="panel">
|
||||
<div class="panel-head"><div><small class="eyebrow">PIPELINE · 生成分镜任务清单</small><h2>分镜任务清单</h2></div>
|
||||
<div class="row"><span class="muted">预计成本 {{ fmtMoney(plan?.estimated_cost, plan?.currency) }}</span>
|
||||
<button class="primary" :disabled="!!busy" @click="enqueue">▶ 入队所选 / 全部待生成</button></div></div>
|
||||
<div class="chipbar chips">
|
||||
<span class="chip">待入队 {{ enqueueable.length }}</span>
|
||||
<span class="chip">配音待生成 {{ voiceoverable.length }}</span>
|
||||
<span class="chip">已排队 {{ plan?.queued_count || 0 }}</span>
|
||||
<span class="chip">阻塞 {{ plan?.blocked_count || 0 }}</span>
|
||||
<span class="chip">跳过 {{ plan?.skipped_count || 0 }}</span>
|
||||
<span class="chip">预检就绪 {{ plan?.preflight?.ready || 0 }}</span>
|
||||
<span class="chip">预检告警 {{ plan?.preflight?.warnings || 0 }}</span>
|
||||
<span class="chip">预计 {{ plan?.voiceover_count || 0 }} 条配音</span>
|
||||
</div>
|
||||
<div class="tablebox" style="max-height:360px">
|
||||
<table class="tbl">
|
||||
<thead><tr><th style="width:34px" class="c">#</th><th>镜头</th><th>动作</th><th>Provider / 模型</th><th class="r">时长</th><th class="r">预估成本</th><th>说明</th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="s in plan?.shots || []" :key="s.shot_id">
|
||||
<td class="c"><input type="checkbox" :aria-label="`选择镜头 ${s.order_index}`" :checked="opts.shot_ids.includes(s.shot_id)" @change="toggleShot(s.shot_id)" :disabled="s.action === 'skip' && !opts.force"></td>
|
||||
<td><b>#{{ s.order_index }}</b> {{ s.title }}<div class="muted mono">shot#{{ s.shot_id }}</div></td>
|
||||
<td><span class="tag" :class="s.action === 'enqueue' ? 'ok' : (s.action === 'needs_attention' ? 'bad' : 'warn')">{{ actionLabel(s.action) }}</span></td>
|
||||
<td class="mono muted">{{ s.provider || '—' }} / {{ s.model || '默认' }}</td>
|
||||
<td class="r mono">{{ s.duration }}s</td>
|
||||
<td class="r mono">{{ fmtMoney(s.estimated_cost) }}</td>
|
||||
<td class="wrap muted">{{ s.reason }}<span v-if="s.blocking?.length" class="error"> 阻塞:{{ s.blocking.join(';') }}</span></td>
|
||||
</tr>
|
||||
<tr v-for="v in plan?.voiceovers || []" :key="'v' + v.shot_id">
|
||||
<td class="c">🔊</td>
|
||||
<td><b>#{{ v.order_index }}</b> 配音<div class="muted mono">shot#{{ v.shot_id }}</div></td>
|
||||
<td><span class="tag" :class="v.action !== 'skip' ? 'ok' : ''">{{ v.action !== 'skip' ? '待配音' : '跳过' }}</span></td>
|
||||
<td class="mono muted">TTS</td>
|
||||
<td class="r mono">{{ v.chars }} 字</td>
|
||||
<td class="r mono">—</td>
|
||||
<td class="wrap muted">{{ v.reason }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<h3>调度控制</h3>
|
||||
<div class="ctlbar">
|
||||
<label class="check"><input v-model="opts.with_voiceover" type="checkbox" />入队时一并排配音任务</label>
|
||||
<label class="check"><input v-model="opts.allow_unready" type="checkbox" />放行预检未通过的镜头(默认只跳过它们)</label>
|
||||
<label class="check"><input v-model="opts.force" type="checkbox"
|
||||
title="忽略「产物已存在 / 已审核合格 / 已在队列」这三类跳过判定,也忽略幂等键。要单独重做某一镜就得勾它"
|
||||
>强制重建任务(忽略幂等,可重做已生成的镜头)</label>
|
||||
<label class="fld narrow"><span>优先级</span><input v-model.number="opts.priority" type="number" min="0" max="9" aria-label="任务优先级" /></label>
|
||||
</div>
|
||||
<div class="divider"></div>
|
||||
<div class="ctlbar">
|
||||
<label title="勾选「派发后同步排空」会一直等到任务执行结束再返回,适合小批量验证;不勾选时任务留在队列后台执行,页面自动刷新进度。" class="check"><input v-model="drain" type="checkbox" />派发后同步排空(等任务跑完再返回)</label>
|
||||
<label class="fld narrow"><span>单次派发上限</span><input v-model.number="dispatchOpts.limit" type="number" min="1" max="256" aria-label="单次派发上限" /></label>
|
||||
<label class="fld narrow"><span>排空等待(秒)</span><input v-model.number="dispatchOpts.timeout" type="number" min="30" max="7200" aria-label="排空等待秒数" /></label>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button class="primary" :disabled="!!busy" @click="doDispatch">⇶ {{ drain ? '派发并排空队列' : '只派发' }}</button>
|
||||
<button class="secondary" :disabled="!!busy" @click="buildVoiceover">🔊 批量生成配音</button>
|
||||
</div>
|
||||
<div class="divider"></div>
|
||||
<div class="small-label" style="margin-top:0">异常处理</div>
|
||||
<div class="actions">
|
||||
<button class="outline" :disabled="!!busy" @click="retryFailed">↺ 重排全部失败任务</button>
|
||||
<button class="outline" :disabled="!!busy" @click="resume">⏱ 断点续跑(恢复中断)</button>
|
||||
<button class="outline" :disabled="!!busy" @click="cancelActive">✕ 取消进行中任务</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<!-- ===== 队列与容量 ===== -->
|
||||
<div class="layout" style="margin-bottom:16px">
|
||||
<section class="panel">
|
||||
<div class="panel-head"><div><small class="eyebrow">QUEUE MATRIX</small><h2>队列状态</h2></div></div>
|
||||
<div class="tablebox" style="max-height:none">
|
||||
<table class="tbl">
|
||||
<thead><tr><th>任务类型</th><th v-for="st in ['planned','queued','running','retrying','succeeded','failed','cancelled','skipped']" :key="st" class="c">{{ statusLabel(st) }}</th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="kind in ['generate_shot','voiceover','qc_shot','compose','import','asset']" :key="kind">
|
||||
<td><b>{{ statusLabel(kind) }}</b></td>
|
||||
<td v-for="st in ['planned','queued','running','retrying','succeeded','failed','cancelled','skipped']" :key="st" class="c mono">
|
||||
<span :class="{ 'tag ok': (queue?.matrix || []).find((m: any) => m.kind === kind && m.status === st) }">{{ (queue?.matrix || []).find((m: any) => m.kind === kind && m.status === st)?.count || '' }}</span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-head"><div><small class="eyebrow">CAPACITY</small><h2>模型并发与限流</h2></div></div>
|
||||
<div class="tablebox" style="max-height:none">
|
||||
<table class="tbl">
|
||||
<thead><tr><th>Provider / 模型</th><th class="c">运行</th><th class="c">排队</th><th class="c">槽位</th><th class="c">RPM 余量</th><th>状态</th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="c in queue?.capacity || []" :key="c.provider + c.model + c.media_type">
|
||||
<td class="mono">{{ c.provider }} / {{ c.model || '默认' }}<div class="muted">{{ c.media_type }}</div></td>
|
||||
<td class="c mono">{{ c.running }}</td>
|
||||
<td class="c mono">{{ c.queued }}</td>
|
||||
<td class="c mono">{{ c.slots }}/{{ c.concurrency_limit }}</td>
|
||||
<td class="c mono">{{ c.rpm_headroom }}</td>
|
||||
<td><span class="tag" :class="!c.enabled ? 'bad' : c.saturated ? 'warn' : 'ok'">{{ !c.enabled ? '已停用' : c.saturated ? '已满负荷' : '可用' }}</span></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<!-- ===== 任务列表 ===== -->
|
||||
<section class="panel" style="margin-bottom:16px">
|
||||
<div class="panel-head"><div><small class="eyebrow">TASKS</small><h2>任务执行明细({{ tasks.length }})
|
||||
<span v-if="staleTasks.length" class="tag warn" style="margin-left:8px">{{ staleTasks.length }} 条心跳已停止</span></h2>
|
||||
<p v-if="staleTasks.length" class="linehint">这些任务的执行体超过 {{ livenessLabel }}没有报活:多半是那台机器上的模型服务或平台进程中断过。
|
||||
产物与断点都留着,平台回收后会自动续跑;着急就点上方「断点续跑」立即处理。</p></div>
|
||||
<div class="ctlbar"><label class="fld narrow"><span>状态</span><FSelect v-model="statusFilter" size="sm" aria-label="任务状态筛选" @change="load(false)">
|
||||
<option value="">全部状态</option>
|
||||
<option v-for="s in taskStatusOptions" :key="s" :value="s">{{ statusLabel(s) }}</option>
|
||||
</FSelect></label></div></div>
|
||||
<div class="tablebox">
|
||||
<table class="tbl">
|
||||
<thead><tr><th>ID</th><th>任务</th><th>镜头</th><th>后端</th><th class="c">尝试</th><th class="c">进度</th><th class="r">耗时</th><th>状态</th><th>错误 / 检查点</th><th class="r">操作</th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="t in tasks" :key="t.id">
|
||||
<td class="mono">#{{ t.id }}</td>
|
||||
<td>{{ t.name }}<div class="muted mono">{{ statusLabel(t.kind) }} · {{ t.stage }}</div></td>
|
||||
<td class="mono">{{ t.shot_id ? '#' + t.shot_id : (t.timeline_id ? `时间线#${t.timeline_id}` : '—') }}</td>
|
||||
<td class="mono muted">{{ statusLabel(t.execution_backend) }}<div v-if="t.worker_id" class="muted">{{ t.worker_id }}</div></td>
|
||||
<td class="c mono">{{ t.attempts }}/{{ t.max_attempts }}</td>
|
||||
<td><div class="bar"><i :style="{ width: Math.round((t.progress || 0) * 100) + '%' }"></i></div></td>
|
||||
<td class="r mono">{{ t.elapsed_ms ? (t.elapsed_ms / 1000).toFixed(1) + 's' : (t.queue_wait_ms ? `排队 ${(t.queue_wait_ms / 1000).toFixed(1)}s` : '—') }}</td>
|
||||
<td><span :class="statusClass(t.status)">{{ statusLabel(t.status) }}</span>
|
||||
<div class="muted">{{ fmtAgo(t.updated_at) }}</div>
|
||||
<div v-if="t.stale" class="stalewarn">⚠ 心跳已停止 {{ fmtAge(t.heartbeat_age_seconds) }}:可能已中断,不会永远转圈</div></td>
|
||||
<td class="wrap"><span v-if="t.error_message" class="error">{{ t.error_code }} {{ t.error_message }}</span>
|
||||
<div v-if="t.checkpoint?.last_note" class="muted">{{ t.checkpoint.last_note }}</div>
|
||||
<div v-else-if="Object.keys(t.checkpoint || {}).length" class="muted mono">checkpoint: {{ JSON.stringify(t.checkpoint).slice(0, 90) }}</div>
|
||||
<a v-if="t.output_url" class="link" :href="t.output_url" target="_blank">产物 ↗</a></td>
|
||||
<td class="r">
|
||||
<div class="row" style="justify-content:flex-end">
|
||||
<button v-if="['failed', 'cancelled'].includes(t.status)" class="outline tiny" @click="retryTask(t)">重试</button>
|
||||
<button v-if="['queued','running','retrying','planned'].includes(t.status)" class="outline tiny" @click="cancelTask(t)">取消</button>
|
||||
<span v-else class="muted">—</span>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-if="!tasks.length"><td colspan="10" class="muted" style="text-align:center;padding:22px">暂无任务,先在上方生成任务清单并入队。</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel model-handoff">
|
||||
<div>
|
||||
<small class="eyebrow">MODEL REGISTRY</small>
|
||||
<h2>模型配置已迁移至独立管理中心</h2>
|
||||
</div>
|
||||
<router-link title="统一维护大模型、图像、视频与声音模型的适配器、默认项、并发、限流、价格、能力与连接探测。调度中心只负责项目任务编排与执行。" class="primary model-handoff-link" to="/models">打开模型管理中心 →</router-link>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.stalewarn { margin-top:4px; font-size:11px; line-height:1.45; color:#e2a03f; max-width:190px; }
|
||||
.model-handoff { display:flex; justify-content:space-between; align-items:center; gap:20px; }
|
||||
.model-handoff-link { text-decoration:none; white-space:nowrap; }
|
||||
@media (max-width:700px){ .model-handoff{ flex-direction:column; align-items:flex-start; } }
|
||||
</style>
|
||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue