Open source CapCut alternative.
TypeScript
feat(site): select and move preview items together [rebuild]
David Le6ba06b8cd0ba
diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.mdindex f2f5d9cc..1546d48b 100644--- a/docs/guides/cut/README.md+++ b/docs/guides/cut/README.md@@ -28,6 +28,8 @@ AI is hosted whatever the home: image, video, and voiceover generation and the aThe preview scrubs and plays from per-clip decoders held in memory. It shows a frame the moment it arrives and refines behind it, so the timeline always answers and a jump lands on a picture. Every cache is bounded by one memory budget sized to the machine. The performance guide holds the frame budget and how a change is measured.+Timeline and preview share selection: ⌘/Ctrl-click toggles items, and dragging moves them together with one undo step.+Guides draw over the preview from the button beside the timeline zoom: thirds, center, safe margins, the short-form keep-out zone where TikTok, Reels and Shorts draw their own UI or crop the sides of a 9:16 frame, and custom lines dragged into place on the preview. They save with the project, snap a dragged element to their edges, never export, and the assistant reads the safe area they leave when it places graphics.## The exportdiff --git a/site/src/cut/components/OverlayLayer.tsx b/site/src/cut/components/OverlayLayer.tsxindex d5a98ba1..26a15dc9 100644--- a/site/src/cut/components/OverlayLayer.tsx+++ b/site/src/cut/components/OverlayLayer.tsx@@ -5,6 +5,7 @@ import { createContext, Fragment, useCallback, useContext, useEffect, useLayoutEimport { createPortal } from "react-dom";import { releaseAnimRest, useAnimPreview } from "@/cut/lib/animPreview";import { startDrag } from "@/cut/lib/drag";+import { startSelectionDrag } from "@/cut/components/previewSelectionDrag";import { useSkim, usePreviewTime } from "@/cut/lib/playhead";import { useEditor } from "@/cut/lib/store";import {@@ -178,6 +179,7 @@ export function OverlayLayer({[allOverlays, from, to]);const selection = useEditor((s) => s.selection);+ const multiSelection = useEditor((s) => s.multiSelection);const aspect = useEditor((s) => s.aspect);const shownGuides = useEditor((s) => s.guides);const guideLines = useEditor((s) => s.guideLines);@@ -300,7 +302,9 @@ export function OverlayLayer({const scrubbing = skimTime !== null;const sel =selection?.kind === "overlay" ? overlays.find((o) => o.id === selection.id) : undefined;- const isolate = !!sel && !scrubbing && !(t >= sel.start && t <= sel.end);+ const multiple = multiSelection.length > 1;+ const selectedIds = useMemo(() => new Set(multiSelection.flatMap((item) => item?.kind === "overlay" ? [item.id] : [])), [multiSelection]);+ const isolate = !multiple && !!sel && !scrubbing && !(t >= sel.start && t <= sel.end);return (<div@@ -314,16 +318,13 @@ export function OverlayLayer({// (see StageEffects), so it draws nothing here and takes no box,// handles or drag. The timeline bar is the thing you grab.if (o.kind === "effect") return null;- const selected = sel?.id === o.id;- // A group drags as a unit, so any member is grabbable once the- // selection is anywhere inside it.- const inGroup = !!sel?.groupId && sel.groupId === o.groupId;+ const selected = selectedIds.has(o.id) || sel?.id === o.id;const inRange = t >= o.start && t <= o.end;// While hover-scrubbing (paused, skimmer active) the preview must show the// exact frame under the skimmer — a selected but out-of-frame title can't// leak into a frame it isn't part of. Off the skimmer, a selected title// that sits off the playhead is shown alone (isolate) for editing.- if (isolate ? !selected : !inRange && (scrubbing || !selected)) return null;+ if (isolate ? !selected : !inRange && (scrubbing || !selected || multiple)) return null;return (<OverlayItemkey={o.id}@@ -331,7 +332,7 @@ export function OverlayLayer({// The skimmer paints the bare frame: the item still renders, its// selection chrome (outline, resize handle) does not.selected={selected && !scrubbing}- armed={(selected || inGroup) && !scrubbing}+ armed={selected && !scrubbing}ghost={!inRange && !selected}t={t}stageWidth={stageWidth}@@ -449,6 +450,7 @@ function SubtitleCaption({const subtitles = useEditor((s) => s.subtitles);const frame = frameOf(useEditor((s) => s.aspect));const selection = useEditor((s) => s.selection);+ const multiSelection = useEditor((s) => s.multiSelection);const stagePress = useContext(StagePress);const t = usePreviewTime();@@ -457,7 +459,8 @@ function SubtitleCaption({if (!cue || !cue.text.trim()) return null;// The caption moves its whole track, so it takes the same rule the elements// take: the cue on screen has to be the selection before a drag moves it.- const armed = selection?.kind === "cue" && selection.id === cue.id;+ const armed = (selection?.kind === "cue" && selection.id === cue.id) ||+ multiSelection.some((item) => item?.kind === "cue" && item.id === cue.id);// Captions ride the same style/opener/anchor logic as the export burn-in,// so the preview and the rendered file match exactly.@@ -476,12 +479,22 @@ function SubtitleCaption({return (<divref={(el) => registerBox(subtitleBoxId(lane), el)}+ data-preview-kind="cue"+ data-preview-id={cue.id}className={cn("sub-caption pointer-events-auto absolute -translate-x-1/2 -translate-y-1/2 cursor-grab text-center whitespace-pre active:cursor-grabbing",armed && "outline-[1.5px] outline-offset-[3px] outline-[#0a84ff]")}onPointerDown={(e) => {+ if (e.button !== 0) return;const s = useEditor.getState();+ if (e.metaKey || e.ctrlKey) {+ e.preventDefault();+ e.stopPropagation();+ s.toggleSelect({ kind: "cue", id: cue.id });+ return;+ }+ if (armed && startSelectionDrag(e, stageWidth, stageHeight)) return;if (!armed && stagePress) {stagePress(e, () => s.select({ kind: "cue", id: cue.id }));return;@@ -1021,8 +1034,15 @@ function OverlayItem({};const beginMove = (e: React.PointerEvent) => {- if (editing) return;+ if (editing || e.button !== 0) return;const s = useEditor.getState();+ if (e.metaKey || e.ctrlKey) {+ e.preventDefault();+ e.stopPropagation();+ s.toggleSelect({ kind: "overlay", id: o.id });+ return;+ }+ if (armed && startSelectionDrag(e, stageWidth, stageHeight)) return;// Nothing moves until it is the selection: an unselected element is part// of the picture, so the stage pans under it and a stationary press picks// it up for the next drag.@@ -1094,6 +1114,8 @@ function OverlayItem({editing && "cursor-text")}style={style}+ data-preview-kind="overlay"+ data-preview-id={o.id}onPointerDown={beginMove}onDoubleClick={isText ? () => setEditing(true) : undefined}>@@ -1165,6 +1187,8 @@ function OverlayItem({<divclassName="pointer-events-auto absolute cursor-grab active:cursor-grabbing"style={twinStyle}+ data-preview-kind="overlay"+ data-preview-id={o.id}onPointerDown={beginMove}onDoubleClick={isText ? () => setEditing(true) : undefined}>diff --git a/site/src/cut/components/Preview.tools.ts b/site/src/cut/components/Preview.tools.tsindex 5fd8cd60..302dcc09 100644--- a/site/src/cut/components/Preview.tools.ts+++ b/site/src/cut/components/Preview.tools.ts@@ -8,6 +8,11 @@import { bool, num, obj, type AiToolDef } from "@/cut/lib/aiToolDef";export const PREVIEW_TOOLS = [+ {+ name: "move_selection",+ description: "Move selected visual items together in the preview, preserving their spacing. dx/dy are fractions of frame width/height. Supports video, titles, shapes, stickers, and caption tracks; audio and effects keep their timing. Keyframed items receive position keys at the playhead. One undo step.",+ inputSchema: obj({ dx: num("Horizontal movement as a frame fraction"), dy: num("Vertical movement as a frame fraction") }, ["dx", "dy"]),+ },{name: "capture_frame",description:diff --git a/site/src/cut/components/Preview.tsx b/site/src/cut/components/Preview.tsxindex c1bc84a0..5c68d967 100644--- a/site/src/cut/components/Preview.tsx+++ b/site/src/cut/components/Preview.tsx@@ -4,6 +4,7 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, typimport { Check, Copy, Loader2, PanelTopClose, ZoomIn, ZoomOut } from "lucide-react";import { usePlayback } from "@/cut/hooks/usePlayback";import { startDrag } from "@/cut/lib/drag";+import { startSelectionDrag } from "@/cut/components/previewSelectionDrag";import { useBrushUi } from "@/cut/lib/removal/brushUi";import {playheadAt,@@ -496,7 +497,7 @@ export function Preview() {// its picture selects it, in the preview and the timeline alike. Full-frame// clips stay out: a click on the backdrop clears the selection.const clipAtPoint = (e: React.MouseEvent): string | null => {- const rct = e.currentTarget.getBoundingClientRect();+ const rct = boxRef.current!.getBoundingClientRect();const px = (e.clientX - rct.left) / rct.width;const py = (e.clientY - rct.top) / rct.height;const s = useEditor.getState();@@ -505,10 +506,18 @@ export function Preview() {for (const c of s.clips) {if (c.hidden) continue;const r = rectOf(c);- if (isFullRect(r)) continue;+ if (isFullRect(r) && !e.metaKey && !e.ctrlKey) continue;const len = clipLen(c);if (t < c.start || t >= c.start + len) continue;- if (px < r.x || px > r.x + r.w || py < r.y || py > r.y + r.h) continue;+ const pose = clipKeyed(c) ? clipPoseAt(c, t - c.start) : null;+ const cx = pose?.x ?? r.x + r.w / 2;+ const cy = pose?.y ?? r.y + r.h / 2;+ const angle = -((pose?.rotation ?? c.rotation ?? 0) * Math.PI) / 180;+ const dx = (px - cx) * rct.width, dy = (py - cy) * rct.height;+ const x = dx * Math.cos(angle) - dy * Math.sin(angle);+ const y = dx * Math.sin(angle) + dy * Math.cos(angle);+ const scale = pose?.scale ?? 1;+ if (Math.abs(x) > r.w * rct.width * scale / 2 || Math.abs(y) > r.h * rct.height * scale / 2) continue;if (!best || c.track > best.track) best = { id: c.id, track: c.track };}return best?.id ?? null;@@ -522,6 +531,25 @@ export function Preview() {// A middle-button drag pans the camera from anywhere in the pane, ahead// of whatever gizmo or clip sits under the pointer.onPointerDownCapture={(e) => {+ // Selection chrome can cover another item. Modifier picking follows+ // the visible elements inside the stage.+ if (e.button === 0 && (e.metaKey || e.ctrlKey) &&+ (e.target as HTMLElement).closest("[data-preview-clip], [data-preview-kind]") &&+ !(e.target as HTMLElement).closest("[title], [contenteditable=true]")) {+ const element = document.elementsFromPoint(e.clientX, e.clientY)+ .map((node) => node.closest<HTMLElement>(".overlay-item[data-preview-kind], .sub-caption[data-preview-kind]"))+ .find((node) => node && e.currentTarget.contains(node));+ const kind = element?.dataset.previewKind;+ const id = element?.dataset.previewId;+ const clipId = !id ? clipAtPoint(e) : null;+ if ((id && (kind === "overlay" || kind === "cue")) || clipId) {+ e.preventDefault();+ e.stopPropagation();+ useEditor.getState().toggleSelect(id && (kind === "overlay" || kind === "cue")+ ? { kind, id } : { kind: "clip", id: clipId! });+ return;+ }+ }if (e.button !== 1) return;e.preventDefault();e.stopPropagation();@@ -593,7 +621,12 @@ export function Preview() {(e.target as HTMLElement).tagName === "CANVAS") {const hit = clipAtPoint(e);- if (hit) useEditor.getState().select({ kind: "clip", id: hit });+ if (hit) {+ const s = useEditor.getState();+ const item = { kind: "clip" as const, id: hit };+ if (e.metaKey || e.ctrlKey) s.toggleSelect(item);+ else s.select(item);+ }}}}>@@ -639,7 +672,7 @@ export function Preview() {<GuideOverlay stage={stage} /><ClipMaskGizmo stage={stage} /><RemovalBrush stage={stage} />- <ClipTransformGizmo stage={stage} />+ <ClipSelectionGizmos stage={stage} /></div></div><ZoomHud@@ -860,9 +893,18 @@ function snapEdge(v: number, tol: number): number | null {return best;}-function ClipTransformGizmo({ stage }: { stage: Stage }) {+function ClipSelectionGizmos({ stage }: { stage: Stage }) {const selection = useEditor((s) => s.selection);- const clips = useEditor((s) => s.clips);+ const multi = useEditor((s) => s.multiSelection);+ const allClips = useEditor((s) => s.clips);+ const clips = useMemo(() => {+ const ids = new Set((multi.length ? multi : [selection]).flatMap((item) => item?.kind === "clip" ? [item.id] : []));+ return allClips.filter((clip) => ids.has(clip.id));+ }, [allClips, multi, selection]);+ return clips.map((clip) => <ClipTransformGizmo key={clip.id} selectedClip={clip} stage={stage} />);+}++function ClipTransformGizmo({ stage, selectedClip }: { stage: Stage; selectedClip: VideoClip }) {const assets = useEditor((s) => s.assets);const skimTime = useSkim();const layerRef = useRef<HTMLDivElement>(null);@@ -874,7 +916,6 @@ function ClipTransformGizmo({ stage }: { stage: Stage }) {// The gizmo only cares whether its clip is on screen, so it subscribes to// that answer instead of to the clock: one render when the clip comes and// goes, rather than one per frame while it stays.- const selectedClip = selection?.kind === "clip" ? clips.find((c) => c.id === selection.id) : null;const brushClipId = useBrushUi((s) => s.clipId);const live = usePreviewSelector((t) => {if (!selectedClip) return false;@@ -921,8 +962,15 @@ function ClipTransformGizmo({ stage }: { stage: Stage }) {});};const asset = assets.find((a) => a.id === clip.assetId);- const r = rectOf(clip);- const rotation = clip.rotation ?? 0;+ const restingRect = rectOf(clip);+ const pose = clipKeyed(clip) ? clipPoseAt(clip, Math.max(0, previewAt() - clip.start)) : null;+ const r = pose ? {+ x: pose.x - restingRect.w * pose.scale / 2,+ y: pose.y - restingRect.h * pose.scale / 2,+ w: restingRect.w * pose.scale,+ h: restingRect.h * pose.scale,+ } : restingRect;+ const rotation = pose?.rotation ?? clip.rotation ?? 0;const zoom = clipZoom(clip);// Where the source actually lands inside the box — the same geometry the// compositor draws and the export crops, measured in stage pixels so the two@@ -956,7 +1004,15 @@ function ClipTransformGizmo({ stage }: { stage: Stage }) {// The box may leave the frame — oversize it to focus on an area, or park it// partly off screen — as long as a sliver stays inside to grab.- const onMoveBox = (e: React.PointerEvent) =>+ const onMoveBox = (e: React.PointerEvent) => {+ if (e.button !== 0) return;+ if (e.metaKey || e.ctrlKey) {+ e.preventDefault();+ e.stopPropagation();+ st().toggleSelect({ kind: "clip", id: clip.id });+ return;+ }+ if (startSelectionDrag(e, stage.w, stage.h)) return;surfaceDrag(e,(dx, dy) => {@@ -973,6 +1029,7 @@ function ClipTransformGizmo({ stage }: { stage: Stage }) {},() => setGuides({ x: null, y: null }));+ };// A turned box is grabbed on screen but sized in the frame's own axes, so a// grip's travel comes back the way the box went out.@@ -1221,6 +1278,7 @@ function ClipTransformGizmo({ stage }: { stage: Stage }) {<divclassName="pointer-events-auto absolute cursor-move rounded-[3px] border-2 border-dashed border-[#0a84ff]"style={box}+ data-preview-clip={clip.id}onPointerDown={onMoveBox}><TransformHandlesdiff --git a/site/src/cut/components/Timeline.tools.ts b/site/src/cut/components/Timeline.tools.tsindex ce39b741..e3863caa 100644--- a/site/src/cut/components/Timeline.tools.ts+++ b/site/src/cut/components/Timeline.tools.ts@@ -7,6 +7,7 @@*/import { bool, num, obj, str, type AiToolDef } from "@/cut/lib/aiToolDef";+import { SELECTABLE_ITEM_KINDS } from "@/cut/lib/previewSelection";import {TEXT_EMPHASIS_IDS,TEXT_LAYOUT_IDS,@@ -20,10 +21,11 @@ export const TIMELINE_TOOLS = [{name: "select",description:- "Select a video clip (on any track), soundtrack clip, or overlay element — title, shape, or sticker (or clear the selection). Selection drives the inspector panel.",+ "Select a video clip (on any track), soundtrack clip, or overlay element — title, shape, or sticker (or clear the selection). Selection appears in the timeline and preview. Use additive:true to toggle an item in the selection; move_selection moves the selected visual items together.",inputSchema: obj({- kind: { type: "string", enum: ["clip", "audio", "overlay", "none"], description: "What to select — 'clip' is any video clip, whatever track; 'overlay' is any title-lane element" },+ kind: { type: "string", enum: [...SELECTABLE_ITEM_KINDS, "none"], description: "What to select — 'clip' is any video clip, whatever track; 'overlay' is any title-lane element" },id: str("The item id (omit for kind=none)"),+ additive: bool("Toggle this item in the existing selection"),}, ["kind"]),},{diff --git a/site/src/cut/components/previewSelectionDrag.ts b/site/src/cut/components/previewSelectionDrag.tsnew file mode 100644index 00000000..e672ef71--- /dev/null+++ b/site/src/cut/components/previewSelectionDrag.ts@@ -0,0 +1,27 @@+"use client";++import type { PointerEvent } from "react";+import { startDrag } from "@/cut/lib/drag";+import { previewAt } from "@/cut/lib/playhead";+import { useEditor } from "@/cut/lib/store";+import { movePreviewSelection, previewSelectionSnapshot } from "@/cut/lib/previewSelection";++/** Selected items share one gesture and one undo checkpoint. */+export function startSelectionDrag(e: PointerEvent, width: number, height: number): boolean {+ const s = useEditor.getState();+ if (s.multiSelection.length < 2) return false;+ const positions = previewSelectionSnapshot(s, previewAt());+ if (!positions.length) return false;+ let began = false;+ startDrag(e, {+ onMove: (dx, dy) => {+ if (!began) {+ if (Math.abs(dx) <= 3 && Math.abs(dy) <= 3) return;+ useEditor.getState().pushHistory();+ began = true;+ }+ movePreviewSelection(useEditor.getState(), positions, dx / width, dy / height);+ },+ });+ return true;+}diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 1ec5c96b..c018785e 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -1,5 +1,7 @@"use client";+import { movePreviewSelection, previewSelectionSnapshot } from "@/cut/lib/previewSelection";+import { libraryShareTargetSchema, shareSettingsSchema, librarySharePath } from "@/cut/lib/librarySharing";import { requestSharing } from "@/cut/lib/sharingClient";import { copyLibraryForSharing } from "@/cut/lib/libraryShareCopy";@@ -1237,6 +1239,15 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {return { playing: Boolean(input.playing) };},+ move_selection: (s, input) => {+ if (!isNum(input.dx) || !isNum(input.dy)) throw new ToolError("dx and dy must be finite frame fractions.");+ const positions = previewSelectionSnapshot(s, playheadAt());+ if (!positions.length) throw new ToolError("Select visual items before moving them.");+ s.pushHistory();+ movePreviewSelection(s, positions, input.dx, input.dy);+ return { moved: positions.length };+ },+select: (s, input) => {const kind = String(input.kind);if (kind === "none") {@@ -1253,13 +1264,14 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {? s.audioClips: kind === "overlay" || kind === "text"? s.overlays- : null;+ : kind === "cue" ? s.subtitles.cues : null;if (!pool) throw new ToolError(`Unknown kind: ${kind}`);if (!pool.some((x) => x.id === id)) throw new ToolError(`No ${kind} with id ${id}.`);const selKind =- kind === "overlayClip" ? "clip" : kind === "text" ? "overlay" : (kind as "clip" | "audio" | "overlay");- s.select({ kind: selKind, id });- return { selection: { kind: selKind, id } };+ kind === "overlayClip" ? "clip" : kind === "text" ? "overlay" : (kind as "clip" | "audio" | "overlay" | "cue");+ if (input.additive === true) s.toggleSelect({ kind: selKind, id });+ else s.select({ kind: selKind, id });+ return { selection: useEditor.getState().selection, multiSelection: useEditor.getState().multiSelection };},set_side_panel: (_s, input) => {diff --git a/site/src/cut/lib/previewSelection.test.ts b/site/src/cut/lib/previewSelection.test.tsnew file mode 100644index 00000000..03311177--- /dev/null+++ b/site/src/cut/lib/previewSelection.test.ts@@ -0,0 +1,84 @@+import { beforeEach, expect, test } from "bun:test";+import { movePreviewSelection, previewSelectionSnapshot } from "@/cut/lib/previewSelection";+import { useEditor } from "@/cut/lib/store";+import { emptySubtitles, type TextOverlay, type VideoClip } from "@/cut/lib/types";+import { runAiTool } from "@/cut/lib/aiTools";+import { setPlayhead } from "@/cut/lib/playhead";++const title = (id: string, x: number, y: number): TextOverlay => ({+ id, text: id, start: 0, end: 4, x, y, size: 60, font: "sf", weight: 700,+ color: "#fff", shadow: false, plate: false,+});+const clip: VideoClip = { id: "video", assetId: "asset", track: 0, start: 0, in: 0, out: 4, muted: true, frame: { x: 0.1, y: 0.1, w: 0.3, h: 0.3 } };+const st = () => useEditor.getState();+beforeEach(() => {+ setPlayhead(1);+ useEditor.setState({ clips: [], assets: [], overlays: [], audioClips: [], transitions: [], subtitles: emptySubtitles(), selection: null, multiSelection: [] });+});++test("timeline selection moves mixed visuals together and undoes as one edit", () => {+ useEditor.setState({ overlays: [title("a", 0.4, 0.4), title("b", 0.6, 0.6), title("untouched", 0.2, 0.2)], clips: [clip] });+ st().setMultiSelection([{ kind: "overlay", id: "a" }, { kind: "overlay", id: "b" }, { kind: "clip", id: "video" }]);+ const before = st();+ const snapshot = previewSelectionSnapshot(before, 1);+ st().pushHistory();+ movePreviewSelection(st(), snapshot, 0.05, 0.05);+ movePreviewSelection(st(), snapshot, 0.1, 0.2);+ expect(st().overlays[0].x).toBeCloseTo(0.5);+ expect(st().overlays[1].x).toBeCloseTo(0.7);+ expect(st().overlays[1].y - st().overlays[0].y).toBeCloseTo(0.2);+ expect(st().clips[0].frame?.x).toBeCloseTo(0.2);+ expect(st().overlays[2]).toEqual(before.overlays[2]);+ expect(st().multiSelection).toEqual(before.multiSelection);+ st().undo();+ expect(st().overlays).toEqual(before.overlays);+ expect(st().clips[0].frame).toEqual(before.clips[0].frame);+});++test("clamping preserves the spacing of the entire selection", () => {+ useEditor.setState({ overlays: [title("a", 0.5, 0.3), title("b", 0.9, 0.6)] });+ st().setMultiSelection([{ kind: "overlay", id: "a" }, { kind: "overlay", id: "b" }]);+ movePreviewSelection(st(), previewSelectionSnapshot(st(), 1), 0.5, -0.5);+ expect(st().overlays[1].x).toBeCloseTo(0.98);+ expect(st().overlays[1].x - st().overlays[0].x).toBeCloseTo(0.4);+ expect(st().overlays[0].y).toBeCloseTo(0.02);+ expect(st().overlays[1].y - st().overlays[0].y).toBeCloseTo(0.3);+});++test("keyed items move from their evaluated poses while retaining other keys", () => {+ const keys = [{ t: 0, x: 0.2, y: 0.3, scale: 1, rotation: 30, opacity: 0.8 }, { t: 2, x: 0.6, y: 0.5, scale: 2, rotation: 60, opacity: 1 }];+ useEditor.setState({ overlays: [{ ...title("a", 0.5, 0.5), kf: keys }], clips: [{ ...clip, kf: keys }] });+ st().setMultiSelection([{ kind: "overlay", id: "a" }, { kind: "clip", id: "video" }]);+ movePreviewSelection(st(), previewSelectionSnapshot(st(), 1), 0.1, 0.1);+ for (const item of [st().overlays[0], st().clips[0]]) {+ expect(item.kf).toHaveLength(3);+ expect(item.kf?.[0]).toEqual(keys[0]);+ expect(item.kf?.[2]).toEqual(keys[1]);+ expect(item.kf?.[1].x).toBeCloseTo(0.5);+ expect(item.kf?.[1].y).toBeCloseTo(0.5);+ expect(item.kf?.[1].rotation).toBeCloseTo(45);+ expect(item.kf?.[1].scale).toBeCloseTo(1.5);+ }+});++test("multiple cues on a track move its shared anchor once", () => {+ useEditor.setState({ overlays: [title("a", 0.3, 0.4)], subtitles: { ...emptySubtitles(), tracks: [{ x: 0.4, y: 0.6 }], cues: [{ id: "q1", start: 0, end: 1, text: "one" }, { id: "q2", start: 1, end: 2, text: "two" }] } });+ st().setMultiSelection([{ kind: "overlay", id: "a" }, { kind: "cue", id: "q1" }, { kind: "cue", id: "q2" }]);+ const snapshot = previewSelectionSnapshot(st(), 1);+ expect(snapshot).toHaveLength(2);+ movePreviewSelection(st(), snapshot, 0.1, 0.1);+ expect(st().subtitles.tracks?.[0].x).toBeCloseTo(0.5);+ expect(st().subtitles.cues[0].start).toBe(0);+});++test("chat can add, move, and remove preview selections", async () => {+ useEditor.setState({ overlays: [title("a", 0.3, 0.4), title("b", 0.6, 0.7)] });+ await runAiTool("select", { kind: "overlay", id: "a" });+ await runAiTool("select", { kind: "overlay", id: "b", additive: true });+ expect(st().multiSelection).toHaveLength(2);+ await runAiTool("move_selection", { dx: 0.1, dy: 0.1 });+ expect(st().overlays[0].x).toBeCloseTo(0.4);+ expect(st().overlays[1].x).toBeCloseTo(0.7);+ await runAiTool("select", { kind: "overlay", id: "a", additive: true });+ expect(st().multiSelection).toEqual([{ kind: "overlay", id: "b" }]);+});diff --git a/site/src/cut/lib/previewSelection.ts b/site/src/cut/lib/previewSelection.tsnew file mode 100644index 00000000..b4b3b07a--- /dev/null+++ b/site/src/cut/lib/previewSelection.ts@@ -0,0 +1,68 @@+import { hasOverlayKeys, keyAt, upsertKey, type OverlayKey } from "@donkeycut/effects-kit";+import { clipLen, type EditorState } from "@/cut/lib/store";+import { clipKeyed, clipPoseAt, rectOf, type FrameRect } from "@/cut/lib/types";+import { captionStyle, laneHidden, trackPos } from "@/cut/lib/subtitles";++export const SELECTABLE_ITEM_KINDS = ["clip", "audio", "overlay", "cue"] as const;++type Position = {+ kind: "clip" | "overlay" | "cue";+ id: string;+ x: number;+ y: number;+ frame?: FrameRect;+ key?: OverlayKey;+ keys?: OverlayKey[];+ lane?: number;+};++/** Capture positions once per gesture. Every member receives the same delta. */+export function previewSelectionSnapshot(s: EditorState, t: number): Position[] {+ const selected = new Set((s.multiSelection.length ? s.multiSelection : [s.selection])+ .flatMap((item) => item ? [`${item.kind}:${item.id}`] : []));+ const positions: Position[] = [];+ for (const o of s.overlays) {+ if (!selected.has(`overlay:${o.id}`) || o.hidden || o.kind === "effect") continue;+ const key = hasOverlayKeys(o) ? keyAt(o, Math.max(0, Math.min(t - o.start, Math.max(0.1, o.end - o.start)))) : undefined;+ positions.push({ kind: "overlay", id: o.id, x: key?.x ?? o.x, y: key?.y ?? o.y, key, keys: o.kf });+ }+ for (const c of s.clips) {+ if (!selected.has(`clip:${c.id}`) || c.hidden) continue;+ const frame = rectOf(c);+ const local = Math.max(0, Math.min(t - c.start, clipLen(c)));+ const key = clipKeyed(c) ? { t: local, ...clipPoseAt(c, local) } : undefined;+ positions.push({ kind: "clip", id: c.id, x: key?.x ?? frame.x, y: key?.y ?? frame.y, frame, key, keys: c.kf });+ }+ const lanes = new Set<number>();+ for (const cue of s.subtitles.cues) {+ const lane = cue.lane ?? 0;+ if (!selected.has(`cue:${cue.id}`) || lanes.has(lane) || laneHidden(s.subtitles, lane)) continue;+ lanes.add(lane);+ const p = trackPos(s.subtitles, captionStyle(s.subtitles.style), lane);+ positions.push({ kind: "cue", id: cue.id, lane, x: p.x!, y: p.y! });+ }+ return positions;+}++/** Deltas are frame fractions; clamp the group together to preserve spacing. */+export function movePreviewSelection(s: EditorState, positions: Position[], dx: number, dy: number) {+ let minX = -Infinity, maxX = Infinity, minY = -Infinity, maxY = Infinity;+ for (const p of positions) {+ const f = p.kind === "clip" && !p.key ? p.frame : undefined;+ minX = Math.max(minX, Math.min(0, (f ? 0.05 - f.w : 0.02) - p.x));+ maxX = Math.min(maxX, Math.max(0, (f ? 0.95 : 0.98) - p.x));+ minY = Math.max(minY, Math.min(0, (f ? 0.05 - f.h : 0.02) - p.y));+ maxY = Math.min(maxY, Math.max(0, (f ? 0.95 : 0.98) - p.y));+ }+ dx = Math.max(minX, Math.min(maxX, dx));+ dy = Math.max(minY, Math.min(maxY, dy));+ const patches: Parameters<EditorState["updateDocTransient"]>[0] = { clips: [], overlays: [] };+ for (const p of positions) {+ const x = p.x + dx, y = p.y + dy;+ const keyed = p.key ? { kf: upsertKey(p.keys, { ...p.key, x, y }) } : null;+ if (p.kind === "overlay") patches.overlays!.push({ id: p.id, patch: keyed ?? { x, y } });+ else if (p.kind === "clip") patches.clips!.push({ id: p.id, patch: keyed ?? { frame: { ...p.frame!, x, y } } });+ else s.setSubtitleTrackMeta(p.lane!, { x, y });+ }+ if (patches.clips!.length || patches.overlays!.length) s.updateDocTransient(patches);+}diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex a40e3357..0e56a9e0 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -385,6 +385,8 @@ Project media (\`media\` in editor_state) is every file in the open project. The- media_organize keeps the Media panel's own folders (\`mediaFolders\` in editor_state, per project): create/rename/delete a folder, move_asset to file media into one — filing a created asset also moves it into Media, like dropping its card on a folder tile.- delete_asset removes an asset from the project plus its timeline clips; the media does not come back with undo, so only on an explicit ask, and say what went with it.- convert_media rewrites project media as MP4 (H.264/AAC) in place, one call for a whole list of asset ids. Reach for it when footage plays black or shows a format warning — phone HEVC, ProRes, raw PCM sound — and whenever someone asks for mp4 files. That ask is usually files dropped straight on this chat: convert them and each one is on its own card in the thread, converted, ready to download or drag onto the timeline — close by saying they're on their cards. An asset that came from the Media panel stays there. Streams that already fit are copied, so most .mov files convert in seconds, and a file that is already H.264/AAC MP4 comes back untouched (say so instead of claiming a conversion); max_height shrinks an oversized source at the same time. Clips already cut from the asset keep playing. It runs on whichever machine already holds the bytes — this Mac, the render worker, or the tab — and works with no editor tab attached; when nothing available can decode the source the error names the fix (the Mac app, another browser, or moving the project to the cloud), so report it and move on.+Preview selection is shared with the timeline. Use select with additive:true to toggle multiple items, then move_selection with dx/dy frame fractions to move them together. Caption positions apply to their whole track.+The Library is shared across every project: folders, reusable assets, and templates — a template is a saved arrangement (clips, overlays, titles, captions, by reference) that comes back editable.- library_list browses it; library_add copies an asset into the project (the import step "library"-scope attachments need); template_add re-materializes a template; save_template saves timeline items as one.- Assets from the user's iOS app carry an origin: "camera" is a clip they recorded on their phone (their Camera Roll — "the video I shot on my phone" lives here), "inspiration" a reference saved into the Library's Inspiration folder. library_add imports either like any other asset. A camera clip's name is the clock it was shot on; its title, when it has one, was read off the clip itself and is what the user sees on the card — match a request like "the one about the launch" against the title.