Skip to content

Open source CapCut alternative.

TypeScript

feat(site): panel adds land at the playhead

David Lec6e7712a19ed
diff --git a/site/src/cut/components/AudioPanel.tsx b/site/src/cut/components/AudioPanel.tsx
index ae6fdf15..1dcea9dc 100644
--- a/site/src/cut/components/AudioPanel.tsx
+++ b/site/src/cut/components/AudioPanel.tsx
@@ -865,7 +865,7 @@ function ProjectAudio({
playing={playingUrl === a.url}
pulse={pulsing.includes(a.id)}
onTogglePlay={onTogglePlay}
- onAdd={() => useEditor.getState().addAudioFromAsset(a.id)}
+ onAdd={() => useEditor.getState().addAssetAtPlayhead(a.id)}
menu={
<GeneratedAssetMenu
asset={a}
@@ -927,7 +927,7 @@ function ProjectMusic({
playing={playingUrl === a.url}
pulse={pulsing.includes(a.id)}
onTogglePlay={onTogglePlay}
- onAdd={() => useEditor.getState().addAudioFromAsset(a.id)}
+ onAdd={() => useEditor.getState().addAssetAtPlayhead(a.id)}
menu={
<GeneratedAssetMenu
asset={a}
diff --git a/site/src/cut/components/ChatAssets.tsx b/site/src/cut/components/ChatAssets.tsx
index 7149bb52..5ba0e8a6 100644
--- a/site/src/cut/components/ChatAssets.tsx
+++ b/site/src/cut/components/ChatAssets.tsx
@@ -213,11 +213,7 @@ function ChatCardMenu({ asset, triggerClassName }: { asset: MediaAsset; triggerC
before={
<>
<DropdownMenuItem
- onClick={() => {
- const s = useEditor.getState();
- if (asset.type === "audio") s.addAudioFromAsset(asset.id);
- else s.addClipFromAsset(asset.id);
- }}
+ onClick={() => useEditor.getState().addAssetAtPlayhead(asset.id)}
>
<Plus /> Add to timeline
</DropdownMenuItem>
@@ -325,7 +321,7 @@ function AudioCard({ item, asset }: ChatCardProps) {
peaks={asset?.peaks}
playing={playing}
onTogglePlay={(url) => usePreviewAudio.getState().toggle(url)}
- onAdd={() => asset && useEditor.getState().addAudioFromAsset(asset.id)}
+ onAdd={() => asset && useEditor.getState().addAssetAtPlayhead(asset.id)}
menu={asset && <ChatCardMenu asset={asset} triggerClassName={scrimIconButton} />}
onDragStart={(e) => {
if (asset) setAssetDragData(e, asset.id);
diff --git a/site/src/cut/components/GeneratePanel.tsx b/site/src/cut/components/GeneratePanel.tsx
index a7a0b1bd..66ec8eb9 100644
--- a/site/src/cut/components/GeneratePanel.tsx
+++ b/site/src/cut/components/GeneratePanel.tsx
@@ -387,7 +387,7 @@ function JobRow({ job, handle }: { job: GenerateJob; handle?: string }) {
<button
title="Add to timeline"
className="grid size-5 place-items-center rounded-full bg-primary text-primary-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:brightness-110"
- onClick={() => useEditor.getState().addClipFromAsset(asset.id)}
+ onClick={() => useEditor.getState().addAssetAtPlayhead(asset.id)}
>
<Plus className="size-3" />
</button>
diff --git a/site/src/cut/components/Lightbox.tsx b/site/src/cut/components/Lightbox.tsx
index f5f47025..4eb47ae7 100644
--- a/site/src/cut/components/Lightbox.tsx
+++ b/site/src/cut/components/Lightbox.tsx
@@ -49,11 +49,7 @@ export function Lightbox() {
setAdding(true);
try {
if (item.assetId) {
- if (item.kind === "audio") {
- useEditor.getState().addAudioFromAsset(item.assetId);
- } else {
- useEditor.getState().addClipFromAsset(item.assetId);
- }
+ useEditor.getState().addAssetAtPlayhead(item.assetId);
} else if (item.libraryId) {
// Library media copies in through the library route, like using it
// from the Library panel.
@@ -66,7 +62,7 @@ export function Lightbox() {
item.kind === "video"
? await importStockVideo(projectId, { url: item.src, name: item.name })
: await importImage(projectId, { url: item.src, name: item.name });
- useEditor.getState().addClipFromAsset(asset.id);
+ useEditor.getState().addAssetAtPlayhead(asset.id);
}
setAddedSrc(item.src);
} catch {
diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsx
index 21eac99d..6cd9989e 100644
--- a/site/src/cut/components/SidePanel.tsx
+++ b/site/src/cut/components/SidePanel.tsx
@@ -961,11 +961,7 @@ function AssetCard({ asset, projectId }: { asset: MediaAsset; projectId: string
const [hovered, setHovered] = useState(false);
const sizeBytes = useMediaFileSize(asset.url, hovered && !asset.upload);
- const add = () => {
- const s = useEditor.getState();
- if (asset.type === "video" || asset.type === "image") s.addClipFromAsset(asset.id);
- else s.addAudioFromAsset(asset.id);
- };
+ const add = () => useEditor.getState().addAssetAtPlayhead(asset.id);
const saveToLibrary = async (e: React.MouseEvent) => {
e.stopPropagation();
diff --git a/site/src/cut/components/StockMusicPanel.tsx b/site/src/cut/components/StockMusicPanel.tsx
index 7d6c6607..04dbfb85 100644
--- a/site/src/cut/components/StockMusicPanel.tsx
+++ b/site/src/cut/components/StockMusicPanel.tsx
@@ -85,7 +85,7 @@ export function SampleLibrary({ projectId }: { projectId: string }) {
name: sampleName(s.id),
duration: s.duration,
})
- .then((a) => useEditor.getState().addAudioFromAsset(a.id))
+ .then((a) => useEditor.getState().addAssetAtPlayhead(a.id))
.catch(() => {})
}
/>
diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.ts
index 304c5507..11a9db9d 100644
--- a/site/src/cut/lib/library.ts
+++ b/site/src/cut/lib/library.ts
@@ -284,15 +284,14 @@ export async function importLibraryAsset(
);
}
-/** Copy a library asset into the open project and append it to the timeline. */
+/** Copy a library asset into the open project and add it to the timeline at
+ * the playhead. */
export async function addLibraryAssetToProject(
projectId: string,
lib: LibraryAsset
): Promise<MediaAsset> {
const asset = await importLibraryAsset(projectId, lib);
- const s = useEditor.getState();
- if (asset.type === "video" || asset.type === "image") s.addClipFromAsset(asset.id);
- else s.addAudioFromAsset(asset.id);
+ useEditor.getState().addAssetAtPlayhead(asset.id);
return asset;
}
diff --git a/site/src/cut/lib/store.test.ts b/site/src/cut/lib/store.test.ts
index 0bd5b086..2d031e3e 100644
--- a/site/src/cut/lib/store.test.ts
+++ b/site/src/cut/lib/store.test.ts
@@ -295,6 +295,66 @@ describe("committed video updates (AI chat / inspector)", () => {
});
});
+describe("the panel + add", () => {
+ test("a video lands under the playhead when its track has room there", () => {
+ const a = asset(2);
+ useEditor.setState({ assets: [a], clips: [vclip({ start: 0, out: 2 })] });
+ setPlayhead(5);
+ s().addAssetAtPlayhead(a.id);
+ const added = s().clips.find((c) => c.assetId === a.id)!;
+ expect(added.start).toBeCloseTo(5);
+ expect(added.track).toBe(0);
+ });
+
+ test("an occupied playhead climbs to the first open track, opening one when the stack is full", () => {
+ const a = asset(2);
+ useEditor.setState({
+ assets: [a],
+ clips: [vclip({ start: 0, out: 8 }), vclip({ track: 1, start: 4, out: 4 })],
+ });
+ setPlayhead(5);
+ s().addAssetAtPlayhead(a.id);
+ const added = s().clips.find((c) => c.assetId === a.id)!;
+ expect(added.start).toBeCloseTo(5);
+ expect(added.track).toBe(2);
+ expectLaneSound(videoLane(0));
+ expectLaneSound(videoLane(1));
+ });
+
+ test("a gap too small for the clip counts as occupied", () => {
+ const a = asset(4);
+ useEditor.setState({
+ assets: [a],
+ clips: [vclip({ start: 0, out: 2 }), vclip({ start: 4, out: 2 })],
+ });
+ setPlayhead(2); // 2s gap, 4s clip
+ s().addAssetAtPlayhead(a.id);
+ const added = s().clips.find((c) => c.assetId === a.id)!;
+ expect(added.start).toBeCloseTo(2);
+ expect(added.track).toBe(1);
+ expectLaneSound(videoLane(0));
+ });
+
+ test("a live skimmer wins over the playhead", () => {
+ const a = asset(2);
+ useEditor.setState({ assets: [a], clips: [] });
+ setPlayhead(1);
+ setSkim(6);
+ s().addAssetAtPlayhead(a.id);
+ expect(s().clips.find((c) => c.assetId === a.id)!.start).toBeCloseTo(6);
+ });
+
+ test("audio under a full lane opens the next lane at the same moment", () => {
+ const a = asset(3, "audio");
+ useEditor.setState({ assets: [a], audioClips: [aclip({ start: 0, out: 10 })] });
+ setPlayhead(2);
+ s().addAssetAtPlayhead(a.id);
+ const added = s().audioClips.find((c) => c.assetId === a.id)!;
+ expect(added.start).toBeCloseTo(2);
+ expect(added.lane).toBe(1);
+ });
+});
+
describe("audio lanes", () => {
test("adding at an occupied time slides right", () => {
const a = asset(2, "audio");
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index a89ce168..56ffe2f3 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -251,6 +251,11 @@ export interface EditorState {
* to that gain while it plays; `opts.lane` picks the audio track it lands
* on (default: the first one). */
addAudioFromAsset: (assetId: string, start?: number, opts?: { duck?: number; lane?: number }) => void;
+ /** The panel “+” add: the asset lands at the preview time (the skimmer while
+ * one is live, the playhead otherwise), on the lowest video track or audio
+ * lane with room for its whole length there. When every existing row is
+ * occupied at that moment it opens a new row above. */
+ addAssetAtPlayhead: (assetId: string) => void;
/** Set (or clear) the persisted brief-to-video run. Replaces the object by
* reference so autosave detects the change. */
setGenvideo: (project: VideoProject | undefined) => void;
@@ -1880,6 +1885,52 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
}));
},
+ addAssetAtPlayhead: (assetId) => {
+ const asset = get().assets.find((a) => a.id === assetId);
+ if (!asset) return;
+ push();
+ const t = Math.max(0, previewAt());
+ // A row fits when `nextFreeStart` keeps the clip at the preview time
+ // itself; the scan climbs until one does. A brand-new row always fits,
+ // so the clip lands under the indicator no matter how full the stack is.
+ const fits = (spans: { start: number; end: number }[], len: number) =>
+ nextFreeStart(spans, t, len) < t + 1e-3;
+ if (asset.type === "audio") {
+ const len = Math.max(MIN_LEN, asset.duration);
+ const all = get().audioClips;
+ const top = all.reduce((m, c) => Math.max(m, c.lane ?? 0), 0);
+ let lane = 0;
+ while (lane <= top && !fits(footprints(all.filter((c) => (c.lane ?? 0) === lane)), len))
+ lane++;
+ const clip: AudioClip = {
+ id: uid(),
+ assetId,
+ start: t,
+ in: 0,
+ out: asset.duration,
+ volume: 1,
+ ...(lane > 0 ? { lane } : {}),
+ };
+ set((s) => ({
+ audioClips: [...s.audioClips, clip],
+ ...sole({ kind: "audio", id: clip.id }),
+ }));
+ return;
+ }
+ const out = asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration;
+ const len = Math.max(MIN_LEN, out);
+ const all = get().clips;
+ const top = all.reduce((m, c) => Math.max(m, c.track), 0);
+ let track = 0;
+ while (track <= top && !fits(footprints(all.filter((c) => c.track === track)), len))
+ track++;
+ const clip: VideoClip = { id: uid(), assetId, track, start: t, in: 0, out, muted: false };
+ set((s) => ({
+ clips: [...s.clips, clip].sort((a, b) => a.start - b.start),
+ ...sole({ kind: "clip", id: clip.id }),
+ }));
+ },
+
addOverlay: () => {
// Seed the visual style from the last-used title so repeated titles in a
// project share one look; fall back to the built-in defaults.
@@ -2541,46 +2592,59 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
const out = asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration;
push();
if (place.kind === "track" && place.track === 0) {
- const taken = footprints(track0Clips(get().clips));
- const v: VideoClip = {
- id: uid(),
- assetId,
- track: 0,
- start: nextFreeStart(taken, Math.max(0, start), Math.max(MIN_LEN, out)),
- in: 0,
- out,
- muted: false,
- };
- set((s) => ({
- clips: [...s.clips, v].sort((a, b) => a.start - b.start),
- ...sole({ kind: "clip", id: v.id }),
- }));
+ // Insert at the pointer, rippling later clips right — the same landing
+ // a drag along the row gives.
+ const { start: at, shifts } = rippleInsert(
+ track0Clips(get().clips),
+ Math.max(0, start),
+ Math.max(MIN_LEN, out)
+ );
+ const move = new Map(shifts.map((sh) => [sh.id, sh.start]));
+ const v: VideoClip = { id: uid(), assetId, track: 0, start: at, in: 0, out, muted: false };
+ set((s) => {
+ const clips = [
+ ...s.clips.map((c) => (move.has(c.id) ? { ...c, start: move.get(c.id)! } : c)),
+ v,
+ ].sort((a, b) => a.start - b.start);
+ return {
+ clips,
+ transitions: reanchorTransitions(s.clips, clips, s.transitions),
+ ...sole({ kind: "clip", id: v.id }),
+ };
+ });
return;
}
// Full-frame by default: covers track 0 ("topmost plays"); the inspector
// regions it (split half / corner PiP).
const track = place.kind === "insert" ? place.level : place.track;
- // An existing track has residents: slide to its next free slot, like the
- // track-0 add. An inserted track is brand-new, so the start holds as-is.
- const at =
+ // An existing track has residents: insert at the pointer and ripple that
+ // track's later clips right. An inserted track is brand-new, so the
+ // start holds as-is.
+ const landing =
place.kind === "track"
- ? nextFreeStart(
- footprints(get().clips.filter((c) => c.track === track)),
+ ? rippleInsert(
+ get().clips.filter((c) => c.track === track),
Math.max(0, start),
Math.max(MIN_LEN, out)
)
- : Math.max(0, start);
+ : { start: Math.max(0, start), shifts: [] as { id: string; start: number }[] };
+ const move = new Map(landing.shifts.map((sh) => [sh.id, sh.start]));
const ov: VideoClip = {
id: uid(),
assetId,
track,
- start: at,
+ start: landing.start,
in: 0,
out,
muted: false,
};
set((s) => ({
- clips: [...shiftTracksUp(s.clips, place), ov],
+ clips: [
+ ...shiftTracksUp(s.clips, place).map((c) =>
+ move.has(c.id) ? { ...c, start: move.get(c.id)! } : c
+ ),
+ ov,
+ ],
...sole({ kind: "clip", id: ov.id }),
}));
},
@@ -2594,29 +2658,46 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
if (place.kind === "track" && place.track === 0) {
if (onTrack0) return; // a same-track move commits through the lane coordinator
- // Drop a layer clip down onto track 0: slide to its next free slot.
- const taken = footprints(track0Clips(get().clips));
- const at = nextFreeStart(taken, Math.max(0, start), clipLen(src));
- set((st) => ({
- clips: st.clips.map((c) =>
- c.id === id ? { ...c, track: 0, start: at } : c
- ).sort((a, b) => a.start - b.start),
- ...sole({ kind: "clip", id }),
- }));
+ // Drop a layer clip down onto track 0: insert at the pointer, rippling
+ // later clips right — the same landing a drag along the row gives.
+ const { start: at, shifts } = rippleInsert(
+ track0Clips(get().clips),
+ Math.max(0, start),
+ clipLen(src)
+ );
+ const move = new Map(shifts.map((sh) => [sh.id, sh.start]));
+ set((st) => {
+ const clips = st.clips
+ .map((c) =>
+ c.id === id
+ ? { ...c, track: 0, start: at }
+ : move.has(c.id)
+ ? { ...c, start: move.get(c.id)! }
+ : c
+ )
+ .sort((a, b) => a.start - b.start);
+ return {
+ clips,
+ transitions: reanchorTransitions(st.clips, clips, st.transitions),
+ ...sole({ kind: "clip", id }),
+ };
+ });
return;
}
const track = place.kind === "insert" ? place.level : place.track;
- // An existing track has residents: slide to its next free slot, like the
- // track-0 drop. An inserted track is brand-new, so the start holds as-is.
- const at =
+ // An existing track has residents: insert at the pointer and ripple that
+ // track's later clips right. An inserted track is brand-new, so the
+ // start holds as-is.
+ const landing =
place.kind === "track"
- ? nextFreeStart(
- footprints(get().clips.filter((c) => c.track === track && c.id !== id)),
+ ? rippleInsert(
+ get().clips.filter((c) => c.track === track && c.id !== id),
Math.max(0, start),
clipLen(src)
)
- : Math.max(0, start);
+ : { start: Math.max(0, start), shifts: [] as { id: string; start: number }[] };
+ const move = new Map(landing.shifts.map((sh) => [sh.id, sh.start]));
set((st) => {
// Inserting a new track opens the slot by renumbering the others; the
// moved clip itself is excluded from the shift, then placed at `track`.
@@ -2624,7 +2705,13 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
place.kind === "insert" ? openInsertSlot(st.clips, place.level, id) : st.clips;
return {
clips: shifted
- .map((c) => (c.id === id ? { ...c, track, start: at } : c))
+ .map((c) =>
+ c.id === id
+ ? { ...c, track, start: landing.start }
+ : move.has(c.id)
+ ? { ...c, start: move.get(c.id)! }
+ : c
+ )
.sort((a, b) => a.start - b.start),
...sole({ kind: "clip", id }),
};