Open source CapCut alternative.
TypeScript
feat(site): live effect and transition previews on real footage
David Le50c37d721355
diff --git a/site/src/cut/components/EffectsPanel.tsx b/site/src/cut/components/EffectsPanel.tsxindex 0e3fc50f..12506bb3 100644--- a/site/src/cut/components/EffectsPanel.tsx+++ b/site/src/cut/components/EffectsPanel.tsx@@ -5,46 +5,77 @@ import {EFFECT_IDS,EFFECT_LABELS,effectPreviewState,+ grainTileUrl,+ leakGradient,type EffectId,} from "@donkeycut/effects-kit";-import { PICKED_RING, useAssetPick } from "@/cut/lib/assetPick";+import { PICKED_RING, pickGridNav, useAssetPick } from "@/cut/lib/assetPick";import { clearElementDrag, setElementDragData } from "@/cut/lib/assetDrag";+import { SubTabs } from "@/cut/components/SubTabs";+import { getPreviewCanvas } from "@/cut/lib/previewCanvas";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";import { ScrollArea } from "@/components/ui/scroll-area";+import "./grain.css";/*** The Effects tab: time-ranged treatments over the finished picture — the- * footage and everything laid over it. Two families in one list, the- * treatments (grain, VHS, glitch, blur, vignette, light leak, flash, shake)- * and the graded looks (vintage, noir, halation…). Drag one onto the timeline- * to place it; a click only picks the tile, the same as every other panel.+ * footage and everything laid over it. A segmented toggle splits the grid+ * into two families: Moving, the effects that play over their stretch of+ * timeline (zoom, grain, VHS, glitch, light leak, flash, shake), and+ * Filters, the still treatments and graded looks (blur, vignette, vintage,+ * noir, halation…). Drag one onto the timeline to place it; a click only+ * picks the tile, the same as every other panel.*- * Select an effect on the timeline and the tab follows it: its tile is the- * marked one, and a click on another tile changes that element to it. The- * click never places anything — with an effect selected it retunes what is- * already there, and with nothing selected it just picks.+ * Select an effect on the timeline and the tab follows it: its family opens,+ * its tile is the marked one, and a click on another tile changes that+ * element to it. The click never places anything — with an effect selected+ * it retunes what is already there, and with nothing selected it just picks.*/++type EffectGroup = "moving" | "filters";++const GROUPS = [+ { id: "moving", label: "Moving" },+ { id: "filters", label: "Filters" },+] as const;++const MOVING: EffectId[] = ["zoom", "grain", "vhs", "glitch", "lightleak", "flash", "shake"];++const groupOf = (id: EffectId): EffectGroup => (MOVING.includes(id) ? "moving" : "filters");+export function EffectsPanel() {const live = useEditor((s) => {if (s.selection?.kind !== "overlay") return null;const o = s.overlays.find((x) => x.id === s.selection!.id);return o && isEffectOverlay(o) ? o : null;});+ const [group, setGroup] = useLocalPref<EffectGroup>("cut-effects-group", "moving", (v) =>+ GROUPS.some((g) => g.id === v)+ );+ // The tab follows the selection into its family so the marked tile shows.+ const liveEffect = live?.effect;+ useEffect(() => {+ if (liveEffect) setGroup(groupOf(liveEffect));+ }, [liveEffect, setGroup]);+ const frame = usePlayheadFrame();return (<>- <div className="flex h-12 shrink-0 items-center pr-2.5 pl-4">- <span className="text-sm font-semibold tracking-tight">Effects</span>+ {/* PanelHead's height, so the side panel's floating close button lands+ on the toggle's centerline; the right padding keeps clear of it. */}+ <div className="flex h-12 shrink-0 items-center pr-12 pl-3.5">+ <SubTabs tabs={GROUPS} value={group} onChange={setGroup} /></div>{/* The top pad is the selected tile's ring and its offset: the gridstarts at the scroll edge, and a ring drawn outside the tile would becut off there. */}<ScrollArea className="min-h-0 flex-1" contentClassName="px-3.5 pt-1 pb-4">- <div className="grid grid-cols-2 gap-2">- {EFFECT_IDS.map((id) => (- <EffectTile key={id} id={id} live={live} />+ <div className="grid grid-cols-2 gap-2" onKeyDown={pickGridNav}>+ {EFFECT_IDS.filter((id) => groupOf(id) === group).map((id) => (+ <EffectTile key={id} id={id} live={live} frame={frame} />))}</div></ScrollArea>@@ -52,14 +83,93 @@ export function EffectsPanel() {);}+/** How wide the sampled preview frame is, doubled from the tile swatch's+ * on-screen size so it stays sharp on retina displays. */+const FRAME_W = 280;+const FRAME_H = 192;++/** A cover-cropped snapshot of the live preview canvas — the frame under the+ * playhead — 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 c = document.createElement("canvas");+ c.width = FRAME_W;+ c.height = FRAME_H;+ const ctx = c.getContext("2d", { willReadFrequently: true });+ if (!ctx) return null;+ const scale = Math.max(FRAME_W / src.width, FRAME_H / src.height);+ const sw = FRAME_W / scale;+ const sh = FRAME_H / scale;+ try {+ ctx.drawImage(src, (src.width - sw) / 2, (src.height - sh) / 2, sw, sh, 0, 0, FRAME_W, FRAME_H);+ // 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, FRAME_W, FRAME_H).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 = useEditor((s) => Math.round(s.currentTime * 5));+ const epoch = useEditor((s) => s.loadEpoch);+ const hasClips = useEditor((s) => s.clips.length > 0);+ useEffect(() => {+ if (!hasClips || !projectId) return;+ const t = setTimeout(() => {+ const shot = snapshotPreview();+ if (shot) {+ lastFrame = { project: projectId, url: shot };+ setFrame(shot);+ }+ }, 160);+ return () => clearTimeout(t);+ }, [tick, epoch, hasClips, projectId]);+ return hasClips ? 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,* the shake moves. */-function EffectTile({ id, live }: { id: EffectId; live: EffectOverlay | null }) {+function EffectTile({+ id,+ live,+ frame,+}: {+ id: EffectId;+ live: EffectOverlay | null;+ frame: string | null;+}) {const { picked, pick } = useAssetPick(`effect:${id}`);const [hover, setHover] = useState(false);- const t = useSwatchClock(hover);+ // A moving effect's whole point is its motion, so its swatch always plays;+ // a filter swatch stands still until the pointer asks it to run.+ const t = useSwatchClock(hover || groupOf(id) === "moving");const ref = useRef<HTMLButtonElement>(null);// What the selection means for this tile: it wears the ring when it is the// selected element's effect, and a click swaps that element onto it.@@ -73,12 +183,8 @@ function EffectTile({ id, live }: { id: EffectId; live: EffectOverlay | null })<buttonref={ref}type="button"+ data-pick-id={`effect:${id}`}aria-pressed={marked}- title={- live- ? `Change the selected effect to ${EFFECT_LABELS[id]}`- : `Drag ${EFFECT_LABELS[id]} onto the timeline`- }draggableonDragStart={(e) => setElementDragData(e, { kind: "effect", effect: id })}onDragEnd={clearElementDrag}@@ -90,15 +196,18 @@ function EffectTile({ id, live }: { id: EffectId; live: EffectOverlay | null })if (!live) return pick();if (!isLive) useEditor.getState().updateOverlay(live.id, { effect: id });}}- className={cn(- // Scroll margin keeps the whole tile — selection ring included — clear- // of the scroller's edges when scrollIntoView lands it there.- "flex scroll-m-2 flex-col overflow-hidden rounded-lg border border-border text-[11px] font-medium text-muted-foreground transition-colors hover:text-foreground",- marked && PICKED_RING- )}+ // Scroll margin keeps the whole tile — selection ring included — clear+ // of the scroller's edges when scrollIntoView lands it there. The picked+ // ring is the focus indicator; the browser outline stays off.+ className="flex scroll-m-2 flex-col gap-1.5 text-[11px] font-medium text-muted-foreground outline-none transition-colors hover:text-foreground">- <EffectSwatch id={id} t={t} className="h-16 w-full rounded-none" />- <span className="py-1.5 leading-none">{EFFECT_LABELS[id]}</span>+ <EffectSwatch+ id={id}+ t={t}+ frame={frame}+ className={cn("h-24 w-full rounded-lg border border-border", marked && PICKED_RING)}+ />+ <span className="leading-none">{EFFECT_LABELS[id]}</span></button>);}@@ -108,7 +217,9 @@ function EffectTile({ id, live }: { id: EffectId; live: EffectOverlay | null })const SWATCH_T = 0.12; // seconds in — past a flash's white peakconst LOOP_S = 1.4;-function useSwatchClock(running: boolean): number {+/** A looping clock for tile previews, shared with the Transitions tab. A+ * `resetKey` change starts the loop over from the top. */+export function useSwatchClock(running: boolean, loop = LOOP_S, resetKey = 0): number {const [t, setT] = useState(SWATCH_T);useEffect(() => {if (!running) return;@@ -116,7 +227,7 @@ function useSwatchClock(running: boolean): number {let from = 0;const step = (now: number) => {if (!from) from = now;- setT(((now - from) / 1000) % LOOP_S);+ setT(((now - from) / 1000) % loop);raf = requestAnimationFrame(step);};raf = requestAnimationFrame(step);@@ -125,52 +236,116 @@ function useSwatchClock(running: boolean): number {cancelAnimationFrame(raf);setT(SWATCH_T);};- }, [running]);+ }, [running, loop, resetKey]);return t;}-/** What an effect does to a picture, on a stand-in picture: the same preview- * state the canvas pass reads, over a gradient with a bright disc in it so- * blur, grain, vignette, tearing and shake all read at tile size. */+/** The picture a swatch treats: the given frame when there is one, and a small+ * colored landscape as the stand-in, so every treatment reads at tile size.+ * The stand-in comes in two casts — day (sun over green hills) and dusk (moon+ * over dark ones) — so a transition tile can hand over between two scenes that+ * read as different shots. Shared with the Transitions tab. */+export function SwatchScene({+ frame,+ variant = "day",+}: {+ frame: string | null;+ variant?: "day" | "dusk";+}) {+ if (frame) {+ return (+ // eslint-disable-next-line @next/next/no-img-element -- a transient data URL or filmstrip thumb; the image optimizer has no role+ <img src={frame} alt="" draggable={false} className="absolute inset-0 size-full object-cover" />+ );+ }+ if (variant === "dusk") {+ return (+ <>+ <span className="absolute inset-0 bg-[linear-gradient(165deg,#2b3f77_0%,#5a4a8a_55%,#c26d4a_100%)]" />+ <span className="absolute top-[14%] right-[16%] size-[22%] rounded-full bg-[#f3ead0]" />+ <svg+ viewBox="0 0 100 56"+ preserveAspectRatio="none"+ aria-hidden+ className="absolute inset-x-0 bottom-0 h-[62%] w-full"+ >+ <polygon points="0,56 30,8 60,56" fill="#17293c" />+ <polygon points="38,56 70,22 100,52 100,56" fill="#1f3a4d" />+ </svg>+ </>+ );+ }+ return (+ <>+ <span className="absolute inset-0 bg-[linear-gradient(165deg,#6ea8f5_0%,#a97ee0_55%,#f0a12e_100%)]" />+ <span className="absolute top-[12%] left-[14%] size-[34%] rounded-full bg-[#fdf0c2]" />+ <svg+ viewBox="0 0 100 56"+ preserveAspectRatio="none"+ aria-hidden+ className="absolute inset-x-0 bottom-0 h-[62%] w-full"+ >+ <polygon points="0,56 30,8 60,56" fill="#255c3f" />+ <polygon points="38,56 70,22 100,52 100,56" fill="#3a7a52" />+ </svg>+ </>+ );+}++/** What an effect does to the picture: the same preview state the canvas pass+ * reads, applied over the swatch scene. */export function EffectSwatch({id,t = SWATCH_T,+ frame = null,className,}: {id: EffectId;t?: number;+ /** The frame under the playhead as a data URL; null shows the stand-in. */+ frame?: string | null;className?: string;}) {const st = effectPreviewState(id, 0.9, t);+ const grainUrl = grainTileUrl();const wash = st.washes?.[0];+ // Filter blur radii are design px against the full frame; the swatch is a+ // small fraction of one, so the same radius smears it to a wash. Scale the+ // radius to the tile so the picture stays readable through the blur.+ const filter = (st.cssFilter || "").replace(+ /blur\(([\d.]+)px\)/,+ (_, n) => `blur(${(Number(n) * 0.15).toFixed(2)}px)`+ );// The shake's offset is in design pixels against a 1080 short side; the- // swatch is a fraction of that, so it needs the room exaggerated to read.- const pct = (px: number) => (px / 1080) * 800;+ // swatch is a fraction of that, so the offset is scaled up just enough to+ // read as a tremble at tile size.+ const pct = (px: number) => (px / 1080) * 40;const shake =st.dx || st.dy || st.zoom? `translate(${pct(st.dx ?? 0).toFixed(2)}%, ${pct(st.dy ?? 0).toFixed(2)}%) scale(${st.zoom ?? 1})`: undefined;// A zoom scales about the point it holds; everything else about the middle.const origin = st.origin ? `${st.origin.x * 100}% ${st.origin.y * 100}%` : undefined;- const scene = "absolute inset-0 bg-[linear-gradient(135deg,#5b7cfa_0%,#c04cc0_55%,#f0a12e_100%)]";return (<span className={cn("relative block overflow-hidden rounded-md bg-black", className)}>{!!st.ghostFrac && (<span- className={cn(scene, "opacity-60 mix-blend-screen")}+ className="absolute inset-0 opacity-60 mix-blend-screen"style={{ transform: `translateX(${(st.ghostFrac * 900).toFixed(2)}%)` }}- />+ >+ <SwatchScene frame={frame} />+ </span>)}<span- className={scene}- style={{ filter: st.cssFilter || undefined, transform: shake, transformOrigin: origin }}+ className="absolute inset-0"+ style={{ filter: filter || undefined, transform: shake, transformOrigin: origin }}>- <span className="absolute top-1/4 left-[18%] size-1/3 rounded-full bg-white/85" />+ <SwatchScene frame={frame} /></span>- {!!st.grain && (+ {!!st.grain && grainUrl && (<span- className="absolute inset-0 bg-[radial-gradient(circle_at_1px_1px,#fff_0.5px,transparent_0)] bg-[length:3px_3px]"- style={{ opacity: Math.min(0.9, st.grain * 3) }}+ className="cut-grain absolute inset-0"+ style={{ opacity: st.grain, backgroundImage: `url(${grainUrl})` }}/>)}{!!st.vignette && st.vignette > 0 && (@@ -193,9 +368,16 @@ export function EffectSwatch({}}/>)}+ {st.leak && (+ <span+ className="absolute inset-0 mix-blend-screen"+ style={{ opacity: st.leak.alpha, background: leakGradient(st.leak.x, st.leak.y) }}+ />+ )}{!!st.flash && (<span className="absolute inset-0 bg-white" style={{ opacity: Math.min(0.75, st.flash) }} />)}</span>);}+diff --git a/site/src/cut/components/StageEffects.tsx b/site/src/cut/components/StageEffects.tsxindex 6008371a..8e43beec 100644--- a/site/src/cut/components/StageEffects.tsx+++ b/site/src/cut/components/StageEffects.tsx@@ -1,10 +1,16 @@"use client";import { useMemo } from "react";-import { effectPreviewState, type EffectPreviewState } from "@donkeycut/effects-kit";+import {+ effectPreviewState,+ grainTileUrl,+ leakGradient,+ type EffectPreviewState,+} from "@donkeycut/effects-kit";import { useEditor } from "@/cut/lib/store";import { isEffectOverlay, laneOf } from "@/cut/lib/types";import type { LiveEffect } from "@/cut/lib/effectStack";+import "./grain.css";/*** Effect elements in the preview's stack.@@ -57,17 +63,19 @@ export function useEffectLanes(): number[] {* them and under everything above. */export function StageEffectPaint({ states }: { states: EffectPreviewState[] }) {if (states.length === 0) return null;+ const grainUrl = grainTileUrl();const grain = Math.max(0, ...states.map((s) => s.grain ?? 0));const vignette = Math.max(0, ...states.map((s) => s.vignette ?? 0));const flash = Math.max(0, ...states.map((s) => s.flash ?? 0));const washes = states.flatMap((s) => s.washes ?? []);- if (!grain && !vignette && !flash && washes.length === 0) return null;+ const leaks = states.flatMap((s) => (s.leak ? [s.leak] : []));+ if (!grain && !vignette && !flash && washes.length === 0 && leaks.length === 0) return null;return (<div className="pointer-events-none absolute inset-0">- {grain > 0 && (+ {grain > 0 && grainUrl && (<div- className="absolute inset-0 bg-[radial-gradient(circle_at_1px_1px,#fff_0.6px,transparent_0)] bg-[length:3px_3px]"- style={{ opacity: grain }}+ className="cut-grain absolute inset-0"+ style={{ opacity: grain, backgroundImage: `url(${grainUrl})` }}/>)}{vignette > 0 && (@@ -78,6 +86,13 @@ export function StageEffectPaint({ states }: { states: EffectPreviewState[] }) {}}/>)}+ {leaks.map((l, i) => (+ <div+ key={`leak-${i}`}+ className="absolute inset-0 mix-blend-screen"+ style={{ opacity: l.alpha, background: leakGradient(l.x, l.y) }}+ />+ ))}{washes.map((w, i) => (<divkey={i}diff --git a/site/src/cut/components/TransitionsPanel.tsx b/site/src/cut/components/TransitionsPanel.tsxindex 0871dd7b..bb46026c 100644--- a/site/src/cut/components/TransitionsPanel.tsx+++ b/site/src/cut/components/TransitionsPanel.tsx@@ -1,27 +1,7 @@"use client";-import { useEffect, useRef, useState } from "react";-import {- ArrowDown,- ArrowDownToLine,- ArrowLeft,- ArrowLeftToLine,- ArrowRight,- ArrowRightToLine,- ArrowUp,- ArrowUpToLine,- Blend,- Circle,- Droplets,- Expand,- FoldHorizontal,- Moon,- Sun,- Target,- Trash2,- UnfoldHorizontal,- type LucideIcon,-} from "lucide-react";+import { useEffect, useMemo, useRef, useState } from "react";+import { Trash2 } from "lucide-react";import {Select,SelectContent,@@ -30,11 +10,11 @@ import {SelectValue,} from "@/components/ui/select";import { Slider } from "@/components/ui/slider";-import { Tile } from "@/cut/components/PanelTile";+import { SwatchScene, useSwatchClock } from "@/cut/components/EffectsPanel";import { parseSecondsInput, ScrubValue } from "@/cut/components/ScrubValue";import { SectionTitle } from "@/cut/components/SectionTitle";import { clearElementDrag, setElementDragData } from "@/cut/lib/assetDrag";-import { PICKED_RING, useAssetPick } from "@/cut/lib/assetPick";+import { PICKED_RING, pickGridNav, useAssetPick } from "@/cut/lib/assetPick";import { getClipSpans, resolveTransitions, useEditor } from "@/cut/lib/store";import {ANIM_DEFAULT_SECONDS,@@ -44,34 +24,15 @@ import {TRANSITION_STYLE_GROUPS,TRANSITION_STYLE_IDS,TRANSITION_STYLE_LABELS,- type AnimStyle,+ type MediaAsset,type TimelineTransition,type TransitionStyle,type VideoClip,+ type AnimStyle,} from "@/cut/lib/types";import { cn } from "@/lib/utils";import { ScrollArea } from "@/components/ui/scroll-area";-const TILE_ICONS: Record<TransitionStyle, LucideIcon> = {- crossfade: Blend,- crosszoom: Expand,- dipblack: Moon,- dipwhite: Sun,- blur: Droplets,- pushleft: ArrowLeft,- pushright: ArrowRight,- pushup: ArrowUp,- pushdown: ArrowDown,- wipeleft: ArrowLeftToLine,- wiperight: ArrowRightToLine,- wipeup: ArrowUpToLine,- wipedown: ArrowDownToLine,- circleopen: Circle,- circleclose: Target,- splitopen: UnfoldHorizontal,- splitclose: FoldHorizontal,-};-/*** The Transitions tab: how one clip hands over to the next, and how a clip* enters and leaves on its own.@@ -103,39 +64,97 @@ export function TransitionsPanel() {}) ?? null);});+ const { a, b } = useCutFrames();return (<>- <div className="flex h-12 shrink-0 items-center pr-2.5 pl-4">- <span className="text-sm font-semibold tracking-tight">Transitions</span>- </div>-- <ScrollArea className="min-h-0 flex-1" contentClassName="px-3.5 pb-4">+ {/* No header row. The top padding clears the side panel's floating+ close button: the first group's title runs beside it on the left,+ and the first tile row starts below it. */}+ <ScrollArea className="min-h-0 flex-1" contentClassName="px-3.5 pt-5 pb-4"><SelectedClip />- {TRANSITION_STYLE_GROUPS.map((g) => (- <section key={g.label} className="mb-3 flex flex-col gap-1.5">- <SectionTitle>{g.label}</SectionTitle>- <div className="grid grid-cols-2 gap-1.5">- {g.ids.map((id) => (- <TransitionTile key={id} style={id} live={live} />- ))}- </div>- </section>- ))}+ {/* One key handler over every group, so arrows walk the whole list+ across section boundaries. It wraps only the tile grids — the+ selected clip's sliders and selects keep their own arrow keys. */}+ <div onKeyDown={pickGridNav}>+ {TRANSITION_STYLE_GROUPS.map((g) => (+ <section key={g.label} className="mb-3 flex flex-col gap-1.5">+ <SectionTitle>{g.label}</SectionTitle>+ <div className="grid grid-cols-2 gap-2">+ {g.ids.map((id) => (+ <TransitionTile key={id} style={id} live={live} a={a} b={b} />+ ))}+ </div>+ </section>+ ))}+ </div></ScrollArea></>);}+/** The frame an asset shows at `srcT` seconds into its source: the nearest+ * filmstrip thumb for video, the picture itself for an image. */+function frameAt(asset: MediaAsset, srcT: number): string | null {+ if (asset.thumbs?.length) {+ const step = asset.thumbStep || 1;+ const i = Math.max(0, Math.min(asset.thumbs.length - 1, Math.round(srcT / step)));+ return asset.thumbs[i];+ }+ if (asset.type === "image") return asset.url;+ return null;+}++/** The two frames either side of the cut nearest the playhead — the real+ * footage a transition dropped there would blend. Null sides fall back to the+ * tiles' stand-in scenes. */+function useCutFrames(): { a: string | null; b: string | null } {+ const clips = useEditor((s) => s.clips);+ const assets = useEditor((s) => s.assets);+ // Re-pick the cut as the playhead crosses half-second marks.+ const tick = useEditor((s) => Math.round(s.currentTime * 2));+ return useMemo(() => {+ const spans = getClipSpans(clips, assets);+ let best: { a: string | null; b: string | null } | null = null;+ let bestDist = Infinity;+ for (let i = 0; i + 1 < spans.length; i++) {+ const out = spans[i];+ const inc = spans[i + 1];+ const cut = inc.start;+ const dist = Math.abs(tick / 2 - cut);+ if (dist >= bestDist) continue;+ bestDist = dist;+ best = {+ a: frameAt(out.asset, out.clip.in + out.len * (out.clip.speed ?? 1)),+ b: frameAt(inc.asset, inc.clip.in),+ };+ }+ return best ?? { a: null, b: null };+ }, [clips, assets, tick]);+}++/** How a transition tile's loop spends its time: a beat on the first shot,+ * the handover, a beat on the second. */+const X_LOOP = 2.4;+const X_HOLD = 0.5;+const X_RUN = 1.2;+function TransitionTile({style,live,+ a,+ b,}: {style: TransitionStyle;live: TimelineTransition | null;+ a: string | null;+ b: string | null;}) {const { picked, pick } = useAssetPick(`transition:${style}`);const ref = useRef<HTMLButtonElement>(null);- const Icon = TILE_ICONS[style];+ // Hovering a tile starts its handover over from the top, so the pointer+ // never lands mid-blend waiting for the loop to come around.+ const [runEpoch, setRunEpoch] = useState(0);+ const t = useSwatchClock(true, X_LOOP, runEpoch);// What the selection means for this tile: it wears the ring when it is the// live bar's style, and a click swaps that bar onto it.const isLive = !!live && live.style === style;@@ -146,29 +165,219 @@ function TransitionTile({if (isLive) ref.current?.scrollIntoView({ block: "nearest" });}, [isLive]);return (- <Tile+ <buttonref={ref}- selected={marked}- label={TRANSITION_STYLE_LABELS[style]}- title={- live- ? `Change the selected transition to ${TRANSITION_STYLE_LABELS[style]}`- : `Drag ${TRANSITION_STYLE_LABELS[style]} onto the transition track`- }- // Scroll margin keeps the whole tile — selection ring included — clear- // of the scroller's edges when scrollIntoView lands it there.- className={cn("scroll-m-2", marked && PICKED_RING)}+ type="button"+ data-pick-id={`transition:${style}`}+ aria-pressed={marked}+ draggable+ onDragStart={(e) => setElementDragData(e, { kind: "transition", style })}+ onDragEnd={clearElementDrag}+ onPointerEnter={() => setRunEpoch((n) => n + 1)}+ onFocus={() => setRunEpoch((n) => n + 1)}onClick={() => {if (!live) return pick();if (!isLive) useEditor.getState().updateTransition(live.id, { style });previewBar(live);}}- draggable- onDragStart={(e) => setElementDragData(e, { kind: "transition", style })}- onDragEnd={clearElementDrag}+ // Scroll margin keeps the whole tile — selection ring included — clear+ // of the scroller's edges when scrollIntoView lands it there. The picked+ // ring is the focus indicator; the browser outline stays off.+ className="flex scroll-m-2 flex-col gap-1.5 text-[11px] font-medium text-muted-foreground outline-none transition-colors hover:text-foreground">- <Icon className="size-4" />- </Tile>+ <TransitionSwatch+ style={style}+ a={a}+ b={b}+ t={t}+ className={cn("h-24 w-full rounded-lg border border-border", marked && PICKED_RING)}+ />+ <span className="leading-none">{TRANSITION_STYLE_LABELS[style]}</span>+ </button>+ );+}++/** One full-tile layer of the handover — a shot, transformed or clipped as+ * the style's moment demands. */+function Layer({+ frame,+ variant,+ style,+}: {+ frame: string | null;+ variant: "day" | "dusk";+ style?: React.CSSProperties;+}) {+ return (+ <span className="absolute inset-0 overflow-hidden" style={style}>+ <SwatchScene frame={frame} variant={variant} />+ </span>+ );+}++/** The handover itself, played on the two shots: each style renders its own+ * moment at progress `p` — sliding, wiping, dipping or blending shot A into+ * shot B the way the real render does. */+function TransitionSwatch({+ style,+ a,+ b,+ t,+ className,+}: {+ style: TransitionStyle;+ a: string | null;+ b: string | null;+ t: number;+ className?: string;+}) {+ const p0 = Math.min(1, Math.max(0, (t - X_HOLD) / X_RUN));+ const p = p0 * p0 * (3 - 2 * p0);+ const pc = (n: number) => `${(n * 100).toFixed(1)}%`;+ const A = (s?: React.CSSProperties) => <Layer frame={a} variant="day" style={s} />;+ const B = (s?: React.CSSProperties) => <Layer frame={b} variant="dusk" style={s} />;+ let layers: React.ReactNode;+ switch (style) {+ case "crossfade":+ layers = (+ <>+ {A()}+ {B({ opacity: p })}+ </>+ );+ break;+ case "crosszoom":+ layers = (+ <>+ {A({ transform: `scale(${(1 + 0.4 * p).toFixed(3)})` })}+ {B({ opacity: p, transform: `scale(${(1.4 - 0.4 * p).toFixed(3)})` })}+ </>+ );+ break;+ case "dipblack":+ case "dipwhite":+ layers = (+ <>+ {p < 0.5 ? A() : B()}+ <span+ className="absolute inset-0"+ style={{+ background: style === "dipblack" ? "#000" : "#fff",+ opacity: 1 - Math.abs(2 * p - 1),+ }}+ />+ </>+ );+ break;+ case "blur":+ layers = (+ <>+ {A({ filter: `blur(${(p * 3).toFixed(2)}px)` })}+ {B({ opacity: p, filter: `blur(${((1 - p) * 3).toFixed(2)}px)` })}+ </>+ );+ break;+ case "pushleft":+ layers = (+ <>+ {A({ transform: `translateX(${pc(-p)})` })}+ {B({ transform: `translateX(${pc(1 - p)})` })}+ </>+ );+ break;+ case "pushright":+ layers = (+ <>+ {A({ transform: `translateX(${pc(p)})` })}+ {B({ transform: `translateX(${pc(-(1 - p))})` })}+ </>+ );+ break;+ case "pushup":+ layers = (+ <>+ {A({ transform: `translateY(${pc(-p)})` })}+ {B({ transform: `translateY(${pc(1 - p)})` })}+ </>+ );+ break;+ case "pushdown":+ layers = (+ <>+ {A({ transform: `translateY(${pc(p)})` })}+ {B({ transform: `translateY(${pc(-(1 - p))})` })}+ </>+ );+ break;+ case "wipeleft":+ layers = (+ <>+ {A()}+ {B({ clipPath: `inset(0 0 0 ${pc(1 - p)})` })}+ </>+ );+ break;+ case "wiperight":+ layers = (+ <>+ {A()}+ {B({ clipPath: `inset(0 ${pc(1 - p)} 0 0)` })}+ </>+ );+ break;+ case "wipeup":+ layers = (+ <>+ {A()}+ {B({ clipPath: `inset(${pc(1 - p)} 0 0 0)` })}+ </>+ );+ break;+ case "wipedown":+ layers = (+ <>+ {A()}+ {B({ clipPath: `inset(0 0 ${pc(1 - p)} 0)` })}+ </>+ );+ break;+ case "circleopen":+ layers = (+ <>+ {A()}+ {B({ clipPath: `circle(${(p * 72).toFixed(1)}% at 50% 50%)` })}+ </>+ );+ break;+ case "circleclose":+ layers = (+ <>+ {B()}+ {A({ clipPath: `circle(${((1 - p) * 72).toFixed(1)}% at 50% 50%)` })}+ </>+ );+ break;+ case "splitopen":+ layers = (+ <>+ {A()}+ {B({ clipPath: `inset(0 ${pc((1 - p) / 2)})` })}+ </>+ );+ break;+ case "splitclose":+ layers = (+ <>+ {B()}+ {A({ clipPath: `inset(0 ${pc(p / 2)})` })}+ </>+ );+ break;+ }+ return (+ <span className={cn("relative block overflow-hidden rounded-md bg-black", className)}>+ {layers}+ </span>);}diff --git a/site/src/cut/components/grain.css b/site/src/cut/components/grain.cssnew file mode 100644index 00000000..c16b03e7--- /dev/null+++ b/site/src/cut/components/grain.css@@ -0,0 +1,31 @@+/* Film grain for DOM surfaces (the preview stage and the effect tiles): the+ element's background-image is the effects-kit grain tile (grainTileUrl, set+ inline), overlay-blended so grain holds in the midtones, jumping to a new+ offset a dozen times a second so it boils. The effect's amount sets the+ layer's opacity inline. */+.cut-grain {+ background-size: 256px 256px;+ mix-blend-mode: overlay;+ animation: cut-grain-boil 0.5s steps(1) infinite;+}++@keyframes cut-grain-boil {+ 0% {+ background-position: 0px 0px;+ }+ 17% {+ background-position: 96px 37px;+ }+ 33% {+ background-position: 201px 153px;+ }+ 50% {+ background-position: 58px 219px;+ }+ 67% {+ background-position: 173px 90px;+ }+ 83% {+ background-position: 33px 141px;+ }+}