feat(short-drama-agent-front): 新增视觉风格骨架屏并优化参考图添加

This commit is contained in:
GJ committed 2026-10-11 00:01:24 +08:00
1 parent 3cc65aa056
commit 519b956808
11 files changed
+621 -242

No files matched your search

+7 -10
View File
@@ -16,6 +16,7 @@ import { projectGenerationRevisionKey } from '../generation-config/context'
import WorkflowExecutionPanel from '../workflows/WorkflowExecutionPanel.vue'
import CreateDramaSkeleton from '../create-drama/CreateDramaSkeleton.vue'
import BreakdownSkeleton from '../breakdown/BreakdownSkeleton.vue'
import VisualStyleSkeleton from '../visual-style/VisualStyleSkeleton.vue'
/** 项目标题只保留名称;下游工作区在剧本完成前不挂载,直接链接也无法越过限制。 */
const route = useRoute()
@@ -103,14 +104,8 @@ const currentAccess = computed(() => {
return section ? stageAccess.sections.value[section] : null
})
const isCreation = computed(() => currentSection.value === 'create-drama')
/** 剧本首次读取或切换项目时显示骨架;刷新已有项目时保留正文与阅读位置。 */
const isCreationInitialLoading = computed(
() => isCreation.value && context.loading.value && context.project.value?.id !== id.value
)
/** 拆解页只在首次读取或切换项目时占位,刷新已有结果时保留内容与分类。 */
const isBreakdownInitialLoading = computed(
() => currentSection.value === 'breakdown' && context.loading.value && context.project.value?.id !== id.value
)
/** 各工作区共用首次读取判定;切换项目显示占位,刷新已有项目保留内容。 */
const isProjectInitialLoading = computed(() => context.loading.value && context.project.value?.id !== id.value)
type OperationGuide = {
title: string
description: string
@@ -311,9 +306,11 @@ onScopeDispose(() => {
>
</EmptyState>
<!-- 以下是剧本创作首次读取的骨架屏模块 -->
<CreateDramaSkeleton v-else-if="isCreationInitialLoading" />
<CreateDramaSkeleton v-else-if="isProjectInitialLoading && isCreation" />
<!-- 以下是剧本拆解首次读取的骨架屏模块 -->
<BreakdownSkeleton v-else-if="isBreakdownInitialLoading" />
<BreakdownSkeleton v-else-if="isProjectInitialLoading && currentSection === 'breakdown'" />
<!-- 以下是视觉风格项目首次读取的骨架屏模块 -->
<VisualStyleSkeleton v-else-if="isProjectInitialLoading && currentSection === 'visual-style'" />
<NSpin v-else-if="context.loading.value" class="workspace-loading" description="正在读取项目内容…" />
</div>
</section>
+39 -11
View File
@@ -1,6 +1,5 @@
<script setup lang="ts">
import WorkspacePage from '../../components/ui/WorkspacePage.vue'
import DetailDisclosure from '../../components/ui/DetailDisclosure.vue'
import { NAlert, NButton } from 'naive-ui'
import { LoaderCircle, LockKeyhole, LockKeyholeOpen, Palette, TriangleAlert } from '@lucide/vue'
import { computed, ref } from 'vue'
@@ -13,9 +12,11 @@ import { visualStyleApi } from './api'
import type { AddStyleImageInput, SaveVisualStyleInput, VisualStyle, VisualStyleImage } from './types'
import StyleEditor from './components/StyleEditor.vue'
import StyleImages from './components/StyleImages.vue'
import VisualStyleSkeleton from './VisualStyleSkeleton.vue'
/** 项目视觉风格工作区:文本编辑、锁定和风格图记录分开管理。 */
const { projectId, blocked } = useProjectMutationGuard()
const { projectId, operation, blocked } = useProjectMutationGuard()
/** 项目阶段就绪状态沿用父布局的真实响应。 */
const projectContext = useProjectContext()
/** 风格页仅在进入、切换项目或显式刷新时读取。 */
const query = useQuery(projectId, async (id, signal) => {
@@ -23,11 +24,23 @@ const query = useQuery(projectId, async (id, signal) => {
assertProject(style, id)
return { style }
})
/** 已读取的视觉风格,接口返回空值时允许首次人工创建。 */
const style = computed(() => query.data.value?.style ?? null)
/** 仅首读与项目切换显示骨架,刷新已有风格时保留编辑草稿。 */
const initialLoading = computed(() => query.loading.value && !query.data.value)
/** 查询失败或项目活动锁生效时禁止写入。 */
const disabled = computed(() => blocked.value || !!query.error.value || !query.data.value)
/** 保存成功后重建编辑器,确保草稿对应已确认的响应。 */
const editorRevision = ref(0)
/** 添加图片成功后重建组件,关闭弹窗并清空草稿。 */
const imageRevision = ref(0)
/** 仅添加参考图期间锁定添加弹窗,查询失败仍可关闭。 */
const addingImage = computed(() => operation.value.pending && operation.value.label === '添加风格参考图')
/** 添加失败的真实接口反馈同时显示在弹窗中,保留来源与设置。 */
const imageAddError = computed(() => (operation.value.label === '添加风格参考图' ? operation.value.error : ''))
/** 未保存的风格修改用于阻止 AI 覆盖。 */
const dirty = ref(false)
/** 后端确认视觉风格准备好后提供下一步入口。 */
const nextReady = computed(() => projectContext.stageReadiness.value?.visualStyle.ready === true)
/** 状态是只读说明,与操作按钮分组;读取失败不能被误报成尚未创建。 */
@@ -91,9 +104,12 @@ async function writeImage(label: string, action: (id: string) => Promise<VisualS
await query.refresh()
}
/** 登记已存在的图片地址,不上传文件或调用模型。 */
/**
* 添加已有项目素材或图片链接,成功后关闭添加弹窗并刷新列表。
* @param input 图片来源、应用范围、顺序及参与生成设置
*/
function addImage(input: AddStyleImageInput) {
void writeImage('登记风格参考图', id => visualStyleApi.addImage(id, input), true)
void writeImage('添加风格参考图', id => visualStyleApi.addImage(id, input), true)
}
/** 风格图启停不受文字锁定影响。 */
@@ -108,8 +124,10 @@ function removeImage(image: VisualStyleImage) {
</script>
<template>
<!-- 以下是视觉风格首次读取的完整骨架屏模块 -->
<VisualStyleSkeleton v-if="initialLoading" />
<!-- 以下是手机提示、风格工具与正文共同滚动的视觉风格工作区 -->
<WorkspacePage compact mobile-scroll class="visual-style-page"
<WorkspacePage v-else compact mobile-scroll class="visual-style-page"
><template #header>
<!-- 以下是标题、锁定状态与生成操作 -->
<div class="workspace-toolbar visual-style-toolbar">
@@ -131,7 +149,7 @@ function removeImage(image: VisualStyleImage) {
</div>
</template>
<template #notice>
<NAlert v-if="nextReady" type="success" :show-icon="false">
<NAlert v-if="nextReady && style" type="success" :show-icon="false">
视觉风格已准备好,可以继续确认人物、场景和道具的主体身份。
<RouterLink :to="`/projects/${projectId}/subject-identity`" class="text-button ml-2"
>继续主体身份 →</RouterLink
@@ -146,10 +164,16 @@ function removeImage(image: VisualStyleImage) {
<p v-if="dirty" class="mb-4 text-xs text-muted">
有未保存修改,AI 重生成暂不可用。刷新不会覆盖编辑内容;离开页面不会自动保存。
</p>
<DetailDisclosure title="风格生成规则">
AI
生成时,若项目和世界观没有明确其它人物背景,人物风格默认采用中国人物选角基线;人工填写的人物背景和角色事实优先。修改风格只影响之后的生成,旧资产不会自动更新。 </DetailDisclosure
><StyleEditor
<!-- 以下是始终显示的风格生成规则模块 -->
<section v-if="query.data.value" class="panel workspace-panel visual-style-rules">
<h3 class="font-medium">风格生成规则</h3>
<p class="mt-3 text-xs leading-6 text-muted">
AI
生成时,若项目和世界观没有明确其它人物背景,人物风格默认采用中国人物选角基线;人工填写的人物背景和角色事实优先。修改风格只影响之后的生成,旧资产不会自动更新。
</p>
</section>
<!-- 以下是风格编辑与始终展开的分类补充模块 -->
<StyleEditor
v-if="query.data.value"
:key="editorRevision"
:visual-style="style"
@@ -157,11 +181,15 @@ function removeImage(image: VisualStyleImage) {
@save="save"
@dirty="dirty = $event"
/>
<p v-else-if="query.loading.value" class="py-8 text-sm text-muted" role="status">正在读取视觉风格…</p>
<!-- 以下是读取成功后的参考图列表与添加入口模块 -->
<StyleImages
v-if="query.data.value"
:key="imageRevision"
:project-id="projectId"
:images="style?.images ?? []"
:has-style="!!style"
:adding="addingImage"
:add-error="imageAddError"
:disabled="disabled || !style"
@add="addImage"
@toggle="toggleImage"
@@ -0,0 +1,122 @@
<script setup lang="ts">
import { NSkeleton } from 'naive-ui'
import WorkspacePage from '../../components/ui/WorkspacePage.vue'
/** 占位顺序与风格表单一致,分类风格始终按单列排列。 */
const fieldHeights = [34, 128, 128, 128, 128, 96]
</script>
<template>
<WorkspacePage
compact
mobile-scroll
class="visual-style-skeleton"
role="status"
aria-label="正在读取视觉风格内容"
aria-busy="true"
>
<template #header>
<!-- 以下是固定标题、锁定状态与生成操作占位模块 -->
<div class="workspace-toolbar visual-style-skeleton-toolbar">
<h2 class="font-semibold">项目视觉风格</h2>
<div class="visual-style-skeleton-status">
<NSkeleton circle :width="16" :height="16" />
<NSkeleton :width="48" :height="12" />
<NSkeleton class="visual-style-skeleton-hint" :width="180" :height="12" />
</div>
<NSkeleton class="visual-style-skeleton-action" :width="130" :height="34" />
</div>
</template>
<div class="workspace-section-stack">
<!-- 以下是始终展开的风格生成规则占位模块 -->
<section class="panel workspace-panel visual-style-skeleton-rules">
<NSkeleton :width="96" :height="14" />
<NSkeleton :width="'94%'" :height="12" />
<NSkeleton :width="'68%'" :height="12" />
</section>
<!-- 以下是风格名称、整体风格、三类补充与硬约束占位模块 -->
<section class="panel workspace-panel visual-style-skeleton-editor">
<NSkeleton :width="64" :height="14" />
<div v-for="(height, index) in fieldHeights" :key="index" class="visual-style-skeleton-field">
<NSkeleton v-if="index === 2" :width="126" :height="14" />
<NSkeleton :width="index === 2 ? 140 : 96" :height="12" />
<NSkeleton :height="height" />
</div>
<div class="visual-style-skeleton-lock">
<NSkeleton :width="16" :height="16" />
<NSkeleton :width="'min(260px, 80%)'" :height="12" />
</div>
<NSkeleton :width="'72%'" :height="12" />
<NSkeleton :width="110" :height="34" />
</section>
<!-- 以下是参考图说明与两个添加入口占位模块,不预先展示图片数量或空状态 -->
<section class="panel workspace-panel visual-style-skeleton-images">
<NSkeleton :width="84" :height="14" />
<NSkeleton :width="'86%'" :height="12" />
<div class="visual-style-skeleton-image-fields">
<NSkeleton v-for="entry in 2" :key="entry" :width="120" :height="34" />
</div>
</section>
</div>
</WorkspacePage>
</template>
<style scoped>
/* 骨架沿用真实页面的表面、模块间距和移动端滚动边界。 */
@reference "../../styles/styles.css";
.visual-style-skeleton {
container: visual-style-skeleton-header / inline-size;
}
.visual-style-skeleton-toolbar {
@apply flex-nowrap;
}
.visual-style-skeleton-status {
@apply flex flex-1 min-w-0 items-center gap-2 overflow-hidden;
}
.visual-style-skeleton-status :deep(.n-skeleton) {
@apply shrink-0;
}
.visual-style-skeleton-action {
@apply shrink-0;
}
.visual-style-skeleton-rules,
.visual-style-skeleton-images {
@apply flex flex-col gap-3;
}
.visual-style-skeleton-editor {
@apply flex flex-col gap-5;
}
.visual-style-skeleton-field {
@apply flex flex-col gap-[9px] min-w-0;
}
.visual-style-skeleton-field > :first-child:not(:last-child) {
@apply shrink-0;
}
.visual-style-skeleton-lock {
@apply flex items-center gap-2;
}
.visual-style-skeleton-image-fields {
@apply flex flex-wrap gap-3;
}
.workspace-panel :deep(.n-skeleton) {
/* 明暗主题都保持占位条与面板之间的可见层次。 */
--n-color-start: var(--app-border) !important;
--n-color-end: var(--app-field-hover) !important;
}
@container visual-style-skeleton-header (max-width: 760px) {
.visual-style-skeleton-toolbar {
@apply flex-wrap gap-x-3 gap-y-2;
}
.visual-style-skeleton-action {
@apply mr-[calc(100%_-_130px)];
}
.visual-style-skeleton-hint {
@apply hidden;
}
}
@media (prefers-reduced-motion: reduce) {
.visual-style-skeleton :deep(.n-skeleton) {
animation: none;
}
}
</style>
@@ -2,14 +2,15 @@
import AppForm from '../../../components/ui/AppForm.vue'
import { NFormItem } from 'naive-ui'
import { stringArrayJsonRule } from '../../../lib/form-rules'
import DetailDisclosure from '../../../components/ui/DetailDisclosure.vue'
import { NButton, NCheckbox, NInput, NTag } from 'naive-ui'
import { computed, reactive, ref, watch } from 'vue'
import type { SaveVisualStyleInput, VisualStyle } from '../types'
/** 编辑草稿独立于轮询结果,刷新不会覆盖尚未保存的输入。 */
const props = defineProps<{ visualStyle: VisualStyle | null; disabled: boolean }>()
/** 保存校验后的风格配置,并向父页面同步草稿状态。 */
const emit = defineEmits<{ save: [input: SaveVisualStyleInput]; dirty: [value: boolean] }>()
/** 整体风格、分类补充和硬约束保持在同一份编辑草稿中。 */
const form = reactive({
name: '',
prompt: '',
@@ -19,7 +20,9 @@ const form = reactive({
constraints: '[]',
isLocked: false
})
/** 上次成功读取的表单快照,用于识别未保存修改。 */
const baseline = ref('')
/** 草稿变更时禁止 AI 覆盖现有输入。 */
const dirty = computed(() => JSON.stringify(form) !== baseline.value)
watch(
() => props.visualStyle,
@@ -54,18 +57,10 @@ function save() {
})
}
const rules = { constraints: stringArrayJsonRule }
const constraintsDetails = ref<InstanceType<typeof DetailDisclosure> | null>(null)
</script>
<template>
<AppForm
:model="form"
:rules="rules"
:disabled="disabled"
class="panel workspace-panel"
@invalid="constraintsDetails?.expand()"
@submit="save"
>
<AppForm :model="form" :rules="rules" :disabled="disabled" class="panel workspace-panel" @submit="save">
<fieldset :disabled="disabled" class="space-y-5">
<div class="flex flex-wrap items-center justify-between gap-3">
<h3 class="font-medium">风格说明</h3>
@@ -85,8 +80,10 @@ const constraintsDetails = ref<InstanceType<typeof DetailDisclosure> | null>(nul
:autosize="{ minRows: 3, maxRows: 12 }"
></NInput>
</NFormItem>
<DetailDisclosure ref="constraintsDetails" display-directive="show" title="分类风格与硬约束"
><div class="grid gap-5 lg:grid-cols-3">
<!-- 以下是始终展开的分类风格模块,人物、场景、道具各占一行 -->
<section class="style-category-section" aria-labelledby="style-category-heading">
<h3 id="style-category-heading" class="font-medium mb-5">分类风格与硬约束</h3>
<div class="style-category-fields grid grid-cols-1 gap-5">
<NFormItem path="characterPrompt" label="人物风格与选角背景"
><NInput
:input-props="{ 'aria-label': '人物风格与选角背景' }"
@@ -134,7 +131,7 @@ const constraintsDetails = ref<InstanceType<typeof DetailDisclosure> | null>(nul
:autosize="{ minRows: 3, maxRows: 12 }"
></NInput>
</NFormItem>
</DetailDisclosure>
</section>
<NCheckbox
:disabled="disabled"
id="style-lock"
@@ -1,123 +1,168 @@
<script setup lang="ts">
import { NButton, NCheckbox, NFormItem, NInput, NInputNumber, NSelect, type FormRules } from 'naive-ui'
import { computed, onBeforeUnmount, reactive, ref, watch } from 'vue'
import AppForm from '../../../components/ui/AppForm.vue'
import { NFormItem } from 'naive-ui'
import { fieldRule, imageUrlRule } from '../../../lib/form-rules'
import { NButton, NCheckbox, NInput, NInputNumber, NSelect } from 'naive-ui'
import { reactive, ref } from 'vue'
import { AppDialog, AssetImage } from '../../../components/ui'
import { fieldRule, imageUrlRule } from '../../../lib/form-rules'
import { referenceImageUrl } from '../../../lib/assets'
import { errorMessage } from '../../../lib/http'
import { projectAssetsApi } from '../../project-assets/api'
import type { ProjectAsset } from '../../project-assets/types'
import type { AddStyleImageInput, StyleCategory, VisualStyleImage } from '../types'
/** 风格图可关联项目资产,也保留外部地址兼容入口。 */
const props = defineProps<{ projectId: string; images: VisualStyleImage[]; disabled: boolean }>()
/** 参考图列表与添加弹窗的项目、保存状态及操作反馈。 */
interface Props {
/** 当前项目数据库编号。 */
projectId: string
/** 已保存的风格参考图记录。 */
images: VisualStyleImage[]
/** 当前项目是否禁止写入。 */
disabled: boolean
/** 视觉风格是否已创建;未创建时必须先保存。 */
hasStyle?: boolean
/** 添加请求执行期间锁定弹窗关闭和重复提交。 */
adding?: boolean
/** 当前添加请求返回的错误。 */
addError?: string
}
/** 页内只展示记录与入口,来源和生成设置统一在弹窗内填写。 */
const props = withDefaults(defineProps<Props>(), { hasStyle: true, adding: false, addError: '' })
/** 添加、启停与移除分别交由父页面调用正式接口。 */
const emit = defineEmits<{
add: [input: AddStyleImageInput]
toggle: [image: VisualStyleImage]
remove: [image: VisualStyleImage]
}>()
const form = reactive({ imageUrl: '', category: 'overall' as StyleCategory, sortOrder: 0, enabled: true })
/** 两种来源保留独立输入,成功后由父页面重建组件清空草稿。 */
const form = reactive({
imageUrl: '',
projectAssetId: '',
category: 'overall' as StyleCategory,
sortOrder: 0,
enabled: true
})
/** 二次确认移除的记录编号。 */
const confirmingId = ref('')
const assetPickerOpen = ref(false)
/** 当前添加入口决定来源区域和校验规则。 */
const source = ref<'asset' | 'link'>('asset')
/** 共用弹窗仅呈现当前入口对应的来源表单。 */
const addOpen = ref(false)
/** 当前弹窗是否已尝试提交,避免重新打开时展示旧操作反馈。 */
const attempted = ref(false)
/** 资产读取期间显示独立加载状态。 */
const assetLoading = ref(false)
/** 资产查询错误可在原弹窗重试。 */
const assetError = ref('')
/** 仅存放当前项目的图片素材。 */
const assets = ref<ProjectAsset[] | null>(null)
const selectedAssetId = ref('')
/** 关闭、重试或切换项目时取消旧资产查询。 */
let assetController: AbortController | undefined
/** 记录卡片沿用接口分类的显示名称。 */
const categories = { overall: '整体', character: '人物', scene: '场景', prop: '道具' } as const
/** 仅通过校验后发出新增请求,输入框在失败时保留供修正。 */
/** 整体参考同时参与人物、场景和道具生成,分类参考仅用于对应范围。 */
const scopeOptions = [
{ label: '全部(人物、场景、道具)', value: 'overall' },
{ label: '人物', value: 'character' },
{ label: '场景', value: 'scene' },
{ label: '道具', value: 'prop' }
]
/** 按入口校验图片来源,资产库入口不要求填写链接。 */
const rules = computed<FormRules>(() => ({
...(source.value === 'link'
? { imageUrl: imageUrlRule }
: {
projectAssetId: fieldRule(
value => !!assets.value?.some(asset => asset.id === value),
'请选择一张项目图片',
true
)
}),
sortOrder: fieldRule(Number.isSafeInteger, '排序须为整数')
}))
/** 弹窗正文验证后再发出请求,失败时不关闭或清空表单。 */
function add() {
if (props.disabled) return
emit('add', { ...form, imageUrl: form.imageUrl.trim(), source: 'upload' })
}
/** 素材仅在用户打开选择器时读取,避免风格页首屏增加重复请求。 */
async function openAssetPicker() {
if (props.disabled) return
assetPickerOpen.value = true
assetError.value = ''
selectedAssetId.value = ''
assetLoading.value = true
try {
const rows = await projectAssetsApi.list(props.projectId)
if (rows.some(asset => asset.projectId !== props.projectId)) throw new Error('素材与当前项目不匹配。')
assets.value = rows.filter(asset => asset.type === 'image')
} catch (error) {
assetError.value = errorMessage(error)
} finally {
assetLoading.value = false
}
}
function addAsset() {
if (props.disabled || !selectedAssetId.value) return
if (props.disabled || !props.hasStyle || (source.value === 'asset' && assetLoading.value)) return
attempted.value = true
emit('add', {
projectAssetId: selectedAssetId.value,
...(source.value === 'asset' ? { projectAssetId: form.projectAssetId } : { imageUrl: form.imageUrl.trim() }),
category: form.category,
source: 'upload',
enabled: form.enabled,
sortOrder: form.sortOrder
})
assetPickerOpen.value = false
}
/** 删除只移除记录,需确认且不声称删除远程文件。 */
/**
* 打开指定图片来源的添加弹窗,资产只在进入资产库入口时读取。
* @param kind 本次图片来源
*/
function openAdd(kind: 'asset' | 'link') {
if (props.disabled || !props.hasStyle) return
source.value = kind
attempted.value = false
addOpen.value = true
if (kind === 'asset') void loadAssets()
}
/** 读取当前项目图片,忽略关闭弹窗或切换项目后返回的旧响应。 */
async function loadAssets() {
assetController?.abort()
const controller = new AbortController()
assetController = controller
const id = props.projectId
assetLoading.value = true
assetError.value = ''
assets.value = null
try {
const rows = await projectAssetsApi.list(id, controller.signal)
if (controller.signal.aborted || props.projectId !== id) return
if (rows.some(asset => asset.projectId !== id)) throw new Error('素材与当前项目不匹配。')
assets.value = rows.filter(asset => asset.type === 'image')
if (!assets.value.some(asset => asset.id === form.projectAssetId)) form.projectAssetId = ''
} catch (error) {
if (!controller.signal.aborted && props.projectId === id) assetError.value = errorMessage(error)
} finally {
if (assetController === controller) assetLoading.value = false
}
}
/**
* 只移除经过二次确认的引用记录。
* @param image 要移除的风格参考图
*/
function remove(image: VisualStyleImage) {
if (props.disabled || confirmingId.value !== image.id) return
confirmingId.value = ''
emit('remove', image)
}
const rules = { imageUrl: imageUrlRule, sortOrder: fieldRule(Number.isSafeInteger, '排序须为整数') }
/** 关闭弹窗后取消读取,避免失效查询写入下一次选择器。 */
watch(addOpen, shown => {
if (!shown) assetController?.abort()
})
/** 切换项目时清理来源草稿和确认状态,不复用其它项目图片。 */
watch(
() => props.projectId,
() => {
addOpen.value = false
assetController?.abort()
assets.value = null
confirmingId.value = ''
Object.assign(form, { imageUrl: '', projectAssetId: '', category: 'overall', sortOrder: 0, enabled: true })
}
)
onBeforeUnmount(() => assetController?.abort())
</script>
<template>
<!-- 以下是参考图说明、独立添加入口与已保存图片列表模块 -->
<section class="panel style-images-panel mt-5 p-5 sm:p-6" aria-label="风格参考图">
<h3 class="font-medium">
风格参考图 <span class="ml-2 text-xs text-muted">{{ images.length }} 张</span>
</h3>
<p class="mt-2 text-xs leading-6 text-muted">
优先从项目资产库选择,也可登记已有 HTTP(S) 或 /storage/
图片地址。启用的参考图会参与后续身份与形态生图,已有图片不会自动更新。
添加已有图片作为风格参考。参与生成的参考图用于后续主体身份与形态生图,已有图片不会自动更新。
</p>
<AppForm :model="form" :rules="rules" :disabled="disabled" class="mt-4" @submit="add">
<fieldset :disabled="disabled" class="form-controls style-image-controls">
<NFormItem class="style-image-url" path="imageUrl" label="图片地址"
><NInput
placeholder="https://… 或 /storage/…"
:input-props="{ 'aria-label': '风格图片地址' }"
v-model:value="form.imageUrl"
></NInput
></NFormItem>
<NFormItem path="category" label="分类" :label-props="{ for: 'style-image-category' }"
><NSelect
id="style-image-category"
v-model:value="form.category"
:options="[
...Object.entries(categories).map(([value, label]) => ({
label: String(label),
value: value
}))
]"
class="select-control"
></NSelect
></NFormItem>
<NFormItem path="sortOrder" label="排序"
><NInputNumber
:input-props="{ 'aria-label': '风格图片排序' }"
:value="typeof form.sortOrder === 'number' ? form.sortOrder : null"
@update:value="form.sortOrder = $event ?? 0"
:step="1"
></NInputNumber
></NFormItem>
<NCheckbox v-model:checked="form.enabled" class="control-row-checkbox text-xs">启用</NCheckbox>
<div class="style-image-submit flex gap-2">
<NButton :disabled="disabled" @click="openAssetPicker">从资产库选择</NButton>
<NButton :disabled="disabled" attr-type="submit">登记参考图</NButton>
</div>
</fieldset>
</AppForm>
<div class="mt-4 flex flex-wrap items-center gap-3">
<NButton :disabled="disabled || !hasStyle" @click="openAdd('asset')">从资产库添加</NButton>
<NButton :disabled="disabled || !hasStyle" @click="openAdd('link')">通过链接添加</NButton>
</div>
<div v-if="images.length" class="style-image-list mt-5">
<article v-for="image in images" :key="image.id" class="surface-inset min-w-0 p-3">
<AssetImage
@@ -165,67 +210,136 @@ const rules = { imageUrl: imageUrlRule, sortOrder: fieldRule(Number.isSafeIntege
</div>
</article>
</div>
<p v-else class="mt-5 text-sm text-muted">尚无风格参考图。先保存视觉风格,再登记图片。</p>
<p v-else class="mt-5 text-sm text-muted">
{{ hasStyle ? '尚无风格参考图,可从资产库或通过图片链接添加。' : '先保存视觉风格,再添加参考图。' }}
</p>
<!-- 以下是来源对应的添加弹窗;共同参数与确认动作保持一致 -->
<AppDialog
v-model:open="assetPickerOpen"
title="从项目资产库选择"
description="选择一张项目图片作为当前分类的风格参考。这里只创建引用,不复制或删除原素材。"
wide
v-model:open="addOpen"
:title="source === 'asset' ? '从资产库添加参考图' : '通过链接添加参考图'"
:description="
source === 'asset'
? '选择一张当前项目的图片,原素材会保留在资产库中。'
: '填写已有图片的 HTTP(S) 或 /storage/ 链接。'
"
:busy="adding"
:width="source === 'asset' ? 800 : 600"
>
<p v-if="assetError" class="mt-4 text-sm text-danger">{{ assetError }}</p>
<p v-else-if="assetLoading" class="mt-4 text-sm text-muted" role="status">正在读取项目素材…</p>
<div v-else-if="assets?.length" class="style-asset-picker mt-4">
<button
v-for="asset in assets"
:key="asset.id"
type="button"
class="style-asset-option"
:class="{ 'is-selected': selectedAssetId === asset.id }"
:aria-pressed="selectedAssetId === asset.id"
@click="selectedAssetId = asset.id"
<AppForm
id="style-reference-add-form"
:model="form"
:rules="rules"
:disabled="disabled"
:reset-key="source"
@submit="add"
>
<fieldset :disabled="disabled" class="style-reference-fields">
<!-- 以下是资产选择与链接输入模块,每次只校验当前来源 -->
<NFormItem v-if="source === 'asset'" path="projectAssetId" label="选择图片">
<div class="w-full min-w-0">
<div v-if="assetError" role="alert" class="text-sm text-danger">
{{ assetError }}
<NButton text :disabled="disabled" @click="loadAssets">重试读取素材</NButton>
</div>
<p v-else-if="assetLoading" class="text-sm text-muted" role="status">正在读取项目素材…</p>
<div v-else-if="assets?.length" class="style-asset-picker">
<button
v-for="asset in assets"
:key="asset.id"
type="button"
:disabled="disabled"
class="style-asset-option"
:class="{ 'is-selected': form.projectAssetId === asset.id }"
:aria-pressed="form.projectAssetId === asset.id"
@click="form.projectAssetId = asset.id"
>
<AssetImage :src="asset.publicUrl" :alt="asset.name" class="aspect-[4/3]" />
<span class="block truncate p-3 text-left text-xs">{{ asset.name }}</span>
</button>
</div>
<p v-else-if="assets" class="text-sm text-muted">
资产库暂无图片。
<RouterLink :to="`/projects/${projectId}/assets`" class="text-button"
>前往资产库上传</RouterLink
>
</p>
</div>
</NFormItem>
<NFormItem v-else path="imageUrl" label="图片链接">
<NInput
placeholder="https://… 或 /storage/…"
:input-props="{ 'aria-label': '风格图片地址' }"
v-model:value="form.imageUrl"
/>
</NFormItem>
<!-- 以下是应用范围、参考顺序和参与生成设置模块 -->
<div>
<div class="style-reference-settings">
<NFormItem path="category" label="应用范围" :label-props="{ for: 'style-image-category' }">
<NSelect
id="style-image-category"
v-model:value="form.category"
:options="scopeOptions"
/>
</NFormItem>
<NFormItem path="sortOrder" label="参考图顺序">
<NInputNumber
:input-props="{ 'aria-label': '风格图片排序' }"
:value="typeof form.sortOrder === 'number' ? form.sortOrder : null"
@update:value="form.sortOrder = $event ?? 0"
:step="1"
/>
</NFormItem>
</div>
<p class="mt-2 text-xs leading-6 text-muted">同一应用范围内,数值越小越靠前。</p>
</div>
<!-- 以下是参与生成开关与关联说明模块 -->
<div>
<NCheckbox v-model:checked="form.enabled">参与后续生成</NCheckbox>
<p class="mt-2 text-xs leading-6 text-muted">
关闭后仍会保存参考图,后续生成不会使用它;已有图片不会自动更新。
</p>
</div>
</fieldset>
</AppForm>
<p v-if="attempted && addError" role="alert" class="mt-4 text-sm text-danger">{{ addError }}</p>
<template #footer>
<NButton :disabled="adding" @click="addOpen = false">取消</NButton>
<NButton
type="primary"
attr-type="submit"
form="style-reference-add-form"
:loading="adding"
:disabled="
disabled || (source === 'asset' && (!form.projectAssetId || assetLoading || !!assetError))
"
>添加参考图</NButton
>
<AssetImage :src="asset.publicUrl" :alt="asset.name" class="aspect-[4/3]" />
<span class="block truncate p-3 text-left text-xs">{{ asset.name }}</span>
</button>
</div>
<div v-else-if="assets" class="mt-5 text-sm text-muted">
资产库暂无图片。<RouterLink :to="`/projects/${projectId}/assets`" class="text-button"
>前往资产库上传</RouterLink
>
</div>
<div class="mt-5 flex justify-end gap-3">
<NButton @click="assetPickerOpen = false">取消</NButton>
<NButton type="primary" :disabled="!selectedAssetId || disabled" @click="addAsset"
>登记为{{ categories[form.category] }}参考图</NButton
>
</div>
</template>
</AppDialog>
</section>
</template>
<style>
@reference "../../../styles/styles.css";
/* 按面板实际宽度布局,侧栏或移动端压缩内容时也能保持地址输入可用。 */
.style-images-panel {
container-type: inline-size;
}
.style-image-controls {
display: grid;
grid-template-columns: minmax(180px, 1fr) 130px 96px auto auto;
gap: 12px;
min-width: 0;
}
.style-image-submit {
margin-top: 29px;
}
.style-image-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(220px, 100%), 260px));
gap: 16px;
}
/* 表单项统一保留 20px 间距,错误反馈占用自然高度且说明紧邻对应字段。 */
.style-reference-fields {
@apply grid min-w-0 gap-5;
}
/* 来源面板与设置分行,窄屏只保留单列避免标签和操作挤在同一排。 */
.style-reference-settings {
@apply grid grid-cols-[minmax(0,_1fr)_140px] gap-5;
}
.style-asset-picker {
@apply grid grid-cols-[repeat(auto-fill,_minmax(min(180px,_100%),_1fr))] gap-3;
@apply grid grid-cols-[repeat(auto-fill,_minmax(min(160px,_100%),_1fr))] gap-3;
max-height: 280px;
overflow-y: auto;
}
.style-asset-option {
@apply min-w-0 overflow-hidden text-left bg-(--app-subtle) border border-transparent;
@@ -236,31 +350,9 @@ const rules = { imageUrl: imageUrlRule, sortOrder: fieldRule(Number.isSafeIntege
.style-asset-option.is-selected {
@apply border-(--color-accent);
}
.style-image-controls .select-control {
min-width: 0;
width: 100%;
}
@container (max-width: 640px) {
.style-image-controls {
grid-template-columns: minmax(0, 1fr) 96px auto;
}
.style-image-url,
.style-image-submit {
grid-column: 1 / -1;
}
.style-images-panel .app-form .style-image-controls > .style-image-submit {
margin-top: 0;
width: 100%;
min-height: 36px;
}
}
@container (max-width: 300px) {
.style-image-controls {
grid-template-columns: minmax(0, 1fr) 96px;
}
.style-images-panel .app-form .style-image-controls > .n-checkbox {
grid-column: 1 / -1;
margin-top: 0;
@media (max-width: 480px) {
.style-reference-settings {
@apply grid-cols-1;
}
}
</style>
+3 -2
View File
@@ -48,14 +48,15 @@ describe('精简入口保留功能', () => {
expect(wrapper.text()).toContain('完整规则仍然保留')
})
it('风格高级字段收起不丢失保存值,展开后仍可修改', async () => {
it('风格分类始终显示,保存保留人工补充与硬约束', async () => {
wrapper = mount(StyleEditor, { props: { visualStyle: null, disabled: false } })
expect(wrapper.find('#style-constraints').exists()).toBe(true)
await wrapper.get('#style-constraints').setValue('["保留硬约束"]')
const fields = wrapper.findAllComponents(NInput)
fields.find(item => item.props('placeholder')?.includes('人物质感'))!.vm.$emit('update:value', '人物风格')
await flushPromises()
await wrapper.get('.n-collapse-item__header-main').trigger('click')
expect(wrapper.find('.n-collapse').exists()).toBe(false)
expect(wrapper.findAll('.style-category-fields .n-form-item')).toHaveLength(3)
await wrapper.get('form').trigger('submit')
await flushPromises()
expect(wrapper.emitted('save')).toMatchObject([
+5 -2
View File
@@ -17,6 +17,7 @@ import {
import { readFileSync, readdirSync } from 'node:fs'
import { useTheme } from '@/composables/useTheme'
import { readAllStyles } from '@/testing/styles'
import StyleImages from '@/features/visual-style/components/StyleImages.vue'
let wrapper: VueWrapper | undefined
afterEach(() => {
@@ -277,9 +278,11 @@ describe('全站平面主题', () => {
expect(projects).not.toMatch(/<NButton\b[^>]*\bcircle\b/)
})
it('风格参考图操作按钮与输入行对齐,缩略图在宽屏下保持紧凑', () => {
it('风格参考图页内只保留添加入口,缩略图在宽屏下保持紧凑', () => {
const css = readAllStyles()
expect(css).toMatch(/\.style-image-submit\s*\{[^}]*margin-top:\s*29px;/)
wrapper = mount(StyleImages, { props: { projectId: 'theme-test-project', images: [], disabled: false } })
expect(wrapper.find('form').exists()).toBe(false)
expect(wrapper.findAll('button').map(button => button.text())).toEqual(['从资产库添加', '通过链接添加'])
expect(css).toMatch(
/\.style-image-list\s*\{[^}]*display:\s*grid;[^}]*grid-template-columns:\s*repeat\(auto-fill, minmax\(min\(220px, 100%\), 260px\)\);[^}]*gap:\s*16px;/
)
+41 -8
View File
@@ -127,18 +127,18 @@ describe('统一的 Naive UI 表单校验', () => {
expect(wrapper.emitted('generate')).toBeUndefined()
})
it('折叠后的非法 JSON 仍拦截保存并展开错误,修正后保留草稿正常提交', async () => {
it('分类风格始终显示,非法 JSON 拦截保存,修正后保留草稿正常提交', async () => {
wrapper = mount(StyleEditor, { attachTo: document.body, props: { visualStyle: null, disabled: false } })
await flushPromises()
expect(button('分类风格与硬约束').getAttribute('aria-expanded')).toBe('true')
expect(wrapper.find('button[aria-expanded]').exists()).toBe(false)
expect(wrapper.get('.style-category-section h3').text()).toBe('分类风格与硬约束')
expect(wrapper.findAll('.style-category-fields .n-form-item')).toHaveLength(3)
await input('#style-name', '手工风格')
await input('#style-constraints', '{"invalid":true}')
button('分类风格与硬约束').click()
await flushPromises()
await submit()
expect(wrapper.emitted('save')).toBeUndefined()
expect(feedback()).toContain('请输入 JSON 字符串数组')
expect(button('分类风格与硬约束').getAttribute('aria-expanded')).toBe('true')
expect(wrapper.get('#style-constraints').isVisible()).toBe(true)
await input('#style-constraints', '["真人写实"]')
await submit()
expect(wrapper.emitted('save')?.[0]?.[0]).toMatchObject({ name: '手工风格', hardConstraints: ['真人写实'] })
@@ -149,6 +149,10 @@ describe('统一的 Naive UI 表单校验', () => {
attachTo: document.body,
props: { projectId: 'form-test-project', images: [], disabled: false }
})
expect(document.querySelector('[aria-label="风格图片地址"]')).toBeNull()
expect(wrapper.text()).not.toContain('先保存视觉风格')
button('通过链接添加').click()
await flushPromises()
await input('[aria-label="风格图片地址"]', 'javascript:alert(1)')
await input('[aria-label="风格图片排序"]', '1.5')
await submit()
@@ -191,7 +195,7 @@ describe('统一的 Naive UI 表单校验', () => {
})
expect(fetcher).not.toHaveBeenCalled()
button('从资产库选择').click()
button('从资产库添加').click()
await flushPromises()
expect(fetcher).toHaveBeenCalledWith(
'/api/projects/form-test-project/assets',
@@ -201,8 +205,13 @@ describe('统一的 Naive UI 表单校验', () => {
expect(option.textContent).toContain('人物质感参考')
option.click()
await flushPromises()
button('登记为整体参考图').click()
await flushPromises()
await input('[aria-label="风格图片排序"]', '1.5')
await submit()
expect(feedback()).toContain('排序须为整数')
expect(wrapper.emitted('add')).toBeUndefined()
await input('[aria-label="风格图片排序"]', '-1')
await submit()
expect(document.querySelector('[aria-label="风格图片地址"]')).toBeNull()
expect(wrapper.emitted('add')?.[0]?.[0]).toMatchObject({
projectAssetId: 'asset-db-1',
category: 'overall',
@@ -210,6 +219,30 @@ describe('统一的 Naive UI 表单校验', () => {
})
})
it('未保存风格时禁用两个入口,资产读取失败可在弹窗重试', async () => {
const fetcher = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(new Response('{"message":"素材读取失败"}', { status: 500 }))
.mockResolvedValue(new Response('{"data":[]}'))
vi.stubGlobal('fetch', fetcher)
wrapper = mount(StyleImages, {
attachTo: document.body,
props: { projectId: 'form-test-project', images: [], disabled: true, hasStyle: false }
})
expect(wrapper.text()).toContain('先保存视觉风格')
expect(button('从资产库添加').disabled).toBe(true)
expect(button('通过链接添加').disabled).toBe(true)
await wrapper.setProps({ disabled: false, hasStyle: true })
button('从资产库添加').click()
await flushPromises()
expect(document.querySelector('.app-dialog')?.textContent).toContain('素材读取失败')
expect(button('添加参考图').disabled).toBe(true)
button('重试读取素材').click()
await flushPromises()
expect(document.querySelector('.app-dialog')?.textContent).toContain('资产库暂无图片')
expect(fetcher).toHaveBeenCalledTimes(2)
})
it('异步验证期间切换对象或重复提交不会执行旧动作', async () => {
let finish: (() => void) | undefined
const model = reactive({ text: '有效输入' })
+8 -2
View File
@@ -44,11 +44,17 @@ describe('管理后台组件边界', () => {
expect(adminCss).toMatch(/html,\s*body,\s*#app,\s*\.app-provider\s*\{[^}]*overflow:\s*hidden/)
expect(adminCss).toMatch(/\.workspace-page\s*\{[^}]*min-height:\s*0;[^}]*overflow:\s*hidden/)
})
it('仅手机阅读工作区允许项目内容整体滚动,其余面板保持独立滚动', () => {
it('项目整体滚动仅用于手机阅读,弹窗素材选择保留有界滚动', () => {
const css = readAllStyles()
const mobileReading = /\.project-view:has\(\.mobile-reading-workspace\)\s*\{[^}]*\}/
expect(css.match(mobileReading)?.[0]).toContain('overflow-y: auto;')
expect(css.replace(mobileReading, '')).not.toMatch(/overflow(?:-[xy])?\s*:\s*(?:auto|scroll)\b/)
/** 素材列表是弹窗内的局部滚动容器,不改变项目工作区滚动边界。 */
const assetPicker = /\.style-asset-picker\s*\{[^}]*\}/
expect(css.match(assetPicker)?.[0]).toContain('max-height: 280px;')
expect(css.match(assetPicker)?.[0]).toContain('overflow-y: auto;')
expect(css.replace(mobileReading, '').replace(assetPicker, '')).not.toMatch(
/overflow(?:-[xy])?\s*:\s*(?:auto|scroll)\b/
)
})
it('历史缩略图尺寸在非分层样式中覆盖 Naive 按钮,原图不能撑大预览或横向条目', () => {
// happy-dom 不计算几何;专门保护此前失效的层叠和固定尺寸约束。
+43 -39
View File
@@ -106,48 +106,52 @@ async function openProject(initialPath: string) {
}
describe('剧本完成前的下游访问限制', () => {
it('拆解首次读取显示骨架,刷新保留已有内容,切换项目完成后仍遵守访问限制', async () => {
/** 延迟真实查询入口,覆盖初次读取、后台刷新和跨项目读取三个阶段。 */
let resolveDetail!: (value: ProjectDetail) => void
let pending = new Promise<ProjectDetail>(resolve => {
resolveDetail = resolve
})
vi.spyOn(projectsApi, 'detail').mockImplementation(() => pending)
vi.spyOn(projectsApi, 'checkpoints').mockResolvedValue([])
vi.mocked(projectsApi.stageReadiness).mockImplementation(async id => readiness(id, id === 'skeleton-first'))
const { router, mounted } = await openProject('/projects/skeleton-first/breakdown')
expect(wrapper!.get('.breakdown-skeleton').attributes('aria-busy')).toBe('true')
expect(wrapper!.find('.workspace-loading').exists()).toBe(false)
expect(wrapper!.get('.project-title').text()).toBe('')
expect(mounted).not.toHaveBeenCalled()
it.each(['breakdown', 'visual-style'] as const)(
'%s 首次读取显示骨架,刷新保留已有内容,切换项目完成后仍遵守访问限制',
async section => {
/** 延迟真实查询入口,覆盖初次读取、后台刷新和跨项目读取三个阶段。 */
let resolveDetail!: (value: ProjectDetail) => void
let pending = new Promise<ProjectDetail>(resolve => {
resolveDetail = resolve
})
vi.spyOn(projectsApi, 'detail').mockImplementation(() => pending)
vi.spyOn(projectsApi, 'checkpoints').mockResolvedValue([])
vi.mocked(projectsApi.stageReadiness).mockImplementation(async id => readiness(id, id === 'skeleton-first'))
const { router, mounted } = await openProject(`/projects/skeleton-first/${section}`)
const skeleton = section === 'breakdown' ? '.breakdown-skeleton' : '.visual-style-skeleton'
expect(wrapper!.get(skeleton).attributes('aria-busy')).toBe('true')
expect(wrapper!.find('.workspace-loading').exists()).toBe(false)
expect(wrapper!.get('.project-title').text()).toBe('')
expect(mounted).not.toHaveBeenCalled()
resolveDetail(project('skeleton-first', 'completed'))
await flushPromises()
expect(wrapper!.find('.breakdown-skeleton').exists()).toBe(false)
expect(wrapper!.get('.workspace-probe').text()).toBe('breakdown')
resolveDetail(project('skeleton-first', 'completed'))
await flushPromises()
expect(wrapper!.find(skeleton).exists()).toBe(false)
expect(wrapper!.get('.workspace-probe').text()).toBe(section)
pending = new Promise<ProjectDetail>(resolve => {
resolveDetail = resolve
})
await wrapper!.get('.probe-refresh').trigger('click')
expect(wrapper!.find('.breakdown-skeleton').exists()).toBe(false)
expect(wrapper!.get('.workspace-probe').text()).toBe('breakdown')
resolveDetail(project('skeleton-first', 'completed'))
await flushPromises()
pending = new Promise<ProjectDetail>(resolve => {
resolveDetail = resolve
})
await wrapper!.get('.probe-refresh').trigger('click')
expect(wrapper!.find(skeleton).exists()).toBe(false)
expect(wrapper!.get('.workspace-probe').text()).toBe(section)
resolveDetail(project('skeleton-first', 'completed'))
await flushPromises()
pending = new Promise<ProjectDetail>(resolve => {
resolveDetail = resolve
})
await router.push('/projects/skeleton-second/breakdown')
await flushPromises()
expect(wrapper!.find('.breakdown-skeleton').exists()).toBe(true)
expect(wrapper!.find('.workspace-probe').exists()).toBe(false)
resolveDetail(project('skeleton-second', 'draft'))
await flushPromises()
expect(wrapper!.find('.breakdown-skeleton').exists()).toBe(false)
expect(wrapper!.get('.project-access-gate').text()).toContain('请先完成剧本创作')
expect(mounted).toHaveBeenCalledExactlyOnceWith('breakdown')
})
pending = new Promise<ProjectDetail>(resolve => {
resolveDetail = resolve
})
await router.push(`/projects/skeleton-second/${section}`)
await flushPromises()
expect(wrapper!.find(skeleton).exists()).toBe(true)
expect(wrapper!.find('.workspace-probe').exists()).toBe(false)
resolveDetail(project('skeleton-second', 'draft'))
await flushPromises()
expect(wrapper!.find(skeleton).exists()).toBe(false)
expect(wrapper!.get('.project-access-gate').text()).toContain('请先完成剧本创作')
expect(mounted).toHaveBeenCalledExactlyOnceWith(section)
}
)
it('切换图库与其他工作区不自动重复读取项目状态', async () => {
vi.useFakeTimers()
+102 -6
View File
@@ -26,6 +26,7 @@ import SubjectImagesPage from '@/features/subject-images/SubjectImagesPage.vue'
import { formFixture, imageFixture } from '@/features/subject-images/testing/fixtures'
import { getImageSession } from '@/features/subject-images/model'
import VisualStylePage from '@/features/visual-style/VisualStylePage.vue'
import { visualStyleApi } from '@/features/visual-style/api'
import SubjectIdentityPage from '@/features/subject-identity/SubjectIdentityPage.vue'
import { styleFixture, styleImageFixture } from '@/features/visual-style/testing/fixtures'
import { identityFixture, identityImageFixture } from '@/features/subject-identity/testing/fixtures'
@@ -303,6 +304,64 @@ describe('内容级滚动下的生产反馈', () => {
})
describe('视觉风格与主体身份工作区', () => {
it('风格首读显示骨架,失败后展示重试,恢复后分类与规则始终可见', async () => {
/** 延迟首次响应,确认骨架不会混入尚未创建或空参考图提示。 */
let rejectStyle!: (error: Error) => void
vi.spyOn(visualStyleApi, 'get')
.mockImplementationOnce(
() =>
new Promise((_resolve, reject) => {
rejectStyle = reject
})
)
.mockResolvedValue(styleFixture())
await mountAssets('style')
expect(wrapper!.get('.visual-style-skeleton').attributes('aria-busy')).toBe('true')
expect(wrapper!.find('#style-prompt').exists()).toBe(false)
expect(wrapper!.text()).not.toContain('尚无风格参考图')
rejectStyle(new Error('风格读取失败'))
await flushPromises()
expect(wrapper!.find('.visual-style-skeleton').exists()).toBe(false)
expect(wrapper!.get('[role="alert"]').text()).toContain('风格读取失败')
expect(wrapper!.text()).not.toContain('视觉风格已准备好')
expect(wrapper!.find('.style-images-panel').exists()).toBe(false)
button('重试读取').click()
await flushPromises()
expect(wrapper!.find('#style-prompt').exists()).toBe(true)
expect(wrapper!.get('.visual-style-rules').text()).toContain('中国人物选角基线')
expect(wrapper!.find('.n-collapse').exists()).toBe(false)
expect(wrapper!.findAll('.style-category-fields textarea')).toHaveLength(3)
})
it('刷新已有风格时保留编辑器、参考图和未保存的分类草稿', async () => {
const image = styleImageFixture()
/** 图片启停后的刷新延迟返回,保护现有内容与人工草稿。 */
let resolveStyle!: (value: ReturnType<typeof styleFixture>) => void
vi.spyOn(visualStyleApi, 'get')
.mockResolvedValueOnce(styleFixture({ images: [image] }))
.mockImplementationOnce(
() =>
new Promise(resolve => {
resolveStyle = resolve
})
)
vi.spyOn(visualStyleApi, 'setImageEnabled').mockResolvedValue({ ...image, enabled: false })
await mountAssets('style')
const editor = wrapper!.get('.style-category-section').element
await wrapper!.get('textarea[aria-label="人物风格与选角背景"]').setValue('人物风格人工草稿')
button('停用').click()
await flushPromises()
expect(wrapper!.find('.visual-style-skeleton').exists()).toBe(false)
expect(wrapper!.get('.style-category-section').element).toBe(editor)
resolveStyle(styleFixture({ images: [{ ...image, enabled: false }] }))
await flushPromises()
expect((wrapper!.get('textarea[aria-label="人物风格与选角背景"]').element as HTMLTextAreaElement).value).toBe(
'人物风格人工草稿'
)
expect(button('AI 重新生成风格').disabled).toBe(true)
expect(button('启用').disabled).toBe(false)
})
it.each([
{ locked: null, label: '尚未创建', action: 'AI 生成风格', disabled: false },
{ locked: false, label: '未锁定', action: 'AI 重新生成风格', disabled: false },
@@ -458,20 +517,23 @@ describe('视觉风格与主体身份工作区', () => {
)
})
it('风格图拒绝危险 URL,登记只传已有地址及分类排序', async () => {
it('链接添加拒绝危险 URL,只传已有地址及分类排序,成功后关闭并清空弹窗', async () => {
const image = styleImageFixture()
const fetcher = vi
.fn<typeof fetch>()
.mockImplementation(async (_url, init) => jsonResponse(init?.method === 'POST' ? image : styleFixture()))
stubFetch(fetcher)
await mountAssets('style')
await wrapper!.get('[aria-label="风格图片地址"]').setValue('javascript:alert(1)')
button('登记参考图').click()
expect(wrapper!.find('[aria-label="风格图片地址"]').exists()).toBe(false)
button('通过链接添加').click()
await flushPromises()
await new DOMWrapper(document.body).get('[aria-label="风格图片地址"]').setValue('javascript:alert(1)')
button('添加参考图').click()
await flushPromises()
expect(document.querySelector('.n-form-item-feedback--error')?.textContent).toContain('请填写有效的')
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false)
await wrapper!.get('[aria-label="风格图片地址"]').setValue('/storage/style.png')
button('登记参考图').click()
await new DOMWrapper(document.body).get('[aria-label="风格图片地址"]').setValue('/storage/style.png')
button('添加参考图').click()
await flushPromises()
const post = fetcher.mock.calls.find(([, init]) => init?.method === 'POST')!
expect(post[0]).toBe('/api/projects/page-test-project/visual-style/images')
@@ -482,7 +544,41 @@ describe('视觉风格与主体身份工作区', () => {
enabled: true,
sortOrder: 0
})
expect((wrapper!.get('[aria-label="风格图片地址"]').element as HTMLInputElement).value).toBe('')
expect(document.querySelector('.app-dialog')).toBeNull()
button('通过链接添加').click()
await flushPromises()
expect(document.querySelector<HTMLInputElement>('[aria-label="风格图片地址"]')!.value).toBe('')
})
it('参考图添加失败保留弹窗、来源与设置,显式重试成功才关闭', async () => {
let rejectAdd = true
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (_url, init) => {
if (init?.method === 'POST')
return rejectAdd
? new Response('{"message":"参考图保存失败"}', { status: 500 })
: jsonResponse(styleImageFixture())
return jsonResponse(styleFixture())
})
stubFetch(fetcher)
await mountAssets('style')
button('通过链接添加').click()
await flushPromises()
const body = new DOMWrapper(document.body)
await body.get('[aria-label="风格图片地址"]').setValue('/storage/draft.png')
await body.get('[aria-label="风格图片排序"]').setValue('-2')
button('添加参考图').click()
await flushPromises()
expect(document.querySelector('.app-dialog')?.textContent).toContain('参考图保存失败')
expect(document.querySelector<HTMLInputElement>('[aria-label="风格图片地址"]')!.value).toBe(
'/storage/draft.png'
)
expect(document.querySelector<HTMLInputElement>('[aria-label="风格图片排序"]')!.value).toBe('-2')
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(1)
rejectAdd = false
button('添加参考图').click()
await flushPromises()
expect(document.querySelector('.app-dialog')).toBeNull()
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(2)
})
it('AI 确认取消后重新打开必须再次确认,不能复用上次勾选', async () => {