+
diff --git a/src/config/editor.js b/src/config/editor.js
index 1371aad..c44f806 100644
--- a/src/config/editor.js
+++ b/src/config/editor.js
@@ -2,7 +2,6 @@ import {
CirclesThree,
ClosedCaptioning,
ImageSquare,
- MagicWand,
MusicNote,
Scan,
Sticker,
@@ -165,7 +164,6 @@ export const TOOL_RAIL = [
{ id: "audio", label: "音频", icon: MusicNote },
{ id: "transition", label: "转场", icon: CirclesThree },
{ id: "stickers", label: "贴纸", icon: Sticker },
- { id: "filters", label: "滤镜", icon: MagicWand },
];
export const RATIO_OPTIONS = [
diff --git a/src/hooks/useSourceAudioExtraction.js b/src/hooks/useSourceAudioExtraction.js
index 21bb941..cb826e2 100644
--- a/src/hooks/useSourceAudioExtraction.js
+++ b/src/hooks/useSourceAudioExtraction.js
@@ -1,16 +1,24 @@
import { useCallback } from "react";
-import { decodeWaveform, extractAudioFromVideo } from "../lib/media.js";
+import { concatenateAudioBlobs, decodeWaveform, extractAudioFromVideo } from "../lib/media.js";
export function useSourceAudioExtraction(d) {
- return useCallback(async (asset, timelineStart = 0) => {
+ return useCallback(async (asset, timelineStart = 0, options = {}) => {
if (!asset?.blob) { d.clearSourceAudioTrack(null); d.notify("当前视频素材缺少原文件,无法分离原声"); return; }
d.setStatus("generating"); d.setStatusText("加载 FFmpeg WASM 分离视频原声"); d.setProgress(12);
try {
- const blob = await extractAudioFromVideo(asset.blob, asset.name); d.setStatusText("解析视频原声波形"); d.setProgress(78);
- const decoded = await decodeWaveform(blob, 96); if (!decoded.duration) throw new Error("视频没有可识别的音频轨");
- d.replaceSourceAudio(blob, decoded.duration, decoded.peaks, `${asset.name.replace(/\.[^.]+$/, "")} 原声.wav`, "视频原声已分离到时间线", timelineStart, asset.id, { focusAudio: false });
+ const extractedBlob = await extractAudioFromVideo(asset.blob, asset.name); d.setStatusText("解析视频原声波形"); d.setProgress(78);
+ const extracted = await decodeWaveform(extractedBlob, 96); if (!extracted.duration) throw new Error("视频没有可识别的音频轨");
+ const shouldAppend = options.append === true && d.sourceAudioBlob instanceof Blob;
+ const sourceAudioOffset = shouldAppend ? Math.max(0, Number(d.sourceAudioDuration) || 0) : 0;
+ const blob = shouldAppend ? await concatenateAudioBlobs([d.sourceAudioBlob, extractedBlob]) : extractedBlob;
+ const decoded = shouldAppend ? await decodeWaveform(blob, 192) : extracted;
+ d.setVisualSegments((segments) => segments.map((segment) => segment.assetId === asset.id && segment.type === "video"
+ ? { ...segment, sourceAudioOffset }
+ : segment));
+ const sourceName = shouldAppend ? "视频原声合集.wav" : `${asset.name.replace(/\.[^.]+$/, "")} 原声.wav`;
+ d.replaceSourceAudio(blob, decoded.duration, decoded.peaks, sourceName, shouldAppend ? "视频原声已追加到时间线" : "视频原声已分离到时间线", timelineStart, shouldAppend ? "" : asset.id, { focusAudio: false });
} catch (error) {
- console.warn(error); d.clearSourceAudioTrack(null); d.setStatus("ready"); d.setStatusText("视频未检测到可分离原声");
+ console.warn(error); if (!(options.append === true && d.sourceAudioBlob)) d.clearSourceAudioTrack(null); d.setStatus("ready"); d.setStatusText("视频未检测到可分离原声");
d.setProgress(0); d.notify("视频画面已添加,但没有可分离的原声音轨");
}
}, [d]);
diff --git a/src/hooks/useTimelineModel.js b/src/hooks/useTimelineModel.js
index 05419c4..e1bc9fc 100644
--- a/src/hooks/useTimelineModel.js
+++ b/src/hooks/useTimelineModel.js
@@ -126,11 +126,25 @@ export function useTimelineModel(d) {
0,
d.stickerSegments.findIndex((segment) => segment.id === d.selectedStickerSegmentId),
);
+ const currentStickerSegments = d.trackVisibility.sticker
+ ? d.stickerSegments.filter((segment) => {
+ const start = Math.max(0, Number(segment.start) || 0);
+ const end = start + Math.max(0, Number(segment.duration) || 0);
+ return d.currentTime >= start && d.currentTime < end;
+ })
+ : [];
const previewSticker = d.trackVisibility.sticker && currentStickerSegment
? currentStickerSegment
: d.stickerSegments.length
? STICKERS[0]
: selectedSticker;
+ const previewStickers = currentStickerSegments.length
+ ? currentStickerSegments
+ : d.stickerSegments.length
+ ? []
+ : previewSticker?.src || previewSticker?.text
+ ? [previewSticker]
+ : [];
const currentVisualSegmentIndex = getVisualSegmentIndexAtTime(d.visualSegments, d.currentTime);
const currentVisualSegment = currentVisualSegmentIndex >= 0
? d.visualSegments[currentVisualSegmentIndex] ?? null
@@ -192,7 +206,7 @@ export function useTimelineModel(d) {
currentCaptionSegment, currentSegmentIndex, currentStickerSegment,
currentStickerSegmentIndex, currentVisualRange, currentVisualSegment,
currentVisualSegmentIndex, estimatedDuration, focusedSegmentIndex, getStickerDragAsset,
- peaks, previewSticker, previewVisionBaseAnalysis, previewVisionKey,
+ peaks, previewSticker, previewStickers, previewVisionBaseAnalysis, previewVisionKey,
previewVisionRecord, previewVisualLocalTime, previewVisualRange, previewVisualSegment,
previewVisualSegmentIndex, previewVisualSourceTime, previewVisualSrc, previewVisualType,
ratio, segments, selectedAudioSegment, selectedCaptionSegment, selectedFilter,
diff --git a/src/i18n.js b/src/i18n.js
index 89ed06d..704c773 100644
--- a/src/i18n.js
+++ b/src/i18n.js
@@ -199,9 +199,37 @@ const TTS_BACKEND_COPY = {
vi: { ttsStatusLoadingWebGpu: "Đang tải mô hình giọng nói WebGPU", ttsStatusGeneratingWebGpu: "Đang tạo giọng nói bằng WebGPU", ttsStatusFallingBackWasm: "Không dùng được WebGPU; đang chuyển sang WASM", ttsStatusGeneratingWasm: "Đang tạo giọng nói bằng WASM" },
};
+const VISUAL_ANIMATION_COPY = {
+ zh: { visualTabAnimation: "动画", visualAnimation: "片段动画", visualAnimationIn: "入场", visualAnimationOut: "出场", visualAnimationNone: "无动画", visualAnimationFade: "淡入淡出", visualAnimationZoom: "缩放", visualAnimationSlideLeft: "左滑", visualAnimationSlideUp: "上滑", visualAnimationDuration: "动画时长", visualAnimationHoverHint: "悬停预览" },
+ en: { visualTabAnimation: "Animation", visualAnimation: "Clip animation", visualAnimationIn: "In", visualAnimationOut: "Out", visualAnimationNone: "None", visualAnimationFade: "Fade", visualAnimationZoom: "Zoom", visualAnimationSlideLeft: "Slide left", visualAnimationSlideUp: "Slide up", visualAnimationDuration: "Duration", visualAnimationHoverHint: "Hover to preview" },
+ ja: { visualTabAnimation: "アニメーション", visualAnimation: "クリップアニメーション", visualAnimationIn: "入る", visualAnimationOut: "出る", visualAnimationNone: "なし", visualAnimationFade: "フェード", visualAnimationZoom: "ズーム", visualAnimationSlideLeft: "左へスライド", visualAnimationSlideUp: "上へスライド", visualAnimationDuration: "再生時間", visualAnimationHoverHint: "ホバーでプレビュー" },
+ ko: { visualTabAnimation: "애니메이션", visualAnimation: "클립 애니메이션", visualAnimationIn: "등장", visualAnimationOut: "퇴장", visualAnimationNone: "없음", visualAnimationFade: "페이드", visualAnimationZoom: "확대", visualAnimationSlideLeft: "왼쪽 슬라이드", visualAnimationSlideUp: "위쪽 슬라이드", visualAnimationDuration: "지속 시간", visualAnimationHoverHint: "마우스를 올려 미리보기" },
+ es: { visualTabAnimation: "Animación", visualAnimation: "Animación del clip", visualAnimationIn: "Entrada", visualAnimationOut: "Salida", visualAnimationNone: "Ninguna", visualAnimationFade: "Fundido", visualAnimationZoom: "Zoom", visualAnimationSlideLeft: "Deslizar a la izquierda", visualAnimationSlideUp: "Deslizar arriba", visualAnimationDuration: "Duración", visualAnimationHoverHint: "Pasa el cursor para previsualizar" },
+ fr: { visualTabAnimation: "Animation", visualAnimation: "Animation du clip", visualAnimationIn: "Entrée", visualAnimationOut: "Sortie", visualAnimationNone: "Aucune", visualAnimationFade: "Fondu", visualAnimationZoom: "Zoom", visualAnimationSlideLeft: "Glisser à gauche", visualAnimationSlideUp: "Glisser vers le haut", visualAnimationDuration: "Durée", visualAnimationHoverHint: "Survolez pour prévisualiser" },
+ de: { visualTabAnimation: "Animation", visualAnimation: "Clip-Animation", visualAnimationIn: "Eingang", visualAnimationOut: "Ausgang", visualAnimationNone: "Keine", visualAnimationFade: "Überblenden", visualAnimationZoom: "Zoom", visualAnimationSlideLeft: "Nach links", visualAnimationSlideUp: "Nach oben", visualAnimationDuration: "Dauer", visualAnimationHoverHint: "Zum Vorschauen bewegen" },
+ pt: { visualTabAnimation: "Animação", visualAnimation: "Animação do clipe", visualAnimationIn: "Entrada", visualAnimationOut: "Saída", visualAnimationNone: "Nenhuma", visualAnimationFade: "Desvanecer", visualAnimationZoom: "Zoom", visualAnimationSlideLeft: "Deslizar à esquerda", visualAnimationSlideUp: "Deslizar para cima", visualAnimationDuration: "Duração", visualAnimationHoverHint: "Passe o cursor para visualizar" },
+ th: { visualTabAnimation: "แอนิเมชัน", visualAnimation: "แอนิเมชันคลิป", visualAnimationIn: "เข้า", visualAnimationOut: "ออก", visualAnimationNone: "ไม่มี", visualAnimationFade: "เฟด", visualAnimationZoom: "ซูม", visualAnimationSlideLeft: "เลื่อนไปซ้าย", visualAnimationSlideUp: "เลื่อนขึ้น", visualAnimationDuration: "ระยะเวลา", visualAnimationHoverHint: "วางเมาส์เพื่อดูตัวอย่าง" },
+ vi: { visualTabAnimation: "Hoạt ảnh", visualAnimation: "Hoạt ảnh clip", visualAnimationIn: "Vào", visualAnimationOut: "Ra", visualAnimationNone: "Không", visualAnimationFade: "Mờ dần", visualAnimationZoom: "Thu phóng", visualAnimationSlideLeft: "Trượt trái", visualAnimationSlideUp: "Trượt lên", visualAnimationDuration: "Thời lượng", visualAnimationHoverHint: "Di chuột để xem trước" },
+};
+
+const STICKER_EDITOR_COPY = {
+ zh: { stickerProperties: "贴纸属性", stickerHorizontalPosition: "水平位置", stickerVerticalPosition: "垂直位置", stickerScale: "缩放", stickerRotation: "旋转", stickerOpacity: "不透明度", deleteSticker: "删除贴纸", stickerAddedToTrack: "贴纸已添加到贴纸轨" },
+ en: { stickerProperties: "Sticker properties", stickerHorizontalPosition: "Horizontal position", stickerVerticalPosition: "Vertical position", stickerScale: "Scale", stickerRotation: "Rotation", stickerOpacity: "Opacity", deleteSticker: "Delete sticker", stickerAddedToTrack: "Sticker added to the sticker track" },
+ ja: { stickerProperties: "ステッカーのプロパティ", stickerHorizontalPosition: "水平位置", stickerVerticalPosition: "垂直位置", stickerScale: "拡大率", stickerRotation: "回転", stickerOpacity: "不透明度", deleteSticker: "ステッカーを削除", stickerAddedToTrack: "ステッカートラックに追加しました" },
+ ko: { stickerProperties: "스티커 속성", stickerHorizontalPosition: "가로 위치", stickerVerticalPosition: "세로 위치", stickerScale: "크기", stickerRotation: "회전", stickerOpacity: "불투명도", deleteSticker: "스티커 삭제", stickerAddedToTrack: "스티커 트랙에 추가됨" },
+ es: { stickerProperties: "Propiedades del sticker", stickerHorizontalPosition: "Posición horizontal", stickerVerticalPosition: "Posición vertical", stickerScale: "Escala", stickerRotation: "Rotación", stickerOpacity: "Opacidad", deleteSticker: "Eliminar sticker", stickerAddedToTrack: "Sticker añadido a la pista" },
+ fr: { stickerProperties: "Propriétés du sticker", stickerHorizontalPosition: "Position horizontale", stickerVerticalPosition: "Position verticale", stickerScale: "Échelle", stickerRotation: "Rotation", stickerOpacity: "Opacité", deleteSticker: "Supprimer le sticker", stickerAddedToTrack: "Sticker ajouté à la piste" },
+ de: { stickerProperties: "Sticker-Eigenschaften", stickerHorizontalPosition: "Horizontale Position", stickerVerticalPosition: "Vertikale Position", stickerScale: "Skalierung", stickerRotation: "Drehung", stickerOpacity: "Deckkraft", deleteSticker: "Sticker löschen", stickerAddedToTrack: "Sticker zur Spur hinzugefügt" },
+ pt: { stickerProperties: "Propriedades do sticker", stickerHorizontalPosition: "Posição horizontal", stickerVerticalPosition: "Posição vertical", stickerScale: "Escala", stickerRotation: "Rotação", stickerOpacity: "Opacidade", deleteSticker: "Excluir sticker", stickerAddedToTrack: "Sticker adicionado à faixa" },
+ th: { stickerProperties: "คุณสมบัติสติกเกอร์", stickerHorizontalPosition: "ตำแหน่งแนวนอน", stickerVerticalPosition: "ตำแหน่งแนวตั้ง", stickerScale: "ขนาด", stickerRotation: "การหมุน", stickerOpacity: "ความทึบ", deleteSticker: "ลบสติกเกอร์", stickerAddedToTrack: "เพิ่มสติกเกอร์ลงในแทร็กแล้ว" },
+ vi: { stickerProperties: "Thuộc tính nhãn dán", stickerHorizontalPosition: "Vị trí ngang", stickerVerticalPosition: "Vị trí dọc", stickerScale: "Tỷ lệ", stickerRotation: "Xoay", stickerOpacity: "Độ mờ", deleteSticker: "Xóa nhãn dán", stickerAddedToTrack: "Đã thêm nhãn dán vào rãnh" },
+};
+
export const UI_COPY = {
zh: {
...VISUAL_EDITOR_COPY.zh,
+ ...VISUAL_ANIMATION_COPY.zh,
+ ...STICKER_EDITOR_COPY.zh,
...VISUAL_PANEL_TITLE_COPY.zh,
...VISUAL_MASK_SHAPE_COPY.zh,
...VISUAL_KEYFRAME_ACTION_COPY.zh,
@@ -570,6 +598,8 @@ export const UI_COPY = {
},
en: {
...VISUAL_EDITOR_COPY.en,
+ ...VISUAL_ANIMATION_COPY.en,
+ ...STICKER_EDITOR_COPY.en,
...VISUAL_PANEL_TITLE_COPY.en,
...VISUAL_MASK_SHAPE_COPY.en,
...VISUAL_KEYFRAME_ACTION_COPY.en,
@@ -938,6 +968,8 @@ export const UI_COPY = {
},
ja: {
...VISUAL_EDITOR_COPY.ja,
+ ...VISUAL_ANIMATION_COPY.ja,
+ ...STICKER_EDITOR_COPY.ja,
...VISUAL_PANEL_TITLE_COPY.ja,
...VISUAL_MASK_SHAPE_COPY.ja,
...VISUAL_KEYFRAME_ACTION_COPY.ja,
@@ -1015,6 +1047,8 @@ export const UI_COPY = {
Object.assign(UI_COPY, {
ko: {
...VISUAL_EDITOR_COPY.ko,
+ ...VISUAL_ANIMATION_COPY.ko,
+ ...STICKER_EDITOR_COPY.ko,
...VISUAL_PANEL_TITLE_COPY.ko,
...VISUAL_MASK_SHAPE_COPY.ko,
...VISUAL_KEYFRAME_ACTION_COPY.ko,
@@ -1074,6 +1108,8 @@ Object.assign(UI_COPY, {
es: {
...UI_COPY.en,
...VISUAL_EDITOR_COPY.es,
+ ...VISUAL_ANIMATION_COPY.es,
+ ...STICKER_EDITOR_COPY.es,
...VISUAL_PANEL_TITLE_COPY.es,
...VISUAL_MASK_SHAPE_COPY.es,
...VISUAL_KEYFRAME_ACTION_COPY.es,
@@ -1130,6 +1166,8 @@ Object.assign(UI_COPY, {
fr: {
...UI_COPY.en,
...VISUAL_EDITOR_COPY.fr,
+ ...VISUAL_ANIMATION_COPY.fr,
+ ...STICKER_EDITOR_COPY.fr,
...VISUAL_PANEL_TITLE_COPY.fr,
...VISUAL_MASK_SHAPE_COPY.fr,
...VISUAL_KEYFRAME_ACTION_COPY.fr,
@@ -1186,6 +1224,8 @@ Object.assign(UI_COPY, {
de: {
...UI_COPY.en,
...VISUAL_EDITOR_COPY.de,
+ ...VISUAL_ANIMATION_COPY.de,
+ ...STICKER_EDITOR_COPY.de,
...VISUAL_PANEL_TITLE_COPY.de,
...VISUAL_MASK_SHAPE_COPY.de,
...VISUAL_KEYFRAME_ACTION_COPY.de,
@@ -1242,6 +1282,8 @@ Object.assign(UI_COPY, {
pt: {
...UI_COPY.en,
...VISUAL_EDITOR_COPY.pt,
+ ...VISUAL_ANIMATION_COPY.pt,
+ ...STICKER_EDITOR_COPY.pt,
...VISUAL_PANEL_TITLE_COPY.pt,
...VISUAL_MASK_SHAPE_COPY.pt,
...VISUAL_KEYFRAME_ACTION_COPY.pt,
@@ -1298,6 +1340,8 @@ Object.assign(UI_COPY, {
th: {
...UI_COPY.en,
...VISUAL_EDITOR_COPY.th,
+ ...VISUAL_ANIMATION_COPY.th,
+ ...STICKER_EDITOR_COPY.th,
...VISUAL_PANEL_TITLE_COPY.th,
...VISUAL_MASK_SHAPE_COPY.th,
...VISUAL_KEYFRAME_ACTION_COPY.th,
@@ -1354,6 +1398,8 @@ Object.assign(UI_COPY, {
vi: {
...UI_COPY.en,
...VISUAL_EDITOR_COPY.vi,
+ ...VISUAL_ANIMATION_COPY.vi,
+ ...STICKER_EDITOR_COPY.vi,
...VISUAL_PANEL_TITLE_COPY.vi,
...VISUAL_MASK_SHAPE_COPY.vi,
...VISUAL_KEYFRAME_ACTION_COPY.vi,
diff --git a/src/i18nVisualAnimation.test.js b/src/i18nVisualAnimation.test.js
new file mode 100644
index 0000000..14c629f
--- /dev/null
+++ b/src/i18nVisualAnimation.test.js
@@ -0,0 +1,16 @@
+import { describe, expect, it } from "vitest";
+import { APP_LANGUAGES, createTranslator } from "./i18n.js";
+
+describe("visual animation translations", () => {
+ it("provides native animation copy for every supported UI language", () => {
+ for (const language of APP_LANGUAGES) {
+ const t = createTranslator(language.id);
+ expect(t("visualTabAnimation")).not.toBe("visualTabAnimation");
+ expect(t("visualAnimationHoverHint")).not.toBe("visualAnimationHoverHint");
+ expect(t("visualAnimationDuration")).not.toBe("visualAnimationDuration");
+ expect(t("stickerProperties")).not.toBe("stickerProperties");
+ expect(t("stickerOpacity")).not.toBe("stickerOpacity");
+ expect(t("deleteSticker")).not.toBe("deleteSticker");
+ }
+ });
+});
diff --git a/src/lib/assetDragControls.js b/src/lib/assetDragControls.js
index fe2c532..a985e33 100644
--- a/src/lib/assetDragControls.js
+++ b/src/lib/assetDragControls.js
@@ -79,7 +79,8 @@ export function createAssetDragControls(deps) {
};
const handleStickerClick = (event, sticker) => {
if (deps.suppressAssetClickRef.current === sticker.id) { deps.suppressAssetClickRef.current = ""; event.preventDefault(); event.stopPropagation(); return; }
- deps.setSelectedStickerId(sticker.id); deps.setSelectedStickerSegmentId(""); deps.notify(deps.t("stickerApplied"));
+ deps.setSelectedStickerId(sticker.id);
+ deps.addStickerAssetToTimeline(sticker, { startTime: deps.currentTime });
};
const handleTrackAssetDragOver = (event, track) => {
const asset = getDraggedAsset(event); const target = asset?.type === "sticker" ? "sticker" : track;
diff --git a/src/lib/media.js b/src/lib/media.js
index 10db296..94a39ed 100644
--- a/src/lib/media.js
+++ b/src/lib/media.js
@@ -24,6 +24,7 @@ import {
normalizeVisualPlaybackRate,
resolveVisualTransform,
} from "./visualEffects.js";
+import { resolveVisualClipAnimation } from "./visualClipAnimations.js";
export function getAudioRecordingFormat() {
if (typeof MediaRecorder === "undefined") {
@@ -41,10 +42,10 @@ export function getAudioRecordingFormat() {
let ffmpegLoadPromise = null;
let ffmpegTaskQueue = Promise.resolve();
-const VIDEO_TRACK_FRAME_MAX = 72;
+const VIDEO_TRACK_FRAME_MAX = 120;
const VIDEO_TRACK_FRAME_HEIGHT = 90;
-function getVideoTrackSampleCount(duration, maxFrames = VIDEO_TRACK_FRAME_MAX) {
+export function getVideoTrackSampleCount(duration, maxFrames = VIDEO_TRACK_FRAME_MAX) {
const safeDuration = Math.max(0, Number.isFinite(duration) ? duration : 0);
if (!safeDuration) {
return 0;
@@ -52,7 +53,7 @@ function getVideoTrackSampleCount(duration, maxFrames = VIDEO_TRACK_FRAME_MAX) {
const targetStep =
safeDuration <= 20
- ? 0.5
+ ? 0.2
: safeDuration <= 120
? 1.25
: safeDuration <= 600
@@ -207,6 +208,34 @@ function encodeAudioBufferAsWav(buffer) {
return new Blob([output], { type: "audio/wav" });
}
+export async function concatenateAudioBlobs(blobs = []) {
+ const sources = blobs.filter((blob) => blob instanceof Blob && blob.size > 0);
+ if (!sources.length) throw new Error("没有可合并的音频");
+ if (sources.length === 1) return sources[0];
+ const AudioContextClass = window.AudioContext || window.webkitAudioContext;
+ const OfflineAudioContextClass = window.OfflineAudioContext || window.webkitOfflineAudioContext;
+ if (!AudioContextClass || !OfflineAudioContextClass) throw new Error("当前浏览器不支持音频合并");
+ const decoder = new AudioContextClass();
+ try {
+ const decoded = await Promise.all(sources.map(async (blob) => decoder.decodeAudioData((await blob.arrayBuffer()).slice(0))));
+ const sampleRate = Math.max(...decoded.map((buffer) => buffer.sampleRate));
+ const channels = Math.max(...decoded.map((buffer) => buffer.numberOfChannels));
+ const totalFrames = decoded.reduce((total, buffer) => total + Math.ceil(buffer.duration * sampleRate), 0);
+ const offline = new OfflineAudioContextClass(channels, totalFrames, sampleRate);
+ let cursor = 0;
+ for (const buffer of decoded) {
+ const source = offline.createBufferSource();
+ source.buffer = buffer;
+ source.connect(offline.destination);
+ source.start(cursor);
+ cursor += buffer.duration;
+ }
+ return encodeAudioBufferAsWav(await offline.startRendering());
+ } finally {
+ await decoder.close().catch(() => {});
+ }
+}
+
export async function reverseAudioBlob(blob) {
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
if (!AudioContextClass) throw new Error("当前浏览器不支持 AudioContext,无法反转音频。");
@@ -521,6 +550,8 @@ function drawPreviewFrame(context, visual, canvas, options) {
captionReferenceSize = null,
sticker = null,
stickerImage = null,
+ stickers = [],
+ stickerImages = [],
transitionId = "none",
vision = null,
visualEffects = null,
@@ -532,6 +563,14 @@ function drawPreviewFrame(context, visual, canvas, options) {
context.fillStyle = "#090b0f";
context.fillRect(0, 0, width, height);
const transform = resolveVisualTransform(visualEffects?.keyframes, visualTime);
+ const animation = resolveVisualClipAnimation(visualEffects?.animation, visualTime, visualEffects?.duration);
+ const animatedTransform = {
+ ...transform,
+ x: transform.x + animation.x,
+ y: transform.y + animation.y,
+ scale: transform.scale * animation.scale,
+ opacity: transform.opacity * animation.opacity,
+ };
const mask = visualEffects?.mask ?? {};
const maskCenterX = (Number.isFinite(mask.centerX) ? mask.centerX : 50) / 100 * width;
const maskCenterY = (Number.isFinite(mask.centerY) ? mask.centerY : 50) / 100 * height;
@@ -546,10 +585,10 @@ function drawPreviewFrame(context, visual, canvas, options) {
const maskContext = layers.mask.getContext("2d");
layerContext.clearRect(0, 0, width, height);
layerContext.save();
- layerContext.globalAlpha = transform.opacity;
- layerContext.translate(width / 2 + (transform.x / 100) * width, height / 2 + (transform.y / 100) * height);
- layerContext.rotate((transform.rotation * Math.PI) / 180);
- layerContext.scale(transform.scale, transform.scale);
+ layerContext.globalAlpha = animatedTransform.opacity;
+ layerContext.translate(width / 2 + (animatedTransform.x / 100) * width, height / 2 + (animatedTransform.y / 100) * height);
+ layerContext.rotate((animatedTransform.rotation * Math.PI) / 180);
+ layerContext.scale(animatedTransform.scale, animatedTransform.scale);
layerContext.translate(-width / 2, -height / 2);
visualLayout = drawFittedVisual(layerContext, visual, layers.visual, fitMode, filter, vision);
layerContext.restore();
@@ -568,10 +607,10 @@ function drawPreviewFrame(context, visual, canvas, options) {
} else if (["rectangle", "rounded"].includes(mask.type)) {
context.beginPath(); context.roundRect(maskCenterX - maskWidth / 2, maskCenterY - maskHeight / 2, maskWidth, maskHeight, mask.type === "rounded" ? Math.min(maskWidth, maskHeight) * (Number.isFinite(mask.cornerRadius) ? mask.cornerRadius : 12) / 100 : 0); context.clip();
}
- context.globalAlpha = transform.opacity;
- context.translate(width / 2 + (transform.x / 100) * width, height / 2 + (transform.y / 100) * height);
- context.rotate((transform.rotation * Math.PI) / 180);
- context.scale(transform.scale, transform.scale);
+ context.globalAlpha = animatedTransform.opacity;
+ context.translate(width / 2 + (animatedTransform.x / 100) * width, height / 2 + (animatedTransform.y / 100) * height);
+ context.rotate((animatedTransform.rotation * Math.PI) / 180);
+ context.scale(animatedTransform.scale, animatedTransform.scale);
context.translate(-width / 2, -height / 2);
visualLayout = drawFittedVisual(context, visual, canvas, fitMode, filter, vision);
context.restore();
@@ -611,22 +650,34 @@ function drawPreviewFrame(context, visual, canvas, options) {
);
}
- if (sticker?.src && stickerImage) {
+ const visibleStickers = stickers.length ? stickers : sticker ? [sticker] : [];
+ visibleStickers.forEach((activeSticker, index) => {
+ const activeStickerImage = stickerImages[index] ?? (activeSticker === sticker ? stickerImage : null);
+ if (activeSticker?.src && activeStickerImage) {
const stickerRatio =
- (stickerImage.naturalWidth || stickerImage.width || 1) /
- (stickerImage.naturalHeight || stickerImage.height || 1);
- const maxStickerSize = Math.min(width, height) * 0.22;
+ (activeStickerImage.naturalWidth || activeStickerImage.width || 1) /
+ (activeStickerImage.naturalHeight || activeStickerImage.height || 1);
+ const stickerScale = Math.max(0.2, Math.min(3, Number(activeSticker.scale) || 1));
+ const maxStickerSize = Math.min(width, height) * 0.22 * stickerScale;
const stickerWidth = stickerRatio >= 1 ? maxStickerSize : maxStickerSize * stickerRatio;
const stickerHeight = stickerRatio >= 1 ? maxStickerSize / stickerRatio : maxStickerSize;
- context.drawImage(stickerImage, width - stickerWidth - width * 0.1, height * 0.1, stickerWidth, stickerHeight);
- } else if (sticker?.text) {
+ const centerX = (Number.isFinite(activeSticker.x) ? activeSticker.x : 82) / 100 * width;
+ const centerY = (Number.isFinite(activeSticker.y) ? activeSticker.y : 20) / 100 * height;
+ context.save();
+ context.globalAlpha = Math.max(0, Math.min(1, Number.isFinite(activeSticker.opacity) ? activeSticker.opacity : 1));
+ context.translate(centerX, centerY);
+ context.rotate(((Number(activeSticker.rotation) || 0) * Math.PI) / 180);
+ context.drawImage(activeStickerImage, -stickerWidth / 2, -stickerHeight / 2, stickerWidth, stickerHeight);
+ context.restore();
+ } else if (activeSticker?.text) {
context.fillStyle = "rgba(53, 240, 221, 0.92)";
context.fillRect(width - 246, 54, 172, 54);
context.fillStyle = "#061515";
context.font = "800 24px Inter, system-ui, sans-serif";
context.textAlign = "center";
- context.fillText(sticker.text, width - 160, 90);
- }
+ context.fillText(activeSticker.text, width - 160, 90);
+ }
+ });
if (transitionId === "fade") {
const fadeAlpha =
@@ -979,21 +1030,16 @@ export async function exportBrowserVideo({
}
return Math.min(maximumTime, Math.max(0, Number(video.currentTime) || expectedTime));
};
- const getStickerAtTime = (elapsed) => {
+ const getStickersAtTime = (elapsed) => {
if (!stickerSegments.length) {
- return sticker;
+ return sticker ? [sticker] : [];
}
- for (let index = stickerSegments.length - 1; index >= 0; index -= 1) {
- const segment = stickerSegments[index];
+ return stickerSegments.filter((segment) => {
const start = Math.max(0, segment.start || 0);
const end = start + Math.max(0, segment.duration || 0);
- if (elapsed >= start && elapsed < end) {
- return segment;
- }
- }
-
- return null;
+ return elapsed >= start && elapsed < end;
+ });
};
const draw = () => {
const elapsed = Math.min(totalDuration, (performance.now() - startTime) / 1000);
@@ -1003,7 +1049,7 @@ export async function exportBrowserVideo({
const { item: visualItem, range: visualRange } = getVisualItemAtTime(elapsed);
const localTime = Math.max(0, elapsed - (visualRange?.start ?? 0));
const visualSourceTime = syncVideoItem(visualItem, localTime);
- const exportSticker = getStickerAtTime(elapsed);
+ const exportStickers = getStickersAtTime(elapsed);
const exportVisual = visualItem.cutoutVisual || visualItem.visual;
const resolvedVision = resolveVisionAnalysisAtTime(
visualItem.segment.vision ?? null,
@@ -1029,8 +1075,8 @@ export async function exportBrowserVideo({
captionSize,
captionStyle,
captionReferenceSize,
- sticker: exportSticker,
- stickerImage: exportSticker?.src ? stickerImageMap.get(exportSticker.src) : null,
+ stickers: exportStickers,
+ stickerImages: exportStickers.map((item) => item?.src ? stickerImageMap.get(item.src) : null),
transitionId,
vision: frameVision,
visualEffects: visualItem.segment,
@@ -1063,7 +1109,7 @@ export async function exportBrowserVideo({
});
const finalSegmentIndex = getSegmentIndexAtTime(exportSegments, totalDuration, captionTargetDuration);
const { item: finalVisualItem, range: finalVisualRange } = getVisualItemAtTime(totalDuration);
- const finalSticker = getStickerAtTime(totalDuration);
+ const finalStickers = getStickersAtTime(Math.max(0, totalDuration - 0.0001));
const finalLocalTime = Math.max(0, totalDuration - (finalVisualRange?.start ?? 0));
const finalVisualSourceTime = syncVideoItem(finalVisualItem, finalLocalTime);
const finalResolvedVision = resolveVisionAnalysisAtTime(
@@ -1093,8 +1139,8 @@ export async function exportBrowserVideo({
captionSize,
captionStyle,
captionReferenceSize,
- sticker: finalSticker,
- stickerImage: finalSticker?.src ? stickerImageMap.get(finalSticker.src) : null,
+ stickers: finalStickers,
+ stickerImages: finalStickers.map((item) => item?.src ? stickerImageMap.get(item.src) : null),
transitionId,
vision: finalFrameVision,
});
diff --git a/src/lib/sourceAudioSync.js b/src/lib/sourceAudioSync.js
index 580246d..79fee16 100644
--- a/src/lib/sourceAudioSync.js
+++ b/src/lib/sourceAudioSync.js
@@ -12,15 +12,16 @@ function resolveLinkedAssetId(visualSegments, sourceAudioAssetId) {
}
export function getLinkedSourceAudioSegments(visualSegments = [], sourceAudioAssetId = "", sourceAudioDuration = 0) {
+ const hasMappedOffsets = visualSegments.some((segment) => segment.type === "video" && Number.isFinite(segment.sourceAudioOffset));
const linkedAssetId = resolveLinkedAssetId(visualSegments, sourceAudioAssetId);
- if (!linkedAssetId) return [];
+ if (!hasMappedOffsets && !linkedAssetId) return [];
const timeline = getVisualSegmentTimeline(visualSegments);
const maximumSourceTime = Math.max(0, Number(sourceAudioDuration) || 0);
return visualSegments.flatMap((segment, index) => {
- if (segment.type !== "video" || segment.assetId !== linkedAssetId) return [];
+ if (segment.type !== "video" || (!hasMappedOffsets && segment.assetId !== linkedAssetId)) return [];
const range = timeline[index];
const playbackRate = normalizeVisualPlaybackRate(segment.playbackRate);
- const sourceStart = Math.max(0, Number(segment.sourceStart) || 0);
+ const sourceStart = Math.max(0, Number(segment.sourceAudioOffset) || 0) + Math.max(0, Number(segment.sourceStart) || 0);
const requestedSourceDuration = Math.max(0, Number(segment.sourceDuration) || segment.duration * playbackRate);
const sourceDuration = maximumSourceTime
? Math.max(0, Math.min(requestedSourceDuration, maximumSourceTime - sourceStart))
@@ -28,7 +29,7 @@ export function getLinkedSourceAudioSegments(visualSegments = [], sourceAudioAss
if (!range || sourceDuration <= 0) return [];
return [{
id: segment.id,
- assetId: linkedAssetId,
+ assetId: segment.assetId || linkedAssetId,
start: range.start,
duration: Math.min(range.duration, sourceDuration / playbackRate),
sourceStart,
diff --git a/src/lib/sourceAudioSync.test.js b/src/lib/sourceAudioSync.test.js
index a1d2c5d..7dcac5f 100644
--- a/src/lib/sourceAudioSync.test.js
+++ b/src/lib/sourceAudioSync.test.js
@@ -23,4 +23,18 @@ describe("linked source audio", () => {
expect(getLinkedSourceAudioState(segments, 2.5)).toMatchObject({ active: false, playbackRate: 1 });
expect(getLinkedSourceAudioState(segments, 4)).toMatchObject({ active: true, sourceTime: 5, playbackRate: 1 });
});
+
+ it("keeps source audio mappings for multiple imported video assets", () => {
+ const clips = [
+ { id: "first", assetId: "video-1", type: "video", duration: 4, sourceStart: 0, sourceDuration: 4, sourceAudioOffset: 0 },
+ { id: "second", assetId: "video-2", type: "video", duration: 3, sourceStart: 0, sourceDuration: 3, sourceAudioOffset: 4 },
+ ];
+ const segments = getLinkedSourceAudioSegments(clips, "", 7);
+ expect(segments).toMatchObject([
+ { id: "first", assetId: "video-1", start: 0, duration: 4, sourceStart: 0 },
+ { id: "second", assetId: "video-2", start: 4, duration: 3, sourceStart: 4 },
+ ]);
+ expect(getLinkedSourceAudioState(segments, 2)).toMatchObject({ active: true, sourceTime: 2 });
+ expect(getLinkedSourceAudioState(segments, 5)).toMatchObject({ active: true, sourceTime: 5 });
+ });
});
diff --git a/src/lib/stickerTimelineActions.js b/src/lib/stickerTimelineActions.js
index 30caccd..26cbead 100644
--- a/src/lib/stickerTimelineActions.js
+++ b/src/lib/stickerTimelineActions.js
@@ -33,7 +33,7 @@ export function createStickerTimelineActions(d) {
};
});
d.setStickerSegments(normalizedSegments);
- d.setSelectedTrack("sticker");
+ d.setSelectedTrack(normalizedSegments.length ? "sticker" : "image");
d.setActiveTool("stickers");
const selectedSegment =
normalizedSegments.find((segment) => segment.id === selectedId) ??
@@ -53,10 +53,13 @@ export function createStickerTimelineActions(d) {
d.notify("当前贴纸素材不可用");
return;
}
- const startTime = Math.min(
+ const requestedStartTime = Number.isFinite(options.startTime)
+ ? options.startTime
+ : getTimelineTimeFromDropPercent(options.percent ?? 0);
+ const startTime = Math.max(0, Math.min(
MAX_TIMELINE_DURATION_SECONDS - DEFAULT_STICKER_SEGMENT_SECONDS,
- getTimelineTimeFromDropPercent(options.percent ?? 0),
- );
+ requestedStartTime,
+ ));
const nextSegment = createStickerSegment(
asset,
startTime,
@@ -64,7 +67,7 @@ export function createStickerTimelineActions(d) {
);
commitStickerSegments(
[...d.stickerSegments, nextSegment],
- "贴纸已添加到贴纸轨",
+ d.t?.("stickerAddedToTrack") ?? "贴纸已添加到贴纸轨",
nextSegment.id,
);
d.seekTo(startTime);
diff --git a/src/lib/stickerTimelineActions.test.js b/src/lib/stickerTimelineActions.test.js
new file mode 100644
index 0000000..37923ee
--- /dev/null
+++ b/src/lib/stickerTimelineActions.test.js
@@ -0,0 +1,21 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { createStickerTimelineActions } from "./stickerTimelineActions.js";
+
+describe("sticker timeline actions", () => {
+ it("adds a clicked sticker at the current playhead time", () => {
+ const setStickerSegments = vi.fn();
+ const actions = createStickerTimelineActions({
+ estimatedDuration: 10, timelineDurationRef: { current: 10 }, trackLocks: {}, stickerSegments: [],
+ setStickerSegments, setSelectedTrack: vi.fn(), setActiveTool: vi.fn(),
+ setSelectedStickerSegmentId: vi.fn(), setSelectedStickerId: vi.fn(), notify: vi.fn(), seekTo: vi.fn(),
+ });
+
+ actions.addStickerAssetToTimeline(
+ { id: "fire", src: "/fire.png", type: "sticker", name: "Fire" },
+ { startTime: 6.25 },
+ );
+
+ expect(setStickerSegments.mock.calls[0][0][0]).toMatchObject({ stickerId: "fire", start: 6.25 });
+ });
+});
diff --git a/src/lib/timeline.js b/src/lib/timeline.js
index 828f1ac..97772d0 100644
--- a/src/lib/timeline.js
+++ b/src/lib/timeline.js
@@ -65,6 +65,11 @@ export function createStickerSegment(sticker, start = 0, duration = DEFAULT_STIC
src: sticker?.src ?? "",
start: Math.max(0, Math.min(MAX_TIMELINE_DURATION_SECONDS - safeDuration, start || 0)),
duration: safeDuration,
+ x: Number.isFinite(sticker?.x) ? sticker.x : 82,
+ y: Number.isFinite(sticker?.y) ? sticker.y : 20,
+ scale: Number.isFinite(sticker?.scale) ? sticker.scale : 1,
+ rotation: Number.isFinite(sticker?.rotation) ? sticker.rotation : 0,
+ opacity: Number.isFinite(sticker?.opacity) ? sticker.opacity : 1,
};
}
diff --git a/src/lib/timelineMoveControls.js b/src/lib/timelineMoveControls.js
index 9ec45dc..6dd2e64 100644
--- a/src/lib/timelineMoveControls.js
+++ b/src/lib/timelineMoveControls.js
@@ -1,4 +1,5 @@
import { DEFAULT_STICKER_SEGMENT_SECONDS, MAX_TIMELINE_DURATION_SECONDS, MIN_VISUAL_SEGMENT_SECONDS } from "../config/editor.js";
+import { collectTimelineSnapPoints, snapTimelineRange } from "./timelineSnap.js";
export function createTimelineMoveControls(d) {
const startSingleTrackMove = (event, track) => {
@@ -12,15 +13,19 @@ export function createTimelineMoveControls(d) {
if (!rect) return;
event.preventDefault(); event.stopPropagation(); d.setSelectedTrack(track); d.setActiveTool("audio");
const startX = event.clientX; let moved = false; let latest = start;
+ const snapPoints = collectTimelineSnapPoints(d, { track, id: track });
const move = (e) => {
if (!moved && Math.abs(e.clientX - startX) < 4) return;
moved = true; e.preventDefault();
- latest = Math.max(0, Math.min(MAX_TIMELINE_DURATION_SECONDS - clipDuration, start + ((e.clientX - startX) / Math.max(rect.width, 1)) * duration));
+ const unsnapped = start + ((e.clientX - startX) / Math.max(rect.width, 1)) * duration;
+ const snapped = snapTimelineRange(unsnapped, clipDuration, snapPoints, (10 / Math.max(rect.width, 1)) * duration);
+ latest = Math.max(0, Math.min(MAX_TIMELINE_DURATION_SECONDS - clipDuration, snapped.start));
+ d.setSnapGuide?.(snapped.guide);
if (isSource) { d.setSourceAudioLinked(false); d.setSourceAudioStart(latest); }
else d.setMusicStart(latest);
d.setTimelineHorizon((value) => Math.max(value, Math.ceil((latest + clipDuration + 5) / 10) * 10));
};
- const cleanup = () => { removeEventListener("pointermove", move); removeEventListener("pointerup", up); removeEventListener("pointercancel", cleanup); };
+ const cleanup = () => { removeEventListener("pointermove", move); removeEventListener("pointerup", up); removeEventListener("pointercancel", cleanup); d.setSnapGuide?.(null); };
const up = () => { cleanup(); if (moved) { d.seekTo(latest); d.notify(`${isSource ? "视频原声" : "音乐"}片段位置已调整`); } };
addEventListener("pointermove", move, { passive: false }); addEventListener("pointerup", up); addEventListener("pointercancel", cleanup);
};
@@ -33,12 +38,16 @@ export function createTimelineMoveControls(d) {
if (!rect) return;
event.stopPropagation(); d.setSelectedTrack("audio"); d.setSelectedAudioSegmentId(segment.id);
const startX = event.clientX; const start = segment.start || 0;
+ const snapPoints = collectTimelineSnapPoints(d, { track: "audio", id: segment.id });
const captions = d.captionSegments.filter((caption) => caption.audioSegmentId === segment.id);
let moved = false; let latest = start;
const move = (e) => {
if (!moved && Math.abs(e.clientX - startX) < 4) return;
moved = true; e.preventDefault();
- latest = Math.max(0, Math.min(MAX_TIMELINE_DURATION_SECONDS - segment.duration, start + ((e.clientX - startX) / Math.max(rect.width, 1)) * duration));
+ const unsnapped = start + ((e.clientX - startX) / Math.max(rect.width, 1)) * duration;
+ const snapped = snapTimelineRange(unsnapped, segment.duration, snapPoints, (10 / Math.max(rect.width, 1)) * duration);
+ latest = Math.max(0, Math.min(MAX_TIMELINE_DURATION_SECONDS - segment.duration, snapped.start));
+ d.setSnapGuide?.(snapped.guide);
d.setAudioSegments((items) => items.map((item) => item.id === segment.id ? { ...item, start: latest } : item));
const delta = latest - start;
d.setCaptionSegments((items) => items.map((caption) => {
@@ -47,7 +56,7 @@ export function createTimelineMoveControls(d) {
}));
d.setTimelineHorizon((value) => Math.max(value, Math.ceil((latest + segment.duration + 5) / 10) * 10));
};
- const cleanup = () => { removeEventListener("pointermove", move); removeEventListener("pointerup", up); removeEventListener("pointercancel", cleanup); };
+ const cleanup = () => { removeEventListener("pointermove", move); removeEventListener("pointerup", up); removeEventListener("pointercancel", cleanup); d.setSnapGuide?.(null); };
const up = () => { cleanup(); if (moved) { d.seekTo(latest); d.notify(d.t("audioClipMoved")); } };
addEventListener("pointermove", move, { passive: false }); addEventListener("pointerup", up); addEventListener("pointercancel", cleanup);
};
@@ -64,13 +73,17 @@ export function createTimelineMoveControls(d) {
const startX = event.clientX; const startY = event.clientY; const start = segment.start || 0;
const segmentDuration = Math.max(MIN_VISUAL_SEGMENT_SECONDS, segment.duration || DEFAULT_STICKER_SEGMENT_SECONDS);
let moved = false; let latest = start;
+ const snapPoints = collectTimelineSnapPoints(d, { track: "sticker", id: segment.id });
const move = (e) => {
if (!moved && Math.hypot(e.clientX - startX, e.clientY - startY) < 4) return;
moved = true; e.preventDefault();
- latest = Math.max(0, Math.min(MAX_TIMELINE_DURATION_SECONDS - segmentDuration, start + ((e.clientX - startX) / Math.max(rect.width, 1)) * duration));
+ const unsnapped = start + ((e.clientX - startX) / Math.max(rect.width, 1)) * duration;
+ const snapped = snapTimelineRange(unsnapped, segmentDuration, snapPoints, (10 / Math.max(rect.width, 1)) * duration);
+ latest = Math.max(0, Math.min(MAX_TIMELINE_DURATION_SECONDS - segmentDuration, snapped.start));
+ d.setSnapGuide?.(snapped.guide);
d.setStickerSegments((items) => items.map((item) => item.id === segment.id ? { ...item, start: latest } : item));
};
- const cleanup = () => { removeEventListener("pointermove", move); removeEventListener("pointerup", up); removeEventListener("pointercancel", cleanup); };
+ const cleanup = () => { removeEventListener("pointermove", move); removeEventListener("pointerup", up); removeEventListener("pointercancel", cleanup); d.setSnapGuide?.(null); };
const up = () => {
cleanup(); if (!moved) return;
d.suppressTimelineClipClickRef.current = segment.id;
diff --git a/src/lib/timelinePlaybackDrag.test.js b/src/lib/timelinePlaybackDrag.test.js
index d2d7c4d..4b7600a 100644
--- a/src/lib/timelinePlaybackDrag.test.js
+++ b/src/lib/timelinePlaybackDrag.test.js
@@ -67,4 +67,38 @@ describe("timeline drag playback behavior", () => {
expect(pauseForTimelineEdit).toHaveBeenCalledTimes(1);
expect(timelineClipDragRef.current.dragging).toBe(true);
});
+
+ it("resizes either edge of a timed caption without moving the opposite edge", () => {
+ const listeners = installPointerListeners();
+ vi.stubGlobal("document", {
+ querySelector: vi.fn(() => ({ getBoundingClientRect: () => ({ width: 200 }) })),
+ });
+ const commitCaptionSegments = vi.fn();
+ const timelineClipDragRef = { current: null };
+ const controls = createTimelineReorderControls({
+ captionSegments: [{ id: "caption-1", text: "test", start: 2, end: 5 }],
+ captionTargetDuration: 10, timelineDuration: 10, trackLocks: { caption: false },
+ timelineClipDragRef, setTimelineClipDrag: vi.fn(), setSelectedTrack: vi.fn(),
+ setSelectedSegmentId: vi.fn(), commitCaptionSegments, notify: vi.fn(),
+ suppressTimelineClipClickRef: { current: "" }, pauseForTimelineEdit: vi.fn(),
+ });
+
+ controls.startCaptionResize(
+ { button: 0, clientX: 40, clientY: 10, preventDefault: vi.fn(), stopPropagation: vi.fn() },
+ "caption-1", 0, "start",
+ );
+ listeners.get("pointermove")({ clientX: 60, clientY: 10 });
+ expect(timelineClipDragRef.current.previewStart).toBe(3);
+ expect(timelineClipDragRef.current.previewEnd).toBe(5);
+ listeners.get("pointerup")();
+ expect(commitCaptionSegments.mock.calls[0][0][0]).toMatchObject({ start: 3, end: 5 });
+
+ controls.startCaptionResize(
+ { button: 0, clientX: 100, clientY: 10, preventDefault: vi.fn(), stopPropagation: vi.fn() },
+ "caption-1", 0, "end",
+ );
+ listeners.get("pointermove")({ clientX: 120, clientY: 10 });
+ expect(timelineClipDragRef.current.previewStart).toBe(2);
+ expect(timelineClipDragRef.current.previewEnd).toBe(6);
+ });
});
diff --git a/src/lib/timelineReorderControls.js b/src/lib/timelineReorderControls.js
index 12da8ff..61110aa 100644
--- a/src/lib/timelineReorderControls.js
+++ b/src/lib/timelineReorderControls.js
@@ -1,4 +1,5 @@
import { getVisualSegmentTimeline, materializeCaptionTimings, moveTimedCaptionSegment, reorderTimelineItems } from "./timeline.js";
+import { collectTimelineSnapPoints, findClosestTimelineSnap, snapTimelineRange } from "./timelineSnap.js";
export function createTimelineReorderControls(d) {
const getTimelineReorderIndex = (track, x, y) => {
@@ -23,7 +24,7 @@ export function createTimelineReorderControls(d) {
}
};
const startTimelineClipDrag = (event, track, segmentId, index) => {
- if (event.button !== 0 || event.target.closest(".image-resize-handle")) return;
+ if (event.button !== 0 || event.target.closest(".image-resize-handle, .caption-resize-handle")) return;
d.pauseForTimelineEdit?.();
if (d.trackLocks[track]) return void d.notify(track === "image" ? "图片轨已锁定,无法拖动片段" : "字幕轨已锁定,无法拖动片段");
if (track === "image") { d.setSelectedTrack("image"); d.setSelectedVisualSegmentId(segmentId); }
@@ -33,6 +34,7 @@ export function createTimelineReorderControls(d) {
if (caption) {
event.preventDefault(); event.stopPropagation();
const duration = Math.max(0.2, caption.end - caption.start);
+ const snapPoints = collectTimelineSnapPoints(d, { track: "caption", id: segmentId });
const initial = { track, mode: "move", segmentId, fromIndex: index, startX: event.clientX, startY: event.clientY,
originalStart: caption.start, originalEnd: caption.end, previewStart: caption.start, previewEnd: caption.end,
previewSegments: materializedCaptions, dragging: false };
@@ -43,15 +45,18 @@ export function createTimelineReorderControls(d) {
const trackElement = document.querySelector('[data-timeline-reorder-track="caption"]');
const width = Math.max(1, trackElement?.getBoundingClientRect().width || 1);
const delta = ((e.clientX - state.startX) / width) * d.timelineDuration;
- const previewStart = Math.max(0, Math.min(d.timelineDuration - duration, state.originalStart + delta));
+ const unsnappedStart = Math.max(0, Math.min(d.timelineDuration - duration, state.originalStart + delta));
+ const snapped = snapTimelineRange(unsnappedStart, duration, snapPoints, (10 / width) * d.timelineDuration);
+ const previewStart = Math.max(0, Math.min(d.timelineDuration - duration, snapped.start));
const previewEnd = previewStart + duration;
const previewSegments = moveTimedCaptionSegment(materializedCaptions, segmentId, previewStart, previewEnd);
const next = { ...state, previewStart, previewEnd, previewSegments, dragging: true };
d.timelineClipDragRef.current = next; d.setTimelineClipDrag(next);
+ d.setSnapGuide?.(snapped.guide);
};
const up = () => {
removeEventListener("pointermove", move); removeEventListener("pointerup", up);
- const state = d.timelineClipDragRef.current; d.timelineClipDragRef.current = null; d.setTimelineClipDrag(null);
+ const state = d.timelineClipDragRef.current; d.timelineClipDragRef.current = null; d.setTimelineClipDrag(null); d.setSnapGuide?.(null);
if (!state?.dragging) return;
d.suppressTimelineClipClickRef.current = segmentId;
setTimeout(() => { if (d.suppressTimelineClipClickRef.current === segmentId) d.suppressTimelineClipClickRef.current = ""; }, 120);
@@ -82,5 +87,57 @@ export function createTimelineReorderControls(d) {
};
addEventListener("pointermove", move); addEventListener("pointerup", up, { once: true });
};
- return { commitTimelineClipReorder, getTimelineReorderIndex, startTimelineClipDrag };
+ const startCaptionResize = (event, segmentId, index, edge) => {
+ if (event.button !== 0) return;
+ event.preventDefault(); event.stopPropagation();
+ if (d.trackLocks.caption) return void d.notify("字幕轨已锁定,无法调整片段时长");
+ const materialized = materializeCaptionTimings(d.captionSegments, d.captionTargetDuration);
+ const caption = materialized[index];
+ if (!caption || caption.id !== segmentId) return;
+ d.setSelectedTrack("caption"); d.setSelectedSegmentId(segmentId);
+ const trackElement = document.querySelector('[data-timeline-reorder-track="caption"]');
+ const trackWidth = Math.max(1, trackElement?.getBoundingClientRect().width || 1);
+ const startX = event.clientX;
+ const snapPoints = collectTimelineSnapPoints(d, { track: "caption", id: segmentId });
+ const initial = {
+ track: "caption", mode: edge === "start" ? "resize-start" : "resize-end", segmentId,
+ fromIndex: index, startX, startY: event.clientY, originalStart: caption.start, originalEnd: caption.end,
+ previewStart: caption.start, previewEnd: caption.end, previewSegments: materialized, dragging: false,
+ };
+ d.timelineClipDragRef.current = initial; d.setTimelineClipDrag(initial);
+ const move = (moveEvent) => {
+ const state = d.timelineClipDragRef.current;
+ if (!state || state.segmentId !== segmentId) return;
+ if (!state.dragging && Math.abs(moveEvent.clientX - startX) < 3) return;
+ if (!state.dragging) d.pauseForTimelineEdit?.();
+ const delta = ((moveEvent.clientX - startX) / trackWidth) * d.timelineDuration;
+ const minimumDuration = 0.2;
+ let previewStart = edge === "start"
+ ? Math.max(0, Math.min(state.originalEnd - minimumDuration, state.originalStart + delta))
+ : state.originalStart;
+ let previewEnd = edge === "end"
+ ? Math.min(d.timelineDuration, Math.max(state.originalStart + minimumDuration, state.originalEnd + delta))
+ : state.originalEnd;
+ const movingValue = edge === "start" ? previewStart : previewEnd;
+ const snap = findClosestTimelineSnap(movingValue, snapPoints, (10 / trackWidth) * d.timelineDuration);
+ if (snap) {
+ if (edge === "start") previewStart = Math.min(state.originalEnd - minimumDuration, snap.time);
+ else previewEnd = Math.max(state.originalStart + minimumDuration, snap.time);
+ }
+ const previewSegments = moveTimedCaptionSegment(materialized, segmentId, previewStart, previewEnd);
+ const next = { ...state, previewStart, previewEnd, previewSegments, dragging: true };
+ d.timelineClipDragRef.current = next; d.setTimelineClipDrag(next);
+ d.setSnapGuide?.(snap ? { time: snap.time, label: `${snap.time.toFixed(2)}s` } : null);
+ };
+ const up = () => {
+ removeEventListener("pointermove", move); removeEventListener("pointerup", up);
+ const state = d.timelineClipDragRef.current; d.timelineClipDragRef.current = null; d.setTimelineClipDrag(null); d.setSnapGuide?.(null);
+ if (!state?.dragging) return;
+ d.suppressTimelineClipClickRef.current = segmentId;
+ setTimeout(() => { if (d.suppressTimelineClipClickRef.current === segmentId) d.suppressTimelineClipClickRef.current = ""; }, 120);
+ d.commitCaptionSegments(state.previewSegments, "已调整字幕片段时长", index);
+ };
+ addEventListener("pointermove", move); addEventListener("pointerup", up, { once: true });
+ };
+ return { commitTimelineClipReorder, getTimelineReorderIndex, startCaptionResize, startTimelineClipDrag };
}
diff --git a/src/lib/timelineSegmentCountActions.js b/src/lib/timelineSegmentCountActions.js
index 25def13..b1dafb4 100644
--- a/src/lib/timelineSegmentCountActions.js
+++ b/src/lib/timelineSegmentCountActions.js
@@ -1,5 +1,5 @@
import { DEFAULT_STICKER_SEGMENT_SECONDS, IMAGE_SEGMENT_SECONDS, MAX_TIMELINE_DURATION_SECONDS, MIN_VISUAL_SEGMENT_SECONDS } from "../config/editor.js";
-import { createStickerSegment, createVisualSegment, getVisualSegmentsTotal, hasExplicitCaptionTiming, makeId } from "./timeline.js";
+import { createStickerSegment, createVisualSegment, getVisualSegmentTimeline, getVisualSegmentsTotal, makeId } from "./timeline.js";
export function createTimelineSegmentCountActions(d) {
const stickerIndex = () => {
@@ -25,33 +25,43 @@ export function createTimelineSegmentCountActions(d) {
const source = d.visualSegments.length ? d.visualSegments : [createVisualSegment(d.imageDuration || 4, d.getCurrentVisualAssetSnapshot())];
const available = MAX_TIMELINE_DURATION_SECONDS - getVisualSegmentsTotal(source);
if (available < MIN_VISUAL_SEGMENT_SECONDS) return void d.notify("视觉轨道已经达到 30 分钟上限");
- const asset = source[d.selectedVisualSegmentId && source.some((segment) => segment.id === d.selectedVisualSegmentId) ? d.selectedVisualSegmentIndex : source.length - 1] ?? d.getCurrentVisualAssetSnapshot();
+ const timeline = getVisualSegmentTimeline(source);
+ const playhead = Math.max(0, Math.min(getVisualSegmentsTotal(source), d.currentTime));
+ const activeIndex = timeline.findIndex((range) => playhead >= range.start && playhead < range.end);
+ const selectedIndex = d.selectedVisualSegmentId && source.some((segment) => segment.id === d.selectedVisualSegmentId)
+ ? d.selectedVisualSegmentIndex
+ : activeIndex >= 0 ? activeIndex : source.length - 1;
+ const asset = source[selectedIndex] ?? d.getCurrentVisualAssetSnapshot();
const segment = createVisualSegment(Math.min(IMAGE_SEGMENT_SECONDS, available), asset);
- return void d.commitVisualSegments([...source, segment], "已新增一个视觉片段", source.length);
+ const boundaryIndex = timeline.findIndex((range) => Math.abs(range.start - playhead) < 0.001);
+ if (boundaryIndex >= 0) {
+ const next = [...source]; next.splice(boundaryIndex, 0, segment);
+ return void d.commitVisualSegments(next, "已在播放头位置新增视觉片段", boundaryIndex);
+ }
+ const range = timeline[activeIndex]; const active = source[activeIndex];
+ if (range && active && playhead > range.start && playhead < range.end) {
+ const leftDuration = playhead - range.start; const rightDuration = range.end - playhead;
+ if (leftDuration < MIN_VISUAL_SEGMENT_SECONDS || rightDuration < MIN_VISUAL_SEGMENT_SECONDS) {
+ return void d.notify("播放头离片段边缘太近,请稍微移开后新增");
+ }
+ const playbackRate = active.type === "video" ? Math.max(0.25, Math.min(4, Number(active.playbackRate) || 1)) : 1;
+ const left = { ...active, id: makeId("visual"), duration: leftDuration,
+ sourceDuration: active.type === "video" ? leftDuration * playbackRate : active.sourceDuration };
+ const right = { ...active, id: makeId("visual"), duration: rightDuration,
+ sourceDuration: active.type === "video" ? rightDuration * playbackRate : active.sourceDuration,
+ sourceStart: active.type === "video" ? Math.max(0, Number(active.sourceStart) || 0) + leftDuration * playbackRate : Math.max(0, Number(active.sourceStart) || 0) };
+ const next = [...source]; next.splice(activeIndex, 1, left, segment, right);
+ return void d.commitVisualSegments(next, "已在播放头位置新增视觉片段", activeIndex + 1);
+ }
+ return void d.commitVisualSegments([...source, segment], "已在播放头位置新增视觉片段", source.length);
}
if (["audio", "source", "music"].includes(d.selectedTrack)) return void d.notify(d.selectedTrack === "music" ? "背景音乐暂不支持切片,请删除后重新上传" : d.selectedTrack === "source" ? "视频原声暂不支持切片,可删除后重新上传视频" : "音频片段由生成结果决定,请重新生成或复制 WAV");
- if (Number.isFinite(requestedStart)) {
- const start = Math.max(0, Math.min(MAX_TIMELINE_DURATION_SECONDS - 0.45, requestedStart));
- const segment = {
- id: makeId("caption"),
- text: "新的字幕片段",
- weight: 1,
- hidden: false,
- start,
- end: Math.min(MAX_TIMELINE_DURATION_SECONDS, start + 1.8),
- };
- const next = [...d.captionSegments, segment].sort((a, b) => (a.start || 0) - (b.start || 0));
- return void d.commitCaptionSegments(next, "已在点击位置新增字幕片段", next.findIndex((item) => item.id === segment.id));
- }
- const index = d.selectedSegmentId ? d.selectedSegmentIndex : d.focusedSegmentIndex;
- const previous = d.captionSegments[index]; const nextCaption = d.captionSegments[index + 1];
- const start = hasExplicitCaptionTiming(previous) ? previous.end : null;
- const end = start !== null && hasExplicitCaptionTiming(nextCaption) && nextCaption.start - start > 0.45 ? nextCaption.start
- : start !== null ? Math.min(MAX_TIMELINE_DURATION_SECONDS, start + 1.8) : null;
- const next = [...d.captionSegments]; next.splice(d.captionSegments.length ? index + 1 : 0, 0,
- { id: makeId("caption"), text: "新的字幕片段", weight: d.captionSegments[index]?.weight ?? 1, hidden: false,
- ...(start !== null && end !== null ? { start, end: Math.max(start + 0.45, end) } : {}) });
- d.commitCaptionSegments(next, "已新增字幕片段", index + 1);
+ const insertionTime = Number.isFinite(requestedStart) ? requestedStart : d.currentTime;
+ const start = Math.max(0, Math.min(MAX_TIMELINE_DURATION_SECONDS - 0.45, insertionTime));
+ const segment = { id: makeId("caption"), text: "新的字幕片段", weight: 1, hidden: false,
+ start, end: Math.min(MAX_TIMELINE_DURATION_SECONDS, start + 1.8) };
+ const next = [...d.captionSegments, segment].sort((a, b) => (Number(a.start) || 0) - (Number(b.start) || 0));
+ d.commitCaptionSegments(next, Number.isFinite(requestedStart) ? "已在点击位置新增字幕片段" : "已在播放头位置新增字幕片段", next.findIndex((item) => item.id === segment.id));
};
const handleRemoveSegment = () => {
if (d.selectedTrack === "sticker") return void deleteSticker();
diff --git a/src/lib/timelineSegmentCountActions.test.js b/src/lib/timelineSegmentCountActions.test.js
new file mode 100644
index 0000000..cf41d0d
--- /dev/null
+++ b/src/lib/timelineSegmentCountActions.test.js
@@ -0,0 +1,29 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { createTimelineSegmentCountActions } from "./timelineSegmentCountActions.js";
+
+describe("timeline segment insertion", () => {
+ it("adds a caption at the playhead", () => {
+ const commitCaptionSegments = vi.fn();
+ const controls = createTimelineSegmentCountActions({
+ selectedTrack: "caption", currentTime: 4.25, captionSegments: [], trackLocks: {},
+ commitCaptionSegments, notify: vi.fn(),
+ });
+ controls.handleAddSegment();
+ expect(commitCaptionSegments.mock.calls[0][0][0]).toMatchObject({ start: 4.25, end: 6.05 });
+ });
+
+ it("splits the active visual and inserts the new clip at the playhead", () => {
+ const commitVisualSegments = vi.fn();
+ const source = { id: "visual-1", type: "image", src: "image.png", duration: 8 };
+ const controls = createTimelineSegmentCountActions({
+ selectedTrack: "image", currentTime: 3, imageSrc: "image.png", imageDuration: 8,
+ visualSegments: [source], selectedVisualSegmentId: "visual-1", selectedVisualSegmentIndex: 0,
+ trackLocks: {}, commitVisualSegments, notify: vi.fn(), getCurrentVisualAssetSnapshot: () => source,
+ });
+ controls.handleAddSegment();
+ const [segments, , selectedIndex] = commitVisualSegments.mock.calls[0];
+ expect(segments.map((item) => item.duration)).toEqual([3, 2, 5]);
+ expect(selectedIndex).toBe(1);
+ });
+});
diff --git a/src/lib/timelineSnap.js b/src/lib/timelineSnap.js
new file mode 100644
index 0000000..047207f
--- /dev/null
+++ b/src/lib/timelineSnap.js
@@ -0,0 +1,44 @@
+import { getVisualSegmentTimeline, materializeCaptionTimings } from "./timeline.js";
+
+const addRange = (points, track, id, start, duration) => {
+ const safeStart = Math.max(0, Number(start) || 0);
+ const safeDuration = Math.max(0, Number(duration) || 0);
+ if (!(safeDuration > 0)) return;
+ points.push(
+ { time: safeStart, track, id, edge: "start" },
+ { time: safeStart + safeDuration, track, id, edge: "end" },
+ );
+};
+
+export function collectTimelineSnapPoints(d, exclude = {}) {
+ const points = [];
+ getVisualSegmentTimeline(d.visualSegments ?? []).forEach((range, index) => {
+ const segment = d.visualSegments[index];
+ addRange(points, "image", segment?.id, range.start, range.end - range.start);
+ });
+ materializeCaptionTimings(d.captionSegments ?? [], d.captionTargetDuration ?? d.timelineDuration ?? 0)
+ .forEach((segment) => addRange(points, "caption", segment.id, segment.start, segment.end - segment.start));
+ (d.stickerSegments ?? []).forEach((segment) => addRange(points, "sticker", segment.id, segment.start, segment.duration));
+ (d.audioSegments ?? []).forEach((segment) => addRange(points, "audio", segment.id, segment.start, segment.duration));
+ if (d.sourceAudioDuration > 0) addRange(points, "source", "source", d.sourceAudioStart, d.sourceAudioDuration);
+ if (d.musicDuration > 0) addRange(points, "music", "music", d.musicStart, d.musicDuration);
+ return points.filter((point) => point.track !== exclude.track || point.id !== exclude.id);
+}
+
+export function findClosestTimelineSnap(value, points, thresholdSeconds) {
+ let closest = null;
+ points.forEach((point) => {
+ const distance = Math.abs(point.time - value);
+ if (distance <= thresholdSeconds && (!closest || distance < closest.distance)) closest = { ...point, distance };
+ });
+ return closest;
+}
+
+export function snapTimelineRange(start, duration, points, thresholdSeconds) {
+ const startSnap = findClosestTimelineSnap(start, points, thresholdSeconds);
+ const endSnap = findClosestTimelineSnap(start + duration, points, thresholdSeconds);
+ const snap = !startSnap ? endSnap : !endSnap ? startSnap : startSnap.distance <= endSnap.distance ? startSnap : endSnap;
+ if (!snap) return { start, guide: null };
+ const snappedStart = snap === endSnap ? snap.time - duration : snap.time;
+ return { start: snappedStart, guide: { time: snap.time, label: `${snap.time.toFixed(2)}s` } };
+}
diff --git a/src/lib/timelineSnap.test.js b/src/lib/timelineSnap.test.js
new file mode 100644
index 0000000..79e1f47
--- /dev/null
+++ b/src/lib/timelineSnap.test.js
@@ -0,0 +1,23 @@
+import { describe, expect, it } from "vitest";
+
+import { collectTimelineSnapPoints, snapTimelineRange } from "./timelineSnap.js";
+
+describe("cross-track timeline snapping", () => {
+ it("collects start and end boundaries from every timed track", () => {
+ const points = collectTimelineSnapPoints({
+ visualSegments: [{ id: "visual", duration: 2 }],
+ captionSegments: [{ id: "caption", text: "x", start: 3, end: 4 }],
+ stickerSegments: [{ id: "sticker", start: 5, duration: 1 }],
+ audioSegments: [{ id: "voice", start: 7, duration: 2 }],
+ sourceAudioStart: 10, sourceAudioDuration: 2,
+ musicStart: 13, musicDuration: 2,
+ timelineDuration: 20,
+ });
+ expect(points.map((point) => point.time)).toEqual(expect.arrayContaining([0, 2, 3, 4, 5, 6, 7, 9, 10, 12, 13, 15]));
+ });
+
+ it("snaps either moving edge to the closest foreign boundary", () => {
+ expect(snapTimelineRange(2.94, 1, [{ time: 3, track: "caption", id: "a" }], 0.1)).toMatchObject({ start: 3, guide: { time: 3 } });
+ expect(snapTimelineRange(1.96, 1, [{ time: 3, track: "audio", id: "b" }], 0.1)).toMatchObject({ start: 2, guide: { time: 3 } });
+ });
+});
diff --git a/src/lib/timelineViewModel.js b/src/lib/timelineViewModel.js
index db292b7..ac65c4a 100644
--- a/src/lib/timelineViewModel.js
+++ b/src/lib/timelineViewModel.js
@@ -5,6 +5,10 @@ import {
reorderTimelineItems,
} from "./timeline.js";
+export function shouldShowStickerTrack({ stickerSegments = [], assetDropTargetTrack = "", assetDragPreview = null, draggedAsset = null } = {}) {
+ return stickerSegments.length > 0 || assetDropTargetTrack === "sticker" || assetDragPreview?.type === "sticker" || draggedAsset?.type === "sticker";
+}
+
export function createTimelineViewModel(d) {
const progressPercent = Math.max(0, Math.min(100, d.progress));
const playheadPercent = Math.max(
@@ -23,12 +27,12 @@ export function createTimelineViewModel(d) {
: [];
const activeTimelineClipDrag = d.timelineClipDrag?.dragging ? d.timelineClipDrag : null;
const draggedAsset = d.draggedAssetId ? d.findAssetById(d.draggedAssetId) : null;
- const showStickerTrack =
- d.stickerSegments.length > 0 ||
- d.selectedTrack === "sticker" ||
- d.assetDropTargetTrack === "sticker" ||
- d.assetDragPreview?.type === "sticker" ||
- draggedAsset?.type === "sticker";
+ const showStickerTrack = shouldShowStickerTrack({
+ stickerSegments: d.stickerSegments,
+ assetDropTargetTrack: d.assetDropTargetTrack,
+ assetDragPreview: d.assetDragPreview,
+ draggedAsset,
+ });
const displayedVisualSegments = activeTimelineClipDrag?.track === "image"
? reorderTimelineItems(
renderedVisualSegments,
@@ -38,7 +42,7 @@ export function createTimelineViewModel(d) {
: renderedVisualSegments;
const renderedVisualTimeline = getVisualSegmentTimeline(displayedVisualSegments);
const displayedCaptionSegments = activeTimelineClipDrag?.track === "caption"
- ? activeTimelineClipDrag.mode === "move"
+ ? activeTimelineClipDrag.mode === "move" || activeTimelineClipDrag.mode?.startsWith("resize-")
? activeTimelineClipDrag.previewSegments
: reorderTimelineItems(
d.captionSegments,
diff --git a/src/lib/timelineViewModel.test.js b/src/lib/timelineViewModel.test.js
new file mode 100644
index 0000000..9093b7f
--- /dev/null
+++ b/src/lib/timelineViewModel.test.js
@@ -0,0 +1,13 @@
+import { describe, expect, it } from "vitest";
+import { shouldShowStickerTrack } from "./timelineViewModel.js";
+
+describe("sticker track visibility", () => {
+ it("hides an empty sticker track even if it was previously selected", () => {
+ expect(shouldShowStickerTrack({ stickerSegments: [] })).toBe(false);
+ });
+
+ it("shows the sticker track for content and active sticker drags", () => {
+ expect(shouldShowStickerTrack({ stickerSegments: [{ id: "one" }] })).toBe(true);
+ expect(shouldShowStickerTrack({ assetDragPreview: { type: "sticker" } })).toBe(true);
+ });
+});
diff --git a/src/lib/visualClipAnimations.js b/src/lib/visualClipAnimations.js
new file mode 100644
index 0000000..4bf0b8e
--- /dev/null
+++ b/src/lib/visualClipAnimations.js
@@ -0,0 +1,57 @@
+export const VISUAL_CLIP_ANIMATION_OPTIONS = [
+ { id: "none", labelKey: "visualAnimationNone" },
+ { id: "fade", labelKey: "visualAnimationFade" },
+ { id: "zoom", labelKey: "visualAnimationZoom" },
+ { id: "slide-left", labelKey: "visualAnimationSlideLeft" },
+ { id: "slide-up", labelKey: "visualAnimationSlideUp" },
+];
+
+export const DEFAULT_VISUAL_ANIMATION_DURATION = 0.6;
+
+function clamp01(value) {
+ return Math.max(0, Math.min(1, Number(value) || 0));
+}
+
+function easeOutCubic(value) {
+ const inverse = 1 - clamp01(value);
+ return 1 - inverse * inverse * inverse;
+}
+
+function animationTransform(id, amount) {
+ const remaining = 1 - easeOutCubic(amount);
+ if (id === "fade") return { x: 0, y: 0, scale: 1, opacity: 1 - remaining };
+ if (id === "zoom") return { x: 0, y: 0, scale: 1 - remaining * 0.18, opacity: 1 };
+ if (id === "slide-left") return { x: -18 * remaining, y: 0, scale: 1, opacity: 1 };
+ if (id === "slide-up") return { x: 0, y: 18 * remaining, scale: 1, opacity: 1 };
+ return { x: 0, y: 0, scale: 1, opacity: 1 };
+}
+
+export function normalizeVisualClipAnimation(animation = {}) {
+ const normalizePhase = (phase) => ({
+ id: phase?.id || "none",
+ duration: Math.max(0.1, Math.min(3, Number(phase?.duration) || DEFAULT_VISUAL_ANIMATION_DURATION)),
+ });
+ return { in: normalizePhase(animation.in), out: normalizePhase(animation.out) };
+}
+
+export function resolveVisualClipAnimation(animation, localTime, clipDuration) {
+ const normalized = normalizeVisualClipAnimation(animation);
+ const safeDuration = Math.max(0.01, Number(clipDuration) || 0.01);
+ const safeTime = Math.max(0, Math.min(safeDuration, Number(localTime) || 0));
+ let result = { x: 0, y: 0, scale: 1, opacity: 1 };
+ if (normalized.in.id !== "none" && safeTime < normalized.in.duration) {
+ result = animationTransform(normalized.in.id, safeTime / normalized.in.duration);
+ }
+ if (normalized.out.id !== "none" && safeTime > safeDuration - normalized.out.duration) {
+ const outProgress = (safeDuration - safeTime) / normalized.out.duration;
+ const outgoing = animationTransform(normalized.out.id, outProgress);
+ result = {
+ x: result.x + outgoing.x,
+ y: result.y + outgoing.y,
+ scale: result.scale * outgoing.scale,
+ opacity: result.opacity * outgoing.opacity,
+ };
+ }
+ return result;
+}
+
diff --git a/src/lib/visualClipAnimations.test.js b/src/lib/visualClipAnimations.test.js
new file mode 100644
index 0000000..576a059
--- /dev/null
+++ b/src/lib/visualClipAnimations.test.js
@@ -0,0 +1,16 @@
+import { describe, expect, it } from "vitest";
+import { resolveVisualClipAnimation } from "./visualClipAnimations.js";
+
+describe("visual clip animations", () => {
+ it("resolves an entrance animation only near the clip start", () => {
+ const animation = { in: { id: "zoom", duration: 1 } };
+ expect(resolveVisualClipAnimation(animation, 0, 5).scale).toBeCloseTo(0.82);
+ expect(resolveVisualClipAnimation(animation, 1.5, 5).scale).toBe(1);
+ });
+
+ it("reverses an exit animation near the clip end", () => {
+ const animation = { out: { id: "fade", duration: 1 } };
+ expect(resolveVisualClipAnimation(animation, 3, 5).opacity).toBe(1);
+ expect(resolveVisualClipAnimation(animation, 5, 5).opacity).toBeCloseTo(0);
+ });
+});
diff --git a/src/lib/visualTimelineActions.js b/src/lib/visualTimelineActions.js
index c957a0e..26dbce7 100644
--- a/src/lib/visualTimelineActions.js
+++ b/src/lib/visualTimelineActions.js
@@ -114,7 +114,7 @@ export function createVisualTimelineActions(d) {
sourceSegments.length,
);
d.seekTo(totalDuration);
- if (asset.type === "video") d.extractVideoSourceAudio(asset, totalDuration);
+ if (asset.type === "video") d.extractVideoSourceAudio(asset, totalDuration, { append: true });
}
function updateVisualAssetInTimeline(assetId, updates) {
diff --git a/src/styles.css b/src/styles.css
index 126d4b3..4db0e8d 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -1518,6 +1518,33 @@ button:disabled {
.audio-property-slider b { color: #dce7eb; font-weight: 650; }.audio-property-slider em { color: #69e4d9; font-style: normal; }
.audio-property-slider input { width: 100%; accent-color: #35ead9; }
.audio-context-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }.audio-context-actions button { display: flex; align-items: center; justify-content: center; gap: 6px; min-height: 36px; }.audio-context-actions .is-danger { color: #ff969b; }
+.audio-download-actions,
+.audio-delete-actions {
+ display: grid;
+ gap: 9px;
+}
+
+.audio-download-actions {
+ margin-top: 10px;
+}
+
+.audio-delete-actions {
+ gap: 8px;
+ margin-top: 7px;
+ padding-top: 13px;
+ border-top: 1px solid rgba(255, 255, 255, 0.075);
+}
+
+.audio-download-actions > button,
+.audio-delete-actions > button {
+ min-height: 40px;
+}
+
+.audio-delete-actions .is-danger:not(:disabled) {
+ color: #ff9da5;
+ border-color: rgba(255, 103, 116, 0.22);
+ background: rgba(255, 82, 97, 0.055);
+}
.avatar-context-hero { display: grid; grid-template-columns: 42px minmax(0, 1fr); gap: 10px; align-items: start; padding: 13px; border: 1px solid rgba(109, 137, 255, .22); border-radius: 10px; background: linear-gradient(135deg, rgba(85, 112, 235, .15), rgba(53, 234, 217, .05)); }
.avatar-context-hero > span { display: grid; place-items: center; width: 42px; height: 42px; border-radius: 10px; color: #b4c7ff; background: rgba(108, 137, 255, .18); }
.avatar-context-hero > div { display: grid; gap: 4px; }
@@ -1841,9 +1868,14 @@ button:disabled {
.caption-tool-panel::-webkit-scrollbar { display: none; width: 0; height: 0; }
+.caption-tool-panel > .segmented {
+ gap: 6px;
+}
+
.caption-tool-panel > .segmented button {
min-height: 32px;
- padding: 5px 8px;
+ border-radius: 6px;
+ padding: 4px 8px;
font-size: 12px;
line-height: 1;
}
@@ -2155,7 +2187,7 @@ button:disabled {
.visual-effects-panel { gap: 12px; }
.visual-effects-panel > .tool-panel { padding: 0; }
.visual-effects-panel > .tool-panel > h2 { font-size: 13px; color: #9ba9b2; }
-.visual-context-tabs { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 4px; padding: 4px; border: 1px solid rgba(255,255,255,.075); border-radius: 9px; background: rgba(4,10,14,.42); }
+.visual-context-tabs { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 4px; padding: 4px; border: 1px solid rgba(255,255,255,.075); border-radius: 9px; background: rgba(4,10,14,.42); }
.visual-context-tabs button { min-width: 0; border: 0; border-radius: 6px; padding: 8px 3px; color: #82919b; background: transparent; font-size: 11px; cursor: pointer; }
.visual-context-tabs button:hover { color: #c8d8de; background: rgba(255,255,255,.04); }
.visual-context-tabs button.is-active { color: #dffffb; background: rgba(53,234,217,.13); box-shadow: inset 0 0 0 1px rgba(53,234,217,.38); }
@@ -2177,6 +2209,23 @@ button:disabled {
.visual-speed-summary strong { color: #d9e6eb; font-size: 12px; font-variant-numeric: tabular-nums; }
.visual-speed-hint { margin: 0; color: #7f8d97; font-size: 10px; line-height: 1.55; }
.visual-speed-empty { min-height: 92px; }
+.visual-animation-card { gap: 11px; }
+.visual-animation-sections { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 5px; padding: 3px; border-radius: 7px; background: rgba(4,10,14,.42); }
+.visual-animation-sections button { border: 0; border-radius: 5px; padding: 7px; color: #8998a1; background: transparent; font-size: 11px; cursor: pointer; }
+.visual-animation-sections button.is-active { color: #dffffb; background: rgba(53,234,217,.13); box-shadow: inset 0 0 0 1px rgba(53,234,217,.34); }
+.visual-animation-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 7px; }
+.visual-animation-grid > button { display: grid; grid-template-columns: 38px minmax(0,1fr); align-items: center; gap: 8px; min-width: 0; border: 1px solid rgba(255,255,255,.08); border-radius: 7px; padding: 7px; color: #aebbc3; background: rgba(255,255,255,.035); text-align: left; cursor: pointer; }
+.visual-animation-grid > button:hover { border-color: rgba(53,234,217,.38); color: #e2fffc; background: rgba(53,234,217,.07); }
+.visual-animation-grid > button.is-active { border-color: #35ead9; color: #effffd; background: rgba(53,234,217,.12); }
+.visual-animation-grid strong { min-width: 0; overflow: hidden; font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }
+.visual-animation-swatch { position: relative; display: grid; place-items: center; width: 38px; height: 28px; overflow: hidden; border-radius: 5px; background: linear-gradient(135deg, rgba(103,181,255,.26), rgba(53,234,217,.18)); }
+.visual-animation-swatch i { width: 18px; height: 14px; border: 1px solid rgba(222,255,251,.78); border-radius: 2px; background: rgba(222,255,251,.16); }
+.visual-animation-swatch.is-none i { width: 22px; height: 1px; border: 0; background: rgba(222,255,251,.6); transform: rotate(-32deg); }
+.visual-animation-swatch.is-fade i { opacity: .42; }
+.visual-animation-swatch.is-zoom i { transform: scale(.72); box-shadow: 0 0 0 3px rgba(222,255,251,.12); }
+.visual-animation-swatch.is-slide-left i { transform: translateX(-7px); }
+.visual-animation-swatch.is-slide-up i { transform: translateY(6px); }
+.visual-animation-duration { margin-top: 1px; }
.remaster-card { gap: 11px; }
.remaster-model-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 10px; border-radius: 7px; background: rgba(5,10,14,.38); }
.remaster-model-row > span { display: grid; gap: 3px; min-width: 0; }
@@ -2628,20 +2677,44 @@ button:disabled {
.sticker-overlay {
position: absolute;
- top: 12%;
- right: 12%;
z-index: 3;
pointer-events: none;
}
-.sticker-overlay.is-image {
+.sticker-transform-box {
width: clamp(76px, 18%, 142px);
- height: auto;
- object-fit: contain;
+ aspect-ratio: 1;
background: transparent;
- filter: drop-shadow(0 12px 18px rgba(0, 0, 0, 0.3));
+ cursor: move;
+ pointer-events: auto;
+ touch-action: none;
}
+.sticker-overlay-image { display: block; width: 100%; height: 100%; object-fit: contain; background: transparent; }
+
+.sticker-overlay.is-editable {
+ outline: 1px dashed rgba(53, 234, 217, 0.8);
+ outline-offset: 4px;
+}
+
+.sticker-rotate-handle,
+.sticker-scale-handle { position: absolute; z-index: 2; width: 14px; height: 14px; border: 2px solid #081315; border-radius: 50%; padding: 0; background: #35ead9; box-shadow: 0 0 0 1px rgba(255,255,255,.72); }
+.sticker-rotate-handle { top: -23px; left: 50%; cursor: grab; transform: translateX(-50%); }
+.sticker-rotate-handle::after { position: absolute; top: 11px; left: 5px; width: 2px; height: 10px; background: #35ead9; content: ""; }
+.sticker-scale-handle { right: -8px; bottom: -8px; cursor: nwse-resize; }
+
+.sticker-properties-panel { display: grid; gap: 14px; }
+.sticker-properties-preview { display: grid; place-items: center; min-height: 92px; border: 1px solid rgba(255,255,255,.07); border-radius: 9px; background: rgba(255,255,255,.025); }
+.sticker-properties-preview img { width: 70px; height: 70px; object-fit: contain; }
+.sticker-property-field { display: grid; gap: 7px; }
+.sticker-property-field > div { display: flex; align-items: center; justify-content: space-between; color: #9aa8b4; font-size: 12px; }
+.sticker-property-field strong { color: #e5f0f3; font-variant-numeric: tabular-nums; }
+.sticker-property-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 9px; }
+.sticker-property-grid label { display: grid; gap: 5px; color: #8f9da8; font-size: 11px; }
+.sticker-property-grid input { width: 100%; min-width: 0; height: 34px; border: 1px solid rgba(255,255,255,.08); border-radius: 6px; padding: 0 8px; color: #e9f4f5; background: rgba(255,255,255,.04); }
+.sticker-delete-button { display: inline-flex; align-items: center; justify-content: center; justify-self: end; gap: 6px; min-height: 30px; width: auto; border: 1px solid rgba(255,112,122,.2); border-radius: 6px; padding: 5px 11px; color: #ff9ca3; background: rgba(255,90,102,.07); font-size: 11px; cursor: pointer; }
+.sticker-delete-button:hover { border-color: rgba(255,112,122,.38); background: rgba(255,90,102,.11); }
+
.sticker-overlay.is-label {
border-radius: 7px;
padding: 9px 15px;
@@ -3738,6 +3811,8 @@ button:disabled {
}
.image-thumbnails.is-video {
+ grid-template-columns: repeat(var(--video-thumbnail-count, 1), minmax(0, 1fr));
+ grid-auto-columns: unset;
gap: 1px;
background: #05070a;
}
@@ -3917,6 +3992,29 @@ button:disabled {
0 0 0 1px rgba(103, 181, 255, 0.4);
}
+.caption-segment-label {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.caption-resize-handle {
+ position: absolute;
+ z-index: 2;
+ top: 0;
+ bottom: 0;
+ width: 10px;
+ cursor: ew-resize;
+ opacity: 0;
+ transition: opacity 120ms ease, background 120ms ease;
+}
+
+.caption-resize-handle.is-start { left: 0; }
+.caption-resize-handle.is-end { right: 0; }
+.caption-segment:hover .caption-resize-handle,
+.caption-segment.is-selected-segment .caption-resize-handle { opacity: 1; }
+.caption-resize-handle:hover { background: rgba(255, 255, 255, 0.22); }
+
.sticker-track {
padding: 5px 0;
}