Skip to content

Open source CapCut alternative.

TypeScript

fix(site): drag a clip from chat onto the timeline as a placed segment

David Led217c01ecb7f
diff --git a/site/src/cut/components/ChatAssets.tsx b/site/src/cut/components/ChatAssets.tsx
index 06a64085..057c6be9 100644
--- a/site/src/cut/components/ChatAssets.tsx
+++ b/site/src/cut/components/ChatAssets.tsx
@@ -4,7 +4,7 @@ import { useEffect, type ReactNode } from "react";
import type React from "react";
import { Copy, ExternalLink, FileText, Film, Loader2, Maximize2, Plus } from "lucide-react";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
-import { clearAssetDrag, setAssetDragData } from "@/cut/lib/assetDrag";
+import { clearAssetDrag, setAssetDragData, setChipDragImage } from "@/cut/lib/assetDrag";
import {
projectRefs,
refFromAsset,
@@ -158,6 +158,9 @@ const dragProps = (item: AssetRef, asset?: MediaAsset) => ({
// either way so composers and creators accept the drag too.
if (asset) setAssetDragData(e, asset.id);
else setRefDragData(e, item);
+ // A small cursor chip instead of the full-card snapshot, so dragging a clip
+ // onto the timeline doesn't blanket the track it's aiming for.
+ setChipDragImage(e);
},
onDragEnd: clearAssetDrag,
});
diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsx
index f61e9eb1..ae7be2cf 100644
--- a/site/src/cut/components/Timeline.tsx
+++ b/site/src/cut/components/Timeline.tsx
@@ -32,7 +32,7 @@ import {
import { isDragActive, startDrag, subscribeDragActive } from "@/cut/lib/drag";
import { CLIP_GAP, startLaneMove, startLaneTrim, type LaneDrag } from "@/cut/lib/laneTracks";
import { ensurePeaks, importImage, importStockMusic, importStockVideo } from "@/cut/lib/media";
-import { baseClips, clipLen, clipSpeed, getClipSpans, nextFreeStart, overlayLayers, projectDuration, TIMELINE_H_MAX, useEditor } from "@/cut/lib/store";
+import { baseClips, clipLen, clipSpeed, getClipSpans, overlayLayers, projectDuration, rippleInsertBase, TIMELINE_H_MAX, useEditor } from "@/cut/lib/store";
import type { VideoTrackPlacement } from "@/cut/lib/store";
import { subtitleLaneCount } from "@/cut/lib/subtitles";
import { formatTime, formatTimecode } from "@/cut/lib/time";
@@ -216,8 +216,11 @@ export function Timeline() {
const contentW = heldContentW.current;
// Drop preview while dragging a media asset onto video track 0: where the
- // pointer is and how long the clip would run.
- const [assetDrop, setAssetDrop] = useState<{ t: number; len: number } | null>(null);
+ // clip would land, how long it runs, and a poster frame so the preview reads
+ // as the segment itself sliding along the row rather than an empty slot.
+ const [assetDrop, setAssetDrop] = useState<{ t: number; len: number; thumb?: string } | null>(
+ null
+ );
// Kind of external media being dragged over the timeline (audio vs video).
const [dropType, setDropType] = useState<"video" | "audio" | null>(null);
// A video clip is being dragged (internal or external): reveals the track
@@ -504,7 +507,9 @@ export function Timeline() {
const s = useEditor.getState();
if (isClipMedia(type)) {
if (place.kind === "insert") s.addVideoFromAsset(assetId, place, t);
- else s.addClipFromAsset(assetId, t);
+ // Drop at the pointer, rippling later clips right — so a drop into a
+ // leading gap or between clips lands there instead of sliding to the end.
+ else s.dropClipFromAsset(assetId, t);
} else {
const used = [...new Set(s.audioClips.map((a) => a.lane ?? 0))].sort((a, b) => a - b);
const lane =
@@ -675,6 +680,8 @@ export function Timeline() {
// stock drags carry their own shape since they aren't in the project yet.
let type: "video" | "audio" | "image" | undefined;
let duration = 0;
+ // Poster frame for the on-track ghost, when the source can offer one.
+ let thumb: string | undefined;
if (isLib) {
const lib = draggingLibrary();
type = lib?.type;
@@ -693,6 +700,7 @@ export function Timeline() {
const asset = id ? useEditor.getState().assets.find((a) => a.id === id) : null;
type = asset?.type;
duration = asset?.type === "image" ? STILL_SECONDS : asset?.duration ?? 0;
+ thumb = asset?.type === "image" ? asset.url : asset?.thumbs?.[0];
}
// A still rides the video tracks: reveal their guides and new-track rows.
setDropType(isClipMedia(type) ? "video" : type ?? null);
@@ -720,15 +728,12 @@ export function Timeline() {
return;
}
setOverlayDrop(null);
- // Preview the true landing spot: the drop slides past occupied
- // stretches to the next free slot, so the dashed box must too — a
- // box under the pointer that lands minutes away is a lie.
+ // Preview the true landing spot: a drop at the pointer inserts here,
+ // rippling later clips right, so the ghost sits where the segment will
+ // actually land — a box under the pointer that lands minutes away lies.
const cur = useEditor.getState();
- const taken = baseClips(cur.clips).map((c) => ({ start: c.start, end: c.start + clipLen(c) }));
- setAssetDrop({
- t: nextFreeStart(taken, dropTimeAt(e.clientX), duration),
- len: duration,
- });
+ const { start } = rippleInsertBase(baseClips(cur.clips), dropTimeAt(e.clientX), duration);
+ setAssetDrop({ t: start, len: duration, thumb });
}}
onDragLeave={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {
@@ -969,7 +974,10 @@ export function Timeline() {
onPointerDown={deselectIfSelf}
>
{spans.length > 0 && laneRail(VIDEO_H - 2)}
- {videoDragActive && trackGuide(TRACK_ZERO)}
+ {/* An external asset drag previews as an on-track segment ghost
+ (below), so the base row skips the full-width dashed guide that
+ would otherwise cover it; an internal clip move still shows it. */}
+ {videoDragging && trackGuide(TRACK_ZERO)}
{trackSlot(TRACK_ZERO, VIDEO_H - 4)}
{laneDrag?.kind === "clip" && !laneDrag.away && (
<LaneSlot
@@ -981,15 +989,30 @@ export function Timeline() {
/>
)}
{assetDrop && (
+ // The dragged clip as a floating segment: the poster fills it and
+ // it rides above the row's clips (z-20), so a drag reads as a
+ // placed segment sliding to its landing spot, not a hole to fill.
<div
- className="tl-asset-drop-slot pointer-events-none absolute top-0.5 flex items-center justify-center rounded-lg border-[1.5px] border-dashed border-[#0a84ff]/70 bg-[#0a84ff]/10 text-[#0a84ff] transition-[left] duration-150 ease-out"
+ className="tl-asset-drop-slot pointer-events-none absolute top-0.5 z-20 overflow-hidden rounded-lg bg-neutral-200 opacity-90 shadow-2xl ring-[1.5px] ring-[#0a84ff]/70 transition-[left] duration-100 ease-out"
style={{
left: assetDrop.t * pps,
width: Math.max(10, assetDrop.len * pps - CLIP_GAP),
height: VIDEO_H - 4,
}}
>
- <Plus className="size-4" />
+ {assetDrop.thumb && (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img
+ src={assetDrop.thumb}
+ alt=""
+ draggable={false}
+ className="absolute inset-0 h-full w-full object-cover"
+ />
+ )}
+ <span className="absolute top-1 left-1 flex items-center gap-0.5 rounded-[5px] bg-black/65 px-1.5 py-px font-mono text-[10px] tabular-nums text-white">
+ <Plus className="size-2.5" />
+ {assetDrop.len.toFixed(1)}s
+ </span>
</div>
)}
{spans.map((span, i) => (
diff --git a/site/src/cut/lib/assetDrag.ts b/site/src/cut/lib/assetDrag.ts
index 807aa680..d407b762 100644
--- a/site/src/cut/lib/assetDrag.ts
+++ b/site/src/cut/lib/assetDrag.ts
@@ -143,6 +143,21 @@ export function setCardDragImage(e: React.DragEvent, el: HTMLElement) {
setTimeout(() => clone.remove(), 0);
}
+/** A small chip as the drag image, so the cursor carries a compact marker
+ * instead of the full card snapshot that blankets the timeline track. The
+ * timeline renders its own on-track segment ghost for where the clip lands; the
+ * chip is just the "I'm holding something" cursor. A solid div paints
+ * synchronously (no image-load race), so it works the first drag too. */
+export function setChipDragImage(e: React.DragEvent) {
+ const chip = document.createElement("div");
+ chip.style.cssText =
+ "position:absolute;top:-1000px;left:-1000px;width:60px;height:34px;border-radius:6px;" +
+ "background:#e5e5e5;box-shadow:0 6px 16px rgba(0,0,0,0.35),inset 0 0 0 1.5px rgba(10,132,255,0.7);";
+ document.body.appendChild(chip);
+ e.dataTransfer.setDragImage(chip, 30, 17);
+ setTimeout(() => chip.remove(), 0);
+}
+
/** Clear the in-flight ids; call on `dragend` and after a drop. */
export function clearAssetDrag() {
inFlightAssetId = null;
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 61813ad9..dd0420c8 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -150,6 +150,11 @@ export interface EditorState {
/** Add a video clip from an asset onto video track 0 — at `start` (sliding
* to the track's next free slot), or appended at the end when omitted. */
addClipFromAsset: (assetId: string, start?: number) => void;
+ /** Drop a video/still onto base track 0 at pointer-time `t`: inserts at the
+ * drop and ripples later clips right, so a drop into a leading gap or between
+ * clips lands there instead of sliding to the end (the drop gesture's
+ * placement, distinct from `addClipFromAsset`'s slide-to-end). */
+ dropClipFromAsset: (assetId: string, t: number) => void;
/** Add a soundtrack clip from an audio asset at `start` (default: the
* playhead). `opts.duck` marks it a voiceover that lowers everything else
* to that gain while it plays; `opts.lane` picks the audio track it lands
@@ -411,6 +416,30 @@ export function footprints(items: (VideoClip | AudioClip)[]): { start: number; e
return items.map((c) => ({ start: c.start, end: c.start + clipLen(c) }));
}
+/** Where a `len`-long clip dropped at pointer-time `t` lands on the base row,
+ * and how the clips after it slide to open room. The drop-at-pointer companion
+ * to `nextFreeStart` (which only ever appends): clips whose center sits left of
+ * the drop hold their place; the rest shift right as one run, so a clip dropped
+ * into a leading gap or between two others inserts there instead of piling up at
+ * the end when it is longer than the gap. */
+export function rippleInsertBase(
+ base: VideoClip[],
+ t: number,
+ len: number
+): { start: number; shifts: { id: string; start: number }[] } {
+ const items = base
+ .map((c) => ({ id: c.id, start: c.start, len: clipLen(c) }))
+ .sort((a, b) => a.start - b.start);
+ const center = t + len / 2;
+ const before = items.filter((c) => c.start + c.len / 2 <= center);
+ const after = items.filter((c) => c.start + c.len / 2 > center);
+ const floor = before.reduce((m, c) => Math.max(m, c.start + c.len), 0);
+ const start = Math.max(t, floor);
+ const delta = after.length ? Math.max(0, start + len - after[0].start) : 0;
+ const shifts = delta > 0 ? after.map((c) => ({ id: c.id, start: c.start + delta })) : [];
+ return { start, shifts };
+}
+
/** POST a transcribe spec and poll the job to completion. Returns the cues, or
* null when the user switches projects mid-run. Throws user-facing errors.
* Shared with the brief-to-video transcribe adapter. */
@@ -893,6 +922,24 @@ export const useEditor = create<EditorState>((set, get) => {
}));
},
+ dropClipFromAsset: (assetId, t) => {
+ const asset = get().assets.find((a) => a.id === assetId);
+ if (!asset || (asset.type !== "video" && asset.type !== "image")) return;
+ push();
+ const out = asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration;
+ const len = Math.max(MIN_LEN, out);
+ const { start, shifts } = rippleInsertBase(baseClips(get().clips), Math.max(0, t), len);
+ const move = new Map(shifts.map((sh) => [sh.id, sh.start]));
+ const clip: VideoClip = { id: uid(), assetId, track: 0, start, in: 0, out, muted: false };
+ set((s) => ({
+ clips: [
+ ...s.clips.map((c) => (move.has(c.id) ? { ...c, start: move.get(c.id)! } : c)),
+ clip,
+ ].sort((a, b) => a.start - b.start),
+ ...sole({ kind: "clip", id: clip.id }),
+ }));
+ },
+
addAudioFromAsset: (assetId, start, opts) => {
const asset = get().assets.find((a) => a.id === assetId);
if (!asset || asset.type !== "audio") return;