Open source CapCut alternative.
TypeScript
feat(site): preview guides — thirds, center, margins, short-form keep-out, custom lines [rebuild]
David Le66f194cc0707
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsxindex 6092afd3..5aec852e 100644--- a/site/src/cut/components/Editor.tsx+++ b/site/src/cut/components/Editor.tsx@@ -621,6 +621,8 @@ export function Editor({s.mediaFolders !== (last.mediaFolders as unknown) ||s.subtitles !== (last.subtitles as unknown) ||s.aspect !== last.aspect ||+ s.guides !== last.guides ||+ s.guideLines !== last.guideLines ||s.fadeIn !== (last.fadeIn ?? 0) ||s.fadeOut !== (last.fadeOut ?? 0) ||s.background !== last.background ||@@ -1042,6 +1044,9 @@ export function Editor({s.splitAtPlayhead(skimAt() ?? undefined);} else if (e.key.toLowerCase() === "s" && !e.metaKey && !e.ctrlKey && !e.altKey) {s.splitAtPlayhead(skimAt() ?? undefined);+ } else if (mod && e.key === ";") {+ e.preventDefault();+ s.setGuidesHidden(!s.guidesHidden);} else if (e.key.toLowerCase() === "t" && !e.metaKey && !e.ctrlKey && !e.altKey) {s.addOverlay();} else if ((e.key === "ArrowLeft" || e.key === "ArrowRight") && !controlFocused) {diff --git a/site/src/cut/components/GuideOverlay.tsx b/site/src/cut/components/GuideOverlay.tsxnew file mode 100644index 00000000..419b0f45--- /dev/null+++ b/site/src/cut/components/GuideOverlay.tsx@@ -0,0 +1,156 @@+"use client";++import type React from "react";+import { startDrag } from "@/cut/lib/drag";+import { useEditor } from "@/cut/lib/store";+import { guideGeometry } from "@/cut/lib/guides";++/** A custom line released this close to a frame edge drops. */+const EDGE_DROP = 0.01;++/**+ * The preview guides: thin lines and shaded keep-out regions drawn over the+ * stage in an SVG sized to it. The layer sits beside the stage in the chrome+ * host, outside the picture, so it never enters the frame loop, a captured+ * frame, or an export. It hides in a shared read-only view and under ⌘;.+ * Custom lines draw in blue and drag; a click on one, or a release at the+ * frame edge, removes it.+ */+export function GuideOverlay({ stage }: { stage: { w: number; h: number } }) {+ const guides = useEditor((s) => s.guides);+ const guideLines = useEditor((s) => s.guideLines);+ const hidden = useEditor((s) => s.guidesHidden);+ const readOnly = useEditor((s) => s.readOnly);+ const aspect = useEditor((s) => s.aspect);+ if (hidden || readOnly || guides.length === 0) return null;+ const geo = guideGeometry(guides, aspect, guideLines);+ if (+ geo.v.length === 0 &&+ geo.h.length === 0 &&+ geo.boxes.length === 0 &&+ geo.custom.v.length === 0 &&+ geo.custom.h.length === 0+ )+ return null;+ const { w, h } = stage;+ const label = Math.max(9, Math.min(12, w / 36));++ const dragLine = (axis: "v" | "h", index: number, from: number) => (e: React.PointerEvent) => {+ const size = axis === "v" ? w : h;+ const st = useEditor.getState();+ st.beginHistoryBatch();+ let raw = from;+ startDrag(e, {+ cursor: () => (axis === "v" ? "col-resize" : "row-resize"),+ onMove: (dx, dy) => {+ raw = from + (axis === "v" ? dx : dy) / size;+ useEditor.getState().moveGuideLine(axis, index, raw);+ },+ onUp: (_dx, _dy, moved) => {+ const s = useEditor.getState();+ if (!moved || raw <= EDGE_DROP || raw >= 1 - EDGE_DROP) s.removeGuideLine(axis, index);+ s.endHistoryBatch();+ },+ });+ };++ return (+ <svg+ className="pointer-events-none absolute inset-0 overflow-visible"+ width={w}+ height={h}+ viewBox={`0 0 ${w} ${h}`}+ aria-hidden+ >+ <defs>+ <pattern id="cut-guide-hatch" width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">+ <line x1="0" y1="0" x2="0" y2="8" stroke="rgba(239,68,68,0.45)" strokeWidth="1.5" />+ </pattern>+ </defs>+ {geo.boxes.map((b, i) => {+ const x = b.x * w;+ const y = b.y * h;+ const bw = b.w * w;+ const bh = b.h * h;+ // A full-width band names itself at its inner edge; a side rail at+ // its top, so the label sits where the keep-out meets the picture.+ const labelY = b.w >= 0.99 && b.y <= 0.01 ? y + bh - 5 : y + label + 4;+ return (+ <g key={`box-${i}`}>+ <rect x={x} y={y} width={bw} height={bh} fill="rgba(239,68,68,0.12)" />+ <rect x={x} y={y} width={bw} height={bh} fill="url(#cut-guide-hatch)" />+ <rect+ x={x + 0.5}+ y={y + 0.5}+ width={Math.max(0, bw - 1)}+ height={Math.max(0, bh - 1)}+ fill="none"+ stroke="rgba(239,68,68,0.8)"+ strokeWidth="1"+ strokeDasharray="4 3"+ />+ {bw > 40 && bh > label * 2 && (+ <text+ x={x + 6}+ y={labelY}+ fontSize={label}+ fontWeight={600}+ fill="rgba(255,255,255,0.95)"+ stroke="rgba(0,0,0,0.5)"+ strokeWidth="2.5"+ paintOrder="stroke"+ style={{ fontFamily: "ui-sans-serif, system-ui, sans-serif" }}+ >+ {b.label}+ </text>+ )}+ </g>+ );+ })}+ {geo.v.map((f, i) => (+ <g key={`v-${i}`}>+ <line x1={f * w} y1={0} x2={f * w} y2={h} stroke="rgba(0,0,0,0.45)" strokeWidth="3" />+ <line x1={f * w} y1={0} x2={f * w} y2={h} stroke="rgba(255,255,255,0.9)" strokeWidth="1" />+ </g>+ ))}+ {geo.h.map((f, i) => (+ <g key={`h-${i}`}>+ <line x1={0} y1={f * h} x2={w} y2={f * h} stroke="rgba(0,0,0,0.45)" strokeWidth="3" />+ <line x1={0} y1={f * h} x2={w} y2={f * h} stroke="rgba(255,255,255,0.9)" strokeWidth="1" />+ </g>+ ))}+ {geo.custom.v.map((f, i) => (+ <g key={`cv-${i}`}>+ <line x1={f * w} y1={0} x2={f * w} y2={h} stroke="rgba(0,0,0,0.45)" strokeWidth="3" />+ <line x1={f * w} y1={0} x2={f * w} y2={h} stroke="rgb(96,165,250)" strokeWidth="1" />+ <line+ x1={f * w}+ y1={0}+ x2={f * w}+ y2={h}+ stroke="transparent"+ strokeWidth="12"+ className="cursor-col-resize" style={{ pointerEvents: "stroke" }}+ onPointerDown={dragLine("v", i, f)}+ />+ </g>+ ))}+ {geo.custom.h.map((f, i) => (+ <g key={`ch-${i}`}>+ <line x1={0} y1={f * h} x2={w} y2={f * h} stroke="rgba(0,0,0,0.45)" strokeWidth="3" />+ <line x1={0} y1={f * h} x2={w} y2={f * h} stroke="rgb(96,165,250)" strokeWidth="1" />+ <line+ x1={0}+ y1={f * h}+ x2={w}+ y2={f * h}+ stroke="transparent"+ strokeWidth="12"+ className="cursor-row-resize" style={{ pointerEvents: "stroke" }}+ onPointerDown={dragLine("h", i, f)}+ />+ </g>+ ))}+ </svg>+ );+}diff --git a/site/src/cut/components/GuidesMenu.tsx b/site/src/cut/components/GuidesMenu.tsxnew file mode 100644index 00000000..ac777765--- /dev/null+++ b/site/src/cut/components/GuidesMenu.tsx@@ -0,0 +1,96 @@+"use client";++import { ChevronDown, Grid3x3 } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuCheckboxItem,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { GUIDE_PRESETS, guideFits } from "@/cut/lib/guides";+import { useEditor } from "@/cut/lib/store";+import { cn } from "@/lib/utils";++/** The preview guides control beside the timeline zoom: the icon shows and+ * hides the guides (⌘;), the chevron beside it picks which presets draw. A+ * first press with nothing picked turns on the safe margins. The icon lights+ * while any guide is showing. */+export function GuidesMenu() {+ const aspect = useEditor((s) => s.aspect);+ const guides = useEditor((s) => s.guides);+ const guidesHidden = useEditor((s) => s.guidesHidden);+ const showing = guides.length > 0 && !guidesHidden;+ const toggle = () => {+ const s = useEditor.getState();+ if (s.guides.length === 0) s.toggleGuide("margins");+ else s.setGuidesHidden(!s.guidesHidden);+ };+ return (+ <div className="mr-2 flex items-center">+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label={showing ? "Hide guides" : "Show guides"}+ title={showing ? "Hide guides (⌘;)" : "Show guides (⌘;)"}+ aria-pressed={showing}+ className={cn("rounded-r-none", showing && "bg-accent text-foreground")}+ onClick={toggle}+ >+ <Grid3x3 strokeWidth={1.5} />+ </Button>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label="Guide presets"+ title="Guide presets"+ className={cn("w-4 rounded-l-none", showing && "bg-accent text-foreground")}+ />+ }+ >+ <ChevronDown className="size-3" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-52">+ <DropdownMenuGroup>+ <DropdownMenuLabel>Guides</DropdownMenuLabel>+ {GUIDE_PRESETS.map((g) => {+ const fits = guideFits(g.id, aspect);+ return (+ <DropdownMenuCheckboxItem+ key={g.id}+ checked={guides.includes(g.id)}+ disabled={!fits}+ closeOnClick={false}+ onCheckedChange={() => useEditor.getState().toggleGuide(g.id)}+ >+ <span className="flex-1">+ {g.name}+ {g.sublabel && (+ <span className="block text-[10.5px] text-muted-foreground">+ {fits ? g.sublabel : "Portrait frames"}+ </span>+ )}+ </span>+ </DropdownMenuCheckboxItem>+ );+ })}+ </DropdownMenuGroup>+ <DropdownMenuSeparator />+ <DropdownMenuItem closeOnClick={false} onClick={() => useEditor.getState().addGuideLine("v")}>+ Add vertical line+ </DropdownMenuItem>+ <DropdownMenuItem closeOnClick={false} onClick={() => useEditor.getState().addGuideLine("h")}>+ Add horizontal line+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+}diff --git a/site/src/cut/components/OverlayLayer.tsx b/site/src/cut/components/OverlayLayer.tsxindex 30355f3d..ed3851de 100644--- a/site/src/cut/components/OverlayLayer.tsx+++ b/site/src/cut/components/OverlayLayer.tsx@@ -1,5 +1,6 @@"use client";+import { guideSnapLines } from "@/cut/lib/guides";import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties } from "react";import { createPortal } from "react-dom";import { releaseAnimRest, useAnimPreview } from "@/cut/lib/animPreview";@@ -178,6 +179,9 @@ export function OverlayLayer({);const selection = useEditor((s) => s.selection);const aspect = useEditor((s) => s.aspect);+ const shownGuides = useEditor((s) => s.guides);+ const guideLines = useEditor((s) => s.guideLines);+ const guidesHidden = useEditor((s) => s.guidesHidden);// Titles preview under the skimmer too (paused only), matching the canvas.const t = usePreviewTime();const skimTime = useSkim();@@ -218,9 +222,15 @@ export function OverlayLayer({const r = el.getBoundingClientRect();const cx = px * stageWidth;const cy = py * stageHeight;- // Frame lines: edges, safe margins, center.+ // Frame lines: edges, safe margins, center, and every guide showing —+ // a keep-out box offers its inner edge, so a title pulls flush to it.const vt = [0, CANVAS_MARGIN * stageWidth, stageWidth / 2, (1 - CANVAS_MARGIN) * stageWidth, stageWidth];const ht = [0, CANVAS_MARGIN * stageHeight, stageHeight / 2, (1 - CANVAS_MARGIN) * stageHeight, stageHeight];+ if (!guidesHidden) {+ const lines = guideSnapLines(shownGuides, aspect, guideLines);+ vt.push(...lines.v.map((f) => f * stageWidth));+ ht.push(...lines.h.map((f) => f * stageHeight));+ }// Plus every other on-screen box's edges and center (titles and the// subtitle caption alike), read from its rect in stage space.const rootRect = root.getBoundingClientRect();@@ -261,7 +271,7 @@ export function OverlayLayer({setGuides({ v, h });return { x: outX, y: outY };},- [stageWidth, stageHeight]+ [stageWidth, stageHeight, shownGuides, guideLines, guidesHidden, aspect]);const clearGuides = useCallback(() => setGuides({ v: [], h: [] }), []);diff --git a/site/src/cut/components/Preview.tsx b/site/src/cut/components/Preview.tsxindex bbe98562..2bf3b409 100644--- a/site/src/cut/components/Preview.tsx+++ b/site/src/cut/components/Preview.tsx@@ -24,6 +24,7 @@ import { CLIP_MAX_ZOOM, clipCovers, clipKeyed, clipPoseAt, clipZoom, contentRectimport { hasMaskKeys, type MaskKey } from "@donkeycut/effects-kit";import { cn } from "@/lib/utils";import { MaskGizmoCore, OverlayChromeHost, OverlayLayer, StagePress } from "./OverlayLayer";+import { GuideOverlay } from "./GuideOverlay";import { RemovalBrush } from "./RemovalBrush";import { CORNER_HANDLES, HANDLE_AXIS, TransformHandles, type ResizeHandle } from "./TransformHandles";import {@@ -634,6 +635,7 @@ export function Preview() {className="pointer-events-none absolute inset-0"style={{ "--stage-radius": `${stageRadius(stage.w, stage.h)}px` } as React.CSSProperties}/>+ <GuideOverlay stage={stage} /><ClipMaskGizmo stage={stage} /><RemovalBrush stage={stage} /><ClipTransformGizmo stage={stage} />diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex 8cc941d0..c99ebd13 100644--- a/site/src/cut/components/Timeline.tsx+++ b/site/src/cut/components/Timeline.tsx@@ -4,6 +4,7 @@ import { Fragment, useCallback, useEffect, useLayoutEffect, useMemo, useReducer,import { ArrowDownToLine, AudioLines, Check, Clapperboard, Copy, Diamond, Download, EllipsisVertical, Eye, EyeOff, FolderOpen, FolderPlus, Fullscreen, Loader2, MoreHorizontal, Pause, Play, Scissors, SkipBack, Sticker, Trash2, Type, Volume2, VolumeX } from "lucide-react";import { EFFECT_CHIP_ICONS, effectIconKind, SHAPE_CHIP_ICONS, TRANSITION_ICONS } from "@/cut/components/entityIcons";import { Button } from "@/components/ui/button";+import { GuidesMenu } from "@/cut/components/GuidesMenu";import {DropdownMenu,DropdownMenuContent,@@ -2320,6 +2321,7 @@ export function Timeline() {barTight && "invisible absolute right-0 pointer-events-none")}>+ <GuidesMenu /><SliderclassName="data-horizontal:w-28"min={0}@@ -2333,6 +2335,7 @@ export function Timeline() {Fit</Button></div>+ {barTight && <GuidesMenu />}{barTight && (<TimelineToolsMenupps={pps}diff --git a/site/src/cut/lib/guides.test.ts b/site/src/cut/lib/guides.test.tsnew file mode 100644index 00000000..c5edda4d--- /dev/null+++ b/site/src/cut/lib/guides.test.ts@@ -0,0 +1,41 @@+import { describe, expect, test } from "bun:test";+import { guideGeometry, guideSnapLines, safeAreaOf, sanitizeGuideLines, sanitizeGuides } from "./guides";++describe("guides", () => {+ test("sanitizeGuides keeps known ids once, in registry order", () => {+ expect(sanitizeGuides(["shortform", "nope", "thirds", "shortform"])).toEqual(["thirds", "shortform"]);+ expect(sanitizeGuides(undefined)).toEqual([]);+ });++ test("platform zones apply to portrait frames only", () => {+ expect(guideGeometry(["shortform"], "9:16").boxes.length).toBe(3);+ expect(guideGeometry(["shortform"], "16:9").boxes.length).toBe(0);+ expect(guideGeometry(["thirds"], "16:9").v).toEqual([1 / 3, 2 / 3]);+ });++ test("the safe area is the frame minus every keep-out band and rail", () => {+ const safe = safeAreaOf(["shortform"], "9:16")!;+ expect(safe.x).toBe(0);+ expect(safe.y).toBeGreaterThan(0.07);+ expect(safe.x + safe.w).toBeLessThan(0.88);+ expect(safe.y + safe.h).toBeLessThan(0.77);+ expect(safeAreaOf(["thirds", "center"], "9:16")).toBeNull();+ expect(safeAreaOf(["margins"], "16:9")).toEqual({ x: 0.05, y: 0.05, w: 0.9, h: 0.9 });+ });++ test("custom lines draw and snap only while the custom set is on", () => {+ const lines = { v: [0.2], h: [0.7] };+ expect(guideGeometry(["custom"], "16:9", lines).custom).toEqual(lines);+ expect(guideGeometry(["thirds"], "16:9", lines).custom).toEqual({ v: [], h: [] });+ expect(guideSnapLines(["custom"], "16:9", lines).v).toEqual([0.2]);+ expect(sanitizeGuideLines({ v: [1.4, "x", -0.2], h: null })).toEqual({ v: [1, 0], h: [] });+ });++ test("snap lines carry drawn lines and the inner edge of every box", () => {+ const lines = guideSnapLines(["center", "shortform"], "9:16");+ expect(lines.v.includes(0.5)).toBe(true);+ expect(lines.h.includes(0.5)).toBe(true);+ expect(lines.h.length).toBe(3);+ expect(lines.v.length).toBe(2);+ });+});diff --git a/site/src/cut/lib/guides.ts b/site/src/cut/lib/guides.tsnew file mode 100644index 00000000..a4a8d575--- /dev/null+++ b/site/src/cut/lib/guides.ts@@ -0,0 +1,206 @@+/**+ * Preview guides: lines and keep-out regions drawn over the stage so titles,+ * stickers and captions land where a phone will show them. Geometry is in+ * frame fractions (0..1 of width and height), so one preset serves every+ * frame size. Guides draw in the editor only; exports and captured frames+ * never carry them. The short-form preset is measured on a 1080×1920 phone+ * screen and dated, so a change in an app's UI is one edit here.+ */++import { aspectOrientation, type Aspect } from "./types";++export type GuideId = "thirds" | "center" | "margins" | "shortform" | "custom";++/** The user's own lines, frame fractions per axis: v is x positions, h is y. */+export interface GuideLines {+ v: number[];+ h: number[];+}++/** A region the platform's own UI covers, as frame fractions. */+export interface GuideBox {+ x: number;+ y: number;+ w: number;+ h: number;+ label: string;+}++/** Lines (frame fractions along one axis) and keep-out boxes to draw. The+ * custom lines come separately: they draw in their own color and drag. */+export interface GuideGeometry {+ v: number[];+ h: number[];+ boxes: GuideBox[];+ custom: GuideLines;+}++/** The rectangle left for graphics once every keep-out box is removed. */+export interface SafeArea {+ x: number;+ y: number;+ w: number;+ h: number;+}++export interface GuidePreset {+ id: GuideId;+ name: string;+ sublabel?: string;+ /** Phone UI is measured on a phone, so the preset fits portrait frames. */+ portraitOnly?: boolean;+ geometry: Omit<GuideGeometry, "custom">;+}++/** Safe-margin inset, fraction of the frame. */+export const MARGIN_INSET = 0.05;++const phone = (px: number, of: 1080 | 1920) => px / of;++export const GUIDE_PRESETS: readonly GuidePreset[] = [+ {+ id: "thirds",+ name: "Thirds",+ geometry: { v: [1 / 3, 2 / 3], h: [1 / 3, 2 / 3], boxes: [] },+ },+ {+ id: "center",+ name: "Center",+ geometry: { v: [0.5], h: [0.5], boxes: [] },+ },+ {+ id: "margins",+ name: "Safe margins",+ sublabel: "5% inset",+ geometry: {+ v: [MARGIN_INSET, 1 - MARGIN_INSET],+ h: [MARGIN_INSET, 1 - MARGIN_INSET],+ boxes: [],+ },+ },+ // The phone UI of TikTok, Instagram Reels and YouTube Shorts, merged into+ // one keep-out: each region is the widest of the three. Measured September+ // 2026 on a 1080×1920 screen.+ {+ id: "shortform",+ name: "Short form",+ sublabel: "TikTok, Instagram, YouTube",+ portraitOnly: true,+ geometry: {+ v: [],+ h: [],+ boxes: [+ { x: 0, y: 0, w: 1, h: phone(150, 1920), label: "Top bar" },+ { x: phone(930, 1080), y: phone(800, 1920), w: phone(150, 1080), h: phone(740, 1920), label: "Actions" },+ { x: 0, y: phone(1460, 1920), w: 1, h: phone(460, 1920), label: "Caption · music · nav" },+ ],+ },+ },+ // The user's own lines, held in the project's guideLines and dragged on+ // the preview.+ {+ id: "custom",+ name: "Custom",+ sublabel: "Drag lines on the preview",+ geometry: { v: [], h: [], boxes: [] },+ },+];++export const EMPTY_GUIDE_LINES: GuideLines = { v: [], h: [] };++const clamp01 = (n: number) => Math.min(1, Math.max(0, n));++/** A stored line list with every position a number in 0..1. */+export function sanitizeGuideLines(v: unknown): GuideLines {+ const axis = (a: unknown) =>+ Array.isArray(a) ? a.filter((n): n is number => typeof n === "number" && Number.isFinite(n)).map(clamp01) : [];+ const o = v && typeof v === "object" ? (v as Record<string, unknown>) : {};+ return { v: axis(o.v), h: axis(o.h) };+}++export const GUIDE_IDS = GUIDE_PRESETS.map((p) => p.id) as GuideId[];++export function isGuideId(v: unknown): v is GuideId {+ return typeof v === "string" && (GUIDE_IDS as string[]).includes(v);+}++/** The known guide ids in a stored list, in registry order, each once. */+export function sanitizeGuides(v: unknown): GuideId[] {+ if (!Array.isArray(v)) return [];+ return GUIDE_IDS.filter((id) => v.includes(id));+}++export function guidePreset(id: GuideId): GuidePreset {+ return GUIDE_PRESETS.find((p) => p.id === id)!;+}++/** Whether a preset applies to the frame: platform chrome fits portrait frames. */+export function guideFits(id: GuideId, aspect: Aspect): boolean {+ return !guidePreset(id).portraitOnly || aspectOrientation(aspect) === "portrait";+}++/** Every line and box of the guides that are on and fit the frame, merged;+ * the custom lines ride along when the custom set is on. */+export function guideGeometry(+ ids: readonly GuideId[],+ aspect: Aspect,+ lines: GuideLines = EMPTY_GUIDE_LINES+): GuideGeometry {+ const out: GuideGeometry = { v: [], h: [], boxes: [], custom: EMPTY_GUIDE_LINES };+ for (const id of ids) {+ if (!guideFits(id, aspect)) continue;+ if (id === "custom") {+ out.custom = lines;+ continue;+ }+ const g = guidePreset(id).geometry;+ out.v.push(...g.v);+ out.h.push(...g.h);+ out.boxes.push(...g.boxes);+ }+ return out;+}++/** The snap lines the guides offer a dragged element: every drawn line plus+ * the inner edge of every keep-out box. */+export function guideSnapLines(+ ids: readonly GuideId[],+ aspect: Aspect,+ lines: GuideLines = EMPTY_GUIDE_LINES+): GuideLines {+ const g = guideGeometry(ids, aspect, lines);+ const v = [...g.v, ...g.custom.v];+ const h = [...g.h, ...g.custom.h];+ for (const b of g.boxes) {+ if (b.w >= 0.99) h.push(b.y <= 0.01 ? b.y + b.h : b.y);+ else if (b.x + b.w >= 0.99) v.push(b.x);+ else if (b.x <= 0.01) v.push(b.x + b.w);+ }+ return { v, h };+}++/** The frame minus every keep-out box and inside the safe margins, as one+ * rectangle; null when no active guide bounds anything. */+export function safeAreaOf(ids: readonly GuideId[], aspect: Aspect): SafeArea | null {+ let left = 0;+ let top = 0;+ let right = 1;+ let bottom = 1;+ let bounded = false;+ if (ids.includes("margins")) {+ left = top = MARGIN_INSET;+ right = bottom = 1 - MARGIN_INSET;+ bounded = true;+ }+ for (const b of guideGeometry(ids, aspect).boxes) {+ bounded = true;+ if (b.w >= 0.99) {+ if (b.y <= 0.01) top = Math.max(top, b.y + b.h);+ else bottom = Math.min(bottom, b.y);+ } else if (b.x + b.w >= 0.99) right = Math.min(right, b.x);+ else if (b.x <= 0.01) left = Math.max(left, b.x + b.w);+ }+ if (!bounded) return null;+ const round = (n: number) => Math.round(n * 1000) / 1000;+ return { x: round(left), y: round(top), w: round(right - left), h: round(bottom - top) };+}diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 43fc1e32..97417a9e 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -1,5 +1,6 @@"use client";+import { EMPTY_GUIDE_LINES, sanitizeGuideLines, sanitizeGuides, type GuideId, type GuideLines } from "./guides";import {groupRemap,isAudioEffect,@@ -330,6 +331,12 @@ export interface EditorState {/** The aspect was chosen deliberately (picker, set_aspect, or saved in the* doc) — the first-import orientation guess stands down. Not a doc field. */aspectTouched: boolean;+ /** Preview guides turned on, persisted per project. */+ guides: GuideId[];+ /** The custom guide lines, drawn when "custom" is among `guides`. */+ guideLines: GuideLines;+ /** Guides stay chosen but draw nothing (⌘;). Not a doc field. */+ guidesHidden: boolean;/** Whole-video fades, seconds (0 = off): in from black at the start, out to* black at the end of the cut. Applied to the final picture and mix. */fadeIn: number;@@ -416,6 +423,15 @@ export interface EditorState {setSharedView: (features: ShareFeatures) => void;setAspect: (a: Aspect) => void;+ setGuides: (ids: GuideId[]) => void;+ toggleGuide: (id: GuideId) => void;+ setGuidesHidden: (hidden: boolean) => void;+ setGuideLines: (lines: GuideLines) => void;+ /** Add a custom line at the frame center (stepping aside from one already+ * there), turning the custom set on and the guides visible. */+ addGuideLine: (axis: "v" | "h") => void;+ moveGuideLine: (axis: "v" | "h", index: number, at: number) => void;+ removeGuideLine: (axis: "v" | "h", index: number) => void;/** Set the whole-video fade in/out (seconds; 0 clears). Like the aspect,* project-level settings sit outside the undo history. */setProjectFade: (patch: { fadeIn?: number; fadeOut?: number }) => void;@@ -1292,6 +1308,8 @@ const DOC_KEYS = ["templates","mediaFolders","aspect",+ "guides",+ "guideLines","fadeIn","fadeOut","background",@@ -1694,6 +1712,8 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {mediaFolders: [],aspect: lastChosenAspect() ?? "9:16",aspectTouched: lastChosenAspect() !== null,+ guides: [],+ guideLines: EMPTY_GUIDE_LINES,fadeIn: 0,fadeOut: 0,background: DEFAULT_BACKGROUND,@@ -1744,6 +1764,9 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {mediaFolders: [],aspect: lastChosenAspect() ?? "9:16",aspectTouched: lastChosenAspect() !== null,+ guides: [],+ guidesHidden: false,+ guideLines: EMPTY_GUIDE_LINES,fadeIn: 0,fadeOut: 0,background: DEFAULT_BACKGROUND,@@ -2112,6 +2135,8 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {mediaFolders: doc.mediaFolders ?? [],aspect: normalizeAspect(doc.aspect) ?? lastChosenAspect() ?? "9:16",aspectTouched: doc.aspect !== undefined || lastChosenAspect() !== null,+ guides: sanitizeGuides(doc.guides),+ guideLines: sanitizeGuideLines(doc.guideLines),fadeIn: doc.fadeIn ?? 0,fadeOut: doc.fadeOut ?? 0,background: projectBackground(doc.background),@@ -2326,6 +2351,39 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {rememberAspect(n);set({ aspect: n, aspectTouched: true });},+ setGuides: (ids) => set({ guides: sanitizeGuides(ids) }),+ toggleGuide: (id) =>+ set((s) => ({+ guides: s.guides.includes(id)+ ? s.guides.filter((g) => g !== id)+ : sanitizeGuides([...s.guides, id]),+ // Turning a guide on is a request to see it.+ guidesHidden: s.guides.includes(id) ? s.guidesHidden : false,+ })),+ setGuidesHidden: (hidden) => set({ guidesHidden: hidden }),+ setGuideLines: (lines) => set({ guideLines: sanitizeGuideLines(lines) }),+ addGuideLine: (axis) =>+ set((s) => {+ const have = s.guideLines[axis];+ let at = 0.5;+ while (have.some((n) => Math.abs(n - at) < 0.01) && at < 0.95) at += 0.05;+ return {+ guideLines: { ...s.guideLines, [axis]: [...have, at] },+ guides: s.guides.includes("custom") ? s.guides : sanitizeGuides([...s.guides, "custom"]),+ guidesHidden: false,+ };+ }),+ moveGuideLine: (axis, index, at) =>+ set((s) => {+ if (index < 0 || index >= s.guideLines[axis].length) return {};+ const next = [...s.guideLines[axis]];+ next[index] = Math.min(1, Math.max(0, at));+ return { guideLines: { ...s.guideLines, [axis]: next } };+ }),+ removeGuideLine: (axis, index) =>+ set((s) => ({+ guideLines: { ...s.guideLines, [axis]: s.guideLines[axis].filter((_, i) => i !== index) },+ })),setProjectFade: (patch) => {const clamp = (v: number | undefined) =>v === undefined ? undefined : Math.max(0, Math.min(TRANSITION_MAX, v));@@ -5223,6 +5281,8 @@ export function serializeDoc(s: {templates: LibraryTemplate[];mediaFolders: MediaFolder[];aspect: Aspect;+ guides: GuideId[];+ guideLines: GuideLines;fadeIn: number;fadeOut: number;background: string;@@ -5245,6 +5305,8 @@ export function serializeDoc(s: {templates: s.templates,mediaFolders: s.mediaFolders,aspect: s.aspect,+ guides: s.guides,+ guideLines: s.guideLines,fadeIn: s.fadeIn,fadeOut: s.fadeOut,background: s.background,diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsindex ce7dcc6c..186c8527 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -1,3 +1,4 @@+import type { GuideId, GuideLines } from "./guides";import {behindSubjectMask,overlayKind,@@ -1433,6 +1434,11 @@ export interface ProjectDoc {overlays: Overlay[];/** Output frame; absent in older projects (which are all 9:16). */aspect?: Aspect;+ /** Preview guides turned on: thirds, center, safe margins, platform+ * keep-out zones. Drawn over the preview only; absent = none. */+ guides?: GuideId[];+ /** The custom guide lines, frame fractions per axis; absent = none. */+ guideLines?: GuideLines;/** Whole-video fades, seconds: in from black at the start, out to black at* the end. Applied to the final picture and mix (titles, captions, and* soundtrack fade together), so they survive clip reordering. */diff --git a/site/src/cut/server/cloud/projects.ts b/site/src/cut/server/cloud/projects.tsindex 18bc724d..79ac7ad0 100644--- a/site/src/cut/server/cloud/projects.ts+++ b/site/src/cut/server/cloud/projects.ts@@ -1,5 +1,6 @@// Cloud twin of the engine's project CRUD (server/projects.ts + http/projects.ts):// docs and metadata in Postgres, media bytes in R2. Every query scopes by userId.+import { sanitizeGuideLines, sanitizeGuides } from "@/cut/lib/guides";import { resolveParent } from "@/cut/lib/folderTree";import { normalizeAspect, type ProjectDoc, type ProjectFolder, type ProjectSummary } from "@/cut/lib/types";import type { Prisma } from "@/generated/prisma/client";@@ -218,6 +219,8 @@ export const projectsCloud = {templates: Array.isArray(body.templates) ? body.templates : existing.templates,mediaFolders: Array.isArray(body.mediaFolders) ? body.mediaFolders : existing.mediaFolders,aspect: normalizeAspect(body.aspect) ?? existing.aspect,+ guides: Array.isArray(body.guides) ? sanitizeGuides(body.guides) : existing.guides,+ guideLines: body.guideLines !== undefined ? sanitizeGuideLines(body.guideLines) : existing.guideLines,fadeIn: typeof body.fadeIn === "number" ? body.fadeIn : existing.fadeIn,fadeOut: typeof body.fadeOut === "number" ? body.fadeOut : existing.fadeOut,background: typeof body.background === "string" ? body.background : existing.background,diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.tsindex ea9b2caf..7116760e 100644--- a/site/src/cut/server/http/projects.ts+++ b/site/src/cut/server/http/projects.ts@@ -1,3 +1,4 @@+import { sanitizeGuideLines, sanitizeGuides } from "@/cut/lib/guides";import { execFile } from "node:child_process";import { normalizeAspect, type ProjectDoc } from "@/cut/lib/types";import { detectSilence, extractAudio, makeFreezeFrame, probeDims, probeDuration } from "../frames";@@ -130,6 +131,8 @@ export const projectsApi = {templates: Array.isArray(body.templates) ? body.templates : existing.templates,mediaFolders: Array.isArray(body.mediaFolders) ? body.mediaFolders : existing.mediaFolders,aspect: normalizeAspect(body.aspect) ?? existing.aspect,+ guides: Array.isArray(body.guides) ? sanitizeGuides(body.guides) : existing.guides,+ guideLines: body.guideLines !== undefined ? sanitizeGuideLines(body.guideLines) : existing.guideLines,fadeIn: typeof body.fadeIn === "number" ? body.fadeIn : existing.fadeIn,fadeOut: typeof body.fadeOut === "number" ? body.fadeOut : existing.fadeOut,background: typeof body.background === "string" ? body.background : existing.background,