Skip to content

Formerly KrillinAI, VideoTranslation and Dubbing Tool for 120+ Languages. Open-source AI workspace for creators, powered by Codex. Video downloader, video translation, create videos, images, audios, and edits with Agents in one place. For your Social Media like YouTube, TikTok, Instagram, etc.

feat(creator): improve video translation preview and download layout

米饭二两1221ed17e2ca
diff --git a/apps/web/e2e/video-download-layout.spec.ts b/apps/web/e2e/video-download-layout.spec.ts
new file mode 100644
index 00000000..db0e0e5d
--- /dev/null
+++ b/apps/web/e2e/video-download-layout.spec.ts
@@ -0,0 +1,46 @@
+import type { CreatorJob } from '@opencreator/protocol';
+import { expect, test } from './fixtures/runtime.js';
+
+test('video download platforms stay centered and wrap within translation-sized settings', async ({ page, runtime }) => {
+ const { job } = await runtime.api<{ job: CreatorJob }>('POST', '/creator/jobs', {
+ projectId: runtime.projectId,
+ templateId: 'video-download',
+ creationKey: 'video-download-layout'
+ });
+
+ await runtime.openApp(page);
+ await page.goto(`${runtime.origin}/#/workbench?tool=video-download&jobId=${encodeURIComponent(job.id)}`);
+
+ const stack = page.locator('.video-download-workspace-page .creator-tool-stack');
+ const platforms = page.getByRole('list', { name: '支持的平台' });
+ const items = platforms.locator('li');
+ await expect(items).toHaveCount(9);
+
+ await page.setViewportSize({ width: 1920, height: 1000 });
+ const wide = await platforms.evaluate(element => {
+ const list = element.getBoundingClientRect();
+ const itemBoxes = [...element.querySelectorAll('li')].map(item => item.getBoundingClientRect());
+ return {
+ listCenter: list.x + list.width / 2,
+ itemsCenter: (itemBoxes[0]!.left + itemBoxes.at(-1)!.right) / 2,
+ rowTops: [...new Set(itemBoxes.map(box => Math.round(box.top)))],
+ loadedIcons: [...element.querySelectorAll<HTMLImageElement>('img')].every(image => image.naturalWidth > 0)
+ };
+ });
+ expect(await stack.evaluate(element => element.getBoundingClientRect().width)).toBeCloseTo(960, 0);
+ expect(wide.rowTops).toHaveLength(1);
+ expect(Math.abs(wide.itemsCenter - wide.listCenter)).toBeLessThan(2);
+ expect(wide.loadedIcons).toBe(true);
+
+ await page.setViewportSize({ width: 1000, height: 800 });
+ const narrow = await platforms.evaluate(element => {
+ const list = element.getBoundingClientRect();
+ const itemBoxes = [...element.querySelectorAll('li')].map(item => item.getBoundingClientRect());
+ return {
+ rowTops: [...new Set(itemBoxes.map(box => Math.round(box.top)))],
+ withinBounds: itemBoxes.every(box => box.left >= list.left && box.right <= list.right)
+ };
+ });
+ expect(narrow.rowTops.length).toBeGreaterThan(1);
+ expect(narrow.withinBounds).toBe(true);
+});
diff --git a/apps/web/e2e/video-translation-style-preview.spec.ts b/apps/web/e2e/video-translation-style-preview.spec.ts
new file mode 100644
index 00000000..a00b2c1b
--- /dev/null
+++ b/apps/web/e2e/video-translation-style-preview.spec.ts
@@ -0,0 +1,78 @@
+import type { CreatorJob } from '@opencreator/protocol';
+import { expect, test } from './fixtures/runtime.js';
+
+const poster = Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/B2kAAAAASUVORK5CYII=',
+ 'base64'
+);
+
+test('字幕样式预览显示视频封面并按源比例或竖屏输出比例排版', async ({ page, runtime }) => {
+ await page.route('**/video-metadata?*', route => route.fulfill({
+ json: {
+ platform: 'bilibili',
+ title: '4:3 source',
+ thumbnailUrl: 'https://images.example.test/source.png',
+ width: 1024,
+ height: 768
+ }
+ }));
+ await page.route('https://images.example.test/source.png', route => route.fulfill({
+ body: poster,
+ contentType: 'image/png'
+ }));
+ const job = await runtime.api<{ job: CreatorJob }>('POST', '/creator/jobs', {
+ projectId: runtime.projectId,
+ templateId: 'video-translation',
+ templateVersion: 1,
+ state: {
+ sourceType: 'url',
+ sourceUrl: 'https://www.bilibili.com/video/BV1abc123',
+ sourceLanguage: 'en',
+ targetLanguage: 'zh_cn',
+ currentStep: 2,
+ furthestStep: 2,
+ workspacePhase: 'configure'
+ },
+ creationKey: 'style-preview-ratio'
+ }).then(response => response.job);
+
+ await runtime.openApp(page);
+ await page.goto(`${runtime.origin}/#/workbench?tool=video-translation&jobId=${encodeURIComponent(job.id)}`);
+ const preview = page.getByRole('region', { name: '字幕样式预览' });
+ const image = preview.locator('img.video-translation-subtitle-preview-media');
+ const frame = preview.locator(':scope > div');
+ const settings = page.locator('.video-translation-wizard-main .video-translation-wizard-body');
+ await expect(preview).toHaveAttribute('data-ratio', '4:3');
+ await expect(image).toBeVisible();
+ await expect.poll(() => image.evaluate(element => (element as HTMLImageElement).naturalWidth)).toBeGreaterThan(0);
+ await page.setViewportSize({ width: 1920, height: 1000 });
+ await expect.poll(() => settings.evaluate(element => element.getBoundingClientRect().width)).toBeGreaterThan(720);
+ expect(await frame.evaluate(element => {
+ const overlay = getComputedStyle(element, '::after');
+ const cues = element.querySelector('.video-translation-subtitle-preview-cues');
+ return {
+ background: overlay.backgroundColor,
+ overlayLayer: overlay.zIndex,
+ cueLayer: cues === null ? '' : getComputedStyle(cues).zIndex
+ };
+ })).toEqual({ background: 'rgba(0, 0, 0, 0.55)', overlayLayer: '1', cueLayer: '2' });
+ const sourceBox = await frame.boundingBox();
+ expect(sourceBox).not.toBeNull();
+ expect(sourceBox!.width / sourceBox!.height).toBeCloseTo(4 / 3, 1);
+
+ await page.setViewportSize({ width: 1100, height: 800 });
+ expect(await settings.evaluate(element => {
+ const container = element.closest('.video-translation-wizard-main');
+ return container !== null && element.getBoundingClientRect().width <= container.getBoundingClientRect().width;
+ })).toBe(true);
+
+ await page.getByRole('button', { name: '继续' }).click();
+ await page.getByRole('switch', { name: '合成字幕视频' }).click();
+ await page.getByRole('radio', { name: /9:16/ }).click();
+ await page.getByRole('navigation', { name: '翻译流程' }).getByRole('button', { name: /字幕样式$/ }).click();
+ await expect(preview).toHaveAttribute('data-ratio', '9:16');
+ await expect(preview).toHaveAttribute('data-converted', 'true');
+ const verticalBox = await frame.boundingBox();
+ expect(verticalBox).not.toBeNull();
+ expect(verticalBox!.width / verticalBox!.height).toBeCloseTo(9 / 16, 1);
+});
diff --git a/apps/web/src/app/AppController.tsx b/apps/web/src/app/AppController.tsx
index 645181d8..fdf45b41 100644
--- a/apps/web/src/app/AppController.tsx
+++ b/apps/web/src/app/AppController.tsx
@@ -4575,6 +4575,7 @@ export function AppController(props: AppControllerProps) {
creatorService={creatorService}
runtimeDependencies={runtimeDependencies}
creatorServicesService={creatorServicesService}
+ videoMetadataService={videoMetadataService}
workspace={props.route.view === 'workbench' ? props.route.tool : undefined}
jobId={props.route.view === 'workbench' ? props.route.jobId : undefined}
onJobCreated={rememberCreatorJob}
diff --git a/apps/web/src/features/dashboard/VideoDownloadWorkspace.test.tsx b/apps/web/src/features/dashboard/VideoDownloadWorkspace.test.tsx
index 41869c59..64f0c3d6 100644
--- a/apps/web/src/features/dashboard/VideoDownloadWorkspace.test.tsx
+++ b/apps/web/src/features/dashboard/VideoDownloadWorkspace.test.tsx
@@ -7,7 +7,7 @@ import type {
CreatorStageRun,
CreatorYtDlpStatus
} from '@opencreator/protocol';
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { LanguageProvider } from '../../i18n/LanguageProvider.js';
import { CreatorSessionProvider } from './creator-session-store.js';
@@ -45,12 +45,17 @@ afterEach(() => {
});
describe('VideoDownloadWorkspace', () => {
- it('shows compact icons for every supported platform', () => {
+ it('shows labeled icons for every supported platform', () => {
renderWorkspace(job(), { applyAction: vi.fn() });
- const platforms = screen.getByLabelText('支持的平台');
- expect(platforms.querySelectorAll('img')).toHaveLength(9);
- for (const name of ['YouTube', 'Bilibili', 'X', 'TikTok', 'Instagram', '抖音', 'Facebook', '小红书', 'Pinterest']) {
- expect(screen.getByAltText(name)).toHaveAttribute('src', expect.stringMatching(/^\/platforms\//));
+ expect(screen.getByText('支持的视频来源(支持单个公开视频链接)')).toBeInTheDocument();
+ expect(screen.getAllByText(/支持单个公开视频链接/)).toHaveLength(1);
+ const platforms = screen.getByRole('list', { name: '支持的平台' });
+ const items = within(platforms).getAllByRole('listitem');
+ expect(items).toHaveLength(9);
+ for (const [index, name] of ['YouTube', 'Bilibili', 'X', 'TikTok', 'Instagram', '抖音', 'Facebook', '小红书', 'Pinterest'].entries()) {
+ const item = items[index]!;
+ expect(item).toHaveTextContent(name);
+ expect(item.querySelector('img')).toHaveAttribute('src', expect.stringMatching(/^\/platforms\//));
}
});
diff --git a/apps/web/src/features/dashboard/VideoDownloadWorkspace.tsx b/apps/web/src/features/dashboard/VideoDownloadWorkspace.tsx
index 282f9d5b..1c4b2543 100644
--- a/apps/web/src/features/dashboard/VideoDownloadWorkspace.tsx
+++ b/apps/web/src/features/dashboard/VideoDownloadWorkspace.tsx
@@ -577,6 +577,7 @@ export default function VideoDownloadWorkspace(props: {
return (
<CreatorToolShell
title={l('视频下载', 'Video Downloader')}
+ pageClassName="video-download-workspace-page"
subtitle={l(
'解析公开链接并把视频或音频保存到项目',
'Analyze a public link and save video or audio to the project'
@@ -692,23 +693,23 @@ export default function VideoDownloadWorkspace(props: {
<h2 id="video-download-source-title">
{l('公开视频链接', 'Public video link')}
</h2>
- <p>
- {l(
- '支持以下平台的单个公开视频',
- 'Supports individual public videos from these platforms'
- )}
- </p>
- <div className="video-download-platforms" aria-label={l('支持的平台', 'Supported platforms')}>
- {([
- ['youtube', 'YouTube'], ['bilibili', 'Bilibili'], ['x', 'X'],
- ['tiktok', 'TikTok'], ['instagram', 'Instagram'], ['douyin', l('抖音', 'Douyin')],
- ['facebook', 'Facebook'], ['xiaohongshu', l('小红书', 'Xiaohongshu')], ['pinterest', 'Pinterest']
- ] as const).map(([platformName, name]) => (
- <img key={platformName} src={`/platforms/${platformName}.png`} alt={name} title={name} width="16" height="16" />
- ))}
- </div>
</div>
</div>
+ <div className="video-download-platform-section">
+ <span>{l('支持的视频来源(支持单个公开视频链接)', 'Supported video sources (one public video link)')}</span>
+ <ul className="video-download-platforms" aria-label={l('支持的平台', 'Supported platforms')}>
+ {([
+ ['youtube', 'YouTube'], ['bilibili', 'Bilibili'], ['x', 'X'],
+ ['tiktok', 'TikTok'], ['instagram', 'Instagram'], ['douyin', l('抖音', 'Douyin')],
+ ['facebook', 'Facebook'], ['xiaohongshu', l('小红书', 'Xiaohongshu')], ['pinterest', 'Pinterest']
+ ] as const).map(([platformName, name]) => (
+ <li key={platformName}>
+ <img src={`/platforms/${platformName}.png`} alt="" width="32" height="32" />
+ <span>{name}</span>
+ </li>
+ ))}
+ </ul>
+ </div>
<label className="creator-tool-url-input">
<Link2 size={17} strokeWidth={1.8} aria-hidden="true" />
<input
diff --git a/apps/web/src/features/dashboard/VideoSourceInput.tsx b/apps/web/src/features/dashboard/VideoSourceInput.tsx
index d4386897..75b23ecc 100644
--- a/apps/web/src/features/dashboard/VideoSourceInput.tsx
+++ b/apps/web/src/features/dashboard/VideoSourceInput.tsx
@@ -1,6 +1,7 @@
import { useRef, useState, type DragEvent } from 'react';
import { Link2, UploadCloud } from 'lucide-react';
import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';
+import type { VideoMetadataResponse } from '@opencreator/protocol';
import type { VideoMetadataService } from '../../services/video-metadata-service.js';
import VideoSourcePreview from './VideoSourcePreview.js';
@@ -16,6 +17,7 @@ export default function VideoSourceInput(props: {
onUrlChange(url: string): void;
onClear(): void;
onDimensions?(width: number, height: number): void;
+ onMetadata?(url: string, metadata: VideoMetadataResponse): void;
}) {
const l = useLocalizedCopy();
const fileInputRef = useRef<HTMLInputElement>(null);
@@ -66,6 +68,7 @@ export default function VideoSourceInput(props: {
onChooseFile={openFilePicker}
onClear={props.onClear}
onDimensions={props.onDimensions}
+ onMetadata={props.onMetadata}
/>
) : (
<>
diff --git a/apps/web/src/features/dashboard/VideoSourcePreview.tsx b/apps/web/src/features/dashboard/VideoSourcePreview.tsx
index e1f151dd..8a8e1433 100644
--- a/apps/web/src/features/dashboard/VideoSourcePreview.tsx
+++ b/apps/web/src/features/dashboard/VideoSourcePreview.tsx
@@ -11,7 +11,7 @@ type VideoSource =
| { kind: 'link'; url: string; hostname: string; label: string }
| { kind: 'invalid'; label: string };
-function parseVideoSource(value: string): VideoSource {
+export function parseVideoSource(value: string): VideoSource {
const trimmed = value.trim();
try {
@@ -123,6 +123,7 @@ export default function VideoSourcePreview(props: {
displayDetail?: string;
metadataService?: VideoMetadataService;
onDimensions?(width: number, height: number): void;
+ onMetadata?(url: string, metadata: VideoMetadataResponse): void;
}) {
const l = useLocalizedCopy();
const [showYouTubePlayer, setShowYouTubePlayer] = useState(false);
@@ -177,6 +178,7 @@ export default function VideoSourcePreview(props: {
void props.metadataService.getVideoMetadata(props.url).then(result => {
if (!active) return;
setMetadata(result);
+ props.onMetadata?.(props.url, result);
if (result.width !== undefined && result.height !== undefined) {
updateMediaDimensions(result.width, result.height);
}
diff --git a/apps/web/src/features/dashboard/VideoTranslationWorkspace.control.test.tsx b/apps/web/src/features/dashboard/VideoTranslationWorkspace.control.test.tsx
index 52c068fa..951143d1 100644
--- a/apps/web/src/features/dashboard/VideoTranslationWorkspace.control.test.tsx
+++ b/apps/web/src/features/dashboard/VideoTranslationWorkspace.control.test.tsx
@@ -89,6 +89,210 @@ describe('VideoTranslationWorkspace task controls', () => {
expect(screen.getByRole('button', { name: '#7EE7FF' })).toHaveAttribute('aria-pressed', 'true');
});
+ it('uses the same preset and custom color controls for original, outline, and shadow', () => {
+ render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job({ status: 'draft', revision: 0, stages: [], state: { currentStep: 2, furthestStep: 2 } })}
+ service={{ applyAction: vi.fn(), runAgentTurn: vi.fn() } as never}
+ >
+ <VideoTranslationWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ for (const label of ['原文颜色', '描边颜色', '阴影颜色']) {
+ const preset = screen.getByRole('button', { name: `${label} #7EE7FF` });
+ fireEvent.click(preset);
+ expect(preset).toHaveAttribute('aria-pressed', 'true');
+ expect(screen.getByLabelText(label)).toHaveValue('#7ee7ff');
+ }
+ expect(screen.getAllByText('自定义')).toHaveLength(4);
+ });
+
+ it('uses the platform poster and actual dimensions when metadata provides them', async () => {
+ const getVideoMetadata = vi.fn(async () => ({
+ platform: 'bilibili' as const,
+ title: '4:3 source',
+ thumbnailUrl: 'https://images.example.test/source.jpg',
+ width: 1024,
+ height: 768
+ }));
+ render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job({
+ status: 'draft', revision: 0, stages: [],
+ state: { currentStep: 2, furthestStep: 2, sourceUrl: 'https://www.bilibili.com/video/BV1abc' }
+ })}
+ service={{ applyAction: vi.fn(), runAgentTurn: vi.fn() } as never}
+ >
+ <VideoTranslationWorkspace onBack={vi.fn()} videoMetadataService={{ getVideoMetadata }} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ const preview = screen.getByRole('region', { name: '字幕样式预览' });
+ await waitFor(() => expect(preview).toHaveAttribute('data-ratio', '4:3'));
+ expect(preview.querySelector('img.video-translation-subtitle-preview-media')).toHaveAttribute(
+ 'src', 'https://images.example.test/source.jpg'
+ );
+ expect(preview.querySelector(':scope > div')).toHaveStyle({ '--subtitle-preview-aspect-ratio': '1024 / 768' });
+ expect(getVideoMetadata).toHaveBeenCalledWith('https://www.bilibili.com/video/BV1abc');
+ });
+
+ it('shows a YouTube Shorts poster in a portrait frame without video metadata', () => {
+ render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job({
+ status: 'draft', revision: 0, stages: [],
+ state: { currentStep: 2, furthestStep: 2, sourceUrl: 'https://www.youtube.com/shorts/portrait123' }
+ })}
+ service={{ applyAction: vi.fn(), runAgentTurn: vi.fn() } as never}
+ >
+ <VideoTranslationWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ const preview = screen.getByRole('region', { name: '字幕样式预览' });
+ expect(preview).toHaveAttribute('data-ratio', '9:16');
+ expect(preview.querySelector('img.video-translation-subtitle-preview-media')).toHaveAttribute(
+ 'src', 'https://i.ytimg.com/vi/portrait123/hqdefault.jpg'
+ );
+ });
+
+ it('seeks a playable source to a still frame and uses its nonstandard aspect ratio', () => {
+ render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job({
+ status: 'draft', revision: 0, stages: [],
+ state: { currentStep: 2, furthestStep: 2, sourceUrl: 'https://video.example.test/source.mp4' }
+ })}
+ service={{ applyAction: vi.fn(), runAgentTurn: vi.fn() } as never}
+ >
+ <VideoTranslationWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ const preview = screen.getByRole('region', { name: '字幕样式预览' });
+ const video = preview.querySelector('video');
+ expect(video).toHaveAttribute('src', 'https://video.example.test/source.mp4');
+ Object.defineProperties(video!, {
+ videoWidth: { configurable: true, value: 1440 },
+ videoHeight: { configurable: true, value: 1080 },
+ duration: { configurable: true, value: 100 }
+ });
+ fireEvent.loadedMetadata(video!);
+ fireEvent.seeked(video!);
+
+ expect(video).toHaveProperty('currentTime', 5);
+ expect(video).toHaveAttribute('data-ready', 'true');
+ expect(preview).toHaveAttribute('data-ratio', '4:3');
+ expect(preview.querySelector(':scope > div')).toHaveStyle({ '--subtitle-preview-aspect-ratio': '1440 / 1080' });
+
+ fireEvent.click(screen.getByRole('button', { name: '继续' }));
+ fireEvent.click(screen.getByRole('switch', { name: '合成字幕视频' }));
+ fireEvent.click(screen.getByRole('radio', { name: /9:16/ }));
+ fireEvent.click(within(screen.getByRole('navigation', { name: '翻译流程' })).getByRole('button', {
+ name: /字幕样式$/
+ }));
+ expect(screen.getByRole('region', { name: '字幕样式预览' })).toHaveAttribute('data-ratio', '9:16');
+ expect(screen.getByRole('region', { name: '字幕样式预览' })).toHaveAttribute('data-converted', 'true');
+ });
+
+ it('uses a local video still and preserves its portrait 3:4 ratio', () => {
+ const createObjectUrlDescriptor = Object.getOwnPropertyDescriptor(URL, 'createObjectURL');
+ const revokeObjectUrlDescriptor = Object.getOwnPropertyDescriptor(URL, 'revokeObjectURL');
+ const createObjectURL = vi.fn()
+ .mockReturnValueOnce('blob:source-video')
+ .mockReturnValueOnce('blob:subtitle-preview');
+ const revokeObjectURL = vi.fn();
+ Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: createObjectURL });
+ Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: revokeObjectURL });
+ let view: ReturnType<typeof render> | undefined;
+
+ try {
+ view = render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job({ status: 'draft', revision: 0, stages: [], state: { currentStep: 0, furthestStep: 0 } })}
+ service={{ applyAction: vi.fn(), runAgentTurn: vi.fn() } as never}
+ >
+ <VideoTranslationWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+ const file = new File(['video'], 'portrait.mp4', { type: 'video/mp4' });
+ fireEvent.change(screen.getByLabelText('上传本地视频'), { target: { files: [file] } });
+ const sourceVideo = screen.getByLabelText('本地视频预览');
+ Object.defineProperties(sourceVideo, {
+ videoWidth: { configurable: true, value: 1080 },
+ videoHeight: { configurable: true, value: 1440 }
+ });
+ fireEvent.loadedMetadata(sourceVideo);
+ fireEvent.click(screen.getByRole('button', { name: '继续' }));
+ fireEvent.click(screen.getByRole('button', { name: '继续' }));
+
+ const preview = screen.getByRole('region', { name: '字幕样式预览' });
+ expect(preview).toHaveAttribute('data-ratio', '3:4');
+ expect(preview.querySelector('video')).toHaveAttribute('src', 'blob:subtitle-preview');
+ expect(createObjectURL).toHaveBeenCalledTimes(2);
+ } finally {
+ view?.unmount();
+ expect(revokeObjectURL).toHaveBeenCalledWith('blob:source-video');
+ expect(revokeObjectURL).toHaveBeenCalledWith('blob:subtitle-preview');
+ restoreUrlMethod('createObjectURL', createObjectUrlDescriptor);
+ restoreUrlMethod('revokeObjectURL', revokeObjectUrlDescriptor);
+ }
+ });
+
+ it('loads the saved source video for a resumed subtitle-style preview', async () => {
+ const createObjectUrlDescriptor = Object.getOwnPropertyDescriptor(URL, 'createObjectURL');
+ const revokeObjectUrlDescriptor = Object.getOwnPropertyDescriptor(URL, 'revokeObjectURL');
+ const createObjectURL = vi.fn(() => 'blob:saved-source');
+ const revokeObjectURL = vi.fn();
+ Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: createObjectURL });
+ Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: revokeObjectURL });
+ const source = sourceVideoArtifact(1);
+ const openArtifact = vi.fn(async () => new Response(new Blob(['video'], { type: 'video/mp4' })));
+ const view = render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job({
+ status: 'draft', revision: 0, stages: [], artifacts: [source],
+ state: {
+ currentStep: 2,
+ furthestStep: 2,
+ sourceType: 'file',
+ sourceUrl: '',
+ sourceFileName: 'saved.mp4',
+ sourceArtifactId: source.id
+ }
+ })}
+ service={{ applyAction: vi.fn(), runAgentTurn: vi.fn(), openArtifact } as never}
+ >
+ <VideoTranslationWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ try {
+ const preview = screen.getByRole('region', { name: '字幕样式预览' });
+ expect(preview).toHaveAttribute('data-ratio', '16:9');
+ await waitFor(() => expect(preview.querySelector('video')).toHaveAttribute('src', 'blob:saved-source'));
+ expect(openArtifact).toHaveBeenCalledWith('job_control', source.id);
+ } finally {
+ view.unmount();
+ expect(revokeObjectURL).toHaveBeenCalledWith('blob:saved-source');
+ restoreUrlMethod('createObjectURL', createObjectUrlDescriptor);
+ restoreUrlMethod('revokeObjectURL', revokeObjectUrlDescriptor);
+ }
+ });
+
it('edits every subtitle style field and persists one structured patch', async () => {
let currentJob = job({
status: 'draft',
diff --git a/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsx b/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsx
index 6daa7f7e..2d1c214e 100644
--- a/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsx
+++ b/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsx
@@ -28,7 +28,7 @@ import VideoTranslationAgentPanel from './VideoTranslationAgentPanel.js';
import CreatorResizableLayout from './CreatorResizableLayout.js';
import CreatorTaskSummary from './CreatorTaskSummary.js';
import VideoSourceInput from './VideoSourceInput.js';
-import VideoSourcePreview from './VideoSourcePreview.js';
+import { parseVideoSource } from './VideoSourcePreview.js';
import { VideoTranslationSubtitleImport } from './VideoTranslationSubtitleImport.js';
import VideoTranslationResultWorkspace, {
type SubtitleCue,
@@ -49,7 +49,8 @@ import {
type CreatorArtifact,
type CreatorJson,
type CreatorResultSnapshot,
- type CreatorTtsProvider
+ type CreatorTtsProvider,
+ type VideoMetadataResponse
} from '@opencreator/protocol';
type SourceType = 'url' | 'file';
@@ -1378,6 +1379,99 @@ function videoOrientationFromDimensions(width: unknown, height: unknown): VideoO
return height > width ? 'portrait' : 'landscape';
}
+function videoDimensionsFromUnknown(width: unknown, height: unknown): { width: number; height: number } | undefined {
+ if (typeof width !== 'number' || typeof height !== 'number' || width <= 0 || height <= 0) return undefined;
+ return { width, height };
+}
+
+function aspectRatioLabel(width: number, height: number): string {
+ if (Math.abs(width / height - 16 / 9) < 0.02) return '16:9';
+ if (Math.abs(width / height - 9 / 16) < 0.02) return '9:16';
+ let left = width;
+ let right = height;
+ while (right !== 0) [left, right] = [right, left % right];
+ return `${width / left}:${height / left}`;
+}
+
+function isYouTubeShort(url: string): boolean {
+ try {
+ return new URL(url).pathname.startsWith('/shorts/');
+ } catch {
+ return false;
+ }
+}
+
+function SubtitlePreviewVideo(props: {
+ src: string;
+ onDimensions(width: number, height: number): void;
+}) {
+ const [ready, setReady] = useState(false);
+
+ return (
+ <video
+ className="video-translation-subtitle-preview-media"
+ src={props.src}
+ muted
+ playsInline
+ preload="metadata"
+ aria-hidden="true"
+ data-ready={ready}
+ onLoadedMetadata={event => {
+ const video = event.currentTarget;
+ if (video.videoWidth > 0 && video.videoHeight > 0) {
+ props.onDimensions(video.videoWidth, video.videoHeight);
+ }
+ if (Number.isFinite(video.duration) && video.duration > 0.2) {
+ video.currentTime = Math.min(video.duration * 0.1, 5, video.duration - 0.1);
+ }
+ }}
+ onLoadedData={event => {
+ if (!event.currentTarget.seeking) setReady(true);
+ }}
+ onSeeked={() => setReady(true)}
+ onError={() => setReady(false)}
+ />
+ );
+}
+
+function SubtitleColorControl(props: {
+ label: string;
+ inputLabel: string;
+ customLabel: string;
+ value: string;
+ onChange(value: string): void;
+ prefixPresetLabel?: boolean;
+}) {
+ return (
+ <div className="video-translation-style-control">
+ <span>{props.label}</span>
+ <div className="video-translation-color-options">
+ {subtitleColors.map(color => (
+ <button
+ type="button"
+ aria-label={props.prefixPresetLabel ? `${props.label} ${color}` : color}
+ aria-pressed={props.value.toUpperCase() === color}
+ key={color}
+ style={{ '--subtitle-swatch-color': color } as CSSProperties}
+ onClick={() => props.onChange(color)}
+ >
+ {props.value.toUpperCase() === color ? <Check size={13} strokeWidth={2.4} aria-hidden="true" /> : null}
+ </button>
+ ))}
+ <label className="video-translation-custom-color" title={props.customLabel}>
+ <input
+ type="color"
+ aria-label={props.inputLabel}
+ value={props.value}
+ onChange={event => props.onChange(event.target.value.toUpperCase())}
+ />
+ <span>{props.customLabel}</span>
+ </label>
+ </div>
+ </div>
+ );
+}
+
export default function VideoTranslationWorkspace(props: {
onBack(): void;
promptHint?: string;
@@ -1389,6 +1483,7 @@ export default function VideoTranslationWorkspace(props: {
const videoInputRef = useRef<HTMLInputElement>(null);
const agentFocusTimeoutRef = useRef<number>();
const skipPersistRef = useRef(false);
+ const dimensionsJobIdRef = useRef<string>();
const restoredResultNavigationRef = useRef<{
jobId: string;
latestVersion: number | null;
@@ -1399,6 +1494,9 @@ export default function VideoTranslationWorkspace(props: {
const [sourceType, setSourceType] = useState<SourceType>('url');
const [videoUrl, setVideoUrl] = useState('');
const [videoFile, setVideoFile] = useState<File | null>(null);
+ const [sourceDimensions, setSourceDimensions] = useState<{ width: number; height: number }>();
+ const [urlMetadata, setUrlMetadata] = useState<{ url: string; value: VideoMetadataResponse }>();
+ const [localPreviewUrl, setLocalPreviewUrl] = useState<{ file: File; url: string }>();
const [videoFileName, setVideoFileName] = useState<string | null>(null);
const [videoFileSize, setVideoFileSize] = useState<number | null>(null);
const [videoFileLastModified, setVideoFileLastModified] = useState<number | null>(null);
@@ -1448,6 +1546,35 @@ export default function VideoTranslationWorkspace(props: {
const [cancelDialogOpen, setCancelDialogOpen] = useState(false);
const [agentFocus, setAgentFocus] = useState<AgentFocus>();
const cancelConfirmRef = useRef<HTMLButtonElement>(null);
+ const parsedVideoSource = useMemo(() => parseVideoSource(videoUrl), [videoUrl]);
+ const currentUrlMetadata = urlMetadata?.url === videoUrl ? urlMetadata.value : undefined;
+
+ useEffect(() => {
+ if (workspacePhase !== 'configure' || currentStep !== 2 || sourceType !== 'file'
+ || videoFile === null || !videoFile.type.startsWith('video/')
+ || typeof URL.createObjectURL !== 'function') {
+ setLocalPreviewUrl(undefined);
+ return;
+ }
+ const url = URL.createObjectURL(videoFile);
+ setLocalPreviewUrl({ file: videoFile, url });
+ return () => URL.revokeObjectURL(url);
+ }, [workspacePhase, currentStep, sourceType, videoFile]);
+
+ useEffect(() => {
+ if (currentStep === 0 || sourceType !== 'url' || !isValidVideoUrl(videoUrl)
+ || props.videoMetadataService === undefined || currentUrlMetadata !== undefined
+ || (parsedVideoSource.kind !== 'youtube' && parsedVideoSource.kind !== 'bilibili')) return;
+ let canceled = false;
+ void props.videoMetadataService.getVideoMetadata(videoUrl).then(metadata => {
+ if (canceled) return;
+ setUrlMetadata({ url: videoUrl, value: metadata });
+ if (metadata.width !== undefined && metadata.height !== undefined) {
+ updateSourceOrientation(metadata.width, metadata.height);
+ }
+ }).catch(() => undefined);
+ return () => { canceled = true; };
+ }, [currentStep, sourceType, videoUrl, props.videoMetadataService, currentUrlMetadata, parsedVideoSource.kind]);
useEffect(() => {
if (creatorSession === null) return;
@@ -1496,9 +1623,23 @@ export default function VideoTranslationWorkspace(props: {
const persistedSourceArtifact = [...creatorSession.job.artifacts].reverse().find(artifact => (
artifact.kind === 'source_video' && artifact.status === 'completed'
));
+ const artifactMatchesCurrentFile = persistedSourceArtifact !== undefined
+ && persisted.sourceType === 'file'
+ && videoFile === null
+ && (persisted.sourceArtifactId === persistedSourceArtifact.id
+ || (typeof persisted.sourceFileName === 'string'
+ && persisted.sourceFileName === readArtifactString(persistedSourceArtifact, 'fileName')));
+ const restoredDimensions = videoDimensionsFromUnknown(
+ artifactMatchesCurrentFile ? persistedSourceArtifact.metadata.width : undefined,
+ artifactMatchesCurrentFile ? persistedSourceArtifact.metadata.height : undefined
+ );
+ if (dimensionsJobIdRef.current !== creatorSession.job.id) {
+ setSourceDimensions(restoredDimensions);
+ }
+ dimensionsJobIdRef.current = creatorSession.job.id;
setSourceOrientation(videoOrientationFromDimensions(
- persistedSourceArtifact?.metadata.width,
- persistedSourceArtifact?.metadata.height
+ restoredDimensions?.width,
+ restoredDimensions?.height
) ?? persistedOrientation ?? 'landscape');
if (typeof persisted.verticalTitle === 'string') setVerticalTitle(persisted.verticalTitle);
if (typeof persisted.verticalSubtitle === 'string') setVerticalSubtitle(persisted.verticalSubtitle);
@@ -1740,6 +1881,61 @@ export default function VideoTranslationWorkspace(props: {
size: readArtifactNumber(registeredSourceArtifact, 'size') ?? 0,
mime: readArtifactString(registeredSourceArtifact, 'mimeType') ?? 'application/octet-stream'
};
+ const [artifactPreviewUrl, setArtifactPreviewUrl] = useState<{ artifactId: string; url: string }>();
+ useEffect(() => {
+ if (workspacePhase !== 'configure' || currentStep !== 2 || sourceType !== 'file'
+ || videoFile !== null || registeredSourceArtifact === undefined
+ || creatorSession?.openArtifact === undefined) {
+ setArtifactPreviewUrl(undefined);
+ return;
+ }
+ let canceled = false;
+ let objectUrl: string | undefined;
+ void createCreatorArtifactObjectUrl(
+ creatorSession,
+ registeredSourceArtifact.id,
+ 'video-translation.load-style-preview',
+ l('字幕预览画面加载失败。', 'The subtitle preview frame failed to load.')
+ ).then(url => {
+ objectUrl = url;
+ if (canceled) {
+ URL.revokeObjectURL(url);
+ return;
+ }
+ setArtifactPreviewUrl({ artifactId: registeredSourceArtifact.id, url });
+ }).catch(() => undefined);
+ return () => {
+ canceled = true;
+ if (objectUrl !== undefined) URL.revokeObjectURL(objectUrl);
+ };
+ }, [workspacePhase, currentStep, sourceType, videoFile, registeredSourceArtifact?.id,
+ creatorSession?.openArtifact, creatorSession?.captureCreatorFailure, l]);
+
+ const previewVideoSrc = sourceType === 'file'
+ ? videoFile !== null
+ ? localPreviewUrl?.file === videoFile ? localPreviewUrl.url : undefined
+ : artifactPreviewUrl !== undefined && artifactPreviewUrl.artifactId === registeredSourceArtifact?.id
+ ? artifactPreviewUrl.url : undefined
+ : parsedVideoSource.kind === 'direct' ? parsedVideoSource.url : undefined;
+ const previewPosterUrl = sourceType === 'url'
+ ? currentUrlMetadata?.thumbnailUrl
+ ?? (parsedVideoSource.kind === 'youtube' ? parsedVideoSource.thumbnailUrl : undefined)
+ : undefined;
+ const shortVideo = sourceType === 'url' && parsedVideoSource.kind === 'youtube' && isYouTubeShort(videoUrl);
+ const measuredDimensions = sourceDimensions ?? videoDimensionsFromUnknown(
+ currentUrlMetadata?.width,
+ currentUrlMetadata?.height
+ );
+ const knownDimensions = sourceType === 'url' && parsedVideoSource.kind === 'youtube'
+ && measuredDimensions !== undefined && measuredDimensions.width <= 640 && measuredDimensions.height <= 480
+ ? undefined
+ : measuredDimensions;
+ const sourceIsPortrait = shortVideo || (knownDimensions === undefined
+ ? sourceOrientation === 'portrait'
+ : knownDimensions.height > knownDimensions.width);
+ const convertedToVertical = videoFormat === 'vertical' && !sourceIsPortrait;
+ const previewWidth = convertedToVertical ? 9 : knownDimensions?.width ?? (sourceIsPortrait ? 9 : 16);
+ const previewHeight = convertedToVertical ? 16 : knownDimensions?.height ?? (sourceIsPortrait ? 16 : 9);
const selectedFileRegistered = videoFile !== null
&& registeredSourceArtifact !== undefined
&& sourceArtifactMatchesFile(registeredSourceArtifact, videoFile);
@@ -2249,6 +2445,7 @@ export default function VideoTranslationWorkspace(props: {
setVideoFileName(file?.name ?? null);
setVideoFileSize(file?.size ?? null);
setVideoFileLastModified(file?.lastModified ?? null);
+ setSourceDimensions(undefined);
setSourceOrientation('landscape');
if (file) {
setVideoUrl('');
@@ -2265,6 +2462,7 @@ export default function VideoTranslationWorkspace(props: {
return;
}
setVideoUrl('');
+ setSourceDimensions(undefined);
setSourceType('url');
setAttemptedContinue(false);
}
@@ -2272,6 +2470,7 @@ export default function VideoTranslationWorkspace(props: {
function updateSourceOrientation(width: number, height: number) {
const orientation = videoOrientationFromDimensions(width, height);
if (orientation === undefined) return;
+ setSourceDimensions(current => current?.width === width && current.height === height ? current : { width, height });
setSourceOrientation(orientation);
if (orientation === 'portrait') setVideoFormat('vertical');
}
@@ -2805,11 +3004,15 @@ export default function VideoTranslationWorkspace(props: {
setVideoUrl(url);
setSourceType('url');
setVideoFile(null);
+ setSourceDimensions(undefined);
setSourceOrientation('landscape');
setAttemptedContinue(false);
}}
onClear={clearCurrentSource}
onDimensions={updateSourceOrientation}
+ onMetadata={(url, metadata) => {
+ setUrlMetadata({ url, value: metadata });
+ }}
/>
) : null}
@@ -2934,52 +3137,32 @@ export default function VideoTranslationWorkspace(props: {
</div>
</div>
- <div className="video-translation-style-control">
- <span>{l('译文颜色', 'Translation color')}</span>
- <div className="video-translation-color-options">
- {subtitleColors.map(color => (
- <button
- type="button"
- aria-label={color}
- aria-pressed={subtitleColor.toUpperCase() === color}
- key={color}
- style={{ '--subtitle-swatch-color': color } as CSSProperties}
- onClick={() => setSubtitleColor(color)}
- >
- {subtitleColor.toUpperCase() === color ? <Check size={13} strokeWidth={2.4} aria-hidden="true" /> : null}
- </button>
- ))}
- <label className="video-translation-custom-color" title={l('自定义颜色', 'Custom color')}>
- <input
- type="color"
- aria-label={l('自定义译文颜色', 'Custom translation color')}
- value={subtitleColor}
- onChange={event => setSubtitleColor(event.target.value.toUpperCase())}
- />
- <span>{l('自定义', 'Custom')}</span>
- </label>
- </div>
- </div>
-
- <div className="video-translation-style-fields">
- <label className="video-translation-field video-translation-color-field">
- <span>{l('原文颜色', 'Original color')}</span>
- <input
- type="color"
- aria-label={l('原文颜色', 'Original color')}
- value={subtitleSecondaryColor}
- onChange={event => setSubtitleSecondaryColor(event.target.value.toUpperCase())}
- />
- </label>
- <label className="video-translation-field video-translation-color-field">
- <span>{l('描边颜色', 'Outline color')}</span>
- <input
- type="color"
- aria-label={l('描边颜色', 'Outline color')}
- value={subtitleOutlineColor}
- onChange={event => setSubtitleOutlineColor(event.target.value.toUpperCase())}
- />
- </label>
+ <SubtitleColorControl
+ label={l('译文颜色', 'Translation color')}
+ inputLabel={l('自定义译文颜色', 'Custom translation color')}
+ customLabel={l('自定义', 'Custom')}
+ value={subtitleColor}
+ onChange={setSubtitleColor}
+ />
+
+ <SubtitleColorControl
+ label={l('原文颜色', 'Original color')}
+ inputLabel={l('原文颜色', 'Original color')}
+ customLabel={l('自定义', 'Custom')}
+ value={subtitleSecondaryColor}
+ onChange={setSubtitleSecondaryColor}
+ prefixPresetLabel
+ />
+
+ <div className="video-translation-outline-fields">
+ <SubtitleColorControl
+ label={l('描边颜色', 'Outline color')}
+ inputLabel={l('描边颜色', 'Outline color')}
+ customLabel={l('自定义', 'Custom')}
+ value={subtitleOutlineColor}
+ onChange={setSubtitleOutlineColor}
+ prefixPresetLabel
+ />
<label className="video-translation-field">
<span>{l('描边宽度', 'Outline width')}</span>
<input
@@ -3001,74 +3184,78 @@ export default function VideoTranslationWorkspace(props: {
onChange={setSubtitleShadowEnabled}
/>
{subtitleShadowEnabled ? (
- <div className="video-translation-style-fields">
- <label className="video-translation-field video-translation-color-field">
- <span>{l('阴影颜色', 'Shadow color')}</span>
- <input
- type="color"
- aria-label={l('阴影颜色', 'Shadow color')}
- value={subtitleShadowColor}
- onChange={event => setSubtitleShadowColor(event.target.value.toUpperCase())}
- />
- </label>
- <label className="video-translation-field">
- <span>{l('不透明度', 'Opacity')}</span>
- <input
- type="number"
- min="0"
- max="1"
- step="0.05"
- value={subtitleShadowOpacity}
- onChange={event => setSubtitleShadowOpacity(Number(event.target.value))}
- />
- </label>
- <label className="video-translation-field">
- <span>{l('水平偏移', 'Horizontal offset')}</span>
- <input
- type="number"
- min="-20"
- max="20"
- step="1"
- value={subtitleShadowOffsetX}
- onChange={event => setSubtitleShadowOffsetX(Number(event.target.value))}
- />
- </label>
- <label className="video-translation-field">
- <span>{l('垂直偏移', 'Vertical offset')}</span>
- <input
- type="number"
- min="-20"
- max="20"
- step="1"
- value={subtitleShadowOffsetY}
- onChange={event => setSubtitleShadowOffsetY(Number(event.target.value))}
- />
- </label>
- <label className="video-translation-field">
- <span>{l('模糊', 'Blur')}</span>
- <input
- type="number"
- min="0"
- max="10"
- step="0.5"
- value={subtitleShadowBlur}
- onChange={event => setSubtitleShadowBlur(Number(event.target.value))}
- />
- </label>
- </div>
+ <>
+ <SubtitleColorControl
+ label={l('阴影颜色', 'Shadow color')}
+ inputLabel={l('阴影颜色', 'Shadow color')}
+ customLabel={l('自定义', 'Custom')}
+ value={subtitleShadowColor}
+ onChange={setSubtitleShadowColor}
+ prefixPresetLabel
+ />
+ <div className="video-translation-style-fields">
+ <label className="video-translation-field">
+ <span>{l('不透明度', 'Opacity')}</span>
+ <input
+ type="number"
+ min="0"
+ max="1"
+ step="0.05"
+ value={subtitleShadowOpacity}
+ onChange={event => setSubtitleShadowOpacity(Number(event.target.value))}
+ />
+ </label>
+ <label className="video-translation-field">
+ <span>{l('水平偏移', 'Horizontal offset')}</span>
+ <input
+ type="number"
+ min="-20"
+ max="20"
+ step="1"
+ value={subtitleShadowOffsetX}
+ onChange={event => setSubtitleShadowOffsetX(Number(event.target.value))}
+ />
+ </label>
+ <label className="video-translation-field">
+ <span>{l('垂直偏移', 'Vertical offset')}</span>
+ <input
+ type="number"
+ min="-20"
+ max="20"
+ step="1"
+ value={subtitleShadowOffsetY}
+ onChange={event => setSubtitleShadowOffsetY(Number(event.target.value))}
+ />
+ </label>
+ <label className="video-translation-field">
+ <span>{l('模糊', 'Blur')}</span>
+ <input
+ type="number"
+ min="0"
+ max="10"
+ step="0.5"
+ value={subtitleShadowBlur}
+ onChange={event => setSubtitleShadowBlur(Number(event.target.value))}
+ />
+ </label>
+ </div>
+ </>
) : null}
</div>
</div>
<div
className="video-translation-subtitle-preview"
- data-ratio={videoFormat === 'vertical' ? '9:16' : '16:9'}
+ data-ratio={aspectRatioLabel(previewWidth, previewHeight)}
+ data-orientation={previewHeight > previewWidth ? 'portrait' : 'landscape'}
+ data-converted={convertedToVertical}
role="region"
aria-label={l('字幕样式预览', 'Subtitle style preview')}
>
<span>{l('字幕样式预览', 'Subtitle style preview')}</span>
<div
style={{
+ '--subtitle-preview-aspect-ratio': `${previewWidth} / ${previewHeight}`,
'--subtitle-preview-color': subtitleColor,
'--subtitle-preview-secondary-color': subtitleSecondaryColor,
'--subtitle-preview-outline-color': subtitleOutlineColor,
@@ -3081,13 +3268,27 @@ export default function VideoTranslationWorkspace(props: {
'--subtitle-preview-font-weight': ({ regular: 400, medium: 500, bold: 700 } as const)[subtitleWeight]
} as CSSProperties}
>
- {bilingual && subtitlePosition === 'bottom' ? (
- <small data-subtitle-kind="original">{l('这是一段原文字幕', 'This is an original subtitle')}</small>
+ {previewPosterUrl ? (
+ <img
+ className="video-translation-subtitle-preview-media"
+ src={previewPosterUrl}
+ alt=""
+ aria-hidden="true"
+ onError={event => { event.currentTarget.hidden = true; }}
+ />
) : null}
- <strong data-subtitle-kind="translation">{l('这是一段译文字幕', 'This is a translated subtitle')}</strong>
- {bilingual && subtitlePosition === 'top' ? (
- <small data-subtitle-kind="original">{l('这是一段原文字幕', 'This is an original subtitle')}</small>
+ {previewVideoSrc ? (
+ <SubtitlePreviewVideo key={previewVideoSrc} src={previewVideoSrc} onDimensions={updateSourceOrientation} />
) : null}
+ <div className="video-translation-subtitle-preview-cues">
+ {bilingual && subtitlePosition === 'bottom' ? (
+ <small data-subtitle-kind="original">{l('这是一段原文字幕', 'This is an original subtitle')}</small>
+ ) : null}
+ <strong data-subtitle-kind="translation">{l('这是一段译文字幕', 'This is a translated subtitle')}</strong>
+ {bilingual && subtitlePosition === 'top' ? (
+ <small data-subtitle-kind="original">{l('这是一段原文字幕', 'This is an original subtitle')}</small>
+ ) : null}
+ </div>
</div>
</div>
</div>
diff --git a/apps/web/src/features/dashboard/dashboard-css.test.ts b/apps/web/src/features/dashboard/dashboard-css.test.ts
index 6d446ad0..10746085 100644
--- a/apps/web/src/features/dashboard/dashboard-css.test.ts
+++ b/apps/web/src/features/dashboard/dashboard-css.test.ts
@@ -119,16 +119,52 @@ describe('dashboard CSS contracts', () => {
it('keeps subtitle style previews at their output aspect ratio instead of stretching with the form', () => {
const layout = cssBlocks('.video-translation-subtitle-style-layout');
+ const outlineFields = cssBlocks('.video-translation-outline-fields');
+ const colorOptions = cssBlocks('.video-translation-color-options');
const preview = cssBlocks('.video-translation-subtitle-preview');
const player = cssBlocks('.video-translation-subtitle-preview > div');
- const verticalPreview = cssBlocks('.video-translation-subtitle-preview[data-ratio="9:16"] > div');
+ const overlay = cssBlocks('.video-translation-subtitle-preview > div::after');
+ const media = cssBlocks('.video-translation-subtitle-preview-media');
+ const cues = cssBlocks('.video-translation-subtitle-preview-cues');
+ const verticalPreview = cssBlocks('.video-translation-subtitle-preview[data-orientation="portrait"] > div');
expect(layout[0]).toContain('align-items: start;');
+ expect(layout[0]).toContain('minmax(350px, 1.2fr) minmax(260px, 1fr)');
+ expect(outlineFields[0]).toContain('grid-template-columns: minmax(0, 1fr) 88px;');
+ expect(colorOptions[0]).toContain('flex-wrap: wrap;');
+ expect(dashboardCss).toMatch(/@container video-translation-workspace \(max-width: 760px\) \{\s*\.video-translation-subtitle-style-layout/);
expect(preview[0]).toContain('grid-template-rows: auto auto;');
expect(preview[0]).toContain('align-content: start;');
- expect(player[0]).toContain('aspect-ratio: 16 / 9;');
+ expect(player[0]).toContain('aspect-ratio: var(--subtitle-preview-aspect-ratio, 16 / 9);');
+ expect(overlay[0]).toContain('background: rgb(0 0 0 / 55%);');
+ expect(overlay[0]).toContain('z-index: 1;');
+ expect(media[0]).toContain('object-fit: cover;');
+ expect(cues[0]).toContain('position: absolute;');
+ expect(cues[0]).toContain('z-index: 2;');
expect(verticalPreview).toHaveLength(1);
- expect(verticalPreview[0]).toContain('aspect-ratio: 9 / 16;');
+ expect(verticalPreview[0]).toContain('width: min(236px, 100%);');
+ });
+
+ it('widens the translation settings consistently and keeps smaller color swatches', () => {
+ for (const selector of [
+ '.video-translation-source-step',
+ '.video-translation-configure-top',
+ '.video-translation-wizard-main .video-translation-wizard-body',
+ '.video-translation-wizard-main .video-translation-wizard-actions',
+ '.video-translation-run-notice'
+ ]) {
+ expect(cssBlocks(selector)[0]).toContain('width: min(960px, 100%);');
+ }
+ expect(cssBlocks('.video-translation-color-options > button')[0]).toContain('width: 26px;');
+ expect(cssBlocks('.video-translation-custom-color input')[0]).toContain('width: 26px;');
+ });
+
+ it('matches video download settings width to translation and centers labeled platforms', () => {
+ expect(cssBlocks('.video-download-workspace-page .creator-tool-stack')[0]).toContain('width: min(960px, 100%);');
+ expect(cssBlocks('.video-download-platforms')[0]).toContain('justify-content: center;');
+ expect(cssBlocks('.video-download-platforms')[0]).toContain('flex-wrap: wrap;');
+ expect(cssBlocks('.video-download-platforms img')[0]).toContain('width: 32px;');
+ expect(cssBlocks('.video-download-platforms li')[0]).toContain('text-align: center;');
});
it('fits subtitle previews to the available pane while keeping cues in one scrollable list', () => {
diff --git a/apps/web/src/features/dashboard/dashboard.css b/apps/web/src/features/dashboard/dashboard.css
index b87dd43c..dcd3aeb6 100644
--- a/apps/web/src/features/dashboard/dashboard.css
+++ b/apps/web/src/features/dashboard/dashboard.css
@@ -1056,7 +1056,7 @@
.video-translation-subtitle-style-layout {
display: grid;
- grid-template-columns: minmax(230px, 0.82fr) minmax(300px, 1.18fr);
+ grid-template-columns: minmax(350px, 1.2fr) minmax(260px, 1fr);
align-items: start;
gap: 22px;
}
@@ -1107,13 +1107,14 @@
.video-translation-color-options {
min-height: 38px;
display: flex;
+ flex-wrap: wrap;
align-items: center;
gap: 9px;
}
.video-translation-color-options > button {
- width: 30px;
- height: 30px;
+ width: 26px;
+ height: 26px;
flex: 0 0 auto;
display: grid;
place-items: center;
@@ -1141,8 +1142,8 @@
}
.video-translation-custom-color input {
- width: 30px;
- height: 30px;
+ width: 26px;
+ height: 26px;
flex: 0 0 auto;
padding: 2px;
border: 1px solid var(--border);
@@ -1166,10 +1167,11 @@
gap: 10px;
}
-.video-translation-color-field input[type="color"] {
- width: 100%;
- min-height: 36px;
- padding: 3px;
+.video-translation-outline-fields {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 88px;
+ align-items: start;
+ gap: 12px;
}
.video-translation-shadow-settings {
@@ -1188,13 +1190,9 @@
}
.video-translation-subtitle-preview > div {
- aspect-ratio: 16 / 9;
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: flex-end;
- gap: 7px;
- padding: 28px 24px;
+ position: relative;
+ aspect-ratio: var(--subtitle-preview-aspect-ratio, 16 / 9);
+ overflow: hidden;
border: 1px solid #343a43;
border-radius: 8px;
background: #1b2027;
@@ -1204,9 +1202,46 @@
text-align: center;
}
-.video-translation-subtitle-preview[data-ratio="9:16"] > div {
+.video-translation-subtitle-preview > div::after {
+ content: "";
+ position: absolute;
+ z-index: 1;
+ inset: 0;
+ background: rgb(0 0 0 / 55%);
+ pointer-events: none;
+}
+
+.video-translation-subtitle-preview-media {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+
+.video-translation-subtitle-preview-media[data-ready="false"] {
+ opacity: 0;
+}
+
+.video-translation-subtitle-preview[data-converted="true"] .video-translation-subtitle-preview-media {
+ object-fit: contain;
+}
+
+.video-translation-subtitle-preview-cues {
+ position: absolute;
+ z-index: 2;
+ inset: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: flex-end;
+ gap: 7px;
+ padding: 28px 24px;
+ box-sizing: border-box;
+}
+
+.video-translation-subtitle-preview[data-orientation="portrait"] > div {
width: min(236px, 100%);
- aspect-ratio: 9 / 16;
justify-self: center;
}
@@ -1557,6 +1592,10 @@
margin: 0 auto;
}
+.video-download-workspace-page .creator-tool-stack {
+ width: min(960px, 100%);
+}
+
.auto-clip-tool-stack {
position: relative;
}
@@ -1692,21 +1731,52 @@
line-height: 1.45;
}
+.video-download-platform-section {
+ margin-bottom: 18px;
+}
+
+.video-download-platform-section > span {
+ color: var(--muted);
+ font-size: 12px;
+ font-weight: 550;
+}
+
.video-download-platforms {
display: flex;
flex-wrap: wrap;
- align-items: center;
- gap: 8px 10px;
- margin-top: 10px;
+ justify-content: center;
+ gap: 16px 18px;
+ margin: 14px 0 0;
+ padding: 0;
+ list-style: none;
+}
+
+.video-download-platforms li {
+ width: 78px;
+ min-width: 0;
+ display: grid;
+ justify-items: center;
+ align-content: start;
+ gap: 7px;
+ color: var(--text);
+ font-size: 12px;
+ font-weight: 600;
+ line-height: 1.2;
+ text-align: center;
}
.video-download-platforms img {
display: block;
- width: 16px;
- height: 16px;
+ width: 32px;
+ height: 32px;
object-fit: contain;
}
+.video-download-platforms li > span {
+ max-width: 100%;
+ overflow-wrap: anywhere;
+}
+
.creator-tool-panel-heading > small {
display: inline-flex;
align-items: center;
@@ -11154,7 +11224,7 @@
}
.video-translation-source-step {
- width: min(720px, 100%);
+ width: min(960px, 100%);
margin: 0 auto;
padding: 24px;
box-sizing: border-box;
@@ -11577,7 +11647,7 @@
}
.video-translation-run-notice {
- width: min(720px, 100%);
+ width: min(960px, 100%);
min-height: 40px;
display: flex;
align-items: center;
@@ -11705,7 +11775,7 @@
}
.video-translation-configure-top {
- width: min(720px, 100%);
+ width: min(960px, 100%);
display: grid;
gap: 14px;
margin: 0 auto 20px;
@@ -11871,7 +11941,7 @@
}
.video-translation-wizard-main .video-translation-wizard-body {
- width: min(720px, 100%);
+ width: min(960px, 100%);
min-height: 0;
margin: 0 auto;
overflow-y: auto;
@@ -11881,7 +11951,7 @@
}
.video-translation-wizard-main .video-translation-wizard-actions {
- width: min(720px, 100%);
+ width: min(960px, 100%);
margin-right: auto;
margin-left: auto;
}
@@ -11899,6 +11969,18 @@
background: var(--surface);
}
+@container video-translation-workspace (max-width: 760px) {
+ .video-translation-subtitle-style-layout {
+ grid-template-columns: minmax(0, 1fr);
+ }
+}
+
+@container video-translation-workspace (max-width: 480px) {
+ .video-translation-outline-fields {
+ grid-template-columns: minmax(0, 1fr);
+ }
+}
+
@container video-translation-workspace (max-width: 720px) {
.auto-clip-settings-grid {
grid-template-columns: minmax(0, 1fr);
@@ -11953,10 +12035,6 @@
position: static;
}
- .video-translation-subtitle-style-layout {
- grid-template-columns: minmax(0, 1fr);
- }
-
.creator-task-final-grid,
.creator-result-layout,
.stickman-audio-layout,