Open source CapCut alternative.
TypeScript
feat(site): redesigned Color panel
David Lea15d59e1af13
diff --git a/site/src/cut/components/ColorPanel.tsx b/site/src/cut/components/ColorPanel.tsxnew file mode 100644index 00000000..4e5886f8--- /dev/null+++ b/site/src/cut/components/ColorPanel.tsx@@ -0,0 +1,704 @@+"use client";++import { useEffect, useMemo, useRef, useState } from "react";+import { ChevronLeft, RotateCcw, SlidersHorizontal, Wand2 } from "lucide-react";+import {+ applyLutToImageData,+ autoGradeFromImageData,+ buildGradeLut,+ GRADE_BASIC_FIELDS,+ GRADE_HUE_MAX,+ GRADE_MAX,+ GRADE_PRESET_CATEGORIES,+ gradeCssApprox,+ gradePresetsInCategory,+ gradeToolDirty,+ HSL_BANDS,+ normalizeGrade,+ type ColorGrade,+ type GradeLut,+ type GradePreset,+ type GradePresetCategory,+ type HslBand,+ type HslTuple,+ type WheelTuple,+} from "@donkeycut/effects-kit";+import { getPreviewCanvas, sampleClipFrameData } from "@/cut/lib/previewCanvas";+import { useEditor } from "@/cut/lib/store";+import type { VideoClip } from "@/cut/lib/types";+import { ResetButton, Row, useSliderCheckpoint } from "@/cut/components/panelBits";+import { ColorWheel } from "@/cut/components/ColorWheel";+import { CurveEditor } from "@/cut/components/CurveEditor";+import { ValueSlider } from "@/cut/components/ValueSlider";+import { parseNumberInput } from "@/cut/components/ScrubValue";+import { useClipSourceFrame } from "@/cut/components/usePlayheadFrame";+import { cn } from "@/lib/utils";+import { ScrollArea } from "@/components/ui/scroll-area";+import { Switch } from "@/components/ui/switch";++/**+ * The clip panel's Color subview, two levels deep. The first level is the+ * preset grid — category chips over click-to-apply tiles, with the applied+ * preset's intensity and skin-tone protection on the panel floor. The second+ * level, behind the header's sliders button, is Adjust: Basic sliders,+ * Curves, Wheels and per-hue HSL as segmented tools, every manual adjustment+ * layering over whatever preset is applied. Both levels write the one `grade`+ * field, drafts stream through the transient updater under one history+ * checkpoint per gesture, and preview, filmstrip and exports render the same+ * numbers.+ */+export function ColorPanel({ clip, onBack }: { clip: VideoClip; onBack: () => void }) {+ const [view, setView] = useState<"presets" | "adjust">("presets");+ if (view === "adjust") {+ return <AdjustView clip={clip} onBack={() => setView("presets")} />;+ }+ return <PresetView clip={clip} onBack={onBack} onAdjust={() => setView("adjust")} />;+}++/** The tools of the Adjust view; `dirty` feeds each tab's marker dot. */+const TOOLS = [+ { id: "basic", label: "Basic" },+ { id: "curves", label: "Curves" },+ { id: "wheels", label: "Wheels" },+ { id: "hsl", label: "HSL" },+] as const;++type Tool = (typeof TOOLS)[number]["id"];++/** Shared write path: normalize and store a whole grade, transiently while a+ * gesture is live, committed at its end. */+function useGradeWriter(clip: VideoClip) {+ const ck = useSliderCheckpoint();+ const write = (g: ColorGrade | undefined) => {+ // The checkpoint taken on the gesture's first change is the whole undo+ // step, so every write — drag frames and the commit alike — goes through+ // the transient updater. updateClip would push a second checkpoint and+ // make ⌘Z a two-press affair.+ ck.begin();+ useEditor.getState().updateClipTransient(clip.id, { grade: normalizeGrade(g) });+ };+ const commit = (g: ColorGrade | undefined) => {+ write(g);+ ck.end();+ };+ return { draft: write, commit };+}++/* ------------------------------------------------------------------ */+/* Level 1: presets */+/* ------------------------------------------------------------------ */++function PresetView({+ clip,+ onBack,+ onAdjust,+}: {+ clip: VideoClip;+ onBack: () => void;+ onAdjust: () => void;+}) {+ const [category, setCategory] = useState<GradePresetCategory | "all">("all");+ // The clip's own frame, ungraded: a swatch shows what its preset does to the+ // footage, never what the clip's current grade already did.+ const frame = useClipSourceFrame(clip.id);+ const { draft, commit } = useGradeWriter(clip);+ const active = clip.grade?.preset;+ const manualDirty = TOOLS.some((t) => gradeToolDirty(clip.grade, t.id));+ const presets =+ category === "all"+ ? GRADE_PRESET_CATEGORIES.flatMap((c) => gradePresetsInCategory(c.id))+ : gradePresetsInCategory(category);++ const pick = (id: string) => {+ commit({+ ...clip.grade,+ preset:+ active?.id === id+ ? undefined+ : { id, amount: active?.amount ?? 1, skin: active?.skin },+ });+ };++ const chip = (activeChip: boolean) =>+ cn(+ "shrink-0 rounded-full px-2 py-0.5 text-[10px] font-medium transition-colors",+ activeChip ? "bg-primary/15 text-primary" : "bg-muted text-muted-foreground hover:text-foreground"+ );++ return (+ <div className="flex min-h-0 flex-1 flex-col">+ <div className="shrink-0 bg-card pb-2">+ <div className="flex h-10 shrink-0 items-center gap-1 px-2.5 text-sm font-semibold tracking-tight">+ <button+ type="button"+ aria-label="Back"+ className="clip-color-back grid size-6 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground"+ onClick={onBack}+ >+ <ChevronLeft className="size-4" />+ </button>+ Color+ <button+ type="button"+ title="Adjust"+ aria-label="Adjust"+ className="clip-color-adjust relative ml-auto grid size-6 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground"+ onClick={onAdjust}+ >+ <SlidersHorizontal className="size-4" />+ {manualDirty && (+ <span className="absolute top-0.5 right-0.5 size-1.5 rounded-full bg-violet-500" aria-label="Adjusted" />+ )}+ </button>+ </div>+ <div className="flex min-w-0 flex-wrap gap-1 px-3.5">+ <button type="button" className={chip(category === "all")} onClick={() => setCategory("all")}>+ All+ </button>+ {GRADE_PRESET_CATEGORIES.map((c) => (+ <button+ key={c.id}+ type="button"+ className={chip(category === c.id)}+ onClick={() => setCategory(c.id)}+ >+ {c.label}+ </button>+ ))}+ </div>+ </div>+ <ScrollArea+ key={category}+ className="min-h-0 flex-1"+ viewportClassName="overscroll-contain"+ contentClassName="grid grid-cols-2 gap-2 px-3.5 pt-1 pb-2"+ >+ {presets.map((p) => (+ <PresetTile key={p.id} preset={p} frame={frame} selected={active?.id === p.id} onPick={pick} />+ ))}+ </ScrollArea>+ <div className="shrink-0 border-t border-border bg-card px-3.5 py-1">+ <Row label="Intensity">+ <ValueSlider+ label="Intensity"+ sliderClassName="clip-grade-preset-amount data-horizontal:w-24"+ valueClassName="w-9 text-muted-foreground"+ value={Math.round((active?.amount ?? 1) * 100)}+ min={0}+ max={100}+ step={1}+ disabled={!active}+ format={(v) => `${Math.round(v)}%`}+ parse={parseNumberInput}+ onDraft={(v) =>+ active && draft({ ...clip.grade, preset: { ...active, amount: v / 100 } })+ }+ onCommit={(v) =>+ active && commit({ ...clip.grade, preset: { ...active, amount: v / 100 } })+ }+ />+ </Row>+ <Row label="Protect skin tones">+ <Switch+ size="sm"+ className="clip-grade-protect-skin"+ checked={!!active?.skin}+ disabled={!active}+ onCheckedChange={(on: boolean) =>+ active && commit({ ...clip.grade, preset: { ...active, skin: on || undefined } })+ }+ />+ </Row>+ </div>+ </div>+ );+}++/** Rendered preset thumbnails for the tiles whose recipes go beyond CSS+ * filters: the playhead frame pushed through the preset's real LUT at a thumb+ * size, cached per (frame, preset). The LUTs themselves are built once per+ * preset and kept for the session. */+const presetLutCache = new Map<string, GradeLut | null>();+const presetThumbCache = new Map<string, string>();++function presetLut(p: GradePreset): GradeLut | null {+ let lut = presetLutCache.get(p.id);+ if (lut === undefined) {+ lut = buildGradeLut(p.grade);+ presetLutCache.set(p.id, lut);+ }+ return lut;+}++/** A preset's recipe reaches past what a CSS filter can draw. */+const presetNeedsLutThumb = (p: GradePreset) => !!(p.grade.curves || p.grade.wheels || p.grade.hsl);++function PresetTile({+ preset,+ frame,+ selected,+ onPick,+}: {+ preset: GradePreset;+ frame: string | null;+ selected: boolean;+ onPick: (id: string) => void;+}) {+ const needsLut = presetNeedsLutThumb(preset);+ const approx = useMemo(() => gradeCssApprox(preset.grade), [preset]);+ const key = needsLut && frame ? `${preset.id}|${frame}` : null;+ // The render reads the module cache; the effect fills it asynchronously+ // (decode → LUT → data URL) and bumps to re-read.+ const [, bump] = useState(0);+ useEffect(() => {+ if (!key || !frame || presetThumbCache.has(key)) return;+ let gone = false;+ const img = new Image();+ img.onload = () => {+ if (gone) return;+ const lut = presetLut(preset);+ const w = 128;+ const h = Math.max(1, Math.round((img.naturalHeight / (img.naturalWidth || 1)) * w));+ const c = document.createElement("canvas");+ c.width = w;+ c.height = h;+ const ctx = c.getContext("2d", { willReadFrequently: true });+ if (!ctx) return;+ ctx.drawImage(img, 0, 0, w, h);+ if (lut) {+ const px = ctx.getImageData(0, 0, w, h);+ applyLutToImageData(px.data, lut);+ ctx.putImageData(px, 0, 0);+ }+ const url = c.toDataURL("image/jpeg", 0.72);+ presetThumbCache.set(key, url);+ // The frame refreshes as the playhead moves; drop the thumbs of frames+ // that have gone by, never the ones the mounted tiles are showing.+ if (presetThumbCache.size > 128)+ for (const k of presetThumbCache.keys())+ if (!k.endsWith(`|${frame}`)) presetThumbCache.delete(k);+ bump((n) => n + 1);+ };+ img.src = frame;+ return () => {+ gone = true;+ };+ }, [key, frame, preset]);++ const src = needsLut ? (key ? presetThumbCache.get(key) ?? null : null) : frame;+ return (+ <button+ type="button"+ aria-pressed={selected}+ className={cn(+ `clip-grade-preset-${preset.id} group flex flex-col items-center gap-1 rounded-lg p-1 text-[11px] font-medium outline-none transition-colors`,+ selected ? "text-foreground" : "text-muted-foreground hover:text-foreground"+ )}+ onClick={() => onPick(preset.id)}+ >+ <span+ className={cn(+ "relative block aspect-video w-full overflow-hidden rounded-md bg-muted",+ selected && "ring-2 ring-[#0a84ff] ring-offset-1 ring-offset-card"+ )}+ >+ {src ? (+ <>+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img+ src={src}+ alt=""+ draggable={false}+ className="absolute inset-0 h-full w-full object-cover"+ style={needsLut ? undefined : { filter: approx.filter || undefined }}+ />+ {!needsLut && approx.tint && (+ <span+ className="absolute inset-0"+ style={{ backgroundColor: approx.tint, mixBlendMode: "multiply" }}+ />+ )}+ </>+ ) : (+ <StandInScene filter={approx.filter} tint={approx.tint} />+ )}+ </span>+ {preset.label}+ </button>+ );+}++/** A drawn stand-in for projects with no picture yet, taking the preset's CSS+ * approximation so the tiles still read differently from each other. */+function StandInScene({ filter, tint }: { filter: string; tint: string | null }) {+ return (+ <span className="absolute inset-0" style={{ filter: filter || undefined }}>+ <span className="absolute inset-0 bg-[#7fa8c9]" />+ <span className="absolute inset-x-0 bottom-0 h-[38%] bg-[#b08d5f]" />+ <span className="absolute bottom-[20%] left-1/2 size-[26%] -translate-x-1/2 rounded-full bg-[#e2b189]" />+ {tint && <span className="absolute inset-0" style={{ backgroundColor: tint, mixBlendMode: "multiply" }} />}+ </span>+ );+}++/* ------------------------------------------------------------------ */+/* Level 2: adjust */+/* ------------------------------------------------------------------ */++function AdjustView({ clip, onBack }: { clip: VideoClip; onBack: () => void }) {+ const [tool, setTool] = useState<Tool>("basic");+ const { draft, commit } = useGradeWriter(clip);+ const grade = clip.grade;+ // Manual adjustments only — reset-all keeps the preset layer.+ const manualDirty = TOOLS.some((t) => gradeToolDirty(grade, t.id));+ // Fit a starting grade from the clip's raw decoder frame (never the graded+ // preview, which would fold the current grade back into the fit); the+ // sliders show the result and stay fully adjustable after.+ const autoGrade = () => {+ const data = sampleClipFrameData(clip.id);+ if (data) commit({ ...autoGradeFromImageData(data), preset: grade?.preset });+ };+ const resetAll = () => commit(grade?.preset ? { preset: grade.preset } : undefined);+ return (+ <div className="flex min-h-0 flex-1 flex-col">+ <div className="shrink-0 bg-card pb-2">+ <div className="flex h-10 shrink-0 items-center gap-1 px-2.5 text-sm font-semibold tracking-tight">+ <button+ type="button"+ aria-label="Back"+ className="clip-color-back grid size-6 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground"+ onClick={onBack}+ >+ <ChevronLeft className="size-4" />+ </button>+ Adjust+ <button+ type="button"+ className="clip-grade-auto ml-auto flex items-center gap-1 rounded-md border border-input px-2 py-0.5 text-[11.5px] font-medium text-muted-foreground transition-colors hover:text-foreground"+ onClick={autoGrade}+ >+ <Wand2 className="size-3" />+ Auto+ </button>+ <button+ type="button"+ title="Reset all adjustments"+ aria-label="Reset all adjustments"+ className={cn(+ "clip-grade-reset grid size-6 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground",+ !manualDirty && "invisible"+ )}+ onClick={resetAll}+ >+ <RotateCcw className="size-3.5" />+ </button>+ </div>+ <div className="mx-3.5 flex shrink-0 rounded-lg bg-muted p-0.5 text-[11.5px] font-medium">+ {TOOLS.map((t) => (+ <button+ key={t.id}+ type="button"+ className={cn(+ `clip-grade-tab-${t.id} relative flex-1 rounded-md px-1.5 py-1 transition-colors`,+ tool === t.id ? "bg-neutral-900 text-white" : "text-muted-foreground hover:text-foreground"+ )}+ onClick={() => setTool(t.id)}+ >+ {t.label}+ {gradeToolDirty(grade, t.id) && (+ <span+ className={cn(+ "absolute top-1 right-1.5 size-1 rounded-full",+ tool === t.id ? "bg-white/80" : "bg-violet-500"+ )}+ aria-label={`${t.label} adjusted`}+ />+ )}+ </button>+ ))}+ </div>+ </div>+ <ScrollArea+ key={tool}+ className="min-h-0 flex-1"+ viewportClassName="overscroll-contain"+ contentClassName="flex flex-col gap-1 px-3.5 pt-1 pb-4"+ >+ <Histogram />+ {tool === "basic" && <BasicTool grade={grade} draft={draft} commit={commit} />}+ {tool === "curves" && (+ <CurveEditor+ curves={grade?.curves}+ onDraft={(curves) => draft({ ...grade, curves })}+ onCommit={(curves) => commit({ ...grade, curves })}+ />+ )}+ {tool === "wheels" && <WheelsTool grade={grade} draft={draft} commit={commit} />}+ {tool === "hsl" && <HslTool grade={grade} draft={draft} commit={commit} />}+ </ScrollArea>+ </div>+ );+}++type GradeWrite = {+ grade: ColorGrade | undefined;+ draft: (g: ColorGrade) => void;+ commit: (g: ColorGrade | undefined) => void;+};++const formatSigned = (v: number) => (v > 0 ? `+${Math.round(v)}` : `${Math.round(v)}`);++function BasicTool({ grade, draft, commit }: GradeWrite) {+ // Legacy fields keep rendering and stay editable on clips that carry them;+ // fresh grades never surface the rows.+ const legacy: { key: "brightness" | "hue"; label: string; max: number }[] = [];+ if (grade?.brightness) legacy.push({ key: "brightness", label: "Brightness", max: GRADE_MAX });+ if (grade?.hue) legacy.push({ key: "hue", label: "Hue", max: GRADE_HUE_MAX });+ const groups = [+ { id: "light" as const, label: "Light" },+ { id: "color" as const, label: "Color" },+ ];+ const sliderRow = (key: keyof ColorGrade & string, label: string, max: number) => {+ const value = (grade?.[key] as number | undefined) ?? 0;+ return (+ <Row key={key} label={label}>+ <ValueSlider+ label={label}+ sliderClassName={`clip-grade-${key} data-horizontal:w-24`}+ valueClassName="w-9 text-muted-foreground"+ value={value}+ min={-max}+ max={max}+ step={1}+ snap={[0]}+ format={(v) => (key === "hue" ? `${Math.round(v)}°` : formatSigned(v))}+ parse={parseNumberInput}+ onDraft={(v) => draft({ ...grade, [key]: v })}+ onCommit={(v) => commit({ ...grade, [key]: v })}+ />+ <ResetButton+ title={`Reset ${label.toLowerCase()}`}+ show={value !== 0}+ onClick={() => commit({ ...grade, [key]: 0 })}+ />+ </Row>+ );+ };+ return (+ <>+ {groups.map((g) => (+ <div key={g.id} className="flex flex-col gap-1">+ <span className="mt-1 text-xs font-semibold text-muted-foreground">{g.label}</span>+ {GRADE_BASIC_FIELDS.filter((f) => f.group === g.id).map((f) =>+ sliderRow(f.key, f.label, GRADE_MAX)+ )}+ </div>+ ))}+ {legacy.length > 0 && (+ <div className="flex flex-col gap-1">+ <span className="mt-1 text-xs font-semibold text-muted-foreground">Legacy</span>+ {legacy.map((f) => sliderRow(f.key, f.label, f.max))}+ </div>+ )}+ </>+ );+}++const WHEEL_ZONES = [+ { id: "s" as const, label: "Shadows" },+ { id: "m" as const, label: "Midtones" },+ { id: "h" as const, label: "Highlights" },+];++function WheelsTool({ grade, draft, commit }: GradeWrite) {+ const wheels = grade?.wheels;+ const tuple = (z: "s" | "m" | "h"): WheelTuple => wheels?.[z] ?? [0, 0, 0];+ const write = (+ to: (g: ColorGrade) => void,+ z: "s" | "m" | "h",+ next: WheelTuple+ ) => to({ ...grade, wheels: { ...wheels, [z]: next } });+ return (+ <>+ <div className="mt-1 grid grid-cols-3 gap-2">+ {WHEEL_ZONES.map((z) => {+ const [dx, dy, lum] = tuple(z.id);+ return (+ <div key={z.id} className={`clip-grade-wheel-${z.id}`}>+ <ColorWheel+ label={z.label}+ value={[dx, dy]}+ onDraft={([nx, ny]) => write(draft, z.id, [nx, ny, lum])}+ onCommit={([nx, ny]) => write(commit, z.id, [nx, ny, lum])}+ />+ </div>+ );+ })}+ </div>+ <span className="mt-2 text-xs font-semibold text-muted-foreground">Luminance</span>+ {WHEEL_ZONES.map((z) => {+ const [dx, dy, lum] = tuple(z.id);+ return (+ <Row key={z.id} label={z.label}>+ <ValueSlider+ label={`${z.label} luminance`}+ sliderClassName={`clip-grade-wheel-${z.id}-luma data-horizontal:w-24`}+ valueClassName="w-9 text-muted-foreground"+ value={lum}+ min={-GRADE_MAX}+ max={GRADE_MAX}+ step={1}+ snap={[0]}+ format={formatSigned}+ parse={parseNumberInput}+ onDraft={(v) => write(draft, z.id, [dx, dy, v])}+ onCommit={(v) => write(commit, z.id, [dx, dy, v])}+ />+ <ResetButton+ title={`Reset ${z.label.toLowerCase()} wheel`}+ show={dx !== 0 || dy !== 0 || lum !== 0}+ onClick={() => write(commit, z.id, [0, 0, 0])}+ />+ </Row>+ );+ })}+ </>+ );+}++const HSL_AXES = [+ { index: 0, label: "Hue" },+ { index: 1, label: "Saturation" },+ { index: 2, label: "Luminance" },+] as const;++function HslTool({ grade, draft, commit }: GradeWrite) {+ const [band, setBand] = useState<HslBand>("orange");+ const active = HSL_BANDS.find((b) => b.id === band)!;+ const tuple: HslTuple = grade?.hsl?.[band] ?? [0, 0, 0];+ const write = (to: (g: ColorGrade) => void, next: HslTuple) =>+ to({ ...grade, hsl: { ...grade?.hsl, [band]: next } });+ return (+ <>+ <div className="mt-1 flex flex-wrap gap-1.5">+ {HSL_BANDS.map((b) => (+ <button+ key={b.id}+ type="button"+ title={b.label}+ aria-label={b.label}+ aria-pressed={band === b.id}+ className={cn(+ `clip-grade-hsl-${b.id} relative size-7 rounded-full border-2 transition-transform`,+ band === b.id ? "border-[#0a84ff]" : "border-transparent hover:scale-105"+ )}+ style={{ backgroundColor: b.swatch }}+ onClick={() => setBand(b.id)}+ >+ {!!grade?.hsl?.[b.id] && (+ <span className="absolute -top-0.5 -right-0.5 size-1.5 rounded-full bg-violet-500" />+ )}+ </button>+ ))}+ </div>+ <div className="mt-1 text-[12px] text-muted-foreground">+ Adjusting <span className="font-semibold text-foreground">{active.label}</span>+ </div>+ {HSL_AXES.map((axis) => (+ <Row key={axis.label} label={axis.label}>+ <ValueSlider+ label={`${active.label} ${axis.label.toLowerCase()}`}+ sliderClassName={`clip-grade-hsl-${axis.label.toLowerCase()} data-horizontal:w-24`}+ valueClassName="w-9 text-muted-foreground"+ value={tuple[axis.index]}+ min={-GRADE_MAX}+ max={GRADE_MAX}+ step={1}+ snap={[0]}+ format={formatSigned}+ parse={parseNumberInput}+ onDraft={(v) => {+ const next = [...tuple] as HslTuple;+ next[axis.index] = v;+ write(draft, next);+ }}+ onCommit={(v) => {+ const next = [...tuple] as HslTuple;+ next[axis.index] = v;+ write(commit, next);+ }}+ />+ <ResetButton+ title={`Reset ${axis.label.toLowerCase()}`}+ show={tuple[axis.index] !== 0}+ onClick={() => {+ const next = [...tuple] as HslTuple;+ next[axis.index] = 0;+ write(commit, next);+ }}+ />+ </Row>+ ))}+ </>+ );+}++/** Live RGB histogram of the composited preview frame: the three channel+ * curves screen over each other so overlaps read light. Samples a small+ * downscale of the preview canvas on a short interval while open. */+function Histogram() {+ const ref = useRef<HTMLCanvasElement>(null);+ useEffect(() => {+ const cv = ref.current;+ const ctx = cv?.getContext("2d");+ if (!cv || !ctx) return;+ const sample = document.createElement("canvas");+ sample.width = 96;+ sample.height = 54;+ const sctx = sample.getContext("2d", { willReadFrequently: true });+ if (!sctx) return;+ const BINS = 64;+ const COLORS = ["#ff453a", "#32d74b", "#0a84ff"];+ const draw = () => {+ const src = getPreviewCanvas();+ if (!src) return;+ let data: Uint8ClampedArray;+ try {+ sctx.drawImage(src, 0, 0, sample.width, sample.height);+ data = sctx.getImageData(0, 0, sample.width, sample.height).data;+ } catch {+ return; // unreadable canvas — keep whatever is drawn+ }+ const bins = [new Float64Array(BINS), new Float64Array(BINS), new Float64Array(BINS)];+ for (let i = 0; i < data.length; i += 4) {+ bins[0][data[i] >> 2]++;+ bins[1][data[i + 1] >> 2]++;+ bins[2][data[i + 2] >> 2]++;+ }+ const W = cv.width;+ const H = cv.height;+ ctx.globalCompositeOperation = "source-over";+ ctx.fillStyle = "#101014";+ ctx.fillRect(0, 0, W, H);+ const peak = Math.max(1, ...bins.map((b) => Math.max(...b)));+ ctx.globalCompositeOperation = "screen";+ bins.forEach((b, ci) => {+ ctx.fillStyle = COLORS[ci];+ ctx.beginPath();+ ctx.moveTo(0, H);+ for (let i = 0; i < BINS; i++) {+ // sqrt tames the peaks so midtone shape stays visible.+ ctx.lineTo((i / (BINS - 1)) * W, H - Math.sqrt(b[i] / peak) * (H - 3));+ }+ ctx.lineTo(W, H);+ ctx.closePath();+ ctx.fill();+ });+ ctx.globalCompositeOperation = "source-over";+ };+ draw();+ const id = setInterval(draw, 150);+ return () => clearInterval(id);+ }, []);+ return <canvas ref={ref} width={256} height={80} className="mb-1.5 h-20 w-full rounded-md" />;+}diff --git a/site/src/cut/components/ColorWheel.tsx b/site/src/cut/components/ColorWheel.tsxnew file mode 100644index 00000000..115b3b27--- /dev/null+++ b/site/src/cut/components/ColorWheel.tsx@@ -0,0 +1,103 @@+"use client";++import { useRef } from "react";+import { GRADE_MAX } from "@donkeycut/effects-kit";++/**+ * One color wheel of the Wheels tool: a hue disc with a draggable puck whose+ * position is the wheel's chroma offset ([dx, dy], each -50..50). The disc's+ * hue layout matches the renderer's angle-to-hue mapping, so the puck sits on+ * the color it pushes toward. Double-click recenters.+ */+export function ColorWheel({+ label,+ value,+ onDraft,+ onCommit,+ className,+}: {+ label: string;+ /** [dx, dy] of the wheel's tuple; luminance rides its own slider row. */+ value: [number, number];+ onDraft: (v: [number, number]) => void;+ onCommit: (v: [number, number]) => void;+ className?: string;+}) {+ const ref = useRef<HTMLDivElement>(null);+ const dragging = useRef(false);+ const last = useRef<[number, number]>(value);++ const fromEvent = (e: React.PointerEvent): [number, number] => {+ const r = ref.current!.getBoundingClientRect();+ let dx = ((e.clientX - r.left) / r.width - 0.5) * 2 * GRADE_MAX;+ let dy = ((e.clientY - r.top) / r.height - 0.5) * 2 * GRADE_MAX;+ const m = Math.hypot(dx, dy);+ if (m > GRADE_MAX) {+ dx *= GRADE_MAX / m;+ dy *= GRADE_MAX / m;+ }+ return [Math.round(dx), Math.round(dy)];+ };++ return (+ <div className={className}>+ <p className="mb-1 text-center text-[11px] text-muted-foreground">{label}</p>+ <div+ ref={ref}+ role="slider"+ aria-label={`${label} color`}+ aria-valuemin={0}+ aria-valuemax={GRADE_MAX}+ aria-valuenow={Math.round(Math.hypot(value[0], value[1]))}+ aria-valuetext={`${value[0]}, ${value[1]}`}+ className="relative mx-auto aspect-square w-full max-w-[84px] cursor-pointer touch-none rounded-full"+ style={{+ background:+ // The angle-to-hue map the renderer uses: 0° (right) red, 90°+ // (down) spring green — a conic sweep from the +x axis.+ "conic-gradient(from 90deg, hsl(0 80% 60%), hsl(60 80% 60%), hsl(120 80% 60%), hsl(180 80% 60%), hsl(240 80% 60%), hsl(300 80% 60%), hsl(0 80% 60%))",+ }}+ onPointerDown={(e) => {+ dragging.current = true;+ ref.current?.setPointerCapture(e.pointerId);+ last.current = fromEvent(e);+ onDraft(last.current);+ }}+ onPointerMove={(e) => {+ if (!dragging.current) return;+ last.current = fromEvent(e);+ onDraft(last.current);+ }}+ onPointerUp={() => {+ if (!dragging.current) return;+ dragging.current = false;+ onCommit(last.current);+ }}+ onPointerCancel={() => {+ // A cancelled drag still ends the gesture: commit where the puck was+ // left, or the checkpoint stays open and swallows the next drag's.+ if (!dragging.current) return;+ dragging.current = false;+ onCommit(last.current);+ }}+ onDoubleClick={() => onCommit([0, 0])}+ >+ {/* Saturation falls toward the center, like the offset it maps to. */}+ <div+ className="pointer-events-none absolute inset-0 rounded-full"+ style={{+ background:+ "radial-gradient(circle, var(--card) 0%, color-mix(in srgb, var(--card) 55%, transparent) 55%, transparent 100%)",+ }}+ />+ <div+ className="pointer-events-none absolute size-3 rounded-full border-2 border-neutral-800 bg-white shadow-sm"+ style={{+ left: `calc(${50 + (value[0] / GRADE_MAX) * 44}% - 6px)`,+ top: `calc(${50 + (value[1] / GRADE_MAX) * 44}% - 6px)`,+ }}+ />+ </div>+ </div>+ );+}diff --git a/site/src/cut/components/CurveEditor.tsx b/site/src/cut/components/CurveEditor.tsxnew file mode 100644index 00000000..ad6bb22e--- /dev/null+++ b/site/src/cut/components/CurveEditor.tsx@@ -0,0 +1,183 @@+"use client";++import { useRef, useState } from "react";+import { curveLut, type CurvePoint, type GradeCurves } from "@donkeycut/effects-kit";+import { cn } from "@/lib/utils";++/**+ * The tone-curve editor: one editable spline per channel (master, R, G, B),+ * drawn by sampling the same monotone spline the renderer bakes, so the line+ * on screen is the mapping the export applies. Drag a point to move it, click+ * the curve to add one, double-click a middle point to remove it. Drags+ * stream through onDraft and settle with onCommit, matching the sliders'+ * checkpoint discipline.+ */++type Channel = "m" | "r" | "g" | "b";++const CHANNELS: { id: Channel; label: string; color: string }[] = [+ { id: "m", label: "Master", color: "var(--foreground)" },+ { id: "r", label: "Red", color: "#ff453a" },+ { id: "g", label: "Green", color: "#32d74b" },+ { id: "b", label: "Blue", color: "#0a84ff" },+];++const IDENTITY: CurvePoint[] = [+ [0, 0],+ [255, 255],+];++const clampByte = (v: number) => Math.max(0, Math.min(255, Math.round(v)));++export function CurveEditor({+ curves,+ onDraft,+ onCommit,+}: {+ curves: GradeCurves | undefined;+ onDraft: (curves: GradeCurves) => void;+ onCommit: (curves: GradeCurves) => void;+}) {+ const [channel, setChannel] = useState<Channel>("m");+ const svgRef = useRef<SVGSVGElement>(null);+ const drag = useRef<{ index: number; points: CurvePoint[] } | null>(null);+ const points = curves?.[channel] ?? IDENTITY;+ const color = CHANNELS.find((c) => c.id === channel)!.color;++ const withChannel = (pts: CurvePoint[] | undefined): GradeCurves => {+ const next: GradeCurves = { ...curves };+ if (pts) next[channel] = pts;+ else delete next[channel];+ return next;+ };++ /** Pointer position in curve coordinates: x 0..255, y 0..255 bottom-up. */+ const curvePos = (e: React.PointerEvent): [number, number] => {+ const r = svgRef.current!.getBoundingClientRect();+ return [+ clampByte(((e.clientX - r.left) / r.width) * 255),+ clampByte((1 - (e.clientY - r.top) / r.height) * 255),+ ];+ };++ const onPointerDown = (e: React.PointerEvent) => {+ if (!svgRef.current) return;+ const [x, y] = curvePos(e);+ const pts = points.map((p) => [...p] as CurvePoint);+ // Grab the nearest existing point when it is within reach; otherwise add+ // a point at the pointer.+ let index = -1;+ let best = Infinity;+ pts.forEach((p, i) => {+ const d = Math.hypot(p[0] - x, p[1] - y);+ if (d < best) {+ best = d;+ index = i;+ }+ });+ if (best > 18) {+ const insert: CurvePoint = [x, y];+ index = pts.findIndex((p) => p[0] > x);+ if (index < 0) index = pts.length;+ pts.splice(index, 0, insert);+ }+ drag.current = { index, points: pts };+ svgRef.current.setPointerCapture(e.pointerId);+ onDraft(withChannel(pts));+ };++ const onPointerMove = (e: React.PointerEvent) => {+ const d = drag.current;+ if (!d) return;+ const [x, y] = curvePos(e);+ const pts = d.points;+ const p = pts[d.index];+ p[1] = y;+ // Endpoints hold their input; middle points slide between neighbors.+ if (d.index > 0 && d.index < pts.length - 1) {+ p[0] = Math.max(pts[d.index - 1][0] + 1, Math.min(pts[d.index + 1][0] - 1, x));+ }+ onDraft(withChannel(pts.map((q) => [...q] as CurvePoint)));+ };++ const onPointerUp = () => {+ const d = drag.current;+ drag.current = null;+ if (d) onCommit(withChannel(d.points));+ };++ const removePoint = (i: number) => {+ if (i <= 0 || i >= points.length - 1) return;+ const pts = points.filter((_, k) => k !== i);+ onCommit(withChannel(pts));+ };++ // The drawn line samples the renderer's own spline.+ const lut = curveLut(points);+ let path = "";+ for (let x = 0; x <= 255; x += 4) {+ const y = 255 - lut[x] * 255;+ path += `${path ? " L" : "M"} ${x} ${y.toFixed(1)}`;+ }++ return (+ <div className="flex flex-col gap-2">+ <div className="flex gap-1">+ {CHANNELS.map((c) => (+ <button+ key={c.id}+ type="button"+ className={cn(+ "flex-1 rounded-md px-1 py-0.5 text-[11.5px] font-medium transition-colors",+ channel === c.id+ ? "bg-secondary text-foreground"+ : "text-muted-foreground hover:text-foreground",+ !!curves?.[c.id] && channel !== c.id && "text-foreground"+ )}+ onClick={() => setChannel(c.id)}+ >+ {c.label}+ </button>+ ))}+ </div>+ <svg+ ref={svgRef}+ viewBox="0 0 256 256"+ className="clip-grade-curves aspect-square w-full cursor-crosshair touch-none rounded-md bg-secondary/60"+ onPointerDown={onPointerDown}+ onPointerMove={onPointerMove}+ onPointerUp={onPointerUp}+ onPointerCancel={onPointerUp}+ >+ {[64, 128, 192].map((g) => (+ <g key={g} className="stroke-border">+ <line x1={g} y1={0} x2={g} y2={256} strokeWidth={1} />+ <line x1={0} y1={g} x2={256} y2={g} strokeWidth={1} />+ </g>+ ))}+ <line+ x1={0}+ y1={256}+ x2={256}+ y2={0}+ strokeWidth={1}+ strokeDasharray="4 4"+ className="stroke-muted-foreground/40"+ />+ <path d={path} fill="none" stroke={color} strokeWidth={2.5} />+ {points.map((p, i) => (+ <circle+ key={i}+ cx={p[0]}+ cy={255 - p[1]}+ r={7}+ fill="var(--card)"+ stroke={color}+ strokeWidth={2}+ onDoubleClick={() => removePoint(i)}+ />+ ))}+ </svg>+ </div>+ );+}diff --git a/site/src/cut/components/EffectsPanel.tsx b/site/src/cut/components/EffectsPanel.tsxindex 671d4259..aca232d8 100644--- a/site/src/cut/components/EffectsPanel.tsx+++ b/site/src/cut/components/EffectsPanel.tsx@@ -14,9 +14,8 @@ import {import { PICKED_RING, pickGridNav, useAssetPick } from "@/cut/lib/assetPick";import { clearElementDrag, setElementDragData, setObjectDragImage } from "@/cut/lib/assetDrag";import { SubTabs } from "@/cut/components/SubTabs";-import { getPreviewCanvas } from "@/cut/lib/previewCanvas";-import { projectDuration, useEditor } from "@/cut/lib/store";-import { usePreviewTimeEvery } from "@/cut/lib/playhead";+import { usePlayheadFrame } from "@/cut/components/usePlayheadFrame";+import { useEditor } from "@/cut/lib/store";import { isEffectOverlay, type EffectOverlay } from "@/cut/lib/types";import { useLocalPref } from "@/cut/lib/uiState";import { cn } from "@/lib/utils";@@ -86,74 +85,6 @@ export function EffectsPanel() {);}-/** The sampled preview frame's short side, doubled from the tile swatch's- * on-screen size so it stays sharp on retina displays. */-const FRAME_SHORT = 360;--/** A snapshot of the live preview canvas — the whole frame under the playhead,- * at the canvas's own aspect — encoded small for the tile swatches; null when- * the canvas has no picture yet. */-function snapshotPreview(): string | null {- const src = getPreviewCanvas();- if (!src || !src.width || !src.height) return null;- const scale = FRAME_SHORT / Math.min(src.width, src.height);- const c = document.createElement("canvas");- c.width = Math.round(src.width * scale);- c.height = Math.round(src.height * scale);- const ctx = c.getContext("2d", { willReadFrequently: true });- if (!ctx) return null;- try {- ctx.drawImage(src, 0, 0, c.width, c.height);- // The engine leaves the canvas untouched until a decoder has a frame; a- // fully transparent readback means there is no picture to show yet.- const px = ctx.getImageData(0, 0, c.width, c.height).data;- let lit = false;- for (let i = 3; i < px.length; i += 397 * 4) {- if (px[i] > 0) {- lit = true;- break;- }- }- if (!lit) return null;- return c.toDataURL("image/jpeg", 0.72);- } catch {- // A tainted canvas or a blocked readback: the swatch keeps its stand-in.- return null;- }-}--/** The last sampled frame, kept across tab switches: the panel unmounts when- * another tab opens, and a fresh mount seeds from here so the tiles paint the- * real picture at once with no pass through the stand-in. */-let lastFrame: { project: string; url: string } | null = null;--/** The frame under the playhead as a small data URL, re-sampled as the- * playhead moves (about five times a second, a beat after each move so the- * decoder has painted); null until the preview has a picture. */-function usePlayheadFrame(): string | null {- const projectId = useEditor((s) => s.projectId);- const [frame, setFrame] = useState<string | null>(() =>- lastFrame && lastFrame.project === projectId ? lastFrame.url : null- );- const tick = usePreviewTimeEvery(5);- const epoch = useEditor((s) => s.loadEpoch);- // The tile shows the live frame, which a cut of titles and shapes over the- // background has as much as one made of footage.- const hasPicture = useEditor((s) => projectDuration(s) > 0);- useEffect(() => {- if (!hasPicture || !projectId) return;- const t = setTimeout(() => {- const shot = snapshotPreview();- if (shot) {- lastFrame = { project: projectId, url: shot };- setFrame(shot);- }- }, 160);- return () => clearTimeout(t);- }, [tick, epoch, hasPicture, projectId]);- return hasPicture ? frame : null;-}-/** One effect: the preview fills the tile with its name under it, a click* picks it (or swaps the selected element to it), and a drag onto the timeline* places it. Hovering runs the preview — the flash pulses, the glitch tears,diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsxindex 430871c4..8a767144 100644--- a/site/src/cut/components/Inspector.tsx+++ b/site/src/cut/components/Inspector.tsx@@ -1,7 +1,7 @@"use client";import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";-import { AlignCenter, AlignHorizontalSpaceAround, AlignLeft, AlignRight, AlignVerticalSpaceAround, Bold, ChevronLeft, ChevronRight, Diamond, Info, Italic, RotateCcw, SlidersHorizontal, Smile, Trash2, Type, Wand2 } from "lucide-react";+import { AlignCenter, AlignHorizontalSpaceAround, AlignLeft, AlignRight, AlignVerticalSpaceAround, Bold, ChevronLeft, ChevronRight, Diamond, Italic, SlidersHorizontal, Smile, Trash2, Type } from "lucide-react";import { Button } from "@/components/ui/button";import { EmojiPicker } from "@/cut/components/EmojiPicker";import { FontPicker } from "@/cut/components/FontPicker";@@ -13,12 +13,6 @@ import {SelectValue,} from "@/components/ui/select";import { Switch } from "@/components/ui/switch";-import {- Tooltip,- TooltipContent,- TooltipProvider,- TooltipTrigger,-} from "@/components/ui/tooltip";import { Textarea } from "@/components/ui/textarea";import {EFFECT_LABELS,@@ -72,8 +66,6 @@ import { formatTime } from "@/cut/lib/time";import {fontStack,frameOf,- GRADE_HUE_MAX,- GRADE_MAX,isEffectOverlay,isShapeOverlay,isTextOverlay,@@ -89,7 +81,6 @@ import {type AudioClip,type BoxStyle,type ClipShadow,- type ColorGrade,type FrameRect,type LayoutId,type EffectOverlay,@@ -99,7 +90,7 @@ import {type TextOverlay,type VideoClip,} from "@/cut/lib/types";-import { autoGradeFromImageData, isNeutralGrade, normalizeGrade } from "@donkeycut/effects-kit";+import { GRADE_PRESETS, isNeutralGrade } from "@donkeycut/effects-kit";import {matchTextMove,MOVE_STRENGTH_MAX,@@ -107,28 +98,11 @@ import {MOVE_STRENGTH_STEP,textMoveKeys,} from "@/cut/lib/textMotion";-import { getPreviewCanvas, sampleClipFrameData } from "@/cut/lib/previewCanvas";+import { getPreviewCanvas } from "@/cut/lib/previewCanvas";import { cn } from "@/lib/utils";import { ScrollArea } from "@/components/ui/scroll-area";--/**- * One undo checkpoint per slider drag: capture the pre-drag state on the first- * change, then feed live changes through the transient updater so the whole- * drag collapses to a single ⌘Z. Reset when the interaction commits.- */-function useSliderCheckpoint() {- const active = useRef(false);- return {- begin() {- if (active.current) return;- active.current = true;- useEditor.getState().pushHistory();- },- end() {- active.current = false;- },- };-}+import { InfoTip, ResetButton, Row, useSliderCheckpoint, Value } from "@/cut/components/panelBits";+import { ColorPanel } from "@/cut/components/ColorPanel";/** Where the animation panel is, for the panel that offers the way in. It is* held by the Inspector rather than by each panel because the animation panel@@ -178,6 +152,11 @@ function InspectorColumn({overlay?: Overlay;}) {const [animView, setAnimView] = useState<"closed" | "open" | "returned">("closed");+ // The color subview replaces the whole column the same way the animation+ // panel does: it lays out its own bands (header, chips, floor bar) around+ // its own scroller. It remembers which clip opened it, so selecting another+ // clip lands back on the main view.+ const [colorFor, setColorFor] = useState<string | null>(null);const nav = useMemo<AnimNav>(() => ({view: animView,@@ -193,11 +172,13 @@ function InspectorColumn({<AnimationPanel overlay={overlay} onBack={nav.back} /></AnimNavContext.Provider>);+ if (clip && colorFor === clip.id)+ return <ColorPanel clip={clip} onBack={() => setColorFor(null)} />;return (<AnimNavContext.Provider value={nav}><ScrollArea className="min-h-0 flex-1">{clip ? (- <ClipPanel clip={clip} />+ <ClipPanel clip={clip} onColor={() => setColorFor(clip.id)} />) : audio ? (<AudioPanel clip={audio} />) : overlay ? (@@ -237,31 +218,6 @@ function ClipHead({ name, time }: { name?: string; time: string }) {);}-function Row({- label,- info,- grow,- children,-}: {- label: string;- /** Hoverable (i) after the label explaining what the control does. */- info?: React.ReactNode;- /** Stretch the control over the row's free width; the default hugs the- * control to the right edge at its own size. */- grow?: boolean;- children: React.ReactNode;-}) {- return (- <div className="flex min-h-9 items-center justify-between gap-2.5">- <span className="flex shrink-0 items-center gap-1 text-[13px] text-muted-foreground">- {label}- {info && <InfoTip label={label}>{info}</InfoTip>}- </span>- <div className={cn("flex min-w-0 items-center gap-2", grow && "grow")}>{children}</div>- </div>- );-}-/** A control that carries its own caption, for the two-up rows where the* settings sit side by side instead of behind a label on the left. */function Field({ label, children }: { label: string; children: React.ReactNode }) {@@ -311,24 +267,6 @@ function SegToggle({}/** Hoverable (i) explaining the control it follows. */-function InfoTip({ label, children }: { label: string; children: React.ReactNode }) {- return (- <TooltipProvider>- <Tooltip>- <TooltipTrigger- className="grid size-4 place-items-center text-muted-foreground/70 transition-colors hover:text-foreground"- aria-label={`About ${label.toLowerCase()}`}- >- <Info className="size-3.5" />- </TooltipTrigger>- <TooltipContent side="bottom" className="max-w-60">- {children}- </TooltipContent>- </Tooltip>- </TooltipProvider>- );-}-/*** A named group of rows under a hairline. A section that owns a feature carries* the switch that turns it on and holds its rows back until it is, so the panel@@ -369,34 +307,9 @@ function Section({);}-const Value = ({ children, className }: { children: React.ReactNode; className?: string }) => (- <span className={cn("font-mono text-[11.5px] tabular-nums", className)}>{children}</span>-);-/** Matches the store's MIN_LEN: the shortest a trim can leave a clip. */const MIN_TRIM = 0.1;-/** Sits at the right end of a row, visible once its value has moved off the- * default. Always occupies its slot so the row doesn't shift when it appears. */-function ResetButton({ title, show, onClick }: { title: string; show: boolean; onClick: () => void }) {- return (- <button- type="button"- title={title}- aria-label={title}- aria-hidden={!show}- tabIndex={show ? undefined : -1}- className={cn(- "grid size-5 shrink-0 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground",- !show && "invisible",- )}- onClick={onClick}- >- <RotateCcw className="size-3" />- </button>- );-}-const formatSpeed = (v: number) => `${v.toFixed(2)}×`;const formatPercent = (v: number) => `${Math.round(v * 100)}%`;@@ -472,7 +385,7 @@ function LayoutButtons({);}-function ClipPanel({ clip }: { clip: VideoClip }) {+function ClipPanel({ clip, onColor }: { clip: VideoClip; onColor: () => void }) {const asset = useEditor((s) => s.assets.find((a) => a.id === clip.assetId));const aspect = useEditor((s) => s.aspect);const updateClip = useEditor((s) => s.updateClip);@@ -481,19 +394,12 @@ function ClipPanel({ clip }: { clip: VideoClip }) {const fadeCk = useSliderCheckpoint();const [speedDraft, setSpeedDraft] = useState<number | null>(null);const [volumeDraft, setVolumeDraft] = useState<number | null>(null);- // The panel can push into the color-grade subview, which remembers which- // clip opened it, so selecting another clip lands back on the main view.- const [colorFor, setColorFor] = useState<string | null>(null);- const view = colorFor === clip.id ? "color" : "main";const volume = volumeDraft ?? clip.volume ?? 1;const speed = speedDraft ?? clip.speed ?? 1;const speedLen = (clip.out - clip.in) / (speed > 0 ? speed : 1);// Typing can trim out to the source's end but no further; an image has no// intrinsic duration, so its clip can be any length.const maxOut = asset && asset.type !== "image" ? asset.duration : Infinity;- if (view === "color") {- return <ColorPanel clip={clip} onBack={() => setColorFor(null)} />;- }return (<><div className="flex flex-col gap-1 px-3.5 pb-4">@@ -577,16 +483,18 @@ function ClipPanel({ clip }: { clip: VideoClip }) {<buttontype="button"className="clip-color flex h-8 w-[8.5rem] items-center justify-between rounded-md border border-input px-2.5 text-[11.5px] font-medium text-muted-foreground transition-colors hover:text-foreground"- onClick={() => setColorFor(clip.id)}+ onClick={onColor}>- <span className="flex items-center gap-1.5">- <SlidersHorizontal className="size-3.5" />- Adjust+ <span className="flex min-w-0 items-center gap-1.5">+ <SlidersHorizontal className="size-3.5 shrink-0" />+ <span className="truncate">+ {(clip.grade?.preset && GRADE_PRESETS[clip.grade.preset.id]?.label) || "Adjust"}+ </span>{!isNeutralGrade(clip.grade) && (- <span className="size-1.5 rounded-full bg-violet-500" aria-label="Adjusted" />+ <span className="size-1.5 shrink-0 rounded-full bg-violet-500" aria-label="Adjusted" />)}</span>- <ChevronRight className="size-3.5" />+ <ChevronRight className="size-3.5 shrink-0" /></button></Row>@@ -772,168 +680,6 @@ function ClipPanel({ clip }: { clip: VideoClip }) {);}-const GRADE_FIELDS: { key: keyof ColorGrade; label: string; max: number }[] = [- { key: "brightness", label: "Brightness", max: GRADE_MAX },- { key: "contrast", label: "Contrast", max: GRADE_MAX },- { key: "saturation", label: "Saturation", max: GRADE_MAX },- { key: "exposure", label: "Exposure", max: GRADE_MAX },- { key: "temperature", label: "Temperature", max: GRADE_MAX },- { key: "hue", label: "Hue", max: GRADE_HUE_MAX },-];--const formatGradeValue = (key: keyof ColorGrade, v: number) =>- key === "hue" ? `${Math.round(v)}°` : v > 0 ? `+${Math.round(v)}` : `${Math.round(v)}`;--/** The color-grade subview a clip panel pushes into: live histogram over the- * adjustment sliders. Slider drags stream through the transient updater under- * one history checkpoint, so the preview follows live and ⌘Z undoes the whole- * drag. */-function ColorPanel({ clip, onBack }: { clip: VideoClip; onBack: () => void }) {- const ck = useSliderCheckpoint();- const updateClip = useEditor((s) => s.updateClip);- const setField = (key: keyof ColorGrade, v: number) => {- ck.begin();- useEditor.getState().updateClipTransient(clip.id, {- grade: normalizeGrade({ ...clip.grade, [key]: v }),- });- };- // Fit a starting grade from the clip's raw decoder frame (never the graded- // preview, which would fold the current grade back into the fit); the- // sliders show the result and stay fully adjustable after.- const autoGrade = () => {- const data = sampleClipFrameData(clip.id);- if (data) updateClip(clip.id, { grade: autoGradeFromImageData(data) });- };- return (- <>- <div className="flex h-10 shrink-0 items-center gap-1 px-2.5 text-sm font-semibold tracking-tight">- <button- type="button"- aria-label="Back"- className="clip-color-back grid size-6 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground"- onClick={onBack}- >- <ChevronLeft className="size-4" />- </button>- Color- <button- type="button"- className="clip-grade-auto ml-auto flex items-center gap-1 rounded-md border border-input px-2 py-0.5 text-[11.5px] font-medium text-muted-foreground transition-colors hover:text-foreground"- onClick={autoGrade}- >- <Wand2 className="size-3" />- Auto- </button>- </div>- <div className="flex flex-col gap-1 px-3.5 pb-4">- <Histogram />- {GRADE_FIELDS.map((f) => {- const value = clip.grade?.[f.key] ?? 0;- return (- <Row key={f.key} label={f.label}>- <ValueSlider- label={f.label}- sliderClassName={`clip-grade-${f.key} data-horizontal:w-24`}- valueClassName="w-9 text-muted-foreground"- value={value}- min={-f.max}- max={f.max}- step={1}- snap={[0]}- format={(v) => formatGradeValue(f.key, v)}- parse={parseNumberInput}- onDraft={(v) => setField(f.key, v)}- onCommit={(v) => {- setField(f.key, v);- ck.end();- }}- />- <ResetButton- title={`Reset ${f.label.toLowerCase()}`}- show={value !== 0}- onClick={() => {- setField(f.key, 0);- ck.end();- }}- />- </Row>- );- })}- {!isNeutralGrade(clip.grade) && (- <Button- variant="outline"- size="sm"- className="clip-grade-reset mt-2"- onClick={() => updateClip(clip.id, { grade: undefined })}- >- Reset all- </Button>- )}- </div>- </>- );-}--/** Live RGB histogram of the composited preview frame: the three channel- * curves screen over each other so overlaps read light. Samples a small- * downscale of the preview canvas on a short interval while open. */-function Histogram() {- const ref = useRef<HTMLCanvasElement>(null);- useEffect(() => {- const cv = ref.current;- const ctx = cv?.getContext("2d");- if (!cv || !ctx) return;- const sample = document.createElement("canvas");- sample.width = 96;- sample.height = 54;- const sctx = sample.getContext("2d", { willReadFrequently: true });- if (!sctx) return;- const BINS = 64;- const COLORS = ["#ff453a", "#32d74b", "#0a84ff"];- const draw = () => {- const src = getPreviewCanvas();- if (!src) return;- let data: Uint8ClampedArray;- try {- sctx.drawImage(src, 0, 0, sample.width, sample.height);- data = sctx.getImageData(0, 0, sample.width, sample.height).data;- } catch {- return; // unreadable canvas — keep whatever is drawn- }- const bins = [new Float64Array(BINS), new Float64Array(BINS), new Float64Array(BINS)];- for (let i = 0; i < data.length; i += 4) {- bins[0][data[i] >> 2]++;- bins[1][data[i + 1] >> 2]++;- bins[2][data[i + 2] >> 2]++;- }- const W = cv.width;- const H = cv.height;- ctx.globalCompositeOperation = "source-over";- ctx.fillStyle = "#101014";- ctx.fillRect(0, 0, W, H);- const peak = Math.max(1, ...bins.map((b) => Math.max(...b)));- ctx.globalCompositeOperation = "screen";- bins.forEach((b, ci) => {- ctx.fillStyle = COLORS[ci];- ctx.beginPath();- ctx.moveTo(0, H);- for (let i = 0; i < BINS; i++) {- // sqrt tames the peaks so midtone shape stays visible.- ctx.lineTo((i / (BINS - 1)) * W, H - Math.sqrt(b[i] / peak) * (H - 3));- }- ctx.lineTo(W, H);- ctx.closePath();- ctx.fill();- });- ctx.globalCompositeOperation = "source-over";- };- draw();- const id = setInterval(draw, 150);- return () => clearInterval(id);- }, []);- return <canvas ref={ref} width={256} height={80} className="mb-1.5 h-20 w-full rounded-md" />;-}-/** Per-clip generated-audio block: the voice picker, "Generate audio for clip"* (which transcribes just this clip when it has no cues yet), and one volume* slider driving the voiceovers laid over the clip. Shared by every clipdiff --git a/site/src/cut/components/panelBits.tsx b/site/src/cut/components/panelBits.tsxnew file mode 100644index 00000000..dd24915f--- /dev/null+++ b/site/src/cut/components/panelBits.tsx@@ -0,0 +1,100 @@+"use client";++import { useRef } from "react";+import { Info, RotateCcw } from "lucide-react";+import { useEditor } from "@/cut/lib/store";+import { cn } from "@/lib/utils";+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";++/**+ * The Inspector's shared row furniture, in a module of its own so the panels+ * that grew out of the Inspector (the color panel) build rows the same way+ * without importing the whole file.+ */++/**+ * One undo checkpoint per slider drag: capture the pre-drag state on the first+ * change, then feed live changes through the transient updater so the whole+ * drag collapses to a single ⌘Z. Reset when the interaction commits.+ */+export function useSliderCheckpoint() {+ const active = useRef(false);+ return {+ begin() {+ if (active.current) return;+ active.current = true;+ useEditor.getState().pushHistory();+ },+ end() {+ active.current = false;+ },+ };+}++export function InfoTip({ label, children }: { label: string; children: React.ReactNode }) {+ return (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger+ className="grid size-4 place-items-center text-muted-foreground/70 transition-colors hover:text-foreground"+ aria-label={`About ${label.toLowerCase()}`}+ >+ <Info className="size-3.5" />+ </TooltipTrigger>+ <TooltipContent side="bottom" className="max-w-60">+ {children}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ );+}++export function Row({+ label,+ info,+ grow,+ children,+}: {+ label: string;+ /** Hoverable (i) after the label explaining what the control does. */+ info?: React.ReactNode;+ /** Stretch the control over the row's free width; the default hugs the+ * control to the right edge at its own size. */+ grow?: boolean;+ children: React.ReactNode;+}) {+ return (+ <div className="flex min-h-9 items-center justify-between gap-2.5">+ <span className="flex shrink-0 items-center gap-1 text-[13px] text-muted-foreground">+ {label}+ {info && <InfoTip label={label}>{info}</InfoTip>}+ </span>+ <div className={cn("flex min-w-0 items-center gap-2", grow && "grow")}>{children}</div>+ </div>+ );+}++export const Value = ({ children, className }: { children: React.ReactNode; className?: string }) => (+ <span className={cn("font-mono text-[11.5px] tabular-nums", className)}>{children}</span>+);++/** Sits at the right end of a row, visible once its value has moved off the+ * default. Always occupies its slot so the row doesn't shift when it appears. */+export function ResetButton({ title, show, onClick }: { title: string; show: boolean; onClick: () => void }) {+ return (+ <button+ type="button"+ title={title}+ aria-label={title}+ aria-hidden={!show}+ tabIndex={show ? undefined : -1}+ className={cn(+ "grid size-5 shrink-0 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground",+ !show && "invisible",+ )}+ onClick={onClick}+ >+ <RotateCcw className="size-3" />+ </button>+ );+}diff --git a/site/src/cut/components/usePlayheadFrame.ts b/site/src/cut/components/usePlayheadFrame.tsnew file mode 100644index 00000000..3fc6da0e--- /dev/null+++ b/site/src/cut/components/usePlayheadFrame.ts@@ -0,0 +1,130 @@+"use client";++import { useEffect, useState } from "react";+import { getPreviewCanvas, sampleClipSource } from "@/cut/lib/previewCanvas";+import { projectDuration, useEditor } from "@/cut/lib/store";+import { usePreviewTimeEvery } from "@/cut/lib/playhead";++/** The sampled preview frame's short side, doubled from the tile swatch's+ * on-screen size so it stays sharp on retina displays. */+export const FRAME_SHORT = 360;++/** A snapshot of the live preview canvas — the whole frame under the playhead,+ * at the canvas's own aspect — encoded small for the tile swatches; null when+ * the canvas has no picture yet. */+export function snapshotPreview(): string | null {+ const src = getPreviewCanvas();+ if (!src || !src.width || !src.height) return null;+ const scale = FRAME_SHORT / Math.min(src.width, src.height);+ const c = document.createElement("canvas");+ c.width = Math.round(src.width * scale);+ c.height = Math.round(src.height * scale);+ const ctx = c.getContext("2d", { willReadFrequently: true });+ if (!ctx) return null;+ try {+ ctx.drawImage(src, 0, 0, c.width, c.height);+ // The engine leaves the canvas untouched until a decoder has a frame; a+ // fully transparent readback means there is no picture to show yet.+ const px = ctx.getImageData(0, 0, c.width, c.height).data;+ let lit = false;+ for (let i = 3; i < px.length; i += 397 * 4) {+ if (px[i] > 0) {+ lit = true;+ break;+ }+ }+ if (!lit) return null;+ return c.toDataURL("image/jpeg", 0.72);+ } catch {+ // A tainted canvas or a blocked readback: the swatch keeps its stand-in.+ return null;+ }+}++/** The natural size of whatever the decoder handed over — a video frame, an+ * image bitmap, or a canvas. */+function sourceSize(src: CanvasImageSource): { w: number; h: number } | null {+ const s = src as {+ displayWidth?: number;+ displayHeight?: number;+ videoWidth?: number;+ videoHeight?: number;+ naturalWidth?: number;+ naturalHeight?: number;+ width?: number | SVGAnimatedLength;+ height?: number | SVGAnimatedLength;+ };+ const plain = (v: number | SVGAnimatedLength | undefined) => (typeof v === "number" ? v : 0);+ const w = s.displayWidth || s.videoWidth || s.naturalWidth || plain(s.width);+ const h = s.displayHeight || s.videoHeight || s.naturalHeight || plain(s.height);+ return w > 0 && h > 0 ? { w, h } : null;+}++/** A clip's own decoded frame, before any grade, encoded small. The composited+ * preview carries the clip's grade already, so a preset swatch drawn from it+ * would fold that grade in twice. */+export function snapshotClipSource(clipId: string): string | null {+ const src = sampleClipSource(clipId);+ const size = src && sourceSize(src);+ if (!src || !size) return null;+ const scale = Math.min(1, FRAME_SHORT / Math.min(size.w, size.h));+ const c = document.createElement("canvas");+ c.width = Math.max(1, Math.round(size.w * scale));+ c.height = Math.max(1, Math.round(size.h * scale));+ const ctx = c.getContext("2d");+ if (!ctx) return null;+ try {+ ctx.drawImage(src, 0, 0, c.width, c.height);+ return c.toDataURL("image/jpeg", 0.72);+ } catch {+ return null;+ }+}++/** The clip's ungraded frame under the playhead, re-sampled as it moves — the+ * base every color preset swatch paints its own recipe onto. */+export function useClipSourceFrame(clipId: string): string | null {+ const [frame, setFrame] = useState<string | null>(null);+ const tick = usePreviewTimeEvery(5);+ const epoch = useEditor((s) => s.loadEpoch);+ useEffect(() => {+ const t = setTimeout(() => {+ const shot = snapshotClipSource(clipId);+ if (shot) setFrame(shot);+ }, 160);+ return () => clearTimeout(t);+ }, [tick, epoch, clipId]);+ return frame;+}++/** The last sampled frame, kept across tab switches: a panel unmounts when+ * another tab opens, and a fresh mount seeds from here so the tiles paint the+ * real picture at once with no pass through the stand-in. */+let lastFrame: { project: string; url: string } | null = null;++/** The frame under the playhead as a small data URL, re-sampled as the+ * playhead moves (about five times a second, a beat after each move so the+ * decoder has painted); null until the preview has a picture. */+export function usePlayheadFrame(): string | null {+ const projectId = useEditor((s) => s.projectId);+ const [frame, setFrame] = useState<string | null>(() =>+ lastFrame && lastFrame.project === projectId ? lastFrame.url : null+ );+ const tick = usePreviewTimeEvery(5);+ const epoch = useEditor((s) => s.loadEpoch);+ // The tile shows the live frame, which a cut of titles and shapes over the+ // background has as much as one made of footage.+ const hasPicture = useEditor((s) => projectDuration(s) > 0);+ useEffect(() => {+ if (!hasPicture || !projectId) return;+ const t = setTimeout(() => {+ const shot = snapshotPreview();+ if (shot) {+ lastFrame = { project: projectId, url: shot };+ setFrame(shot);+ }+ }, 160);+ return () => clearTimeout(t);+ }, [tick, epoch, hasPicture, projectId]);+ return hasPicture ? frame : null;+}