Open source CapCut alternative.
TypeScript
feat(site): one selection frame on the preview
David Le6996a4f50c51
diff --git a/site/src/cut/components/OverlayLayer.tsx b/site/src/cut/components/OverlayLayer.tsxindex d1b0987c..cf65b9e6 100644--- a/site/src/cut/components/OverlayLayer.tsx+++ b/site/src/cut/components/OverlayLayer.tsx@@ -6,6 +6,7 @@ import { createPortal } from "react-dom";import { releaseAnimRest, useAnimPreview } from "@/cut/lib/animPreview";import { startDrag } from "@/cut/lib/drag";import { startSelectionDrag, togglePreviewSelection } from "@/cut/components/previewSelectionDrag";+import { pictureGroupSelected } from "@/cut/lib/previewSelection";import { useSkim, usePreviewTime } from "@/cut/lib/playhead";import { useEditor } from "@/cut/lib/store";import {@@ -303,6 +304,7 @@ export function OverlayLayer({const sel =selection?.kind === "overlay" ? overlays.find((o) => o.id === selection.id) : undefined;const multiple = multiSelection.length > 1;+ const grouped = pictureGroupSelected(multiSelection);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);@@ -333,6 +335,7 @@ export function OverlayLayer({// selection chrome (outline, resize handle) does not.selected={selected && !scrubbing}armed={selected && !scrubbing}+ grouped={grouped}ghost={!inRange && !selected}t={t}stageWidth={stageWidth}@@ -538,6 +541,7 @@ function OverlayItem({overlay: o,selected,armed,+ grouped,ghost,t,stageWidth,@@ -552,6 +556,9 @@ function OverlayItem({/** Whether a press on this element moves it. Only the selection (or the* group holding it) drags; everything else hands the press to the stage. */armed: boolean;+ /** One of several selected items: it wears its outline alone, and the+ * selection frame carries the grips for the whole set. */+ grouped: boolean;ghost: boolean;/** The previewed timeline moment (playhead or paused skimmer). */t: number;@@ -675,7 +682,7 @@ function OverlayItem({// size is read off the real box, which keeps auto-sized text honest.const chromeHost = useContext(OverlayChromeHost);const stagePress = useContext(StagePress);- const liftChrome = !!chromeHost && selected && !editing;+ const liftChrome = !!chromeHost && selected && !editing && !grouped;const [chromeSize, setChromeSize] = useState<{ w: number; h: number } | null>(null);useLayoutEffect(() => {if (!liftChrome) return;@@ -1030,7 +1037,7 @@ function OverlayItem({if (editing || e.button !== 0) return;const s = useEditor.getState();if (togglePreviewSelection(e, { kind: "overlay", id: o.id })) return;- if (armed && startSelectionDrag(e, stageWidth, stageHeight)) return;+ if (armed && startSelectionDrag(e, stageWidth, stageHeight, { kind: "overlay", id: o.id })) 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.@@ -1060,7 +1067,7 @@ function OverlayItem({});};- const chrome = selected && !editing && (+ const chrome = selected && !editing && !grouped && (<>{/* The rotate button clears the element's own top edge, so moving isnever caught by it. Its cursor rides the element's rotation, sodiff --git a/site/src/cut/components/Preview.tsx b/site/src/cut/components/Preview.tsxindex 52e842ea..6e13c010 100644--- a/site/src/cut/components/Preview.tsx+++ b/site/src/cut/components/Preview.tsx@@ -5,6 +5,7 @@ import { Check, Copy, Loader2, PanelTopClose, ZoomIn, ZoomOut } from "lucide-reaimport { usePlayback } from "@/cut/hooks/usePlayback";import { startDrag } from "@/cut/lib/drag";import { isPreviewSelectionModifier, startSelectionDrag, togglePreviewSelection } from "@/cut/components/previewSelectionDrag";+import { pictureGroupSelected } from "@/cut/lib/previewSelection";import { useBrushUi } from "@/cut/lib/removal/brushUi";import {playheadAt,@@ -28,6 +29,7 @@ import { MaskGizmoCore, OverlayChromeHost, OverlayLayer, StagePress } from "./Ovimport { GuideHandles, GuideOverlay } from "./GuideOverlay";import { RemovalBrush } from "./RemovalBrush";import { CORNER_HANDLES, HANDLE_AXIS, TransformHandles, type ResizeHandle } from "./TransformHandles";+import { SelectionFrame } from "./SelectionFrame";import {StageEffectPaint,StagePictureFx,@@ -670,6 +672,7 @@ export function Preview() {<ClipMaskGizmo stage={stage} /><RemovalBrush stage={stage} /><ClipSelectionGizmos stage={stage} />+ <SelectionFrame stage={stage} /></div></div><ZoomHud@@ -898,10 +901,13 @@ function ClipSelectionGizmos({ stage }: { stage: Stage }) {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} />);+ const grouped = pictureGroupSelected(multi);+ return clips.map((clip) => <ClipTransformGizmo key={clip.id} selectedClip={clip} stage={stage} grouped={grouped} />);}-function ClipTransformGizmo({ stage, selectedClip }: { stage: Stage; selectedClip: VideoClip }) {+/** `grouped`: one of several selected items — the box still moves the set,+ * and the selection frame carries the grips for all of them. */+function ClipTransformGizmo({ stage, selectedClip, grouped }: { stage: Stage; selectedClip: VideoClip; grouped: boolean }) {const assets = useEditor((s) => s.assets);const skimTime = useSkim();const layerRef = useRef<HTMLDivElement>(null);@@ -1004,7 +1010,7 @@ function ClipTransformGizmo({ stage, selectedClip }: { stage: Stage; selectedCliconst onMoveBox = (e: React.PointerEvent) => {if (e.button !== 0) return;if (togglePreviewSelection(e, { kind: "clip", id: clip.id })) return;- if (startSelectionDrag(e, stage.w, stage.h)) return;+ if (startSelectionDrag(e, stage.w, stage.h, { kind: "clip", id: clip.id })) return;surfaceDrag(e,(dx, dy) => {@@ -1254,7 +1260,7 @@ function ClipTransformGizmo({ stage, selectedClip }: { stage: Stage; selectedClititle={overflows ? "Drag to pan the picture" : undefined}onPointerDown={overflows ? onPanPicture : undefined}>- {overflows && (+ {overflows && !grouped && (<TransformHandlescolor="#c7c7cc"handles={CORNER_HANDLES}@@ -1273,14 +1279,16 @@ function ClipTransformGizmo({ stage, selectedClip }: { stage: Stage; selectedClidata-preview-clip={clip.id}onPointerDown={onMoveBox}>- <TransformHandles- color="#0a84ff"- className="z-20"- rotation={rotation}- angle={turning}- onResize={onResize}- onRotate={onRotate}- />+ {!grouped && (+ <TransformHandles+ color="#0a84ff"+ className="z-20"+ rotation={rotation}+ angle={turning}+ onResize={onResize}+ onRotate={onRotate}+ />+ )}</div></div>{/* The solid ring and the snap guides live outside the turn: the ring'sdiff --git a/site/src/cut/components/SelectionFrame.tsx b/site/src/cut/components/SelectionFrame.tsxnew file mode 100644index 00000000..2659415f--- /dev/null+++ b/site/src/cut/components/SelectionFrame.tsx@@ -0,0 +1,150 @@+"use client";++import { useLayoutEffect, useRef, useState } from "react";+import { startDrag } from "@/cut/lib/drag";+import { previewAt, usePreviewTime, useSkim } from "@/cut/lib/playhead";+import { clipLen, useEditor } from "@/cut/lib/store";+import {+ normDeg,+ pictureGroupSelected,+ previewSelectionSnapshot,+ rotatePreviewSelection,+ scalePreviewSelection,+} from "@/cut/lib/previewSelection";+import { clipKeyed, clipPoseAt, rectOf } from "@/cut/lib/types";+import { HANDLE_AXIS, TransformHandles, type ResizeHandle } from "@/cut/components/TransformHandles";++type Rect = { x: number; y: number; w: number; h: number };+const ROTATE_SNAP_DEG = 6;++/**+ * One frame around a multi-selection on the stage: the box every selected+ * item fits in, with the grips and the rotate button a single item wears.+ * A grip scales the set about the opposite edge, the button turns it about+ * its center, and every member keeps its place in the set. The ring itself+ * takes no press: a member moves the whole set from its own box, and the+ * room between members stays the stage's. Members draw only their thin+ * outline underneath. The frame rests while the cut plays or the skimmer is+ * out, when the picture is what matters.+ */+export function SelectionFrame({ stage }: { stage: { w: number; h: number } }) {+ const multi = useEditor((s) => s.multiSelection);+ const overlays = useEditor((s) => s.overlays);+ const clips = useEditor((s) => s.clips);+ const playing = useEditor((s) => s.playing);+ const readOnly = useEditor((s) => s.readOnly);+ const t = usePreviewTime();+ const skim = useSkim();+ const ref = useRef<HTMLDivElement>(null);+ const [rect, setRect] = useState<Rect | null>(null);+ const [spin, setSpin] = useState<number | null>(null);+ const active = pictureGroupSelected(multi) && !playing && skim === null && !readOnly;++ // The box is read from what is on screen: each element's laid-out box,+ // and a clip's frame turned by its angle. One read per change, off the+ // frame loop.+ useLayoutEffect(() => {+ const root = ref.current;+ if (!active || !root) {+ setRect(null);+ return;+ }+ const origin = root.getBoundingClientRect();+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;+ const add = (x: number, y: number) => {+ x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y);+ };+ const scope = root.parentElement ?? root;+ for (const m of multi) {+ if (m?.kind === "overlay") {+ const el = scope.querySelector<HTMLElement>(`.overlay-item[data-preview-id="${CSS.escape(m.id)}"]`);+ if (!el) continue;+ const r = el.getBoundingClientRect();+ add(r.left - origin.left, r.top - origin.top);+ add(r.right - origin.left, r.bottom - origin.top);+ } else if (m?.kind === "clip") {+ const clip = clips.find((c) => c.id === m.id);+ if (!clip || clip.hidden || t < clip.start || t >= clip.start + clipLen(clip)) continue;+ const resting = rectOf(clip);+ const pose = clipKeyed(clip) ? clipPoseAt(clip, Math.max(0, t - clip.start)) : null;+ const r = pose+ ? { x: pose.x - (resting.w * pose.scale) / 2, y: pose.y - (resting.h * pose.scale) / 2, w: resting.w * pose.scale, h: resting.h * pose.scale }+ : resting;+ const deg = pose?.rotation ?? clip.rotation ?? 0;+ const cx = (r.x + r.w / 2) * stage.w, cy = (r.y + r.h / 2) * stage.h;+ const hw = (r.w * stage.w) / 2, hh = (r.h * stage.h) / 2;+ const a = (deg * Math.PI) / 180;+ for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) {+ add(cx + sx * hw * Math.cos(a) - sy * hh * Math.sin(a), cy + sx * hw * Math.sin(a) + sy * hh * Math.cos(a));+ }+ }+ }+ setRect(Number.isFinite(x0) && x1 > x0 && y1 > y0 ? { x: x0, y: y0, w: x1 - x0, h: y1 - y0 } : null);+ }, [active, multi, overlays, clips, t, stage.w, stage.h]);++ const st = () => useEditor.getState();++ // A grip scales about the opposite edge or corner: a corner pulls both axes+ // together along its diagonal, a side pulls its own axis alone.+ const onResize = (handle: ResizeHandle, e: React.PointerEvent) => {+ if (!rect) return;+ e.stopPropagation();+ st().pushHistory();+ const snapshot = previewSelectionSnapshot(st(), previewAt());+ const axis = HANDLE_AXIS[handle];+ const corner = axis.x !== 0 && axis.y !== 0;+ const at = (ax: -1 | 0 | 1, ay: -1 | 0 | 1) => ({+ x: rect.x + rect.w * (ax === 0 ? 0.5 : ax > 0 ? 1 : 0),+ y: rect.y + rect.h * (ay === 0 ? 0.5 : ay > 0 ? 1 : 0),+ });+ const grip = at(axis.x, axis.y);+ const anchor = at(-axis.x as -1 | 0 | 1, -axis.y as -1 | 0 | 1);+ const arm = { x: grip.x - anchor.x, y: grip.y - anchor.y };+ startDrag(e, {+ onMove: (dx, dy) => {+ const p = { x: grip.x + dx - anchor.x, y: grip.y + dy - anchor.y };+ let kx = 1, ky = 1;+ if (corner) kx = ky = (p.x * arm.x + p.y * arm.y) / (arm.x * arm.x + arm.y * arm.y);+ else if (axis.x !== 0) kx = p.x / arm.x;+ else ky = p.y / arm.y;+ scalePreviewSelection(st(), snapshot, { x: anchor.x / stage.w, y: anchor.y / stage.h }, kx, ky);+ },+ });+ };++ const onRotate = (e: React.PointerEvent) => {+ if (!rect) return;+ e.stopPropagation();+ st().pushHistory();+ const snapshot = previewSelectionSnapshot(st(), previewAt());+ const origin = ref.current!.getBoundingClientRect();+ const cx = origin.left + rect.x + rect.w / 2;+ const cy = origin.top + rect.y + rect.h / 2;+ const angleAt = (ev: { clientX: number; clientY: number }) => (Math.atan2(ev.clientY - cy, ev.clientX - cx) * 180) / Math.PI;+ const start0 = angleAt(e);+ setSpin(0);+ startDrag(e, {+ onMove: (_dx, _dy, ev) => {+ let delta = normDeg(angleAt(ev) - start0);+ for (const q of [-180, -90, 0, 90, 180]) if (Math.abs(delta - q) < ROTATE_SNAP_DEG) delta = q;+ setSpin(Math.round(delta));+ rotatePreviewSelection(st(), snapshot, { x: (rect.x + rect.w / 2) / stage.w, y: (rect.y + rect.h / 2) / stage.h }, delta, stage.h / stage.w);+ },+ onUp: () => setSpin(null),+ });+ };++ return (+ <div ref={ref} className="pointer-events-none absolute inset-0">+ {rect && (+ <div+ className="pointer-events-none absolute rounded-[3px] border-[1.5px] border-dashed border-[#0a84ff]"+ style={{ left: rect.x - 4, top: rect.y - 4, width: rect.w + 8, height: rect.h + 8 }}+ data-preview-selection=""+ >+ <TransformHandles color="#0a84ff" angle={spin} onResize={onResize} onRotate={onRotate} />+ </div>+ )}+ </div>+ );+}diff --git a/site/src/cut/components/previewSelectionDrag.ts b/site/src/cut/components/previewSelectionDrag.tsindex 593af083..da0dda6c 100644--- a/site/src/cut/components/previewSelectionDrag.ts+++ b/site/src/cut/components/previewSelectionDrag.ts@@ -19,8 +19,10 @@ export function togglePreviewSelection(e: PointerEvent, item: NonNullable<Selectreturn true;}-/** Selected items share one gesture and one undo checkpoint. */-export function startSelectionDrag(e: PointerEvent, width: number, height: number): boolean {+/** Selected items share one gesture and one undo checkpoint. A press on one+ * member that never travels narrows the selection to that member, the way a+ * plain click anywhere does. */+export function startSelectionDrag(e: PointerEvent, width: number, height: number, item?: NonNullable<Selection>): boolean {const s = useEditor.getState();if (s.multiSelection.length < 2) return false;const positions = previewSelectionSnapshot(s, previewAt());@@ -35,6 +37,9 @@ export function startSelectionDrag(e: PointerEvent, width: number, height: numbe}movePreviewSelection(useEditor.getState(), positions, dx / width, dy / height);},+ onUp: (_dx, _dy, moved) => {+ if (!moved && item) useEditor.getState().select(item);+ },});return true;}diff --git a/site/src/cut/lib/previewSelection.test.ts b/site/src/cut/lib/previewSelection.test.tsindex 03311177..d1b0095c 100644--- a/site/src/cut/lib/previewSelection.test.ts+++ b/site/src/cut/lib/previewSelection.test.ts@@ -82,3 +82,36 @@ test("chat can add, move, and remove preview selections", async () => {await runAiTool("select", { kind: "overlay", id: "a", additive: true });expect(st().multiSelection).toEqual([{ kind: "overlay", id: "b" }]);});++test("scaling grows what each kind stores about the anchor", () => {+ const { scalePreviewSelection } = require("@/cut/lib/previewSelection");+ useEditor.setState({+ overlays: [title("a", 0.4, 0.4), { id: "box", kind: "shape", shape: "rect", start: 0, end: 4, x: 0.6, y: 0.6, w: 0.2, h: 0.1, fill: "#fff" }],+ clips: [clip],+ });+ st().setMultiSelection([{ kind: "overlay", id: "a" }, { kind: "overlay", id: "box" }, { kind: "clip", id: "video" }]);+ const snapshot = previewSelectionSnapshot(st(), 1);+ scalePreviewSelection(st(), snapshot, { x: 0.2, y: 0.2 }, 2, 2);+ expect(st().overlays[0].x).toBeCloseTo(0.6);+ expect((st().overlays[0] as TextOverlay).size).toBeCloseTo(120);+ expect(st().overlays[1].x).toBeCloseTo(0.98);+ expect((st().overlays[1] as { w: number }).w).toBeCloseTo(0.4);+ expect(st().clips[0].frame).toEqual({ x: 0.0, y: 0.0, w: 0.6, h: 0.6 });+ scalePreviewSelection(st(), snapshot, { x: 0.2, y: 0.2 }, 2, 1);+ expect((st().overlays[0] as TextOverlay).size).toBe(60);+ expect((st().overlays[0] as TextOverlay).stretchX).toBeCloseTo(2);+});++test("rotating orbits every center and turns every item", () => {+ const { rotatePreviewSelection } = require("@/cut/lib/previewSelection");+ useEditor.setState({ overlays: [title("a", 0.7, 0.5), title("b", 0.3, 0.5)], clips: [clip] });+ st().setMultiSelection([{ kind: "overlay", id: "a" }, { kind: "overlay", id: "b" }, { kind: "clip", id: "video" }]);+ const snapshot = previewSelectionSnapshot(st(), 1);+ rotatePreviewSelection(st(), snapshot, { x: 0.5, y: 0.5 }, 90, 1);+ expect(st().overlays[0].x).toBeCloseTo(0.5);+ expect(st().overlays[0].y).toBeCloseTo(0.7);+ expect(st().overlays[0].rotation).toBe(90);+ expect(st().overlays[1].y).toBeCloseTo(0.3);+ expect(st().clips[0].rotation).toBe(90);+ expect(st().clips[0].frame!.x + 0.15).toBeCloseTo(0.75);+});diff --git a/site/src/cut/lib/previewSelection.ts b/site/src/cut/lib/previewSelection.tsindex b4b3b07a..9d0de981 100644--- a/site/src/cut/lib/previewSelection.ts+++ b/site/src/cut/lib/previewSelection.ts@@ -1,10 +1,16 @@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 { clampOverlayPos, clipKeyed, clipPoseAt, isShapeOverlay, isTextOverlay, rectOf, type FrameRect, type OverlayPatch, type Selection } from "@/cut/lib/types";import { captionStyle, laneHidden, trackPos } from "@/cut/lib/subtitles";export const SELECTABLE_ITEM_KINDS = ["clip", "audio", "overlay", "cue"] as const;+/** Two or more picture items selected: the selection frame carries the grips+ * and each member wears only its outline. */+export function pictureGroupSelected(multiSelection: readonly Selection[]): boolean {+ return multiSelection.filter((m) => m?.kind === "overlay" || m?.kind === "clip").length > 1;+}+type Position = {kind: "clip" | "overlay" | "cue";id: string;@@ -14,8 +20,17 @@ type Position = {key?: OverlayKey;keys?: OverlayKey[];lane?: number;+ /** The item's angle at the gesture's start, degrees clockwise. */+ rotation: number;+ /** What a scale gesture grows: a shape or sticker's box, a title's size or+ * stretch, a clip's frame. A keyed item scales its key instead. */+ box?: { w: number; h?: number };+ text?: { size: number; stretchX: number; stretchY: number };};+/** Into (-180, 180], the range every rotation is stored in. */+export const normDeg = (deg: number) => ((((deg + 180) % 360) + 360) % 360) - 180;+/** 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])@@ -24,14 +39,22 @@ export function previewSelectionSnapshot(s: EditorState, t: number): 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 });+ positions.push({+ kind: "overlay", id: o.id, x: key?.x ?? o.x, y: key?.y ?? o.y, key, keys: o.kf,+ rotation: key?.rotation ?? o.rotation ?? 0,+ box: isShapeOverlay(o) || o.kind === "sticker" ? { w: o.w, h: o.h } : undefined,+ text: isTextOverlay(o) ? { size: o.size, stretchX: o.stretchX ?? 1, stretchY: o.stretchY ?? 1 } : undefined,+ });}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 });+ positions.push({+ kind: "clip", id: c.id, x: key?.x ?? frame.x, y: key?.y ?? frame.y, frame, key, keys: c.kf,+ rotation: key?.rotation ?? c.rotation ?? 0,+ });}const lanes = new Set<number>();for (const cue of s.subtitles.cues) {@@ -39,7 +62,7 @@ export function previewSelectionSnapshot(s: EditorState, t: number): Position[]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! });+ positions.push({ kind: "cue", id: cue.id, lane, x: p.x!, y: p.y!, rotation: 0 });}return positions;}@@ -66,3 +89,100 @@ export function movePreviewSelection(s: EditorState, positions: Position[], dx:}if (patches.clips!.length || patches.overlays!.length) s.updateDocTransient(patches);}++type DocPatches = Parameters<EditorState["updateDocTransient"]>[0];++/** Land one pose on each member: a keyed item writes its key at the playhead,+ * the rest write their own fields. Clips place by their frame's top-left. */+function writePoses(+ s: EditorState,+ poses: { p: Position; x: number; y: number; rotation?: number; scale?: number; own?: OverlayPatch & Partial<FrameRect> }[],+) {+ const patches: DocPatches = { clips: [], overlays: [] };+ for (const { p, x, y, rotation, scale, own } of poses) {+ if (p.kind === "cue") {+ s.setSubtitleTrackMeta(p.lane!, { x, y });+ continue;+ }+ if (p.key) {+ const key = { ...p.key, x, y, ...(rotation !== undefined ? { rotation } : {}), ...(scale !== undefined ? { scale: p.key.scale * scale } : {}) };+ const patch = { kf: upsertKey(p.keys, key) };+ if (p.kind === "overlay") patches.overlays!.push({ id: p.id, patch });+ else patches.clips!.push({ id: p.id, patch });+ continue;+ }+ const turn = rotation === undefined ? {} : { rotation: rotation === 0 ? undefined : rotation };+ if (p.kind === "overlay") patches.overlays!.push({ id: p.id, patch: { x, y, ...turn, ...own } });+ else {+ const { w = p.frame!.w, h = p.frame!.h } = own ?? {};+ patches.clips!.push({ id: p.id, patch: { frame: { ...p.frame!, x, y, w, h }, ...turn } });+ }+ }+ if (patches.clips!.length || patches.overlays!.length) s.updateDocTransient(patches);+}++const clipCenter = (p: Position) => ({ x: p.x + (p.key ? 0 : p.frame!.w / 2), y: p.y + (p.key ? 0 : p.frame!.h / 2) });++/**+ * Scale the selection about an anchor (frame fractions) by kx and ky: every+ * center walks out from the anchor, and each item grows what it stores — a+ * shape's box, a sticker's width, a title's size (or its stretch on a+ * one-axis pull), a clip's frame, a keyed item's scale.+ */+export function scalePreviewSelection(s: EditorState, positions: Position[], anchor: { x: number; y: number }, kx: number, ky: number) {+ kx = Math.max(0.05, kx);+ ky = Math.max(0.05, ky);+ const uniform = Math.abs(kx - ky) < 1e-6;+ const k = uniform ? kx : kx * ky;+ writePoses(s, positions.map((p) => {+ const c = p.kind === "clip" ? clipCenter(p) : { x: p.x, y: p.y };+ const cx = anchor.x + (c.x - anchor.x) * kx;+ const cy = anchor.y + (c.y - anchor.y) * ky;+ if (p.key) return { p, x: cx, y: cy, scale: k };+ if (p.kind === "clip") {+ const w = p.frame!.w * kx, h = p.frame!.h * ky;+ return { p, x: Math.max(0.05 - w, Math.min(0.95, cx - w / 2)), y: Math.max(0.05 - h, Math.min(0.95, cy - h / 2)), own: { w, h } };+ }+ if (p.kind === "cue") return { p, x: cx, y: cy };+ let own: OverlayPatch | undefined;+ if (p.box) {+ // A sticker with no height of its own keeps its aspect and grows with+ // whichever axis the pull moved.+ own = { w: Math.max(0.01, p.box.w * (p.box.h === undefined && kx === 1 ? ky : kx)), ...(p.box.h !== undefined ? { h: Math.max(0.01, p.box.h * ky) } : {}) };+ } else if (p.text) {+ // Every frame writes the whole set from the snapshot, so a pull that+ // turns uniform mid-drag lands cleanly on one of the two.+ own = uniform+ ? { size: Math.max(8, p.text.size * k), stretchX: stretch(p.text.stretchX), stretchY: stretch(p.text.stretchY) }+ : { size: p.text.size, stretchX: stretch(p.text.stretchX * kx), stretchY: stretch(p.text.stretchY * ky) };+ }+ return { p, x: clampOverlayPos(cx), y: clampOverlayPos(cy), own };+ }));+}++const stretch = (v: number) => {+ const c = Math.max(0.25, Math.min(4, v));+ return Math.abs(c - 1) < 1e-6 ? undefined : c;+};++/**+ * Turn the selection rigidly about a center (frame fractions) by `delta`+ * degrees: every center orbits, in a square space keyed to width so the set+ * turns rigidly on screen, and every item adds the same angle to its own.+ */+export function rotatePreviewSelection(s: EditorState, positions: Position[], center: { x: number; y: number }, delta: number, aspect: number) {+ const rad = (delta * Math.PI) / 180;+ const ay = aspect;+ writePoses(s, positions.map((p) => {+ const c = p.kind === "clip" ? clipCenter(p) : { x: p.x, y: p.y };+ const ox = c.x - center.x;+ const oy = (c.y - center.y) * ay;+ const cx = center.x + ox * Math.cos(rad) - oy * Math.sin(rad);+ const cy = center.y + (ox * Math.sin(rad) + oy * Math.cos(rad)) / ay;+ const rotation = Math.round(normDeg(p.rotation + delta));+ if (p.kind === "cue") return { p, x: cx, y: cy };+ if (p.key) return { p, x: cx, y: cy, rotation };+ if (p.kind === "clip") return { p, x: cx - p.frame!.w / 2, y: cy - p.frame!.h / 2, rotation };+ return { p, x: clampOverlayPos(cx), y: clampOverlayPos(cy), rotation };+ }));+}