Open source CapCut alternative.
TypeScript
feat(site): Cut timeline, canvas & text-overlay editing fixes
David Le57d01c5bd418
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsxindex 894125b7..2af7d0f7 100644--- a/site/src/cut/components/Inspector.tsx+++ b/site/src/cut/components/Inspector.tsx@@ -1,8 +1,13 @@"use client";-import { useRef, useState } from "react";-import { Bold } from "lucide-react";+import { useEffect, useRef, useState } from "react";+import { Bold, Smile } from "lucide-react";import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";import {Select,SelectContent,@@ -15,6 +20,7 @@ import { Switch } from "@/components/ui/switch";import { Textarea } from "@/components/ui/textarea";import { useEditor } from "@/cut/lib/store";import { PLATE_COLOR, PLATE_OPACITY, PLATE_RADIUS } from "@/cut/lib/textRender";+import { writeTextStyle } from "@/cut/lib/textStyle";import { formatTime } from "@/cut/lib/time";import {FONTS,@@ -29,6 +35,14 @@ import { cn } from "@/lib/utils";const SWATCHES = ["#FFFFFF", "#111114", "#FFD60A", "#FF375F", "#0A84FF", "#30D158"];+// A compact set of social-friendly emoji for the text editor. These are plain+// unicode, so they render with the viewer's system emoji font.+const EMOJIS = [+ "๐ฅ", "๐", "๐ฎ", "๐", "๐ฏ", "๐", "๐", "โจ",+ "๐", "๐ช", "๐คฏ", "๐", "๐", "โค๏ธ", "๐ ", "๐ฅถ",+ "๐", "๐ก", "โก", "๐ค", "๐ฑ", "๐", "๐", "๐ธ",+];+/** Last three custom colors picked with the eyedropper, newest first. */const RECENT_COLORS_KEY = "cut-recent-colors";@@ -348,19 +362,82 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {const sizeCk = useSliderCheckpoint();const radiusCk = useSliderCheckpoint();const opacityCk = useSliderCheckpoint();+ const taRef = useRef<HTMLTextAreaElement>(null);++ // Remember this title's look across clips and projects, so the next new title+ // starts from the same style.+ useEffect(() => {+ writeTextStyle({+ size: o.size,+ font: o.font,+ weight: o.weight,+ color: o.color,+ shadow: o.shadow,+ plate: o.plate,+ plateColor: o.plateColor,+ plateOpacity: o.plateOpacity,+ plateRadius: o.plateRadius,+ });+ }, [o.size, o.font, o.weight, o.color, o.shadow, o.plate, o.plateColor, o.plateOpacity, o.plateRadius]);++ const insertEmoji = (emoji: string) => {+ const ta = taRef.current;+ const s = useEditor.getState();+ s.pushHistory();+ const start = ta?.selectionStart ?? o.text.length;+ const end = ta?.selectionEnd ?? start;+ const next = o.text.slice(0, start) + emoji + o.text.slice(end);+ s.updateOverlayTransient(o.id, { text: next });+ requestAnimationFrame(() => {+ const pos = start + emoji.length;+ ta?.focus();+ ta?.setSelectionRange(pos, pos);+ });+ };+return (<>- <PanelTitle>Title</PanelTitle>+ <PanelTitle>Text</PanelTitle><div className="flex flex-col gap-1 px-3.5 pb-4">- <Textarea- className="mb-2 min-h-16 select-text"- rows={3}- value={o.text}- onChange={(e) =>- useEditor.getState().updateOverlayTransient(o.id, { text: e.target.value })- }- onFocus={() => useEditor.getState().pushHistory()}- />+ <div className="relative mb-2">+ <Textarea+ ref={taRef}+ className="min-h-16 select-text pr-9"+ rows={3}+ value={o.text}+ onChange={(e) =>+ useEditor.getState().updateOverlayTransient(o.id, { text: e.target.value })+ }+ onFocus={() => useEditor.getState().pushHistory()}+ />+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label="Insert emoji"+ title="Insert emoji"+ className="absolute top-1.5 right-1.5 text-muted-foreground"+ />+ }+ >+ <Smile />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="grid grid-cols-8 gap-0.5 p-1.5">+ {EMOJIS.map((e) => (+ <button+ key={e}+ type="button"+ className="grid size-7 place-items-center rounded text-lg hover:bg-accent"+ onClick={() => insertEmoji(e)}+ >+ {e}+ </button>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ </div><Row label="Font"><Selectvalue={o.font}diff --git a/site/src/cut/components/OverlayLayer.tsx b/site/src/cut/components/OverlayLayer.tsxindex 16cb1c99..697b00ff 100644--- a/site/src/cut/components/OverlayLayer.tsx+++ b/site/src/cut/components/OverlayLayer.tsx@@ -3,10 +3,9 @@import { useEffect, useRef, useState, type CSSProperties } from "react";import { startDrag } from "@/cut/lib/drag";import { useEditor } from "@/cut/lib/store";-import { cueAt, SUB_STYLE, wrapCaption } from "@/cut/lib/subtitles";+import { captionStyle, cueAt, cueOverlay } from "@/cut/lib/subtitles";import {LINE_HEIGHT,- PLATE_FILL,PLATE_PAD_X,PLATE_PAD_Y,PLATE_RADIUS,@@ -40,7 +39,7 @@ export function OverlayLayer({ stageWidth }: { stageWidth: number }) {key={o.id}overlay={o}selected={selected}- ghost={!inRange}+ ghost={!inRange && !selected}stageWidth={stageWidth}/>);@@ -63,26 +62,38 @@ export function SubtitleLayer({ stageWidth }: { stageWidth: number }) {const cue = cueAt(subtitles.cues, t);if (!cue || !cue.text.trim()) return null;+ // Captions ride the same style/opener logic as the export burn-in, so the+ // preview and the rendered file match exactly.+ const ov = cueOverlay(+ cue,+ captionStyle(subtitles.style),+ cue.id === subtitles.cues[0]?.id+ );const scale = stageWidth / FRAME[aspect].w;return (<div className="pointer-events-none absolute inset-0"><div- className="sub-caption absolute -translate-x-1/2 -translate-y-1/2 text-center whitespace-pre"+ className="sub-caption absolute -translate-x-1/2 -translate-y-1/2 text-center whitespace-pre-wrap"style={{- left: `${SUB_STYLE.x * 100}%`,- top: `${SUB_STYLE.y * 100}%`,- fontSize: SUB_STYLE.size * scale,- fontFamily: fontStack(SUB_STYLE.font),- fontWeight: SUB_STYLE.weight,+ left: `${ov.x * 100}%`,+ top: `${ov.y * 100}%`,+ // Hard cap at the safe area so a caption can never spill past the+ // frame edge, even if a line slips past the wrap estimate.+ maxWidth: `${0.9 * stageWidth}px`,+ fontSize: ov.size * scale,+ fontFamily: fontStack(ov.font),+ fontWeight: ov.weight,lineHeight: LINE_HEIGHT,- color: SUB_STYLE.color,- textShadow: `0 ${SHADOW.offsetY * scale}px ${SHADOW.blur * scale}px ${SHADOW.color}`,- background: PLATE_FILL,- padding: PLATE_PADDING,- borderRadius: PLATE_RADIUS_EM,+ color: ov.color,+ textShadow: ov.shadow+ ? `0 ${SHADOW.offsetY * scale}px ${SHADOW.blur * scale}px ${SHADOW.color}`+ : undefined,+ background: ov.plate ? plateFill(ov) : undefined,+ padding: ov.plate ? PLATE_PADDING : undefined,+ borderRadius: ov.plate ? PLATE_RADIUS_EM : undefined,}}>- {wrapCaption(cue.text)}+ {ov.text}</div></div>);@@ -144,6 +155,19 @@ function OverlayItem({}};+ // A single click anywhere outside the editable box commits and dismisses it,+ // so text doesn't stay "stuck" in edit mode when the click misses focus.+ useEffect(() => {+ if (!editing) return;+ const onDown = (e: PointerEvent) => {+ if (!editRef.current?.contains(e.target as Node)) commitText();+ };+ document.addEventListener("pointerdown", onDown, true);+ return () => document.removeEventListener("pointerdown", onDown, true);+ // commitText closes over the current overlay; re-bind when editing toggles.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [editing]);+return (<divref={boxRef}diff --git a/site/src/cut/components/Preview.tsx b/site/src/cut/components/Preview.tsxindex 641f6b8c..4160c12e 100644--- a/site/src/cut/components/Preview.tsx+++ b/site/src/cut/components/Preview.tsx@@ -86,7 +86,7 @@ export function Preview() {};return (- <section className="flex min-h-0 min-w-0 flex-col bg-muted/40">+ <section className="flex min-h-0 min-w-0 flex-col bg-muted/40 select-none"><div ref={wrapRef} className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 p-3"><divclassName={cn(diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex 7d83b599..e0893c7f 100644--- a/site/src/cut/components/Timeline.tsx+++ b/site/src/cut/components/Timeline.tsx@@ -10,7 +10,16 @@ import {DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";import { Slider } from "@/components/ui/slider";-import { clearAssetDrag, draggedAssetId, draggingAssetId, hasAssetDrag } from "@/cut/lib/assetDrag";+import {+ clearAssetDrag,+ draggedAssetId,+ draggedLibraryId,+ draggingAssetId,+ draggingLibrary,+ hasAssetDrag,+ hasLibraryDrag,+} from "@/cut/lib/assetDrag";+import { importLibraryAsset } from "@/cut/lib/library";import { startDrag } from "@/cut/lib/drag";import { ensurePeaks } from "@/cut/lib/media";import { clipLen, clipSpeed, getClipSpans, TIMELINE_H_MAX, totalDuration, useEditor } from "@/cut/lib/store";@@ -82,6 +91,9 @@ export function Timeline() {const subtitles = useEditor((s) => s.subtitles);const scrollRef = useRef<HTMLDivElement>(null);const innerRef = useRef<HTMLDivElement>(null);+ // Measured width of the scroll viewport, so the ruler and tracks always draw+ // end-to-end no matter how wide the window is.+ const [viewportW, setViewportW] = useState(900);// Membership set so every track can highlight all selected items, not just// the primary one.@@ -92,7 +104,9 @@ export function Timeline() {const spans = useMemo(() => getClipSpans(clips, assets), [clips, assets]);const total = totalDuration(clips);- const contentW = Math.max(total * pps + PAD_END, 900);+ // Fill the viewport at minimum so a wide window never leaves the ruler/tracks+ // cut off; grow past it once the content is longer.+ const contentW = Math.max(total * pps + PAD_END, viewportW - PAD_SIDE * 2, 600);// Reorder drag on the video track: neighbors part to open a highlighted// slot at the insertion point; releasing drops the clip into it.@@ -236,6 +250,17 @@ export function Timeline() {return () => el.removeEventListener("wheel", onWheel);}, [zoomTo]);+ // Track the viewport width so `contentW` can fill it end-to-end.+ useEffect(() => {+ const el = scrollRef.current;+ if (!el) return;+ const measure = () => setViewportW(el.clientWidth);+ measure();+ const ro = new ResizeObserver(measure);+ ro.observe(el);+ return () => ro.disconnect();+ }, []);+// Timeline-scoped keys: = / - zoom around the playhead, Home/End jump.useEffect(() => {const onKey = (e: KeyboardEvent) => {@@ -267,6 +292,23 @@ export function Timeline() {return () => window.removeEventListener("keydown", onKey);}, [zoomTo]);+ // Drop an asset onto the timeline: video snaps into the nearest slot at time+ // `t`, audio lands free-form there.+ const placeAssetAt = (assetId: string, type: "video" | "audio", t: number) => {+ const s = useEditor.getState();+ if (type === "video") {+ const sp = getClipSpans(s.clips, s.assets);+ const spanIndex = videoInsertIndex(sp, t);+ const clipsIndex =+ spanIndex < sp.length+ ? s.clips.findIndex((c) => c.id === sp[spanIndex].clip.id)+ : s.clips.length;+ s.addClipFromAsset(assetId, clipsIndex);+ } else {+ s.addAudioFromAsset(assetId, t);+ }+ };+// Drag the panel's top border to resize; the border itself stays as-is,// only an invisible grab strip sits on top of it.const resize = (e: React.PointerEvent) => {@@ -281,24 +323,34 @@ export function Timeline() {return (<footer- className="relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border bg-card"+ className="relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border bg-card select-none"style={{ height: timelineH }}onDragOver={(e) => {- if (!hasAssetDrag(e)) return;+ const isLib = hasLibraryDrag(e);+ if (!hasAssetDrag(e) && !isLib) return;e.preventDefault();e.dataTransfer.dropEffect = "copy";- // Preview where a video asset would land; audio drops free-form.- const id = draggingAssetId();- const asset = id ? useEditor.getState().assets.find((a) => a.id === id) : null;- if (!asset || asset.type !== "video") {+ // Preview where a video would land; audio drops free-form. Library drags+ // carry their own shape since they aren't in the project yet.+ let type: "video" | "audio" | undefined;+ let duration = 0;+ if (isLib) {+ const lib = draggingLibrary();+ type = lib?.type;+ duration = lib?.duration ?? 0;+ } else {+ const id = draggingAssetId();+ const asset = id ? useEditor.getState().assets.find((a) => a.id === id) : null;+ type = asset?.type;+ duration = asset?.duration ?? 0;+ }+ if (type !== "video" || !duration) {setAssetDrop(null);return;}const index = videoInsertIndex(spans, Math.max(0, timeAt(e.clientX)));setAssetDrop((prev) =>- prev && prev.index === index && prev.len === asset.duration- ? prev- : { index, len: asset.duration }+ prev && prev.index === index && prev.len === duration ? prev : { index, len: duration });}}onDragLeave={(e) => {@@ -306,25 +358,26 @@ export function Timeline() {}}onDrop={(e) => {setAssetDrop(null);+ const t = Math.max(0, timeAt(e.clientX));++ // A library asset must be copied into the project before it can land.+ const lib = draggingLibrary();+ const libId = draggedLibraryId(e);+ const projectId = useEditor.getState().projectId;clearAssetDrag();+ if (libId && lib && projectId) {+ e.preventDefault();+ void importLibraryAsset(projectId, lib)+ .then((asset) => placeAssetAt(asset.id, asset.type, t))+ .catch(() => {});+ return;+ }+const id = draggedAssetId(e);if (!id) return;e.preventDefault();- const s = useEditor.getState();- const asset = s.assets.find((a) => a.id === id);- if (!asset) return;- const t = Math.max(0, timeAt(e.clientX));- if (asset.type === "video") {- const sp = getClipSpans(s.clips, s.assets);- const spanIndex = videoInsertIndex(sp, t);- const clipsIndex =- spanIndex < sp.length- ? s.clips.findIndex((c) => c.id === sp[spanIndex].clip.id)- : s.clips.length;- s.addClipFromAsset(id, clipsIndex);- } else {- s.addAudioFromAsset(id, t);- }+ const asset = useEditor.getState().assets.find((a) => a.id === id);+ if (asset) placeAssetAt(id, asset.type, t);}}><div@@ -344,8 +397,8 @@ export function Timeline() {><Scissors /> Split</Button>- <Button variant="ghost" size="sm" title="Title (T)" onClick={() => useEditor.getState().addOverlay()}>- <Type /> Title+ <Button variant="ghost" size="sm" title="Text (T)" onClick={() => useEditor.getState().addOverlay()}>+ <Type /> Text</Button><Buttonvariant="ghost"@@ -374,11 +427,12 @@ export function Timeline() {</div><div ref={scrollRef} className="tl-scroll min-h-0 flex-1 overflow-auto">- <div className="min-h-full" style={{ width: contentW + PAD_SIDE * 2 }}>+ <div className="flex min-h-full flex-col" style={{ width: contentW + PAD_SIDE * 2 }}><divref={innerRef}- className="tl-content relative min-h-full pb-2"+ className="tl-content relative flex-1 pb-2"style={{ width: contentW, marginLeft: PAD_SIDE }}+ onPointerDown={deselectIfSelf}><Ruler pps={pps} width={contentW} onScrub={scrub} />diff --git a/site/src/cut/lib/subtitles.ts b/site/src/cut/lib/subtitles.tsindex 75ff4d19..c0f15ded 100644--- a/site/src/cut/lib/subtitles.ts+++ b/site/src/cut/lib/subtitles.ts@@ -1,5 +1,5 @@import { formatTime } from "./time";-import type { SubtitleCue, TextOverlay } from "./types";+import type { FontId, SubtitleCue, TextOverlay } from "./types";/** Caption look shared by the preview layer and the export burn-in โ* TikTok-style bold white on a translucent plate, low center. */@@ -14,6 +14,75 @@ export const SUB_STYLE = {plate: true,} as const;+export type CaptionStyleId = "clean" | "hook" | "punchy";++/** A caption preset: the shared subtitle look plus optional opener emphasis+ * (a bigger, punchier first line). */+export interface CaptionStyle {+ id: CaptionStyleId;+ label: string;+ x: number;+ y: number;+ size: number;+ font: FontId;+ weight: 400 | 700;+ color: string;+ shadow: boolean;+ plate: boolean;+ plateColor?: string;+ plateOpacity?: number;+ /** Multiply the opening cue's size, so the hook lands bigger. */+ openerScale?: number;+}++export const CAPTION_STYLES: Record<CaptionStyleId, CaptionStyle> = {+ clean: {+ id: "clean",+ label: "Clean",+ x: 0.5,+ y: 0.8,+ size: 42,+ font: "sf",+ weight: 700,+ color: "#FFFFFF",+ shadow: true,+ plate: true,+ },+ hook: {+ id: "hook",+ label: "Curiosity hook",+ x: 0.5,+ y: 0.78,+ size: 46,+ font: "rounded",+ weight: 700,+ color: "#FFFFFF",+ shadow: true,+ plate: true,+ plateColor: "#0A84FF",+ plateOpacity: 0.9,+ openerScale: 1.28,+ },+ punchy: {+ id: "punchy",+ label: "Big & punchy",+ x: 0.5,+ y: 0.74,+ size: 50,+ font: "impact",+ weight: 700,+ color: "#FFE94A",+ shadow: true,+ plate: false,+ openerScale: 1.34,+ },+};++/** The active caption preset for a subtitles block. */+export function captionStyle(style: CaptionStyleId | undefined): CaptionStyle {+ return CAPTION_STYLES[style ?? "clean"] ?? CAPTION_STYLES.clean;+}+/** Balance a caption onto up to two lines so it never overflows the frame. */export function wrapCaption(text: string): string {const t = text.trim().replace(/\s+/g, " ");@@ -26,9 +95,57 @@ export function wrapCaption(text: string): string {return best === -1 ? t : t.slice(0, best) + "\n" + t.slice(best + 1);}-/** A cue as a synthetic overlay, so captions ride the title pipeline. */-export function cueOverlay(cue: SubtitleCue): TextOverlay {- return { id: `sub-${cue.id}`, text: wrapCaption(cue.text), start: cue.start, end: cue.end, ...SUB_STYLE };+/**+ * Wrap a caption into as many lines as it takes to keep every line inside the+ * frame width at font `size`. The export burn-in renders each `\n`-separated+ * line centered without wrapping, so this is what guarantees captions stay in+ * bounds โ bigger styles (and the punchy opener) wrap to fewer words per line.+ */+export function wrapCaptionForSize(text: string, size: number): string {+ const words = text.trim().replace(/\s+/g, " ").split(" ").filter(Boolean);+ if (words.length === 0) return "";+ // ~88% of the 1080 design short-side, with a conservative bold-glyph advance+ // (~0.58ยทsize) so real fonts stay comfortably inside the safe area.+ const maxChars = Math.max(8, Math.floor((0.88 * 1080) / (0.58 * size)));+ const lines: string[] = [];+ let line = "";+ for (const w of words) {+ const cand = line ? `${line} ${w}` : w;+ if (line && cand.length > maxChars) {+ lines.push(line);+ line = w;+ } else {+ line = cand;+ }+ }+ if (line) lines.push(line);+ return lines.join("\n");+}++/** A cue as a synthetic overlay, so captions ride the title pipeline. The style+ * preset drives the look; the opening cue can render bigger for a punchy hook. */+export function cueOverlay(+ cue: SubtitleCue,+ style: CaptionStyle = CAPTION_STYLES.clean,+ isOpener = false+): TextOverlay {+ const size = Math.round(style.size * (isOpener && style.openerScale ? style.openerScale : 1));+ return {+ id: `sub-${cue.id}`,+ text: wrapCaptionForSize(cue.text, size),+ start: cue.start,+ end: cue.end,+ x: style.x,+ y: style.y,+ size,+ font: style.font,+ weight: style.weight,+ color: style.color,+ shadow: style.shadow,+ plate: style.plate,+ ...(style.plateColor ? { plateColor: style.plateColor } : {}),+ ...(style.plateOpacity !== undefined ? { plateOpacity: style.plateOpacity } : {}),+ };}/** The cue under a given time, if any. */diff --git a/site/src/cut/lib/textStyle.ts b/site/src/cut/lib/textStyle.tsnew file mode 100644index 00000000..4a043e29--- /dev/null+++ b/site/src/cut/lib/textStyle.ts@@ -0,0 +1,30 @@+import type { TextOverlay } from "./types";++// The style fields a title carries, minus its text/position/id/timing. Remembered+// across clips and projects so repeated titles share one look. Position and size+// stay at sensible defaults; only the visual style is reused.+export type TextStyle = Pick<+ TextOverlay,+ "size" | "font" | "weight" | "color" | "shadow" | "plate" | "plateColor" | "plateOpacity" | "plateRadius"+>;++const KEY = "cut-text-style";++export function readTextStyle(): Partial<TextStyle> {+ if (typeof localStorage === "undefined") return {};+ try {+ const v = JSON.parse(localStorage.getItem(KEY) ?? "{}") as unknown;+ return v && typeof v === "object" ? (v as Partial<TextStyle>) : {};+ } catch {+ return {};+ }+}++export function writeTextStyle(style: Partial<TextStyle>) {+ if (typeof localStorage === "undefined") return;+ try {+ localStorage.setItem(KEY, JSON.stringify(style));+ } catch {+ // Storage full/blocked โ the style just won't persist.+ }+}