Skip to content

Open source CapCut alternative.

TypeScript

feat(site): multi-track titles with customizable plates

David Le1932f3f1e31d
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index 58cee832..77cd5009 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useRef, useState } from "react";
+import { useRef, useState } from "react";
import { Bold } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
@@ -14,7 +14,7 @@ import { Slider } from "@/components/ui/slider";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { useEditor } from "@/cut/lib/store";
-import { PLATE_RADIUS } from "@/cut/lib/textRender";
+import { PLATE_COLOR, PLATE_OPACITY, PLATE_RADIUS } from "@/cut/lib/textRender";
import { formatTime } from "@/cut/lib/time";
import { FONTS, type AudioClip, type TextOverlay, type VideoClip } from "@/cut/lib/types";
import { cn } from "@/lib/utils";
@@ -52,6 +52,70 @@ function readRecentColors(): string[] {
}
}
+/** Preset swatches, recent custom colors, and an eyedropper. `onBegin` marks
+ * an undo checkpoint, `onLive` streams the drag, `onCommit` sets a final pick. */
+function ColorSwatches({
+ value,
+ onBegin,
+ onLive,
+ onCommit,
+}: {
+ value: string;
+ onBegin: () => void;
+ onLive: (c: string) => void;
+ onCommit: (c: string) => void;
+}) {
+ const [recents, setRecents] = useState<string[]>(() =>
+ typeof window === "undefined" ? [] : readRecentColors()
+ );
+
+ const recordRecent = (c: string) => {
+ if (SWATCHES.some((s) => s.toUpperCase() === c.toUpperCase())) return;
+ const next = [c, ...recents.filter((r) => r.toUpperCase() !== c.toUpperCase())].slice(0, 3);
+ setRecents(next);
+ try {
+ localStorage.setItem(RECENT_COLORS_KEY, JSON.stringify(next));
+ } catch {
+ // Storage full/blocked — recents just won't persist.
+ }
+ };
+
+ return (
+ <div className="flex max-w-44 flex-wrap items-center justify-end gap-1.5">
+ {[...SWATCHES, ...recents].map((c) => (
+ <button
+ key={c}
+ title={c}
+ aria-label={`Color ${c}`}
+ className={cn(
+ "size-5 rounded-full border border-black/15 transition-transform hover:scale-110",
+ value.toUpperCase() === c.toUpperCase() &&
+ "ring-2 ring-primary ring-offset-2 ring-offset-card"
+ )}
+ style={{ background: c }}
+ onClick={() => onCommit(c)}
+ />
+ ))}
+ <label
+ title="Custom color"
+ className="color-picker-well relative size-5 cursor-pointer rounded-full border border-black/15 bg-[conic-gradient(from_0deg,#f43f5e,#f59e0b,#84cc16,#06b6d4,#6366f1,#d946ef,#f43f5e)] transition-transform hover:scale-110"
+ >
+ <span className="absolute inset-1 rounded-full bg-card" />
+ <span className="absolute inset-[5px] rounded-full" style={{ background: value }} />
+ <input
+ type="color"
+ aria-label="Pick a custom color"
+ className="absolute inset-0 size-full cursor-pointer opacity-0"
+ value={/^#[0-9a-fA-F]{6}$/.test(value) ? value : "#ffffff"}
+ onFocus={onBegin}
+ onChange={(e) => onLive(e.target.value)}
+ onBlur={() => recordRecent(value)}
+ />
+ </label>
+ </div>
+ );
+}
+
export function Inspector() {
const selection = useEditor((s) => s.selection);
const clip = useEditor((s) =>
@@ -227,19 +291,7 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
const update = useEditor((s) => s.updateOverlay);
const sizeCk = useSliderCheckpoint();
const radiusCk = useSliderCheckpoint();
- const [recents, setRecents] = useState<string[]>([]);
- useEffect(() => setRecents(readRecentColors()), []);
-
- const recordRecent = (c: string) => {
- if (SWATCHES.some((s) => s.toUpperCase() === c.toUpperCase())) return;
- const next = [c, ...recents.filter((r) => r.toUpperCase() !== c.toUpperCase())].slice(0, 3);
- setRecents(next);
- try {
- localStorage.setItem(RECENT_COLORS_KEY, JSON.stringify(next));
- } catch {
- // Storage full/blocked — recents just won't persist.
- }
- };
+ const opacityCk = useSliderCheckpoint();
return (
<>
<PanelTitle>Title</PanelTitle>
@@ -296,45 +348,12 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
<Value className="w-9 text-right text-muted-foreground">{o.size}</Value>
</Row>
<Row label="Color">
- <div className="flex max-w-44 flex-wrap items-center justify-end gap-1.5">
- {[...SWATCHES, ...recents].map((c) => (
- <button
- key={c}
- title={c}
- aria-label={`Color ${c}`}
- className={cn(
- "size-5 rounded-full border border-black/15 transition-transform hover:scale-110",
- o.color.toUpperCase() === c.toUpperCase() &&
- "ring-2 ring-primary ring-offset-2 ring-offset-card"
- )}
- style={{ background: c }}
- onClick={() => update(o.id, { color: c })}
- />
- ))}
- <label
- title="Custom color"
- className="color-picker-well relative size-5 cursor-pointer rounded-full border border-black/15 bg-[conic-gradient(from_0deg,#f43f5e,#f59e0b,#84cc16,#06b6d4,#6366f1,#d946ef,#f43f5e)] transition-transform hover:scale-110"
- >
- <span className="absolute inset-1 rounded-full bg-card" />
- <span className="absolute inset-[5px] rounded-full" style={{ background: o.color }} />
- <input
- type="color"
- aria-label="Pick a custom color"
- className="absolute inset-0 size-full cursor-pointer opacity-0"
- value={/^#[0-9a-fA-F]{6}$/.test(o.color) ? o.color : "#ffffff"}
- onFocus={() => useEditor.getState().pushHistory()}
- onChange={(e) =>
- useEditor.getState().updateOverlayTransient(o.id, { color: e.target.value })
- }
- onBlur={() => {
- const c = useEditor
- .getState()
- .overlays.find((x) => x.id === o.id)?.color;
- if (c) recordRecent(c);
- }}
- />
- </label>
- </div>
+ <ColorSwatches
+ value={o.color}
+ onBegin={() => useEditor.getState().pushHistory()}
+ onLive={(c) => useEditor.getState().updateOverlayTransient(o.id, { color: c })}
+ onCommit={(c) => update(o.id, { color: c })}
+ />
</Row>
<Row label="Shadow">
<Switch checked={o.shadow} onCheckedChange={(v) => update(o.id, { shadow: v })} />
@@ -343,23 +362,50 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
<Switch checked={o.plate} onCheckedChange={(v) => update(o.id, { plate: v })} />
</Row>
{o.plate && (
- <Row label="Radius">
- <Slider
- className="data-horizontal:w-24"
- min={0}
- max={1}
- step={0.01}
- value={o.plateRadius ?? PLATE_RADIUS}
- onValueChange={(v) => {
- radiusCk.begin();
- useEditor.getState().updateOverlayTransient(o.id, { plateRadius: Number(v) });
- }}
- onValueCommitted={radiusCk.end}
- />
- <Value className="w-9 text-right text-muted-foreground">
- {Math.round((o.plateRadius ?? PLATE_RADIUS) * 100)}
- </Value>
- </Row>
+ <>
+ <Row label="Backdrop color">
+ <ColorSwatches
+ value={o.plateColor ?? PLATE_COLOR}
+ onBegin={() => useEditor.getState().pushHistory()}
+ onLive={(c) => useEditor.getState().updateOverlayTransient(o.id, { plateColor: c })}
+ onCommit={(c) => update(o.id, { plateColor: c })}
+ />
+ </Row>
+ <Row label="Opacity">
+ <Slider
+ className="data-horizontal:w-24"
+ min={0}
+ max={1}
+ step={0.01}
+ value={o.plateOpacity ?? PLATE_OPACITY}
+ onValueChange={(v) => {
+ opacityCk.begin();
+ useEditor.getState().updateOverlayTransient(o.id, { plateOpacity: Number(v) });
+ }}
+ onValueCommitted={opacityCk.end}
+ />
+ <Value className="w-9 text-right text-muted-foreground">
+ {Math.round((o.plateOpacity ?? PLATE_OPACITY) * 100)}
+ </Value>
+ </Row>
+ <Row label="Radius">
+ <Slider
+ className="data-horizontal:w-24"
+ min={0}
+ max={1}
+ step={0.01}
+ value={o.plateRadius ?? PLATE_RADIUS}
+ onValueChange={(v) => {
+ radiusCk.begin();
+ useEditor.getState().updateOverlayTransient(o.id, { plateRadius: Number(v) });
+ }}
+ onValueCommitted={radiusCk.end}
+ />
+ <Value className="w-9 text-right text-muted-foreground">
+ {Math.round((o.plateRadius ?? PLATE_RADIUS) * 100)}
+ </Value>
+ </Row>
+ </>
)}
<p className="mt-2.5 text-[11.5px] leading-relaxed text-muted-foreground">
Drag the title in the preview to place it; use the corner handle to resize.
diff --git a/site/src/cut/components/OverlayLayer.tsx b/site/src/cut/components/OverlayLayer.tsx
index 55720dca..16cb1c99 100644
--- a/site/src/cut/components/OverlayLayer.tsx
+++ b/site/src/cut/components/OverlayLayer.tsx
@@ -10,6 +10,7 @@ import {
PLATE_PAD_X,
PLATE_PAD_Y,
PLATE_RADIUS,
+ plateFill,
SHADOW,
} from "@/cut/lib/textRender";
import { FRAME, fontStack, type TextOverlay } from "@/cut/lib/types";
@@ -127,7 +128,7 @@ function OverlayItem({
textShadow: o.shadow
? `0 ${SHADOW.offsetY * scale}px ${SHADOW.blur * scale}px ${SHADOW.color}`
: undefined,
- background: o.plate ? PLATE_FILL : undefined,
+ background: o.plate ? plateFill(o) : undefined,
padding: o.plate ? PLATE_PADDING : undefined,
borderRadius: o.plate ? `${o.plateRadius ?? PLATE_RADIUS}em` : undefined,
opacity: ghost ? 0.35 : 1,
diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsx
index 541a602d..6b58555a 100644
--- a/site/src/cut/components/Timeline.tsx
+++ b/site/src/cut/components/Timeline.tsx
@@ -116,6 +116,32 @@ export function Timeline() {
if (from >= 0) s.moveClip(id, dropIndex(sp, from, dx / s.pxPerSec));
}, []);
+ // Title tracks: overlays carry a `lane`; used lanes compact to contiguous
+ // display rows, so empty tracks disappear on their own.
+ const [textDrag, setTextDrag] = useState<{ id: string; targetRow: number } | null>(null);
+ const overlayLanes = useMemo(() => {
+ const used = [...new Set(overlays.map((o) => o.lane ?? 0))].sort((a, b) => a - b);
+ const rowOf = new Map(used.map((l, i) => [l, i]));
+ return { used, rowOf, count: used.length };
+ }, [overlays]);
+
+ const onTextLaneDrag = useCallback(
+ (id: string, targetRow: number) => setTextDrag({ id, targetRow }),
+ []
+ );
+ const onTextLaneDrop = useCallback((id: string, targetRow: number) => {
+ setTextDrag(null);
+ const s = useEditor.getState();
+ const used = [...new Set(s.overlays.map((o) => o.lane ?? 0))].sort((a, b) => a - b);
+ const cur = s.overlays.find((o) => o.id === id);
+ if (!cur) return;
+ const curRow = used.indexOf(cur.lane ?? 0);
+ if (targetRow === curRow) return;
+ // A row past the end becomes a brand-new track above the current max.
+ const lane = targetRow < used.length ? used[targetRow] : (used[used.length - 1] ?? -1) + 1;
+ s.moveOverlayToLane(id, lane);
+ }, []);
+
const timeAt = (clientX: number) => {
const rect = innerRef.current!.getBoundingClientRect();
return (clientX - rect.left) / pps;
@@ -404,15 +430,31 @@ export function Timeline() {
)}
{overlays.length > 0 && (
- <div className="relative mt-1.5" style={{ height: TEXT_H }} onPointerDown={deselectIfSelf}>
- {overlays.map((o) => (
- <TextBar
- key={o.id}
- overlay={o}
- pps={pps}
- selected={selection?.kind === "text" && selection.id === o.id}
- />
- ))}
+ <div
+ className="relative mt-1.5"
+ style={{
+ height:
+ Math.max(overlayLanes.count, (textDrag?.targetRow ?? -1) + 1) * TEXT_H,
+ }}
+ onPointerDown={deselectIfSelf}
+ >
+ {overlays.map((o) => {
+ const baseRow = overlayLanes.rowOf.get(o.lane ?? 0) ?? 0;
+ const row = textDrag?.id === o.id ? textDrag.targetRow : baseRow;
+ return (
+ <TextBar
+ key={o.id}
+ overlay={o}
+ pps={pps}
+ top={row * TEXT_H}
+ baseRow={baseRow}
+ laneCount={overlayLanes.count}
+ selected={selection?.kind === "text" && selection.id === o.id}
+ onLaneDrag={onTextLaneDrag}
+ onLaneDrop={onTextLaneDrop}
+ />
+ );
+ })}
</div>
)}
@@ -938,11 +980,21 @@ function AudioView({
function TextBar({
overlay: o,
pps,
+ top,
+ baseRow,
+ laneCount,
selected,
+ onLaneDrag,
+ onLaneDrop,
}: {
overlay: TextOverlay;
pps: number;
+ top: number;
+ baseRow: number;
+ laneCount: number;
selected: boolean;
+ onLaneDrag: (id: string, targetRow: number) => void;
+ onLaneDrop: (id: string, targetRow: number) => void;
}) {
const w = Math.max(8, (o.end - o.start) * pps);
@@ -952,11 +1004,19 @@ function TextBar({
s.pushHistory();
const start0 = o.start;
const len = o.end - o.start;
+ let targetRow = baseRow;
startDrag(e, {
- onMove: (dx) => {
+ onMove: (dx, dy) => {
const start = Math.max(0, start0 + dx / pps);
s.updateOverlayTransient(o.id, { start, end: start + len });
+ // Vertical drag retracks the title; one row past the end opens a new one.
+ const next = Math.min(laneCount, Math.max(0, baseRow + Math.round(dy / TEXT_H)));
+ if (next !== targetRow) {
+ targetRow = next;
+ onLaneDrag(o.id, targetRow);
+ }
},
+ onUp: () => onLaneDrop(o.id, targetRow),
});
};
@@ -989,10 +1049,10 @@ function TextBar({
return (
<div
className={cn(
- "tl-text-bar group absolute top-0.5 flex cursor-grab items-center overflow-hidden rounded-md bg-gradient-to-b from-purple-500 to-purple-600 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.1)]",
+ "tl-text-bar group absolute flex cursor-grab items-center overflow-hidden rounded-md bg-gradient-to-b from-purple-500 to-purple-600 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.1)]",
selected && SELECTED_SHADOW
)}
- style={{ left: o.start * pps, width: w, height: TEXT_H - 6 }}
+ style={{ left: o.start * pps, top: top + 2, width: w, height: TEXT_H - 6 }}
onPointerDown={onBody}
>
<span className="pointer-events-none truncate px-2 text-[10.5px] font-medium text-white">
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index c4435616..17ff1a9b 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -83,6 +83,9 @@ interface EditorState {
addClipFromAsset: (assetId: string, index?: number) => void;
addAudioFromAsset: (assetId: string, start?: number) => void;
addOverlay: () => void;
+ /** Move a title to a title track (row); lanes are renumbered to stay
+ * contiguous, so empty tracks collapse and a past-the-end lane adds one. */
+ moveOverlayToLane: (id: string, lane: number) => void;
updateClip: (id: string, patch: Partial<VideoClip>) => void;
updateAudio: (id: string, patch: Partial<AudioClip>) => void;
updateOverlay: (id: string, patch: Partial<TextOverlay>) => void;
@@ -369,6 +372,7 @@ export const useEditor = create<EditorState>((set, get) => {
color: "#FFFFFF",
shadow: true,
plate: false,
+ lane: 0,
};
set((s) => ({
overlays: [...s.overlays, overlay],
@@ -376,6 +380,20 @@ export const useEditor = create<EditorState>((set, get) => {
}));
},
+ moveOverlayToLane: (id, lane) => {
+ const overlays = get().overlays;
+ if (!overlays.some((o) => o.id === id)) return;
+ // No checkpoint here: the drag gesture that calls this already pushed
+ // one at pointer-down, so the whole move is a single undo step.
+ // Drop the title on the target row, then renumber so lanes stay
+ // contiguous — empty tracks vanish, and a past-the-end target becomes a
+ // fresh top-numbered track.
+ const moved = overlays.map((o) => (o.id === id ? { ...o, lane } : o));
+ const used = [...new Set(moved.map((o) => o.lane ?? 0))].sort((a, b) => a - b);
+ const remap = new Map(used.map((l, i) => [l, i]));
+ set({ overlays: moved.map((o) => ({ ...o, lane: remap.get(o.lane ?? 0) ?? 0 })) });
+ },
+
// The non-transient updaters are just a checkpoint plus the live update.
updateClip: (id, patch) => {
push();
diff --git a/site/src/cut/lib/textRender.ts b/site/src/cut/lib/textRender.ts
index 52521d2b..180a7853 100644
--- a/site/src/cut/lib/textRender.ts
+++ b/site/src/cut/lib/textRender.ts
@@ -6,9 +6,21 @@ export const LINE_HEIGHT = 1.25;
export const PLATE_PAD_X = 0.55; // em
export const PLATE_PAD_Y = 0.3; // em
export const PLATE_RADIUS = 0.32; // em
+export const PLATE_COLOR = "#000000";
+export const PLATE_OPACITY = 0.55;
export const PLATE_FILL = "rgba(0, 0, 0, 0.55)";
export const SHADOW = { color: "rgba(0, 0, 0, 0.65)", blur: 14, offsetY: 2 };
+/** A title's plate fill as an rgba() string, defaulting to translucent black
+ * when color/opacity are unset. Shared by the preview and the export burn-in. */
+export function plateFill(o: { plateColor?: string; plateOpacity?: number }): string {
+ const a = o.plateOpacity ?? PLATE_OPACITY;
+ const m = /^#?([0-9a-fA-F]{6})$/.exec((o.plateColor ?? PLATE_COLOR).trim());
+ if (!m) return `rgba(0, 0, 0, ${a})`;
+ const n = parseInt(m[1], 16);
+ return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${a})`;
+}
+
/**
* Render an overlay to a transparent full-frame PNG at the export resolution.
* Uses the same font stacks and metrics as the DOM preview so the export
@@ -46,7 +58,7 @@ export async function renderOverlayPng(
const r = (overlay.plateRadius ?? PLATE_RADIUS) * fpx;
const w = maxW + padX * 2;
const h = totalH + padY * 2;
- ctx.fillStyle = PLATE_FILL;
+ ctx.fillStyle = plateFill(overlay);
ctx.beginPath();
ctx.roundRect(cx - w / 2, cy - h / 2, w, h, r);
ctx.fill();
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index fecfe0fa..af630399 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -95,8 +95,13 @@ export interface TextOverlay {
weight: 400 | 700;
color: string;
shadow: boolean;
- plate: boolean; // translucent rounded plate behind the text
+ plate: boolean; // rounded plate behind the text
plateRadius?: number; // plate corner radius in em (default PLATE_RADIUS)
+ plateColor?: string; // plate fill color (default black)
+ plateOpacity?: number; // plate fill opacity 0..1 (default PLATE_OPACITY)
+ /** Which title track (row) this sits on, 0-based. Tracks are kept
+ * contiguous: empty ones collapse and dragging past the last adds one. */
+ lane?: number;
}
/** One subtitle caption, timed against the timeline (not the source files). */