Skip to content

🎬 火宝短剧 - 基于AI的一站式短剧生成平台 《一句话生成完整短剧,从剧本到成片全自动化》 Huobao Drama - An AI-Powered End-to-End Short Drama Generator "One Sentence to Complete Drama: Fully Automated from Script to Final Video"

TypeScript

feat 修改样式

jiangzijun9b74f701f4dd
diff --git a/application/services/prompt_i18n.go b/application/services/prompt_i18n.go
index 3bfafaa..7932aee 100644
--- a/application/services/prompt_i18n.go
+++ b/application/services/prompt_i18n.go
@@ -771,7 +771,7 @@ func (p *PromptI18n) GetStylePrompt(style string) string {
**[风格核心逻辑]**
- **视觉流派与画面质感**:采用 **3D 盲盒艺术风格 (Blind Box / Toy Art Style)**。画面具有极强的 **类塑料与树脂质感 (Plastic and Resin texture)**,表面圆润、平滑,边缘带有微妙的倒角。主体呈现出明显的 **Q 版比例**(大头小身),增强了亲和力。
-- **色彩美学逻辑**:使用 **"温和的高饱和调色盘 (Muted Vibrant Palette)"**。色彩鲜艳但并不刺眼,通常带有一定的 **粉质感 (Pastel undertone)**。色彩分布遵循"主次分明"原则,利用大面积的自然底色(如森林绿、泥土褐)衬托主体鲜明的服饰色彩。
+- **色彩美学逻辑**:使用 **"温和的高饱和调色盘 (Muted Vibrant Palette)"**。色彩鲜艳但并不刺眼。色彩分布遵循"主次分明"原则,利用大面积的自然底色(如森林绿、泥土褐)衬托主体鲜明的服饰色彩。
- **光影表现手法**:光源通常柔和且均匀。**顶光/面光**:均匀照亮主体正面,突出五官和服饰细节。**环境遮蔽 (Ambient Occlusion)**:在缝隙和接触面产生细腻的阴影,增强物体的重量感和真实感。`,
},
"en": {
@@ -844,7 +844,7 @@ You are a top-tier **3D Toy Designer and Rendering Artist**, specializing in hig
**[Core Style Logic]**
- **Visual Genre & Frame Texture**: Adopts a **3D Blind Box / Toy Art Style**. The image features strong **plastic and resin textures**; surfaces are rounded and smooth with subtle beveled edges. The subject uses **Chibi proportions** (large head, small body) to enhance appeal.
-- **Color Aesthetic Logic**: Uses a **"Muted Vibrant Palette."** Colors are vivid but not piercing, usually with a **pastel undertone**. Color distribution follows a "primary-secondary" principle, using large areas of natural base colors (forest green, earth brown) to set off the bright colors of the character's outfit.
+- **Color Aesthetic Logic**: Uses a **"Muted Vibrant Palette."** Colors are vivid but not piercing. Color distribution follows a "primary-secondary" principle, using large areas of natural base colors (forest green, earth brown) to set off the bright colors of the character's outfit.
- **Lighting Technique**: Light sources are typically soft and even: **Top/Key Light**: Evenly illuminates the subject's front, highlighting facial features and clothing details. **Ambient Occlusion (AO)**: Produces delicate shadows in crevices and contact points, enhancing the object's sense of weight and realism.`,
},
}
diff --git a/web/src/assets/styles/main.css b/web/src/assets/styles/main.css
index bf0f26c..b010d40 100644
--- a/web/src/assets/styles/main.css
+++ b/web/src/assets/styles/main.css
@@ -126,16 +126,15 @@
--shadow-card: 0 2px 4px 0 rgb(0 0 0 / 0.3);
--shadow-card-hover: 0 8px 20px -4px rgb(0 0 0 / 0.5), 0 0 0 1px rgba(34, 211, 238, 0.15);
- --el-fill-color-blank: #181F28;
+ --el-fill-color-blank: #181f28;
--el-border-color: #4d4d4d;
--el-border-color-light: #2a333d;
--el-fill-color-light: #2a333d;
- --el-bg-color-overlay: #181F28;
+ --el-bg-color-overlay: #181f28;
--el-text-color-regular: #e8edf3;
--el-descriptions-table-border: #4d4d4d;
--el-border-color-lighter: #4d4d4d;
--el-text-color-primary: #e8edf3;
-
}
/* ========================================
@@ -151,10 +150,20 @@ html,
body {
width: 100%;
height: 100%;
- font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
+ font-family:
+ 'Inter',
+ -apple-system,
+ BlinkMacSystemFont,
+ 'Segoe UI',
+ Roboto,
+ 'Helvetica Neue',
+ Arial,
+ sans-serif;
background-color: var(--bg-primary);
color: var(--text-primary);
- transition: background-color var(--transition-normal), color var(--transition-normal);
+ transition:
+ background-color var(--transition-normal),
+ color var(--transition-normal);
}
#app {
@@ -773,6 +782,13 @@ body {
background: var(--text-muted);
}
+/* 图片样式 */
+.el-image-viewer__close,
+.el-image-viewer__actions {
+ background-color: var(--bg-primary);
+ border: 1px solid var(--border-primary);
+}
+
/* ========================================
Utility Classes / 工具类
======================================== */
@@ -889,7 +905,9 @@ body {
/* Hover lift effect / 悬停提升效果 */
.hover-lift {
- transition: transform var(--transition-normal), box-shadow var(--transition-normal);
+ transition:
+ transform var(--transition-normal),
+ box-shadow var(--transition-normal);
}
.hover-lift:hover {
@@ -940,6 +958,34 @@ body {
}
/* Scrollbar styling / 滚动条样式 */
+/* 全局滚动条样式 */
+::-webkit-scrollbar {
+ width: 8px;
+ height: 8px;
+}
+
+::-webkit-scrollbar-track {
+ background: var(--bg-secondary);
+ border-radius: var(--radius-full);
+}
+
+::-webkit-scrollbar-thumb {
+ background: var(--border-secondary);
+ border-radius: var(--radius-full);
+ transition: background var(--transition-fast);
+}
+
+::-webkit-scrollbar-thumb:hover {
+ background: var(--accent);
+}
+
+/* Firefox 滚动条样式 */
+* {
+ scrollbar-width: thin;
+ scrollbar-color: var(--border-secondary) var(--bg-secondary);
+}
+
+/* 自定义滚动条类 */
.custom-scrollbar::-webkit-scrollbar {
width: 6px;
height: 6px;
@@ -955,7 +1001,7 @@ body {
}
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
- background: var(--text-muted);
+ background: var(--accent);
}
/* Hide scrollbar / 隐藏滚动条 */
@@ -1027,7 +1073,6 @@ body {
}
@keyframes pulse {
-
0%,
100% {
opacity: 1;
@@ -1059,7 +1104,6 @@ body {
}
@keyframes bounce {
-
0%,
100% {
transform: translateY(-5%);
@@ -1107,7 +1151,6 @@ body {
}
@keyframes status-pulse {
-
0%,
100% {
box-shadow: 0 0 0 0 currentColor;
@@ -1131,11 +1174,17 @@ body {
}
.font-display {
- font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
+ font-family:
+ 'Inter',
+ -apple-system,
+ BlinkMacSystemFont,
+ 'Segoe UI',
+ Roboto,
+ sans-serif;
font-weight: 700;
letter-spacing: -0.02em;
}
.font-mono {
font-family: 'JetBrains Mono', 'Fira Code', 'Consolas', monospace;
-}
\ No newline at end of file
+}
diff --git a/web/src/components/common/ImageCropDialog.vue b/web/src/components/common/ImageCropDialog.vue
index 675df72..9281a97 100644
--- a/web/src/components/common/ImageCropDialog.vue
+++ b/web/src/components/common/ImageCropDialog.vue
@@ -15,11 +15,7 @@
<!-- 左侧裁剪区域 -->
<div class="crop-area">
<div class="crop-canvas-wrapper">
- <cropper-canvas
- ref="cropperCanvasRef"
- background
- class="cropper-canvas-element"
- >
+ <cropper-canvas ref="cropperCanvasRef" background class="cropper-canvas-element">
<cropper-image
v-if="imageUrl"
ref="cropperImageRef"
@@ -30,24 +26,20 @@
skewable
translatable
/>
- <cropper-shade
- hidden
- style="min-width: 300px; min-height: 300px"
- ></cropper-shade>
+ <cropper-shade hidden style="min-width: 300px; min-height: 300px"></cropper-shade>
<cropper-handle action="move" plain></cropper-handle>
<cropper-selection
+ :width="300"
+ :height="300"
+ style="min-width: 300px; min-height: 300px"
movable
resizable
outlined
aspectRatio="1"
- style="min-width: 300px; min-height: 300px"
>
<!-- <cropper-grid role="grid" bordered covered></cropper-grid> -->
<!-- <cropper-crosshair centered></cropper-crosshair> -->
- <cropper-handle
- action="move"
- theme-color="rgba(255, 255, 255, 0.35)"
- ></cropper-handle>
+ <cropper-handle action="move" theme-color="rgba(255, 255, 255, 0.35)"></cropper-handle>
<cropper-handle action="n-resize"></cropper-handle>
<cropper-handle action="e-resize"></cropper-handle>
<cropper-handle action="s-resize"></cropper-handle>
@@ -64,12 +56,7 @@
<!-- 缩放控制区域 -->
<div class="zoom-control">
<div class="slider-box">
- <el-button
- :icon="ZoomIn"
- circle
- @click="handleZoomIn"
- :disabled="zoomLevel >= 200"
- />
+ <el-button :icon="ZoomIn" circle @click="handleZoomIn" :disabled="zoomLevel >= 200" />
<el-slider
v-model="zoomLevel"
:min="50"
@@ -79,32 +66,14 @@
height="300px"
@change="handleZoomChange"
/>
- <el-button
- :icon="ZoomOut"
- circle
- @click="handleZoomOut"
- :disabled="zoomLevel <= 50"
- />
+ <el-button :icon="ZoomOut" circle @click="handleZoomOut" :disabled="zoomLevel <= 50" />
<div class="zoom-label">{{ zoomLevel }}%</div>
</div>
<div class="crop-actions">
<!-- 裁剪和重置按钮 -->
- <el-button
- :icon="Crop"
- circle
- type="primary"
- @click="cropImage"
- :disabled="!canCrop"
- title="裁剪"
- />
- <el-button
- :icon="RefreshLeft"
- circle
- @click="resetCrop"
- title="重置"
- style="margin: 0"
- />
+ <el-button :icon="Crop" circle type="primary" @click="cropImage" :disabled="!canCrop" title="裁剪" />
+ <el-button :icon="RefreshLeft" circle @click="resetCrop" title="重置" style="margin: 0" />
</div>
</div>
@@ -116,7 +85,9 @@
v-for="folder in folders"
:key="folder.type"
class="folder-item"
- :class="{ 'drag-over': dragOverFolder === folder.type }"
+ :class="{
+ 'drag-over': dragOverFolder === folder.type,
+ }"
@dragover.prevent="handleFolderDragOver(folder.type)"
@dragleave="handleFolderDragLeave"
@drop="handleFolderDrop($event, folder.type)"
@@ -128,9 +99,7 @@
<el-badge :value="folder.count" :hidden="folder.count === 0" />
</div>
</div>
- <div class="preview-title">
- 已裁剪图片 ({{ croppedImages.length }})
- </div>
+ <div class="preview-title">已裁剪图片 ({{ croppedImages.length }})</div>
<div class="preview-grid">
<div
v-for="(img, index) in croppedImages"
@@ -142,11 +111,7 @@
>
<img :src="img.url" alt="cropped" />
<div class="preview-overlay">
- <el-icon
- :size="16"
- class="delete-icon"
- @click="removeCroppedImage(index)"
- >
+ <el-icon :size="16" class="delete-icon" @click="removeCroppedImage(index)">
<Close />
</el-icon>
</div>
@@ -161,225 +126,209 @@
<template #footer>
<el-button @click="handleClose">取消</el-button>
- <el-button type="primary" @click="handleSave" :loading="saving">
- 保存
- </el-button>
+ <el-button type="primary" @click="handleSave" :loading="saving"> 保存 </el-button>
</template>
</el-dialog>
</template>
<script setup lang="ts">
-import { ref, computed, watch, nextTick, onMounted } from "vue";
-import {
- Folder,
- Close,
- ZoomIn,
- ZoomOut,
- Crop,
- RefreshLeft,
-} from "@element-plus/icons-vue";
-import "cropperjs";
+import { ref, computed, watch, nextTick, onMounted } from 'vue'
+import { Folder, Close, ZoomIn, ZoomOut, Crop, RefreshLeft } from '@element-plus/icons-vue'
+import 'cropperjs'
interface CroppedImage {
- url: string;
- blob: Blob;
- frameType?: string;
+ url: string
+ blob: Blob
+ frameType?: string
}
interface Props {
- modelValue: boolean;
- imageUrl?: string;
+ modelValue: boolean
+ imageUrl?: string
}
interface Emits {
- (e: "update:modelValue", value: boolean): void;
- (e: "save", images: { blob: Blob; frameType: string }[]): void;
+ (e: 'update:modelValue', value: boolean): void
+ (e: 'save', images: { blob: Blob; frameType: string }[]): void
}
-const props = defineProps<Props>();
-const emit = defineEmits<Emits>();
+const props = defineProps<Props>()
+const emit = defineEmits<Emits>()
const dialogVisible = computed({
get: () => props.modelValue,
- set: (val) => emit("update:modelValue", val),
-});
-
-const cropperCanvasRef = ref<any>();
-const cropperImageRef = ref<any>();
-const croppedImages = ref<CroppedImage[]>([]);
-const dragOverFolder = ref<string | null>(null);
-const draggingImageIndex = ref<number | null>(null);
-const saving = ref(false);
-const zoomLevel = ref(100);
-const previousZoomLevel = ref(100);
+ set: (val) => emit('update:modelValue', val),
+})
+
+const cropperCanvasRef = ref<any>()
+const cropperImageRef = ref<any>()
+const croppedImages = ref<CroppedImage[]>([])
+const dragOverFolder = ref<string | null>(null)
+const draggingImageIndex = ref<number | null>(null)
+const saving = ref(false)
+const zoomLevel = ref(100)
+const previousZoomLevel = ref(100)
const folders = computed(() => [
{
- type: "first",
- name: "首帧",
- count: croppedImages.value.filter((img) => img.frameType === "first")
- .length,
+ type: 'first',
+ name: '首帧',
+ count: croppedImages.value.filter((img) => img.frameType === 'first').length,
},
{
- type: "last",
- name: "尾帧",
- count: croppedImages.value.filter((img) => img.frameType === "last").length,
+ type: 'last',
+ name: '尾帧',
+ count: croppedImages.value.filter((img) => img.frameType === 'last').length,
},
{
- type: "key",
- name: "关键帧",
- count: croppedImages.value.filter((img) => img.frameType === "key").length,
+ type: 'key',
+ name: '关键帧',
+ count: croppedImages.value.filter((img) => img.frameType === 'key').length,
},
-]);
+])
const canCrop = computed(() => {
- return (
- cropperCanvasRef.value !== undefined && cropperImageRef.value !== undefined
- );
-});
+ return cropperCanvasRef.value !== undefined && cropperImageRef.value !== undefined
+})
watch(
() => props.modelValue,
(val) => {
if (val) {
nextTick(() => {
- console.log("Dialog opened, canvas ref:", cropperCanvasRef.value);
- console.log("Image ref:", cropperImageRef.value);
- });
+ console.log('Dialog opened, canvas ref:', cropperCanvasRef.value)
+ console.log('Image ref:', cropperImageRef.value)
+ })
}
},
-);
+)
const cropImage = async () => {
if (!cropperCanvasRef.value) {
- console.error("Cropper canvas not found");
- return;
+ console.error('Cropper canvas not found')
+ return
}
try {
// 使用 Web Components API 的 $toCanvas 方法获取裁剪后的画布
- const selection = cropperCanvasRef.value.querySelector("cropper-selection");
+ const selection = cropperCanvasRef.value.querySelector('cropper-selection')
if (!selection) {
- console.error("Cropper selection not found");
- return;
+ console.error('Cropper selection not found')
+ return
}
// 获取选区的 canvas
- const canvas = await selection.$toCanvas();
+ const canvas = await selection.$toCanvas()
if (!canvas) {
- console.error("Failed to get canvas");
- return;
+ console.error('Failed to get canvas')
+ return
}
// 转换为 Blob
canvas.toBlob((blob) => {
- if (!blob) return;
+ if (!blob) return
- const url = URL.createObjectURL(blob);
+ const url = URL.createObjectURL(blob)
croppedImages.value.push({
url,
blob,
frameType: undefined,
- });
- console.log("Image cropped successfully");
- });
+ })
+ console.log('Image cropped successfully')
+ })
} catch (error) {
- console.error("Error cropping image:", error);
+ console.error('Error cropping image:', error)
}
-};
+}
const resetCrop = () => {
if (cropperImageRef.value && cropperImageRef.value.$resetTransform) {
- cropperImageRef.value.$resetTransform();
- zoomLevel.value = 100;
- console.log("Crop reset");
+ cropperImageRef.value.$resetTransform()
+ zoomLevel.value = 100
+ console.log('Crop reset')
}
-};
+}
const handleZoomIn = () => {
if (zoomLevel.value < 200) {
- zoomLevel.value = Math.min(200, zoomLevel.value + 2);
- applyZoom();
+ zoomLevel.value = Math.min(200, zoomLevel.value + 2)
+ applyZoom()
}
-};
+}
const handleZoomOut = () => {
if (zoomLevel.value > 50) {
- zoomLevel.value = Math.max(50, zoomLevel.value - 2);
- applyZoom();
+ zoomLevel.value = Math.max(50, zoomLevel.value - 2)
+ applyZoom()
}
-};
+}
const handleZoomChange = (value: number) => {
- zoomLevel.value = value;
- applyZoom();
-};
+ zoomLevel.value = value
+ applyZoom()
+}
const applyZoom = () => {
if (cropperImageRef.value && cropperImageRef.value.$scale) {
// 计算相对于上一次的缩放比例
- const ratio = zoomLevel.value / previousZoomLevel.value;
- cropperImageRef.value.$scale(ratio);
- previousZoomLevel.value = zoomLevel.value;
+ const ratio = zoomLevel.value / previousZoomLevel.value
+ cropperImageRef.value.$scale(ratio)
+ previousZoomLevel.value = zoomLevel.value
}
-};
+}
const removeCroppedImage = (index: number) => {
- const img = croppedImages.value[index];
- URL.revokeObjectURL(img.url);
- croppedImages.value.splice(index, 1);
-};
-
-const handleImageDragStart = (
- event: DragEvent,
- img: CroppedImage,
- index: number,
-) => {
- draggingImageIndex.value = index;
+ const img = croppedImages.value[index]
+ URL.revokeObjectURL(img.url)
+ croppedImages.value.splice(index, 1)
+}
+
+const handleImageDragStart = (event: DragEvent, img: CroppedImage, index: number) => {
+ draggingImageIndex.value = index
if (event.dataTransfer) {
- event.dataTransfer.effectAllowed = "move";
+ event.dataTransfer.effectAllowed = 'move'
}
-};
+}
const handleImageDragEnd = () => {
- draggingImageIndex.value = null;
- dragOverFolder.value = null;
-};
+ draggingImageIndex.value = null
+ dragOverFolder.value = null
+}
const handleFolderDragOver = (folderType: string) => {
- dragOverFolder.value = folderType;
-};
+ dragOverFolder.value = folderType
+}
const handleFolderDragLeave = () => {
- dragOverFolder.value = null;
-};
+ dragOverFolder.value = null
+}
const handleFolderDrop = (event: DragEvent, folderType: string) => {
- event.preventDefault();
- dragOverFolder.value = null;
+ event.preventDefault()
+ dragOverFolder.value = null
- if (draggingImageIndex.value === null) return;
+ if (draggingImageIndex.value === null) return
- const img = croppedImages.value[draggingImageIndex.value];
- img.frameType = folderType;
- draggingImageIndex.value = null;
-};
+ const img = croppedImages.value[draggingImageIndex.value]
+ img.frameType = folderType
+ draggingImageIndex.value = null
+}
const getFrameTypeName = (type: string) => {
const map: Record<string, string> = {
- first: "首帧",
- last: "尾帧",
- key: "关键帧",
- };
- return map[type] || type;
-};
+ first: '首帧',
+ last: '尾帧',
+ key: '关键帧',
+ }
+ return map[type] || type
+}
const handleClose = () => {
croppedImages.value.forEach((img) => {
- URL.revokeObjectURL(img.url);
- });
- croppedImages.value = [];
- dialogVisible.value = false;
-};
+ URL.revokeObjectURL(img.url)
+ })
+ croppedImages.value = []
+ dialogVisible.value = false
+}
const handleSave = () => {
const imagesToSave = croppedImages.value
@@ -387,15 +336,15 @@ const handleSave = () => {
.map((img) => ({
blob: img.blob,
frameType: img.frameType!,
- }));
+ }))
if (imagesToSave.length === 0) {
- return;
+ return
}
- emit("save", imagesToSave);
- handleClose();
-};
+ emit('save', imagesToSave)
+ handleClose()
+}
</script>
<style>
@@ -639,7 +588,7 @@ const handleSave = () => {
.crop-canvas-wrapper :deep(.cropper-center::before),
.crop-canvas-wrapper :deep(.cropper-center::after) {
background-color: #eee;
- content: " ";
+ content: ' ';
display: block;
position: absolute;
}
diff --git a/web/src/components/editor/VideoTimelineEditor.vue b/web/src/components/editor/VideoTimelineEditor.vue
index 07da388..8876606 100644
--- a/web/src/components/editor/VideoTimelineEditor.vue
+++ b/web/src/components/editor/VideoTimelineEditor.vue
@@ -4,19 +4,12 @@
<div class="editor-toolbar">
<div class="toolbar-left">
<el-button-group>
- <el-button
- :icon="VideoPlay"
- @click="playTimeline"
- :disabled="timelineClips.length === 0"
- >{{ $t("common.play") }}</el-button
- >
- <el-button :icon="VideoPause" @click="pauseTimeline">{{
- $t("common.pause")
+ <el-button :icon="VideoPlay" @click="playTimeline" :disabled="timelineClips.length === 0">{{
+ $t('common.play')
}}</el-button>
+ <el-button :icon="VideoPause" @click="pauseTimeline">{{ $t('common.pause') }}</el-button>
</el-button-group>
- <span class="time-display"
- >{{ formatTime(currentTime) }} / {{ formatTime(totalDuration) }}</span
- >
+ <span class="time-display">{{ formatTime(currentTime) }} / {{ formatTime(totalDuration) }}</span>
</div>
<div class="toolbar-right">
<el-button
@@ -26,7 +19,7 @@
:disabled="timelineClips.length === 0"
:loading="serverMerging"
>
- {{ $t("video.merge") }}
+ {{ $t('video.merge') }}
</el-button>
</div>
</div>
@@ -65,11 +58,7 @@
:style="{ animationDuration: transitionState.duration + 's' }"
></div>
<!-- 播放/暂停图标覆盖层 -->
- <div
- class="video-play-overlay"
- :class="{ hidden: isPlaying }"
- v-if="currentPreviewUrl"
- >
+ <div class="video-play-overlay" :class="{ hidden: isPlaying }" v-if="currentPreviewUrl">
<el-icon :size="64"><VideoPlay /></el-icon>
</div>
<div class="preview-overlay" v-if="!currentPreviewUrl">
@@ -77,12 +66,7 @@
</div>
</div>
<div class="preview-controls">
- <el-slider
- v-model="currentTime"
- :max="totalDuration"
- :step="0.1"
- @change="seekToTime"
- />
+ <el-slider v-model="currentTime" :max="totalDuration" :step="0.1" @change="seekToTime" />
</div>
</div>
@@ -90,10 +74,8 @@
<div class="media-library">
<div class="library-header">
<div class="header-left">
- <h4>{{ $t("video.mediaLibrary") }}</h4>
- <span>{{
- $t("video.videoCount", { count: availableStoryboards.length })
- }}</span>
+ <h4>{{ $t('video.mediaLibrary') }}</h4>
+ <span>{{ $t('video.videoCount', { count: availableStoryboards.length }) }}</span>
</div>
<el-button
type="primary"
@@ -102,7 +84,7 @@
@click="addAllScenesInOrder"
:disabled="availableStoryboards.length === 0"
>
- {{ $t("common.addAll") }}
+ {{ $t('common.addAll') }}
</el-button>
</div>
<div class="media-grid">
@@ -115,9 +97,7 @@
>
<div class="media-thumbnail" @click="previewScene(scene)">
<video :src="scene.video_url" />
- <div class="media-duration">
- {{ scene.duration > 0 ? scene.duration.toFixed(1) : "?" }}s
- </div>
+ <div class="media-duration">{{ scene.duration > 0 ? scene.duration.toFixed(1) : '?' }}s</div>
<el-button
class="delete-btn"
type="danger"
@@ -127,22 +107,13 @@
@click.stop="deleteAsset(scene)"
/>
<div class="media-overlay">
- <el-button
- type="primary"
- size="small"
- :icon="Plus"
- @click.stop="addClipToTimeline(scene)"
- >
- {{ $t("common.addToTimeline") }}
+ <el-button type="primary" size="small" :icon="Plus" @click.stop="addClipToTimeline(scene)">
+ {{ $t('common.addToTimeline') }}
</el-button>
</div>
</div>
<div class="media-info">
- <div class="media-title">
- {{ $t("storyboard.shot") }} #{{
- scene.storyboard_num || scene.asset_id
- }}
- </div>
+ <div class="media-title">{{ $t('storyboard.shot') }} #{{ scene.storyboard_num || scene.asset_id }}</div>
</div>
</div>
</div>
@@ -155,7 +126,7 @@
<div class="zoom-controls">
<el-button-group size="small">
<el-button @click="zoomOut">-</el-button>
- <el-button @click="zoomReset">{{ $t("common.reset") }}</el-button>
+ <el-button @click="zoomReset">{{ $t('common.reset') }}</el-button>
<el-button @click="zoomIn">+</el-button>
</el-button-group>
<span class="zoom-level">{{ Math.round(zoom * 100) }}%</span>
@@ -180,8 +151,8 @@
<!-- 播放头 -->
<div class="playhead" :style="{ left: playheadPosition + 'px' }">
- <div class="playhead-line"></div>
- <div class="playhead-handle"></div>
+ <div class="playhead-line" @mousedown="startDragPlayhead"></div>
+ <div class="playhead-handle" @mousedown="startDragPlayhead"></div>
</div>
<!-- 视频轨道 -->
@@ -193,7 +164,7 @@
@click="clickTimeline($event)"
>
<div class="track-label">
- <span>{{ $t("video.videoTrack") }}</span>
+ <span>{{ $t('video.videoTrack') }}</span>
<el-button
type="text"
size="small"
@@ -220,22 +191,12 @@
<video :src="clip.video_url" />
</div>
<div class="clip-info">
- <div class="clip-title">
- {{ $t("storyboard.scene") }} {{ clip.storyboard_number }}
- </div>
- <div class="clip-duration">
- {{ clip.duration.toFixed(1) }}s
- </div>
+ <div class="clip-title">{{ $t('storyboard.scene') }} {{ clip.storyboard_number }}</div>
+ <div class="clip-duration">{{ clip.duration.toFixed(1) }}s</div>
</div>
</div>
- <div
- class="clip-resize-left"
- @mousedown.stop="startResizeClip($event, clip, 'left')"
- ></div>
- <div
- class="clip-resize-right"
- @mousedown.stop="startResizeClip($event, clip, 'right')"
- ></div>
+ <div class="clip-resize-left" @mousedown.stop="startResizeClip($event, clip, 'left')"></div>
+ <div class="clip-resize-right" @mousedown.stop="startResizeClip($event, clip, 'right')"></div>
<div class="clip-remove" @click.stop="removeClip(clip)">
<el-icon><Close /></el-icon>
</div>
@@ -250,9 +211,7 @@
@click.stop="openTransitionDialog(timelineClips[index])"
>
<el-icon><connection /></el-icon>
- <span class="transition-label">{{
- getTransitionLabel(timelineClips[index])
- }}</span>
+ <span class="transition-label">{{ getTransitionLabel(timelineClips[index]) }}</span>
</div>
</div>
</div>
@@ -265,7 +224,7 @@
@click="clickTimeline($event)"
>
<div class="track-label">
- <span>{{ $t("video.audioTrack") }}</span>
+ <span>{{ $t('video.audioTrack') }}</span>
<el-button
type="text"
size="small"
@@ -292,22 +251,12 @@
<el-icon><Microphone /></el-icon>
</div>
<div class="clip-info">
- <div class="clip-title">
- {{ $t("video.audio") }} {{ audio.order + 1 }}
- </div>
- <div class="clip-duration">
- {{ audio.duration.toFixed(1) }}s
- </div>
+ <div class="clip-title">{{ $t('video.audio') }} {{ audio.order + 1 }}</div>
+ <div class="clip-duration">{{ audio.duration.toFixed(1) }}s</div>
</div>
</div>
- <div
- class="clip-resize-left"
- @mousedown.stop="startResizeAudioClip($event, audio, 'left')"
- ></div>
- <div
- class="clip-resize-right"
- @mousedown.stop="startResizeAudioClip($event, audio, 'right')"
- ></div>
+ <div class="clip-resize-left" @mousedown.stop="startResizeAudioClip($event, audio, 'left')"></div>
+ <div class="clip-resize-right" @mousedown.stop="startResizeAudioClip($event, audio, 'right')"></div>
<div class="clip-remove" @click.stop="removeAudioClip(audio)">
<el-icon><Close /></el-icon>
</div>
@@ -318,17 +267,10 @@
</div>
<!-- 转场设置对话框 -->
- <el-dialog
- v-model="transitionDialogVisible"
- title="设置转场效果"
- width="500px"
- >
+ <el-dialog v-model="transitionDialogVisible" title="设置转场效果" width="500px">
<el-form label-width="100px">
<el-form-item :label="$t('video.transitionType')">
- <el-select
- v-model="editingTransition.type"
- :placeholder="$t('video.selectTransition')"
- >
+ <el-select v-model="editingTransition.type" :placeholder="$t('video.selectTransition')">
<el-option label="无转场" value="none" />
<!-- 淡入淡出类 -->
<el-option label="淡入淡出" value="fade" />
@@ -357,10 +299,7 @@
<el-option label="垂直关闭" value="vertclose" />
</el-select>
</el-form-item>
- <el-form-item
- :label="$t('video.transitionDuration')"
- v-if="editingTransition.type !== 'none'"
- >
+ <el-form-item :label="$t('video.transitionDuration')" v-if="editingTransition.type !== 'none'">
<el-slider
v-model="editingTransition.duration"
:min="0.3"
@@ -405,9 +344,7 @@
<el-progress
:percentage="mergeProgressDetail.progress"
- :status="
- mergeProgressDetail.phase === 'completed' ? 'success' : undefined
- "
+ :status="mergeProgressDetail.phase === 'completed' ? 'success' : undefined"
:stroke-width="20"
/>
@@ -439,8 +376,8 @@
</template>
<script setup lang="ts">
-import { ref, computed, onMounted, onUnmounted } from "vue";
-import { ElMessage, ElMessageBox } from "element-plus";
+import { ref, computed, onMounted, onUnmounted } from 'vue'
+import { ElMessage, ElMessageBox } from 'element-plus'
import {
VideoPlay,
VideoPause,
@@ -462,94 +399,94 @@ import {
Loading,
Headset,
Microphone,
-} from "@element-plus/icons-vue";
-import { videoMerger, type MergeProgress } from "@/utils/videoMerger";
-import { trimAndMergeVideos } from "@/utils/ffmpeg";
-import { getVideoUrl } from "@/utils/image";
+} from '@element-plus/icons-vue'
+import { videoMerger, type MergeProgress } from '@/utils/videoMerger'
+import { trimAndMergeVideos } from '@/utils/ffmpeg'
+import { getVideoUrl } from '@/utils/image'
interface Scene {
- id: string;
- storyboard_id: string;
- storyboard_number: number;
- title?: string;
- description?: string;
- location?: string;
- time?: string;
- video_url: string;
- asset_id?: string;
- duration?: number;
+ id: string
+ storyboard_id: string
+ storyboard_number: number
+ title?: string
+ description?: string
+ location?: string
+ time?: string
+ video_url: string
+ asset_id?: string
+ duration?: number
}
interface TimelineClip {
- id: string;
- storyboard_id: string;
- storyboard_number: number;
- video_url: string;
- asset_id?: string; // 素材库中的资源ID
- start_time: number;
- end_time: number;
- duration: number;
- position: number; // 在时间线上的位置(秒)
- order: number;
+ id: string
+ storyboard_id: string
+ storyboard_number: number
+ video_url: string
+ asset_id?: string // 素材库中的资源ID
+ start_time: number
+ end_time: number
+ duration: number
+ position: number // 在时间线上的位置(秒)
+ order: number
transition?: {
type:
- | "fade"
- | "fadeblack"
- | "fadewhite"
- | "fadegrays"
- | "slideleft"
- | "slideright"
- | "slideup"
- | "slidedown"
- | "wipeleft"
- | "wiperight"
- | "wipeup"
- | "wipedown"
- | "circleopen"
- | "circleclose"
- | "dissolve"
- | "distance"
- | "horzopen"
- | "horzclose"
- | "vertopen"
- | "vertclose"
- | "none";
- duration: number;
- };
- audio_url?: string; // 提取的音频URL
- muted?: boolean; // 是否静音
+ | 'fade'
+ | 'fadeblack'
+ | 'fadewhite'
+ | 'fadegrays'
+ | 'slideleft'
+ | 'slideright'
+ | 'slideup'
+ | 'slidedown'
+ | 'wipeleft'
+ | 'wiperight'
+ | 'wipeup'
+ | 'wipedown'
+ | 'circleopen'
+ | 'circleclose'
+ | 'dissolve'
+ | 'distance'
+ | 'horzopen'
+ | 'horzclose'
+ | 'vertopen'
+ | 'vertclose'
+ | 'none'
+ duration: number
+ }
+ audio_url?: string // 提取的音频URL
+ muted?: boolean // 是否静音
}
interface AudioClip {
- id: string;
- source_clip_id: string; // 关联的视频片段ID
- audio_url: string;
- start_time: number;
- end_time: number;
- duration: number;
- position: number;
- order: number;
- volume: number; // 音量 0-1
+ id: string
+ source_clip_id: string // 关联的视频片段ID
+ audio_url: string
+ start_time: number
+ end_time: number
+ duration: number
+ position: number
+ order: number
+ volume: number // 音量 0-1
}
const props = defineProps<{
- scenes: Scene[];
- episodeId: string;
- dramaId: string;
- assets?: any[];
-}>();
+ scenes: Scene[]
+ episodeId: string
+ dramaId: string
+ assets?: any[]
+}>()
const emit = defineEmits<{
- (e: "merge-completed", mergeId: number): void;
- (e: "asset-deleted"): void;
-}>();
+ (e: 'merge-completed', mergeId: number): void
+ (e: 'asset-deleted'): void
+}>()
// 基础状态
const availableStoryboards = computed(() => {
const assets = (props.assets || [])
.filter((a) => {
- const isValid = a.type === "video" && a.url;
- return isValid;
+ const isValid = a.type === 'video' && a.url
+ return isValid
})
.map((a) => ({
id: `asset_${a.id}`,
@@ -564,462 +501,432 @@ const availableStoryboards = computed(() => {
}))
.sort((a, b) => {
// 优先按storyboard_num排序,如果没有则按storyboard_id排序,最后按asset id排序
- const aNum = a.storyboard_num || a.storyboard_id || a.asset_id;
- const bNum = b.storyboard_num || b.storyboard_id || b.asset_id;
- return aNum - bNum;
- });
- return assets;
-});
-const timelineClips = ref<TimelineClip[]>([]);
-const audioClips = ref<AudioClip[]>([]);
-const selectedClipId = ref<string | null>(null);
-const selectedAudioClipId = ref<string | null>(null);
-const previewPlayer = ref<HTMLVideoElement | null>(null);
-const audioPlayer = ref<HTMLAudioElement | null>(null);
-const timelineContainer = ref<HTMLElement | null>(null);
-const showAudioTrack = ref(true); // 是否显示音频轨道
+ const aNum = a.storyboard_num || a.storyboard_id || a.asset_id
+ const bNum = b.storyboard_num || b.storyboard_id || b.asset_id
+ return aNum - bNum
+ })
+ return assets
+})
+const timelineClips = ref<TimelineClip[]>([])
+const audioClips = ref<AudioClip[]>([])
+const selectedClipId = ref<string | null>(null)
+const selectedAudioClipId = ref<string | null>(null)
+const previewPlayer = ref<HTMLVideoElement | null>(null)
+const audioPlayer = ref<HTMLAudioElement | null>(null)
+const timelineContainer = ref<HTMLElement | null>(null)
+const showAudioTrack = ref(true) // 是否显示音频轨道
// 时间线状态
-const currentTime = ref(0);
-const zoom = ref(1); // 缩放级别
-const pixelsPerSecond = computed(() => 50 * zoom.value); // 每秒对应的像素数
-const isPlaying = ref(false);
-const playbackTimer = ref<number | null>(null);
+const currentTime = ref(0)
+const zoom = ref(1) // 缩放级别
+const pixelsPerSecond = computed(() => 50 * zoom.value) // 每秒对应的像素数
+const isPlaying = ref(false)
+const playbackTimer = ref<number | null>(null)
// 转场预览状态(必须在模板使用前定义)
const transitionState = ref({
active: false,
- type: "fade",
- phase: "in" as "in" | "out",
+ type: 'fade',
+ phase: 'in' as 'in' | 'out',
duration: 1.0,
-});
+})
// 导出状态
-const merging = ref(false);
-const serverMerging = ref(false);
-const mergeProgress = ref(0);
-const mergeDialogVisible = ref(false);
+const merging = ref(false)
+const serverMerging = ref(false)
+const mergeProgress = ref(0)
+const mergeDialogVisible = ref(false)
const mergeProgressDetail = ref<MergeProgress>({
- phase: "loading",
+ phase: 'loading',
progress: 0,
- message: "",
-});
+ message: '',
+})
// 转场设置状态
-const transitionDialogVisible = ref(false);
-const editingTransitionClipId = ref<string | null>(null);
+const transitionDialogVisible = ref(false)
+const editingTransitionClipId = ref<string | null>(null)
const editingTransition = ref({
- type: "fade" as
- | "fade"
- | "fadeblack"
- | "fadewhite"
- | "fadegrays"
- | "slideleft"
- | "slideright"
- | "slideup"
- | "slidedown"
- | "wipeleft"
- | "wiperight"
- | "wipeup"
- | "wipedown"
- | "circleopen"
- | "circleclose"
- | "dissolve"
- | "distance"
- | "horzopen"
- | "horzclose"
- | "vertopen"
- | "vertclose"
- | "none",
+ type: 'fade' as
+ | 'fade'
+ | 'fadeblack'
+ | 'fadewhite'
+ | 'fadegrays'
+ | 'slideleft'
+ | 'slideright'
+ | 'slideup'
+ | 'slidedown'
+ | 'wipeleft'
+ | 'wiperight'
+ | 'wipeup'
+ | 'wipedown'
+ | 'circleopen'
+ | 'circleclose'
+ | 'dissolve'
+ | 'distance'
+ | 'horzopen'
+ | 'horzclose'
+ | 'vertopen'
+ | 'vertclose'
+ | 'none',
duration: 1.0,
-});
+})
// 计算总时长
const totalDuration = computed(() => {
- if (timelineClips.value.length === 0) return 0;
- const lastClip = timelineClips.value[timelineClips.value.length - 1];
- return lastClip ? lastClip.position + lastClip.duration : 0;
-});
+ if (timelineClips.value.length === 0) return 0
+ const lastClip = timelineClips.value[timelineClips.value.length - 1]
+ return lastClip ? lastClip.position + lastClip.duration : 0
+})
// 工具函数
const formatTime = (seconds: number) => {
- const mins = Math.floor(seconds / 60);
- const secs = Math.floor(seconds % 60);
- const ms = Math.floor((seconds % 1) * 10);
- return `${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}.${ms}`;
-};
+ const mins = Math.floor(seconds / 60)
+ const secs = Math.floor(seconds % 60)
+ const ms = Math.floor((seconds % 1) * 10)
+ return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}.${ms}`
+}
const getSceneDesc = (scene: Scene) => {
- const parts = [];
- if (scene.location) parts.push(scene.location);
- if (scene.time) parts.push(scene.time);
- return (
- parts.join(" · ") || scene.description?.slice(0, 15) + "..." || "无描述"
- );
-};
+ const parts = []
+ if (scene.location) parts.push(scene.location)
+ if (scene.time) parts.push(scene.time)
+ return parts.join(' · ') || scene.description?.slice(0, 15) + '...' || '无描述'
+}
// 预览相关
const currentPreviewUrl = computed(() => {
- if (timelineClips.value.length === 0) return "";
+ if (timelineClips.value.length === 0) return ''
// 根据当前时间找到应该播放的片段
const clip = timelineClips.value.find(
- (c) =>
- currentTime.value >= c.position &&
- currentTime.value < c.position + c.duration,
- );
- return clip?.video_url || timelineClips.value[0]?.video_url || "";
-});
+ (c) => currentTime.value >= c.position && currentTime.value < c.position + c.duration,
+ )
+ return clip?.video_url || timelineClips.value[0]?.video_url || ''
+})
// 当前音频URL
const currentAudioUrl = computed(() => {
- if (audioClips.value.length === 0) return "";
+ if (audioClips.value.length === 0) return ''
// 根据当前时间找到应该播放的音频片段
const audioClip = audioClips.value.find(
- (a) =>
- currentTime.value >= a.position &&
- currentTime.value < a.position + a.duration,
- );
- return audioClip?.audio_url || "";
-});
+ (a) => currentTime.value >= a.position && currentTime.value < a.position + a.duration,
+ )
+ return audioClip?.audio_url || ''
+})
const previewScene = (scene: Scene) => {
if (previewPlayer.value) {
- previewPlayer.value.src = scene.video_url;
- previewPlayer.value.play();
+ previewPlayer.value.src = scene.video_url
+ previewPlayer.value.play()
}
-};
+}
const handlePreviewLoaded = () => {
// 视频加载完成后跳转到正确的时间点
if (previewPlayer.value) {
const clip = timelineClips.value.find(
- (c) =>
- currentTime.value >= c.position &&
- currentTime.value < c.position + c.duration,
- );
+ (c) => currentTime.value >= c.position && currentTime.value < c.position + c.duration,
+ )
if (clip) {
- const offsetInClip = currentTime.value - clip.position;
- previewPlayer.value.currentTime = clip.start_time + offsetInClip;
+ const offsetInClip = currentTime.value - clip.position
+ previewPlayer.value.currentTime = clip.start_time + offsetInClip
}
}
-};
+}
const handleAudioLoaded = () => {
// 音频加载完成后跳转到正确的时间点
if (audioPlayer.value && audioClips.value.length > 0) {
const audioClip = audioClips.value.find(
- (a) =>
- currentTime.value >= a.position &&
- currentTime.value < a.position + a.duration,
- );
+ (a) => currentTime.value >= a.position && currentTime.value < a.position + a.duration,
+ )
if (audioClip) {
- const offsetInClip = currentTime.value - audioClip.position;
- audioPlayer.value.currentTime = audioClip.start_time + offsetInClip;
+ const offsetInClip = currentTime.value - audioClip.position
+ audioPlayer.value.currentTime = audioClip.start_time + offsetInClip
}
}
-};
+}
const handleAudioEnded = () => {
// 音频自然结束,尝试播放下一个音频片段
const currentAudio = audioClips.value.find(
- (a) =>
- currentTime.value >= a.position &&
- currentTime.value < a.position + a.duration,
- );
+ (a) => currentTime.value >= a.position && currentTime.value < a.position + a.duration,
+ )
if (currentAudio) {
- const currentIndex = audioClips.value.findIndex(
- (a) => a.id === currentAudio.id,
- );
- const nextAudio = audioClips.value[currentIndex + 1];
+ const currentIndex = audioClips.value.findIndex((a) => a.id === currentAudio.id)
+ const nextAudio = audioClips.value[currentIndex + 1]
if (nextAudio && isPlaying.value) {
// 有下一个音频片段且正在播放,继续
// 时间线会自动更新到下一个片段
}
}
-};
+}
const handlePreviewTimeUpdate = () => {
- if (!isPlaying.value || !previewPlayer.value) return;
+ if (!isPlaying.value || !previewPlayer.value) return
// 找到当前播放的片段
const currentClip = timelineClips.value.find(
- (c) =>
- currentTime.value >= c.position &&
- currentTime.value < c.position + c.duration,
- );
+ (c) => currentTime.value >= c.position && currentTime.value < c.position + c.duration,
+ )
if (!currentClip) {
- pauseTimeline();
- return;
+ pauseTimeline()
+ return
}
// 计算时间线上的当前位置
- const videoTime = previewPlayer.value.currentTime;
- const clipOffset = videoTime - currentClip.start_time;
- currentTime.value = currentClip.position + clipOffset;
+ const videoTime = previewPlayer.value.currentTime
+ const clipOffset = videoTime - currentClip.start_time
+ currentTime.value = currentClip.position + clipOffset
// 检查是否播放到片段结尾(提前0.1秒检测,避免播放完才切换)
if (videoTime >= currentClip.end_time - 0.1) {
// 查找下一个片段
- const currentIndex = timelineClips.value.findIndex(
- (c) => c.id === currentClip.id,
- );
- const nextClip = timelineClips.value[currentIndex + 1];
+ const currentIndex = timelineClips.value.findIndex((c) => c.id === currentClip.id)
+ const nextClip = timelineClips.value[currentIndex + 1]
if (nextClip) {
// 切换到下一个片段
- switchToClip(nextClip);
+ switchToClip(nextClip)
} else {
// 没有下一个片段,停止播放
- pauseTimeline();
- currentTime.value = totalDuration.value;
+ pauseTimeline()
+ currentTime.value = totalDuration.value
}
}
-};
+}
const switchToClip = async (clip: TimelineClip) => {
- if (!previewPlayer.value) return;
+ if (!previewPlayer.value) return
// 获取转场配置
- const transition = clip.transition;
- const hasTransition = transition && transition.type !== "none";
- const transitionDuration = hasTransition ? transition.duration * 1000 : 0;
+ const transition = clip.transition
+ const hasTransition = transition && transition.type !== 'none'
+ const transitionDuration = hasTransition ? transition.duration * 1000 : 0
if (hasTransition) {
// 触发转场效果
transitionState.value = {
active: true,
type: transition.type,
- phase: "out",
+ phase: 'out',
duration: transition.duration,
- };
+ }
// 等待转场动画完成一半
- await new Promise((resolve) => setTimeout(resolve, transitionDuration / 2));
+ await new Promise((resolve) => setTimeout(resolve, transitionDuration / 2))
}
// 暂停当前播放,避免冲突
- previewPlayer.value.pause();
+ previewPlayer.value.pause()
if (audioPlayer.value) {
- audioPlayer.value.pause();
+ audioPlayer.value.pause()
}
// 切换视频源
- currentTime.value = clip.position;
- previewPlayer.value.src = clip.video_url;
+ currentTime.value = clip.position
+ previewPlayer.value.src = clip.video_url
// 同步切换音频源
if (audioClips.value.length > 0 && audioPlayer.value) {
const audioClip = audioClips.value.find(
- (a) =>
- clip.position >= a.position && clip.position < a.position + a.duration,
- );
+ (a) => clip.position >= a.position && clip.position < a.position + a.duration,
+ )
if (audioClip) {
- audioPlayer.value.src = audioClip.audio_url;
+ audioPlayer.value.src = audioClip.audio_url
}
}
// 等待视频加载
try {
await new Promise((resolve, reject) => {
- if (!previewPlayer.value) return reject();
+ if (!previewPlayer.value) return reject()
const onCanPlay = () => {
- previewPlayer.value?.removeEventListener("canplay", onCanPlay);
- previewPlayer.value?.removeEventListener("error", onError);
- resolve(undefined);
- };
+ previewPlayer.value?.removeEventListener('canplay', onCanPlay)
+ previewPlayer.value?.removeEventListener('error', onError)
+ resolve(undefined)
+ }
const onError = () => {
- previewPlayer.value?.removeEventListener("canplay", onCanPlay);
- previewPlayer.value?.removeEventListener("error", onError);
- reject();
- };
+ previewPlayer.value?.removeEventListener('canplay', onCanPlay)
+ previewPlayer.value?.removeEventListener('error', onError)
+ reject()
+ }
- previewPlayer.value.addEventListener("canplay", onCanPlay);
- previewPlayer.value.addEventListener("error", onError);
- });
+ previewPlayer.value.addEventListener('canplay', onCanPlay)
+ previewPlayer.value.addEventListener('error', onError)
+ })
// 设置起始时间并播放
- previewPlayer.value.currentTime = clip.start_time;
+ previewPlayer.value.currentTime = clip.start_time
if (hasTransition) {
// 切换到转场入场阶段
- transitionState.value.phase = "in";
+ transitionState.value.phase = 'in'
// 等待转场剩余时间
setTimeout(() => {
- transitionState.value.active = false;
- }, transitionDuration / 2);
+ transitionState.value.active = false
+ }, transitionDuration / 2)
}
if (isPlaying.value) {
- await previewPlayer.value.play();
+ await previewPlayer.value.play()
// 同步播放音频
if (audioClips.value.length > 0 && audioPlayer.value) {
const audioClip = audioClips.value.find(
- (a) =>
- clip.position >= a.position &&
- clip.position < a.position + a.duration,
- );
+ (a) => clip.position >= a.position && clip.position < a.position + a.duration,
+ )
if (audioClip && audioPlayer.value.src) {
- audioPlayer.value.currentTime = audioClip.start_time;
+ audioPlayer.value.currentTime = audioClip.start_time
audioPlayer.value.play().catch((err) => {
- console.warn("音频播放失败:", err);
- });
+ console.warn('音频播放失败:', err)
+ })
}
}
}
} catch (error) {
- console.error("切换视频片段失败:", error);
- transitionState.value.active = false;
- pauseTimeline();
+ console.error('切换视频片段失败:', error)
+ transitionState.value.active = false
+ pauseTimeline()
}
-};
+}
const handlePreviewEnded = () => {
// 视频自然结束,尝试播放下一个片段
const currentClip = timelineClips.value.find(
- (c) =>
- currentTime.value >= c.position &&
- currentTime.value < c.position + c.duration,
- );
+ (c) => currentTime.value >= c.position && currentTime.value < c.position + c.duration,
+ )
if (currentClip) {
- const currentIndex = timelineClips.value.findIndex(
- (c) => c.id === currentClip.id,
- );
- const nextClip = timelineClips.value[currentIndex + 1];
+ const currentIndex = timelineClips.value.findIndex((c) => c.id === currentClip.id)
+ const nextClip = timelineClips.value[currentIndex + 1]
if (nextClip) {
- currentTime.value = nextClip.position;
- seekToTime(nextClip.position);
+ currentTime.value = nextClip.position
+ seekToTime(nextClip.position)
} else {
- pauseTimeline();
+ pauseTimeline()
}
}
-};
+}
// 时间线计算
const timelineWidth = computed(() => {
- const duration = Math.max(totalDuration.value, 30);
- const contentWidth = duration * pixelsPerSecond.value;
- const minContentWidth = 800; // 最小内容宽度
- return 100 + Math.max(contentWidth, minContentWidth) + 100; // 100px左边距 + 100px右边距
-});
+ const duration = Math.max(totalDuration.value, 30)
+ const contentWidth = duration * pixelsPerSecond.value
+ const minContentWidth = 800 // 最小内容宽度
+ return 100 + Math.max(contentWidth, minContentWidth) + 100 // 100px左边距 + 100px右边距
+})
const playheadPosition = computed(() => {
- return 100 + currentTime.value * pixelsPerSecond.value;
-});
+ return 100 + currentTime.value * pixelsPerSecond.value
+})
const timeRulerTicks = computed(() => {
- const ticks = [];
- const duration = Math.max(totalDuration.value, 30);
- const interval = zoom.value >= 1.5 ? 1 : zoom.value >= 0.5 ? 5 : 10;
+ const ticks = []
+ const duration = Math.max(totalDuration.value, 30)
+ const interval = zoom.value >= 1.5 ? 1 : zoom.value >= 0.5 ? 5 : 10
for (let i = 0; i <= duration; i += interval) {
ticks.push({
time: i,
position: 100 + i * pixelsPerSecond.value,
- type: i % (interval * 2) === 0 ? "major" : "minor",
- });
+ type: i % (interval * 2) === 0 ? 'major' : 'minor',
+ })
}
- return ticks;
-});
+ return ticks
+})
// 片段样式计算
const getClipStyle = (clip: TimelineClip) => {
return {
- left: 100 + clip.position * pixelsPerSecond.value + "px",
- width: clip.duration * pixelsPerSecond.value + "px",
- };
-};
+ left: 100 + clip.position * pixelsPerSecond.value + 'px',
+ width: clip.duration * pixelsPerSecond.value + 'px',
+ }
+}
// 拖拽场景到时间线
const handleDragStart = (event: DragEvent, scene: Scene) => {
if (event.dataTransfer) {
- event.dataTransfer.effectAllowed = "copy";
- event.dataTransfer.setData("scene", JSON.stringify(scene));
+ event.dataTransfer.effectAllowed = 'copy'
+ event.dataTransfer.setData('scene', JSON.stringify(scene))
}
-};
+}
const handleTrackDrop = (event: DragEvent) => {
- event.preventDefault();
- const sceneData = event.dataTransfer?.getData("scene");
- if (!sceneData) return;
+ event.preventDefault()
+ const sceneData = event.dataTransfer?.getData('scene')
+ if (!sceneData) return
- const scene = JSON.parse(sceneData) as Scene;
+ const scene = JSON.parse(sceneData) as Scene
// 默认添加到末尾,不使用拖拽位置(避免产生空隙)
- addClipToTimeline(scene);
-};
+ addClipToTimeline(scene)
+}
const getVideoDuration = (videoUrl: string): Promise<number> => {
return new Promise((resolve, reject) => {
- const video = document.createElement("video");
- video.preload = "metadata";
- video.src = videoUrl;
+ const video = document.createElement('video')
+ video.preload = 'metadata'
+ video.src = videoUrl
video.onloadedmetadata = () => {
- const duration = video.duration;
- video.remove();
- resolve(duration);
- };
+ const duration = video.duration
+ video.remove()
+ resolve(duration)
+ }
video.onerror = () => {
- video.remove();
- reject(new Error("Failed to load video"));
- };
- });
-};
+ video.remove()
+ reject(new Error('Failed to load video'))
+ }
+ })
+}
const addClipToTimeline = async (scene: Scene, insertAtPosition?: number) => {
// 获取视频真实时长
- let videoDuration = scene.duration || 5;
+ let videoDuration = scene.duration || 5
if (scene.video_url) {
try {
- videoDuration = await getVideoDuration(scene.video_url);
+ videoDuration = await getVideoDuration(scene.video_url)
} catch (error) {
- console.warn(
- "Failed to get video duration, using default or scene duration:",
- error,
- );
- videoDuration = scene.duration || 5;
+ console.warn('Failed to get video duration, using default or scene duration:', error)
+ videoDuration = scene.duration || 5
}
}
// 计算新片段的位置
- let clipPosition: number;
- let insertAfterIndex: number | null = null;
+ let clipPosition: number
+ let insertAfterIndex: number | null = null
if (insertAtPosition !== undefined && timelineClips.value.length > 0) {
// 如果指定了插入位置,找到应该插入的位置
- clipPosition = insertAtPosition;
+ clipPosition = insertAtPosition
} else if (selectedClipId.value && timelineClips.value.length > 0) {
// 如果有选中的片段,插入到选中片段之后
- const selectedIndex = timelineClips.value.findIndex(
- (c) => c.id === selectedClipId.value,
- );
+ const selectedIndex = timelineClips.value.findIndex((c) => c.id === selectedClipId.value)
if (selectedIndex !== -1) {
- const selectedClip = timelineClips.value[selectedIndex];
- clipPosition = selectedClip.position + selectedClip.duration;
- insertAfterIndex = selectedIndex;
+ const selectedClip = timelineClips.value[selectedIndex]
+ clipPosition = selectedClip.position + selectedClip.duration
+ insertAfterIndex = selectedIndex
} else {
// 选中的片段不存在,添加到末尾
- const lastClip = timelineClips.value[timelineClips.value.length - 1];
- clipPosition = lastClip.position + lastClip.duration;
+ const lastClip = timelineClips.value[timelineClips.value.length - 1]
+ clipPosition = lastClip.position + lastClip.duration
}
} else {
// 默认添加到末尾(紧密连接)
if (timelineClips.value.length === 0) {
- clipPosition = 0; // 第一个片段从0开始
+ clipPosition = 0 // 第一个片段从0开始
} else {
// 添加到最后一个片段的结尾
- const lastClip = timelineClips.value[timelineClips.value.length - 1];
- clipPosition = lastClip.position + lastClip.duration;
+ const lastClip = timelineClips.value[timelineClips.value.length - 1]
+ clipPosition = lastClip.position + lastClip.duration
}
}
@@ -1035,232 +942,223 @@ const addClipToTimeline = async (scene: Scene, insertAtPosition?: number) => {
position: clipPosition,
order: timelineClips.value.length,
transition: {
- type: "fade",
+ type: 'fade',
duration: 1.0,
},
- };
+ }
// 如果是插入到中间,需要调整后续片段的位置
- if (
- insertAfterIndex !== null &&
- insertAfterIndex < timelineClips.value.length - 1
- ) {
- const newDuration = newClip.duration;
+ if (insertAfterIndex !== null && insertAfterIndex < timelineClips.value.length - 1) {
+ const newDuration = newClip.duration
// 将后续所有片段向后移动
for (let i = insertAfterIndex + 1; i < timelineClips.value.length; i++) {
- timelineClips.value[i].position += newDuration;
+ timelineClips.value[i].position += newDuration
}
}
- timelineClips.value.push(newClip);
- timelineClips.value.sort((a, b) => a.position - b.position);
- updateClipOrders();
+ timelineClips.value.push(newClip)
+ timelineClips.value.sort((a, b) => a.position - b.position)
+ updateClipOrders()
// 选中新添加的片段
- selectedClipId.value = newClip.id;
+ selectedClipId.value = newClip.id
- const insertInfo = insertAfterIndex !== null ? "(已插入到选中片段后)" : "";
- ElMessage.success(`已添加到时间线${insertInfo}`);
-};
+ const insertInfo = insertAfterIndex !== null ? '(已插入到选中片段后)' : ''
+ ElMessage.success(`已添加到时间线${insertInfo}`)
+}
// 一键添加全部场景
const addAllScenesInOrder = async () => {
if (availableStoryboards.value.length === 0) {
- ElMessage.warning("没有可用的场景");
- return;
+ ElMessage.warning('没有可用的场景')
+ return
}
// 按场景编号排序
- const sortedScenes = [...availableStoryboards.value].sort(
- (a, b) => a.storyboard_number - b.storyboard_number,
- );
+ const sortedScenes = [...availableStoryboards.value].sort((a, b) => a.storyboard_number - b.storyboard_number)
// 清空当前选中,让所有场景都添加到末尾
- selectedClipId.value = null;
+ selectedClipId.value = null
// 批量添加(顺序添加以确保正确的时长)
for (const scene of sortedScenes) {
- await addClipToTimeline(scene);
+ await addClipToTimeline(scene)
}
- ElMessage.success(`已批量添加 ${sortedScenes.length} 个场景到时间线`);
-};
+ ElMessage.success(`已批量添加 ${sortedScenes.length} 个场景到时间线`)
+}
// 删除素材
const deleteAsset = async (scene: any) => {
if (!scene.isAsset) {
- ElMessage.warning("只能删除素材库中的视频");
- return;
+ ElMessage.warning('只能删除素材库中的视频')
+ return
}
try {
// 直接调用API删除
- const { assetAPI } = await import("@/api/asset");
- await assetAPI.deleteAsset(scene.asset_id);
+ const { assetAPI } = await import('@/api/asset')
+ await assetAPI.deleteAsset(scene.asset_id)
- ElMessage.success("删除成功");
+ ElMessage.success('删除成功')
// 通知父组件刷新素材列表
- emit("asset-deleted");
+ emit('asset-deleted')
} catch (error: any) {
- console.error("删除素材失败:", error);
- ElMessage.error(error.message || "删除失败");
+ console.error('删除素材失败:', error)
+ ElMessage.error(error.message || '删除失败')
}
-};
+}
// 转场相关方法
const getTransitionStyle = (clip: TimelineClip) => {
// 转场指示器显示在片段开始位置
return {
- left: 100 + clip.position * pixelsPerSecond.value - 15 + "px",
- };
-};
+ left: 100 + clip.position * pixelsPerSecond.value - 15 + 'px',
+ }
+}
const getTransitionLabel = (clip: TimelineClip) => {
- if (!clip.transition || clip.transition.type === "none") {
- return "无";
+ if (!clip.transition || clip.transition.type === 'none') {
+ return '无'
}
const labels: Record<string, string> = {
- fade: "淡入",
- fadeblack: "黑场",
- fadewhite: "白场",
- fadegrays: "灰场",
- slideleft: "左滑",
- slideright: "右滑",
- slideup: "上滑",
- slidedown: "下滑",
- wipeleft: "左擦",
- wiperight: "右擦",
- wipeup: "上擦",
- wipedown: "下擦",
- circleopen: "圆开",
- circleclose: "圆关",
- dissolve: "溶解",
- distance: "距离",
- horzopen: "水平开",
- horzclose: "水平关",
- vertopen: "垂直开",
- vertclose: "垂直关",
- };
- return labels[clip.transition.type] || "转场";
-};
+ fade: '淡入',
+ fadeblack: '黑场',
+ fadewhite: '白场',
+ fadegrays: '灰场',
+ slideleft: '左滑',
+ slideright: '右滑',
+ slideup: '上滑',
+ slidedown: '下滑',
+ wipeleft: '左擦',
+ wiperight: '右擦',
+ wipeup: '上擦',
+ wipedown: '下擦',
+ circleopen: '圆开',
+ circleclose: '圆关',
+ dissolve: '溶解',
+ distance: '距离',
+ horzopen: '水平开',
+ horzclose: '水平关',
+ vertopen: '垂直开',
+ vertclose: '垂直关',
+ }
+ return labels[clip.transition.type] || '转场'
+}
const openTransitionDialog = (clip: TimelineClip) => {
- console.log("🎬 打开转场设置对话框:", {
+ console.log('🎬 打开转场设置对话框:', {
clip_id: clip.id,
storyboard_id: clip.storyboard_id,
order: clip.order,
current_transition: clip.transition,
- });
- editingTransitionClipId.value = clip.id;
+ })
+ editingTransitionClipId.value = clip.id
editingTransition.value = {
- type: clip.transition?.type || "fade",
+ type: clip.transition?.type || 'fade',
duration: clip.transition?.duration || 1.0,
- };
- transitionDialogVisible.value = true;
-};
+ }
+ transitionDialogVisible.value = true
+}
const applyTransition = () => {
- const clip = timelineClips.value.find(
- (c) => c.id === editingTransitionClipId.value,
- );
+ const clip = timelineClips.value.find((c) => c.id === editingTransitionClipId.value)
if (clip) {
clip.transition = {
type: editingTransition.value.type,
duration: editingTransition.value.duration,
- };
- console.log("✅ 转场效果已设置:", {
+ }
+ console.log('✅ 转场效果已设置:', {
clip_id: clip.id,
storyboard_id: clip.storyboard_id,
order: clip.order,
transition: clip.transition,
- });
- ElMessage.success("转场效果已设置");
+ })
+ ElMessage.success('转场效果已设置')
} else {
- console.error("❌ 未找到目标片段:", editingTransitionClipId.value);
+ console.error('❌ 未找到目标片段:', editingTransitionClipId.value)
}
- transitionDialogVisible.value = false;
-};
+ transitionDialogVisible.value = false
+}
// 选择和删除片段
const selectClip = (clip: TimelineClip) => {
- selectedClipId.value = clip.id;
-};
+ selectedClipId.value = clip.id
+}
const removeClip = (clip: TimelineClip) => {
- const index = timelineClips.value.findIndex((c) => c.id === clip.id);
+ const index = timelineClips.value.findIndex((c) => c.id === clip.id)
if (index !== -1) {
- timelineClips.value.splice(index, 1);
- updateClipOrders();
+ timelineClips.value.splice(index, 1)
+ updateClipOrders()
// 同时移除关联的音频片段
- const audioIndex = audioClips.value.findIndex(
- (a) => a.source_clip_id === clip.id,
- );
+ const audioIndex = audioClips.value.findIndex((a) => a.source_clip_id === clip.id)
if (audioIndex !== -1) {
- audioClips.value.splice(audioIndex, 1);
- updateAudioClipOrders();
+ audioClips.value.splice(audioIndex, 1)
+ updateAudioClipOrders()
}
}
-};
+}
const clearAllClips = () => {
- if (timelineClips.value.length === 0) return;
-
- timelineClips.value = [];
- audioClips.value = [];
- selectedClipId.value = null;
- selectedAudioClipId.value = null;
- currentTime.value = 0;
- ElMessage.success("已清空轨道");
-};
+ if (timelineClips.value.length === 0) return
+
+ timelineClips.value = []
+ audioClips.value = []
+ selectedClipId.value = null
+ selectedAudioClipId.value = null
+ currentTime.value = 0
+ ElMessage.success('已清空轨道')
+}
const updateClipOrders = () => {
timelineClips.value.forEach((clip, index) => {
- clip.order = index;
- });
-};
+ clip.order = index
+ })
+}
// 音频片段管理
const extractAllAudio = async () => {
if (timelineClips.value.length === 0) {
- ElMessage.warning("时间线上没有视频片段");
- return;
+ ElMessage.warning('时间线上没有视频片段')
+ return
}
const loadingMessage = ElMessage.info({
- message: "正在从视频中提取音频轨道,请稍候...",
+ message: '正在从视频中提取音频轨道,请稍候...',
duration: 0,
- });
+ })
try {
// 清空现有音频
- audioClips.value = [];
+ audioClips.value = []
// 收集所有视频URL
- const videoUrls = timelineClips.value.map((clip) => clip.video_url);
+ const videoUrls = timelineClips.value.map((clip) => clip.video_url)
// 调用后端API批量提取音频
- const { audioAPI } = await import("@/api/audio");
- const response = await audioAPI.batchExtractAudio(videoUrls);
+ const { audioAPI } = await import('@/api/audio')
+ const response = await audioAPI.batchExtractAudio(videoUrls)
if (!response.results || response.results.length === 0) {
- throw new Error("音频提取失败,未返回结果");
+ throw new Error('音频提取失败,未返回结果')
}
// 为每个视频片段创建对应的音频片段
timelineClips.value.forEach((clip, index) => {
- const extractedAudio = response.results[index];
+ const extractedAudio = response.results[index]
if (!extractedAudio) {
- console.warn(`视频片段 ${index} 未能提取音频`);
- return;
+ console.warn(`视频片段 ${index} 未能提取音频`)
+ return
}
// 验证音频时长
- const audioDuration = extractedAudio.duration;
+ const audioDuration = extractedAudio.duration
if (!audioDuration || audioDuration <= 0) {
- console.error(`音频片段 ${index} 时长无效:`, audioDuration);
- throw new Error(`音频片段 ${index + 1} 时长无效`);
+ console.error(`音频片段 ${index} 时长无效:`, audioDuration)
+ throw new Error(`音频片段 ${index + 1} 时长无效`)
}
console.log(`音频片段 ${index}:`, {
@@ -1269,7 +1167,7 @@ const extractAllAudio = async () => {
video_position: clip.position,
video_url: clip.video_url,
audio_url: extractedAudio.audio_url,
- });
+ })
const audioClip: AudioClip = {
id: `audio_${Date.now()}_${index}`,
@@ -1281,47 +1179,47 @@ const extractAllAudio = async () => {
position: clip.position, // 和视频片段在时间轴上相同位置
order: index,
volume: 1.0,
- };
- audioClips.value.push(audioClip);
- });
+ }
+ audioClips.value.push(audioClip)
+ })
- updateAudioClipOrders();
- loadingMessage.close();
- ElMessage.success(`已成功提取 ${audioClips.value.length} 个音频片段`);
+ updateAudioClipOrders()
+ loadingMessage.close()
+ ElMessage.success(`已成功提取 ${audioClips.value.length} 个音频片段`)
} catch (error: any) {
- console.error("提取音频失败:", error);
- loadingMessage.close();
- ElMessage.error(error.message || "音频提取失败,请重试");
+ console.error('提取音频失败:', error)
+ loadingMessage.close()
+ ElMessage.error(error.message || '音频提取失败,请重试')
// 清空部分提取的音频
- audioClips.value = [];
+ audioClips.value = []
}
-};
+}
const selectAudioClip = (audio: AudioClip) => {
- selectedAudioClipId.value = audio.id;
+ selectedAudioClipId.value = audio.id
// 取消选中视频片段
- selectedClipId.value = null;
-};
+ selectedClipId.value = null
+}
const removeAudioClip = (audio: AudioClip) => {
- const index = audioClips.value.findIndex((a) => a.id === audio.id);
+ const index = audioClips.value.findIndex((a) => a.id === audio.id)
if (index !== -1) {
- audioClips.value.splice(index, 1);
- updateAudioClipOrders();
+ audioClips.value.splice(index, 1)
+ updateAudioClipOrders()
}
-};
+}
const updateAudioClipOrders = () => {
audioClips.value.forEach((clip, index) => {
- clip.order = index;
- });
-};
+ clip.order = index
+ })
+}
// 拖拽音频片段
const startDragAudioClip = (event: MouseEvent, audio: AudioClip) => {
- if (dragState.value.isResizing) return;
+ if (dragState.value.isResizing) return
- event.stopPropagation();
+ event.stopPropagation()
dragState.value = {
isDragging: true,
isResizing: false,
@@ -1330,45 +1228,41 @@ const startDragAudioClip = (event: MouseEvent, audio: AudioClip) => {
startPosition: audio.position,
startTime: 0,
originalDuration: audio.duration,
- };
+ }
- selectedAudioClipId.value = audio.id;
- document.addEventListener("mousemove", handleDragAudioMove);
- document.addEventListener("mouseup", handleDragAudioEnd);
-};
+ selectedAudioClipId.value = audio.id
+ document.addEventListener('mousemove', handleDragAudioMove)
+ document.addEventListener('mouseup', handleDragAudioEnd)
+}
const handleDragAudioMove = (event: MouseEvent) => {
- if (!dragState.value.isDragging || !dragState.value.clipId) return;
+ if (!dragState.value.isDragging || !dragState.value.clipId) return
- const audio = audioClips.value.find((a) => a.id === dragState.value.clipId);
- if (!audio) return;
+ const audio = audioClips.value.find((a) => a.id === dragState.value.clipId)
+ if (!audio) return
- const deltaX = event.clientX - dragState.value.startX;
- const deltaTime = deltaX / pixelsPerSecond.value;
- const newPosition = Math.max(0, dragState.value.startPosition + deltaTime);
+ const deltaX = event.clientX - dragState.value.startX
+ const deltaTime = deltaX / pixelsPerSecond.value
+ const newPosition = Math.max(0, dragState.value.startPosition + deltaTime)
- audio.position = newPosition;
-};
+ audio.position = newPosition
+}
const handleDragAudioEnd = () => {
- dragState.value.isDragging = false;
- dragState.value.clipId = null;
+ dragState.value.isDragging = false
+ dragState.value.clipId = null
- document.removeEventListener("mousemove", handleDragAudioMove);
- document.removeEventListener("mouseup", handleDragAudioEnd);
+ document.removeEventListener('mousemove', handleDragAudioMove)
+ document.removeEventListener('mouseup', handleDragAudioEnd)
// 重新排序
- audioClips.value.sort((a, b) => a.position - b.position);
- updateAudioClipOrders();
-};
+ audioClips.value.sort((a, b) => a.position - b.position)
+ updateAudioClipOrders()
+}
// 调整音频片段大小
-const startResizeAudioClip = (
- event: MouseEvent,
- audio: AudioClip,
- side: "left" | "right",
-) => {
- event.stopPropagation();
+const startResizeAudioClip = (event: MouseEvent, audio: AudioClip, side: 'left' | 'right') => {
+ event.stopPropagation()
dragState.value = {
isDragging: false,
@@ -1379,62 +1273,56 @@ const startResizeAudioClip = (
startPosition: audio.position,
startTime: audio.start_time,
originalDuration: audio.duration,
- };
+ }
- selectedAudioClipId.value = audio.id;
- document.addEventListener("mousemove", handleResizeAudioMove);
- document.addEventListener("mouseup", handleResizeAudioEnd);
-};
+ selectedAudioClipId.value = audio.id
+ document.addEventListener('mousemove', handleResizeAudioMove)
+ document.addEventListener('mouseup', handleResizeAudioEnd)
+}
const handleResizeAudioMove = (event: MouseEvent) => {
- if (!dragState.value.isResizing || !dragState.value.clipId) return;
+ if (!dragState.value.isResizing || !dragState.value.clipId) return
- const audio = audioClips.value.find((a) => a.id === dragState.value.clipId);
- if (!audio) return;
+ const audio = audioClips.value.find((a) => a.id === dragState.value.clipId)
+ if (!audio) return
- const deltaX = event.clientX - dragState.value.startX;
- const deltaTime = deltaX / pixelsPerSecond.value;
+ const deltaX = event.clientX - dragState.value.startX
+ const deltaTime = deltaX / pixelsPerSecond.value
- if (dragState.value.resizeSide === "left") {
- const newStartTime = Math.max(0, dragState.value.startTime + deltaTime);
- const maxStartTime =
- dragState.value.startTime + dragState.value.originalDuration - 0.1;
+ if (dragState.value.resizeSide === 'left') {
+ const newStartTime = Math.max(0, dragState.value.startTime + deltaTime)
+ const maxStartTime = dragState.value.startTime + dragState.value.originalDuration - 0.1
- audio.start_time = Math.min(newStartTime, maxStartTime);
- audio.position = dragState.value.startPosition + deltaTime;
- audio.duration =
- dragState.value.originalDuration -
- (audio.start_time - dragState.value.startTime);
+ audio.start_time = Math.min(newStartTime, maxStartTime)
+ audio.position = dragState.value.startPosition + deltaTime
+ audio.duration = dragState.value.originalDuration - (audio.start_time - dragState.value.startTime)
} else {
- const newDuration = Math.max(
- 0.1,
- dragState.value.originalDuration + deltaTime,
- );
- const maxDuration = audio.end_time - audio.start_time;
+ const newDuration = Math.max(0.1, dragState.value.originalDuration + deltaTime)
+ const maxDuration = audio.end_time - audio.start_time
- audio.duration = Math.min(newDuration, maxDuration);
- audio.end_time = audio.start_time + audio.duration;
+ audio.duration = Math.min(newDuration, maxDuration)
+ audio.end_time = audio.start_time + audio.duration
}
-};
+}
const handleResizeAudioEnd = () => {
- dragState.value.isResizing = false;
- dragState.value.clipId = null;
+ dragState.value.isResizing = false
+ dragState.value.clipId = null
- document.removeEventListener("mousemove", handleResizeAudioMove);
- document.removeEventListener("mouseup", handleResizeAudioEnd);
-};
+ document.removeEventListener('mousemove', handleResizeAudioMove)
+ document.removeEventListener('mouseup', handleResizeAudioEnd)
+}
// 拖拽和调整片段
interface DragState {
- isDragging: boolean;
- isResizing: boolean;
- resizeSide?: "left" | "right";
- clipId: string | null;
- startX: number;
- startPosition: number;
- startTime: number;
- originalDuration: number;
+ isDragging: boolean
+ isResizing: boolean
+ resizeSide?: 'left' | 'right'
+ clipId: string | null
+ startX: number
+ startPosition: number
+ startTime: number
+ originalDuration: number
}
const dragState = ref<DragState>({
@@ -1445,13 +1333,13 @@ const dragState = ref<DragState>({
startPosition: 0,
startTime: 0,
originalDuration: 0,
-});
+})
// 拖拽移动片段位置
const startDragClip = (event: MouseEvent, clip: TimelineClip) => {
- if (dragState.value.isResizing) return;
+ if (dragState.value.isResizing) return
- event.stopPropagation();
+ event.stopPropagation()
dragState.value = {
isDragging: true,
isResizing: false,
@@ -1460,34 +1348,34 @@ const startDragClip = (event: MouseEvent, clip: TimelineClip) => {
startPosition: clip.position,
startTime: 0,
originalDuration: clip.duration,
- };
+ }
- selectedClipId.value = clip.id;
- document.addEventListener("mousemove", handleDragMove);
- document.addEventListener("mouseup", handleDragEnd);
-};
+ selectedClipId.value = clip.id
+ document.addEventListener('mousemove', handleDragMove)
+ document.addEventListener('mouseup', handleDragEnd)
+}
const handleDragMove = (event: MouseEvent) => {
- if (!dragState.value.clipId) return;
+ if (!dragState.value.clipId) return
- const clip = timelineClips.value.find((c) => c.id === dragState.value.clipId);
- if (!clip) return;
+ const clip = timelineClips.value.find((c) => c.id === dragState.value.clipId)
+ if (!clip) return
if (dragState.value.isDragging) {
// 计算新位置
- const deltaX = event.clientX - dragState.value.startX;
- const deltaTime = deltaX / pixelsPerSecond.value;
- let newPosition = Math.max(0, dragState.value.startPosition + deltaTime);
+ const deltaX = event.clientX - dragState.value.startX
+ const deltaTime = deltaX / pixelsPerSecond.value
+ let newPosition = Math.max(0, dragState.value.startPosition + deltaTime)
// 吸附到其他片段边缘
- newPosition = snapToNearby(newPosition, clip.id, clip.duration);
+ newPosition = snapToNearby(newPosition, clip.id, clip.duration)
- clip.position = newPosition;
- updateClipOrders();
+ clip.position = newPosition
+ updateClipOrders()
} else if (dragState.value.isResizing) {
- handleResizeMove(event, clip);
+ handleResizeMove(event, clip)
}
-};
+}
const handleDragEnd = () => {
dragState.value = {
@@ -1498,33 +1386,29 @@ const handleDragEnd = () => {
startPosition: 0,
startTime: 0,
originalDuration: 0,
- };
+ }
- document.removeEventListener("mousemove", handleDragMove);
- document.removeEventListener("mouseup", handleDragEnd);
+ document.removeEventListener('mousemove', handleDragMove)
+ document.removeEventListener('mouseup', handleDragEnd)
// 重新排序片段并紧密连接
- timelineClips.value.sort((a, b) => a.position - b.position);
- compactClips();
- updateClipOrders();
-};
+ timelineClips.value.sort((a, b) => a.position - b.position)
+ compactClips()
+ updateClipOrders()
+}
// 紧密排列所有片段(消除空隙)
const compactClips = () => {
- let currentPosition = 0;
+ let currentPosition = 0
for (const clip of timelineClips.value) {
- clip.position = currentPosition;
- currentPosition += clip.duration;
+ clip.position = currentPosition
+ currentPosition += clip.duration
}
-};
+}
// 调整片段时长
-const startResizeClip = (
- event: MouseEvent,
- clip: TimelineClip,
- side: "left" | "right",
-) => {
- event.stopPropagation();
+const startResizeClip = (event: MouseEvent, clip: TimelineClip, side: 'left' | 'right') => {
+ event.stopPropagation()
dragState.value = {
isDragging: false,
@@ -1533,362 +1417,389 @@ const startResizeClip = (
clipId: clip.id,
startX: event.clientX,
startPosition: clip.position,
- startTime: side === "left" ? clip.start_time : clip.end_time,
+ startTime: side === 'left' ? clip.start_time : clip.end_time,
originalDuration: clip.duration,
- };
+ }
- selectedClipId.value = clip.id;
- document.addEventListener("mousemove", handleDragMove);
- document.addEventListener("mouseup", handleDragEnd);
-};
+ selectedClipId.value = clip.id
+ document.addEventListener('mousemove', handleDragMove)
+ document.addEventListener('mouseup', handleDragEnd)
+}
const handleResizeMove = (event: MouseEvent, clip: TimelineClip) => {
- const deltaX = event.clientX - dragState.value.startX;
- const deltaTime = deltaX / pixelsPerSecond.value;
+ const deltaX = event.clientX - dragState.value.startX
+ const deltaTime = deltaX / pixelsPerSecond.value
- if (dragState.value.resizeSide === "left") {
+ if (dragState.value.resizeSide === 'left') {
// 调整开始时间(不改变位置,只改变裁剪点)
- const newStartTime = Math.max(0, dragState.value.startTime + deltaTime);
- const maxStartTime = clip.end_time - 0.1; // 至少保留0.1秒
+ const newStartTime = Math.max(0, dragState.value.startTime + deltaTime)
+ const maxStartTime = clip.end_time - 0.1 // 至少保留0.1秒
- clip.start_time = Math.min(newStartTime, maxStartTime);
- clip.duration = clip.end_time - clip.start_time;
+ clip.start_time = Math.min(newStartTime, maxStartTime)
+ clip.duration = clip.end_time - clip.start_time
// 调整左边缘后需要重新紧密连接
- const clipIndex = timelineClips.value.findIndex((c) => c.id === clip.id);
+ const clipIndex = timelineClips.value.findIndex((c) => c.id === clip.id)
if (clipIndex > 0) {
// 调整前面片段的结束位置
- compactClipsFromIndex(clipIndex);
+ compactClipsFromIndex(clipIndex)
}
} else {
// 调整结束时间
- const scene = props.scenes.find((s) => s.id === clip.scene_id);
- const maxDuration = scene?.duration || 10;
- const maxEndTime = clip.start_time + maxDuration;
+ const scene = props.scenes.find((s) => s.id === clip.scene_id)
+ const maxDuration = scene?.duration || 10
+ const maxEndTime = clip.start_time + maxDuration
- const newEndTime = Math.max(
- clip.start_time + 0.1,
- dragState.value.startTime + deltaTime,
- );
- clip.end_time = Math.min(newEndTime, maxEndTime);
- clip.duration = clip.end_time - clip.start_time;
+ const newEndTime = Math.max(clip.start_time + 0.1, dragState.value.startTime + deltaTime)
+ clip.end_time = Math.min(newEndTime, maxEndTime)
+ clip.duration = clip.end_time - clip.start_time
// 调整右边缘后需要重新紧密连接后续片段
- const clipIndex = timelineClips.value.findIndex((c) => c.id === clip.id);
+ const clipIndex = timelineClips.value.findIndex((c) => c.id === clip.id)
if (clipIndex < timelineClips.value.length - 1) {
- compactClipsFromIndex(clipIndex + 1);
+ compactClipsFromIndex(clipIndex + 1)
}
}
-};
+}
// 从指定索引开始重新紧密排列片段
const compactClipsFromIndex = (startIndex: number) => {
- if (startIndex >= timelineClips.value.length) return;
+ if (startIndex >= timelineClips.value.length) return
for (let i = startIndex; i < timelineClips.value.length; i++) {
if (i === 0) {
- timelineClips.value[i].position = 0;
+ timelineClips.value[i].position = 0
} else {
- const prevClip = timelineClips.value[i - 1];
- timelineClips.value[i].position = prevClip.position + prevClip.duration;
+ const prevClip = timelineClips.value[i - 1]
+ timelineClips.value[i].position = prevClip.position + prevClip.duration
}
}
-};
+}
// 吸附到附近片段
-const snapToNearby = (
- position: number,
- clipId: string,
- duration: number,
-): number => {
- const snapThreshold = 5 / pixelsPerSecond.value; // 5像素的吸附范围
+const snapToNearby = (position: number, clipId: string, duration: number): number => {
+ const snapThreshold = 5 / pixelsPerSecond.value // 5像素的吸附范围
for (const other of timelineClips.value) {
- if (other.id === clipId) continue;
+ if (other.id === clipId) continue
- const otherEnd = other.position + other.duration;
+ const otherEnd = other.position + other.duration
// 吸附到前一个片段的结尾
if (Math.abs(position - otherEnd) < snapThreshold) {
- return otherEnd;
+ return otherEnd
}
// 吸附到后一个片段的开头
if (Math.abs(position + duration - other.position) < snapThreshold) {
- return other.position - duration;
+ return other.position - duration
}
}
// 吸附到起点
if (position < snapThreshold) {
- return 0;
+ return 0
}
- return position;
-};
+ return position
+}
// 缩放控制
const zoomIn = () => {
- zoom.value = Math.min(zoom.value * 1.2, 3);
-};
+ zoom.value = Math.min(zoom.value * 1.2, 3)
+}
const zoomOut = () => {
- zoom.value = Math.max(zoom.value / 1.2, 0.3);
-};
+ zoom.value = Math.max(zoom.value / 1.2, 0.3)
+}
const zoomReset = () => {
- zoom.value = 1;
-};
+ zoom.value = 1
+}
+
+// 播放头拖拽
+const playheadDragState = ref({
+ isDragging: false,
+ startX: 0,
+ startTime: 0,
+})
+
+const startDragPlayhead = (event: MouseEvent) => {
+ event.stopPropagation()
+
+ playheadDragState.value = {
+ isDragging: true,
+ startX: event.clientX,
+ startTime: currentTime.value,
+ }
+
+ // 暂停播放
+ if (isPlaying.value) {
+ pauseTimeline()
+ }
+
+ document.addEventListener('mousemove', handlePlayheadDragMove)
+ document.addEventListener('mouseup', handlePlayheadDragEnd)
+}
+
+const handlePlayheadDragMove = (event: MouseEvent) => {
+ if (!playheadDragState.value.isDragging) return
+
+ const deltaX = event.clientX - playheadDragState.value.startX
+ const deltaTime = deltaX / pixelsPerSecond.value
+ const newTime = Math.max(0, Math.min(totalDuration.value, playheadDragState.value.startTime + deltaTime))
+
+ seekToTime(newTime)
+}
+
+const handlePlayheadDragEnd = () => {
+ playheadDragState.value.isDragging = false
+
+ document.removeEventListener('mousemove', handlePlayheadDragMove)
+ document.removeEventListener('mouseup', handlePlayheadDragEnd)
+}
// 时间线点击跳转
const clickTimeline = (event: MouseEvent) => {
- if (dragState.value.isDragging || dragState.value.isResizing) return;
+ if (dragState.value.isDragging || dragState.value.isResizing) return
- const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();
- const clickX = event.clientX - rect.left - 100;
- const newTime = Math.max(0, clickX / pixelsPerSecond.value);
- seekToTime(newTime);
-};
+ const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()
+ const clickX = event.clientX - rect.left - 100
+ const newTime = Math.max(0, clickX / pixelsPerSecond.value)
+ seekToTime(newTime)
+}
const seekToTime = (time: number) => {
- currentTime.value = time;
+ currentTime.value = time
// 找到对应时间的视频片段并播放
- const clip = timelineClips.value.find(
- (c) => time >= c.position && time < c.position + c.duration,
- );
+ const clip = timelineClips.value.find((c) => time >= c.position && time < c.position + c.duration)
if (clip && previewPlayer.value) {
// 切换视频源(如果需要)
if (previewPlayer.value.src !== clip.video_url) {
- previewPlayer.value.src = clip.video_url;
+ previewPlayer.value.src = clip.video_url
}
// 跳转到片段内的对应时间
- const offsetInClip = time - clip.position;
- previewPlayer.value.currentTime = clip.start_time + offsetInClip;
+ const offsetInClip = time - clip.position
+ previewPlayer.value.currentTime = clip.start_time + offsetInClip
if (isPlaying.value) {
- previewPlayer.value.play();
+ previewPlayer.value.play()
}
}
// 同步音频播放器
if (audioClips.value.length > 0 && audioPlayer.value) {
- const audioClip = audioClips.value.find(
- (a) => time >= a.position && time < a.position + a.duration,
- );
+ const audioClip = audioClips.value.find((a) => time >= a.position && time < a.position + a.duration)
if (audioClip) {
// 切换音频源(如果需要)
if (audioPlayer.value.src !== audioClip.audio_url) {
- audioPlayer.value.src = audioClip.audio_url;
+ audioPlayer.value.src = audioClip.audio_url
}
// 跳转到音频片段内的对应时间
- const offsetInAudioClip = time - audioClip.position;
- audioPlayer.value.currentTime = audioClip.start_time + offsetInAudioClip;
+ const offsetInAudioClip = time - audioClip.position
+ audioPlayer.value.currentTime = audioClip.start_time + offsetInAudioClip
if (isPlaying.value) {
audioPlayer.value.play().catch((err) => {
- console.warn("音频播放失败:", err);
- });
+ console.warn('音频播放失败:', err)
+ })
}
} else {
// 当前位置没有音频,暂停音频播放器
- audioPlayer.value.pause();
+ audioPlayer.value.pause()
}
}
-};
+}
// 播放控制
const playTimeline = () => {
if (timelineClips.value.length === 0) {
- ElMessage.warning("时间线中没有视频片段");
- return;
+ ElMessage.warning('时间线中没有视频片段')
+ return
}
- isPlaying.value = true;
+ isPlaying.value = true
// 找到当前时间对应的视频片段
const clip = timelineClips.value.find(
- (c) =>
- currentTime.value >= c.position &&
- currentTime.value < c.position + c.duration,
- );
+ (c) => currentTime.value >= c.position && currentTime.value < c.position + c.duration,
+ )
if (clip && previewPlayer.value) {
if (previewPlayer.value.src !== clip.video_url) {
- previewPlayer.value.src = clip.video_url;
+ previewPlayer.value.src = clip.video_url
}
- const offsetInClip = currentTime.value - clip.position;
- previewPlayer.value.currentTime = clip.start_time + offsetInClip;
- previewPlayer.value.play();
+ const offsetInClip = currentTime.value - clip.position
+ previewPlayer.value.currentTime = clip.start_time + offsetInClip
+ previewPlayer.value.play()
} else if (timelineClips.value[0]) {
// 如果当前时间超出范围,从头开始播放
- currentTime.value = 0;
- seekToTime(0);
- previewPlayer.value?.play();
+ currentTime.value = 0
+ seekToTime(0)
+ previewPlayer.value?.play()
}
// 同时播放音频(如果有)
if (audioClips.value.length > 0 && audioPlayer.value) {
const audioClip = audioClips.value.find(
- (a) =>
- currentTime.value >= a.position &&
- currentTime.value < a.position + a.duration,
- );
+ (a) => currentTime.value >= a.position && currentTime.value < a.position + a.duration,
+ )
if (audioClip) {
if (audioPlayer.value.src !== audioClip.audio_url) {
- audioPlayer.value.src = audioClip.audio_url;
+ audioPlayer.value.src = audioClip.audio_url
}
- const offsetInAudioClip = currentTime.value - audioClip.position;
- audioPlayer.value.currentTime = audioClip.start_time + offsetInAudioClip;
+ const offsetInAudioClip = currentTime.value - audioClip.position
+ audioPlayer.value.currentTime = audioClip.start_time + offsetInAudioClip
audioPlayer.value.play().catch((err) => {
- console.warn("音频播放失败:", err);
- });
+ console.warn('音频播放失败:', err)
+ })
}
}
-};
+}
const pauseTimeline = () => {
- isPlaying.value = false;
+ isPlaying.value = false
if (previewPlayer.value) {
- previewPlayer.value.pause();
+ previewPlayer.value.pause()
}
// 同时暂停音频
if (audioPlayer.value) {
- audioPlayer.value.pause();
+ audioPlayer.value.pause()
}
-};
+}
const togglePlay = () => {
if (isPlaying.value) {
- pauseTimeline();
+ pauseTimeline()
} else {
- playTimeline();
+ playTimeline()
}
-};
+}
// 键盘快捷键
const handleKeyPress = (event: KeyboardEvent) => {
// 如果在输入框中,不处理快捷键
- if ((event.target as HTMLElement).tagName === "INPUT") return;
+ if ((event.target as HTMLElement).tagName === 'INPUT') return
switch (event.code) {
- case "Space":
- event.preventDefault();
+ case 'Space':
+ event.preventDefault()
if (isPlaying.value) {
- pauseTimeline();
+ pauseTimeline()
} else {
- playTimeline();
+ playTimeline()
}
- break;
- case "Delete":
- case "Backspace":
+ break
+ case 'Delete':
+ case 'Backspace':
if (selectedClipId.value) {
- event.preventDefault();
- const clip = timelineClips.value.find(
- (c) => c.id === selectedClipId.value,
- );
- if (clip) removeClip(clip);
+ event.preventDefault()
+ const clip = timelineClips.value.find((c) => c.id === selectedClipId.value)
+ if (clip) removeClip(clip)
}
- break;
- case "ArrowLeft":
- event.preventDefault();
- seekToTime(Math.max(0, currentTime.value - 1));
- break;
- case "ArrowRight":
- event.preventDefault();
- seekToTime(Math.min(totalDuration.value, currentTime.value + 1));
- break;
- case "Home":
- event.preventDefault();
- seekToTime(0);
- break;
- case "End":
- event.preventDefault();
- seekToTime(totalDuration.value);
- break;
- }
-};
+ break
+ case 'ArrowLeft':
+ event.preventDefault()
+ seekToTime(Math.max(0, currentTime.value - 1))
+ break
+ case 'ArrowRight':
+ event.preventDefault()
+ seekToTime(Math.min(totalDuration.value, currentTime.value + 1))
+ break
+ case 'Home':
+ event.preventDefault()
+ seekToTime(0)
+ break
+ case 'End':
+ event.preventDefault()
+ seekToTime(totalDuration.value)
+ break
+ }
+}
// 生命周期管理
onMounted(() => {
- document.addEventListener("keydown", handleKeyPress);
-});
+ document.addEventListener('keydown', handleKeyPress)
+})
onUnmounted(() => {
- document.removeEventListener("keydown", handleKeyPress);
- document.removeEventListener("mousemove", handleDragMove);
- document.removeEventListener("mouseup", handleDragEnd);
-});
+ document.removeEventListener('keydown', handleKeyPress)
+ document.removeEventListener('mousemove', handleDragMove)
+ document.removeEventListener('mouseup', handleDragEnd)
+ document.removeEventListener('mousemove', handlePlayheadDragMove)
+ document.removeEventListener('mouseup', handlePlayheadDragEnd)
+})
// 进度显示辅助函数
const getPhaseType = (phase: string) => {
switch (phase) {
- case "loading":
- return "info";
- case "processing":
- return "warning";
- case "encoding":
- return "warning";
- case "completed":
- return "success";
+ case 'loading':
+ return 'info'
+ case 'processing':
+ return 'warning'
+ case 'encoding':
+ return 'warning'
+ case 'completed':
+ return 'success'
default:
- return "info";
+ return 'info'
}
-};
+}
const getPhaseText = (phase: string) => {
switch (phase) {
- case "loading":
- return "初始化";
- case "processing":
- return "处理中";
- case "encoding":
- return "编码中";
- case "completed":
- return "完成";
+ case 'loading':
+ return '初始化'
+ case 'processing':
+ return '处理中'
+ case 'encoding':
+ return '编码中'
+ case 'completed':
+ return '完成'
default:
- return "准备中";
+ return '准备中'
}
-};
+}
// 导出功能
const handleExport = async () => {
if (timelineClips.value.length === 0) {
- ElMessage.warning("请至少添加一个视频片段");
- return;
+ ElMessage.warning('请至少添加一个视频片段')
+ return
}
try {
// 计算总视频大小(粗略估算)
- const totalSize = timelineClips.value.length * 20; // 假设每个片段约20MB
- const estimatedTime = Math.ceil(totalSize / 50); // 每50MB约1分钟
+ const totalSize = timelineClips.value.length * 20 // 假设每个片段约20MB
+ const estimatedTime = Math.ceil(totalSize / 50) // 每50MB约1分钟
await ElMessageBox.confirm(
`即将在浏览器中合并 ${timelineClips.value.length} 个视频片段。\n\n` +
`预计处理时间:${estimatedTime}-${estimatedTime + 1} 分钟\n` +
`预计内存占用:约 ${Math.round(totalSize * 1.5)}MB\n\n` +
`处理期间请勿关闭页面。`,
- "确认导出",
+ '确认导出',
{
- confirmButtonText: "开始合并",
- cancelButtonText: "取消",
- type: "warning",
+ confirmButtonText: '开始合并',
+ cancelButtonText: '取消',
+ type: 'warning',
dangerouslyUseHTMLString: true,
},
- );
+ )
- mergeDialogVisible.value = true;
- merging.value = true;
+ mergeDialogVisible.value = true
+ merging.value = true
// 初始化FFmpeg
await videoMerger.initialize((progress) => {
- mergeProgress.value = progress;
- });
+ mergeProgress.value = progress
+ })
// 准备视频片段数据(包含转场信息)
const clips = timelineClips.value.map((clip) => ({
@@ -1897,115 +1808,115 @@ const handleExport = async () => {
endTime: clip.end_time,
duration: clip.end_time - clip.start_time,
transition: clip.transition,
- }));
+ }))
// 执行合并
- const mergedBlob = await videoMerger.mergeVideos(clips);
+ const mergedBlob = await videoMerger.mergeVideos(clips)
// 下载合并后的视频
- const url = URL.createObjectURL(mergedBlob);
- const a = document.createElement("a");
- a.href = url;
- a.download = `merged_video_${Date.now()}.mp4`;
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- URL.revokeObjectURL(url);
-
- ElMessage.success("视频合并完成,已开始下载!");
- mergeDialogVisible.value = false;
+ const url = URL.createObjectURL(mergedBlob)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = `merged_video_${Date.now()}.mp4`
+ document.body.appendChild(a)
+ a.click()
+ document.body.removeChild(a)
+ URL.revokeObjectURL(url)
+
+ ElMessage.success('视频合并完成,已开始下载!')
+ mergeDialogVisible.value = false
} catch (error: any) {
- if (error !== "cancel") {
- console.error("视频合并失败:", error);
- ElMessage.error(error.message || "视频合并失败");
+ if (error !== 'cancel') {
+ console.error('视频合并失败:', error)
+ ElMessage.error(error.message || '视频合并失败')
}
} finally {
- merging.value = false;
+ merging.value = false
}
-};
+}
// 提交时间线数据到后端进行合成
// 浏览器端FFmpeg合成
const mergeVideoInBrowser = async () => {
if (timelineClips.value.length === 0) {
- ElMessage.warning("时间线上没有视频片段");
- return;
+ ElMessage.warning('时间线上没有视频片段')
+ return
}
try {
await ElMessageBox.confirm(
- "将在浏览器中使用FFmpeg合成视频。\n注意:处理时间较长,且会占用浏览器资源,请勿关闭页面。\n适合少量视频场景(1-5个)。\n是否继续?",
- "浏览器合成视频",
+ '将在浏览器中使用FFmpeg合成视频。\n注意:处理时间较长,且会占用浏览器资源,请勿关闭页面。\n适合少量视频场景(1-5个)。\n是否继续?',
+ '浏览器合成视频',
{
- confirmButtonText: "确定",
- cancelButtonText: "取消",
- type: "warning",
+ confirmButtonText: '确定',
+ cancelButtonText: '取消',
+ type: 'warning',
},
- );
+ )
- merging.value = true;
- mergeProgress.value = 0;
+ merging.value = true
+ mergeProgress.value = 0
- ElMessage.info("开始加载FFmpeg引擎...");
+ ElMessage.info('开始加载FFmpeg引擎...')
// 准备剪辑数据
const clips = timelineClips.value.map((clip) => ({
url: clip.video_url,
startTime: clip.start_time,
endTime: clip.end_time,
- }));
+ }))
// 使用FFmpeg合成
- ElMessage.info("正在合成视频,请稍候...");
+ ElMessage.info('正在合成视频,请稍候...')
const mergedBlob = await trimAndMergeVideos(clips, (progress) => {
- mergeProgress.value = Math.round(progress);
- });
+ mergeProgress.value = Math.round(progress)
+ })
// 创建下载链接
- const url = URL.createObjectURL(mergedBlob);
- const link = document.createElement("a");
- link.href = url;
- link.download = `episode_${props.episodeId}_merged.mp4`;
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- URL.revokeObjectURL(url);
-
- ElMessage.success("视频合成完成并已下载!");
- emit("merge-completed", 0);
+ const url = URL.createObjectURL(mergedBlob)
+ const link = document.createElement('a')
+ link.href = url
+ link.download = `episode_${props.episodeId}_merged.mp4`
+ document.body.appendChild(link)
+ link.click()
+ document.body.removeChild(link)
+ URL.revokeObjectURL(url)
+
+ ElMessage.success('视频合成完成并已下载!')
+ emit('merge-completed', 0)
} catch (error: any) {
- if (error !== "cancel") {
+ if (error !== 'cancel') {
ElMessage.error({
- message: `合成失败: ${error.message || "未知错误"}。请检查控制台或尝试服务器合成`,
+ message: `合成失败: ${error.message || '未知错误'}。请检查控制台或尝试服务器合成`,
duration: 5000,
- });
+ })
}
} finally {
- merging.value = false;
- mergeProgress.value = 0;
+ merging.value = false
+ mergeProgress.value = 0
}
-};
+}
// 服务器端合成
const submitTimelineForMerge = async () => {
if (timelineClips.value.length === 0) {
- ElMessage.warning("时间线上没有视频片段");
- return;
+ ElMessage.warning('时间线上没有视频片段')
+ return
}
try {
await ElMessageBox.confirm(
- "将根据时间线编排的顺序和转场效果合成最终视频。\n注意:未生成视频的场景将被跳过,只合成已有视频的场景。\n适合大量场景合成。\n是否继续?",
- "服务器合成视频",
+ '将根据时间线编排的顺序和转场效果合成最终视频。\n注意:未生成视频的场景将被跳过,只合成已有视频的场景。\n适合大量场景合成。\n是否继续?',
+ '服务器合成视频',
{
- confirmButtonText: "确定",
- cancelButtonText: "取消",
- type: "warning",
+ confirmButtonText: '确定',
+ cancelButtonText: '取消',
+ type: 'warning',
dangerouslyUseHTMLString: false,
},
- );
+ )
- serverMerging.value = true;
+ serverMerging.value = true
// 准备时间线数据
const timelineData = {
@@ -2015,7 +1926,7 @@ const submitTimelineForMerge = async () => {
storyboard_id: clip.storyboard_id,
asset_id: clip.asset_id,
transition: clip.transition,
- });
+ })
return {
storyboard_id: String(clip.storyboard_id),
asset_id: clip.asset_id, // 包含素材库ID
@@ -2023,82 +1934,69 @@ const submitTimelineForMerge = async () => {
start_time: clip.start_time,
end_time: clip.end_time,
duration: clip.duration,
- transition: clip.transition || { type: "none", duration: 0 },
- };
+ transition: clip.transition || { type: 'none', duration: 0 },
+ }
}),
- };
- console.log("📤 提交时间线数据:", JSON.stringify(timelineData, null, 2));
+ }
+ console.log('📤 提交时间线数据:', JSON.stringify(timelineData, null, 2))
// 调用后端API
- const { dramaAPI } = await import("@/api/drama");
- const result = await dramaAPI.finalizeEpisode(
- props.episodeId,
- timelineData,
- );
+ const { dramaAPI } = await import('@/api/drama')
+ const result = await dramaAPI.finalizeEpisode(props.episodeId, timelineData)
// 如果有跳过的场景,显示警告
if (result.warning) {
ElMessage.warning({
message: result.warning,
duration: 5000,
- });
+ })
} else {
- ElMessage.success("视频合成任务已提交,正在后台处理...");
+ ElMessage.success('视频合成任务已提交,正在后台处理...')
}
- emit("merge-completed", result.merge_id || 0);
+ emit('merge-completed', result.merge_id || 0)
} catch (error: any) {
- if (error !== "cancel") {
- console.error("提交合成任务失败:", error);
- ElMessage.error(error.response?.data?.message || "提交失败");
+ if (error !== 'cancel') {
+ console.error('提交合成任务失败:', error)
+ ElMessage.error(error.response?.data?.message || '提交失败')
}
} finally {
- serverMerging.value = false;
+ serverMerging.value = false
}
-};
+}
// 暴露方法供父组件调用
-const updateClipsByStoryboardId = (
- storyboardId: string | number,
- newVideoUrl: string,
-) => {
- console.log("=== updateClipsByStoryboardId 调用 ===");
- console.log(
- "目标 storyboard_id:",
- storyboardId,
- "类型:",
- typeof storyboardId,
- );
- console.log("新视频 URL:", newVideoUrl);
- console.log("当前时间线片段数量:", timelineClips.value.length);
-
- let updated = false;
- const targetId = String(storyboardId); // 统一转换为字符串进行比较
+const updateClipsByStoryboardId = (storyboardId: string | number, newVideoUrl: string) => {
+ console.log('=== updateClipsByStoryboardId 调用 ===')
+ console.log('目标 storyboard_id:', storyboardId, '类型:', typeof storyboardId)
+ console.log('新视频 URL:', newVideoUrl)
+ console.log('当前时间线片段数量:', timelineClips.value.length)
+
+ let updated = false
+ const targetId = String(storyboardId) // 统一转换为字符串进行比较
timelineClips.value.forEach((clip, index) => {
- console.log(
- `片段 ${index}: storyboard_id=${clip.storyboard_id} (类型: ${typeof clip.storyboard_id})`,
- );
+ console.log(`片段 ${index}: storyboard_id=${clip.storyboard_id} (类型: ${typeof clip.storyboard_id})`)
if (String(clip.storyboard_id) === targetId) {
- console.log(`✅ 匹配成功!更新片段 ${index} 的视频URL`);
- console.log(" 旧URL:", clip.video_url);
- console.log(" 新URL:", newVideoUrl);
- clip.video_url = newVideoUrl;
- updated = true;
+ console.log(`✅ 匹配成功!更新片段 ${index} 的视频URL`)
+ console.log(' 旧URL:', clip.video_url)
+ console.log(' 新URL:', newVideoUrl)
+ clip.video_url = newVideoUrl
+ updated = true
}
- });
+ })
if (updated) {
- console.log("✅ 时间线视频已更新");
- ElMessage.success("时间线中的视频已自动更新");
+ console.log('✅ 时间线视频已更新')
+ ElMessage.success('时间线中的视频已自动更新')
} else {
- console.log("⚠️ 没有找到匹配的时间线片段");
+ console.log('⚠️ 没有找到匹配的时间线片段')
}
-};
+}
defineExpose({
updateClipsByStoryboardId,
-});
+})
</script>
<style scoped lang="scss">
@@ -2123,7 +2021,7 @@ defineExpose({
gap: 16px;
.time-display {
- font-family: "Courier New", monospace;
+ font-family: 'Courier New', monospace;
font-size: 14px;
color: var(--text-secondary);
min-width: 160px;
@@ -2611,7 +2509,7 @@ defineExpose({
left: 4px;
font-size: 10px;
color: var(--text-muted);
- font-family: "Courier New", monospace;
+ font-family: 'Courier New', monospace;
}
}
}
@@ -2628,6 +2526,8 @@ defineExpose({
height: 100%;
background: var(--accent);
box-shadow: 0 0 8px rgba(14, 165, 233, 0.6);
+ pointer-events: auto;
+ cursor: ew-resize;
}
.playhead-handle {
@@ -2639,6 +2539,13 @@ defineExpose({
background: var(--accent);
border-radius: 50%;
border: 2px solid var(--bg-card);
+ pointer-events: auto;
+ cursor: ew-resize;
+ transition: transform 0.2s ease;
+
+ &:hover {
+ transform: scale(1.2);
+ }
}
}
diff --git a/web/src/views/drama/ProfessionalEditor.vue b/web/src/views/drama/ProfessionalEditor.vue
index 41db14d..760f948 100644
--- a/web/src/views/drama/ProfessionalEditor.vue
+++ b/web/src/views/drama/ProfessionalEditor.vue
@@ -1,22 +1,15 @@
<template>
<div class="professional-editor">
<!-- 顶部工具栏 -->
- <AppHeader
- :fixed="false"
- :show-logo="false"
- @config-updated="loadVideoModels"
- >
+ <AppHeader :fixed="false" :show-logo="false" @config-updated="loadVideoModels">
<template #left>
<el-button text @click="goBack" class="back-btn">
<el-icon>
<ArrowLeft />
</el-icon>
- <span>{{ $t("editor.backToEpisode") }}</span>
+ <span>{{ $t('editor.backToEpisode') }}</span>
</el-button>
- <span class="episode-title"
- >{{ drama?.title }} -
- {{ $t("editor.episode", { number: episodeNumber }) }}</span
- >
+ <span class="episode-title">{{ drama?.title }} - {{ $t('editor.episode', { number: episodeNumber }) }}</span>
</template>
</AppHeader>
@@ -25,10 +18,8 @@
<!-- 左侧分镜列表 -->
<div class="storyboard-panel">
<div class="panel-header">
- <h3>{{ $t("storyboard.scriptStructure") }}</h3>
- <el-button text :icon="Plus" @click="handleAddStoryboard">{{
- $t("storyboard.add")
- }}</el-button>
+ <h3>{{ $t('storyboard.scriptStructure') }}</h3>
+ <el-button text :icon="Plus" @click="handleAddStoryboard">{{ $t('storyboard.add') }}</el-button>
</div>
<div class="storyboard-list">
@@ -43,13 +34,11 @@
<div class="shot-header">
<div class="shot-title-row">
<span class="shot-number">{{
- $t("storyboard.shotNumber", {
+ $t('storyboard.shotNumber', {
number: shot.storyboard_number,
})
}}</span>
- <span class="shot-title">{{
- shot.title || $t("storyboard.untitled")
- }}</span>
+ <span class="shot-title">{{ shot.title || $t('storyboard.untitled') }}</span>
</div>
<div class="shot-actions">
<span class="shot-duration">{{ shot.duration }}s</span>
@@ -83,52 +72,33 @@
@asset-deleted="loadVideoAssets"
@merge-completed="handleMergeCompleted"
/>
- <el-empty
- v-else
- :description="$t('storyboard.noStoryboard')"
- class="empty-timeline"
- />
+ <el-empty v-else :description="$t('storyboard.noStoryboard')" class="empty-timeline" />
</div>
<!-- 右侧编辑面板 -->
<div class="edit-panel">
<el-tabs v-model="activeTab" class="edit-tabs">
<!-- 镜头属性标签 -->
- <el-tab-pane
- :label="$t('storyboard.shotProperties')"
- name="shot"
- v-if="currentStoryboard"
- >
+ <el-tab-pane :label="$t('storyboard.shotProperties')" name="shot" v-if="currentStoryboard">
<div v-if="currentStoryboard" class="shot-editor-new">
<!-- 场景(Scene) -->
<div class="scene-section">
<div class="section-label">
- {{ $t("storyboard.scene") }} (Scene)
- <el-button
- size="small"
- text
- @click="showSceneSelector = true"
- >{{ $t("storyboard.selectScene") }}</el-button
- >
+ {{ $t('storyboard.scene') }} (Scene)
+ <el-button size="small" text @click="showSceneSelector = true">{{
+ $t('storyboard.selectScene')
+ }}</el-button>
</div>
- <div
- class="scene-preview"
- v-if="hasImage(currentStoryboard.background)"
- @click="showSceneImage"
- >
- <img
- :src="getImageUrl(currentStoryboard.background)"
- alt="场景"
- style="cursor: pointer"
- />
+ <div class="scene-preview" v-if="hasImage(currentStoryboard.background)" @click="showSceneImage">
+ <img :src="getImageUrl(currentStoryboard.background)" alt="场景" style="cursor: pointer" />
<div class="scene-info">
<div>
{{ currentStoryboard.background.location }} ·
{{ currentStoryboard.background.time }}
</div>
<div class="scene-id">
- {{ $t("editor.sceneId") }}:
- {{ currentStoryboard.scene_id || "N/A" }}
+ {{ $t('editor.sceneId') }}:
+ {{ currentStoryboard.scene_id || 'N/A' }}
</div>
</div>
</div>
@@ -137,11 +107,7 @@
<Picture />
</el-icon>
<div>
- {{
- currentStoryboard.background
- ? $t("editor.sceneGenerating")
- : $t("editor.noBackground")
- }}
+ {{ currentStoryboard.background ? $t('editor.sceneGenerating') : $t('editor.noBackground') }}
</div>
</div>
</div>
@@ -149,28 +115,16 @@
<!-- 登场角色(Cast) -->
<div class="cast-section">
<div class="section-label">
- {{ $t("editor.cast") }} (Cast)
- <el-button
- size="small"
- text
- :icon="Plus"
- @click="showCharacterSelector = true"
- >{{ $t("editor.addCharacter") }}</el-button
- >
+ {{ $t('editor.cast') }} (Cast)
+ <el-button size="small" text :icon="Plus" @click="showCharacterSelector = true">{{
+ $t('editor.addCharacter')
+ }}</el-button>
</div>
<div class="cast-list">
- <div
- v-for="char in currentStoryboardCharacters"
- :key="char.id"
- class="cast-item active"
- >
+ <div v-for="char in currentStoryboardCharacters" :key="char.id" class="cast-item active">
<div class="cast-avatar" @click="showCharacterImage(char)">
- <img
- v-if="hasImage(char)"
- :src="getImageUrl(char)"
- :alt="char.name"
- />
- <span v-else>{{ char.name?.[0] || "?" }}</span>
+ <img v-if="hasImage(char)" :src="getImageUrl(char)" :alt="char.name" />
+ <span v-else>{{ char.name?.[0] || '?' }}</span>
</div>
<div class="cast-name">{{ char.name }}</div>
<div
@@ -184,13 +138,10 @@
</div>
</div>
<div
- v-if="
- !currentStoryboard?.characters ||
- currentStoryboard.characters.length === 0
- "
+ v-if="!currentStoryboard?.characters || currentStoryboard.characters.length === 0"
class="cast-empty"
>
- {{ $t("editor.noCharacters") }}
+ {{ $t('editor.noCharacters') }}
</div>
</div>
</div>
@@ -198,50 +149,28 @@
<!-- 道具(Props) -->
<div class="cast-section">
<div class="section-label">
- {{ $t("editor.props") }} (Props)
- <el-button
- size="small"
- text
- :icon="Plus"
- @click="showPropSelector = true"
- >{{ $t("editor.addProp") }}</el-button
- >
+ {{ $t('editor.props') }} (Props)
+ <el-button size="small" text :icon="Plus" @click="showPropSelector = true">{{
+ $t('editor.addProp')
+ }}</el-button>
</div>
<div class="cast-list">
- <div
- v-for="prop in currentStoryboardProps"
- :key="prop.id"
- class="cast-item active"
- >
+ <div v-for="prop in currentStoryboardProps" :key="prop.id" class="cast-item active">
<div class="cast-avatar">
- <img
- v-if="hasImage(prop)"
- :src="getImageUrl(prop)"
- :alt="prop.name"
- />
+ <img v-if="hasImage(prop)" :src="getImageUrl(prop)" :alt="prop.name" />
<el-icon v-else>
<Box />
</el-icon>
</div>
<div class="cast-name">{{ prop.name }}</div>
- <div
- class="cast-remove"
- @click.stop="togglePropInShot(prop.id)"
- title="移除道具"
- >
+ <div class="cast-remove" @click.stop="togglePropInShot(prop.id)" title="移除道具">
<el-icon :size="14">
<Close />
</el-icon>
</div>
</div>
- <div
- v-if="
- !currentStoryboardProps ||
- currentStoryboardProps.length === 0
- "
- class="cast-empty"
- >
- {{ $t("editor.noProps") }}
+ <div v-if="!currentStoryboardProps || currentStoryboardProps.length === 0" class="cast-empty">
+ {{ $t('editor.noProps') }}
</div>
</div>
</div>
@@ -249,11 +178,11 @@
<!-- 视效设置 -->
<div class="settings-section">
<div class="section-label">
- {{ $t("editor.visualSettings") }}
+ {{ $t('editor.visualSettings') }}
</div>
<div class="settings-grid">
<div class="setting-item">
- <label>{{ $t("editor.shotType") }}</label>
+ <label>{{ $t('editor.shotType') }}</label>
<el-select
v-model="currentStoryboard.shot_type"
clearable
@@ -273,7 +202,7 @@
</div>
<div class="setting-item">
- <label>{{ $t("editor.movement") }}</label>
+ <label>{{ $t('editor.movement') }}</label>
<el-select
v-model="currentStoryboard.movement"
clearable
@@ -298,7 +227,7 @@
</div>
<div class="setting-item">
- <label>{{ $t("editor.angle") }}</label>
+ <label>{{ $t('editor.angle') }}</label>
<el-select
v-model="currentStoryboard.angle"
clearable
@@ -308,18 +237,12 @@
<el-option label="平视" value="平视" />
<el-option label="俯视" value="俯视" />
<el-option label="仰视" value="仰视" />
- <el-option
- label="大俯视(鸟瞰)"
- value="大俯视(鸟瞰)"
- />
+ <el-option label="大俯视(鸟瞰)" value="大俯视(鸟瞰)" />
<el-option label="大仰视" value="大仰视" />
<el-option label="正侧面" value="正侧面" />
<el-option label="斜侧面" value="斜侧面" />
<el-option label="背面" value="背面" />
- <el-option
- label="倾斜(荷兰角)"
- value="倾斜(荷兰角)"
- />
+ <el-option label="倾斜(荷兰角)" value="倾斜(荷兰角)" />
<el-option label="主观视角" value="主观视角" />
<el-option label="过肩" value="过肩" />
</el-select>
@@ -329,9 +252,7 @@
<!-- 叙事内容 -->
<div class="narrative-section">
- <div class="section-label">
- {{ $t("editor.action") }} (Action)
- </div>
+ <div class="section-label">{{ $t('editor.action') }} (Action)</div>
<el-input
v-model="currentStoryboard.action"
type="textarea"
@@ -342,9 +263,7 @@
</div>
<div class="narrative-section">
- <div class="section-label">
- {{ $t("editor.result") }} (Result)
- </div>
+ <div class="section-label">{{ $t('editor.result') }} (Result)</div>
<el-input
v-model="currentStoryboard.result"
type="textarea"
@@ -355,9 +274,7 @@
</div>
<div class="dialogue-section">
- <div class="section-label">
- {{ $t("editor.dialogue") }} (Dialogue)
- </div>
+ <div class="section-label">{{ $t('editor.dialogue') }} (Dialogue)</div>
<el-input
v-model="currentStoryboard.dialogue"
type="textarea"
@@ -368,9 +285,7 @@
</div>
<div class="narrative-section">
- <div class="section-label">
- {{ $t("editor.description") }} (Description)
- </div>
+ <div class="section-label">{{ $t('editor.description') }} (Description)</div>
<el-input
v-model="currentStoryboard.description"
type="textarea"
@@ -382,7 +297,7 @@
<!-- 音效设置 -->
<div class="settings-section">
- <div class="section-label">{{ $t("editor.soundEffects") }}</div>
+ <div class="section-label">{{ $t('editor.soundEffects') }}</div>
<div class="audio-controls">
<el-input
v-model="currentStoryboard.sound_effect"
@@ -397,7 +312,7 @@
<!-- 配乐设置 -->
<div class="settings-section">
- <div class="section-label">{{ $t("editor.bgmPrompt") }}</div>
+ <div class="section-label">{{ $t('editor.bgmPrompt') }}</div>
<div class="audio-controls">
<el-input
v-model="currentStoryboard.bgm_prompt"
@@ -412,7 +327,7 @@
<!-- 氛围设置 -->
<div class="settings-section">
- <div class="section-label">{{ $t("editor.atmosphere") }}</div>
+ <div class="section-label">{{ $t('editor.atmosphere') }}</div>
<div class="audio-controls">
<el-input
v-model="currentStoryboard.atmosphere"
@@ -435,24 +350,16 @@
<!-- 帧类型选择 -->
<div class="frame-type-selector">
<div class="section-label">
- {{ $t("editor.selectFrameType") }}
+ {{ $t('editor.selectFrameType') }}
</div>
<el-radio-group v-model="selectedFrameType" size="small">
- <el-radio-button label="first">{{
- $t("editor.firstFrame")
- }}</el-radio-button>
- <el-radio-button label="last">{{
- $t("editor.lastFrame")
- }}</el-radio-button>
- <el-radio-button label="panel">{{
+ <el-radio-button label="first">{{ $t('editor.firstFrame') }}</el-radio-button>
+ <el-radio-button label="last">{{ $t('editor.lastFrame') }}</el-radio-button>
+ <!-- <el-radio-button label="panel">{{
$t("editor.panelFrame")
- }}</el-radio-button>
- <el-radio-button label="action">{{
- $t("editor.actionSequence")
- }}</el-radio-button>
- <el-radio-button label="key">{{
- $t("editor.keyFrame")
- }}</el-radio-button>
+ }}</el-radio-button> -->
+ <el-radio-button label="action">{{ $t('editor.actionSequence') }}</el-radio-button>
+ <el-radio-button label="key">{{ $t('editor.keyFrame') }}</el-radio-button>
</el-radio-group>
<el-input-number
v-if="selectedFrameType === 'panel'"
@@ -463,36 +370,24 @@
class="panel-count-input"
style="margin-left: 10px; margin-top: 12px"
/>
- <span
- v-if="selectedFrameType === 'panel'"
- class="panel-count-label"
- >{{ $t("editor.panelCount") }}</span
- >
+ <span v-if="selectedFrameType === 'panel'" class="panel-count-label">{{
+ $t('editor.panelCount')
+ }}</span>
</div>
<!-- 提示词区域 -->
<div class="prompt-section">
<div class="section-label">
- {{ $t("editor.prompt") }}
+ {{ $t('editor.prompt') }}
<el-button
size="small"
type="primary"
- :disabled="
- isGeneratingPrompt(
- currentStoryboard?.id,
- selectedFrameType,
- )
- "
- :loading="
- isGeneratingPrompt(
- currentStoryboard?.id,
- selectedFrameType,
- )
- "
+ :disabled="isGeneratingPrompt(currentStoryboard?.id, selectedFrameType)"
+ :loading="isGeneratingPrompt(currentStoryboard?.id, selectedFrameType)"
@click="extractFramePrompt"
style="margin-left: 10px"
>
- {{ $t("editor.extractPrompt") }}
+ {{ $t('editor.extractPrompt') }}
</el-button>
</div>
<el-input
@@ -512,29 +407,14 @@
:disabled="!currentFramePrompt"
@click="generateFrameImage"
>
- {{
- generatingImage
- ? $t("editor.generating")
- : $t("editor.generateImage")
- }}
+ {{ generatingImage ? $t('editor.generating') : $t('editor.generateImage') }}
</el-button>
- <el-button :icon="Upload" @click="uploadImage">{{
- $t("editor.uploadImage")
- }}</el-button>
+ <el-button :icon="Upload" @click="uploadImage">{{ $t('editor.uploadImage') }}</el-button>
</div>
<!-- 生成结果 -->
- <div
- class="generation-result"
- v-if="
- generatedImages.length > 0 || selectedFrameType === 'action'
- "
- >
- <div class="section-label">
- {{ $t("editor.generationResult") }} ({{
- generatedImages.length
- }})
- </div>
+ <div class="generation-result" v-if="generatedImages.length > 0 || selectedFrameType === 'action'">
+ <div class="section-label">{{ $t('editor.generationResult') }} ({{ generatedImages.length }})</div>
<div class="image-grid">
<!-- 动作序列入口按钮 -->
<div
@@ -553,56 +433,52 @@
}}</span>
</div> -->
</div>
- <div
- v-for="img in generatedImages"
- :key="img.id"
- class="image-item"
- :class="{
- 'action-image-item': img.frame_type === 'action',
- }"
- >
- <el-image
- v-if="hasImage(img)"
- :src="getImageUrl(img)"
- :preview-src-list="
- generatedImages
- .filter((i) => hasImage(i))
- .map((i) => getImageUrl(i)!)
- "
- :initial-index="
- generatedImages
- .filter((i) => i.image_url)
- .findIndex((i) => i.id === img.id)
- "
- fit="cover"
- preview-teleported
- />
- <div v-else class="image-placeholder">
- <el-icon :size="32">
- <Picture />
- </el-icon>
- <p>生成中...</p>
- </div>
- <!-- 动作序列图片裁剪图标 -->
+ <div v-for="img in generatedImages" :key="img.id" class="image-item-wrapper">
<div
- v-if="img.frame_type === 'action' && hasImage(img)"
- class="crop-icon-overlay"
- @click.stop="openCropDialog(img)"
+ class="image-item"
+ :class="{
+ 'action-image-item': img.frame_type === 'action',
+ }"
>
- <el-icon :size="18" color="#fff">
- <Crop />
- </el-icon>
- </div>
- <div class="image-info">
- <el-tag
- :type="getStatusType(img.status)"
- size="small"
- >{{ getStatusText(img.status) }}</el-tag
- >
- <span v-if="img.frame_type" class="frame-type-tag">{{
- getFrameTypeText(img.frame_type)
- }}</span>
+ <el-image
+ v-if="hasImage(img)"
+ :src="getImageUrl(img)"
+ :preview-src-list="generatedImages.filter((i) => hasImage(i)).map((i) => getImageUrl(i)!)"
+ :initial-index="generatedImages.filter((i) => i.image_url).findIndex((i) => i.id === img.id)"
+ fit="cover"
+ preview-teleported
+ />
+ <div v-else class="image-placeholder">
+ <el-icon :size="32">
+ <Picture />
+ </el-icon>
+ <p>{{ getStatusText(img.status) }}</p>
+ </div>
+ <div class="image-actions" v-if="hasImage(img)">
+ <!-- 动作序列图片裁剪图标 -->
+ <div
+ v-if="img.frame_type === 'action' && hasImage(img)"
+ class="crop-icon-overlay"
+ @click.stop="openCropDialog(img)"
+ >
+ <el-icon :size="18" color="var(--text-primary)">
+ <Crop />
+ </el-icon>
+ </div>
+ <div v-else></div>
+ <!-- 删除按钮 -->
+ <div v-if="hasImage(img)" class="delete-icon-overlay" @click.stop="handleDeleteImage(img)">
+ <el-icon :size="18" color="red">
+ <DeleteFilled />
+ </el-icon>
+ </div>
+ </div>
</div>
+ <!-- <div class="image-status">
+ <el-tag :type="getStatusType(img.status)" size="small">{{
+ getStatusText(img.status)
+ }}</el-tag>
+ </div> -->
</div>
</div>
</div>
@@ -617,13 +493,13 @@
<div class="video-generation-section">
<!-- 生成提示词展示 -->
<div class="video-prompt-box">
- {{ currentStoryboard.video_prompt || "暂无提示词" }}
+ {{ currentStoryboard.video_prompt || '暂无提示词' }}
</div>
<!-- 视频参数设置 -->
<div class="video-params-section">
<div class="param-row">
- <span class="param-label">{{ $t("video.model") }}</span>
+ <span class="param-label">{{ $t('video.model') }}</span>
<el-select
v-model="selectedVideoModel"
:placeholder="$t('video.selectVideoModel')"
@@ -636,13 +512,7 @@
:label="model.name"
:value="model.id"
>
- <div
- style="
- display: flex;
- justify-content: space-between;
- align-items: center;
- "
- >
+ <div style="display: flex; justify-content: space-between; align-items: center">
<span>{{ model.name }}</span>
<div class="model-tags">
<el-tag
@@ -659,10 +529,7 @@
style="margin-left: 4px"
>首尾帧</el-tag
>
- <el-tag
- size="small"
- type="info"
- style="margin-left: 4px"
+ <el-tag size="small" type="info" style="margin-left: 4px"
>最多{{ model.maxImages }}张</el-tag
>
</div>
@@ -672,12 +539,7 @@
</div>
<!-- 参考图模式选择 -->
- <div
- v-if="
- selectedVideoModel && availableReferenceModes.length > 0
- "
- class="param-row"
- >
+ <div v-if="selectedVideoModel && availableReferenceModes.length > 0" class="param-row">
<span class="param-label">参考图</span>
<el-select
v-model="selectedReferenceMode"
@@ -691,40 +553,20 @@
:label="mode.label"
:value="mode.value"
>
- <div
- style="
- display: flex;
- justify-content: space-between;
- align-items: center;
- "
- >
+ <div style="display: flex; justify-content: space-between; align-items: center">
<span>{{ mode.label }}</span>
- <span
- v-if="mode.description"
- class="mode-description"
- >{{ mode.description }}</span
- >
+ <span v-if="mode.description" class="mode-description">{{ mode.description }}</span>
</div>
</el-option>
</el-select>
</div>
<div class="param-row">
- <span class="param-label">{{
- $t("professionalEditor.duration")
- }}</span>
+ <span class="param-label">{{ $t('professionalEditor.duration') }}</span>
<div style="flex: 1; display: flex; align-items: center">
- <el-slider
- v-model="videoDuration"
- :min="4"
- :max="10"
- :step="1"
- show-stops
- style="flex: 1"
- />
+ <el-slider v-model="videoDuration" :min="4" :max="10" :step="1" show-stops style="flex: 1" />
<span style="margin-left: 10px; min-width: 40px"
- >{{ videoDuration
- }}{{ $t("professionalEditor.seconds") }}</span
+ >{{ videoDuration }}{{ $t('professionalEditor.seconds') }}</span
>
</div>
</div>
@@ -732,23 +574,15 @@
<!-- 选择参考图片 -->
<div
- v-if="
- selectedReferenceMode && selectedReferenceMode !== 'none'
- "
+ v-if="selectedReferenceMode && selectedReferenceMode !== 'none'"
class="reference-images-section"
style="margin-top: 0"
>
- <div
- class="frame-type-buttons"
- style="text-align: center; margin-bottom: 8px"
- >
- <el-radio-group
- v-model="selectedVideoFrameType"
- size="default"
- >
+ <div class="frame-type-buttons" style="text-align: center; margin-bottom: 8px">
+ <el-radio-group v-model="selectedVideoFrameType" size="default">
<el-radio-button label="first">首帧</el-radio-button>
<el-radio-button label="last">尾帧</el-radio-button>
- <el-radio-button label="panel">分镜板</el-radio-button>
+ <!-- <el-radio-button label="panel">分镜板</el-radio-button> -->
<el-radio-button label="action">动作序列</el-radio-button>
<el-radio-button label="key">关键帧</el-radio-button>
</el-radio-group>
@@ -759,29 +593,13 @@
<div
v-show="selectedVideoFrameType === 'first'"
class="image-scroll-container"
- style="
- max-height: 280px;
- overflow-y: auto;
- overflow-x: hidden;
- "
+ style="max-height: 280px; overflow-y: auto; overflow-x: hidden"
>
<!-- 上一镜头尾帧推荐(紧凑版) -->
- <div
- v-if="previousStoryboardLastFrames.length > 0"
- class="previous-frame-section"
- >
- <div
- style="
- display: flex;
- align-items: center;
- gap: 6px;
- margin-bottom: 6px;
- "
- >
+ <div v-if="previousStoryboardLastFrames.length > 0" class="previous-frame-section">
+ <div style="display: flex; align-items: center; gap: 6px; margin-bottom: 6px">
<el-tag size="small" type="primary">
- 上一镜头 #{{
- previousStoryboard?.storyboard_number
- }}
+ 上一镜头 #{{ previousStoryboard?.storyboard_number }}
尾帧
</el-tag>
<span class="hint-text">点击添加为首帧参考</span>
@@ -806,12 +624,7 @@
<el-image
:src="getImageUrl(img)"
fit="cover"
- style="
- width: 60px;
- height: 40px;
- display: block;
- pointer-events: none;
- "
+ style="width: 60px; height: 40px; display: block; pointer-events: none"
/>
<div
v-if="selectedImagesForVideo.includes(img.id)"
@@ -834,19 +647,11 @@
<!-- 当前镜头首帧列表 -->
<div
class="reference-grid"
- style="
- display: grid;
- grid-template-columns: repeat(4, 1fr);
- gap: 12px;
- max-width: 600px;
- "
+ style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; max-width: 600px"
>
<div
v-for="img in videoReferenceImages.filter(
- (i) =>
- i.status === 'completed' &&
- i.image_url &&
- i.frame_type === 'first',
+ (i) => i.status === 'completed' && i.image_url && i.frame_type === 'first',
)"
:key="img.id"
class="reference-item"
@@ -859,12 +664,7 @@
<el-image
:src="getImageUrl(img)"
fit="cover"
- style="
- max-width: 120px;
- width: 100%;
- display: block;
- pointer-events: none;
- "
+ style="max-width: 120px; width: 100%; display: block; pointer-events: none"
/>
<div
class="preview-icon"
@@ -893,10 +693,7 @@
<el-empty
v-if="
!videoReferenceImages.some(
- (i) =>
- i.status === 'completed' &&
- i.image_url &&
- i.frame_type === 'first',
+ (i) => i.status === 'completed' && i.image_url && i.frame_type === 'first',
) && previousStoryboardLastFrames.length === 0
"
description="暂无首帧图片"
@@ -908,27 +705,15 @@
<div
v-show="selectedVideoFrameType === 'key'"
class="image-scroll-container"
- style="
- max-height: 280px;
- overflow-y: auto;
- overflow-x: hidden;
- "
+ style="max-height: 280px; overflow-y: auto; overflow-x: hidden"
>
<div
class="reference-grid"
- style="
- display: grid;
- grid-template-columns: repeat(4, 1fr);
- gap: 12px;
- max-width: 600px;
- "
+ style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; max-width: 600px"
>
<div
v-for="img in videoReferenceImages.filter(
- (i) =>
- i.status === 'completed' &&
- i.image_url &&
- i.frame_type === 'key',
+ (i) => i.status === 'completed' && i.image_url && i.frame_type === 'key',
)"
:key="img.id"
class="reference-item"
@@ -941,12 +726,7 @@
<el-image
:src="getImageUrl(img)"
fit="cover"
- style="
- max-width: 120px;
- width: 100%;
- display: block;
- pointer-events: none;
- "
+ style="max-width: 120px; width: 100%; display: block; pointer-events: none"
/>
<div
class="preview-icon"
@@ -975,10 +755,7 @@
<el-empty
v-if="
!videoReferenceImages.some(
- (i) =>
- i.status === 'completed' &&
- i.image_url &&
- i.frame_type === 'key',
+ (i) => i.status === 'completed' && i.image_url && i.frame_type === 'key',
)
"
description="暂无关键帧图片"
@@ -990,27 +767,15 @@
<div
v-show="selectedVideoFrameType === 'last'"
class="image-scroll-container"
- style="
- max-height: 280px;
- overflow-y: auto;
- overflow-x: hidden;
- "
+ style="max-height: 280px; overflow-y: auto; overflow-x: hidden"
>
<div
class="reference-grid"
- style="
- display: grid;
- grid-template-columns: repeat(4, 1fr);
- gap: 12px;
- max-width: 600px;
- "
+ style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; max-width: 600px"
>
<div
v-for="img in videoReferenceImages.filter(
- (i) =>
- i.status === 'completed' &&
- i.image_url &&
- i.frame_type === 'last',
+ (i) => i.status === 'completed' && i.image_url && i.frame_type === 'last',
)"
:key="img.id"
class="reference-item"
@@ -1023,12 +788,7 @@
<el-image
:src="getImageUrl(img)"
fit="cover"
- style="
- max-width: 120px;
- width: 100%;
- display: block;
- pointer-events: none;
- "
+ style="max-width: 120px; width: 100%; display: block; pointer-events: none"
/>
<div
class="preview-icon"
@@ -1057,10 +817,7 @@
<el-empty
v-if="
!videoReferenceImages.some(
- (i) =>
- i.status === 'completed' &&
- i.image_url &&
- i.frame_type === 'last',
+ (i) => i.status === 'completed' && i.image_url && i.frame_type === 'last',
)
"
description="暂无尾帧图片"
@@ -1072,27 +829,15 @@
<div
v-show="selectedVideoFrameType === 'panel'"
class="image-scroll-container"
- style="
- max-height: 280px;
- overflow-y: auto;
- overflow-x: hidden;
- "
+ style="max-height: 280px; overflow-y: auto; overflow-x: hidden"
>
<div
class="reference-grid"
- style="
- display: grid;
- grid-template-columns: repeat(4, 1fr);
- gap: 12px;
- max-width: 600px;
- "
+ style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; max-width: 600px"
>
<div
v-for="img in videoReferenceImages.filter(
- (i) =>
- i.status === 'completed' &&
- i.image_url &&
- i.frame_type === 'panel',
+ (i) => i.status === 'completed' && i.image_url && i.frame_type === 'panel',
)"
:key="img.id"
class="reference-item"
@@ -1105,12 +850,7 @@
<el-image
:src="getImageUrl(img)"
fit="cover"
- style="
- max-width: 120px;
- width: 100%;
- display: block;
- pointer-events: none;
- "
+ style="max-width: 120px; width: 100%; display: block; pointer-events: none"
/>
<div
class="preview-icon"
@@ -1139,10 +879,7 @@
<el-empty
v-if="
!videoReferenceImages.some(
- (i) =>
- i.status === 'completed' &&
- i.image_url &&
- i.frame_type === 'panel',
+ (i) => i.status === 'completed' && i.image_url && i.frame_type === 'panel',
)
"
description="暂无分镜板图片"
@@ -1154,27 +891,15 @@
<div
v-show="selectedVideoFrameType === 'action'"
class="image-scroll-container"
- style="
- max-height: 280px;
- overflow-y: auto;
- overflow-x: hidden;
- "
+ style="max-height: 280px; overflow-y: auto; overflow-x: hidden"
>
<div
class="reference-grid"
- style="
- display: grid;
- grid-template-columns: repeat(4, 1fr);
- gap: 12px;
- max-width: 600px;
- "
+ style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; max-width: 600px"
>
<div
v-for="img in videoReferenceImages.filter(
- (i) =>
- i.status === 'completed' &&
- i.image_url &&
- i.frame_type === 'action',
+ (i) => i.status === 'completed' && i.image_url && i.frame_type === 'action',
)"
:key="img.id"
class="reference-item"
@@ -1187,12 +912,7 @@
<el-image
:src="getImageUrl(img)"
fit="cover"
- style="
- max-width: 120px;
- width: 100%;
- display: block;
- pointer-events: none;
- "
+ style="max-width: 120px; width: 100%; display: block; pointer-events: none"
/>
<div
class="preview-icon"
@@ -1221,10 +941,7 @@
<el-empty
v-if="
!videoReferenceImages.some(
- (i) =>
- i.status === 'completed' &&
- i.image_url &&
- i.frame_type === 'action',
+ (i) => i.status === 'completed' && i.image_url && i.frame_type === 'action',
)
"
description="暂无动作序列图片"
@@ -1236,30 +953,19 @@
<!-- 参考图片设置 -->
<div
- v-if="
- selectedReferenceMode && selectedReferenceMode !== 'none'
- "
+ v-if="selectedReferenceMode && selectedReferenceMode !== 'none'"
class="reference-config-section"
style="margin-top: 24px"
>
<!-- 图片框配置区 -->
- <div
- class="image-slots-container"
- style="margin-top: 16px; margin-bottom: 24px"
- >
+ <div class="image-slots-container" style="margin-top: 16px; margin-bottom: 24px">
<!-- 单图模式 -->
- <div
- v-if="selectedReferenceMode === 'single'"
- style="text-align: center"
- >
+ <div v-if="selectedReferenceMode === 'single'" style="text-align: center">
<div class="reference-mode-title">单图参考</div>
<div style="display: inline-block">
<div
class="image-slot"
- @click="
- selectedImagesForVideo.length > 0 &&
- removeSelectedImage(selectedImagesForVideo[0])
- "
+ @click="selectedImagesForVideo.length > 0 && removeSelectedImage(selectedImagesForVideo[0])"
>
<img
v-if="selectedImageObjects[0]"
@@ -1273,10 +979,7 @@
</el-icon>
<div class="slot-hint">点击上方选择图片</div>
</div>
- <div
- v-if="selectedImageObjects[0]"
- class="image-slot-remove"
- >
+ <div v-if="selectedImageObjects[0]" class="image-slot-remove">
<el-icon :size="16" color="#fff">
<Close />
</el-icon>
@@ -1286,37 +989,20 @@
</div>
<!-- 首尾帧模式 -->
- <div
- v-else-if="selectedReferenceMode === 'first_last'"
- style="text-align: center"
- >
+ <div v-else-if="selectedReferenceMode === 'first_last'" style="text-align: center">
<div class="reference-mode-title">首尾帧</div>
- <div
- style="
- display: flex;
- gap: 20px;
- justify-content: center;
- align-items: center;
- "
- >
+ <div style="display: flex; gap: 20px; justify-content: center; align-items: center">
<div>
<div class="frame-label">首帧</div>
<div
class="image-slot"
- @click="
- firstFrameSlotImage &&
- removeSelectedImage(firstFrameSlotImage.id)
- "
+ @click="firstFrameSlotImage && removeSelectedImage(firstFrameSlotImage.id)"
>
<img
v-if="firstFrameSlotImage"
:src="firstFrameSlotImage.image_url"
alt=""
- style="
- width: 100%;
- height: 100%;
- object-fit: cover;
- "
+ style="width: 100%; height: 100%; object-fit: cover"
/>
<div v-else class="image-slot-placeholder">
<el-icon :size="32" color="#c0c4cc">
@@ -1324,10 +1010,7 @@
</el-icon>
<div class="slot-hint">选择首帧</div>
</div>
- <div
- v-if="firstFrameSlotImage"
- class="image-slot-remove"
- >
+ <div v-if="firstFrameSlotImage" class="image-slot-remove">
<el-icon :size="16" color="#fff">
<Close />
</el-icon>
@@ -1341,20 +1024,13 @@
<div class="frame-label">尾帧</div>
<div
class="image-slot"
- @click="
- lastFrameSlotImage &&
- removeSelectedImage(lastFrameSlotImage.id)
- "
+ @click="lastFrameSlotImage && removeSelectedImage(lastFrameSlotImage.id)"
>
<img
v-if="lastFrameSlotImage"
:src="lastFrameSlotImage.image_url"
alt=""
- style="
- width: 100%;
- height: 100%;
- object-fit: cover;
- "
+ style="width: 100%; height: 100%; object-fit: cover"
/>
<div v-else class="image-slot-placeholder">
<el-icon :size="32" color="#c0c4cc">
@@ -1362,10 +1038,7 @@
</el-icon>
<div class="slot-hint">选择尾帧</div>
</div>
- <div
- v-if="lastFrameSlotImage"
- class="image-slot-remove"
- >
+ <div v-if="lastFrameSlotImage" class="image-slot-remove">
<el-icon :size="16" color="#fff">
<Close />
</el-icon>
@@ -1376,33 +1049,13 @@
</div>
<!-- 多图模式 -->
- <div
- v-else-if="selectedReferenceMode === 'multiple'"
- style="text-align: center"
- >
- <div
- style="
- margin-bottom: 12px;
- font-size: 13px;
- color: #606266;
- font-weight: 500;
- "
- >
- 多图参考 ({{ selectedImagesForVideo.length }}/{{
- currentModelCapability?.maxImages || 6
- }})
+ <div v-else-if="selectedReferenceMode === 'multiple'" style="text-align: center">
+ <div style="margin-bottom: 12px; font-size: 13px; color: #606266; font-weight: 500">
+ 多图参考 ({{ selectedImagesForVideo.length }}/{{ currentModelCapability?.maxImages || 6 }})
</div>
- <div
- style="
- display: flex;
- gap: 12px;
- justify-content: center;
- flex-wrap: wrap;
- "
- >
+ <div style="display: flex; gap: 12px; justify-content: center; flex-wrap: wrap">
<div
- v-for="index in currentModelCapability?.maxImages ||
- 6"
+ v-for="index in currentModelCapability?.maxImages || 6"
:key="index"
class="image-slot image-slot-small"
style="
@@ -1416,10 +1069,7 @@
background: #fff;
"
@click="
- selectedImageObjects[index - 1] &&
- removeSelectedImage(
- selectedImageObjects[index - 1].id,
- )
+ selectedImageObjects[index - 1] && removeSelectedImage(selectedImageObjects[index - 1].id)
"
>
<img
@@ -1432,20 +1082,11 @@
<el-icon :size="20" color="#c0c4cc">
<Plus />
</el-icon>
- <div
- style="
- margin-top: 4px;
- font-size: 10px;
- color: #909399;
- "
- >
+ <div style="margin-top: 4px; font-size: 10px; color: #909399">
{{ index }}
</div>
</div>
- <div
- v-if="selectedImageObjects[index - 1]"
- class="image-slot-remove"
- >
+ <div v-if="selectedImageObjects[index - 1]" class="image-slot-remove">
<el-icon :size="14" color="#fff">
<Close />
</el-icon>
@@ -1457,31 +1098,22 @@
</div>
<!-- 生成控制 -->
- <div
- class="generation-controls"
- style="margin-top: 32px; text-align: center"
- >
+ <div class="generation-controls" style="margin-top: 32px; text-align: center">
<el-button
type="primary"
:icon="VideoCamera"
:loading="generatingVideo"
:disabled="
- !selectedVideoModel ||
- (selectedReferenceMode !== 'none' &&
- selectedImagesForVideo.length === 0)
+ !selectedVideoModel || (selectedReferenceMode !== 'none' && selectedImagesForVideo.length === 0)
"
@click="generateVideo"
>
- {{ generatingVideo ? "生成中..." : "生成视频" }}
+ {{ generatingVideo ? '生成中...' : '生成视频' }}
</el-button>
</div>
<!-- 生成的视频列表 -->
- <div
- class="generation-result"
- v-if="generatedVideos.length > 0"
- style="margin-top: 24px"
- >
+ <div class="generation-result" v-if="generatedVideos.length > 0" style="margin-top: 24px">
<div
class="section-label"
style="
@@ -1496,168 +1128,44 @@
<span></span>
生成结果 ({{ generatedVideos.length }})
</div>
- <div
- class="image-grid"
- style="
- display: grid;
- grid-template-columns: repeat(
- auto-fill,
- minmax(140px, 1fr)
- );
- gap: 10px;
- "
- >
- <div
- v-for="video in generatedVideos"
- :key="video.id"
- class="image-item video-item"
- style="
- position: relative;
- border-radius: 8px;
- overflow: hidden;
- background: #fff;
- border: 1px solid #e8e8e8;
- box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
- cursor: pointer;
- transition: all 0.2s ease;
- "
- >
- <div
- class="video-thumbnail"
- v-if="video.video_url"
- style="
- position: relative;
- width: 100%;
- aspect-ratio: 16/9;
- overflow: hidden;
- cursor: pointer;
- "
- @mouseenter="
- (e) =>
- (e.currentTarget.querySelector(
- '.play-overlay',
- ).style.opacity = '1')
- "
- @mouseleave="
- (e) =>
- (e.currentTarget.querySelector(
- '.play-overlay',
- ).style.opacity = '0')
- "
- @click="playVideo(video)"
- >
- <video
- :src="getVideoUrl(video)"
- preload="metadata"
- style="
- width: 100%;
- height: 100%;
- object-fit: cover;
- display: block;
- pointer-events: none;
- "
- />
- <div
- class="play-overlay"
- style="
- position: absolute;
- top: 0;
- left: 0;
- right: 0;
- bottom: 0;
- display: flex;
- align-items: center;
- justify-content: center;
- background: rgba(0, 0, 0, 0.3);
- opacity: 0;
- transition: opacity 0.2s;
- "
- >
- <el-icon
- :size="32"
- color="#fff"
- style="
- filter: drop-shadow(0 2px 8px rgba(0, 0, 0, 0.3));
- "
- >
- <VideoPlay />
- </el-icon>
+ <div class="image-grid">
+ <div v-for="video in generatedVideos" :key="video.id" class="image-item-wrapper">
+ <div class="image-item video-item">
+ <div v-if="video.video_url" class="video-thumbnail" @click="playVideo(video)">
+ <video :src="getVideoUrl(video)" preload="metadata" />
+ <div class="play-overlay">
+ <el-icon :size="40" color="#fff">
+ <VideoPlay />
+ </el-icon>
+ </div>
</div>
- </div>
- <div
- v-else
- class="image-placeholder"
- style="
- width: 100%;
- aspect-ratio: 16/9;
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- gap: 8px;
- background: linear-gradient(
- 135deg,
- #f5f7fa 0%,
- #e8ecf0 100%
- );
- color: #909399;
- "
- >
- <el-icon :size="32">
- <VideoCamera />
- </el-icon>
- <p style="margin: 0; font-size: 11px">生成中...</p>
- </div>
- <div
- class="image-info"
- style="
- position: absolute;
- bottom: 0;
- left: 0;
- right: 0;
- padding: 6px 8px;
- background: linear-gradient(
- to top,
- rgba(0, 0, 0, 0.75),
- rgba(0, 0, 0, 0.2) 70%,
- transparent
- );
- display: flex;
- justify-content: space-between;
- align-items: center;
- gap: 4px;
- "
- >
- <div
- style="display: flex; align-items: center; gap: 4px"
- >
- <el-tag
- :type="getStatusType(video.status)"
- size="small"
- style="
- font-size: 10px;
- height: 20px;
- padding: 0 6px;
- "
- >{{ getStatusText(video.status) }}</el-tag
- >
+ <div v-else class="image-placeholder">
+ <el-icon :size="32">
+ <VideoCamera />
+ </el-icon>
+ <p>{{ getStatusText(video.status) }}</p>
</div>
- <div style="display: flex; gap: 4px">
- <el-button
- v-if="
- video.status === 'completed' && video.video_url
- "
- type="success"
- size="small"
- :loading="addingToAssets.has(video.id)"
+ <!-- 视频操作按钮 -->
+ <div class="video-actions">
+ <div
+ v-if="video.status === 'completed'"
+ class="add-to-assets-button"
@click.stop="addVideoToAssets(video)"
>
- {{
- addingToAssets.has(video.id)
- ? "添加中..."
- : "添加到素材库"
- }}
- </el-button>
+ <el-icon :size="18" color="var(--text-primary)" v-if="!addingToAssets.has(video.id)">
+ <FolderAdd />
+ </el-icon>
+ <el-icon :size="18" color="var(--text-primary)" v-else class="is-loading">
+ <Loading />
+ </el-icon>
+ </div>
+ <div v-else></div>
+ <!-- 删除按钮 -->
+ <div class="delete-video-button" @click.stop="handleDeleteVideo(video)">
+ <el-icon :size="18" color="red">
+ <DeleteFilled />
+ </el-icon>
+ </div>
</div>
</div>
</div>
@@ -1679,18 +1187,12 @@
<el-tab-pane :label="$t('video.videoMerge')" name="merges">
<div class="tab-content">
<div class="merges-list" v-loading="loadingMerges">
- <el-empty
- v-if="videoMerges.length === 0"
- :description="$t('video.noMergeRecords')"
- :image-size="120"
- >
+ <el-empty v-if="videoMerges.length === 0" :description="$t('video.noMergeRecords')" :image-size="120">
<template #description>
- <div
- style="color: #909399; font-size: 14px; margin-top: 12px"
- >
- <p style="margin: 0">{{ $t("video.noMergeYet") }}</p>
+ <div style="color: #909399; font-size: 14px; margin-top: 12px">
+ <p style="margin: 0">{{ $t('video.noMergeYet') }}</p>
<p style="margin: 8px 0 0 0; font-size: 12px">
- {{ $t("video.mergeInstructions") }}
+ {{ $t('video.mergeInstructions') }}
</p>
</div>
</template>
@@ -1712,37 +1214,28 @@
<div class="title-section">
<el-icon :size="20" class="title-icon">
<VideoCamera v-if="merge.status === 'completed'" />
- <Loading
- v-else-if="merge.status === 'processing'"
- class="rotating"
- />
- <WarningFilled
- v-else-if="merge.status === 'failed'"
- />
+ <Loading v-else-if="merge.status === 'processing'" class="rotating" />
+ <WarningFilled v-else-if="merge.status === 'failed'" />
<Clock v-else />
</el-icon>
<h3 class="merge-title">{{ merge.title }}</h3>
</div>
<el-tag
:type="
- merge.status === 'completed'
- ? 'success'
- : merge.status === 'failed'
- ? 'danger'
- : 'warning'
+ merge.status === 'completed' ? 'success' : merge.status === 'failed' ? 'danger' : 'warning'
"
effect="dark"
size="large"
round
>
{{
- merge.status === "pending"
- ? "等待中"
- : merge.status === "processing"
- ? "合成中"
- : merge.status === "completed"
- ? "已完成"
- : "失败"
+ merge.status === 'pending'
+ ? '等待中'
+ : merge.status === 'processing'
+ ? '合成中'
+ : merge.status === 'completed'
+ ? '已完成'
+ : '失败'
}}
</el-tag>
</div>
@@ -1757,14 +1250,14 @@
</div>
<div class="detail-content">
<div class="detail-label">
- {{ $t("professionalEditor.videoDuration") }}
+ {{ $t('professionalEditor.videoDuration') }}
</div>
<div class="detail-value">
{{
merge.duration
? `${merge.duration}
- ${$t("professionalEditor.seconds")}`
- : "-"
+ ${$t('professionalEditor.seconds')}`
+ : '-'
}}
</div>
</div>
@@ -1798,10 +1291,7 @@
</div>
<!-- 错误提示 -->
- <div
- class="merge-error"
- v-if="merge.status === 'failed' && merge.error_msg"
- >
+ <div class="merge-error" v-if="merge.status === 'failed' && merge.error_msg">
<el-alert type="error" :closable="false" show-icon>
<template #title>
<div style="font-size: 13px; line-height: 1.5">
@@ -1813,37 +1303,20 @@
<!-- 操作按钮 -->
<div class="merge-actions">
- <template
- v-if="
- merge.status === 'completed' && merge.merged_url
- "
- >
+ <template v-if="merge.status === 'completed' && merge.merged_url">
<el-button
type="primary"
:icon="VideoCamera"
- @click="
- downloadVideo(merge.merged_url, merge.title)
- "
+ @click="downloadVideo(merge.merged_url, merge.title)"
round
>
下载视频
</el-button>
- <el-button
- :icon="View"
- @click="previewMergedVideo(merge.merged_url)"
- round
- >
+ <el-button :icon="View" @click="previewMergedVideo(merge.merged_url)" round>
在线预览
</el-button>
</template>
- <el-button
- type="danger"
- :icon="Delete"
- @click="deleteMerge(merge.id)"
- round
- >
- 删除
- </el-button>
+ <el-button type="danger" :icon="Delete" @click="deleteMerge(merge.id)" round> 删除 </el-button>
</div>
</div>
</div>
@@ -1856,17 +1329,9 @@
</div>
<!-- 角色选择器对话框 -->
- <el-dialog
- v-model="showCharacterImagePreview"
- :title="previewCharacter?.name"
- width="600px"
- >
+ <el-dialog v-model="showCharacterImagePreview" :title="previewCharacter?.name" width="600px">
<div class="character-image-preview" v-if="previewCharacter">
- <img
- v-if="previewCharacter.local_path"
- :src="getImageUrl(previewCharacter)"
- :alt="previewCharacter.name"
- />
+ <img v-if="previewCharacter.local_path" :src="getImageUrl(previewCharacter)" :alt="previewCharacter.name" />
<el-empty v-else description="暂无图片" />
</div>
<!-- ... -->
@@ -1882,20 +1347,13 @@
"
width="800px"
>
- <div
- class="scene-image-preview"
- v-if="currentStoryboard?.background?.image_url"
- >
+ <div class="scene-image-preview" v-if="currentStoryboard?.background?.image_url">
<img :src="currentStoryboard.background.image_url" alt="场景" />
</div>
</el-dialog>
<!-- 角色选择对话框 -->
- <el-dialog
- v-model="showCharacterSelector"
- title="添加角色到镜头"
- width="800px"
- >
+ <el-dialog v-model="showCharacterSelector" title="添加角色到镜头" width="800px">
<div class="character-selector-grid">
<div
v-for="char in availableCharacters"
@@ -1905,16 +1363,12 @@
@click="toggleCharacterInShot(char.id)"
>
<div class="character-avatar-large">
- <img
- v-if="char.local_path"
- :src="getImageUrl(char)"
- :alt="char.name"
- />
- <span v-else>{{ char.name?.[0] || "?" }}</span>
+ <img v-if="char.local_path" :src="getImageUrl(char)" :alt="char.name" />
+ <span v-else>{{ char.name?.[0] || '?' }}</span>
</div>
<div class="character-info">
<div class="character-name">{{ char.name }}</div>
- <div class="character-role">{{ char.role || "角色" }}</div>
+ <div class="character-role">{{ char.role || '角色' }}</div>
</div>
<div class="character-check" v-if="isCharacterInCurrentShot(char.id)">
<el-icon color="#409eff" :size="24">
@@ -1932,11 +1386,7 @@
</el-dialog>
<!-- 道具选择对话框 -->
- <el-dialog
- v-model="showPropSelector"
- :title="$t('editor.addPropToShot')"
- width="800px"
- >
+ <el-dialog v-model="showPropSelector" :title="$t('editor.addPropToShot')" width="800px">
<div class="character-selector-grid">
<div
v-for="prop in availableProps"
@@ -1946,11 +1396,7 @@
@click="togglePropInShot(prop.id)"
>
<div class="character-avatar-large">
- <img
- v-if="prop.local_path"
- :src="getImageUrl(prop)"
- :alt="prop.name"
- />
+ <img v-if="prop.local_path" :src="getImageUrl(prop)" :alt="prop.name" />
<el-icon v-else :size="32">
<Box />
</el-icon>
@@ -1958,7 +1404,7 @@
<div class="character-info">
<div class="character-name">{{ prop.name }}</div>
<div class="character-role">
- {{ prop.type || $t("editor.props") }}
+ {{ prop.type || $t('editor.props') }}
</div>
</div>
<div class="character-check" v-if="isPropInCurrentShot(prop.id)">
@@ -1972,9 +1418,7 @@
</div>
</div>
<template #footer>
- <el-button @click="showPropSelector = false">{{
- $t("common.close")
- }}</el-button>
+ <el-button @click="showPropSelector = false">{{ $t('common.close') }}</el-button>
</template>
</el-dialog>
@@ -1989,11 +1433,7 @@
@click="selectScene(scene.id)"
>
<div class="scene-image">
- <img
- v-if="hasImage(scene)"
- :src="getImageUrl(scene)"
- :alt="scene.location"
- />
+ <img v-if="hasImage(scene)" :src="getImageUrl(scene)" :alt="scene.location" />
<el-icon v-else :size="48" color="#ccc">
<Picture />
</el-icon>
@@ -2010,26 +1450,14 @@
</el-dialog>
<!-- 视频预览对话框 -->
- <el-dialog
- v-model="showVideoPreview"
- title="视频预览"
- width="800px"
- :close-on-click-modal="true"
- destroy-on-close
- >
+ <el-dialog v-model="showVideoPreview" title="视频预览" width="800px" :close-on-click-modal="true" destroy-on-close>
<div class="video-preview-container" v-if="previewVideo">
<video
v-if="previewVideo.video_url"
:src="getVideoUrl(previewVideo)"
controls
autoplay
- style="
- width: 100%;
- max-height: 70vh;
- display: block;
- background: #000;
- border-radius: 8px;
- "
+ style="width: 100%; max-height: 70vh; display: block; background: #000; border-radius: 8px"
/>
<div v-else style="text-align: center; padding: 40px">
<el-icon :size="48" color="#ccc">
@@ -2038,23 +1466,14 @@
<p style="margin-top: 16px; color: #909399">视频生成中...</p>
</div>
<div class="video-meta">
- <div
- style="
- display: flex;
- justify-content: space-between;
- align-items: center;
- "
- >
+ <div style="display: flex; justify-content: space-between; align-items: center">
<div>
<el-tag :type="getStatusType(previewVideo.status)" size="small">{{
getStatusText(previewVideo.status)
}}</el-tag>
- <span
- v-if="previewVideo.duration"
- style="margin-left: 12px; color: #606266; font-size: 14px"
- >{{ $t("professionalEditor.duration") }}:
- {{ previewVideo.duration
- }}{{ $t("professionalEditor.seconds") }}</span
+ <span v-if="previewVideo.duration" style="margin-left: 12px; color: #606266; font-size: 14px"
+ >{{ $t('professionalEditor.duration') }}: {{ previewVideo.duration
+ }}{{ $t('professionalEditor.seconds') }}</span
>
</div>
<el-button
@@ -2062,18 +1481,10 @@
size="small"
@click="window.open(previewVideo.video_url, '_blank')"
>
- {{ $t("professionalEditor.downloadVideo") }}
+ {{ $t('professionalEditor.downloadVideo') }}
</el-button>
</div>
- <div
- v-if="previewVideo.prompt"
- style="
- margin-top: 12px;
- font-size: 12px;
- color: #606266;
- line-height: 1.6;
- "
- >
+ <div v-if="previewVideo.prompt" style="margin-top: 12px; font-size: 12px; color: #606266; line-height: 1.6">
<strong>提示词:</strong>{{ previewVideo.prompt }}
</div>
</div>
@@ -2090,26 +1501,15 @@
/>
<!-- 图片裁剪对话框 -->
- <ImageCropDialog
- v-model="showCropDialog"
- :image-url="cropImageUrl"
- @save="handleCropSave"
- />
+ <ImageCropDialog v-model="showCropDialog" :image-url="cropImageUrl" @save="handleCropSave" />
</div>
</template>
<script setup lang="ts">
-import {
- ref,
- computed,
- watch,
- onMounted,
- onBeforeUnmount,
- nextTick,
-} from "vue";
-import { useRoute, useRouter } from "vue-router";
-import { useI18n } from "vue-i18n";
-import { ElMessage, ElMessageBox } from "element-plus";
+import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
+import { useRoute, useRouter } from 'vue-router'
+import { useI18n } from 'vue-i18n'
+import { ElMessage, ElMessageBox } from 'element-plus'
import {
ArrowLeft,
Plus,
@@ -2137,134 +1537,130 @@ import {
Connection,
Box,
Crop,
-} from "@element-plus/icons-vue";
-import { dramaAPI } from "@/api/drama";
-import { propAPI } from "@/api/prop";
-import { generateFramePrompt, type FrameType } from "@/api/frame";
-import { imageAPI } from "@/api/image";
-import { videoAPI } from "@/api/video";
-import { aiAPI } from "@/api/ai";
-import { assetAPI } from "@/api/asset";
-import { videoMergeAPI } from "@/api/videoMerge";
-import { taskAPI } from "@/api/task";
-import type { ImageGeneration } from "@/types/image";
-import type { VideoGeneration } from "@/types/video";
-import type { AIServiceConfig } from "@/types/ai";
-import type { Asset } from "@/types/asset";
-import type { VideoMerge } from "@/api/videoMerge";
-import VideoTimelineEditor from "@/components/editor/VideoTimelineEditor.vue";
-import GridImageEditor from "@/components/editor/GridImageEditor.vue";
-import type { Drama, Episode, Storyboard } from "@/types/drama";
-import { AppHeader, ImageCropDialog } from "@/components/common";
-import { getImageUrl, hasImage, getVideoUrl } from "@/utils/image";
-
-const route = useRoute();
-const router = useRouter();
-const { t: $t } = useI18n();
-
-const dramaId = Number(route.params.dramaId);
-const episodeNumber = Number(route.params.episodeNumber);
-const episodeId = ref<number>(0);
-
-const drama = ref<Drama | null>(null);
-const episode = ref<Episode | null>(null);
-const storyboards = ref<Storyboard[]>([]);
-const characters = ref<any[]>([]);
-const availableScenes = ref<any[]>([]);
-const props = ref<any[]>([]);
-const showPropSelector = ref(false);
-
-const currentStoryboardId = ref<string | null>(null);
-const activeTab = ref("shot");
-const showSceneSelector = ref(false);
-const showCharacterSelector = ref(false);
-const showCharacterImagePreview = ref(false);
-const previewCharacter = ref<any>(null);
-const showSceneImagePreview = ref(false);
-const showSettings = ref(false);
-const showVideoPreview = ref(false);
-const previewVideo = ref<VideoGeneration | null>(null);
-const addingToAssets = ref<Set<number>>(new Set());
-
-const currentPlayState = ref<"playing" | "paused">("paused");
-const currentTime = ref(0);
+ FolderAdd,
+} from '@element-plus/icons-vue'
+import { dramaAPI } from '@/api/drama'
+import { propAPI } from '@/api/prop'
+import { generateFramePrompt, type FrameType } from '@/api/frame'
+import { imageAPI } from '@/api/image'
+import { videoAPI } from '@/api/video'
+import { aiAPI } from '@/api/ai'
+import { assetAPI } from '@/api/asset'
+import { videoMergeAPI } from '@/api/videoMerge'
+import { taskAPI } from '@/api/task'
+import type { ImageGeneration } from '@/types/image'
+import type { VideoGeneration } from '@/types/video'
+import type { AIServiceConfig } from '@/types/ai'
+import type { Asset } from '@/types/asset'
+import type { VideoMerge } from '@/api/videoMerge'
+import VideoTimelineEditor from '@/components/editor/VideoTimelineEditor.vue'
+import GridImageEditor from '@/components/editor/GridImageEditor.vue'
+import type { Drama, Episode, Storyboard } from '@/types/drama'
+import { AppHeader, ImageCropDialog } from '@/components/common'
+import { getImageUrl, hasImage, getVideoUrl } from '@/utils/image'
+
+const route = useRoute()
+const router = useRouter()
+const { t: $t } = useI18n()
+
+const dramaId = Number(route.params.dramaId)
+const episodeNumber = Number(route.params.episodeNumber)
+const episodeId = ref<number>(0)
+
+const drama = ref<Drama | null>(null)
+const episode = ref<Episode | null>(null)
+const storyboards = ref<Storyboard[]>([])
+const characters = ref<any[]>([])
+const availableScenes = ref<any[]>([])
+const props = ref<any[]>([])
+const showPropSelector = ref(false)
+
+const currentStoryboardId = ref<string | null>(null)
+const activeTab = ref('shot')
+const showSceneSelector = ref(false)
+const showCharacterSelector = ref(false)
+const showCharacterImagePreview = ref(false)
+const previewCharacter = ref<any>(null)
+const showSceneImagePreview = ref(false)
+const showSettings = ref(false)
+const showVideoPreview = ref(false)
+const previewVideo = ref<VideoGeneration | null>(null)
+const addingToAssets = ref<Set<number>>(new Set())
+
+const currentPlayState = ref<'playing' | 'paused'>('paused')
+const currentTime = ref(0)
const totalDuration = computed(() => {
- if (!Array.isArray(storyboards.value)) return 0;
- return storyboards.value.reduce((sum, s) => sum + (s.duration || 0), 0);
-});
+ if (!Array.isArray(storyboards.value)) return 0
+ return storyboards.value.reduce((sum, s) => sum + (s.duration || 0), 0)
+})
-const selectedCharacters = ref<number[]>([]);
-const narrativeTab = ref("shot-prompt");
+const selectedCharacters = ref<number[]>([])
+const narrativeTab = ref('shot-prompt')
// 图片生成相关状态
-const selectedFrameType = ref<FrameType>("first");
-const panelCount = ref(3);
-const generatingPromptStates = ref<Record<string, boolean>>({}); // 按 "镜头ID_帧类型" 记录生成状态
+const selectedFrameType = ref<FrameType>('first')
+const panelCount = ref(3)
+const generatingPromptStates = ref<Record<string, boolean>>({}) // 按 "镜头ID_帧类型" 记录生成状态
const framePrompts = ref<Record<string, string>>({
- key: "",
- first: "",
- last: "",
- panel: "",
-});
-const currentFramePrompt = ref("");
-const generatingImage = ref(false);
-const generatedImages = ref<ImageGeneration[]>([]);
-const isSwitchingFrameType = ref(false); // 标志位:是否正在切换帧类型
-const loadingImages = ref(false);
-let pollingTimer: any = null;
-let pollingFrameType: FrameType | null = null; // 记录正在轮询的帧类型
+ key: '',
+ first: '',
+ last: '',
+ panel: '',
+})
+const currentFramePrompt = ref('')
+const generatingImage = ref(false)
+const generatedImages = ref<ImageGeneration[]>([])
+const isSwitchingFrameType = ref(false) // 标志位:是否正在切换帧类型
+const loadingImages = ref(false)
+let pollingTimer: any = null
+let pollingFrameType: FrameType | null = null // 记录正在轮询的帧类型
// 宫格图片编辑器状态
-const showGridEditor = ref(false);
+const showGridEditor = ref(false)
// 所有已生成的图片(用于宫格编辑器选择)
-const allGeneratedImages = ref<ImageGeneration[]>([]);
+const allGeneratedImages = ref<ImageGeneration[]>([])
// 图片裁剪对话框状态
-const showCropDialog = ref(false);
-const cropImageUrl = ref<string>("");
-const cropImageData = ref<ImageGeneration | null>(null);
+const showCropDialog = ref(false)
+const cropImageUrl = ref<string>('')
+const cropImageData = ref<ImageGeneration | null>(null)
// 视频生成相关状态
-const videoDuration = ref(5); // 默认5秒,会根据镜头duration自动更新
-const selectedVideoFrameType = ref<FrameType>("first");
-const selectedImagesForVideo = ref<number[]>([]);
-const selectedLastImageForVideo = ref<number | null>(null);
-const generatingVideo = ref(false);
-const generatedVideos = ref<VideoGeneration[]>([]);
-const videoAssets = ref<Asset[]>([]);
-const loadingVideos = ref(false);
-const timelineEditorRef = ref<InstanceType<typeof VideoTimelineEditor> | null>(
- null,
-);
-const videoReferenceImages = ref<ImageGeneration[]>([]);
-const selectedVideoModel = ref<string>("");
-const selectedReferenceMode = ref<string>(""); // 参考图模式:single, first_last, multiple, none
-const previewImageUrl = ref<string>(""); // 预览大图的URL
-const videoModelCapabilities = ref<VideoModelCapability[]>([]);
-let videoPollingTimer: any = null;
-let mergePollingTimer: any = null; // 视频合成列表轮询定时器
+const videoDuration = ref(5) // 默认5秒,会根据镜头duration自动更新
+const selectedVideoFrameType = ref<FrameType>('first')
+const selectedImagesForVideo = ref<number[]>([])
+const selectedLastImageForVideo = ref<number | null>(null)
+const generatingVideo = ref(false)
+const generatedVideos = ref<VideoGeneration[]>([])
+const videoAssets = ref<Asset[]>([])
+const loadingVideos = ref(false)
+const timelineEditorRef = ref<InstanceType<typeof VideoTimelineEditor> | null>(null)
+const videoReferenceImages = ref<ImageGeneration[]>([])
+const selectedVideoModel = ref<string>('')
+const selectedReferenceMode = ref<string>('') // 参考图模式:single, first_last, multiple, none
+const previewImageUrl = ref<string>('') // 预览大图的URL
+const videoModelCapabilities = ref<VideoModelCapability[]>([])
+let videoPollingTimer: any = null
+let mergePollingTimer: any = null // 视频合成列表轮询定时器
// 视频合成列表
-const videoMerges = ref<VideoMerge[]>([]);
-const loadingMerges = ref(false);
+const videoMerges = ref<VideoMerge[]>([])
+const loadingMerges = ref(false)
// 视频模型能力配置
interface VideoModelCapability {
- id: string;
- name: string;
- supportMultipleImages: boolean; // 支持多张图片
- supportFirstLastFrame: boolean; // 支持首尾帧
- supportSingleImage: boolean; // 支持单图
- supportTextOnly: boolean; // 支持纯文本
- maxImages: number; // 最多支持几张图片
+ id: string
+ name: string
+ supportMultipleImages: boolean // 支持多张图片
+ supportFirstLastFrame: boolean // 支持首尾帧
+ supportSingleImage: boolean // 支持单图
+ supportTextOnly: boolean // 支持纯文本
+ maxImages: number // 最多支持几张图片
}
// 模型能力默认配置(作为后备)
-const defaultModelCapabilities: Record<
- string,
- Omit<VideoModelCapability, "id" | "name">
-> = {
+const defaultModelCapabilities: Record<string, Omit<VideoModelCapability, 'id' | 'name'>> = {
kling: {
supportSingleImage: true,
supportMultipleImages: false,
@@ -2286,166 +1682,159 @@ const defaultModelCapabilities: Record<
supportTextOnly: true,
maxImages: 6,
},
- "doubao-seedance-1-5-pro-251215": {
+ 'doubao-seedance-1-5-pro-251215': {
supportSingleImage: true,
supportMultipleImages: false,
supportFirstLastFrame: true,
supportTextOnly: true,
maxImages: 2,
},
- "doubao-seedance-1-0-lite-i2v-250428": {
+ 'doubao-seedance-1-0-lite-i2v-250428': {
supportSingleImage: true,
supportMultipleImages: true,
supportFirstLastFrame: true,
supportTextOnly: false,
maxImages: 6,
},
- "doubao-seedance-1-0-lite-t2v-250428": {
+ 'doubao-seedance-1-0-lite-t2v-250428': {
supportSingleImage: false,
supportMultipleImages: false,
supportFirstLastFrame: false,
supportTextOnly: true,
maxImages: 0,
},
- "doubao-seedance-1-0-pro-250528": {
+ 'doubao-seedance-1-0-pro-250528': {
supportSingleImage: true,
supportMultipleImages: false,
supportFirstLastFrame: true,
supportTextOnly: true,
maxImages: 2,
},
- "doubao-seedance-1-0-pro-fast-251015": {
+ 'doubao-seedance-1-0-pro-fast-251015': {
supportSingleImage: true,
supportMultipleImages: false,
supportFirstLastFrame: false,
supportTextOnly: true,
maxImages: 1,
},
- "sora-2": {
+ 'sora-2': {
supportSingleImage: true,
supportMultipleImages: false,
supportFirstLastFrame: false,
supportTextOnly: true,
maxImages: 1,
},
- "sora-2-pro": {
+ 'sora-2-pro': {
supportSingleImage: true,
supportMultipleImages: false,
supportFirstLastFrame: true,
supportTextOnly: true,
maxImages: 2,
},
- "MiniMax-Hailuo-2.3": {
+ 'MiniMax-Hailuo-2.3': {
supportSingleImage: true,
supportMultipleImages: false,
supportFirstLastFrame: false,
supportTextOnly: true,
maxImages: 1,
},
- "MiniMax-Hailuo-2.3-Fast": {
+ 'MiniMax-Hailuo-2.3-Fast': {
supportSingleImage: true,
supportMultipleImages: false,
supportFirstLastFrame: false,
supportTextOnly: true,
maxImages: 1,
},
- "MiniMax-Hailuo-02": {
+ 'MiniMax-Hailuo-02': {
supportSingleImage: true,
supportMultipleImages: false,
supportFirstLastFrame: false,
supportTextOnly: true,
maxImages: 1,
},
-};
+}
// 从模型名称提取provider
const extractProviderFromModel = (modelName: string): string => {
- if (modelName.startsWith("doubao-") || modelName.startsWith("seedance")) {
- return "doubao";
+ if (modelName.startsWith('doubao-') || modelName.startsWith('seedance')) {
+ return 'doubao'
}
- if (modelName.startsWith("runway")) {
- return "runway";
+ if (modelName.startsWith('runway')) {
+ return 'runway'
}
- if (modelName.startsWith("pika")) {
- return "pika";
+ if (modelName.startsWith('pika')) {
+ return 'pika'
}
if (
- modelName.startsWith("MiniMax-") ||
- modelName.toLowerCase().startsWith("minimax") ||
- modelName.startsWith("hailuo")
+ modelName.startsWith('MiniMax-') ||
+ modelName.toLowerCase().startsWith('minimax') ||
+ modelName.startsWith('hailuo')
) {
- return "minimax";
+ return 'minimax'
}
- if (modelName.startsWith("sora")) {
- return "openai";
+ if (modelName.startsWith('sora')) {
+ return 'openai'
}
- if (modelName.startsWith("kling")) {
- return "kling";
+ if (modelName.startsWith('kling')) {
+ return 'kling'
}
// 默认返回doubao
- return "doubao";
-};
+ return 'doubao'
+}
// 加载视频AI配置
const loadVideoModels = async () => {
try {
- const configs = await aiAPI.list("video");
+ const configs = await aiAPI.list('video')
// 只显示启用的配置
- const activeConfigs = configs.filter((c) => c.is_active);
+ const activeConfigs = configs.filter((c) => c.is_active)
// 展开模型列表并去重
const allModels = activeConfigs
.flatMap((config) => {
- const models = Array.isArray(config.model)
- ? config.model
- : [config.model];
+ const models = Array.isArray(config.model) ? config.model : [config.model]
return models.map((modelName) => ({
modelName,
configName: config.name,
priority: config.priority || 0,
- }));
+ }))
})
- .sort((a, b) => b.priority - a.priority);
+ .sort((a, b) => b.priority - a.priority)
// 按模型名称去重
- const modelMap = new Map<
- string,
- { configName: string; priority: number }
- >();
+ const modelMap = new Map<string, { configName: string; priority: number }>()
allModels.forEach((model) => {
if (!modelMap.has(model.modelName)) {
modelMap.set(model.modelName, {
configName: model.configName,
priority: model.priority,
- });
+ })
}
- });
+ })
// 构建模型能力列表
- videoModelCapabilities.value = Array.from(modelMap.keys()).map(
- (modelName) => {
- const capability = defaultModelCapabilities[modelName] || {
- supportSingleImage: true,
- supportMultipleImages: false,
- supportFirstLastFrame: false,
- supportTextOnly: true,
- maxImages: 1,
- };
-
- return {
- id: modelName,
- name: modelName,
- ...capability,
- };
- },
- );
+ videoModelCapabilities.value = Array.from(modelMap.keys()).map((modelName) => {
+ const capability = defaultModelCapabilities[modelName] || {
+ supportSingleImage: true,
+ supportMultipleImages: false,
+ supportFirstLastFrame: false,
+ supportTextOnly: true,
+ maxImages: 1,
+ }
+
+ return {
+ id: modelName,
+ name: modelName,
+ ...capability,
+ }
+ })
} catch (error: any) {
- console.error("加载视频模型配置失败:", error);
- ElMessage.error("加载视频模型失败");
+ console.error('加载视频模型配置失败:', error)
+ ElMessage.error('加载视频模型失败')
}
-};
+}
// 加载视频素材库
const loadVideoAssets = async () => {
@@ -2453,493 +1842,448 @@ const loadVideoAssets = async () => {
const result = await assetAPI.listAssets({
drama_id: dramaId.toString(),
episode_id: episodeId.value,
- type: "video",
+ type: 'video',
page: 1,
page_size: 100,
- });
+ })
// 检查数据结构并正确赋值
- videoAssets.value = result.items || [];
+ videoAssets.value = result.items || []
} catch (error: any) {
- console.error("加载视频素材库失败:", error);
+ console.error('加载视频素材库失败:', error)
}
-};
+}
// 当前模型能力
const currentModelCapability = computed(() => {
- return videoModelCapabilities.value.find(
- (m) => m.id === selectedVideoModel.value,
- );
-});
+ return videoModelCapabilities.value.find((m) => m.id === selectedVideoModel.value)
+})
// 当前模型支持的参考图模式
const availableReferenceModes = computed(() => {
- const capability = currentModelCapability.value;
- if (!capability) return [];
+ const capability = currentModelCapability.value
+ if (!capability) return []
- const modes: Array<{ value: string; label: string; description?: string }> =
- [];
+ const modes: Array<{ value: string; label: string; description?: string }> = []
if (capability.supportTextOnly) {
- modes.push({ value: "none", label: "纯文本", description: "不使用参考图" });
+ modes.push({ value: 'none', label: '纯文本', description: '不使用参考图' })
}
if (capability.supportSingleImage) {
modes.push({
- value: "single",
- label: "单图",
- description: "使用单张参考图",
- });
+ value: 'single',
+ label: '单图',
+ description: '使用单张参考图',
+ })
}
if (capability.supportFirstLastFrame) {
modes.push({
- value: "first_last",
- label: "首尾帧",
- description: "使用首帧和尾帧",
- });
+ value: 'first_last',
+ label: '首尾帧',
+ description: '使用首帧和尾帧',
+ })
}
if (capability.supportMultipleImages) {
modes.push({
- value: "multiple",
- label: "多图",
+ value: 'multiple',
+ label: '多图',
description: `最多${capability.maxImages}张`,
- });
+ })
}
- return modes;
-});
+ return modes
+})
// 帧提示词存储key生成函数
-const getPromptStorageKey = (
- storyboardId: number | undefined,
- frameType: FrameType,
-) => {
- if (!storyboardId) return null;
- return `frame_prompt_${storyboardId}_${frameType}`;
-};
+const getPromptStorageKey = (storyboardId: number | undefined, frameType: FrameType) => {
+ if (!storyboardId) return null
+ return `frame_prompt_${storyboardId}_${frameType}`
+}
const isCharacterSelected = (charId: number) => {
- return selectedCharacters.value.includes(charId);
-};
+ return selectedCharacters.value.includes(charId)
+}
const toggleCharacter = (charId: number) => {
- const index = selectedCharacters.value.indexOf(charId);
+ const index = selectedCharacters.value.indexOf(charId)
if (index > -1) {
- selectedCharacters.value.splice(index, 1);
+ selectedCharacters.value.splice(index, 1)
} else {
- selectedCharacters.value.push(charId);
+ selectedCharacters.value.push(charId)
}
-};
+}
const currentStoryboard = computed(() => {
- if (!currentStoryboardId.value) return null;
- return (
- storyboards.value.find(
- (s) => String(s.id) === String(currentStoryboardId.value),
- ) || null
- );
-});
+ if (!currentStoryboardId.value) return null
+ return storyboards.value.find((s) => String(s.id) === String(currentStoryboardId.value)) || null
+})
// 获取上一个镜头
const previousStoryboard = computed(() => {
- if (!currentStoryboardId.value || storyboards.value.length < 2) return null;
- const currentIndex = storyboards.value.findIndex(
- (s) => String(s.id) === String(currentStoryboardId.value),
- );
- if (currentIndex <= 0) return null;
- return storyboards.value[currentIndex - 1];
-});
+ if (!currentStoryboardId.value || storyboards.value.length < 2) return null
+ const currentIndex = storyboards.value.findIndex((s) => String(s.id) === String(currentStoryboardId.value))
+ if (currentIndex <= 0) return null
+ return storyboards.value[currentIndex - 1]
+})
// 上一个镜头的尾帧图片列表(支持多个)
-const previousStoryboardLastFrames = ref<any[]>([]);
+const previousStoryboardLastFrames = ref<any[]>([])
// 加载上一个镜头的尾帧
const loadPreviousStoryboardLastFrame = async () => {
if (!previousStoryboard.value) {
- previousStoryboardLastFrames.value = [];
- return;
+ previousStoryboardLastFrames.value = []
+ return
}
try {
const result = await imageAPI.listImages({
storyboard_id: previousStoryboard.value.id,
- frame_type: "last",
+ frame_type: 'last',
page: 1,
page_size: 10,
- });
- const images = result.items || [];
- previousStoryboardLastFrames.value = images.filter(
- (img: any) => img.status === "completed" && img.image_url,
- );
+ })
+ const images = result.items || []
+ previousStoryboardLastFrames.value = images.filter((img: any) => img.status === 'completed' && img.image_url)
} catch (error) {
- console.error("加载上一镜头尾帧失败:", error);
- previousStoryboardLastFrames.value = [];
+ console.error('加载上一镜头尾帧失败:', error)
+ previousStoryboardLastFrames.value = []
}
-};
+}
// 选择上一镜头尾帧作为首帧参考
const selectPreviousLastFrame = (img: any) => {
// 检查是否已选中,已选中则取消
- const currentIndex = selectedImagesForVideo.value.indexOf(img.id);
+ const currentIndex = selectedImagesForVideo.value.indexOf(img.id)
if (currentIndex > -1) {
- selectedImagesForVideo.value.splice(currentIndex, 1);
- ElMessage.success("已取消首帧参考");
- return;
+ selectedImagesForVideo.value.splice(currentIndex, 1)
+ ElMessage.success('已取消首帧参考')
+ return
}
// 参考handleImageSelect的逻辑,根据模式处理
- if (
- !selectedReferenceMode.value ||
- selectedReferenceMode.value === "single"
- ) {
+ if (!selectedReferenceMode.value || selectedReferenceMode.value === 'single') {
// 单图模式或未选模式:直接替换
- selectedImagesForVideo.value = [img.id];
- } else if (selectedReferenceMode.value === "first_last") {
+ selectedImagesForVideo.value = [img.id]
+ } else if (selectedReferenceMode.value === 'first_last') {
// 首尾帧模式:作为首帧参考
- selectedImagesForVideo.value = [img.id];
- } else if (selectedReferenceMode.value === "multiple") {
+ selectedImagesForVideo.value = [img.id]
+ } else if (selectedReferenceMode.value === 'multiple') {
// 多图模式:添加到列表
- const capability = currentModelCapability.value;
- if (
- capability &&
- selectedImagesForVideo.value.length >= capability.maxImages
- ) {
- ElMessage.warning(`最多只能选择${capability.maxImages}张图片`);
- return;
+ const capability = currentModelCapability.value
+ if (capability && selectedImagesForVideo.value.length >= capability.maxImages) {
+ ElMessage.warning(`最多只能选择${capability.maxImages}张图片`)
+ return
}
- selectedImagesForVideo.value.push(img.id);
+ selectedImagesForVideo.value.push(img.id)
}
- ElMessage.success("已添加为首帧参考");
-};
+ ElMessage.success('已添加为首帧参考')
+}
// 监听帧类型切换,从存储中加载或清空
watch(selectedFrameType, (newType) => {
// 切换帧类型时,停止之前的轮询,避免旧结果覆盖新帧类型
- stopPolling();
+ stopPolling()
if (!currentStoryboard.value) {
- currentFramePrompt.value = "";
- generatedImages.value = [];
- return;
+ currentFramePrompt.value = ''
+ generatedImages.value = []
+ return
}
// 设置切换标志,防止watch(currentFramePrompt)错误保存
- isSwitchingFrameType.value = true;
+ isSwitchingFrameType.value = true
// 优先从 sessionStorage 中加载该帧类型的提示词(确保数据准确)
- const storageKey = `frame_prompt_${currentStoryboard.value.id}_${newType}`;
- const stored = sessionStorage.getItem(storageKey);
+ const storageKey = `frame_prompt_${currentStoryboard.value.id}_${newType}`
+ const stored = sessionStorage.getItem(storageKey)
if (stored) {
- currentFramePrompt.value = stored;
- framePrompts.value[newType] = stored;
+ currentFramePrompt.value = stored
+ framePrompts.value[newType] = stored
} else {
// 如果 sessionStorage 中没有,再尝试从 framePrompts 对象中读取
- currentFramePrompt.value = framePrompts.value[newType] || "";
+ currentFramePrompt.value = framePrompts.value[newType] || ''
}
// 重新加载该帧类型的图片
- loadStoryboardImages(currentStoryboard.value.id, newType);
+ loadStoryboardImages(currentStoryboard.value.id, newType)
// 重置切换标志
setTimeout(() => {
- isSwitchingFrameType.value = false;
- }, 0);
-});
+ isSwitchingFrameType.value = false
+ }, 0)
+})
// 监听当前分镜切换,重置提示词
watch(currentStoryboard, async (newStoryboard) => {
if (!newStoryboard) {
- currentFramePrompt.value = "";
- generatedImages.value = [];
- generatedVideos.value = [];
- videoReferenceImages.value = [];
- previousStoryboardLastFrames.value = [];
- return;
+ currentFramePrompt.value = ''
+ generatedImages.value = []
+ generatedVideos.value = []
+ videoReferenceImages.value = []
+ previousStoryboardLastFrames.value = []
+ return
}
// 设置切换标志
- isSwitchingFrameType.value = true;
+ isSwitchingFrameType.value = true
// 清空 framePrompts 对象,避免显示上一个镜头的提示词
framePrompts.value = {
- key: "",
- first: "",
- last: "",
- panel: "",
- };
+ key: '',
+ first: '',
+ last: '',
+ panel: '',
+ }
// 加载当前帧类型的提示词
- const storageKey = getPromptStorageKey(
- newStoryboard.id,
- selectedFrameType.value,
- );
+ const storageKey = getPromptStorageKey(newStoryboard.id, selectedFrameType.value)
if (storageKey) {
- const stored = sessionStorage.getItem(storageKey);
- currentFramePrompt.value = stored || "";
+ const stored = sessionStorage.getItem(storageKey)
+ currentFramePrompt.value = stored || ''
// 同时更新 framePrompts 对象
if (stored) {
- framePrompts.value[selectedFrameType.value] = stored;
+ framePrompts.value[selectedFrameType.value] = stored
}
} else {
- currentFramePrompt.value = "";
+ currentFramePrompt.value = ''
}
// 重置切换标志
setTimeout(() => {
- isSwitchingFrameType.value = false;
- }, 0);
+ isSwitchingFrameType.value = false
+ }, 0)
// 加载该分镜的图片列表(根据当前选择的帧类型)
- await loadStoryboardImages(newStoryboard.id, selectedFrameType.value);
+ await loadStoryboardImages(newStoryboard.id, selectedFrameType.value)
// 加载所有已生成的图片(用于宫格编辑器)
- await loadAllGeneratedImages();
+ await loadAllGeneratedImages()
// 加载视频参考图片(所有帧类型)
- await loadVideoReferenceImages(newStoryboard.id);
+ await loadVideoReferenceImages(newStoryboard.id)
// 加载该分镜的视频列表
- await loadStoryboardVideos(newStoryboard.id);
+ await loadStoryboardVideos(newStoryboard.id)
// 加载上一镜头的尾帧
- await loadPreviousStoryboardLastFrame();
-});
+ await loadPreviousStoryboardLastFrame()
+})
// 监听提示词变化,自动保存到sessionStorage
watch(currentFramePrompt, (newPrompt) => {
// 如果正在切换帧类型或分镜,不要保存(避免错误保存到新帧类型)
- if (isSwitchingFrameType.value) return;
- if (!currentStoryboard.value) return;
+ if (isSwitchingFrameType.value) return
+ if (!currentStoryboard.value) return
- const storageKey = getPromptStorageKey(
- currentStoryboard.value.id,
- selectedFrameType.value,
- );
+ const storageKey = getPromptStorageKey(currentStoryboard.value.id, selectedFrameType.value)
if (storageKey) {
if (newPrompt) {
- sessionStorage.setItem(storageKey, newPrompt);
+ sessionStorage.setItem(storageKey, newPrompt)
} else {
- sessionStorage.removeItem(storageKey);
+ sessionStorage.removeItem(storageKey)
}
}
-});
+})
// 监听视频模型切换,清空已选图片和参考图模式
watch(selectedVideoModel, () => {
- selectedImagesForVideo.value = [];
- selectedLastImageForVideo.value = null;
- selectedReferenceMode.value = "";
-});
+ selectedImagesForVideo.value = []
+ selectedLastImageForVideo.value = null
+ selectedReferenceMode.value = ''
+})
// 监听镜头切换,自动更新视频时长
watch(currentStoryboard, (newStoryboard) => {
if (newStoryboard?.duration) {
// 如果镜头有duration字段,使用镜头的时长
- videoDuration.value = Math.round(newStoryboard.duration);
+ videoDuration.value = Math.round(newStoryboard.duration)
} else {
// 否则使用默认值5秒
- videoDuration.value = 5;
+ videoDuration.value = 5
}
-});
+})
// 监听参考图模式切换,清空已选图片
watch(selectedReferenceMode, () => {
- selectedImagesForVideo.value = [];
- selectedLastImageForVideo.value = null;
-});
+ selectedImagesForVideo.value = []
+ selectedLastImageForVideo.value = null
+})
// 当前分镜的角色列表
const currentStoryboardCharacters = computed(() => {
- if (!currentStoryboard.value?.characters) return [];
+ if (!currentStoryboard.value?.characters) return []
// currentStoryboard.characters 是角色对象数组
- if (
- Array.isArray(currentStoryboard.value.characters) &&
- currentStoryboard.value.characters.length > 0
- ) {
- const firstItem = currentStoryboard.value.characters[0];
+ if (Array.isArray(currentStoryboard.value.characters) && currentStoryboard.value.characters.length > 0) {
+ const firstItem = currentStoryboard.value.characters[0]
// 如果是对象数组(包含id和name),直接返回
- if (typeof firstItem === "object" && firstItem.id) {
- return currentStoryboard.value.characters;
+ if (typeof firstItem === 'object' && firstItem.id) {
+ return currentStoryboard.value.characters
}
// 如果是ID数组,从characters中查找匹配的角色
- if (typeof firstItem === "number") {
- return characters.value.filter((c) =>
- currentStoryboard.value.characters.includes(c.id),
- );
+ if (typeof firstItem === 'number') {
+ return characters.value.filter((c) => currentStoryboard.value.characters.includes(c.id))
}
}
- return [];
-});
+ return []
+})
// 可选择的角色列表
const availableCharacters = computed(() => {
- return characters.value || [];
-});
+ return characters.value || []
+})
// 可选择的道具列表
const availableProps = computed(() => {
- return props.value || [];
-});
+ return props.value || []
+})
// 当前分镜的道具列表
const currentStoryboardProps = computed(() => {
- if (!currentStoryboard.value?.props) return [];
- return currentStoryboard.value.props;
-});
+ if (!currentStoryboard.value?.props) return []
+ return currentStoryboard.value.props
+})
// 检查道具是否在当前镜头中
const isPropInCurrentShot = (propId: number) => {
- if (!currentStoryboard.value?.props) return false;
- return currentStoryboard.value.props.some((p: any) => p.id === propId);
-};
+ if (!currentStoryboard.value?.props) return false
+ return currentStoryboard.value.props.some((p: any) => p.id === propId)
+}
// 切换道具在镜头中的状态
const togglePropInShot = async (propId: number) => {
- if (!currentStoryboard.value) return;
+ if (!currentStoryboard.value) return
- let newProps = [...(currentStoryboard.value.props || [])];
+ let newProps = [...(currentStoryboard.value.props || [])]
if (isPropInCurrentShot(propId)) {
- newProps = newProps.filter((p: any) => p.id !== propId);
+ newProps = newProps.filter((p: any) => p.id !== propId)
} else {
- const prop = props.value.find((p) => p.id === propId);
+ const prop = props.value.find((p) => p.id === propId)
if (prop) {
- newProps.push(prop);
+ newProps.push(prop)
}
}
// 乐观更新
- currentStoryboard.value.props = newProps;
+ currentStoryboard.value.props = newProps
try {
- const propIds = newProps.map((p: any) => p.id);
- await propAPI.associateWithStoryboard(
- Number(currentStoryboard.value.id),
- propIds,
- );
+ const propIds = newProps.map((p: any) => p.id)
+ await propAPI.associateWithStoryboard(Number(currentStoryboard.value.id), propIds)
} catch (error) {
- ElMessage.error($t("editor.updatePropFailed"));
+ ElMessage.error($t('editor.updatePropFailed'))
}
-};
+}
// 检查角色是否已在当前镜头中
const isCharacterInCurrentShot = (charId: number) => {
- if (!currentStoryboard.value?.characters) return false;
+ if (!currentStoryboard.value?.characters) return false
- if (
- Array.isArray(currentStoryboard.value.characters) &&
- currentStoryboard.value.characters.length > 0
- ) {
- const firstItem = currentStoryboard.value.characters[0];
- if (typeof firstItem === "object" && firstItem.id) {
- return currentStoryboard.value.characters.some((c) => c.id === charId);
+ if (Array.isArray(currentStoryboard.value.characters) && currentStoryboard.value.characters.length > 0) {
+ const firstItem = currentStoryboard.value.characters[0]
+ if (typeof firstItem === 'object' && firstItem.id) {
+ return currentStoryboard.value.characters.some((c) => c.id === charId)
}
- if (typeof firstItem === "number") {
- return currentStoryboard.value.characters.includes(charId);
+ if (typeof firstItem === 'number') {
+ return currentStoryboard.value.characters.includes(charId)
}
}
- return false;
-};
+ return false
+}
// 切换角色在镜头中的状态
const showCharacterImage = (char: any) => {
- previewCharacter.value = char;
- showCharacterImagePreview.value = true;
-};
+ previewCharacter.value = char
+ showCharacterImagePreview.value = true
+}
// 展示场景大图
const showSceneImage = () => {
if (currentStoryboard.value?.background?.image_url) {
- showSceneImagePreview.value = true;
+ showSceneImagePreview.value = true
}
-};
+}
// 保存分镜字段
const saveStoryboardField = async (fieldName: string) => {
- if (!currentStoryboard.value) return;
+ if (!currentStoryboard.value) return
try {
- const updateData: any = {};
- updateData[fieldName] = currentStoryboard.value[fieldName];
+ const updateData: any = {}
+ updateData[fieldName] = currentStoryboard.value[fieldName]
- await dramaAPI.updateStoryboard(
- currentStoryboard.value.id.toString(),
- updateData,
- );
+ await dramaAPI.updateStoryboard(currentStoryboard.value.id.toString(), updateData)
} catch (error: any) {
- ElMessage.error("保存失败: " + (error.message || "未知错误"));
+ ElMessage.error('保存失败: ' + (error.message || '未知错误'))
}
-};
+}
// 提取帧提示词
// 提取帧提示词
const extractFramePrompt = async () => {
- if (!currentStoryboard.value) return;
+ if (!currentStoryboard.value) return
- const storyboardId = currentStoryboard.value.id;
+ const storyboardId = currentStoryboard.value.id
// 记录点击时的帧类型,后续任务完成时用于判断是否需要更新当前显示
- const targetFrameType = selectedFrameType.value;
+ const targetFrameType = selectedFrameType.value
- if (targetFrameType === "panel") {
+ if (targetFrameType === 'panel') {
// 如果是分镜板模式,还需要捕获当前的panelCount
// 注意:这里简单起见使用当前的panelCount,理想情况下应该传递参数或锁定UI
}
// 设置当前镜头的生成状态为true
- const stateKey = `${storyboardId}_${targetFrameType}`;
- generatingPromptStates.value[stateKey] = true;
+ const stateKey = `${storyboardId}_${targetFrameType}`
+ generatingPromptStates.value[stateKey] = true
try {
- const params: any = { frame_type: targetFrameType };
- if (targetFrameType === "panel") {
- params.panel_count = panelCount.value;
+ const params: any = { frame_type: targetFrameType }
+ if (targetFrameType === 'panel') {
+ params.panel_count = panelCount.value
}
- const { task_id } = await generateFramePrompt(storyboardId, params);
+ const { task_id } = await generateFramePrompt(storyboardId, params)
// 轮询任务状态(独立函数,不依赖组件当前状态)
const pollTask = async () => {
while (true) {
- const task = await taskAPI.getStatus(task_id);
- if (task.status === "completed") {
- let result = task.result;
- if (typeof result === "string") {
+ const task = await taskAPI.getStatus(task_id)
+ if (task.status === 'completed') {
+ let result = task.result
+ if (typeof result === 'string') {
try {
- result = JSON.parse(result);
+ result = JSON.parse(result)
} catch (e) {
- console.error("Failed to parse task result", e);
- throw new Error("解析任务结果失败");
+ console.error('Failed to parse task result', e)
+ throw new Error('解析任务结果失败')
}
}
- return result.response;
- } else if (task.status === "failed") {
- throw new Error(task.message || task.error || "生成失败");
+ return result.response
+ } else if (task.status === 'failed') {
+ throw new Error(task.message || task.error || '生成失败')
}
// 等待1秒后继续轮询
- await new Promise((resolve) => setTimeout(resolve, 1000));
+ await new Promise((resolve) => setTimeout(resolve, 1000))
}
- };
+ }
- const result = await pollTask();
+ const result = await pollTask()
// 根据返回结果构建提示词字符串
- let extractedPrompt = "";
+ let extractedPrompt = ''
if (result.single_frame) {
- extractedPrompt = result.single_frame.prompt;
+ extractedPrompt = result.single_frame.prompt
} else if (result.multi_frame && result.multi_frame.frames) {
// 多帧情况,将所有帧的prompt合并
- extractedPrompt = result.multi_frame.frames
- .map(
- (frame: any, index: number) =>
- `${frame.description}: ${frame.prompt}`,
- )
- .join("\n\n");
+ extractedPrompt = result.multi_frame.frames.map((frame: any) => frame.prompt).join('\n\n')
}
// 更新存储(这一步必须做,无论用户是否还在当前页面)
// 更新 session storage
- const storageKey = getPromptStorageKey(storyboardId, targetFrameType);
+ const storageKey = getPromptStorageKey(storyboardId, targetFrameType)
if (storageKey) {
- sessionStorage.setItem(storageKey, extractedPrompt);
+ sessionStorage.setItem(storageKey, extractedPrompt)
}
// 如果任务完成时,用户当前的选中状态正好是该镜头+该类型,则立即更新显示
@@ -2948,96 +2292,90 @@ const extractFramePrompt = async () => {
currentStoryboard.value.id === storyboardId &&
selectedFrameType.value === targetFrameType
) {
- currentFramePrompt.value = extractedPrompt;
- framePrompts.value[targetFrameType] = extractedPrompt;
+ currentFramePrompt.value = extractedPrompt
+ framePrompts.value[targetFrameType] = extractedPrompt
}
// 更新内存缓存(稍微复杂点,framePrompts 是响应式的且绑定当前镜头,这里只做sessionStorage持久化即可,
// 因为切换镜头时会重新读取sessionStorage。
// 但为了确保如果用户没切走也能看到,上面已经更新了 currentFramePrompt
- ElMessage.success(`${getFrameTypeLabel(targetFrameType)}提示词提取成功`);
+ ElMessage.success(`${getFrameTypeLabel(targetFrameType)}提示词提取成功`)
} catch (error: any) {
- ElMessage.error("提取失败: " + (error.message || "未知错误"));
+ ElMessage.error('提取失败: ' + (error.message || '未知错误'))
} finally {
// 清除该镜头的生成状态
- const stateKey = `${storyboardId}_${targetFrameType}`;
+ const stateKey = `${storyboardId}_${targetFrameType}`
if (generatingPromptStates.value[stateKey]) {
- generatingPromptStates.value[stateKey] = false;
+ generatingPromptStates.value[stateKey] = false
}
}
-};
+}
// 检查是否正在生成提示词
-const isGeneratingPrompt = (
- storyboardId: number | undefined,
- frameType: string,
-) => {
- if (!storyboardId) return false;
- return !!generatingPromptStates.value[`${storyboardId}_${frameType}`];
-};
+const isGeneratingPrompt = (storyboardId: number | undefined, frameType: string) => {
+ if (!storyboardId) return false
+ return !!generatingPromptStates.value[`${storyboardId}_${frameType}`]
+}
// 获取帧类型的中文标签
const getFrameTypeLabel = (frameType: string): string => {
const labels: Record<string, string> = {
- key: "关键帧",
- first: "首帧",
- last: "尾帧",
- panel: "分镜版",
- };
- return labels[frameType] || frameType;
-};
+ key: '关键帧',
+ first: '首帧',
+ last: '尾帧',
+ panel: '分镜版',
+ }
+ return labels[frameType] || frameType
+}
// 加载分镜的图片列表
-const loadStoryboardImages = async (
- storyboardId: string | number,
- frameType?: string,
-) => {
- loadingImages.value = true;
+const loadStoryboardImages = async (storyboardId: string | number, frameType?: string) => {
+ loadingImages.value = true
try {
const params: any = {
storyboard_id: storyboardId,
page: 1,
page_size: 50,
- };
+ }
// 如果指定了帧类型,添加过滤
if (frameType) {
- params.frame_type = frameType;
+ params.frame_type = frameType
}
- const result = await imageAPI.listImages(params);
- generatedImages.value = result.items || [];
+ const result = await imageAPI.listImages(params)
+ generatedImages.value = result.items || []
// 如果有进行中的任务,启动轮询
const hasPendingOrProcessing = generatedImages.value.some(
- (img) => img.status === "pending" || img.status === "processing",
- );
+ (img) => img.status === 'pending' || img.status === 'processing',
+ )
if (hasPendingOrProcessing) {
- startPolling();
+ startPolling()
}
} catch (error: any) {
- console.error("加载图片列表失败:", error);
+ console.error('加载图片列表失败:', error)
} finally {
- loadingImages.value = false;
+ loadingImages.value = false
}
-};
+}
// 启动状态轮询
const startPolling = () => {
- if (pollingTimer) return;
+ if (pollingTimer) return
// 记录开始轮询时的帧类型
- pollingFrameType = selectedFrameType.value;
+ pollingFrameType = selectedFrameType.value
pollingTimer = setInterval(async () => {
if (!currentStoryboard.value) {
- stopPolling();
- return;
+ stopPolling()
+ return
}
// 如果帧类型已切换,停止轮询(防止更新到错误的帧类型)
if (selectedFrameType.value !== pollingFrameType) {
- stopPolling();
- return;
+ stopPolling()
+ return
}
try {
@@ -3045,381 +2383,376 @@ const startPolling = () => {
storyboard_id: currentStoryboard.value.id,
page: 1,
page_size: 50,
- };
+ }
// 使用轮询开始时记录的帧类型
if (pollingFrameType) {
- params.frame_type = pollingFrameType;
+ params.frame_type = pollingFrameType
}
- const result = await imageAPI.listImages(params);
+ const result = await imageAPI.listImages(params)
// 再次检查帧类型是否仍然匹配,避免竞态条件
if (selectedFrameType.value === pollingFrameType) {
- generatedImages.value = result.items || [];
+ generatedImages.value = result.items || []
}
// 如果没有进行中的任务,停止轮询并刷新视频参考图片
const hasPendingOrProcessing = (result.items || []).some(
- (img: any) => img.status === "pending" || img.status === "processing",
- );
+ (img: any) => img.status === 'pending' || img.status === 'processing',
+ )
if (!hasPendingOrProcessing) {
- stopPolling();
+ stopPolling()
// 刷新视频参考图片列表
if (currentStoryboard.value) {
- loadVideoReferenceImages(currentStoryboard.value.id);
+ loadVideoReferenceImages(currentStoryboard.value.id)
}
}
} catch (error) {
- console.error("轮询图片状态失败:", error);
+ console.error('轮询图片状态失败:', error)
}
- }, 3000); // 每3秒轮询一次
-};
+ }, 3000) // 每3秒轮询一次
+}
// 停止轮询
const stopPolling = () => {
if (pollingTimer) {
- clearInterval(pollingTimer);
- pollingTimer = null;
+ clearInterval(pollingTimer)
+ pollingTimer = null
}
- pollingFrameType = null;
-};
+ pollingFrameType = null
+}
// 生成图片
const generateFrameImage = async () => {
- if (!currentStoryboard.value || !currentFramePrompt.value) return;
+ if (!currentStoryboard.value || !currentFramePrompt.value) return
- generatingImage.value = true;
+ generatingImage.value = true
try {
// 收集参考图片的 local_path
- const referenceImages: string[] = [];
+ const referenceImages: string[] = []
// 1. 添加场景图片(从background字段获取 local_path)
if (currentStoryboard.value.background?.local_path) {
- referenceImages.push(currentStoryboard.value.background.local_path);
+ referenceImages.push(currentStoryboard.value.background.local_path)
}
// 2. 添加当前镜头登场的角色图片(使用 local_path)
- const storyboardCharacters = currentStoryboardCharacters.value;
+ const storyboardCharacters = currentStoryboardCharacters.value
if (storyboardCharacters && storyboardCharacters.length > 0) {
storyboardCharacters.forEach((char: any) => {
if (char.local_path) {
- referenceImages.push(char.local_path);
+ referenceImages.push(char.local_path)
}
- });
+ })
}
const result = await imageAPI.generateImage({
drama_id: dramaId.toString(),
prompt: currentFramePrompt.value,
storyboard_id: currentStoryboard.value.id,
- image_type: "storyboard",
+ image_type: 'storyboard',
frame_type: selectedFrameType.value,
- reference_images:
- referenceImages.length > 0 ? referenceImages : undefined,
- });
+ reference_images: referenceImages.length > 0 ? referenceImages : undefined,
+ })
- generatedImages.value.unshift(result);
+ generatedImages.value.unshift(result)
// 提示信息
- const refMsg =
- referenceImages.length > 0
- ? ` (已添加${referenceImages.length}张参考图)`
- : "";
- ElMessage.success(`图片生成任务已提交${refMsg}`);
+ const refMsg = referenceImages.length > 0 ? ` (已添加${referenceImages.length}张参考图)` : ''
+ ElMessage.success(`图片生成任务已提交${refMsg}`)
// 启动轮询
- startPolling();
+ startPolling()
} catch (error: any) {
- ElMessage.error("生成失败: " + (error.message || "未知错误"));
+ ElMessage.error('生成失败: ' + (error.message || '未知错误'))
} finally {
- generatingImage.value = false;
+ generatingImage.value = false
}
-};
+}
// 获取状态标签类型
const getStatusType = (status: string) => {
const statusMap: Record<string, any> = {
- pending: "info",
- processing: "warning",
- completed: "success",
- failed: "danger",
- };
- return statusMap[status] || "info";
-};
+ pending: 'info',
+ processing: 'warning',
+ completed: 'success',
+ failed: 'danger',
+ }
+ return statusMap[status] || 'info'
+}
// 播放视频
const playVideo = (video: VideoGeneration) => {
- previewVideo.value = video;
- showVideoPreview.value = true;
-};
+ previewVideo.value = video
+ showVideoPreview.value = true
+}
// 添加视频到素材库
const addVideoToAssets = async (video: VideoGeneration) => {
- if (video.status !== "completed" || !video.video_url) {
- ElMessage.warning("只能添加已完成的视频到素材库");
- return;
+ if (video.status !== 'completed' || !video.video_url) {
+ ElMessage.warning('只能添加已完成的视频到素材库')
+ return
}
- addingToAssets.value.add(video.id);
+ addingToAssets.value.add(video.id)
try {
// 检查该镜头是否已存在素材
- let isReplacing = false;
+ let isReplacing = false
if (video.storyboard_id) {
- const existingAsset = videoAssets.value.find(
- (asset: any) => asset.storyboard_id === video.storyboard_id,
- );
+ const existingAsset = videoAssets.value.find((asset: any) => asset.storyboard_id === video.storyboard_id)
if (existingAsset) {
- isReplacing = true;
+ isReplacing = true
// 自动替换:先删除旧素材
try {
- await assetAPI.deleteAsset(existingAsset.id);
+ await assetAPI.deleteAsset(existingAsset.id)
} catch (error) {
- console.error("删除旧素材失败:", error);
+ console.error('删除旧素材失败:', error)
}
}
}
// 添加新素材
- await assetAPI.importFromVideo(video.id);
- ElMessage.success("已添加到素材库");
+ await assetAPI.importFromVideo(video.id)
+ ElMessage.success('已添加到素材库')
// 重新加载素材库列表
- await loadVideoAssets();
+ await loadVideoAssets()
// 如果是替换操作,更新时间线中使用该分镜的所有视频片段
if (isReplacing && video.storyboard_id && video.video_url) {
- console.log("=== 视频替换,准备更新时间线 ===");
- console.log("timelineEditorRef.value:", timelineEditorRef.value);
- console.log("video.storyboard_id:", video.storyboard_id);
- console.log("video.video_url:", video.video_url);
+ console.log('=== 视频替换,准备更新时间线 ===')
+ console.log('timelineEditorRef.value:', timelineEditorRef.value)
+ console.log('video.storyboard_id:', video.storyboard_id)
+ console.log('video.video_url:', video.video_url)
if (timelineEditorRef.value) {
- timelineEditorRef.value.updateClipsByStoryboardId(
- video.storyboard_id,
- video.video_url,
- );
+ timelineEditorRef.value.updateClipsByStoryboardId(video.storyboard_id, video.video_url)
} else {
- console.warn("⚠️ timelineEditorRef.value 为空,无法更新时间线");
+ console.warn('⚠️ timelineEditorRef.value 为空,无法更新时间线')
}
}
} catch (error: any) {
- ElMessage.error(error.message || "添加失败");
+ ElMessage.error(error.message || '添加失败')
} finally {
- addingToAssets.value.delete(video.id);
+ addingToAssets.value.delete(video.id)
}
-};
+}
+
+// 删除视频
+const handleDeleteVideo = async (video: VideoGeneration) => {
+ if (!currentStoryboard.value) return
+
+ try {
+ await ElMessageBox.confirm('确定要删除这个视频吗?删除后无法恢复。', '确认删除', {
+ confirmButtonText: '确定',
+ cancelButtonText: '取消',
+ type: 'warning',
+ })
+
+ await videoAPI.deleteVideo(video.id)
+ ElMessage.success('删除成功')
+
+ // 重新加载当前镜头的视频列表
+ await loadStoryboardVideos(Number(currentStoryboard.value.id))
+ } catch (error: any) {
+ if (error !== 'cancel') {
+ console.error('删除视频失败:', error)
+ ElMessage.error(error.message || '删除失败')
+ }
+ }
+}
// 获取状态中文文本
const getStatusText = (status: string) => {
const statusTextMap: Record<string, string> = {
- pending: "等待中",
- processing: "生成中",
- completed: "已完成",
- failed: "失败",
- };
- return statusTextMap[status] || status;
-};
+ pending: '等待中',
+ processing: '生成中',
+ completed: '已完成',
+ failed: '失败',
+ }
+ return statusTextMap[status] || status
+}
// 获取帧类型中文文本
const getFrameTypeText = (frameType?: string) => {
- if (!frameType) return "";
+ if (!frameType) return ''
const frameTypeMap: Record<string, string> = {
- first: "首帧",
- key: "关键帧",
- last: "尾帧",
- panel: "分镜板",
- action: "动作序列",
- };
- return frameTypeMap[frameType] || frameType;
-};
+ first: '首帧',
+ key: '关键帧',
+ last: '尾帧',
+ panel: '分镜板',
+ action: '动作序列',
+ }
+ return frameTypeMap[frameType] || frameType
+}
// 获取分镜缩略图
const getStoryboardThumbnail = (storyboard: any) => {
// 优先使用composed_image
if (storyboard.composed_image) {
- return storyboard.composed_image;
+ return storyboard.composed_image
}
// 如果没有composed_image,从image_url字段获取
if (storyboard.image_url) {
- return storyboard.image_url;
+ return storyboard.image_url
}
- return null;
-};
+ return null
+}
// 处理图片选择(根据模型能力)
const handleImageSelect = (imageId: number) => {
if (!selectedReferenceMode.value) {
- ElMessage.warning("请先选择参考图模式");
- return;
+ ElMessage.warning('请先选择参考图模式')
+ return
}
if (!currentModelCapability.value) {
- ElMessage.warning("请先选择视频生成模型");
- return;
+ ElMessage.warning('请先选择视频生成模型')
+ return
}
- const capability = currentModelCapability.value;
- const currentIndex = selectedImagesForVideo.value.indexOf(imageId);
+ const capability = currentModelCapability.value
+ const currentIndex = selectedImagesForVideo.value.indexOf(imageId)
// 已选中,则取消选择
if (currentIndex > -1) {
- selectedImagesForVideo.value.splice(currentIndex, 1);
- return;
+ selectedImagesForVideo.value.splice(currentIndex, 1)
+ return
}
// 获取当前点击的图片对象
- const clickedImage = videoReferenceImages.value.find(
- (img) => img.id === imageId,
- );
- if (!clickedImage) return;
+ const clickedImage = videoReferenceImages.value.find((img) => img.id === imageId)
+ if (!clickedImage) return
// 根据选择的参考图模式处理
switch (selectedReferenceMode.value) {
- case "single":
+ case 'single':
// 单图模式:只能选1张,直接替换
- selectedImagesForVideo.value = [imageId];
- break;
+ selectedImagesForVideo.value = [imageId]
+ break
- case "first_last":
+ case 'first_last':
// 首尾帧模式:根据图片类型分别处理
- const frameType = clickedImage.frame_type;
+ const frameType = clickedImage.frame_type
- if (
- frameType === "first" ||
- frameType === "panel" ||
- frameType === "key"
- ) {
+ if (frameType === 'first' || frameType === 'panel' || frameType === 'key') {
// 首帧:直接替换
- selectedImagesForVideo.value = [imageId];
- } else if (frameType === "last") {
+ selectedImagesForVideo.value = [imageId]
+ } else if (frameType === 'last') {
// 尾帧:设置到单独的变量
- selectedLastImageForVideo.value = imageId;
+ selectedLastImageForVideo.value = imageId
} else {
- ElMessage.warning("首尾帧模式下,请选择首帧或尾帧类型的图片");
+ ElMessage.warning('首尾帧模式下,请选择首帧或尾帧类型的图片')
}
- break;
+ break
- case "multiple":
+ case 'multiple':
// 多图模式:检查是否超出最大数量
if (selectedImagesForVideo.value.length >= capability.maxImages) {
- ElMessage.warning(`最多只能选择${capability.maxImages}张图片`);
- return;
+ ElMessage.warning(`最多只能选择${capability.maxImages}张图片`)
+ return
}
- selectedImagesForVideo.value.push(imageId);
- break;
+ selectedImagesForVideo.value.push(imageId)
+ break
default:
- ElMessage.warning("未知的参考图模式");
+ ElMessage.warning('未知的参考图模式')
}
-};
+}
// 预览图片(使用已导入的 getImageUrl 工具函数来获取正确的图片URL)
const previewImage = (url: string) => {
// 使用Element Plus的图片预览
- const viewer = document.createElement("div");
+ const viewer = document.createElement('div')
viewer.innerHTML = `
<div style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 9999; background: rgba(0,0,0,0.8); display: flex; align-items: center; justify-content: center;" onclick="this.remove()">
<img src="${url}" style="max-width: 90vw; max-height: 90vh; object-fit: contain;" onclick="event.stopPropagation();" />
</div>
- `;
- document.body.appendChild(viewer);
-};
+ `
+ document.body.appendChild(viewer)
+}
// 获取已选图片对象列表
const selectedImageObjects = computed(() => {
return selectedImagesForVideo.value
.map((id) => videoReferenceImages.value.find((img) => img.id === id))
- .filter((img) => img && img.image_url);
-});
+ .filter((img) => img && img.image_url)
+})
// 首尾帧模式:获取首帧图片
const firstFrameSlotImage = computed(() => {
- if (selectedImagesForVideo.value.length === 0) return null;
- const firstImageId = selectedImagesForVideo.value[0];
+ if (selectedImagesForVideo.value.length === 0) return null
+ const firstImageId = selectedImagesForVideo.value[0]
// 同时搜索当前镜头图片和上一镜头尾帧
return (
videoReferenceImages.value.find((img) => img.id === firstImageId) ||
previousStoryboardLastFrames.value.find((img) => img.id === firstImageId)
- );
-});
+ )
+})
// 首尾帧模式:获取尾帧图片
const lastFrameSlotImage = computed(() => {
- if (!selectedLastImageForVideo.value) return null;
+ if (!selectedLastImageForVideo.value) return null
// 同时搜索当前镜头图片和上一镜头尾帧
return (
- videoReferenceImages.value.find(
- (img) => img.id === selectedLastImageForVideo.value,
- ) ||
- previousStoryboardLastFrames.value.find(
- (img) => img.id === selectedLastImageForVideo.value,
- )
- );
-});
+ videoReferenceImages.value.find((img) => img.id === selectedLastImageForVideo.value) ||
+ previousStoryboardLastFrames.value.find((img) => img.id === selectedLastImageForVideo.value)
+ )
+})
// 移除已选择的图片
const removeSelectedImage = (imageId: number) => {
// 检查是否是尾帧
if (selectedLastImageForVideo.value === imageId) {
- selectedLastImageForVideo.value = null;
- return;
+ selectedLastImageForVideo.value = null
+ return
}
// 检查是否是首帧或其他图片
- const index = selectedImagesForVideo.value.indexOf(imageId);
+ const index = selectedImagesForVideo.value.indexOf(imageId)
if (index > -1) {
- selectedImagesForVideo.value.splice(index, 1);
+ selectedImagesForVideo.value.splice(index, 1)
}
-};
+}
// 生成视频
const generateVideo = async () => {
if (!selectedVideoModel.value) {
- ElMessage.warning("请先选择视频生成模型");
- return;
+ ElMessage.warning('请先选择视频生成模型')
+ return
}
if (!currentStoryboard.value) {
- ElMessage.warning("请先选择分镜");
- return;
+ ElMessage.warning('请先选择分镜')
+ return
}
// 检查参考图模式
- if (
- selectedReferenceMode.value !== "none" &&
- selectedImagesForVideo.value.length === 0
- ) {
- ElMessage.warning("请选择参考图片");
- return;
+ if (selectedReferenceMode.value !== 'none' && selectedImagesForVideo.value.length === 0) {
+ ElMessage.warning('请选择参考图片')
+ return
}
// 获取第一张选中的图片(仅在需要图片的模式下)
- let selectedImage = null;
- if (
- selectedReferenceMode.value !== "none" &&
- selectedImagesForVideo.value.length > 0
- ) {
+ let selectedImage = null
+ if (selectedReferenceMode.value !== 'none' && selectedImagesForVideo.value.length > 0) {
// 同时搜索当前镜头图片和上一镜头尾帧
selectedImage =
- videoReferenceImages.value.find(
- (img) => img.id === selectedImagesForVideo.value[0],
- ) ||
- previousStoryboardLastFrames.value.find(
- (img) => img.id === selectedImagesForVideo.value[0],
- );
+ videoReferenceImages.value.find((img) => img.id === selectedImagesForVideo.value[0]) ||
+ previousStoryboardLastFrames.value.find((img) => img.id === selectedImagesForVideo.value[0])
if (!selectedImage || !selectedImage.image_url) {
- ElMessage.error("请选择有效的参考图片");
- return;
+ ElMessage.error('请选择有效的参考图片')
+ return
}
}
- generatingVideo.value = true;
+ generatingVideo.value = true
try {
// 从模型名称提取正确的provider
- const provider = extractProviderFromModel(selectedVideoModel.value);
+ const provider = extractProviderFromModel(selectedVideoModel.value)
// 构建请求参数
const requestParams: any = {
@@ -3429,82 +2762,74 @@ const generateVideo = async () => {
currentStoryboard.value.video_prompt ||
currentStoryboard.value.action ||
currentStoryboard.value.description ||
- "",
+ '',
duration: videoDuration.value,
provider: provider,
model: selectedVideoModel.value,
reference_mode: selectedReferenceMode.value,
- };
+ }
// 根据参考图模式设置参数
switch (selectedReferenceMode.value) {
- case "single":
+ case 'single':
// 单图模式 - 优先使用 local_path
if (selectedImage.local_path) {
- requestParams.image_local_path = selectedImage.local_path;
+ requestParams.image_local_path = selectedImage.local_path
} else if (selectedImage.image_url) {
- requestParams.image_url = selectedImage.image_url;
+ requestParams.image_url = selectedImage.image_url
}
- requestParams.image_gen_id = selectedImage.id;
- break;
+ requestParams.image_gen_id = selectedImage.id
+ break
- case "first_last":
+ case 'first_last':
// 首尾帧模式(同时搜索当前镜头图片和上一镜头尾帧)
const firstImage =
- videoReferenceImages.value.find(
- (img) => img.id === selectedImagesForVideo.value[0],
- ) ||
- previousStoryboardLastFrames.value.find(
- (img) => img.id === selectedImagesForVideo.value[0],
- );
+ videoReferenceImages.value.find((img) => img.id === selectedImagesForVideo.value[0]) ||
+ previousStoryboardLastFrames.value.find((img) => img.id === selectedImagesForVideo.value[0])
const lastImage =
- videoReferenceImages.value.find(
- (img) => img.id === selectedLastImageForVideo.value,
- ) ||
- previousStoryboardLastFrames.value.find(
- (img) => img.id === selectedLastImageForVideo.value,
- );
+ videoReferenceImages.value.find((img) => img.id === selectedLastImageForVideo.value) ||
+ previousStoryboardLastFrames.value.find((img) => img.id === selectedLastImageForVideo.value)
// 优先使用 local_path
if (firstImage?.local_path) {
- requestParams.first_frame_local_path = firstImage.local_path;
+ requestParams.first_frame_local_path = firstImage.local_path
} else if (firstImage?.image_url) {
- requestParams.first_frame_url = firstImage.image_url;
+ requestParams.first_frame_url = firstImage.image_url
}
if (lastImage?.local_path) {
- requestParams.last_frame_local_path = lastImage.local_path;
+ requestParams.last_frame_local_path = lastImage.local_path
} else if (lastImage?.image_url) {
- requestParams.last_frame_url = lastImage.image_url;
+ requestParams.last_frame_url = lastImage.image_url
}
- break;
+ break
- case "multiple":
+ case 'multiple':
// 多图模式 - 优先使用 local_path
const selectedImages = selectedImagesForVideo.value
.map((id) => videoReferenceImages.value.find((img) => img.id === id))
.filter((img) => img?.local_path || img?.image_url)
- .map((img) => img!.local_path || img!.image_url);
- requestParams.reference_image_urls = selectedImages;
- break;
+ .map((img) => img!.local_path || img!.image_url)
+ requestParams.reference_image_urls = selectedImages
+ break
- case "none":
+ case 'none':
// 无参考图模式
- break;
+ break
}
- const result = await videoAPI.generateVideo(requestParams);
+ const result = await videoAPI.generateVideo(requestParams)
- generatedVideos.value.unshift(result);
- ElMessage.success("视频生成任务已提交");
+ generatedVideos.value.unshift(result)
+ ElMessage.success('视频生成任务已提交')
// 启动视频轮询
- startVideoPolling();
+ startVideoPolling()
} catch (error: any) {
- ElMessage.error("生成失败: " + (error.message || "未知错误"));
+ ElMessage.error('生成失败: ' + (error.message || '未知错误'))
} finally {
- generatingVideo.value = false;
+ generatingVideo.value = false
}
-};
+}
// 加载分镜的视频参考图片(所有帧类型)
const loadVideoReferenceImages = async (storyboardId: number) => {
@@ -3513,415 +2838,425 @@ const loadVideoReferenceImages = async (storyboardId: number) => {
storyboard_id: storyboardId,
page: 1,
page_size: 100,
- });
- videoReferenceImages.value = result.items || [];
+ })
+ videoReferenceImages.value = result.items || []
} catch (error: any) {
- console.error("加载视频参考图片失败:", error);
+ console.error('加载视频参考图片失败:', error)
}
-};
+}
// 加载分镜的视频列表
const loadStoryboardVideos = async (storyboardId: number) => {
- loadingVideos.value = true;
+ loadingVideos.value = true
try {
const result = await videoAPI.listVideos({
storyboard_id: storyboardId.toString(),
page: 1,
page_size: 50,
- });
- generatedVideos.value = result.items || [];
+ })
+ generatedVideos.value = result.items || []
// 如果有进行中的任务,启动轮询
const hasPendingOrProcessing = generatedVideos.value.some(
- (v) => v.status === "pending" || v.status === "processing",
- );
+ (v) => v.status === 'pending' || v.status === 'processing',
+ )
if (hasPendingOrProcessing) {
- startVideoPolling();
+ startVideoPolling()
}
} catch (error: any) {
- console.error("加载视频列表失败:", error);
+ console.error('加载视频列表失败:', error)
} finally {
- loadingVideos.value = false;
+ loadingVideos.value = false
}
-};
+}
// 启动视频状态轮询
const startVideoPolling = () => {
- if (videoPollingTimer) return;
+ if (videoPollingTimer) return
videoPollingTimer = setInterval(async () => {
if (!currentStoryboard.value) {
- stopVideoPolling();
- return;
+ stopVideoPolling()
+ return
}
try {
// 保存旧的视频列表用于对比
- const oldVideos = [...generatedVideos.value];
+ const oldVideos = [...generatedVideos.value]
const result = await videoAPI.listVideos({
storyboard_id: currentStoryboard.value.id.toString(),
page: 1,
page_size: 50,
- });
- generatedVideos.value = result.items || [];
+ })
+ generatedVideos.value = result.items || []
// 检测是否有视频从 processing 变为 completed
const hasNewlyCompleted = generatedVideos.value.some((newVideo) => {
- const oldVideo = oldVideos.find((v) => v.id === newVideo.id);
+ const oldVideo = oldVideos.find((v) => v.id === newVideo.id)
return (
oldVideo &&
- (oldVideo.status === "pending" || oldVideo.status === "processing") &&
- newVideo.status === "completed"
- );
- });
+ (oldVideo.status === 'pending' || oldVideo.status === 'processing') &&
+ newVideo.status === 'completed'
+ )
+ })
// 如果有视频完成,重新加载分镜列表以更新 duration
if (hasNewlyCompleted && episodeId.value) {
try {
- const storyboardsRes = await dramaAPI.getStoryboards(
- episodeId.value.toString(),
- );
- storyboards.value = storyboardsRes?.storyboards || [];
+ const storyboardsRes = await dramaAPI.getStoryboards(episodeId.value.toString())
+ storyboards.value = storyboardsRes?.storyboards || []
} catch (error) {
- console.error("重新加载分镜列表失败:", error);
+ console.error('重新加载分镜列表失败:', error)
}
}
// 如果没有进行中的任务,停止轮询
const hasPendingOrProcessing = generatedVideos.value.some(
- (v) => v.status === "pending" || v.status === "processing",
- );
+ (v) => v.status === 'pending' || v.status === 'processing',
+ )
if (!hasPendingOrProcessing) {
- stopVideoPolling();
+ stopVideoPolling()
}
} catch (error) {
- console.error("轮询视频状态失败:", error);
+ console.error('轮询视频状态失败:', error)
}
- }, 5000); // 每5秒轮询一次
-};
+ }, 5000) // 每5秒轮询一次
+}
// 停止视频轮询
const stopVideoPolling = () => {
if (videoPollingTimer) {
- clearInterval(videoPollingTimer);
- videoPollingTimer = null;
+ clearInterval(videoPollingTimer)
+ videoPollingTimer = null
}
-};
+}
const toggleCharacterInShot = async (charId: number) => {
- if (!currentStoryboard.value) return;
+ if (!currentStoryboard.value) return
// 初始化characters数组
if (!currentStoryboard.value.characters) {
- currentStoryboard.value.characters = [];
+ currentStoryboard.value.characters = []
}
- const char = characters.value.find((c) => c.id === charId);
- if (!char) return;
+ const char = characters.value.find((c) => c.id === charId)
+ if (!char) return
// 检查是否已存在
const existIndex = currentStoryboard.value.characters.findIndex((c) =>
- typeof c === "object" ? c.id === charId : c === charId,
- );
+ typeof c === 'object' ? c.id === charId : c === charId,
+ )
if (existIndex > -1) {
// 移除角色
- currentStoryboard.value.characters.splice(existIndex, 1);
+ currentStoryboard.value.characters.splice(existIndex, 1)
} else {
// 添加角色(作为对象)
- currentStoryboard.value.characters.push(char);
+ currentStoryboard.value.characters.push(char)
}
// 保存到后端
try {
- const characterIds = currentStoryboard.value.characters.map((c) =>
- typeof c === "object" ? c.id : c,
- );
+ const characterIds = currentStoryboard.value.characters.map((c) => (typeof c === 'object' ? c.id : c))
await dramaAPI.updateStoryboard(currentStoryboard.value.id.toString(), {
character_ids: characterIds,
- });
+ })
if (existIndex > -1) {
- ElMessage.success(`已移除角色: ${char.name}`);
+ ElMessage.success(`已移除角色: ${char.name}`)
} else {
- ElMessage.success(`已添加角色: ${char.name}`);
+ ElMessage.success(`已添加角色: ${char.name}`)
}
} catch (error: any) {
- ElMessage.error("保存失败: " + (error.message || "未知错误"));
+ ElMessage.error('保存失败: ' + (error.message || '未知错误'))
// 回滚操作
if (existIndex > -1) {
- currentStoryboard.value.characters.push(char);
+ currentStoryboard.value.characters.push(char)
} else {
- currentStoryboard.value.characters.splice(
- currentStoryboard.value.characters.length - 1,
- 1,
- );
+ currentStoryboard.value.characters.splice(currentStoryboard.value.characters.length - 1, 1)
}
}
-};
+}
const removeCharacterFromShot = async (charId: number) => {
- if (!currentStoryboard.value) return;
+ if (!currentStoryboard.value) return
// 初始化characters数组
if (!currentStoryboard.value.characters) {
- currentStoryboard.value.characters = [];
+ currentStoryboard.value.characters = []
}
- const char = characters.value.find((c) => c.id === charId);
- if (!char) return;
+ const char = characters.value.find((c) => c.id === charId)
+ if (!char) return
// 检查是否已存在
const existIndex = currentStoryboard.value.characters.findIndex((c) =>
- typeof c === "object" ? c.id === charId : c === charId,
- );
+ typeof c === 'object' ? c.id === charId : c === charId,
+ )
if (existIndex > -1) {
// 移除角色
- currentStoryboard.value.characters.splice(existIndex, 1);
+ currentStoryboard.value.characters.splice(existIndex, 1)
}
// 保存到后端
try {
- const characterIds = currentStoryboard.value.characters.map((c) =>
- typeof c === "object" ? c.id : c,
- );
+ const characterIds = currentStoryboard.value.characters.map((c) => (typeof c === 'object' ? c.id : c))
await dramaAPI.updateStoryboard(currentStoryboard.value.id.toString(), {
character_ids: characterIds,
- });
+ })
- ElMessage.success(`已移除角色: ${char.name}`);
+ ElMessage.success(`已移除角色: ${char.name}`)
} catch (error: any) {
- ElMessage.error("保存失败: " + (error.message || "未知错误"));
+ ElMessage.error('保存失败: ' + (error.message || '未知错误'))
// 回滚操作
- currentStoryboard.value.characters.push(char);
+ currentStoryboard.value.characters.push(char)
}
-};
+}
const loadData = async () => {
try {
// 加载剧集信息
- const dramaRes = await dramaAPI.get(dramaId.toString());
- drama.value = dramaRes;
+ const dramaRes = await dramaAPI.get(dramaId.toString())
+ drama.value = dramaRes
// 找到当前章节
- const ep = dramaRes.episodes?.find(
- (e) => e.episode_number === episodeNumber,
- );
+ const ep = dramaRes.episodes?.find((e) => e.episode_number === episodeNumber)
if (!ep) {
- ElMessage.error("章节不存在");
- router.back();
- return;
+ ElMessage.error('章节不存在')
+ router.back()
+ return
}
- episode.value = ep;
- episodeId.value = ep.id;
+ episode.value = ep
+ episodeId.value = ep.id
// 加载分镜列表
- const storyboardsRes = await dramaAPI.getStoryboards(ep.id.toString());
+ const storyboardsRes = await dramaAPI.getStoryboards(ep.id.toString())
// API返回格式: {storyboards: [...], total: number}
- storyboards.value = storyboardsRes?.storyboards || [];
+ storyboards.value = storyboardsRes?.storyboards || []
// 默认选中第一个分镜
if (storyboards.value.length > 0 && !currentStoryboardId.value) {
- currentStoryboardId.value = storyboards.value[0].id;
+ currentStoryboardId.value = storyboards.value[0].id
}
// 加载角色列表
- characters.value = dramaRes.characters || [];
+ characters.value = dramaRes.characters || []
// 加载可用场景列表
- availableScenes.value = dramaRes.scenes || [];
+ availableScenes.value = dramaRes.scenes || []
// 加载道具列表
- props.value = dramaRes.props || [];
+ props.value = dramaRes.props || []
// 加载视频素材库
- await loadVideoAssets();
+ await loadVideoAssets()
} catch (error: any) {
- ElMessage.error("加载数据失败: " + (error.message || "未知错误"));
+ ElMessage.error('加载数据失败: ' + (error.message || '未知错误'))
}
-};
+}
const selectScene = async (sceneId: number) => {
- if (!currentStoryboard.value) return;
+ if (!currentStoryboard.value) return
try {
// TODO: 调用API更新分镜的scene_id
await dramaAPI.updateStoryboard(currentStoryboard.value.id.toString(), {
scene_id: sceneId,
- });
+ })
// 重新加载数据
- await loadData();
- showSceneSelector.value = false;
- ElMessage.success("场景关联成功");
+ await loadData()
+ showSceneSelector.value = false
+ ElMessage.success('场景关联成功')
} catch (error: any) {
- ElMessage.error(error.message || "场景关联失败");
+ ElMessage.error(error.message || '场景关联失败')
}
-};
+}
const selectStoryboard = (id: string) => {
- currentStoryboardId.value = id;
-};
+ currentStoryboardId.value = id
+}
const handleTimelineSelect = (sceneId: number) => {
- selectStoryboard(String(sceneId));
-};
+ selectStoryboard(String(sceneId))
+}
const togglePlay = () => {
- if (currentPlayState.value === "playing") {
- currentPlayState.value = "paused";
+ if (currentPlayState.value === 'playing') {
+ currentPlayState.value = 'paused'
} else {
- currentPlayState.value = "playing";
+ currentPlayState.value = 'playing'
}
-};
+}
const formatTime = (seconds: number) => {
- const mins = Math.floor(seconds / 60);
- const secs = Math.floor(seconds % 60);
- return `${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
-};
+ const mins = Math.floor(seconds / 60)
+ const secs = Math.floor(seconds % 60)
+ return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
+}
const zoomIn = () => {
- ElMessage.info("时间线缩放功能开发中");
-};
+ ElMessage.info('时间线缩放功能开发中')
+}
const zoomOut = () => {
- ElMessage.info("时间线缩放功能开发中");
-};
+ ElMessage.info('时间线缩放功能开发中')
+}
const generateImage = async () => {
- if (!currentStoryboard.value) return;
+ if (!currentStoryboard.value) return
try {
- ElMessage.info("图片生成功能开发中");
+ ElMessage.info('图片生成功能开发中')
} catch (error: any) {
- ElMessage.error(error.message || "生成失败");
+ ElMessage.error(error.message || '生成失败')
}
-};
+}
const uploadImage = () => {
if (!currentStoryboard.value) {
- ElMessage.warning("请先选择镜头");
- return;
+ ElMessage.warning('请先选择镜头')
+ return
}
// 创建隐藏的文件输入
- const input = document.createElement("input");
- input.type = "file";
- input.accept = "image/*";
+ const input = document.createElement('input')
+ input.type = 'file'
+ input.accept = 'image/*'
input.onchange = async (e: Event) => {
- const target = e.target as HTMLInputElement;
- const file = target.files?.[0];
- if (!file) return;
+ const target = e.target as HTMLInputElement
+ const file = target.files?.[0]
+ if (!file) return
// 验证文件大小 (10MB)
if (file.size > 10 * 1024 * 1024) {
- ElMessage.error("图片大小不能超过 10MB");
- return;
+ ElMessage.error('图片大小不能超过 10MB')
+ return
}
try {
// 创建 FormData
- const formData = new FormData();
- formData.append("file", file);
+ const formData = new FormData()
+ formData.append('file', file)
// 上传到服务器
- const response = await fetch("/api/v1/upload/image", {
- method: "POST",
+ const response = await fetch('/api/v1/upload/image', {
+ method: 'POST',
body: formData,
- });
+ })
if (!response.ok) {
- throw new Error("上传失败");
+ throw new Error('上传失败')
}
- const result = await response.json();
- const imageUrl = result.data?.url;
+ const result = await response.json()
+ const imageUrl = result.data?.url
if (imageUrl && currentStoryboard.value) {
// 创建图片生成记录(关联到当前镜头和帧类型)
await imageAPI.uploadImage({
storyboard_id: currentStoryboard.value.id,
drama_id: parseInt(dramaId),
- frame_type: selectedFrameType.value || "first",
+ frame_type: selectedFrameType.value || 'first',
image_url: imageUrl,
- prompt: currentFramePrompt.value || "用户上传图片",
- });
+ prompt: currentFramePrompt.value || '用户上传图片',
+ })
// 刷新图片列表
- await loadStoryboardImages(
- currentStoryboard.value.id,
- selectedFrameType.value,
- );
+ await loadStoryboardImages(currentStoryboard.value.id, selectedFrameType.value)
- ElMessage.success("图片上传成功");
+ ElMessage.success('图片上传成功')
}
} catch (error: any) {
- console.error("上传图片失败:", error);
- ElMessage.error(error.message || "上传失败");
+ console.error('上传图片失败:', error)
+ ElMessage.error(error.message || '上传失败')
+ }
+ }
+ input.click()
+}
+
+// 删除图片
+const handleDeleteImage = async (img: ImageGeneration) => {
+ if (!currentStoryboard.value) return
+
+ try {
+ await ElMessageBox.confirm('确定要删除这张图片吗?', '确认删除', {
+ confirmButtonText: '确定',
+ cancelButtonText: '取消',
+ type: 'warning',
+ })
+
+ await imageAPI.deleteImage(img.id)
+ ElMessage.success('删除成功')
+
+ // 重新加载当前帧类型的图片列表
+ await loadStoryboardImages(currentStoryboard.value.id, selectedFrameType.value)
+ } catch (error: any) {
+ if (error !== 'cancel') {
+ console.error('删除图片失败:', error)
+ ElMessage.error(error.message || '删除失败')
}
- };
- input.click();
-};
+ }
+}
// 加载所有已生成的图片(用于宫格编辑器)
const loadAllGeneratedImages = async () => {
- if (!currentStoryboard.value) return;
+ if (!currentStoryboard.value) return
try {
const result = await imageAPI.listImages({
storyboard_id: currentStoryboard.value.id,
page: 1,
page_size: 100,
- });
- allGeneratedImages.value = result.items || [];
+ })
+ allGeneratedImages.value = result.items || []
} catch (error: any) {
- console.error("加载所有图片失败:", error);
+ console.error('加载所有图片失败:', error)
}
-};
+}
// 处理宫格图片创建成功
const handleGridImageSuccess = async () => {
if (currentStoryboard.value) {
// 刷新动作序列图片列表
- await loadStoryboardImages(currentStoryboard.value.id, "action");
+ await loadStoryboardImages(currentStoryboard.value.id, 'action')
// 重新加载所有图片
- await loadAllGeneratedImages();
+ await loadAllGeneratedImages()
}
-};
+}
// 打开裁剪对话框
const openCropDialog = (img: ImageGeneration) => {
- cropImageData.value = img;
- cropImageUrl.value = getImageUrl(img) || "";
- showCropDialog.value = true;
-};
+ cropImageData.value = img
+ cropImageUrl.value = getImageUrl(img) || ''
+ showCropDialog.value = true
+}
// 处理裁剪保存
const handleCropSave = async (images: { blob: Blob; frameType: string }[]) => {
- if (!currentStoryboard.value || !cropImageData.value) return;
+ if (!currentStoryboard.value || !cropImageData.value) return
try {
// 将 Blob 转换为 base64 data URL
const convertBlobToBase64 = (blob: Blob): Promise<string> => {
return new Promise((resolve, reject) => {
- const reader = new FileReader();
- reader.onloadend = () => resolve(reader.result as string);
- reader.onerror = reject;
- reader.readAsDataURL(blob);
- });
- };
+ const reader = new FileReader()
+ reader.onloadend = () => resolve(reader.result as string)
+ reader.onerror = reject
+ reader.readAsDataURL(blob)
+ })
+ }
// 上传裁剪后的图片并创建新的图片生成记录
for (const img of images) {
// 将 Blob 转换为 base64
- const imageUrl = await convertBlobToBase64(img.blob);
+ const imageUrl = await convertBlobToBase64(img.blob)
// 调用上传接口
await imageAPI.uploadImage({
@@ -3929,138 +3264,128 @@ const handleCropSave = async (images: { blob: Blob; frameType: string }[]) => {
drama_id: Number(dramaId),
frame_type: img.frameType,
image_url: imageUrl,
- prompt: cropImageData.value.prompt || "",
- });
+ prompt: cropImageData.value.prompt || '',
+ })
}
- ElMessage.success("裁剪图片保存成功");
+ ElMessage.success('裁剪图片保存成功')
// 刷新图片列表 - 刷新所有帧类型的图片,确保新裁剪的图片能在视频生成tab中被选择到
if (currentStoryboard.value) {
// 刷新当前镜头的所有图片(不限制帧类型)
- await loadStoryboardImages(currentStoryboard.value.id);
+ await loadStoryboardImages(currentStoryboard.value.id)
// 刷新所有生成的图片列表
- await loadAllGeneratedImages();
+ await loadAllGeneratedImages()
}
} catch (error) {
- console.error("Failed to save cropped images:", error);
- ElMessage.error("保存裁剪图片失败");
+ console.error('Failed to save cropped images:', error)
+ ElMessage.error('保存裁剪图片失败')
}
-};
+}
const goBack = () => {
router.replace({
- name: "EpisodeWorkflowNew",
+ name: 'EpisodeWorkflowNew',
params: { id: dramaId, episodeNumber },
- });
-};
+ })
+}
const handleAddStoryboard = async () => {
- if (!episodeId.value) return;
+ if (!episodeId.value) return
try {
const nextShotNumber =
- storyboards.value.length > 0
- ? Math.max(...storyboards.value.map((s) => s.storyboard_number)) + 1
- : 1;
+ storyboards.value.length > 0 ? Math.max(...storyboards.value.map((s) => s.storyboard_number)) + 1 : 1
await dramaAPI.createStoryboard({
episode_id: parseInt(episodeId.value),
storyboard_number: nextShotNumber,
title: `镜头 ${nextShotNumber}`,
- description: "新镜头描述",
- action: "动作描述",
- dialogue: "",
+ description: '新镜头描述',
+ action: '动作描述',
+ dialogue: '',
duration: 5,
- scene_id:
- storyboards.value.length > 0
- ? storyboards.value[storyboards.value.length - 1].scene_id
- : undefined,
- });
+ scene_id: storyboards.value.length > 0 ? storyboards.value[storyboards.value.length - 1].scene_id : undefined,
+ })
- ElMessage.success("添加分镜成功");
- await loadData(); // Refresh list
+ ElMessage.success('添加分镜成功')
+ await loadData() // Refresh list
// Select the new storyboard (the last one)
if (storyboards.value.length > 0) {
- selectStoryboard(storyboards.value[storyboards.value.length - 1].id);
+ selectStoryboard(storyboards.value[storyboards.value.length - 1].id)
}
} catch (error: any) {
- console.error("添加分镜失败:", error);
- ElMessage.error(error.message || "添加分镜失败");
+ console.error('添加分镜失败:', error)
+ ElMessage.error(error.message || '添加分镜失败')
}
-};
+}
const handleDeleteStoryboard = async (storyboard: any) => {
try {
- await ElMessageBox.confirm(
- `确定要删除镜头 ${storyboard.storyboard_number} 吗?此操作不可恢复。`,
- "删除确认",
- {
- confirmButtonText: "确定",
- cancelButtonText: "取消",
- type: "warning",
- },
- );
-
- await dramaAPI.deleteStoryboard(storyboard.id);
- ElMessage.success("删除分镜成功");
+ await ElMessageBox.confirm(`确定要删除镜头 ${storyboard.storyboard_number} 吗?此操作不可恢复。`, '删除确认', {
+ confirmButtonText: '确定',
+ cancelButtonText: '取消',
+ type: 'warning',
+ })
+
+ await dramaAPI.deleteStoryboard(storyboard.id)
+ ElMessage.success('删除分镜成功')
// If deleted current storyboard, clear selection or select another
if (currentStoryboardId.value === storyboard.id) {
- currentStoryboardId.value = undefined;
- currentStoryboard.value = undefined;
+ currentStoryboardId.value = undefined
+ currentStoryboard.value = undefined
}
- await loadData();
+ await loadData()
} catch (error: any) {
- if (error !== "cancel") {
- console.error("删除分镜失败:", error);
- ElMessage.error(error.message || "删除分镜失败");
+ if (error !== 'cancel') {
+ console.error('删除分镜失败:', error)
+ ElMessage.error(error.message || '删除分镜失败')
}
}
-};
+}
// 加载视频合成列表
const loadVideoMerges = async () => {
- if (!episodeId.value) return;
+ if (!episodeId.value) return
try {
- loadingMerges.value = true;
+ loadingMerges.value = true
const result = await videoMergeAPI.listMerges({
episode_id: episodeId.value.toString(),
page: 1,
page_size: 20,
- });
- videoMerges.value = result.merges;
+ })
+ videoMerges.value = result.merges
// 检查是否有进行中的任务
const hasProcessingTasks = result.merges.some(
- (merge: any) =>
- merge.status === "pending" || merge.status === "processing",
- );
+ (merge: any) => merge.status === 'pending' || merge.status === 'processing',
+ )
if (hasProcessingTasks) {
- startMergePolling();
+ startMergePolling()
} else {
- stopMergePolling();
+ stopMergePolling()
}
} catch (error: any) {
- console.error("加载视频合成列表失败:", error);
- ElMessage.error("加载视频合成列表失败");
+ console.error('加载视频合成列表失败:', error)
+ ElMessage.error('加载视频合成列表失败')
} finally {
- loadingMerges.value = false;
+ loadingMerges.value = false
}
-};
+}
// 启动视频合成列表轮询
const startMergePolling = () => {
- if (mergePollingTimer) return;
+ if (mergePollingTimer) return
mergePollingTimer = setInterval(async () => {
if (!episodeId.value) {
- stopMergePolling();
- return;
+ stopMergePolling()
+ return
}
try {
@@ -4068,146 +3393,141 @@ const startMergePolling = () => {
episode_id: episodeId.value.toString(),
page: 1,
page_size: 20,
- });
- videoMerges.value = result.merges;
+ })
+ videoMerges.value = result.merges
// 检查是否还有进行中的任务
const hasProcessingTasks = result.merges.some(
- (merge: any) =>
- merge.status === "pending" || merge.status === "processing",
- );
+ (merge: any) => merge.status === 'pending' || merge.status === 'processing',
+ )
if (!hasProcessingTasks) {
- stopMergePolling();
+ stopMergePolling()
}
} catch (error) {}
- }, 3000); // 每3秒轮询一次
-};
+ }, 3000) // 每3秒轮询一次
+}
// 停止视频合成列表轮询
const stopMergePolling = () => {
if (mergePollingTimer) {
- clearInterval(mergePollingTimer);
- mergePollingTimer = null;
+ clearInterval(mergePollingTimer)
+ mergePollingTimer = null
}
-};
+}
// 处理视频合成完成事件
const handleMergeCompleted = async (mergeId: number) => {
// 刷新视频合成列表
- await loadVideoMerges();
+ await loadVideoMerges()
// 切换到视频合成标签页
- activeTab.value = "merges";
-};
+ activeTab.value = 'merges'
+}
// 下载视频
const downloadVideo = async (url: string, title: string) => {
try {
const loadingMsg = ElMessage.info({
- message: "正在准备下载...",
+ message: '正在准备下载...',
duration: 0,
- });
+ })
// 处理相对路径,添加 /static/ 前缀
- const videoUrl = url.startsWith("http") ? url : `/static/${url}`;
+ const videoUrl = url.startsWith('http') ? url : `/static/${url}`
// 使用fetch获取视频blob
- const response = await fetch(videoUrl);
+ const response = await fetch(videoUrl)
if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`);
+ throw new Error(`HTTP error! status: ${response.status}`)
}
- const blob = await response.blob();
- const blobUrl = window.URL.createObjectURL(blob);
+ const blob = await response.blob()
+ const blobUrl = window.URL.createObjectURL(blob)
// 创建下载链接
- const link = document.createElement("a");
- link.href = blobUrl;
- link.download = `${title}.mp4`;
- link.style.display = "none";
- document.body.appendChild(link);
- link.click();
+ const link = document.createElement('a')
+ link.href = blobUrl
+ link.download = `${title}.mp4`
+ link.style.display = 'none'
+ document.body.appendChild(link)
+ link.click()
// 清理
setTimeout(() => {
- document.body.removeChild(link);
- window.URL.revokeObjectURL(blobUrl);
- }, 100);
+ document.body.removeChild(link)
+ window.URL.revokeObjectURL(blobUrl)
+ }, 100)
- loadingMsg.close();
- ElMessage.success("视频下载已开始");
+ loadingMsg.close()
+ ElMessage.success('视频下载已开始')
} catch (error) {
- console.error("下载视频失败:", error);
- ElMessage.error("视频下载失败,请稍后重试");
+ console.error('下载视频失败:', error)
+ ElMessage.error('视频下载失败,请稍后重试')
}
-};
+}
// 预览合成视频
const previewMergedVideo = (url: string) => {
// 处理相对路径,添加 /static/ 前缀
- const videoUrl = url.startsWith("http") ? url : `/static/${url}`;
- window.open(videoUrl, "_blank");
-};
+ const videoUrl = url.startsWith('http') ? url : `/static/${url}`
+ window.open(videoUrl, '_blank')
+}
// 删除视频合成记录
const deleteMerge = async (mergeId: number) => {
try {
- await ElMessageBox.confirm(
- "确定要删除此合成记录吗?此操作不可恢复。",
- "删除确认",
- {
- confirmButtonText: "确定",
- cancelButtonText: "取消",
- type: "warning",
- },
- );
-
- await videoMergeAPI.deleteMerge(mergeId);
- ElMessage.success("删除成功");
+ await ElMessageBox.confirm('确定要删除此合成记录吗?此操作不可恢复。', '删除确认', {
+ confirmButtonText: '确定',
+ cancelButtonText: '取消',
+ type: 'warning',
+ })
+
+ await videoMergeAPI.deleteMerge(mergeId)
+ ElMessage.success('删除成功')
// 刷新列表
- await loadVideoMerges();
+ await loadVideoMerges()
} catch (error: any) {
- if (error !== "cancel") {
- console.error("删除失败:", error);
- ElMessage.error(error.response?.data?.message || "删除失败");
+ if (error !== 'cancel') {
+ console.error('删除失败:', error)
+ ElMessage.error(error.response?.data?.message || '删除失败')
}
}
-};
+}
// 格式化日期时间
const formatDateTime = (dateStr: string) => {
- const date = new Date(dateStr);
- const now = new Date();
- const diff = now.getTime() - date.getTime();
- const minutes = Math.floor(diff / 60000);
- const hours = Math.floor(diff / 3600000);
- const days = Math.floor(diff / 86400000);
-
- if (minutes < 1) return "刚刚";
- if (minutes < 60) return `${minutes}分钟前`;
- if (hours < 24) return `${hours}小时前`;
- if (days < 7) return `${days}天前`;
+ const date = new Date(dateStr)
+ const now = new Date()
+ const diff = now.getTime() - date.getTime()
+ const minutes = Math.floor(diff / 60000)
+ const hours = Math.floor(diff / 3600000)
+ const days = Math.floor(diff / 86400000)
+
+ if (minutes < 1) return '刚刚'
+ if (minutes < 60) return `${minutes}分钟前`
+ if (hours < 24) return `${hours}小时前`
+ if (days < 7) return `${days}天前`
// 超过7天显示完整日期
- const month = String(date.getMonth() + 1).padStart(2, "0");
- const day = String(date.getDate()).padStart(2, "0");
- const hour = String(date.getHours()).padStart(2, "0");
- const minute = String(date.getMinutes()).padStart(2, "0");
- return `${month}-${day} ${hour}:${minute}`;
-};
+ const month = String(date.getMonth() + 1).padStart(2, '0')
+ const day = String(date.getDate()).padStart(2, '0')
+ const hour = String(date.getHours()).padStart(2, '0')
+ const minute = String(date.getMinutes()).padStart(2, '0')
+ return `${month}-${day} ${hour}:${minute}`
+}
onMounted(async () => {
- await loadData();
- await loadVideoModels();
- await loadVideoMerges();
-});
+ await loadData()
+ await loadVideoModels()
+ await loadVideoMerges()
+})
// 组件卸载时停止轮询
onBeforeUnmount(() => {
- stopPolling();
- stopVideoPolling();
- stopMergePolling();
-});
+ stopPolling()
+ stopVideoPolling()
+ stopMergePolling()
+})
</script>
<style scoped lang="scss">
@@ -5252,7 +4572,7 @@ onBeforeUnmount(() => {
}
:deep(.el-textarea__inner) {
- font-family: "Monaco", "Menlo", "Consolas", monospace;
+ font-family: 'Monaco', 'Menlo', 'Consolas', monospace;
font-size: 12px;
line-height: 1.6;
}
@@ -5275,14 +4595,10 @@ onBeforeUnmount(() => {
gap: 6px;
&::before {
- content: "";
+ content: '';
width: 3px;
height: 14px;
- background: linear-gradient(
- to bottom,
- var(--accent),
- var(--accent-hover)
- );
+ background: linear-gradient(to bottom, var(--accent), var(--accent-hover));
border-radius: 2px;
}
}
@@ -5292,6 +4608,12 @@ onBeforeUnmount(() => {
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 10px;
+ .image-item-wrapper {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ }
+
.image-item {
position: relative;
border-radius: 8px;
@@ -5301,11 +4623,17 @@ onBeforeUnmount(() => {
transition: all 0.2s ease;
cursor: pointer;
box-shadow: var(--shadow-sm);
+ height: 150px;
&:hover {
transform: translateY(-2px);
box-shadow: var(--shadow-md);
- border-color: var(--accent);
+ // border-color: var(--accent);
+
+ .image-actions {
+ transform: translateY(0);
+ opacity: 0.7;
+ }
}
:deep(.el-image) {
@@ -5313,6 +4641,7 @@ onBeforeUnmount(() => {
aspect-ratio: 16 / 9;
background: var(--bg-secondary);
display: block;
+ height: 100%;
}
.image-placeholder {
@@ -5327,18 +4656,14 @@ onBeforeUnmount(() => {
color: var(--text-muted);
position: relative;
overflow: hidden;
+ height: 100%;
&::before {
- content: "";
+ content: '';
position: absolute;
width: 200%;
height: 200%;
- background: linear-gradient(
- 45deg,
- transparent 30%,
- rgba(255, 255, 255, 0.3) 50%,
- transparent 70%
- );
+ background: linear-gradient(45deg, transparent 30%, rgba(255, 255, 255, 0.3) 50%, transparent 70%);
animation: shimmer 2s infinite;
top: -50%;
left: -50%;
@@ -5359,42 +4684,52 @@ onBeforeUnmount(() => {
}
}
- .image-info {
+ .image-actions {
position: absolute;
bottom: 0;
left: 0;
- right: 0;
- padding: 6px 8px;
- background: linear-gradient(
- to top,
- rgba(0, 0, 0, 0.75),
- rgba(0, 0, 0, 0.2) 70%,
- transparent
- );
+ width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
- gap: 4px;
+ background-color: var(--bg-primary);
+ opacity: 0;
+ padding: 0 8px;
+ height: 32px;
+ transform: translateY(100%);
+ transition:
+ transform 0.3s ease,
+ opacity 0.2s ease;
+
+ .crop-icon-overlay,
+ .delete-icon-overlay {
+ width: 28px;
+ height: 28px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ cursor: pointer;
+ border-radius: 4px;
+ transition: all 0.2s ease;
- :deep(.el-tag) {
- backdrop-filter: blur(8px);
- font-size: 10px;
- height: 20px;
- padding: 0 6px;
+ &:hover {
+ background: var(--bg-secondary);
+ transform: scale(1.1);
+ }
}
+ }
+ }
- .frame-type-tag {
- padding: 2px 6px;
- border-radius: 4px;
- font-size: 10px;
- font-weight: 500;
- background: rgba(255, 255, 255, 0.25);
- color: white;
- backdrop-filter: blur(8px);
- border: 1px solid rgba(255, 255, 255, 0.3);
- text-transform: uppercase;
- letter-spacing: 0.3px;
- }
+ .image-status {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ padding: 2px 0;
+
+ :deep(.el-tag) {
+ font-size: 10px;
+ height: 20px;
+ padding: 0 6px;
}
}
}
@@ -5473,12 +4808,17 @@ onBeforeUnmount(() => {
border: 1px solid #e8e8e8;
transition: all 0.2s ease;
cursor: pointer;
+ height: 150px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
&:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
- border-color: #409eff;
+
+ .video-actions {
+ transform: translateY(0);
+ opacity: 0.7;
+ }
}
.image-placeholder {
@@ -5493,18 +4833,14 @@ onBeforeUnmount(() => {
color: #909399;
position: relative;
overflow: hidden;
+ height: 100%;
&::before {
- content: "";
+ content: '';
position: absolute;
width: 200%;
height: 200%;
- background: linear-gradient(
- 45deg,
- transparent 30%,
- rgba(255, 255, 255, 0.3) 50%,
- transparent 70%
- );
+ background: linear-gradient(45deg, transparent 30%, rgba(255, 255, 255, 0.3) 50%, transparent 70%);
animation: shimmer 2s infinite;
top: -50%;
left: -50%;
@@ -5531,12 +4867,7 @@ onBeforeUnmount(() => {
left: 0;
right: 0;
padding: 6px 8px;
- background: linear-gradient(
- to top,
- rgba(0, 0, 0, 0.75),
- rgba(0, 0, 0, 0.2) 70%,
- transparent
- );
+ background: linear-gradient(to top, rgba(0, 0, 0, 0.75), rgba(0, 0, 0, 0.2) 70%, transparent);
display: flex;
justify-content: space-between;
align-items: center;
@@ -5567,7 +4898,7 @@ onBeforeUnmount(() => {
&.video-item .video-thumbnail {
position: relative;
width: 100%;
- aspect-ratio: 16 / 9;
+ height: 100%;
overflow: hidden;
cursor: pointer;
@@ -5601,6 +4932,45 @@ onBeforeUnmount(() => {
opacity: 1;
}
}
+
+ .video-actions {
+ position: absolute;
+ bottom: 0;
+ left: 0;
+ width: 100%;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ background-color: var(--bg-primary);
+ opacity: 0;
+ padding: 0 8px;
+ height: 32px;
+ transform: translateY(100%);
+ transition:
+ transform 0.3s ease,
+ opacity 0.2s ease;
+
+ .add-to-assets-button,
+ .delete-video-button {
+ width: 28px;
+ height: 28px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ cursor: pointer;
+ border-radius: 4px;
+ transition: all 0.2s ease;
+
+ &:hover {
+ background: var(--bg-secondary);
+ transform: scale(1.1);
+ }
+
+ .is-loading {
+ animation: rotate 1s linear infinite;
+ }
+ }
+ }
}
}
}
@@ -6120,7 +5490,7 @@ onBeforeUnmount(() => {
position: relative;
}
-.crop-icon-overlay {
+/* .crop-icon-overlay {
position: absolute;
top: 4px;
right: 4px;
@@ -6135,14 +5505,41 @@ onBeforeUnmount(() => {
opacity: 0;
transition: all 0.3s ease;
z-index: 10;
-}
+} */
.action-image-item:hover .crop-icon-overlay {
opacity: 1;
}
.crop-icon-overlay:hover {
- background: var(--accent);
+ /* background: var(--accent); */
+ transform: scale(1.1);
+}
+
+/* 删除按钮样式 */
+/* .delete-icon-overlay {
+ position: absolute;
+ bottom: 4px;
+ left: 4px;
+ width: 28px;
+ height: 28px;
+ background: rgba(220, 38, 38, 0.9);
+ border-radius: 50%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ cursor: pointer;
+ opacity: 0;
+ transition: all 0.3s ease;
+ z-index: 10;
+} */
+
+.image-item:hover .delete-icon-overlay {
+ opacity: 1;
+}
+
+.delete-icon-overlay:hover {
+ /* background: rgba(220, 38, 38, 1); */
transform: scale(1.1);
}