Open source CapCut alternative.
TypeScript
fix(site): harden chat cards, lightbox, and document rendering from review findings
David Lefb05f15dfcac
diff --git a/site/src/cut/components/ChatAssets.tsx b/site/src/cut/components/ChatAssets.tsxindex 1628069c..5db2b2f4 100644--- a/site/src/cut/components/ChatAssets.tsx+++ b/site/src/cut/components/ChatAssets.tsx@@ -1,20 +1,21 @@"use client";-import { useEffect, useRef, useState, type ReactNode } from "react";+import { useEffect, useRef, type ReactNode } from "react";import type React from "react";import { Copy, ExternalLink, FileText, Film, Loader2, Maximize2, Plus } from "lucide-react";import { DropdownMenuItem } from "@/components/ui/dropdown-menu";import { clearAssetDrag, setAssetDragData } from "@/cut/lib/assetDrag";import {+ projectRefs,refFromAsset,refToken,setRefDragData,- useRefFor,type AssetRef,type AssetRefKind,} from "@/cut/lib/assetRef";import { useGenerate } from "@/cut/lib/generate";import { lightboxItemFromRef, useLightbox } from "@/cut/lib/lightbox";+import { usePreviewAudio } from "@/cut/lib/previewAudio";import { useEditor } from "@/cut/lib/store";import { formatTime } from "@/cut/lib/time";import type { MediaAsset } from "@/cut/lib/types";@@ -22,6 +23,7 @@ import { cn } from "@/lib/utils";import { AudioRow } from "./AudioPanel";import { DocText, useDocText } from "./DocText";import { GeneratedAssetMenu } from "./GeneratedAssetMenu";+import { cardIconButton } from "./iconButton";// Assets rendered inside chat messages. Anything the assistant makes previews// here as a media-first card and stays in the chat until the user moves it:@@ -73,8 +75,9 @@ export function ToolOutputAssets({ output }: { output: unknown }) {}/** A video render the tool started but couldn't wait out: a live card that- * follows the generation job and becomes the clip's card when it lands. After- * a reload the job store is empty and the render's home is the Video panel. */+ * follows the generation job and becomes the clip's card when it lands.+ * Settled jobs persist per browser, so the card survives a reload; only a+ * render still in flight when the page closed has no card afterwards. */export function ChatVideoJobCard({ jobId }: { jobId: string }) {const job = useGenerate((s) => s.jobs.find((j) => j.id === jobId));if (!job) return null;@@ -125,7 +128,6 @@ const dragProps = (item: AssetRef, asset?: MediaAsset) => ({/** The chat card's "…" menu: timeline/expand/reference actions around the* shared move-to-Media/Library pair. Project assets only. */function ChatCardMenu({ asset, triggerClassName }: { asset: MediaAsset; triggerClassName: string }) {- const ref = useRefFor(asset.name);const projectId = useEditor((s) => s.projectId);if (!projectId) return null;return (@@ -148,9 +150,16 @@ function ChatCardMenu({ asset, triggerClassName }: { asset: MediaAsset; triggerC<Maximize2 /> Expand</DropdownMenuItem><DropdownMenuItem- onClick={() =>- void navigator.clipboard.writeText(refToken(ref ?? refFromAsset(asset))).catch(() => {})- }+ onClick={() => {+ // The session handle (v2, i1) is derived, not stored — resolve+ // it at click time instead of subscribing every card to it.+ const live = projectRefs(useEditor.getState().assets).find(+ (r) => r.id === asset.id+ );+ void navigator.clipboard+ .writeText(refToken(live ?? refFromAsset(asset)))+ .catch(() => {});+ }}><Copy /> Copy reference</DropdownMenuItem>@@ -228,30 +237,16 @@ function MediaCard({ item, asset }: ChatCardProps) {}/** Audio as the shared playable row (waveform, play, drag), with the chat menu- * on it; double-click opens the big player. */+ * on it; double-click opens the big player. Playback goes through the+ * app-wide preview player, so it stops other previews and vice versa. */function AudioCard({ item, asset }: ChatCardProps) {const ref = liveRef(item, asset);- const audioRef = useRef<HTMLAudioElement | null>(null);- const [playing, setPlaying] = useState(false);+ const playing = usePreviewAudio((s) => s.url === ref.url);+ // Only this card's own preview stops when the card goes away.useEffect(() => {- const el = audioRef.current;- return () => el?.pause();- }, []);- const toggle = () => {- let el = audioRef.current;- if (!el) {- el = new Audio(ref.url);- el.onended = () => setPlaying(false);- audioRef.current = el;- }- if (playing) {- el.pause();- setPlaying(false);- } else {- void el.play().catch(() => setPlaying(false));- setPlaying(true);- }- };+ const url = ref.url;+ return () => usePreviewAudio.getState().stop(url);+ }, [ref.url]);return (<divclassName="ai-chat-asset w-full max-w-[280px] bg-card"@@ -263,16 +258,9 @@ function AudioCard({ item, asset }: ChatCardProps) {url={ref.url}peaks={asset?.peaks}playing={playing}- onTogglePlay={toggle}+ onTogglePlay={(url) => usePreviewAudio.getState().toggle(url)}onAdd={() => asset && useEditor.getState().addAudioFromAsset(asset.id)}- menu={- asset && (- <ChatCardMenu- asset={asset}- triggerClassName="grid size-6 shrink-0 place-items-center rounded-full bg-muted text-foreground transition-all hover:bg-muted-foreground/20"- />- )- }+ menu={asset && <ChatCardMenu asset={asset} triggerClassName={cardIconButton} />}onDragStart={(e) => {if (asset) setAssetDragData(e, asset.id);else setRefDragData(e, item);diff --git a/site/src/cut/components/DocText.tsx b/site/src/cut/components/DocText.tsxindex d3eaa08c..7c1d8328 100644--- a/site/src/cut/components/DocText.tsx+++ b/site/src/cut/components/DocText.tsx@@ -18,6 +18,21 @@ export function docFormat(name: string): DocFormat {return "plain";}+/** One fetch per URL per session — cards remount on every thread switch and+ * the lightbox opens the same file, so the text is cached. A failed fetch is+ * not cached, leaving the next mount to retry. */+const docCache = new Map<string, Promise<string>>();++function fetchDoc(url: string): Promise<string> {+ let p = docCache.get(url);+ if (!p) {+ p = fetch(url).then((r) => (r.ok ? r.text() : Promise.reject(new Error(String(r.status)))));+ p.catch(() => docCache.delete(url));+ docCache.set(url, p);+ }+ return p;+}+/** The file's text, fetched once per URL. `failed` marks an unreadable file so* callers can show a plain error instead of an empty card. */export function useDocText(url: string): { text: string | null; failed: boolean } {@@ -28,8 +43,7 @@ export function useDocText(url: string): { text: string | null; failed: boolean);useEffect(() => {let alive = true;- fetch(url)- .then((r) => (r.ok ? r.text() : Promise.reject(new Error(String(r.status)))))+ fetchDoc(url).then((t) => alive && setState({ url, text: t, failed: false })).catch(() => alive && setState({ url, text: null, failed: true }));return () => {@@ -66,8 +80,11 @@ function parseRows(text: string, delim: string): string[][] {} else {cell += c;}- } else if (c === '"' && cell === "") {+ } else if (c === '"' && cell.trim() === "") {+ // Opens a quoted field even after leading whitespace (`a, "b, c"`),+ // which many exporters emit; the padding drops with the quote.quoted = true;+ cell = "";} else if (c === delim) {push();} else if (c === "\n") {diff --git a/site/src/cut/components/Lightbox.tsx b/site/src/cut/components/Lightbox.tsxindex 0e710946..1ac746ce 100644--- a/site/src/cut/components/Lightbox.tsx+++ b/site/src/cut/components/Lightbox.tsx@@ -1,10 +1,12 @@"use client";-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import { Check, Copy, FileText, Loader2, Music, Plus, X } from "lucide-react";import { Button } from "@/components/ui/button";+import { addLibraryAssetToProject, fetchLibrary } from "@/cut/lib/library";import { useLightbox, type LightboxItem } from "@/cut/lib/lightbox";import { importImage, importStockVideo } from "@/cut/lib/media";+import { usePreviewAudio } from "@/cut/lib/previewAudio";import { useEditor } from "@/cut/lib/store";import { DocText, useDocText } from "./DocText";import { PeakStrip } from "./AudioPanel";@@ -51,6 +53,12 @@ export function Lightbox() {} else {useEditor.getState().addClipFromAsset(item.assetId);}+ } else if (item.libraryId) {+ // Library media copies in through the library route, like using it+ // from the Library panel.+ const lib = (await fetchLibrary()).assets.find((a) => a.id === item.libraryId);+ if (!lib) throw new Error("Library asset not found.");+ await addLibraryAssetToProject(projectId, lib);} else {// A stock clip imports as footage; a stock image bakes into a still.const asset =@@ -67,9 +75,11 @@ export function Lightbox() {}};- // Audio without a project asset (a library ref) has nowhere direct to land;- // text never rides the timeline.- const canAdd = item.kind !== "text" && (item.kind !== "audio" || item.assetId !== null);+ // Text never rides the timeline; audio needs a project or library home to+ // land from.+ const canAdd =+ item.kind !== "text" &&+ (item.kind !== "audio" || item.assetId !== null || item.libraryId !== undefined);// With a known aspect the dialog width follows it — capped so the media// stays within 68vh tall and 860px/92vw wide — and the media box carries the@@ -187,13 +197,22 @@ function AudioBody({ item }: { item: LightboxItem }) {const asset = useEditor((s) =>item.assetId ? s.assets.find((a) => a.id === item.assetId) : undefined);+ const audioEl = useRef<HTMLAudioElement>(null);+ // The big player takes over from any row/card preview, and closing the+ // lightbox stops it — a detached media element can keep playing otherwise.+ // The element renders with the body, so it exists by the time this runs.+ useEffect(() => {+ usePreviewAudio.getState().stop();+ const el = audioEl.current;+ return () => el?.pause();+ }, []);return (<div className="flex flex-col gap-3 rounded-2xl bg-gradient-to-br from-emerald-500 to-emerald-700 p-5 pt-10 shadow-2xl"><Music className="size-8 text-white/90" />{asset?.peaks && asset.peaks.length > 0 && (<PeakStrip peaks={asset.peaks} className="h-10 text-white/85" />)}- <audio controls autoPlay src={item.src} className="w-full" />+ <audio ref={audioEl} controls autoPlay src={item.src} className="w-full" /></div>);}diff --git a/site/src/cut/lib/assetRef.ts b/site/src/cut/lib/assetRef.tsindex 7e620af1..343c6312 100644--- a/site/src/cut/lib/assetRef.ts+++ b/site/src/cut/lib/assetRef.ts@@ -302,13 +302,23 @@ export function useAssetDrop(let libraryCache: LibraryAsset[] | null = null;let libraryLoad: Promise<LibraryAsset[]> | null = null;+/** The open project's media as refs with their session handles, assigned in+ * media order — `v1` videos, `i1` generated stills, `a1` audio — so a prompt+ * can say `@v2` instead of the full name. Handles are derived, never stored:+ * anything that shows one resolves it from the current asset list. */+export function projectRefs(assets: MediaAsset[]): AssetRef[] {+ const counters = { v: 0, i: 0, a: 0 };+ return assets.map((a) => {+ const prefix = a.type === "image" ? "i" : a.type === "video" ? "v" : "a";+ counters[prefix] += 1;+ return { ...refFromAsset(a), handle: `${prefix}${counters[prefix]}` };+ });+}+/** Everything referenceable right now, in resolution order: the open project's* media, then the shared library, then the stock catalog. Names are unique* within the list (first scope wins) so a mention resolves to one asset.- *- * Project assets get short handles in media order — `v1` videos, `i1`- * generated stills, `a1` audio — so a prompt can say `@v2` instead of the full- * name. Library items mention by name; stock ids are already short (`@nature-dunes`). */+ * Library items mention by name; stock ids are already short (`@nature-dunes`). */export function useRefCandidates(): AssetRef[] {const assets = useEditor((s) => s.assets);const [lib, setLib] = useState<LibraryAsset[]>(libraryCache ?? []);@@ -325,12 +335,7 @@ export function useRefCandidates(): AssetRef[] {}, []);return useMemo(() => {- const counters = { v: 0, i: 0, a: 0 };- const project = assets.map((a) => {- const prefix = a.type === "image" ? "i" : a.type === "video" ? "v" : "a";- counters[prefix] += 1;- return { ...refFromAsset(a), handle: `${prefix}${counters[prefix]}` };- });+ const project = projectRefs(assets);const seen = new Set<string>();const out: AssetRef[] = [];for (const ref of [diff --git a/site/src/cut/lib/lightbox.ts b/site/src/cut/lib/lightbox.tsindex 30ae9026..9d37630c 100644--- a/site/src/cut/lib/lightbox.ts+++ b/site/src/cut/lib/lightbox.ts@@ -18,8 +18,11 @@ export interface LightboxItem {* up front so it opens at its final size instead of growing on media load. */aspect?: "16:9" | "9:16" | "1:1";/** For a project asset, its id (add straight to the timeline); null for a- * stock item, which the lightbox imports first. */+ * stock or library item, which the lightbox imports first. */assetId: string | null;+ /** For a library asset, its id — "Use" copies it in through the library+ * route so it files like any other library use, not as stock. */+ libraryId?: string;}/** The lightbox view of an asset ref — how chat cards and attachment chips@@ -30,6 +33,7 @@ export const lightboxItemFromRef = (ref: AssetRef): LightboxItem => ({name: ref.name,prompt: "",assetId: ref.scope === "project" ? ref.id : null,+ ...(ref.scope === "library" ? { libraryId: ref.id } : {}),});interface LightboxState {