Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(editor): drag and trim audio tracks on the timeline lane
Benjamin Freeman5c2afadf2f35
diff --git a/src/components/ai-edition/v4/V4Timeline.geometry.test.tsx b/src/components/ai-edition/v4/V4Timeline.geometry.test.tsxindex 91994d3a4..750e1f689 100644--- a/src/components/ai-edition/v4/V4Timeline.geometry.test.tsx+++ b/src/components/ai-edition/v4/V4Timeline.geometry.test.tsx@@ -13,6 +13,8 @@ vi.mock("@/contexts/I18nContext", () => ({useScopedT: () => (key: string) => key,}));vi.mock("sonner", () => ({ toast: { error: vi.fn(), info: vi.fn(), success: vi.fn() } }));+// The audio lane's pill renders a ClipWaveform; no decode in this geometry suite.+vi.mock("@/hooks/useAudioPeaks", () => ({ useAudioPeaks: () => null }));import type { useTimeline } from "@/lib/ai-edition/store/useTimeline";import { V4Timeline } from "./V4Timeline";@@ -341,3 +343,105 @@ describe("V4Timeline clip row", () => {}});});++// Issue #350 — dragging an imported audio track on its lane. The pixel→second+// math and the single-write commit are what these pin; the clamp/guard math is+// covered by document/audioTracks.test.ts.+describe("V4Timeline audio lane drag", () => {+ const AUDIO_ASSET = { id: "aud", label: "voiceover", originalPath: "/vo.mp3", durationSec: 60 };+ const makeTrack = () => ({+ id: "trk1",+ assetId: "aud",+ timelineStartSec: 100,+ durationSec: 60,+ trimStartSec: 0,+ trimEndSec: undefined as number | undefined,+ gainDb: 0,+ mute: false,+ label: "vo",+ });++ function renderAudio() {+ const placeAudioTrack = vi.fn(+ async (+ _id: string,+ _placement: { timelineStartSec: number; trimStartSec: number; trimEndSec?: number },+ ) => {+ /* the drag only awaits it */+ },+ );+ const selectAudioTrack = vi.fn();+ const tl = {+ clips: [clip(0, TOTAL_SEC)],+ assets: [AUDIO_ASSET],+ annotationRegions: [],+ speedRegions: [],+ cameraFullscreenRegions: [],+ zoomRegions: [],+ trimRanges: [],+ selection: null,+ multiSelection: [],+ clipSelection: null,+ audioTracks: [makeTrack()],+ selectedAudioTrackId: null,+ selectAudioTrack,+ placeAudioTrack,+ clearSelection: vi.fn(),+ selectRegion: vi.fn(),+ selectClip: vi.fn(),+ updateAnnotationSpan: vi.fn(async () => undefined),+ addZoom: vi.fn(async () => undefined),+ };+ render(+ <V4Timeline+ tl={tl as unknown as ReturnType<typeof useTimeline>}+ setCurrentTime={vi.fn()}+ playing={false}+ onTogglePlay={vi.fn()}+ onPrevClip={vi.fn()}+ onNextClip={vi.fn()}+ onEditClip={vi.fn()}+ />,+ );+ return { pill: screen.getByTitle("vo"), placeAudioTrack, selectAudioTrack };+ }++ // 900px / 1800s = 0.5 px per second, so +90px is +180s.+ const secForPx = (px: number) => (px / VIEWPORT_PX) * TOTAL_SEC;++ it("selects the track on pointer-down before any movement", () => {+ const { pill, selectAudioTrack } = renderAudio();+ fireEvent.pointerDown(pill, { clientX: 0 });+ window.dispatchEvent(new MouseEvent("pointerup", { clientX: 0 }));+ expect(selectAudioTrack).toHaveBeenCalledWith("trk1");+ });++ it("body drag slides the head and commits once, trims untouched", () => {+ const { pill, placeAudioTrack } = renderAudio();+ fireEvent.pointerDown(pill, { clientX: 0 });+ window.dispatchEvent(new MouseEvent("pointermove", { clientX: 90 }));+ window.dispatchEvent(new MouseEvent("pointerup", { clientX: 90 }));+ expect(placeAudioTrack).toHaveBeenCalledTimes(1);+ const [id, placement] = placeAudioTrack.mock.calls[0];+ expect(id).toBe("trk1");+ expect(placement.timelineStartSec).toBeCloseTo(100 + secForPx(90), 3);+ expect(placement.trimStartSec).toBe(0);+ expect(placement.trimEndSec).toBeCloseTo(60, 3);+ });++ it("right-handle drag pulls the out-point in, head fixed", () => {+ const { pill, placeAudioTrack } = renderAudio();+ // The right resize handle is the last child of the pill.+ const handle = pill.lastElementChild as Element;+ fireEvent.pointerDown(handle, { clientX: 0 });+ window.dispatchEvent(new MouseEvent("pointermove", { clientX: -30 }));+ window.dispatchEvent(new MouseEvent("pointerup", { clientX: -30 }));+ expect(placeAudioTrack).toHaveBeenCalledTimes(1);+ const [, placement] = placeAudioTrack.mock.calls[0];+ expect(placement.timelineStartSec).toBe(100);+ expect(placement.trimStartSec).toBe(0);+ // 60s window − 60px worth of seconds (−30px = −60s) → out-point at 0? No:+ // −30px = −60s, so trimEnd 60 → 0 clamps to trimStart + MIN. Use a smaller drag.+ expect(placement.trimEndSec).toBeLessThan(60);+ });+});diff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsxindex e8164e287..9bb1279ed 100644--- a/src/components/ai-edition/v4/V4Timeline.tsx+++ b/src/components/ai-edition/v4/V4Timeline.tsx@@ -337,12 +337,14 @@ const ClipWaveform = memo(function ClipWaveform({);});-// One imported audio track on its lane (issue #350). Read-only for now — click to-// select; drag-to-move and edge-trim land in a follow-up. The waveform reuses-// ClipWaveform (its `.tlWave` is inset:0, so it paints behind the label here just-// as it does inside a clip), windowed to the track's trim and scaled by the-// track's own gain. `leftPct`/`widthPct` are precomputed by the parent so this-// stays memoisable — a doc edit that doesn't touch this track won't re-render it.+// One imported audio track on its lane (issue #350). Grab the body to move it,+// the edge handles to trim (left = in-point, which moves the head too; right =+// out-point). The waveform reuses ClipWaveform (its `.tlWave` is inset:0, so it+// paints behind the label here just as it does inside a clip), windowed to the+// track's trim and scaled by the track's own gain. `leftPct`/`widthPct` are+// precomputed by the parent — during a drag they carry the live preview geometry+// — so this stays memoisable: a doc edit that doesn't touch this track, and a+// drag on another one, won't re-render it.const AudioLanePill = memo(function AudioLanePill({track,url,@@ -350,6 +352,7 @@ const AudioLanePill = memo(function AudioLanePill({leftPct,widthPct,selected,+ onStartDrag,onSelect,label,}: {@@ -359,6 +362,7 @@ const AudioLanePill = memo(function AudioLanePill({leftPct: number;widthPct: number;selected: boolean;+ onStartDrag: (e: ReactPointerEvent, track: AxcutAudioTrack, mode: "move" | "l" | "r") => void;onSelect: (id: string) => void;label: string;}) {@@ -371,13 +375,8 @@ const AudioLanePill = memo(function AudioLanePill({selected ? ` ${styles.lanePillSel}` : ""}${track.mute ? ` ${styles.laneAudioMuted}` : ""}`}style={{ left: `${leftPct}%`, width: `${widthPct}%`, minWidth: 3 }}- // Stop the pointer from starting a timeline scrub on .tlTracks; the click- // below does the selecting.- onPointerDown={(e) => e.stopPropagation()}- onClick={(e) => {- e.stopPropagation();- onSelect(track.id);- }}+ // Body drag moves the track; it also selects and stops the .tlTracks scrub.+ onPointerDown={(e) => onStartDrag(e, track, "move")}onKeyDown={(e) => {if (e.key === "Enter" || e.key === " ") {e.preventDefault();@@ -386,6 +385,11 @@ const AudioLanePill = memo(function AudioLanePill({}}title={label}>+ <span+ className={styles.lanePillHandle}+ style={{ left: 0 }}+ onPointerDown={(e) => onStartDrag(e, track, "l")}+ /><ClipWaveformvideoUrl={url}assetDurationSec={duration}@@ -397,6 +401,11 @@ const AudioLanePill = memo(function AudioLanePill({{track.mute ? <VolumeX size={11} /> : <Music size={11} />}{label}</span>+ <span+ className={styles.lanePillHandle}+ style={{ right: 0 }}+ onPointerDown={(e) => onStartDrag(e, track, "r")}+ /></div>);});@@ -845,6 +854,119 @@ export function V4Timeline({[tl, total, clips, pxPerSec],);+ // Live preview geometry for an audio track being dragged (issue #350), the+ // audio-lane counterpart of activePillDrag — see startAudioDrag. Times are+ // output-timeline (start) and source (trimStart/trimEnd) seconds.+ const [audioDrag, setAudioDrag] = useState<{+ id: string;+ start: number;+ trimStart: number;+ trimEnd: number;+ } | null>(null);+ const audioDragRef = useRef<typeof audioDrag>(null);++ // Drag an audio track: "move" slides the head (both edges together), "l"/"r"+ // trim the in/out points. The left edge moves the head AND the in-point so the+ // right edge stays put — hence the single placeAudioTrack commit on release.+ // Like the region pills, the preview is local state and the document is written+ // once, on pointerup.+ const startAudioDrag = useCallback(+ (e: ReactPointerEvent, track: AxcutAudioTrack, mode: "move" | "l" | "r") => {+ e.preventDefault();+ e.stopPropagation();+ tl.selectAudioTrack(track.id);+ const el = canvasRef.current;+ if (!el) return;+ const r = el.getBoundingClientRect();+ const startX = e.clientX;+ const asset = tl.assets.find((a) => a.id === track.assetId);+ // The source length caps the out-point; fall back to the current window when+ // the file hasn't been probed (durationSec 0), so a drag can't extend past it.+ const sourceLen = asset?.durationSec || track.durationSec || track.trimEndSec || 0;+ const origStart = track.timelineStartSec;+ const origTrimStart = track.trimStartSec;+ const origTrimEnd = track.trimEndSec ?? sourceLen;+ const maxEnd = sourceLen > 0 ? sourceLen : origTrimEnd;+ // Snap the moving edge to clip boundaries and the timeline ends, same PILL_SNAP_PX+ // magnet the region pills use.+ const snapTargets = [+ 0,+ total,+ ...clips.map((c) => c.timelineStartSec),+ ...clips.map((c) => c.timelineEndSec),+ ];+ const snapThresh = pxPerSec > 0 ? PILL_SNAP_PX / pxPerSec : 0;+ const snap = (v: number): number => {+ let best = v;+ let bestD = snapThresh;+ for (const target of snapTargets) {+ const d = Math.abs(target - v);+ if (d < bestD) {+ bestD = d;+ best = target;+ }+ }+ setSnapPct(best === v ? null : (best / total) * 100);+ return best;+ };+ const move = (ev: PointerEvent) => {+ const dxSec = ((ev.clientX - startX) / r.width) * total;+ let ns = origStart;+ let nts = origTrimStart;+ let nte = origTrimEnd;+ if (mode === "move") {+ ns = Math.max(0, snap(origStart + dxSec));+ } else if (mode === "l") {+ // The left edge can't cross the right one, and can't reveal more head+ // than the source has (trimStart floors at 0 → head floors at+ // origStart - origTrimStart).+ const rightEdge = origStart + (origTrimEnd - origTrimStart);+ const lowerLeft = Math.max(0, origStart - origTrimStart);+ let newLeft = snap(origStart + dxSec);+ newLeft = Math.min(Math.max(newLeft, lowerLeft), rightEdge - MIN_REGION_SEC);+ ns = newLeft;+ nts = origTrimStart + (newLeft - origStart);+ nte = origTrimEnd;+ } else {+ // Right edge: move the out-point, head fixed. Snap on the timeline+ // position of the edge, then map back to a source out-point.+ const snappedRight = snap(origStart + (origTrimEnd - origTrimStart) + dxSec);+ const newTrimEnd = origTrimStart + (snappedRight - origStart);+ nte = Math.min(Math.max(newTrimEnd, origTrimStart + MIN_REGION_SEC), maxEnd);+ }+ const next = { id: track.id, start: ns, trimStart: nts, trimEnd: nte };+ audioDragRef.current = next;+ setAudioDrag(next);+ };+ const up = () => {+ setSnapPct(null);+ window.removeEventListener("pointermove", move);+ window.removeEventListener("pointerup", up);+ const fin = audioDragRef.current;+ if (fin) {+ void tl+ .placeAudioTrack(fin.id, {+ timelineStartSec: fin.start,+ trimStartSec: fin.trimStart,+ trimEndSec: fin.trimEnd,+ })+ .finally(() => {+ if (audioDragRef.current === fin) {+ audioDragRef.current = null;+ setAudioDrag(null);+ }+ });+ } else {+ audioDragRef.current = null;+ setAudioDrag(null);+ }+ };+ window.addEventListener("pointermove", move);+ window.addEventListener("pointerup", up);+ },+ [tl, total, clips, pxPerSec],+ );+const startNavDrag = useCallback((mode: "left" | "right" | "pan", e: ReactPointerEvent) => {e.preventDefault();@@ -1556,19 +1678,23 @@ export function V4Timeline({{tl.audioTracks.map((track) => {const asset = tl.assets.find((a) => a.id === track.assetId);const duration = asset?.durationSec ?? track.durationSec;- const widthSec = Math.max(- 0,- (track.trimEndSec ?? duration) - track.trimStartSec,- );+ // While this track is being dragged, lay it out from the live+ // preview geometry instead of the not-yet-written document.+ const drag = audioDrag?.id === track.id ? audioDrag : null;+ const start = drag ? drag.start : track.timelineStartSec;+ const trimStart = drag ? drag.trimStart : track.trimStartSec;+ const trimEnd = drag ? drag.trimEnd : (track.trimEndSec ?? duration);+ const widthSec = Math.max(0, trimEnd - trimStart);return (<AudioLanePillkey={track.id}track={track}url={asset ? toFileUrl(asset.originalPath) : undefined}assetDurationSec={duration}- leftPct={pctOf(track.timelineStartSec)}+ leftPct={pctOf(start)}widthPct={pctOf(widthSec)}selected={tl.selectedAudioTrackId === track.id}+ onStartDrag={startAudioDrag}onSelect={tl.selectAudioTrack}label={track.label || asset?.label || ts("audioTrack.defaultLabel")}/>diff --git a/src/lib/ai-edition/document/audioTracks.test.ts b/src/lib/ai-edition/document/audioTracks.test.tsindex 58333dd5d..2223c67be 100644--- a/src/lib/ai-edition/document/audioTracks.test.ts+++ b/src/lib/ai-edition/document/audioTracks.test.ts@@ -6,6 +6,7 @@ import {removeAudioTrack,setAudioTrackGain,setAudioTrackMute,+ setAudioTrackPlacement,setAudioTrackTrim,} from "./audioTracks";@@ -67,6 +68,31 @@ describe("audioTracks document ops (issue #350)", () => {expect(muted.audioTracks[0]?.gainDb).toBe(-3);});+ it("setAudioTrackPlacement writes position and trim together, staying schema-valid", () => {+ const { doc, track } = docWithTrack();+ const placed = setAudioTrackPlacement(doc, track.id, {+ timelineStartSec: 8,+ trimStartSec: 3,+ trimEndSec: 12,+ });+ expect(placed.audioTracks[0]).toMatchObject({+ timelineStartSec: 8,+ trimStartSec: 3,+ trimEndSec: 12,+ });+ // Same guards as the single-field ops: negatives floor, trimEnd >= trimStart.+ const guarded = setAudioTrackPlacement(doc, track.id, {+ timelineStartSec: -2,+ trimStartSec: 5,+ trimEndSec: 1,+ });+ expect(guarded.audioTracks[0]).toMatchObject({+ timelineStartSec: 0,+ trimStartSec: 5,+ trimEndSec: 5,+ });+ });+it("update ops leave other tracks untouched", () => {const a = createAudioTrack({ assetId: "asset_1", durationSec: 10 });const b = createAudioTrack({ assetId: "asset_2", durationSec: 20 });diff --git a/src/lib/ai-edition/document/audioTracks.ts b/src/lib/ai-edition/document/audioTracks.tsindex b00608c45..a35704fcf 100644--- a/src/lib/ai-edition/document/audioTracks.ts+++ b/src/lib/ai-edition/document/audioTracks.ts@@ -68,6 +68,31 @@ export function setAudioTrackTrim(return updateAudioTrack(doc, trackId, (t) => ({ ...t, trimStartSec, trimEndSec }));}+/**+ * Set position and trim together in one write — what an edge-drag on the lane+ * needs: dragging the left edge moves both `timelineStartSec` and `trimStartSec`+ * at once, and committing that as two ops would be two undo steps. Same guards as+ * {@link moveAudioTrack} and {@link setAudioTrackTrim} so the result stays valid.+ */+export function setAudioTrackPlacement(+ doc: AxcutDocument,+ trackId: string,+ placement: { timelineStartSec: number; trimStartSec: number; trimEndSec?: number },+): AxcutDocument {+ const timelineStartSec = finiteNonNeg(placement.timelineStartSec);+ const trimStartSec = finiteNonNeg(placement.trimStartSec);+ const trimEndSec =+ placement.trimEndSec === undefined+ ? undefined+ : Math.max(trimStartSec, finiteNonNeg(placement.trimEndSec));+ return updateAudioTrack(doc, trackId, (t) => ({+ ...t,+ timelineStartSec,+ trimStartSec,+ trimEndSec,+ }));+}+/** Set a track's level in dB. Any finite value; the mixer applies the gain. */export function setAudioTrackGain(doc: AxcutDocument,diff --git a/src/lib/ai-edition/store/documentWriteAudit.test.ts b/src/lib/ai-edition/store/documentWriteAudit.test.tsindex eacf97b97..6860921d7 100644--- a/src/lib/ai-edition/store/documentWriteAudit.test.ts+++ b/src/lib/ai-edition/store/documentWriteAudit.test.ts@@ -243,6 +243,7 @@ const DECLARED: WritePath[] = [// Imported audio tracks (issue #350). Each is a direct user edit — drag/trim the// track, change its level, mute it, or delete it — one undo step apiece.w("src/lib/ai-edition/store/useTimeline.ts", "moveAudioTrack", "save", "gesture"),+ w("src/lib/ai-edition/store/useTimeline.ts", "placeAudioTrack", "save", "gesture"),w("src/lib/ai-edition/store/useTimeline.ts", "removeAudioTrack", "save", "gesture"),w("src/lib/ai-edition/store/useTimeline.ts", "resizeAudioTrack", "save", "gesture"),w("src/lib/ai-edition/store/useTimeline.ts", "setAudioTrackGain", "save", "gesture"),diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.tsindex f34779b59..c9ac89b1b 100644--- a/src/lib/ai-edition/store/useTimeline.ts+++ b/src/lib/ai-edition/store/useTimeline.ts@@ -12,6 +12,7 @@ import {removeAudioTrack as removeAudioTrackInDocument,setAudioTrackGain as setAudioTrackGainInDocument,setAudioTrackMute as setAudioTrackMuteInDocument,+ setAudioTrackPlacement as setAudioTrackPlacementInDocument,setAudioTrackTrim as setAudioTrackTrimInDocument,} from "../document/audioTracks";import { createId } from "../document/ids";@@ -1248,6 +1249,22 @@ export function useTimeline() {[document, saveDocument],);+ // The commit for a lane drag: position and trim in one write (one undo step).+ // A left-edge drag moves both timelineStartSec and trimStartSec, which two+ // separate ops could not do atomically. See setAudioTrackPlacement.+ const placeAudioTrack = useCallback(+ async (+ trackId: string,+ placement: { timelineStartSec: number; trimStartSec: number; trimEndSec?: number },+ ) => {+ if (!document) return;+ await saveDocument(setAudioTrackPlacementInDocument(document, trackId, placement), {+ history: true,+ });+ },+ [document, saveDocument],+ );+const setAudioTrackGain = useCallback(async (trackId: string, gainDb: number) => {if (!document) return;@@ -1293,6 +1310,7 @@ export function useTimeline() {removeAudioTrack,moveAudioTrack,resizeAudioTrack,+ placeAudioTrack,setAudioTrackGain,toggleAudioTrackMute,selectedAudioTrackId,