Open source CapCut alternative.
TypeScript
feat(site): badge and pulse AI generations that finish off-panel
David Lee418d4eb2165
diff --git a/site/src/cut/components/AudioPanel.tsx b/site/src/cut/components/AudioPanel.tsxindex e172766e..25467740 100644--- a/site/src/cut/components/AudioPanel.tsx+++ b/site/src/cut/components/AudioPanel.tsx@@ -42,6 +42,7 @@ import {type LibraryAsset,} from "@/cut/lib/library";import { creditsUrl, signInUrl, useSignedIn } from "@/cut/lib/generate";+import { genPulseOverlay, useGenNotify } from "@/cut/lib/genNotify";import { enrichAsset } from "@/cut/lib/media";import { usePreviewAudio } from "@/cut/lib/previewAudio";import { useEditor } from "@/cut/lib/store";@@ -117,7 +118,9 @@ function VoiceGenerator({ projectId }: { projectId: string }) {const language = useSpeechLanguage();const [script, setScript] = useState("");const [direction, setDirection] = useState("");- const [busy, setBusy] = useState(false);+ // How many syntheses are in flight — several can run at once, so the button+ // stays live and this just drives the status row below it.+ const [pending, setPending] = useState(0);// `credits` marks a failure caused by an empty balance, which renders with a// link to buy more.const [error, setError] = useState<{ text: string; credits?: boolean } | null>(null);@@ -136,7 +139,7 @@ function VoiceGenerator({ projectId }: { projectId: string }) {const generate = async () => {const text = script.trim();if (!text) return;- setBusy(true);+ setPending((p) => p + 1);setError(null);try {const playhead = useEditor.getState().currentTime;@@ -160,7 +163,7 @@ function VoiceGenerator({ projectId }: { projectId: string }) {} catch (e) {fail(e, "Voice generation failed.");} finally {- setBusy(false);+ setPending((p) => p - 1);}};@@ -245,13 +248,19 @@ function VoiceGenerator({ projectId }: { projectId: string }) {/><ButtonclassName="voice-generate w-full"- disabled={!script.trim() || busy || signedOut}+ disabled={!script.trim() || signedOut}title={!script.trim() ? "Write a script above to generate" : undefined}onClick={() => void generate()}>- {busy ? <Loader2 className="animate-spin" /> : <AudioLines data-icon="inline-start" />}+ <AudioLines data-icon="inline-start" />Generate audio</Button>+ {pending > 0 && (+ <div className="flex items-center gap-2 text-[11px] text-muted-foreground">+ <Loader2 className="size-3.5 shrink-0 animate-spin" />+ {pending === 1 ? "Generating…" : `Generating ${pending}…`}+ </div>+ )}</div>{signedOut ? (@@ -402,6 +411,7 @@ export function AudioRow({onAdd,menu,onDragStart,+ pulse,}: {name: string;duration: number;@@ -414,6 +424,8 @@ export function AudioRow({menu?: ReactNode;/** Present when the row can be dragged onto the timeline. */onDragStart?: DragEventHandler<HTMLDivElement>;+ /** A freshly-generated clip the user hasn't seen — pulses blue for a beat. */+ pulse?: boolean;}) {return (<AudioPillSurface@@ -468,6 +480,7 @@ export function AudioRow({<Plus className="size-3" /></button></div>+ {pulse && <div aria-hidden className={genPulseOverlay} />}</AudioPillSurface>);}@@ -485,6 +498,7 @@ function ProjectAudio({}) {const assets = useEditor((s) => s.assets);const audio = assets.filter((a) => a.type === "audio" && a.origin === "voiceover");+ const pulsing = useGenNotify((s) => s.pulsing.audio);return (<div className="flex flex-col gap-1.5"><SectionTitle>Generated audio</SectionTitle>@@ -502,6 +516,7 @@ function ProjectAudio({url={a.url}peaks={a.peaks}playing={playingUrl === a.url}+ pulse={pulsing.includes(a.id)}onTogglePlay={onTogglePlay}onAdd={() => useEditor.getState().addAudioFromAsset(a.id)}menu={diff --git a/site/src/cut/components/GeneratePanel.tsx b/site/src/cut/components/GeneratePanel.tsxindex 23339238..1325955b 100644--- a/site/src/cut/components/GeneratePanel.tsx+++ b/site/src/cut/components/GeneratePanel.tsx@@ -12,6 +12,7 @@ import {useRefCandidates,useAssetDrop,} from "@/cut/lib/assetRef";+import { genPulseOverlay, useGenPulse } from "@/cut/lib/genNotify";import { signInUrl, useGenerate, useSignedIn, type GenerateJob } from "@/cut/lib/generate";import { useLightbox } from "@/cut/lib/lightbox";import { refsFromDroppedFiles } from "@/cut/lib/refMedia";@@ -277,6 +278,7 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {* stay a compact status row. */function JobRow({ job, handle }: { job: GenerateJob; handle?: string }) {const asset = useEditor((s) => s.assets.find((a) => a.id === job.assetId));+ const pulse = useGenPulse("video", job.assetId);const tileRef = useRef<HTMLDivElement>(null);const videoRef = useRef<HTMLVideoElement>(null);@@ -417,6 +419,7 @@ function JobRow({ job, handle }: { job: GenerateJob; handle?: string }) {}/></div>+ {pulse && <div aria-hidden className={genPulseOverlay} />}</div>);}diff --git a/site/src/cut/components/ImageGenPanel.tsx b/site/src/cut/components/ImageGenPanel.tsxindex ef4f099d..70e1c37b 100644--- a/site/src/cut/components/ImageGenPanel.tsx+++ b/site/src/cut/components/ImageGenPanel.tsx@@ -7,6 +7,7 @@ import { DropdownMenuItem } from "@/components/ui/dropdown-menu";import { SectionTitle } from "@/cut/components/SectionTitle";import { clearAssetDrag, setAssetDragData } from "@/cut/lib/assetDrag";import { collectRefs, mentionToken, useRefCandidates, useAssetDrop } from "@/cut/lib/assetRef";+import { genPulseOverlay, useGenPulse } from "@/cut/lib/genNotify";import { signInUrl, useGenerate, useSignedIn } from "@/cut/lib/generate";import {IMAGE_RESOLUTION_LABEL,@@ -20,8 +21,10 @@ import { useEditor } from "@/cut/lib/store";import type { MediaAsset } from "@/cut/lib/types";import { cn } from "@/lib/utils";import { MentionTextarea, RefChips, RefHandlePill } from "./AssetRefs";+import { cardIconButton } from "./iconButton";import { PillSelect } from "./PillSelect";import { GeneratedAssetMenu } from "./GeneratedAssetMenu";+import { HostedErrorText } from "./hostedError";// The generate-image panel: an always-on column in the Image tab, sitting left// of the stock browser. Clicking a stock tile loads its saved prompt here; the@@ -54,9 +57,8 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {const { prompt, aspect, resolution, refs } = useImageGen();const signedIn = useSignedIn();const candidates = useRefCandidates();- const job = useGenerate((s) =>- s.jobs.find((j) => j.kind === "image" && j.projectId === projectId)- );+ const allJobs = useGenerate((s) => s.jobs);+ const jobs = allJobs.filter((j) => j.kind === "image" && j.projectId === projectId);// Select the stable `assets` reference and derive here: filtering inside the// selector returns a fresh array every store write (including usePlayback's// per-frame ticks) and would re-render the panel constantly. Newest first.@@ -152,14 +154,10 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {<ButtonclassName="w-full shrink-0"- disabled={!prompt.trim() || signedIn === false || job?.status === "running"}+ disabled={!prompt.trim() || signedIn === false}onClick={go}>- {job?.status === "running" ? (- <Loader2 data-icon="inline-start" className="animate-spin" />- ) : (- <Sparkles data-icon="inline-start" />- )}+ <Sparkles data-icon="inline-start" />Generate image</Button>@@ -173,26 +171,38 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {</p>)}- {/* A generation in flight (or a failed one): the finished asset drops- into the list below, so only surface the transient states here. */}- {job && job.status !== "done" && (- <div className="flex shrink-0 items-center gap-2">- {job.status === "running" && (- <Loader2 className="size-3.5 shrink-0 animate-spin text-muted-foreground" />- )}- <div className="min-w-0 flex-1">- <div className="truncate text-[11.5px] font-medium">{job.prompt}</div>- <div- className={cn(- "text-[10.5px] leading-snug break-words",- job.status === "error" ? "text-red-600" : "text-muted-foreground"- )}- >- {job.status === "running" ? "Generating…" : (job.error ?? "Failed.")}+ {/* Generations in flight (or failed): a finished asset drops into the+ list below, so only the transient states row here. Several can run+ at once — the button stays live while they render. */}+ {jobs+ .filter((j) => j.status !== "done")+ .map((j) => (+ <div key={j.id} className="group flex shrink-0 items-center gap-2">+ {j.status === "running" && (+ <Loader2 className="size-3.5 shrink-0 animate-spin text-muted-foreground" />+ )}+ <div className="min-w-0 flex-1">+ <div className="truncate text-[11.5px] font-medium">{j.prompt}</div>+ <div+ className={cn(+ "text-[10.5px] leading-snug break-words",+ j.status === "error" ? "text-red-600" : "text-muted-foreground"+ )}+ >+ {j.status === "running" ? "Generating…" : <HostedErrorText error={j.error} />}+ </div></div>+ {j.status === "error" && (+ <button+ title="Dismiss"+ className={cn(cardIconButton, "opacity-0 group-hover:opacity-100")}+ onClick={() => useGenerate.getState().dismiss(j.id)}+ >+ <Trash2 className="size-3.5" />+ </button>+ )}</div>- </div>- )}+ ))}{generated.length > 0 && (<div className="flex shrink-0 flex-col gap-1.5">@@ -227,6 +237,7 @@ function GeneratedTile({handle?: string;}) {const tileRef = useRef<HTMLDivElement>(null);+ const pulse = useGenPulse("image", asset.id);return (<div ref={tileRef} className="group relative overflow-hidden rounded-lg"><button@@ -307,6 +318,7 @@ function GeneratedTile({}/></div>+ {pulse && <div aria-hidden className={genPulseOverlay} />}</div>);}diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsxindex 14991308..7d55297b 100644--- a/site/src/cut/components/SidePanel.tsx+++ b/site/src/cut/components/SidePanel.tsx@@ -33,6 +33,7 @@ import {type LibraryFolder,} from "@/cut/lib/library";import type { LibraryTemplate } from "@/cut/lib/types";+import { isGenTab, useGenNotify, useWatchGenTab } from "@/cut/lib/genNotify";import { CAPTION_LIMIT, normalizeTags } from "@/cut/lib/publish";import { useEditor } from "@/cut/lib/store";import { formatTime } from "@/cut/lib/time";@@ -80,6 +81,10 @@ export function SidePanel({const [tab, setTab] = useLocalPref<Tab>("cut-side-tab", "media", (v) =>TABS.some((t) => t.id === v));+ // Generations that finished while their tab was closed: a blue count rides+ // the rail icon, and opening the tab lets the new tiles pulse for a beat.+ const unseen = useGenNotify((s) => s.unseen);+ useWatchGenTab(tab, projectId);// Clicking a reference token anywhere jumps here: switch to the tab that// owns the asset; the matching card scrolls into view and flashes.@@ -100,17 +105,24 @@ export function SidePanel({{/* Icon rail */}<div className="flex w-[68px] shrink-0 flex-col items-center gap-1 border-r border-border py-3">{TABS.map(({ id, label, icon: Icon }) => {+ // The open tab never badges — its completions are already on screen.+ const unseenCount = isGenTab(id) && id !== tab ? unseen[id].length : 0;const tileClass ="flex flex-col items-center gap-1 rounded-lg px-2 py-1.5 text-muted-foreground transition-colors hover:text-foreground";const inner = (<><spanclassName={cn(- "grid size-9 place-items-center rounded-lg transition-colors",+ "relative grid size-9 place-items-center rounded-lg transition-colors",tab === id ? "bg-muted text-foreground" : "hover:bg-muted/60")}><Icon className="size-4.5" />+ {unseenCount > 0 && (+ <span className="absolute -top-1 -right-1 grid h-[15px] min-w-[15px] place-items-center rounded-full bg-[#0a84ff] px-1 text-[9px] leading-none font-semibold text-white tabular-nums ring-2 ring-card">+ {unseenCount}+ </span>+ )}</span><span className={cn("text-[10px] font-medium", tab === id && "text-foreground")}>{label}diff --git a/site/src/cut/lib/genNotify.css b/site/src/cut/lib/genNotify.cssnew file mode 100644index 00000000..528ee884--- /dev/null+++ b/site/src/cut/lib/genNotify.css@@ -0,0 +1,19 @@+/* Cut generation notifications: a tile whose generation finished while the user+ was on another tab breathes a soft blue ring until its panel has been open+ for a moment. Loaded by genNotify.ts, which owns the `cut-gen-pulse` class. */+@keyframes cut-gen-pulse {+ 0%,+ 100% {+ opacity: 1;+ }+ 50% {+ opacity: 0.25;+ }+}++.cut-gen-pulse {+ animation: cut-gen-pulse 1.7s ease-in-out infinite;+ box-shadow:+ inset 0 0 0 2px rgba(10, 132, 255, 0.85),+ inset 0 0 14px rgba(10, 132, 255, 0.3);+}diff --git a/site/src/cut/lib/genNotify.ts b/site/src/cut/lib/genNotify.tsnew file mode 100644index 00000000..e1bf5300--- /dev/null+++ b/site/src/cut/lib/genNotify.ts@@ -0,0 +1,97 @@+"use client";++import { useEffect } from "react";+import { create } from "zustand";+// The pulse keyframes + ring live in a co-located stylesheet, pulled into the+// client bundle here — the single module every consumer of `genPulseOverlay`+// already imports, so the styles load exactly where the overlay is used.+import "./genNotify.css";++// AI generations outlive the panel that started them — several can render at+// once while the user edits elsewhere. This store notices the ones that finish+// unwatched: the side rail badges each generate tab with a blue count, and+// opening that tab clears the count and lets the freshly-arrived tiles pulse+// blue for a few seconds so the eye lands on them.++export type GenTab = "video" | "image" | "audio";++export const isGenTab = (v: string): v is GenTab =>+ v === "video" || v === "image" || v === "audio";++/** How long a tab's new tiles keep pulsing once it opens. */+const PULSE_MS = 4500;++/** Overlay for a freshly-arrived tile: a soft blue ring breathing over the+ * media. Drop it as the last child of a `relative overflow-hidden rounded-*`+ * tile. */+export const genPulseOverlay =+ "cut-gen-pulse pointer-events-none absolute inset-0 rounded-[inherit]";++const EMPTY: Record<GenTab, string[]> = { video: [], image: [], audio: [] };++interface GenNotifyState {+ /** Finished-while-away asset ids per tab — the rail badge counts these. */+ unseen: Record<GenTab, string[]>;+ /** The just-opened tab's arrivals, pulsing until their timer clears them. */+ pulsing: Record<GenTab, string[]>;+ /** The generate tab on screen; a completion here needs no badge or pulse —+ * the user watched the tile appear. */+ watching: GenTab | null;+ landed: (tab: GenTab, assetId: string) => void;+ watch: (tab: GenTab | null) => void;+ endPulse: (tab: GenTab) => void;+ reset: () => void;+}++export const useGenNotify = create<GenNotifyState>((set, get) => ({+ unseen: EMPTY,+ pulsing: EMPTY,+ watching: null,+ landed: (tab, assetId) => {+ if (get().watching === tab) return; // watched live — no badge, no pulse+ set((s) => ({ unseen: { ...s.unseen, [tab]: [...s.unseen[tab], assetId] } }));+ },+ // Opening a tab clears its badge and hands its arrivals to the pulse set, so+ // leaving before the pulse ends never brings the count back — they're seen.+ watch: (tab) =>+ set((s) => {+ if (tab && isGenTab(tab) && s.unseen[tab].length > 0) {+ return {+ watching: tab,+ pulsing: { ...EMPTY, [tab]: s.unseen[tab] },+ unseen: { ...s.unseen, [tab]: [] },+ };+ }+ // Any other switch just drops whatever was pulsing — one tab pulses at a time.+ return { watching: tab, pulsing: EMPTY };+ }),+ endPulse: (tab) =>+ set((s) => (s.pulsing[tab].length === 0 ? {} : { pulsing: { ...s.pulsing, [tab]: [] } })),+ reset: () => set({ unseen: EMPTY, pulsing: EMPTY }),+}));++/** Whether this finished tile is in its tab's fresh-arrival pulse. */+export function useGenPulse(tab: GenTab, assetId?: string): boolean {+ return useGenNotify((s) => (assetId ? s.pulsing[tab].includes(assetId) : false));+}++/** Wire the side rail in: track which generate tab is open (so its completions+ * skip the badge), and let its fresh tiles pulse for a few seconds after it+ * opens. A project switch drops everything — the tiles belong to the project+ * that made them. */+export function useWatchGenTab(tab: string, projectId: string) {+ const genTab = isGenTab(tab) ? tab : null;+ const pulsing = useGenNotify((s) => (genTab ? s.pulsing[genTab].length > 0 : false));+ useEffect(() => {+ useGenNotify.getState().reset();+ }, [projectId]);+ useEffect(() => {+ useGenNotify.getState().watch(genTab);+ return () => useGenNotify.getState().watch(null);+ }, [genTab]);+ useEffect(() => {+ if (!genTab || !pulsing) return;+ const t = setTimeout(() => useGenNotify.getState().endPulse(genTab), PULSE_MS);+ return () => clearTimeout(t);+ }, [genTab, pulsing]);+}diff --git a/site/src/cut/lib/generate.ts b/site/src/cut/lib/generate.tsindex 00a3bd98..ee064450 100644--- a/site/src/cut/lib/generate.ts+++ b/site/src/cut/lib/generate.ts@@ -8,6 +8,7 @@ import { composeGenPrompt, foldTextRefs } from "./composeGen";import { hostedPost } from "./hosted";import { enrichAsset, importFileToProject } from "./media";import { refsToInlineImages, visualRefs, type InlineImage } from "./refMedia";+import { useGenNotify } from "./genNotify";import { useImageGen } from "./imageGen";import { useEditor } from "./store";import { mediaUrl, type MediaAsset } from "./types";@@ -352,7 +353,7 @@ export const useGenerate = create<GenerateState>((set, get) => {throw new Error(body.error ?? "Could not add the image to the project.");}const asset: MediaAsset = { ...body, url: mediaUrl(projectId, body.fileName) };- adopt(projectId, asset);+ if (adopt(projectId, asset)) useGenNotify.getState().landed("image", asset.id);update(job.id, { status: "done", assetId: asset.id });} catch (err) {fail(job.id, err);@@ -432,7 +433,10 @@ export const useGenerate = create<GenerateState>((set, get) => {if (!asset) throw new Error("Could not import the generated video.");asset.name = promptName(prompt);asset.origin = "generated"; // lives in the generate panel, not Media- if (adopt(projectId, asset)) opts?.onDone?.(asset);+ if (adopt(projectId, asset)) {+ useGenNotify.getState().landed("video", asset.id);+ opts?.onDone?.(asset);+ }update(job.id, { status: "done", assetId: asset.id });} catch (err) {fail(job.id, err);diff --git a/site/src/cut/lib/tts.ts b/site/src/cut/lib/tts.tsindex 7560fc1d..b6832817 100644--- a/site/src/cut/lib/tts.ts+++ b/site/src/cut/lib/tts.ts@@ -1,6 +1,7 @@"use client";import { geminiModels } from "@/lib/inference/gemini-models";+import { useGenNotify } from "./genNotify";import { importFileToProject } from "./media";import type { MediaAsset } from "./types";import {@@ -417,6 +418,9 @@ export async function speechClipToAsset(if (!asset) throw new Error("Could not save the voiceover into the project.");asset.name = label;asset.origin = "voiceover";+ // Every committed voiceover funnels through here (the panel, the subtitles+ // readout, the AI tool), so this is where a finished one gets its badge.+ useGenNotify.getState().landed("audio", asset.id);return asset;}