fix caption lane controls and preview behavior

This commit is contained in:
haixin.yang committed 2026-07-17 19:42:55 +08:00
1 parent eb3501b211
commit 2b9a1e7e0b
10 files changed
+146 -56

No files matched your search

+2 -1
View File
@@ -187,7 +187,7 @@ export function App() {
const {
activePreviewFilter, audioBlob, audioDuration, audioUrl, canPreview, captionDuration,
captionTargetDuration, captionTimeline, currentCaption, currentCaptionSegment,
captionTargetDuration, captionTimeline, currentCaption, currentCaptions, currentCaptionSegment,
currentSegmentIndex, currentStickerSegment, currentStickerSegmentIndex,
currentVisualRange, currentVisualSegment, currentVisualSegmentIndex, estimatedDuration,
focusedSegmentIndex, getStickerDragAsset, peaks, previewSticker, previewStickers, previewTransition,
@@ -753,6 +753,7 @@ export function App() {
setFitMode={setFitModeFromUser}
captionsEnabled={captionsEnabled}
currentCaption={currentCaption}
currentCaptions={currentCaptions}
captionSize={captionSize}
captionStyle={captionStyle}
captionPlacement={effectiveCaptionPlacement}
+22 -11
View File
@@ -45,6 +45,7 @@ export function PreviewStage({
setFitMode,
captionsEnabled,
currentCaption,
currentCaptions = null,
captionSize,
captionStyle,
captionPlacement,
@@ -320,17 +321,27 @@ export function PreviewStage({
<span>{t("visualMask")}</span><button type="button" aria-label={t("visualMaskResize")} onPointerDown={(event) => startMaskEdit(event, "resize")} />
</div>
) : null}
{captionsEnabled && trackVisibility.caption && currentCaption ? (
<CaptionOverlay
text={currentCaption}
captionSize={captionSize}
captionStyle={captionStyle}
placement={captionPlacement}
frameSize={previewFrameSize}
onPointerDown={startCaptionDrag}
onDoubleClick={() => setActiveTool("caption")}
/>
) : null}
{captionsEnabled && trackVisibility.caption
? (Array.isArray(currentCaptions) ? currentCaptions : currentCaption ? [{ id: "current", text: currentCaption }] : [])
.map((caption, index, visibleCaptions) => {
const basePlacement = caption.placement || captionPlacement;
return (
<CaptionOverlay
key={caption.id}
text={caption.text}
captionSize={captionSize}
captionStyle={captionStyle}
placement={{
...basePlacement,
y: basePlacement.y + (caption.placement ? 0 : (index - (visibleCaptions.length - 1) / 2) * 12),
}}
frameSize={previewFrameSize}
onPointerDown={(event) => startCaptionDrag(event, caption.id)}
onDoubleClick={() => setActiveTool("caption")}
/>
);
})
: null}
{visibleStickers.map((sticker, index) => {
const isEditable = stickerEditable && sticker.id === selectedStickerId;
return sticker.src ? (
+28 -31
View File
@@ -6,6 +6,7 @@ import {
ArrowsOutLineHorizontal,
CopySimple,
Crop,
CircleNotch,
Eye,
EyeSlash,
LockKey,
@@ -27,7 +28,7 @@ import {
} from "@phosphor-icons/react";
import { IMAGE_SEGMENT_SECONDS, MAX_IMAGE_THUMBNAILS, TRANSITIONS } from "../config/editor.js";
import { formatClock, formatTime, getSegmentStartTime, packTimedSegmentsIntoLanes } from "../lib/timeline.js";
import { formatClock, formatTime, getSegmentStartTime, packCaptionSegmentsIntoLanes, packTimedSegmentsIntoLanes } from "../lib/timeline.js";
import { sliceSourceAudioPeaks } from "../lib/sourceAudioSync.js";
import {
clampTimelineZoom,
@@ -52,22 +53,6 @@ const TIMELINE_WHEEL_ZOOM_CONTENT_SELECTOR = [
".audio-clip",
].join(", ");
function packCaptionSegmentsIntoLanes(segments, timeline) {
const lanes = [];
segments
.map((segment, index) => ({ segment, index, range: timeline[index] }))
.sort((a, b) => (a.range?.start || 0) - (b.range?.start || 0))
.forEach((item) => {
const laneIndex = lanes.findIndex((lane) => {
const last = lane.at(-1);
return !last || (last.range?.end || 0) <= (item.range?.start || 0) + 0.001;
});
if (laneIndex >= 0) lanes[laneIndex].push(item);
else lanes.push([item]);
});
return lanes.length ? lanes : [[]];
}
function getSampledVideoFrames(frames, count) {
if (!Array.isArray(frames) || !frames.length) {
return [];
@@ -256,7 +241,7 @@ export function Timeline({
const timelineTrackLabels = [
["image", t("imageTrack")],
...(showStickerTrack ? stickerLanes.map((_, index) => ["sticker", `${t("stickerTrack")} ${index + 1}`, `sticker-${index}`]) : []),
...captionLanes.map((_, index) => ["caption", `${t("caption")} ${index + 1}`, `caption-${index}`]),
...captionLanes.map((_, index) => ["caption", `${t("caption")} ${index + 1}`, `caption-${index}`, `caption-${index}`]),
["source", t("sourceTrack")],
...audioLanes.map((_, index) => ["audio", `${t("voiceTrack")} ${index + 1}`, `audio-${index}`]),
["music", t("musicTrack")],
@@ -270,6 +255,7 @@ export function Timeline({
contentWidth: 0,
});
const [contextMenu, setContextMenu] = useState(null);
const [imageCaptionPendingId, setImageCaptionPendingId] = useState("");
const contextImageSegment = contextMenu?.track === "image" && contextMenu.segmentId
? displayedVisualSegments.find((segment) => segment.id === contextMenu.segmentId)
: null;
@@ -289,7 +275,7 @@ export function Timeline({
if (track === "source" && segmentId) setSelectedSourceAudioSegmentId(segmentId);
if (track === "music" && segmentId) setMusicClipSelected(true);
};
const showTrackContextMenu = (event, track, segmentId = "") => {
const showTrackContextMenu = (event, track, segmentId = "", visibilityKey = track) => {
event.preventDefault(); event.stopPropagation();
selectContextTarget(track, segmentId);
const trackRect = trackScrollRef.current?.getBoundingClientRect();
@@ -299,13 +285,23 @@ export function Timeline({
setContextMenu({
x: Math.max(10, Math.min(window.innerWidth - 234, event.clientX)),
y: Math.max(10, Math.min(window.innerHeight - 258, event.clientY)),
track, segmentId, targetTime, kind: segmentId ? "clip" : "track",
track, visibilityKey, segmentId, targetTime, kind: segmentId ? "clip" : "track",
});
};
const runContextAction = (action) => {
setContextMenu(null);
window.requestAnimationFrame(action);
};
const runImageCaptionAction = async (segment) => {
if (!segment || imageCaptionPendingId) return;
setImageCaptionPendingId(segment.id);
try {
await generateImageCaption?.(segment);
setContextMenu(null);
} finally {
setImageCaptionPendingId("");
}
};
useEffect(() => {
if (!contextMenu) return undefined;
const close = () => setContextMenu(null);
@@ -742,23 +738,23 @@ export function Timeline({
<div className="timeline-board">
<div className="track-labels" style={{ gridTemplateRows: timelineLabelRows }}>
{timelineTrackLabels.map(([track, label, rowId = track]) => (
{timelineTrackLabels.map(([track, label, rowId = track, visibilityKey = track]) => (
<div
className={`${selectedTrack === track ? "is-selected" : ""} ${
!isRowVisible(track) ? "is-track-disabled" : ""
!isRowVisible(visibilityKey) ? "is-track-disabled" : ""
}`}
key={rowId}
onContextMenu={(event) => showTrackContextMenu(event, track)}
onContextMenu={(event) => showTrackContextMenu(event, track, "", visibilityKey)}
>
<button
type="button"
aria-label={`${label} ${t("visible")}`}
onClick={(event) => {
event.stopPropagation();
toggleTrackVisibility(track);
toggleTrackVisibility(visibilityKey);
}}
>
{isRowVisible(track) ? <Eye size={15} /> : <EyeSlash size={15} />}
{isRowVisible(visibilityKey) ? <Eye size={15} /> : <EyeSlash size={15} />}
</button>
<button
type="button"
@@ -998,7 +994,7 @@ export function Timeline({
{captionLanes.map((lane, laneIndex) => (
<div
className={`caption-track ${selectedTrack === "caption" ? "is-selected" : ""} ${
!isRowVisible("caption") ? "is-track-disabled" : ""
!isRowVisible(`caption-${laneIndex}`) ? "is-track-disabled" : ""
} ${
activeTimelineClipDrag?.track === "caption" ? "is-reordering" : ""
}`}
@@ -1008,7 +1004,7 @@ export function Timeline({
setActiveTool("caption");
}}
data-timeline-reorder-track="caption"
onContextMenu={(event) => showTrackContextMenu(event, "caption")}
onContextMenu={(event) => showTrackContextMenu(event, "caption", "", `caption-${laneIndex}`)}
>
{lane.map(({ segment, index, range: segmentRange }) => {
const segmentDuration = segmentRange?.duration ?? 0;
@@ -1047,7 +1043,7 @@ export function Timeline({
"--caption-width": `${segmentWidth}%`,
}}
onPointerDown={(event) => startTimelineClipDrag(event, "caption", segment.id, index)}
onContextMenu={(event) => showTrackContextMenu(event, "caption", segment.id)}
onContextMenu={(event) => showTrackContextMenu(event, "caption", segment.id, `caption-${laneIndex}`)}
onClick={(event) => {
event.stopPropagation();
if (suppressTimelineClipClickRef.current === segment.id) {
@@ -1251,8 +1247,9 @@ export function Timeline({
})}><Waveform size={16} />{t("aiVoice")}</button>
) : null}
{contextMenu.track === "image" && builtInImageCaptionAvailable && contextImageSegment && contextImageSegment.type !== "video" ? (
<button type="button" role="menuitem" onClick={() => runContextAction(() => generateImageCaption?.(contextImageSegment))}>
<Sparkle size={16} />{t("generateImageAiCaption")}
<button className={imageCaptionPendingId === contextImageSegment.id ? "is-loading" : ""} type="button" role="menuitem" disabled={Boolean(imageCaptionPendingId)} onClick={() => runImageCaptionAction(contextImageSegment)}>
{imageCaptionPendingId === contextImageSegment.id ? <CircleNotch size={14} /> : <Sparkle size={14} />}
{t(imageCaptionPendingId === contextImageSegment.id ? "generatingImageAiCaption" : "generateImageAiCaption")}
</button>
) : null}
<button type="button" role="menuitem" onClick={() => runContextAction(handleCutTrack)}><Scissors size={16} />{t("splitAtPlayhead")}</button>
@@ -1263,7 +1260,7 @@ export function Timeline({
) : (
<>
{["image", "caption"].includes(contextMenu.track) ? <button type="button" role="menuitem" onClick={() => runContextAction(() => handleAddSegment(contextMenu.targetTime))}><PlusCircle size={16} />{t("addClip")}</button> : null}
<button type="button" role="menuitem" onClick={() => runContextAction(() => toggleTrackVisibility(contextMenu.track))}>{trackVisibility[contextMenu.track] ? <EyeSlash size={16} /> : <Eye size={16} />}{t(trackVisibility[contextMenu.track] ? "hideTrack" : "showTrack")}</button>
<button type="button" role="menuitem" onClick={() => runContextAction(() => toggleTrackVisibility(contextMenu.visibilityKey || contextMenu.track))}>{isRowVisible(contextMenu.visibilityKey || contextMenu.track) ? <EyeSlash size={16} /> : <Eye size={16} />}{t(isRowVisible(contextMenu.visibilityKey || contextMenu.track) ? "hideTrack" : "showTrack")}</button>
<button type="button" role="menuitem" onClick={() => runContextAction(() => toggleTrackLock(contextMenu.track))}>{trackLocks[contextMenu.track] ? <LockKeyOpen size={16} /> : <LockKey size={16} />}{t(trackLocks[contextMenu.track] ? "unlockTrack" : "lockTrack")}</button>
</>
)}
+19 -1
View File
@@ -17,6 +17,7 @@ import {
getTimedSegmentsEnd,
getVisualSegmentIndexAtTime,
getVisualSegmentTimeline,
packCaptionSegmentsIntoLanes,
} from "../lib/timeline.js";
import { getVisionKey } from "../lib/vision.js";
import { getVisualSourceTime } from "../lib/visualEffects.js";
@@ -118,6 +119,23 @@ export function useTimelineModel(d) {
const currentCaption = currentCaptionSegment && !currentCaptionSegment.hidden
? currentCaptionSegment.text
: "";
const currentCaptions = useMemo(() => {
if (!d.trackVisibility.caption) return [];
return packCaptionSegmentsIntoLanes(d.captionSegments, captionTimeline)
.map((lane, laneIndex) => {
if ((d.trackVisibility[`caption-${laneIndex}`] ?? true) === false) return null;
const item = lane.find(({ segment, range }) => (
!segment.hidden && range && d.currentTime >= range.start && d.currentTime < range.end
));
return item ? {
id: item.segment.id,
text: item.segment.text,
placement: item.segment.placement,
laneIndex,
} : null;
})
.filter(Boolean);
}, [captionTimeline, d.captionSegments, d.currentTime, d.trackVisibility]);
const currentStickerSegmentIndex = getTimedSegmentIndexAtTime(d.stickerSegments, d.currentTime);
const currentStickerSegment = currentStickerSegmentIndex >= 0
? d.stickerSegments[currentStickerSegmentIndex] ?? null
@@ -203,7 +221,7 @@ export function useTimelineModel(d) {
return {
activePreviewFilter, audioBlob, audioDuration, audioUrl, canPreview:
hasPlayableVisualTimeline || hasPlayableAudioTimeline,
captionDuration, captionTargetDuration, captionTimeline, currentCaption,
captionDuration, captionTargetDuration, captionTimeline, currentCaption, currentCaptions,
currentCaptionSegment, currentSegmentIndex, currentStickerSegment,
currentStickerSegmentIndex, currentVisualRange, currentVisualSegment,
currentVisualSegmentIndex, estimatedDuration, focusedSegmentIndex, getStickerDragAsset,
+2 -2
View File
@@ -295,8 +295,8 @@ const AUTO_EDIT_RESULT_COPY = {
};
const IMAGE_AI_CAPTION_COPY = {
zh: { generateImageAiCaption: "AI 生成口播字幕", imageAiCaptionAdded: "AI 口播字幕已加入时间线", imageAiCaptionFailed: "无法生成图片口播字幕" },
en: { generateImageAiCaption: "Generate AI voiceover caption", imageAiCaptionAdded: "AI voiceover caption added to the timeline", imageAiCaptionFailed: "Could not generate an image voiceover caption" },
zh: { generateImageAiCaption: "AI 生成口播字幕", generatingImageAiCaption: "正在生成口播字幕…", imageAiCaptionAdded: "AI 口播字幕已加入时间线", imageAiCaptionFailed: "无法生成图片口播字幕" },
en: { generateImageAiCaption: "Generate AI voiceover caption", generatingImageAiCaption: "Generating AI caption…", imageAiCaptionAdded: "AI voiceover caption added to the timeline", imageAiCaptionFailed: "Could not generate an image voiceover caption" },
};
export const UI_COPY = {
+13 -3
View File
@@ -1,5 +1,11 @@
import { getCaptionScript } from "./timeline.js";
export function setCaptionSegmentPlacement(segments, segmentId, placement) {
return segments.map((segment) => (
segment.id === segmentId ? { ...segment, placement: { ...placement } } : segment
));
}
export function createCaptionEditingActions(d) {
function updateScript(nextScript) {
d.setScript(nextScript);
@@ -62,7 +68,7 @@ export function createCaptionEditingActions(d) {
}
}
function startCaptionDrag(event) {
function startCaptionDrag(event, segmentId = d.currentCaptionSegment?.id) {
if (event.button !== 0) return;
if (d.trackLocks.caption) {
d.notify("字幕轨已锁定,无法拖动");
@@ -72,14 +78,18 @@ export function createCaptionEditingActions(d) {
event.stopPropagation();
const disabledSmartAvoidance = disableSmartCaptionAvoidance();
d.setSelectedTrack("caption");
if (d.currentCaptionSegment) d.setSelectedSegmentId(d.currentCaptionSegment.id);
if (segmentId) d.setSelectedSegmentId(segmentId);
const applyPlacement = (clientX, clientY) => {
const rect = d.previewCanvasRef.current?.getBoundingClientRect();
if (!rect) return;
const x = Math.max(10, Math.min(90, ((clientX - rect.left) / rect.width) * 100));
const y = Math.max(10, Math.min(90, ((clientY - rect.top) / rect.height) * 100));
d.setCaptionPlacement({ x, y });
if (segmentId) {
d.setCaptionSegments((items) => setCaptionSegmentPlacement(items, segmentId, { x, y }));
} else {
d.setCaptionPlacement({ x, y });
}
d.setCaptionPosition("custom");
};
+19
View File
@@ -0,0 +1,19 @@
import { describe, expect, it } from "vitest";
import { setCaptionSegmentPlacement } from "./captionEditingActions.js";
describe("caption canvas placement", () => {
it("moves only the caption selected on the preview canvas", () => {
const source = [
{ id: "first", text: "First", placement: { x: 30, y: 40 } },
{ id: "second", text: "Second", placement: { x: 60, y: 70 } },
];
const result = setCaptionSegmentPlacement(source, "first", { x: 45, y: 55 });
expect(result[0].placement).toEqual({ x: 45, y: 55 });
expect(result[1]).toBe(source[1]);
expect(source[0].placement).toEqual({ x: 30, y: 40 });
});
});
+16
View File
@@ -93,6 +93,22 @@ export function packTimedSegmentsIntoLanes(segments) {
return lanes.length ? lanes : [[]];
}
export function packCaptionSegmentsIntoLanes(segments, timeline) {
const lanes = [];
segments
.map((segment, index) => ({ segment, index, range: timeline[index] }))
.sort((a, b) => (a.range?.start || 0) - (b.range?.start || 0))
.forEach((item) => {
const laneIndex = lanes.findIndex((lane) => {
const last = lane.at(-1);
return !last || (last.range?.end || 0) <= (item.range?.start || 0) + 0.001;
});
if (laneIndex >= 0) lanes[laneIndex].push(item);
else lanes.push([item]);
});
return lanes.length ? lanes : [[]];
}
export function getTimedSegmentIndexAtTime(segments, time) {
const safeTime = Math.max(0, Number.isFinite(time) ? time : 0);
for (let index = segments.length - 1; index >= 0; index -= 1) {
+14
View File
@@ -12,6 +12,7 @@ import {
moveTimedCaptionSegment,
materializeCaptionTimings,
packTimedSegmentsIntoLanes,
packCaptionSegmentsIntoLanes,
reorderTimelineItems,
} from "./timeline.js";
import {
@@ -141,3 +142,16 @@ describe("timeline primitives", () => {
expect(sticker.duration).toBeGreaterThanOrEqual(0.5);
});
});
it("packs overlapping captions into separate stable lanes", () => {
const segments = [{ id: "a" }, { id: "b" }, { id: "c" }];
const timeline = [
{ start: 0, end: 4 },
{ start: 0, end: 2 },
{ start: 2, end: 4 },
];
const lanes = packCaptionSegmentsIntoLanes(segments, timeline);
expect(lanes).toHaveLength(2);
expect(lanes[0].map(({ segment }) => segment.id)).toEqual(["a"]);
expect(lanes[1].map(({ segment }) => segment.id)).toEqual(["b", "c"]);
});
+11 -7
View File
@@ -4379,22 +4379,26 @@ button:disabled {
position: fixed;
z-index: 180;
display: grid;
width: 224px;
width: 210px;
max-width: calc(100vw - 20px);
padding: 7px;
padding: 5px;
border: 1px solid rgba(104, 132, 139, .4);
border-radius: 11px;
border-radius: 9px;
background: rgba(15, 20, 26, .98);
box-shadow: 0 18px 50px rgba(0, 0, 0, .48);
transform: translateY(-4px);
}
.timeline-context-heading { display: flex; justify-content: space-between; padding: 7px 9px 8px; color: #e9f2f4; font-size: 12px; font-weight: 750; }
.timeline-context-heading span { color: #71818a; font-size: 10px; font-weight: 650; text-transform: uppercase; }
.timeline-context-menu button { display: flex; align-items: center; gap: 9px; min-height: 34px; padding: 7px 9px; border: 0; border-radius: 7px; color: #cbd7da; text-align: left; background: transparent; cursor: pointer; }
.timeline-context-heading { display: flex; justify-content: space-between; gap: 8px; padding: 6px 7px 7px; color: #e9f2f4; font-size: 11px; line-height: 1; font-weight: 750; white-space: nowrap; }
.timeline-context-heading span { overflow: hidden; color: #71818a; font-size: 9px; font-weight: 650; text-overflow: ellipsis; text-transform: uppercase; }
.timeline-context-menu button { display: flex; align-items: center; gap: 7px; min-height: 29px; width: 100%; overflow: hidden; padding: 5px 7px; border: 0; border-radius: 6px; color: #cbd7da; font-size: 12px; line-height: 1.15; text-align: left; text-overflow: ellipsis; white-space: nowrap; background: transparent; cursor: pointer; }
.timeline-context-menu button svg { flex: 0 0 auto; }
.timeline-context-menu button:disabled { cursor: wait; opacity: .72; }
.timeline-context-menu button.is-loading svg { animation: timeline-context-spin .75s linear infinite; }
.timeline-context-menu button:hover { color: #f2ffff; background: rgba(53, 234, 217, .1); }
.timeline-context-menu button.is-danger { color: #ff9a9a; }
.timeline-context-menu button.is-danger:hover { background: rgba(255, 90, 90, .1); }
.timeline-context-divider { height: 1px; margin: 5px 4px; background: rgba(255,255,255,.08); }
.timeline-context-divider { height: 1px; margin: 4px 3px; background: rgba(255,255,255,.08); }
@keyframes timeline-context-spin { to { transform: rotate(360deg); } }
.timeline-drag-ghost {
position: fixed;