Improve editor timeline and media UX (#14)

Co-authored-by: haixin.yang <haixin.yang@weimob.com>
This commit is contained in:
Martin Delophyandhaixin.yang authored and GitHub committed 2026-07-17 13:49:40 +08:00
1 parent a6b7a9e51b
commit 00c454dbb7
31 files changed
+981 -172

No files matched your search

+45 -9
View File
@@ -199,7 +199,7 @@ export function App() {
captionTargetDuration, captionTimeline, currentCaption, currentCaptionSegment,
currentSegmentIndex, currentStickerSegment, currentStickerSegmentIndex,
currentVisualRange, currentVisualSegment, currentVisualSegmentIndex, estimatedDuration,
focusedSegmentIndex, getStickerDragAsset, peaks, previewSticker,
focusedSegmentIndex, getStickerDragAsset, peaks, previewSticker, previewStickers,
previewVisionBaseAnalysis, previewVisionKey, previewVisionRecord, previewVisualLocalTime,
previewVisualRange, previewVisualSegment, previewVisualSegmentIndex,
previewVisualSourceTime, previewVisualSrc, previewVisualType, ratio, segments,
@@ -238,6 +238,7 @@ export function App() {
const previewFrameSize = usePreviewFrameSize(previewShellRef, ratio, compactRail);
const selectedVisualSegment = visualSegments[selectedVisualSegmentIndex] ?? previewVisualSegment ?? null;
const selectedVisualRange = visualTimeline[selectedVisualSegmentIndex] ?? previewVisualRange;
const [visualAnimationPreview, setVisualAnimationPreview] = useState(null);
const visualLocalTime = Math.max(0, Math.min(
selectedVisualSegment?.duration ?? 0,
currentTime - (selectedVisualRange?.start ?? 0),
@@ -253,6 +254,7 @@ export function App() {
if (change.removePropertyKeyframe) return { ...item, keyframes: removeVisualPropertyKeyframe(item.keyframes, change.removePropertyKeyframe.time, change.removePropertyKeyframe.key) };
if (Number.isFinite(change.removeKeyframeAt)) return { ...item, keyframes: (item.keyframes ?? []).filter((frame) => Math.abs(frame.time - change.removeKeyframeAt) > 0.04) };
if (change.mask) return { ...item, mask: change.mask };
if (change.animation) return { ...item, animation: change.animation };
if (typeof change.enhancementEnabled === "boolean" && item.enhancement) {
if (item.enhancement.mode === "remaster-drunet-full") {
const source = change.enhancementEnabled ? item.enhancement.processed : item.enhancement.original;
@@ -311,7 +313,7 @@ export function App() {
handleAssetPointerDown, handleStickerClick, handleTrackAssetDragLeave,
handleTrackAssetDragOver, triggerAssetDropPulse,
} = createAssetDragControls({
applyAssetToTrack: (...args) => applyAssetToTrack(...args), assetDropPulseTimerRef, builtInAssets, draggedAssetId,
addStickerAssetToTimeline: (...args) => addStickerAssetToTimeline(...args), applyAssetToTrack: (...args) => applyAssetToTrack(...args), assetDropPulseTimerRef, builtInAssets, currentTime, draggedAssetId,
draggedAssetIdRef, getStickerDragAsset, notify, pointerAssetDragRef,
setAssetDragPreview, setAssetDropPosition, setAssetDropPulseTrack,
setAssetDropTargetTrack, setDraggedAssetId, setSelectedLibraryAssetId,
@@ -396,8 +398,26 @@ export function App() {
} = createStickerTimelineActions({
estimatedDuration, notify, seekTo: (...args) => seekTo(...args), setActiveTool,
setSelectedStickerId, setSelectedStickerSegmentId, setSelectedTrack,
setStickerSegments, stickerSegments, timelineDurationRef, trackLocks,
setStickerSegments, stickerSegments, t, timelineDurationRef, trackLocks,
});
const selectedStickerSegment = stickerSegments.find((segment) => segment.id === selectedStickerSegmentId) ?? currentStickerSegment;
const updateSelectedStickerSegment = (change) => {
if (!selectedStickerSegment?.id) return;
setStickerSegments((segments) => segments.map((segment) => segment.id === selectedStickerSegment.id ? { ...segment, ...change } : segment));
};
const updateCanvasStickerSegment = (segmentId, change) => {
if (!segmentId) return;
setStickerSegments((segments) => segments.map((segment) => segment.id === segmentId ? { ...segment, ...change } : segment));
};
const selectCanvasStickerSegment = (segmentId) => {
if (!segmentId) return;
setSelectedStickerSegmentId(segmentId);
setSelectedTrack("sticker");
};
const deleteSelectedStickerSegment = () => {
if (!selectedStickerSegment?.id) return;
commitStickerSegments(stickerSegments.filter((segment) => segment.id !== selectedStickerSegment.id), "已删除贴纸片段");
};
const { generateAvatarAcceptanceFrame, openAvatarPanel } = useAvatarGeneration({
audioBlob, audioDuration, avatarJob, avatarMotionCacheRef, avatarMotionWorkerRef,
@@ -504,12 +524,12 @@ export function App() {
});
const { startAudioSegmentMove, startMusicMove, startSourceAudioMove, startStickerSegmentMove } = createTimelineMoveControls({
audioSegments, captionSegments, estimatedDuration, notify, seekTo, setActiveTool,
audioSegments, captionSegments, captionTargetDuration, estimatedDuration, notify, seekTo, setActiveTool,
setAudioSegments, setCaptionSegments, setSelectedAudioSegmentId, setSelectedStickerId,
setSelectedStickerSegmentId, setSelectedTrack, setStickerSegments, setTimelineHorizon,
setMusicStart, setSourceAudioLinked, setSourceAudioStart, musicDuration, musicStart,
sourceAudioDuration, sourceAudioStart, stickerSegments, suppressTimelineClipClickRef, t, timelineDurationRef,
trackLocks, trackScrollRef, pauseForTimelineEdit,
trackLocks, trackScrollRef, pauseForTimelineEdit, visualSegments, setSnapGuide,
});
const startImageResize = createImageResizeControl({
@@ -523,6 +543,7 @@ export function App() {
const extractVideoSourceAudio = useSourceAudioExtraction({
clearSourceAudioTrack, notify, replaceSourceAudio, setProgress, setStatus, setStatusText,
setVisualSegments, sourceAudioBlob, sourceAudioDuration,
});
const generateCaptionsFromSourceAudio = useAutoCaptions({
@@ -602,11 +623,12 @@ export function App() {
videoBitsPerSecond: getExportBitrate(Number(exportSettings.resolution), exportSettings.quality, exportSettings.frameRate),
},
});
const { startTimelineClipDrag } = createTimelineReorderControls({
captionSegments, captionTargetDuration, commitCaptionSegments, commitVisualSegments,
const { startCaptionResize, startTimelineClipDrag } = createTimelineReorderControls({
audioSegments, captionSegments, captionTargetDuration, commitCaptionSegments, commitVisualSegments,
notify, renderedVisualSegments, seekTo, setSelectedSegmentId, setSelectedTrack,
setSelectedVisualSegmentId, setTimelineClipDrag, suppressTimelineClipClickRef,
timelineClipDragRef, timelineDuration, trackLocks, visualSegments, pauseForTimelineEdit,
stickerSegments, sourceAudioDuration, sourceAudioStart, musicDuration, musicStart, setSnapGuide,
});
return (
@@ -701,8 +723,12 @@ export function App() {
previewVisualRenderSrc={previewVisualRenderSrc}
previewVisionMaskUrl={previewVisionMaskUrl}
previewVisualType={previewVisualType}
visualEffects={previewVisualSegment}
visualLocalTime={previewVisualLocalTime}
visualEffects={visualAnimationPreview?.segmentId && visualAnimationPreview.segmentId === previewVisualSegment?.id
? { ...previewVisualSegment, animation: visualAnimationPreview.animation }
: previewVisualSegment}
visualLocalTime={visualAnimationPreview?.segmentId && visualAnimationPreview.segmentId === previewVisualSegment?.id
? visualAnimationPreview.localTime
: previewVisualLocalTime}
visualMaskEditable={selectedTrack === "image" && Boolean(selectedVisualSegment)}
onUpdateVisualMask={(mask) => updateSelectedVisualEffects({ mask })}
previewRatio={previewRatio}
@@ -733,6 +759,11 @@ export function App() {
startCaptionDrag={startCaptionDrag}
setActiveTool={setActiveTool}
selectedSticker={previewSticker}
stickers={previewStickers}
selectedStickerId={selectedStickerSegment?.id ?? ""}
stickerEditable
onSelectSticker={selectCanvasStickerSegment}
onUpdateSticker={updateCanvasStickerSegment}
isPlaying={isPlaying}
canPreview={canPreview}
handlePlayToggle={handlePlayToggle}
@@ -817,9 +848,13 @@ export function App() {
toggleAudioSegmentReverse={toggleAudioSegmentReverse}
deleteAudioSegment={deleteAudioSegment}
selectedVisualSegment={selectedVisualSegment}
selectedStickerSegment={selectedStickerSegment}
updateStickerSegment={updateSelectedStickerSegment}
deleteStickerSegment={deleteSelectedStickerSegment}
visualLocalTime={visualLocalTime}
visualTimelineStart={selectedVisualRange?.start ?? 0}
updateSelectedVisualEffects={updateSelectedVisualEffects}
onPreviewAnimation={setVisualAnimationPreview}
selectedFilterId={selectedFilterId}
setSelectedFilterId={setSelectedFilterId}
trOption={trOption}
@@ -882,6 +917,7 @@ export function App() {
seekTo={seekTo}
suppressTimelineClipClickRef={suppressTimelineClipClickRef}
startTimelineClipDrag={startTimelineClipDrag}
startCaptionResize={startCaptionResize}
startImageResize={startImageResize}
startStickerSegmentMove={startStickerSegmentMove}
displayedCaptionSegments={displayedCaptionSegments}
+81 -8
View File
@@ -11,6 +11,7 @@ import {
import { formatTime } from "../lib/timeline.js";
import { getVisualMaskInsets, getVisualMaskSvgDataUrl, resolveVisualTransform } from "../lib/visualEffects.js";
import { resolveVisualClipAnimation } from "../lib/visualClipAnimations.js";
import { CaptionOverlay } from "./CaptionOverlay.jsx";
import { IconButton } from "./ui.jsx";
@@ -47,6 +48,11 @@ export function PreviewStage({
startCaptionDrag,
setActiveTool,
selectedSticker,
stickers = [],
selectedStickerId = "",
stickerEditable = false,
onSelectSticker,
onUpdateSticker,
isPlaying,
canPreview,
handlePlayToggle,
@@ -61,12 +67,14 @@ export function PreviewStage({
getDraggedAsset,
applyAssetToTrack,
}) {
const hasStickerOverlay = Boolean(selectedSticker?.src || selectedSticker?.text);
const visibleStickers = stickers.length ? stickers : selectedSticker?.src || selectedSticker?.text ? [selectedSticker] : [];
const hasStickerOverlay = visibleStickers.some((sticker) => sticker?.src || sticker?.text);
const hasPreviewContent = Boolean(previewVisualSrc || hasStickerOverlay);
const renderedVisualSrc = previewVisualRenderSrc || previewVisualSrc;
const activeObjectFit = visualObjectFit || fitMode;
const activeObjectPosition = visualObjectPosition || "50% 50%";
const visualTransform = resolveVisualTransform(visualEffects?.keyframes, visualLocalTime);
const visualAnimation = resolveVisualClipAnimation(visualEffects?.animation, visualLocalTime, visualEffects?.duration);
const visualMask = visualEffects?.mask ?? {};
const enhancement = visualEffects?.enhancement ?? null;
const showRemasterPreview = Boolean(
@@ -86,8 +94,8 @@ export function PreviewStage({
const maskInsets = getVisualMaskInsets(visualMask);
const roundedRadius = Math.min(maskWidth / 100 * frameWidth, maskHeight / 100 * frameHeight) * (Number.isFinite(visualMask.cornerRadius) ? visualMask.cornerRadius : 12) / 100;
const visualTransformStyle = {
transform: `translate(${visualTransform.x}%, ${visualTransform.y}%) scale(${visualTransform.scale}) rotate(${visualTransform.rotation}deg)`,
opacity: visualTransform.opacity,
transform: `translate(${visualTransform.x + visualAnimation.x}%, ${visualTransform.y + visualAnimation.y}%) scale(${visualTransform.scale * visualAnimation.scale}) rotate(${visualTransform.rotation}deg)`,
opacity: visualTransform.opacity * visualAnimation.opacity,
};
const visualMaskStyle = {
clipPath: ["rectangle", "rounded"].includes(visualMask.type) && !usesAlphaMask
@@ -122,6 +130,52 @@ export function PreviewStage({
const end = () => { window.removeEventListener("pointermove", move); window.removeEventListener("pointerup", end); };
window.addEventListener("pointermove", move); window.addEventListener("pointerup", end, { once: true });
};
const startStickerDrag = (event, selectedSticker) => {
if (!stickerEditable || !onUpdateSticker || !selectedSticker) return;
const frame = previewCanvasRef.current;
if (!frame) return;
event.preventDefault(); event.stopPropagation();
const rect = frame.getBoundingClientRect();
const startX = event.clientX; const startY = event.clientY;
const initialX = Number.isFinite(selectedSticker.x) ? selectedSticker.x : 82;
const initialY = Number.isFinite(selectedSticker.y) ? selectedSticker.y : 20;
onSelectSticker?.(selectedSticker.id);
const round = (value) => Math.round(value * 100) / 100;
const move = (moveEvent) => onUpdateSticker(selectedSticker.id, {
x: round(Math.max(4, Math.min(96, initialX + ((moveEvent.clientX - startX) / Math.max(1, rect.width)) * 100))),
y: round(Math.max(4, Math.min(96, initialY + ((moveEvent.clientY - startY) / Math.max(1, rect.height)) * 100))),
});
const end = () => { window.removeEventListener("pointermove", move); window.removeEventListener("pointerup", end); };
window.addEventListener("pointermove", move); window.addEventListener("pointerup", end, { once: true });
};
const startStickerTransform = (event, mode, selectedSticker) => {
if (!stickerEditable || !onUpdateSticker || !selectedSticker) return;
const sticker = event.currentTarget.closest(".sticker-transform-box");
if (!sticker) return;
event.preventDefault(); event.stopPropagation();
const stickerRect = sticker.getBoundingClientRect();
const centerX = stickerRect.left + stickerRect.width / 2;
const centerY = stickerRect.top + stickerRect.height / 2;
const startX = event.clientX; const startY = event.clientY;
const initialScale = Number.isFinite(selectedSticker.scale) ? selectedSticker.scale : 1;
const initialRotation = Number.isFinite(selectedSticker.rotation) ? selectedSticker.rotation : 0;
const initialAngle = Math.atan2(startY - centerY, startX - centerX) * 180 / Math.PI;
const round = (value) => Math.round(value * 100) / 100;
const move = (moveEvent) => {
if (mode === "scale") {
const delta = ((moveEvent.clientX - startX) + (moveEvent.clientY - startY)) / Math.max(60, stickerRect.width + stickerRect.height);
onUpdateSticker(selectedSticker.id, { scale: round(Math.max(0.2, Math.min(3, initialScale + delta * 2))) });
} else {
const angle = Math.atan2(moveEvent.clientY - centerY, moveEvent.clientX - centerX) * 180 / Math.PI;
let rotation = initialRotation + angle - initialAngle;
while (rotation > 180) rotation -= 360;
while (rotation < -180) rotation += 360;
onUpdateSticker(selectedSticker.id, { rotation: round(rotation) });
}
};
const end = () => { window.removeEventListener("pointermove", move); window.removeEventListener("pointerup", end); };
window.addEventListener("pointermove", move); window.addEventListener("pointerup", end, { once: true });
};
useEffect(() => {
const video = previewVideoRef.current;
@@ -263,11 +317,30 @@ export function PreviewStage({
onDoubleClick={() => setActiveTool("caption")}
/>
) : null}
{selectedSticker.src ? (
<img className="sticker-overlay is-image" src={selectedSticker.src} alt="" draggable={false} />
) : selectedSticker.text ? (
<div className="sticker-overlay is-label">{selectedSticker.text}</div>
) : null}
{visibleStickers.map((sticker, index) => {
const isEditable = stickerEditable && sticker.id === selectedStickerId;
return sticker.src ? (
<div
key={sticker.id || `${sticker.src}-${index}`}
className={`sticker-overlay sticker-transform-box ${isEditable ? "is-editable" : ""}`}
onPointerDown={(event) => startStickerDrag(event, sticker)}
style={{
left: `${Number.isFinite(sticker.x) ? sticker.x : 82}%`,
top: `${Number.isFinite(sticker.y) ? sticker.y : 20}%`,
transform: `translate(-50%, -50%) scale(${Number.isFinite(sticker.scale) ? sticker.scale : 1}) rotate(${Number.isFinite(sticker.rotation) ? sticker.rotation : 0}deg)`,
opacity: Number.isFinite(sticker.opacity) ? sticker.opacity : 1,
}}
>
<img className="sticker-overlay-image" src={sticker.src} alt="" draggable={false} />
{isEditable ? <>
<button className="sticker-rotate-handle" type="button" aria-label={t("visualRotation", "旋转")} onPointerDown={(event) => startStickerTransform(event, "rotate", sticker)} />
<button className="sticker-scale-handle" type="button" aria-label={t("visualScale", "缩放")} onPointerDown={(event) => startStickerTransform(event, "scale", sticker)} />
</> : null}
</div>
) : sticker.text ? (
<div key={sticker.id || `${sticker.text}-${index}`} className="sticker-overlay is-label">{sticker.text}</div>
) : null;
})}
</div>
)}
</div>
+27 -13
View File
@@ -25,7 +25,7 @@ import {
Waveform,
} from "@phosphor-icons/react";
import { IMAGE_SEGMENT_SECONDS } from "../config/editor.js";
import { IMAGE_SEGMENT_SECONDS, MAX_IMAGE_THUMBNAILS } from "../config/editor.js";
import { formatClock, formatTime, getSegmentStartTime, packTimedSegmentsIntoLanes } from "../lib/timeline.js";
import { sliceSourceAudioPeaks } from "../lib/sourceAudioSync.js";
import {
@@ -72,8 +72,8 @@ function getSampledVideoFrames(frames, count) {
return [];
}
const safeCount = Math.max(VIDEO_FRAME_MIN_COUNT, Math.min(frames.length, count));
if (safeCount >= frames.length) {
const safeCount = Math.max(VIDEO_FRAME_MIN_COUNT, count);
if (safeCount === frames.length) {
return frames;
}
@@ -87,7 +87,7 @@ function getSampledVideoFrames(frames, count) {
});
}
function getVideoTimelineFrameCount({ duration, timelineDuration, contentWidth, timelineZoom, availableFrames }) {
function getTimelineThumbnailCount({ duration, timelineDuration, contentWidth, timelineZoom, availableFrames = MAX_IMAGE_THUMBNAILS }) {
if (!availableFrames || timelineDuration <= 0 || contentWidth <= 0) {
return VIDEO_FRAME_MIN_COUNT;
}
@@ -95,12 +95,12 @@ function getVideoTimelineFrameCount({ duration, timelineDuration, contentWidth,
const clipPixelWidth = Math.max(68, (Math.max(0, duration || 0) / timelineDuration) * contentWidth);
const targetCellWidth =
timelineZoom >= 8
? 34
? 30
: timelineZoom >= 3
? 42
? 38
: timelineZoom >= 1
? 54
: 82;
? 48
: 68;
return Math.max(
VIDEO_FRAME_MIN_COUNT,
Math.min(availableFrames, Math.ceil(clipPixelWidth / targetCellWidth)),
@@ -172,6 +172,7 @@ export function Timeline({
seekTo,
suppressTimelineClipClickRef,
startTimelineClipDrag,
startCaptionResize,
startImageResize,
startStickerSegmentMove,
displayedCaptionSegments,
@@ -839,12 +840,12 @@ export function Timeline({
segmentType === "video" && videoTrackFrames.length
? getSampledVideoFrames(
videoTrackFrames,
getVideoTimelineFrameCount({
getTimelineThumbnailCount({
duration: segment.duration,
timelineDuration,
contentWidth: rulerViewport.contentWidth,
timelineZoom: localTimelineZoom,
availableFrames: videoTrackFrames.length,
availableFrames: MAX_IMAGE_THUMBNAILS,
}),
)
: [];
@@ -887,7 +888,10 @@ export function Timeline({
className={`image-thumbnails ${segmentType === "video" ? "is-video" : ""} ${
isPortraitVideo ? "is-portrait-video" : ""
}`}
style={{ "--thumbnail-cell-width": `${IMAGE_THUMBNAIL_TARGET_WIDTH}px` }}
style={{
"--thumbnail-cell-width": `${IMAGE_THUMBNAIL_TARGET_WIDTH}px`,
"--video-thumbnail-count": Math.max(1, visibleVideoFrames.length),
}}
>
{segmentType === "video" ? (
visibleVideoFrames.length ? (
@@ -1000,7 +1004,17 @@ export function Timeline({
seekTo(segmentRange?.start ?? getSegmentStartTime(displayedCaptionSegments, index, captionTargetDuration));
}}
>
{segment.text}
<span
className="caption-resize-handle is-start"
aria-hidden="true"
onPointerDown={(event) => startCaptionResize(event, segment.id, index, "start")}
/>
<span className="caption-segment-label">{segment.text}</span>
<span
className="caption-resize-handle is-end"
aria-hidden="true"
onPointerDown={(event) => startCaptionResize(event, segment.id, index, "end")}
/>
</button>
);
})}
@@ -1141,7 +1155,7 @@ export function Timeline({
<span>{formatClock(draggingVisualSegment.duration)}</span>
</div>
) : null}
{draggingCaptionSegment && activeTimelineClipDrag.mode !== "move" ? (
{draggingCaptionSegment && !["move", "resize-start", "resize-end"].includes(activeTimelineClipDrag.mode) ? (
<div
className="timeline-drag-ghost type-caption"
style={{ left: activeTimelineClipDrag.x, top: activeTimelineClipDrag.y }}
+43 -5
View File
@@ -176,6 +176,35 @@ function AudioClipContextPanel({ t, segment, updateAudioSegment, toggleAudioSegm
);
}
function StickerContextPanel({ t, segment, updateStickerSegment, deleteStickerSegment }) {
if (!segment) return null;
const round = (value) => Math.round(value * 100) / 100;
const updateNumber = (key, value, min, max) => updateStickerSegment({
[key]: round(Math.max(min, Math.min(max, Number(value) || 0))),
});
const fields = [
["x", t("stickerHorizontalPosition"), 0, 100, "%"],
["y", t("stickerVerticalPosition"), 0, 100, "%"],
["scale", t("stickerScale"), 0.2, 3, "x"],
["rotation", t("stickerRotation"), -180, 180, "°"],
];
return (
<div className="sticker-properties-panel">
<div className="sticker-properties-preview"><img src={segment.src} alt="" /></div>
<div className="sticker-property-grid">
{fields.map(([key, label, min, max, unit]) => (
<label key={key}>{label}<input type="number" min={min} max={max} step="0.01" value={round(Number.isFinite(segment[key]) ? segment[key] : key === "scale" ? 1 : key === "x" ? 82 : key === "y" ? 20 : 0)} onChange={(event) => updateNumber(key, event.target.value, min, max)} />{unit ? null : null}</label>
))}
</div>
<label className="sticker-property-field">
<div><span>{t("stickerOpacity")}</span><strong>{Math.round((Number.isFinite(segment.opacity) ? segment.opacity : 1) * 100)}%</strong></div>
<input type="range" min="0" max="1" step="0.01" value={Number.isFinite(segment.opacity) ? segment.opacity : 1} onChange={(event) => updateNumber("opacity", event.target.value, 0, 1)} />
</label>
<button className="sticker-delete-button" type="button" onClick={deleteStickerSegment}><Trash size={14} />{t("deleteSticker")}</button>
</div>
);
}
function AvatarContextPanel({ t, hasVisual, visualType, audioBlob, audioDuration, captionSegments, selectedVoice, avatarJob, generateAvatarAcceptanceFrame }) {
const hasPortrait = hasVisual && visualType === "image";
const [probeState, setProbeState] = useState("idle");
@@ -320,9 +349,13 @@ export function VoicePanel({
toggleAudioSegmentReverse,
deleteAudioSegment,
selectedVisualSegment,
selectedStickerSegment,
updateStickerSegment,
deleteStickerSegment,
visualLocalTime,
visualTimelineStart = 0,
updateSelectedVisualEffects,
onPreviewAnimation,
selectedFilterId,
setSelectedFilterId,
trOption,
@@ -333,12 +366,15 @@ export function VoicePanel({
const isAvatarContext = activeTool === "smart" && avatarPanelOpen;
const isAudioClipContext = selectedTrack === "audio" && Boolean(selectedAudioSegment);
const isVisualContext = selectedTrack === "image";
const isStickerContext = selectedTrack === "sticker" && Boolean(selectedStickerSegment);
const selectedCaptionAudioSegment = getCaptionVoiceSegment(audioSegments, selectedCaptionSegment);
const title = isVisualContext ? t("visualPanelTitle") : isAvatarContext ? t("avatarTitle") : isCaptionContext ? t("caption") : isAudioClipContext ? t("audioClipProperties") : t("aiVoice");
const title = isStickerContext ? t("stickerProperties") : isVisualContext ? t("visualPanelTitle") : isAvatarContext ? t("avatarTitle") : isCaptionContext ? t("caption") : isAudioClipContext ? t("audioClipProperties") : t("aiVoice");
const panelStatusText = isCaptionContext
? captionSegments.length
? `${captionSegments.length} ${t("captionSegmentsUnit", "条字幕")}`
: t("noCaptionSegments")
: isStickerContext
? `${selectedStickerSegment.start.toFixed(2)}s · ${selectedStickerSegment.duration.toFixed(2)}s`
: isVisualContext
? selectedVisualSegment
? `${visualLocalTime.toFixed(2)}s · ${normalizeVisualKeyframes(selectedVisualSegment.keyframes).length} ${t("visualFrames")}`
@@ -371,7 +407,7 @@ export function VoicePanel({
</span>
</div>
{!isCaptionContext && !isAvatarContext && !isAudioClipContext && !isVisualContext ? (
{!isCaptionContext && !isAvatarContext && !isAudioClipContext && !isVisualContext && !isStickerContext ? (
<div className="tabs compact">
{[
["synthesis", t("voiceSynthesis")],
@@ -414,6 +450,7 @@ export function VoicePanel({
) : null}
<div className="voice-tab-body">
{isStickerContext ? <StickerContextPanel t={t} segment={selectedStickerSegment} updateStickerSegment={updateStickerSegment} deleteStickerSegment={deleteStickerSegment} /> : null}
{isVisualContext && selectedVisualSegment ? (
<VisualEffectsPanel
contextMode
@@ -421,6 +458,7 @@ export function VoicePanel({
segment={selectedVisualSegment}
localTime={visualLocalTime}
onChange={updateSelectedVisualEffects}
onPreviewAnimation={onPreviewAnimation}
onSeek={(time) => seekTo(visualTimelineStart + time)}
selectedFilterId={selectedFilterId}
trOption={trOption}
@@ -494,7 +532,7 @@ export function VoicePanel({
{isAudioClipContext ? <AudioClipContextPanel t={t} segment={selectedAudioSegment} updateAudioSegment={updateAudioSegment} toggleAudioSegmentReverse={toggleAudioSegmentReverse} deleteAudioSegment={deleteAudioSegment} downloadBlob={downloadBlob} /> : null}
{!isCaptionContext && !isAvatarContext && !isAudioClipContext && !isVisualContext && voiceTab === "synthesis" ? (
{!isCaptionContext && !isAvatarContext && !isAudioClipContext && !isVisualContext && !isStickerContext && voiceTab === "synthesis" ? (
<VoiceSynthesisPanel
script={script}
updateScript={updateScript}
@@ -522,7 +560,7 @@ export function VoicePanel({
/>
) : null}
{!isCaptionContext && !isAvatarContext && !isAudioClipContext && !isVisualContext && voiceTab === "mine" ? (
{!isCaptionContext && !isAvatarContext && !isAudioClipContext && !isVisualContext && !isStickerContext && voiceTab === "mine" ? (
<MyVoicesPanel
favoriteVoiceIds={favoriteVoiceIds}
setFavoriteVoiceIds={setFavoriteVoiceIds}
@@ -540,7 +578,7 @@ export function VoicePanel({
/>
) : null}
{!isCaptionContext && !isAvatarContext && !isAudioClipContext && !isVisualContext && voiceTab === "history" ? (
{!isCaptionContext && !isAvatarContext && !isAudioClipContext && !isVisualContext && !isStickerContext && voiceTab === "history" ? (
<HistoryPanel
historyItems={historyItems}
useHistoryItem={useHistoryItem}
+90 -31
View File
@@ -34,6 +34,7 @@ import {
import { APP_LANGUAGES } from "../i18n.js";
import { formatClock, formatTime, getSegmentStartTime } from "../lib/timeline.js";
import { hasVisualPropertyKeyframe, normalizeVisualKeyframes, resolveVisualTransform } from "../lib/visualEffects.js";
import { DEFAULT_VISUAL_ANIMATION_DURATION, normalizeVisualClipAnimation, VISUAL_CLIP_ANIMATION_OPTIONS } from "../lib/visualClipAnimations.js";
import { Popover } from "./ui.jsx";
export function LanguageIntro({ t, closing, onChoose }) {
@@ -470,36 +471,40 @@ export function ToolPanel(props) {
onChange={(event) => setMusicVolume(Number(event.target.value))}
/>
</div>
<button
className="panel-primary"
type="button"
disabled={!audioBlob}
onClick={() => audioBlob && downloadBlob(audioBlob, "ai-voiceover.wav")}
>
{t("downloadCurrentWav")}
</button>
<button
className="panel-secondary"
type="button"
disabled={!musicBlob}
onClick={() => musicBlob && downloadBlob(musicBlob, musicName || "background-music.wav")}
>
{t("downloadBgm")}
</button>
<button
className="panel-secondary"
type="button"
disabled={!sourceAudioBlob}
onClick={() => sourceAudioBlob && downloadBlob(sourceAudioBlob, sourceAudioName || "source-audio.wav")}
>
{t("downloadSource")}
</button>
<button className="panel-secondary" type="button" disabled={!sourceAudioBlob} onClick={() => clearSourceAudioTrack()}>
{t("deleteSource")}
</button>
<button className="panel-secondary" type="button" disabled={!musicBlob} onClick={() => clearMusicTrack()}>
{t("deleteBgm")}
</button>
<div className="audio-download-actions">
<button
className="panel-primary"
type="button"
disabled={!audioBlob}
onClick={() => audioBlob && downloadBlob(audioBlob, "ai-voiceover.wav")}
>
{t("downloadCurrentWav")}
</button>
<button
className="panel-secondary"
type="button"
disabled={!musicBlob}
onClick={() => musicBlob && downloadBlob(musicBlob, musicName || "background-music.wav")}
>
{t("downloadBgm")}
</button>
<button
className="panel-secondary"
type="button"
disabled={!sourceAudioBlob}
onClick={() => sourceAudioBlob && downloadBlob(sourceAudioBlob, sourceAudioName || "source-audio.wav")}
>
{t("downloadSource")}
</button>
</div>
<div className="audio-delete-actions">
<button className="panel-secondary is-danger" type="button" disabled={!sourceAudioBlob} onClick={() => clearSourceAudioTrack()}>
{t("deleteSource")}
</button>
<button className="panel-secondary is-danger" type="button" disabled={!musicBlob} onClick={() => clearMusicTrack()}>
{t("deleteBgm")}
</button>
</div>
</div>
);
}
@@ -568,8 +573,10 @@ export function ToolPanel(props) {
);
}
export function VisualEffectsPanel({ t, segment, localTime, onChange, onSeek, selectedFilterId, trOption, onSelectFilter, contextMode = false, sourceAudioLinked = false }) {
export function VisualEffectsPanel({ t, segment, localTime, onChange, onSeek, onPreviewAnimation, selectedFilterId, trOption, onSelectFilter, contextMode = false, sourceAudioLinked = false }) {
const [activeTab, setActiveTab] = useState("transform");
const [animationSection, setAnimationSection] = useState("in");
const [hoveredAnimation, setHoveredAnimation] = useState(null);
const keyframes = normalizeVisualKeyframes(segment?.keyframes ?? []);
const transform = resolveVisualTransform(keyframes, localTime);
const mask = segment?.mask ?? { type: "none", feather: 0, inverted: false };
@@ -577,6 +584,8 @@ export function VisualEffectsPanel({ t, segment, localTime, onChange, onSeek, se
const isCircleMask = mask.type === "circle";
const isVideo = segment?.type === "video";
const playbackRate = Math.max(0.25, Math.min(4, Number(segment?.playbackRate) || 1));
const clipAnimation = normalizeVisualClipAnimation(segment?.animation);
const activeAnimation = clipAnimation[animationSection];
const sourceDuration = Math.max(0, Number(segment?.sourceDuration) || (Number(segment?.duration) || 0) * playbackRate);
const updateTransform = (key, value) => onChange?.({ propertyKeyframe: { time: localTime, key, value } });
const tabs = [
@@ -584,7 +593,38 @@ export function VisualEffectsPanel({ t, segment, localTime, onChange, onSeek, se
["mask", t("visualTabMask")],
["speed", t("visualTabSpeed")],
["effects", t("visualTabEffects")],
["animation", t("visualTabAnimation")],
];
useEffect(() => {
if (!hoveredAnimation || !segment || !onPreviewAnimation) return undefined;
let frame = 0;
let lastPaint = 0;
const startedAt = performance.now();
const paint = (now) => {
if (now - lastPaint >= 32) {
const phaseProgress = ((now - startedAt) % 1100) / 900;
const progress = Math.min(1, phaseProgress);
const previewAnimation = {
...clipAnimation,
[hoveredAnimation.phase]: {
id: hoveredAnimation.id,
duration: DEFAULT_VISUAL_ANIMATION_DURATION,
},
};
const previewLocalTime = hoveredAnimation.phase === "in"
? progress * DEFAULT_VISUAL_ANIMATION_DURATION
: Math.max(0, Number(segment.duration) - DEFAULT_VISUAL_ANIMATION_DURATION + progress * DEFAULT_VISUAL_ANIMATION_DURATION);
onPreviewAnimation({ segmentId: segment.id, animation: previewAnimation, localTime: previewLocalTime });
lastPaint = now;
}
frame = requestAnimationFrame(paint);
};
frame = requestAnimationFrame(paint);
return () => {
cancelAnimationFrame(frame);
onPreviewAnimation(null);
};
}, [hoveredAnimation, onPreviewAnimation, segment?.id, segment?.duration]);
return (
<div className={`tool-panel visual-effects-panel ${contextMode ? "is-context-mode" : ""}`}>
{!contextMode ? <h2>{t("imageTrack")}</h2> : null}
@@ -624,6 +664,25 @@ export function VisualEffectsPanel({ t, segment, localTime, onChange, onSeek, se
</> : <div className="empty-state visual-speed-empty">{t("visualSpeedImageHint")}</div>}
</section> : null}
{activeTab === "effects" ? <VisualChoicePanel title={t("visualEffects")} kind="effect" options={EFFECT_OPTIONS} selectedId={selectedFilterId} trOption={trOption} onSelect={onSelectFilter} /> : null}
{activeTab === "animation" ? <section className="visual-editor-card visual-animation-card">
<div className="visual-editor-heading"><strong>{t("visualAnimation")}</strong><em>{t("visualAnimationHoverHint")}</em></div>
<div className="visual-animation-sections" role="tablist" aria-label={t("visualAnimation")}>
{[['in', t('visualAnimationIn')], ['out', t('visualAnimationOut')]].map(([id, label]) => <button type="button" role="tab" aria-selected={animationSection === id} className={animationSection === id ? 'is-active' : ''} key={id} onClick={() => setAnimationSection(id)}>{label}</button>)}
</div>
<div className="visual-animation-grid">
{VISUAL_CLIP_ANIMATION_OPTIONS.map((option) => <button
type="button"
className={activeAnimation.id === option.id ? "is-active" : ""}
key={option.id}
onPointerEnter={() => option.id !== "none" && setHoveredAnimation({ phase: animationSection, id: option.id })}
onPointerLeave={() => setHoveredAnimation(null)}
onFocus={() => option.id !== "none" && setHoveredAnimation({ phase: animationSection, id: option.id })}
onBlur={() => setHoveredAnimation(null)}
onClick={() => onChange?.({ animation: { ...clipAnimation, [animationSection]: { ...activeAnimation, id: option.id } } })}
><span className={`visual-animation-swatch is-${option.id}`} aria-hidden="true"><i /></span><strong>{t(option.labelKey)}</strong></button>)}
</div>
{activeAnimation.id !== "none" ? <div className="slider-field compact-slider visual-animation-duration"><div><label>{t("visualAnimationDuration")}</label><strong>{activeAnimation.duration.toFixed(1)}s</strong></div><input aria-label={t("visualAnimationDuration")} type="range" min="0.1" max={Math.min(3, Math.max(0.1, Number(segment.duration) || 0.1))} step="0.1" value={activeAnimation.duration} onChange={(event) => onChange?.({ animation: { ...clipAnimation, [animationSection]: { ...activeAnimation, duration: Number(event.target.value) } } })} /></div> : null}
</section> : null}
</>}
</div>
);
+19 -1
View File
@@ -1,3 +1,4 @@
import { useEffect, useRef } from "react";
import { X } from "@phosphor-icons/react";
export function IconButton({ label, children, active = false, disabled = false, onClick }) {
@@ -16,8 +17,25 @@ export function IconButton({ label, children, active = false, disabled = false,
}
export function Popover({ children, onClose, className = "" }) {
const popoverRef = useRef(null);
useEffect(() => {
const closeOnOutsidePointer = (event) => {
if (!popoverRef.current?.contains(event.target)) onClose?.();
};
const closeOnEscape = (event) => {
if (event.key === "Escape") onClose?.();
};
document.addEventListener("pointerdown", closeOnOutsidePointer, true);
document.addEventListener("keydown", closeOnEscape);
return () => {
document.removeEventListener("pointerdown", closeOnOutsidePointer, true);
document.removeEventListener("keydown", closeOnEscape);
};
}, [onClose]);
return (
<div className={`popover ${className}`.trim()} role="dialog">
<div ref={popoverRef} className={`popover ${className}`.trim()} role="dialog">
<button className="popover-close" type="button" aria-label="关闭" onClick={onClose}>
<X size={14} />
</button>
-2
View File
@@ -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 = [
+14 -6
View File
@@ -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]);
+15 -1
View File
@@ -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,
+46
View File
@@ -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,
+16
View File
@@ -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");
}
});
});
+2 -1
View File
@@ -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;
+81 -35
View File
@@ -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,
});
+5 -4
View File
@@ -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,
+14
View File
@@ -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 });
});
});
+8 -5
View File
@@ -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);
+21
View File
@@ -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 });
});
});
+5
View File
@@ -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,
};
}
+19 -6
View File
@@ -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;
+34
View File
@@ -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);
});
});
+61 -4
View File
@@ -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 };
}
+35 -25
View File
@@ -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();
@@ -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);
});
});
+44
View File
@@ -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` } };
}
+23
View File
@@ -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 } });
});
});
+11 -7
View File
@@ -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,
+13
View File
@@ -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);
});
});
+57
View File
@@ -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;
}
+16
View File
@@ -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);
});
});
+1 -1
View File
@@ -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) {
+106 -8
View File
@@ -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;
}