Open source CapCut alternative.
TypeScript
feat(site): the Library lends fonts to every project [rebuild]
David Lec62b6bdeef46
diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.mdindex 6bc35ef9..c6a09f31 100644--- a/docs/guides/cut/README.md+++ b/docs/guides/cut/README.md@@ -52,6 +52,8 @@ Every client call goes through a backend seam (`site/src/cut/lib/backend/`): theThe library is the exception, because it is the user's one shelf across places: every residency keeps a library, and the Library lists them at once as one listing, newest first, with a badge saying which shelf each item is on. So a cloud project can pull a clip off this Mac, and a browser project can pull one out of the cloud. A shelf that lives in the page holds its media in the same origin-private storage its projects use, and a link imported onto it rides the cloud worker — a page can't fetch a video off a YouTube link — with the bytes coming back down and the staged cloud copy dropped after. The Mac's shelf takes that same route as a second try: sites refuse fetches on the strength of the tool making them, so a link the engine's own tools can't bring back is fetched by the worker and lands here anyway. Each shelf is remembered on its own, so the Library tab keeps listing the Mac's items with the app closed, read-only, and clicking one raises the same banner an unreachable local project does. The editor's library picker asks only for what it can reach, since an item it cannot copy into the project has no business in a picker. Each item's own shelf answers for it: previews, renames, and deletes go to the backend it came from, and folders belong to one shelf, so items file only into folders beside them. Adding to a project is the one crossing: on the project's own shelf the server copies the file without the bytes leaving it, and off it the browser carries them down and back up.+Some of what the Library holds is lent. Most items are copied when they are used — a clip's bytes become the project's own — but a font is pointed at: every title set in it names it, and the file stays on the shelf where every project can reach it. Lent items follow three rules. They are identified by their bytes, so the same file on two shelves is one entry in the menu and one id in a document. A new one lands on the shelf every surface can read, whenever it is small and the account has room. And a project moving to the cloud takes what it points at with it, so a title keeps its typeface when it starts rendering there — since the id is the bytes, not a word of the document changes. Fonts are the first of these; a .ttf, .otf, .woff or .woff2 dropped on the Library is filed in folders, deleted, and counted against storage like anything else, and every project offers it for titles and captions. A font download arrives as a zip, so the zip is droppable: the faces come out of it and the licence text stays behind, and a family of eighteen weights becomes a single entry. The file is checked by installing it through the renderer's font seam before any bytes move, so what lands is what a preview and an export can draw with, and the family name comes off the font's own metadata rather than the file name. A new account starts with an empty Fonts folder to say the shelf takes them; it is an ordinary folder and can be deleted. A render job reaches the cloud shelf alone, which is what those rules are for. A font filed into a folder belongs to that folder's shelf like anything else, and a full account keeps its font on the shelf it was working from: it draws in the tab, is marked in the font menu as living on this device, and falls back to the base face in a render job. A title set in a font that is later deleted falls back too, so nothing in a document has to be rewritten.+Cloud projects store their doc in Postgres (versioned; a stale autosave 409s and the editor reloads the newer copy) and media in R2: uploads go direct from the browser on presigned URLs (the hosted functions never see the bytes), playback streams on signed range URLs, and a flat per-user quota is enforced at presign time. That quota is visible rather than implicit: a free account editing a cloud project sees what it has used in the editor's top bar, and a presign rejected for space opens an upgrade offer wherever it happened instead of a bare error. The same slot carries the countdown when a subscription is set to cancel, and clicking it opens the billing portal.A dropped file does not wait for that upload. Because a presign claims the stored name before any bytes move, and the browser can read the file it was handed, an import is measured, named, and placed on the timeline in the same moment it is dropped — playing from the local copy, filmstrip and all — while the bytes go out behind the editor. When this browser can hold a store, the dropped bytes are written into origin-private storage under the claimed name and pinned: the document references the asset at once, a tab closed mid-upload resumes the upload on the next open, and once the cloud confirms the object the pin clears and the local file becomes a read cache. A tab-scoped import — a browser with no store — keeps itself honest through the saved document instead: the import stays out of it, along with the clips that use it, until the upload lands, so a tab closed mid-upload leaves nothing to reopen broken. Export waits on the same line, since a render reads the saved document.diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsxindex f032a987..d1aa9eca 100644--- a/site/src/cut/components/Editor.tsx+++ b/site/src/cut/components/Editor.tsx@@ -30,6 +30,7 @@ import "@/cut/lib/genScene";// self-hosted) into the shared font registry before any text renders.import "@/cut/lib/googleFonts";import { syncFontAssets } from "@/cut/lib/fontAssets";+import { syncLinkedLibrary } from "@/cut/lib/linkedLibrary";import { installDevHooks } from "@/cut/lib/devHooks";import { ensureCloudThreads } from "@/cut/lib/chatCloud";import { readProjectThreads, writeActiveChat } from "@/cut/lib/chatThreads";@@ -141,6 +142,9 @@ export function Editor({// drop out when deleted), so titles set in them never measure a fallback.const assetsForFonts = useEditor((s) => s.assets);useEffect(() => void syncFontAssets(assetsForFonts), [assetsForFonts]);+ // What the Library lends rather than copies — the account's own typefaces+ // today — is in reach whichever project is open.+ useEffect(() => void syncLinkedLibrary(), []);const [conflictReloaded, setConflictReloaded] = useState(false);const [shareGone, setShareGone] = useState(false);// This project lives on this Mac and the Donkey app isn't answering. Nothingdiff --git a/site/src/cut/components/FontPicker.tsx b/site/src/cut/components/FontPicker.tsxnew file mode 100644index 00000000..57fb95e0--- /dev/null+++ b/site/src/cut/components/FontPicker.tsx@@ -0,0 +1,231 @@+"use client";++/**+ * The font menu, shared by the title inspector and the caption panel.+ *+ * It lists the base system set, the bundled families, and the account's own+ * fonts off the Library shelf, and it is where a font file gets onto that shelf+ * in the first place: "Upload font" is a row in the menu, and each of the+ * user's own fonts carries the button that takes it off again.+ */++import { Laptop, Loader2, Trash2, Upload } from "lucide-react";+import { useEffect, useRef, useState, useSyncExternalStore } from "react";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectSeparator,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { isFontFile } from "@/cut/lib/media";+import {+ deleteLinkedItem,+ libraryFontId,+ listLibraryFonts,+ expandLinkedFiles,+ linkedAccept,+ onLinkedChanged,+ uploadLibraryFont,+ type LinkedItem,+} from "@/cut/lib/linkedLibrary";+import { useEditor } from "@/cut/lib/store";+import { allFonts, fontStack, onFontsChanged } from "@/cut/lib/types";+import { cn } from "@/lib/utils";++/** Picking this row opens the file dialog; it never becomes the value. */+const UPLOAD = "__upload";++const ACCEPT = linkedAccept();++const NONE: LinkedItem[] = [];++function useShelfFonts(): LinkedItem[] {+ return useSyncExternalStore(onLinkedChanged, listLibraryFonts, () => NONE);+}++/** How many titles and cues are set in this font, so a delete says what it+ * costs before it happens. */+function countUses(fontId: string): number {+ const s = useEditor.getState();+ const titles = s.overlays.filter((o) => "font" in o && o.font === fontId).length;+ const cues = s.subtitles.font === fontId ? 1 : 0;+ return titles + cues;+}++export function FontPicker({+ value,+ onChange,+ className,+}: {+ value: string;+ onChange: (id: string) => void;+ className?: string;+}) {+ // The menu re-reads the registry when the bundled families finish registering+ // or a shelf font lands (the bump re-renders, and the render re-reads).+ const [, bump] = useState(0);+ useEffect(() => onFontsChanged(() => bump((n) => n + 1)), []);+ const fonts = allFonts();+ const shelf = useShelfFonts();+ const shelfIds = new Set(shelf.map((f) => libraryFontId(f.key)));+ const built = fonts.filter((f) => !shelfIds.has(f.id));+ // A font whose bytes wouldn't install still lists, so it can still be taken+ // off the shelf; it just has no specimen to set its own name in.+ const mine = shelf.map((f) => {+ const id = libraryFontId(f.key);+ const def = fonts.find((d) => d.id === id);+ return {+ font: f,+ id,+ label: def?.label ?? f.label,+ stack: def?.stack,+ // Only the cloud shelf is readable from a render job.+ deviceOnly: !f.copies.some((c) => c.residency === "cloud"),+ };+ });++ const inputRef = useRef<HTMLInputElement>(null);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [confirming, setConfirming] = useState<{ font: LinkedItem; uses: number } | null>(null);++ const upload = async (files: FileList | null) => {+ setBusy(true);+ setError(null);+ // A font download is a zip more often than it is a font, so the archive is+ // opened before anything is judged for being one.+ const file = (await expandLinkedFiles(Array.from(files ?? []))).find(isFontFile);+ if (!file) {+ if (files?.length) setError("That file has no font in it. Try a .ttf, .otf or .woff.");+ setBusy(false);+ return;+ }+ try {+ onChange(await uploadLibraryFont(file));+ } catch (e) {+ setError(e instanceof Error ? e.message : "Could not add that font.");+ } finally {+ setBusy(false);+ }+ };++ const remove = async () => {+ const target = confirming?.font;+ setConfirming(null);+ if (!target) return;+ await deleteLinkedItem(target).catch(() => {});+ };++ return (+ <>+ <Select+ value={value}+ items={Object.fromEntries(fonts.map((f) => [f.id, f.label]))}+ onValueChange={(v) => {+ if (v === UPLOAD) {+ inputRef.current?.click();+ return;+ }+ onChange(v as string);+ }}+ >+ <SelectTrigger size="sm" className={cn("w-full", className)} style={{ fontFamily: fontStack(value) }}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {built.map((f) => (+ <SelectItem key={f.id} value={f.id}>+ <span style={{ fontFamily: f.stack }}>{f.label}</span>+ </SelectItem>+ ))}+ {mine.length > 0 && <SelectSeparator />}+ {mine.map(({ font, id, label, stack, deviceOnly }) => (+ <SelectItem key={id} value={id}>+ <span className="flex-1 truncate" style={stack ? { fontFamily: stack } : undefined}>+ {label}+ </span>+ {deviceOnly && (+ <span+ className="text-muted-foreground"+ title="On this device only — a cloud render falls back to SF Pro"+ >+ <Laptop className="size-3" aria-label="On this device only" />+ </span>+ )}+ <button+ type="button"+ aria-label={`Delete ${label}`}+ title="Delete this font"+ className="ml-1 rounded p-0.5 text-muted-foreground opacity-60 hover:text-destructive hover:opacity-100"+ onPointerDown={(e) => {+ e.preventDefault();+ e.stopPropagation();+ }}+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ setConfirming({ font, uses: countUses(id) });+ }}+ >+ <Trash2 className="size-3.5" />+ </button>+ </SelectItem>+ ))}+ <SelectSeparator />+ <SelectItem value={UPLOAD}>+ {busy ? <Loader2 className="size-3.5 animate-spin" /> : <Upload className="size-3.5" />}+ <span className="text-muted-foreground">{busy ? "Adding font…" : "Upload font…"}</span>+ </SelectItem>+ </SelectContent>+ </Select>+ {error && <p className="mt-1 text-xs text-destructive">{error}</p>}+ <input+ ref={inputRef}+ type="file"+ accept={ACCEPT}+ hidden+ onChange={(e) => {+ void upload(e.target.files);+ e.target.value = "";+ }}+ />+ <AlertDialog open={!!confirming} onOpenChange={(o) => !o && setConfirming(null)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Delete this font?</AlertDialogTitle>+ <AlertDialogDescription>+ It leaves your library and every project that offers it.+ {confirming && confirming.uses > 0+ ? ` ${confirming.uses} ${confirming.uses === 1 ? "title or caption" : "titles and captions"} set in it fall back to SF Pro.`+ : ""}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ className="bg-destructive/10 text-destructive hover:bg-destructive/20"+ onClick={(e) => {+ e.preventDefault();+ void remove();+ }}+ >+ Delete+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>+ );+}diff --git a/site/src/cut/components/FontSpecimen.tsx b/site/src/cut/components/FontSpecimen.tsxnew file mode 100644index 00000000..779c4361--- /dev/null+++ b/site/src/cut/components/FontSpecimen.tsx@@ -0,0 +1,105 @@+"use client";++import { useEffect, useLayoutEffect, useRef, useState } from "react";+import { SPECIMEN_LINES } from "@/cut/lib/fontSpecimen";+import { linkIdForAsset, onLinkedChanged } from "@/cut/lib/linkedLibrary";+import { MEDIA_CORS } from "@/cut/lib/mediaCors";+import { fontStack, onFontsChanged } from "@/cut/lib/types";+import { cn } from "@/lib/utils";++// A font drawn in itself: the alphabet the way a font file previews anywhere+// else. The library card carries a small one and the lightbox a large one, both+// from here, so the tile and the big view read as the same object.+//+// The picture the shelf baked at upload is what it draws. Live text in the face+// is the standby, and it asks the page to have that face installed.++const LINES = SPECIMEN_LINES;+/** Measured at one size and scaled; large enough that rounding doesn't show. */+const PROBE_PX = 100;++/**+ * The specimen, set to the width it is given.+ *+ * One size for all three lines: the capitals are the widest line, so fitting+ * them sets the size and the rest fall where the face puts them. The size is+ * measured rather than computed because a script face runs three times the+ * width of a grotesque at the same point size.+ */+export function FontSpecimen({+ assetId,+ poster,+ pad = 16,+ className,+}: {+ /** The library asset holding the font file. */+ assetId: string;+ /** The specimen the shelf keeps for this file. */+ poster?: string;+ /** Room left either side of the widest line. */+ pad?: number;+ className?: string;+}) {+ const [gen, bump] = useState(0);+ const [broken, setBroken] = useState(false);+ const again = () => bump((n) => n + 1);+ // The shelf listing says which font this is; the registry says what that font+ // draws in. Both land after the first paint.+ useEffect(() => onFontsChanged(again), []);+ useEffect(() => onLinkedChanged(again), []);+ const family = fontStack(linkIdForAsset(assetId) ?? "");+ const box = useRef<HTMLDivElement>(null);+ const probe = useRef<HTMLSpanElement>(null);+ const [size, setSize] = useState(0);+ useLayoutEffect(() => {+ const fit = () => {+ const line = probe.current?.getBoundingClientRect().width;+ const width = box.current?.clientWidth;+ if (!line || !width) return;+ setSize((PROBE_PX * (width - pad)) / line);+ };+ fit();+ // The face arrives after the box does, and the box is resized by the grid.+ const ro = new ResizeObserver(fit);+ if (box.current) ro.observe(box.current);+ return () => ro.disconnect();+ }, [family, gen, pad]);+ if (poster && !broken)+ return (+ // eslint-disable-next-line @next/next/no-img-element -- library media file, not Next-optimizable+ <img+ crossOrigin={MEDIA_CORS}+ src={poster}+ alt=""+ className={cn("object-contain", className)}+ onError={() => setBroken(true)}+ />+ );++ return (+ <div+ ref={box}+ className={cn("grid place-items-center overflow-hidden", className)}+ style={{ fontFamily: family }}+ >+ <span+ ref={probe}+ aria-hidden+ className="pointer-events-none invisible fixed top-0 left-0 whitespace-nowrap"+ style={{ fontSize: PROBE_PX }}+ >+ {LINES[0]}+ </span>+ <span+ className="text-center leading-[1.35] whitespace-nowrap"+ style={{ fontSize: size || undefined, opacity: size ? 1 : 0 }}+ >+ {LINES.map((line) => (+ <span key={line} className="block">+ {line}+ </span>+ ))}+ </span>+ </div>+ );+}diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsxindex e61e368c..b60c452b 100644--- a/site/src/cut/components/Inspector.tsx+++ b/site/src/cut/components/Inspector.tsx@@ -4,6 +4,7 @@ import { useCallback, 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 { Button } from "@/components/ui/button";import { EmojiPicker } from "@/cut/components/EmojiPicker";+import { FontPicker } from "@/cut/components/FontPicker";import {Select,SelectContent,@@ -69,7 +70,6 @@ import {import { writeTextStyle } from "@/cut/lib/textStyle";import { formatTime } from "@/cut/lib/time";import {- allFonts,fontStack,frameOf,GRADE_HUE_MAX,@@ -1013,12 +1013,10 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {const strokeCk = useSliderCheckpoint();const shadowCk = useSliderCheckpoint();const taRef = useRef<HTMLTextAreaElement>(null);- // The font menu re-reads the registry when Google families finish- // registering or an uploaded font lands (the bump re-renders, and the- // render re-reads allFonts()).+ // The saved-style previews below are set in whatever font each style names,+ // so they re-render when a family finishes registering.const [, bumpFonts] = useState(0);useEffect(() => onFontsChanged(() => bumpFonts((n) => n + 1)), []);- const fonts = allFonts();// Remember this title's look across clips and projects, so the next new title// starts from the same style.@@ -1088,22 +1086,10 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {/></div><StylePresetsRow overlay={o} />- <Select+ <FontPickervalue={o.font}- items={Object.fromEntries(fonts.map((f) => [f.id, f.label]))}- onValueChange={(v) => update(o.id, { font: v as TextOverlay["font"] })}- >- <SelectTrigger size="sm" className="w-full" style={{ fontFamily: fontStack(o.font) }}>- <SelectValue />- </SelectTrigger>- <SelectContent>- {fonts.map((f) => (- <SelectItem key={f.id} value={f.id}>- <span style={{ fontFamily: f.stack }}>{f.label}</span>- </SelectItem>- ))}- </SelectContent>- </Select>+ onChange={(v) => update(o.id, { font: v as TextOverlay["font"] })}+ /><div className="mt-1 flex items-center gap-2"><SegGroup><SegTogglediff --git a/site/src/cut/components/LibraryView.tools.ts b/site/src/cut/components/LibraryView.tools.tsindex 1995dab7..cab21249 100644--- a/site/src/cut/components/LibraryView.tools.ts+++ b/site/src/cut/components/LibraryView.tools.ts@@ -12,13 +12,13 @@ export const LIBRARY_TOOLS = [{name: "library_list",description:- "List the shared Library — reusable media saved across projects: folders, assets (video/audio/image), and templates (saved arrangements of clips, overlays, titles, and captions). Library items live outside the project: library_add imports an asset, template_add re-materializes a template.",+ "List the shared Library — reusable media saved across projects: folders, assets (video/audio/image, and the account's own font files), and templates (saved arrangements of clips, overlays, titles, and captions). Library items live outside the project: library_add imports an asset, template_add re-materializes a template.",inputSchema: obj({}),},{name: "library_add",description:- "Copy a Library asset into the project (it appears in `media` and previews as a card in this chat). This is the import step \"library\"-scope attachments need before editor tools can touch them. Pass add_to_timeline:true (or start/index) only when the user asked for it in the cut: video/image land on track 0, audio on the soundtrack.",+ "Copy a Library asset into the project (it appears in `media` and previews as a card in this chat). This is the import step \"library\"-scope attachments need before editor tools can touch them. Fonts are not imported — a font on the shelf is already offered to every project as font id \"font:<id>\". Pass add_to_timeline:true (or start/index) only when the user asked for it in the cut: video/image land on track 0, audio on the soundtrack.",inputSchema: obj({id: str("Library asset id (from library_list or an attachment's metadata)"),add_to_timeline: bool("Also place it on the timeline (default false — it stays a project asset until the user asks)"),diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsxindex 4adaf307..64439296 100644--- a/site/src/cut/components/LibraryView.tsx+++ b/site/src/cut/components/LibraryView.tsx@@ -19,6 +19,7 @@ import {Plus,RotateCcw,Trash2,+ Type,Upload,X,} from "lucide-react";@@ -56,7 +57,11 @@ import {} from "@/components/ui/tooltip";import { Skeleton } from "@/components/ui/skeleton";import { MEDIA_CORS } from "@/cut/lib/mediaCors";-import { clearAssetDrag, setLibraryDragData, setObjectDragImage } from "@/cut/lib/assetDrag";+import {+ clearAssetDrag,+ setLibraryDragData,+ setObjectDragImage,+} from "@/cut/lib/assetDrag";import { useInView } from "@/cut/hooks/useInView";import { isMediaFile } from "@/cut/lib/media";import { patchLibrary, refetchLibrary, useLibrary } from "@/cut/lib/queries";@@ -70,6 +75,7 @@ import {importUrlToLibrary,libraryMediaUrl,libraryPosterUrl,+ carryAssetTo,moveLibraryItem,renameLibraryFolder,renameTemplate,@@ -91,13 +97,29 @@ import {import { Lightbox } from "./Lightbox";import { TemplateCard } from "./TemplateCard";import { homeHref, useCutBase } from "@/cut/lib/nav";+import {+ forgetLinkedCopy,+ expandLinkedFiles,+ isLinkedFile,+ linkedAccept,+ isLinkedType,+ shelfForNewItem,+ syncLinkedLibrary,+} from "@/cut/lib/linkedLibrary";import { shapeBand } from "@/cut/lib/types";import { useRevealFlash } from "@/cut/lib/refReveal";import { formatTime } from "@/cut/lib/time";import { cn } from "@/lib/utils";import { CopyNameLabel } from "./AssetRefs";+import { FontSpecimen } from "./FontSpecimen";import { AudioCardFace } from "./AudioPanel";-import { buildDragGhost, FolderCrumb, FolderShelf, formatBytes, Marquee } from "./desktopFolders";+import {+ buildDragGhost,+ FolderCrumb,+ FolderShelf,+ formatBytes,+ Marquee,+} from "./desktopFolders";import { useMediaFileSize } from "@/cut/hooks/useMediaFileSize";// A dragged library selection travels as a JSON array of asset ids, so a whole@@ -165,7 +187,8 @@ function linkLabel(url: string): string {.split("/").filter(Boolean).reverse()- .find((seg) => !ROUTE_SEGMENT.has(seg.toLowerCase())) ?? u.searchParams.get("v");+ .find((seg) => !ROUTE_SEGMENT.has(seg.toLowerCase())) ??+ u.searchParams.get("v");return id ? `${host}/${id}` : host;} catch {return url;@@ -200,7 +223,7 @@ function PendingTile({<divclassName={cn("relative max-w-full overflow-hidden rounded-xl border",- item.error ? "border-destructive/50 bg-muted" : "border-border"+ item.error ? "border-destructive/50 bg-muted" : "border-border",)}style={{width: Math.round(Math.sqrt((area * frame.width) / frame.height)),@@ -210,7 +233,12 @@ function PendingTile({{item.error ? (// Clear of the strip the link and the reason share along the top.<div className="flex size-full flex-col items-center justify-center gap-1.5 pt-8">- <Button variant="outline" size="sm" className="w-24 justify-start" onClick={onRetry}>+ <Button+ variant="outline"+ size="sm"+ className="w-24 justify-start"+ onClick={onRetry}+ ><RotateCcw data-icon="inline-start" /> Retry</Button><Button@@ -232,14 +260,16 @@ function PendingTile({<spanclassName={cn("absolute top-1.5 left-1.5 truncate rounded-lg bg-black/55 px-2 py-1 text-[11px] font-medium text-white backdrop-blur-sm",- item.error ? "max-w-[calc(100%-4rem)]" : "max-w-[70%]"+ item.error ? "max-w-[calc(100%-4rem)]" : "max-w-[70%]",)}/>}>{item.name}</TooltipTrigger>- <TooltipContent className="max-w-xs break-all">{item.source ?? item.name}</TooltipContent>+ <TooltipContent className="max-w-xs break-all">+ {item.source ?? item.name}+ </TooltipContent></Tooltip></TooltipProvider>{item.error ? (@@ -282,7 +312,11 @@ export function ShelfBadge({const Icon = residency === "cloud" ? Cloud : Laptop;return (<span- title={offline ? "Local — open the Donkey app to use it" : RESIDENCY_LABEL[residency]}+ title={+ offline+ ? "Local — open the Donkey app to use it"+ : RESIDENCY_LABEL[residency]+ }className={className}><Icon className="size-3" />@@ -305,10 +339,17 @@ export function LibraryView() {const engineUp = useLocalCompute();// Every shelf but the Mac's is always answering: the cloud is a request away// and the browser shelf is this page's own storage.- const live = useCallback((r: Residency) => r !== "local" || engineUp, [engineUp]);+ const live = useCallback(+ (r: Residency) => r !== "local" || engineUp,+ [engineUp],+ );// Drop the flag when this view goes away: the banner belongs to the surface// that raised it.useEffect(() => () => setNeedsApp(false), []);+ // Lent items draw themselves in what they are — a font card is set in its own+ // face — so the shelf's kinds are put to use as soon as the page is open,+ // ahead of any upload.+ useEffect(() => void syncLinkedLibrary(), []);// New projects and new library items answer the same question — which shelf// is this browser putting things on — so they read the one choice the user// already made, rather than the backend the app happens to be bound to.@@ -318,7 +359,7 @@ export function LibraryView() {const templates = library.data?.templates ?? [];const patch = useCallback((fn: (prev: LibraryData) => LibraryData) => patchLibrary(client, fn),- [client]+ [client],);const reload = useCallback(() => refetchLibrary(client), [client]);// The open folder lives in the URL (?folder=…) so the browser's back button@@ -350,14 +391,19 @@ export function LibraryView() {// that isn't answering can't take one, so the item goes to the root of the// shelf new items go to.const landing = (folderId: string | null) => {- const owner = folderId ? folders.find((f) => f.id === folderId)?.residency : null;+ const owner = folderId+ ? folders.find((f) => f.id === folderId)?.residency+ : null;const residency = owner && live(owner) ? owner : target;return { residency, folderId: owner === residency ? folderId : null };};const renameTpl = async (r: Residency, id: string, name: string) => {if (!live(r)) return;- patch((d) => ({ ...d, templates: d.templates.map((t) => (t.id === id ? { ...t, name } : t)) }));+ patch((d) => ({+ ...d,+ templates: d.templates.map((t) => (t.id === id ? { ...t, name } : t)),+ }));await renameTemplate(r, id, name).catch(() => void reload());};@@ -375,39 +421,62 @@ export function LibraryView() {setPending((q) => q.map((p) => (p.id === id ? { ...p, stage } : p)));const failPending = (id: string, error: string) =>setPending((q) => q.map((p) => (p.id === id ? { ...p, error } : p)));- const dropPending = (id: string) => setPending((q) => q.filter((p) => p.id !== id));+ const dropPending = (id: string) =>+ setPending((q) => q.filter((p) => p.id !== id));// Run a failed arrival again on the tile it already has: the reason clears,// the clock restarts, and the same work goes out once more.const retryPending = (item: Pending) => {setPending((q) =>q.map((p) =>p.id === item.id- ? { ...p, error: undefined, stage: item.startStage, startedAt: Date.now() }- : p- )+ ? {+ ...p,+ error: undefined,+ stage: item.startStage,+ startedAt: Date.now(),+ }+ : p,+ ),);void item.run();};// Upload a batch into `folderId` (the open folder by default — folder tiles// pass their own id when files are dropped straight onto them).- const upload = async (files: FileList | File[], into: string | null = openFolder) => {- const list = Array.from(files).filter(isMediaFile);+ const upload = async (+ files: FileList | File[],+ into: string | null = openFolder,+ ) => {+ const list = (await expandLinkedFiles(Array.from(files))).filter(+ (f) => isMediaFile(f) || isLinkedFile(f),+ );const { residency, folderId } = landing(into);if (!live(residency)) return;for (const file of list) {const id = crypto.randomUUID();const run = async () => {try {- const asset = await uploadToLibrary(file, residency);+ // Something the Library lends rather than copies, dropped outside a+ // folder, takes the shelf every surface can read; dropped into one,+ // the folder still decides.+ const shelf =+ isLinkedFile(file) && !folderId+ ? await shelfForNewItem(file.size)+ : residency;+ const asset = await uploadToLibrary(file, shelf);if (folderId) {- await moveLibraryItem(residency, asset.id, folderId).catch(() => {});+ await moveLibraryItem(shelf, asset.id, folderId).catch(() => {});asset.folderId = folderId;}patch((d) => ({ ...d, assets: [asset, ...d.assets] }));+ // A lent item is only usable once it is in reach of the menus.+ if (isLinkedType(asset.type)) void syncLinkedLibrary();dropPending(id);} catch (e) {- failPending(id, e instanceof Error ? e.message : "Could not upload that file.");+ failPending(+ id,+ e instanceof Error ? e.message : "Could not upload that file.",+ );}};addPending({@@ -435,17 +504,24 @@ export function LibraryView() {const id = crypto.randomUUID();const run = async () => {try {- const imported = await importUrlToLibrary(value, residency, (stage) => setStage(id, stage));+ const imported = await importUrlToLibrary(value, residency, (stage) =>+ setStage(id, stage),+ );if (folderId) {for (const asset of imported) {- await moveLibraryItem(residency, asset.id, folderId).catch(() => {});+ await moveLibraryItem(residency, asset.id, folderId).catch(+ () => {},+ );asset.folderId = folderId;}}patch((d) => ({ ...d, assets: [...imported, ...d.assets] }));dropPending(id);} catch (e) {- failPending(id, e instanceof Error ? e.message : "Could not import that URL.");+ failPending(+ id,+ e instanceof Error ? e.message : "Could not import that URL.",+ );}};addPending({@@ -467,6 +543,7 @@ export function LibraryView() {setDeleting(null);if (!live(residency)) return;patch((d) => ({ ...d, assets: d.assets.filter((a) => a.id !== id) }));+ if (isLinkedType(deleting.type)) forgetLinkedCopy(id);try {await deleteFromLibrary(residency, id);} catch {@@ -482,35 +559,64 @@ export function LibraryView() {};// A folder belongs to one shelf, so a drag that spans both files only the- // items already on that folder's shelf; the rest stay where they are.+ // items already on that folder's shelf — except a lent item, which is small+ // enough to carry to the folder's shelf and follow the user's filing.const moveItems = async (ids: string[], folderId: string | null) => {- const target = folderId ? folders.find((f) => f.id === folderId)?.residency : null;+ const target = folderId+ ? folders.find((f) => f.id === folderId)?.residency+ : null;const moving = ids.map((id) => ({ id, residency: shelfOf(id) })).filter((x): x is { id: string; residency: Residency } => !!x.residency).filter((x) => live(x.residency)).filter((x) => !target || x.residency === target);+ const carried =+ target && live(target)+ ? ids+ .map((id) => all.find((a) => a.id === id))+ .filter(+ (a): a is LibraryAsset =>+ !!a && a.residency !== target && live(a.residency),+ )+ : [];+ if (carried.length > 0) {+ setSelected(new Set());+ await Promise.all(+ carried.map((a) => carryAssetTo(a, target!, folderId).catch(() => {})),+ );+ // The listing decides what the font menu offers, and it just changed.+ void syncLinkedLibrary();+ void reload();+ }if (moving.length === 0) return;const idset = new Set(moving.map((x) => x.id));patch((d) => ({...d,assets: d.assets.map((a) => (idset.has(a.id) ? { ...a, folderId } : a)),- templates: d.templates.map((t) => (idset.has(t.id) ? { ...t, folderId } : t)),+ templates: d.templates.map((t) =>+ idset.has(t.id) ? { ...t, folderId } : t,+ ),}));setSelected(new Set());await Promise.all(- moving.map((x) => moveLibraryItem(x.residency, x.id, folderId))+ moving.map((x) => moveLibraryItem(x.residency, x.id, folderId)),).catch(() => void reload());};// Carry the current selection (or just this card) as a folder-move payload,// with a ghost — alongside the timeline-drag payload the card already sets.// A single card drags as itself; a multi-selection keeps the counted stack.- const onCardDragExtra = (e: React.DragEvent, a: LibraryAsset) => {- const ids = selected.has(a.id) && selected.size > 0 ? Array.from(selected) : [a.id];- if (!selected.has(a.id)) setSelected(new Set([a.id]));+ const dragSelection = (e: React.DragEvent, id: string): string[] => {+ const ids =+ selected.has(id) && selected.size > 0 ? Array.from(selected) : [id];+ if (!selected.has(id)) setSelected(new Set([id]));e.dataTransfer.setData(LIBRARY_MOVE_MIME, JSON.stringify(ids));e.dataTransfer.effectAllowed = "copyMove";+ return ids;+ };++ const onCardDragExtra = (e: React.DragEvent, a: LibraryAsset) => {+ const ids = dragSelection(e, a.id);if (ids.length > 1) {const ghost = buildDragGhost(ids.length, `${ids.length} items`);document.body.appendChild(ghost);@@ -529,35 +635,48 @@ export function LibraryView() {// bands by the shape its link is expected to take and waits at the front of// that band, which is where the finished asset lands.const shapeOf = (a: LibraryAsset) =>- a.type === "audio" || !a.width || !a.height ? 0 : shapeBand(a.width, a.height);- const shownBands = new Map<number, ({ pending: Pending } | { asset: LibraryAsset })[]>();+ a.type === "audio" || !a.width || !a.height+ ? 0+ : shapeBand(a.width, a.height);+ const shownBands = new Map<+ number,+ ({ pending: Pending } | { asset: LibraryAsset })[]+ >();const band = (key: number) => {const found = shownBands.get(key) ?? [];if (found.length === 0) shownBands.set(key, found);return found;};for (const p of pending)- band(p.shape ? shapeBand(p.shape.width, p.shape.height) : 0).push({ pending: p });+ band(p.shape ? shapeBand(p.shape.width, p.shape.height) : 0).push({+ pending: p,+ });for (const a of shown) band(shapeOf(a)).push({ asset: a });// Every tile takes the same area — a wide clip spreads, a tall one stands,// and each carries equal weight on the page. The area is the projects grid's,// so a clip and a project of the same shape are the same card.const TILE_AREA = 180 * 320;- const shownTemplates = templates.filter((t) => (t.folderId ?? null) === openFolder);+ const shownTemplates = templates.filter(+ (t) => (t.folderId ?? null) === openFolder,+ );const openFolderName = folders.find((f) => f.id === openFolder)?.name;const hasContent =- all.length > 0 || folders.length > 0 || templates.length > 0 || pending.length > 0;+ all.length > 0 ||+ folders.length > 0 ||+ templates.length > 0 ||+ pending.length > 0;// Only OS-file drags are drop targets here; internal card drags carry// LIBRARY_MOVE_MIME and are handled by the folder tiles and breadcrumb.- const isFileDrag = (e: React.DragEvent) => Array.from(e.dataTransfer.types).includes("Files");+ const isFileDrag = (e: React.DragEvent) =>+ Array.from(e.dataTransfer.types).includes("Files");return (<divclassName={cn("min-h-full",fileOver &&- "rounded-3xl outline-2 outline-dashed outline-offset-[-10px] outline-[#0a84ff]/60"+ "rounded-3xl outline-2 outline-dashed outline-offset-[-10px] outline-[#0a84ff]/60",)}onDragEnter={(e) => {if (!isFileDrag(e)) return;@@ -586,262 +705,296 @@ export function LibraryView() {void upload(e.dataTransfer.files);}}>- <div className="mx-auto w-full max-w-6xl px-10 py-9">- <div className="mb-5 flex items-center justify-between gap-4">- {openFolder === null ? (- <h1 className="text-lg font-semibold tracking-tight">Library</h1>- ) : (- <FolderCrumb- root="Library"- name={openFolderName ?? "Folder"}- mime={LIBRARY_MOVE_MIME}- onBack={() => gotoFolder(null)}- onDropOut={(ids) => void moveItems(ids, null)}- />- )}- <div className="flex items-center gap-2">- {openFolder === null && (- <Button variant="outline" onClick={() => setFolderCreating(true)}>- <FolderPlus data-icon="inline-start" /> New folder- </Button>+ <div className="mx-auto w-full max-w-6xl px-10 py-9">+ <div className="mb-5 flex items-center justify-between gap-4">+ {openFolder === null ? (+ <h1 className="text-lg font-semibold tracking-tight">Library</h1>+ ) : (+ <FolderCrumb+ root="Library"+ name={openFolderName ?? "Folder"}+ mime={LIBRARY_MOVE_MIME}+ onBack={() => gotoFolder(null)}+ onDropOut={(ids) => void moveItems(ids, null)}+ />)}- <Button onClick={() => setAddOpen(true)}>- <Upload data-icon="inline-start" /> Add media- </Button>- </div>- <input- ref={inputRef}- type="file"- accept="video/*,audio/*"- multiple- hidden- onChange={(e) => {- if (e.target.files?.length) {- void upload(e.target.files);- setAddOpen(false);- }- e.target.value = "";- }}- />- </div>-- {openFolder === null && (folders.length > 0 || folderCreating) ? (- <FolderShelf- folders={folders}- mime={LIBRARY_MOVE_MIME}- creating={folderCreating}- onCreatingChange={setFolderCreating}- statOf={(id) => ({- count:- all.filter((a) => (a.folderId ?? null) === id).length +- templates.filter((t) => (t.folderId ?? null) === id).length,- })}- badgeOf={(id) => {- const r = folders.find((f) => f.id === id)?.residency;- return bothShelves && r ? <ShelfBadge residency={r} offline={!live(r)} /> : null;- }}- onOpen={gotoFolder}- onCreate={async (name) => {- if (!live(target)) return;- const f = await createLibraryFolder(name, target);- patch((d) => ({ ...d, folders: [...d.folders, f] }));- }}- onRename={async (id, name) => {- const r = folders.find((f) => f.id === id)?.residency;- if (!r || !live(r)) return;- patch((d) => ({- ...d,- folders: d.folders.map((f) => (f.id === id ? { ...f, name } : f)),- }));- await renameLibraryFolder(r, id, name).catch(() => void reload());- }}- onDelete={async (id) => {- const r = folders.find((f) => f.id === id)?.residency;- if (!r || !live(r)) return;- patch((d) => ({- folders: d.folders.filter((f) => f.id !== id),- assets: d.assets.map((a) => (a.folderId === id ? { ...a, folderId: null } : a)),- templates: d.templates.map((t) =>- t.folderId === id ? { ...t, folderId: null } : t- ),- }));- if (openFolder === id) router.replace(homeHref(base, "library"));- await deleteLibraryFolder(r, id).catch(() => void reload());- }}- onDropIds={(ids, fid) => void moveItems(ids, fid)}- onDropFiles={(files, fid) => void upload(files, fid)}- />- ) : null}-- {shownTemplates.length > 0 && (- <div className="mb-6 grid grid-cols-[repeat(auto-fill,minmax(240px,1fr))] gap-3">- {shownTemplates.map((t) => (- <TemplateCard- key={t.id}- template={t}- mediaSrc={(f) => libraryMediaUrl(f, t.residency)}- drag={live(t.residency) ? { scope: "library", template: t } : undefined}- onDragStartExtra={(e) => {- e.dataTransfer.setData(LIBRARY_MOVE_MIME, JSON.stringify([t.id]));- e.dataTransfer.effectAllowed = "copyMove";- }}- onRename={- live(t.residency) ? (name) => void renameTpl(t.residency, t.id, name) : undefined- }- onDelete={- live(t.residency) ? () => void removeTpl(t.residency, t.id) : undefined+ <div className="flex items-center gap-2">+ {openFolder === null && (+ <Button variant="outline" onClick={() => setFolderCreating(true)}>+ <FolderPlus data-icon="inline-start" /> New folder+ </Button>+ )}+ <Button onClick={() => setAddOpen(true)}>+ <Upload data-icon="inline-start" /> Add media+ </Button>+ </div>+ <input+ ref={inputRef}+ type="file"+ accept={`video/*,audio/*,${linkedAccept()}`}+ multiple+ hidden+ onChange={(e) => {+ if (e.target.files?.length) {+ void upload(e.target.files);+ setAddOpen(false);}- />- ))}+ e.target.value = "";+ }}+ /></div>- )}- {!library.data && library.isPending ? (- <div className="grid place-items-center py-24 text-muted-foreground">- <Loader2 className="size-5 animate-spin" />- </div>- ) : !hasContent ? (- <button- className="grid w-full cursor-pointer place-items-center rounded-2xl py-24"- onClick={() => setAddOpen(true)}- >- <div className="flex flex-col items-center gap-3 text-center">- <FolderOpen className="size-8 text-muted-foreground" />- <div className="text-base font-medium">- Your Library is shared across all projects.- </div>- <p className="text-sm text-muted-foreground">- Drag and drop videos, images, or audio files here.- </p>+ {/* Folders live at the root and nowhere else, so an open folder shows+ only what is filed in it. */}+ {openFolder === null && (folders.length > 0 || folderCreating) ? (+ <FolderShelf+ folders={folders}+ mime={LIBRARY_MOVE_MIME}+ creating={folderCreating}+ onCreatingChange={setFolderCreating}+ statOf={(id) => ({+ count:+ all.filter((a) => (a.folderId ?? null) === id).length ++ templates.filter((t) => (t.folderId ?? null) === id).length,+ })}+ badgeOf={(id) => {+ const r = folders.find((f) => f.id === id)?.residency;+ return bothShelves && r ? (+ <ShelfBadge residency={r} offline={!live(r)} />+ ) : null;+ }}+ onOpen={gotoFolder}+ onCreate={async (name) => {+ if (!live(target)) return;+ const f = await createLibraryFolder(name, target);+ patch((d) => ({ ...d, folders: [...d.folders, f] }));+ }}+ onRename={async (id, name) => {+ const r = folders.find((f) => f.id === id)?.residency;+ if (!r || !live(r)) return;+ patch((d) => ({+ ...d,+ folders: d.folders.map((f) =>+ f.id === id ? { ...f, name } : f,+ ),+ }));+ await renameLibraryFolder(r, id, name).catch(() => void reload());+ }}+ onDelete={async (id) => {+ const r = folders.find((f) => f.id === id)?.residency;+ if (!r || !live(r)) return;+ patch((d) => ({+ folders: d.folders.filter((f) => f.id !== id),+ assets: d.assets.map((a) =>+ a.folderId === id ? { ...a, folderId: null } : a,+ ),+ templates: d.templates.map((t) =>+ t.folderId === id ? { ...t, folderId: null } : t,+ ),+ }));+ if (openFolder === id) router.replace(homeHref(base, "library"));+ await deleteLibraryFolder(r, id).catch(() => void reload());+ }}+ onDropIds={(ids, fid) => void moveItems(ids, fid)}+ onDropFiles={(files, fid) => void upload(files, fid)}+ />+ ) : null}++ {!library.data && library.isPending ? (+ <div className="grid place-items-center py-24 text-muted-foreground">+ <Loader2 className="size-5 animate-spin" /></div>- </button>- ) : shown.length === 0 && pending.length === 0 ? null : (- <Marquee- className="flex min-h-[40vh] flex-col content-start gap-8"- selected={selected}- setSelected={setSelected}- >- {[...shownBands.entries()].map(([shape, tiles]) => (- <div key={shape} className="flex flex-wrap items-start gap-4">- {tiles.map((tile) => {- if ("pending" in tile)+ ) : !hasContent ? (+ <button+ className="grid w-full cursor-pointer place-items-center rounded-2xl py-24"+ onClick={() => setAddOpen(true)}+ >+ <div className="flex flex-col items-center gap-3 text-center">+ <FolderOpen className="size-8 text-muted-foreground" />+ <div className="text-base font-medium">+ Your Library is shared across all projects.+ </div>+ <p className="text-sm text-muted-foreground">+ Drag and drop videos, images, audio, or font files here.+ </p>+ </div>+ </button>+ ) : shown.length === 0 &&+ pending.length === 0 &&+ shownTemplates.length === 0 ? null : (+ <Marquee+ className="flex min-h-[40vh] flex-col content-start gap-8"+ selected={selected}+ setSelected={setSelected}+ >+ {shownTemplates.length > 0 && (+ <div className="grid grid-cols-[repeat(auto-fill,minmax(240px,1fr))] gap-3">+ {shownTemplates.map((t) => (+ <TemplateCard+ key={t.id}+ template={t}+ mediaSrc={(f) => libraryMediaUrl(f, t.residency)}+ drag={+ live(t.residency)+ ? { scope: "library", template: t }+ : undefined+ }+ selectId={t.id}+ selected={selected.has(t.id)}+ onDragStartExtra={(e) => void dragSelection(e, t.id)}+ onRename={+ live(t.residency)+ ? (name) => void renameTpl(t.residency, t.id, name)+ : undefined+ }+ onDelete={+ live(t.residency)+ ? () => void removeTpl(t.residency, t.id)+ : undefined+ }+ />+ ))}+ </div>+ )}+ {[...shownBands.entries()].map(([shape, tiles]) => (+ <div key={shape} className="flex flex-wrap items-start gap-4">+ {tiles.map((tile) => {+ if ("pending" in tile)+ return (+ <PendingTile+ key={tile.pending.id}+ item={tile.pending}+ area={TILE_AREA}+ onRetry={() => retryPending(tile.pending)}+ onDismiss={() => dropPending(tile.pending.id)}+ />+ );+ const a = tile.asset;return (- <PendingTile- key={tile.pending.id}- item={tile.pending}+ <LibraryCard+ key={a.id}+ asset={a}area={TILE_AREA}- onRetry={() => retryPending(tile.pending)}- onDismiss={() => dropPending(tile.pending.id)}+ selected={selected.has(a.id)}+ offline={!live(a.residency)}+ // A live item opens in the viewer. Clicking one this browser+ // can only remember is the moment something is actually+ // blocked, so that is when the gate's banner — and the way+ // out of it — comes up.+ onClick={+ live(a.residency)+ ? () =>+ useLightbox.getState().open({+ kind: a.type,+ src: libraryMediaUrl(a.fileName, a.residency),+ name: a.name,+ prompt: "",+ assetId: null,+ libraryId: a.id,+ bare: true,+ ...(a.width && a.height+ ? { ratio: a.width / a.height }+ : {}),+ ...(libraryPosterUrl(a)+ ? { poster: libraryPosterUrl(a) }+ : {}),+ })+ : () => setNeedsApp(true)+ }+ onDelete={+ live(a.residency) ? () => setDeleting(a) : undefined+ }+ onDragStartExtra={(e) => onCardDragExtra(e, a)}/>);- const a = tile.asset;- return (- <LibraryCard- key={a.id}- asset={a}- area={TILE_AREA}- selected={selected.has(a.id)}- offline={!live(a.residency)}- // A live item opens in the viewer. Clicking one this browser- // can only remember is the moment something is actually- // blocked, so that is when the gate's banner — and the way- // out of it — comes up.- onClick={- live(a.residency)- ? () =>- useLightbox.getState().open({- kind: a.type,- src: libraryMediaUrl(a.fileName, a.residency),- name: a.name,- prompt: "",- assetId: null,- libraryId: a.id,- bare: true,- ...(a.width && a.height ? { ratio: a.width / a.height } : {}),- ...(libraryPosterUrl(a) ? { poster: libraryPosterUrl(a) } : {}),- })- : () => setNeedsApp(true)- }- onDelete={live(a.residency) ? () => setDeleting(a) : undefined}- onDragStartExtra={(e) => onCardDragExtra(e, a)}- />- );- })}- </div>- ))}- </Marquee>- )}+ })}+ </div>+ ))}+ </Marquee>+ )}- <Dialog open={addOpen} onOpenChange={setAddOpen}>- <DialogContent className="sm:max-w-md">- <DialogHeader>- <DialogTitle>Add media</DialogTitle>- </DialogHeader>- <div className="flex flex-col gap-4">- <button- className="flex flex-col items-center gap-2 rounded-xl py-8 transition-colors hover:bg-muted/40"- onClick={() => inputRef.current?.click()}- >- <Upload className="size-6 text-muted-foreground" />- <span className="text-sm font-medium">Choose files</span>- </button>- <div className="flex items-center gap-3 text-[11px] tracking-wide text-muted-foreground uppercase">- <div className="h-px flex-1 bg-border" /> or paste a link{" "}- <div className="h-px flex-1 bg-border" />- </div>- <div className="flex flex-col gap-1.5">- <div className="flex items-center gap-2">- <div className="relative flex-1">- <LinkIcon className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />- <Input- autoFocus- value={url}- placeholder="TikTok, YouTube, or Instagram link…"- className="pl-8"- onChange={(e) => setUrl(e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter") void importUrl();- }}- />+ <Dialog open={addOpen} onOpenChange={setAddOpen}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>Add media</DialogTitle>+ </DialogHeader>+ <div className="flex flex-col gap-4">+ <button+ className="flex flex-col items-center gap-2 rounded-xl py-8 transition-colors hover:bg-muted/40"+ onClick={() => inputRef.current?.click()}+ >+ <Upload className="size-6 text-muted-foreground" />+ <span className="text-sm font-medium">Choose files</span>+ </button>+ <div className="flex items-center gap-3 text-[11px] tracking-wide text-muted-foreground uppercase">+ <div className="h-px flex-1 bg-border" /> or paste a link{" "}+ <div className="h-px flex-1 bg-border" />+ </div>+ <div className="flex flex-col gap-1.5">+ <div className="flex items-center gap-2">+ <div className="relative flex-1">+ <LinkIcon className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />+ <Input+ autoFocus+ value={url}+ placeholder="TikTok, YouTube, or Instagram link…"+ className="pl-8"+ onChange={(e) => setUrl(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") void importUrl();+ }}+ />+ </div>+ <Button+ disabled={!url.trim()}+ onClick={() => void importUrl()}+ >+ <LinkIcon /> Import+ </Button></div>- <Button disabled={!url.trim()} onClick={() => void importUrl()}>- <LinkIcon /> Import- </Button></div></div>- </div>- </DialogContent>- </Dialog>+ </DialogContent>+ </Dialog>- <AlertDialog open={!!deleting} onOpenChange={(o) => !o && setDeleting(null)}>- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>Remove “{deleting?.name}” from the library?</AlertDialogTitle>- <AlertDialogDescription>- Projects that already use it keep their own copy.- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel>Cancel</AlertDialogCancel>- <AlertDialogAction- className="bg-destructive/10 text-destructive hover:bg-destructive/20"- onClick={(e) => {- e.preventDefault();- void remove();- }}- >- Remove- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>+ <AlertDialog+ open={!!deleting}+ onOpenChange={(o) => !o && setDeleting(null)}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ Remove “{deleting?.name}” from the library?+ </AlertDialogTitle>+ <AlertDialogDescription>+ Projects that already use it keep their own copy.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ className="bg-destructive/10 text-destructive hover:bg-destructive/20"+ onClick={(e) => {+ e.preventDefault();+ void remove();+ }}+ >+ Remove+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>- <Lightbox />- </div>+ <Lightbox />+ </div></div>);}+/** A font's card is set in the font: once the shelf sync has installed it, the+ * family resolves through the registry and the tile shows the typeface itself.+ * Until then (or on a shelf that isn't answering) it falls back to the UI face,+ * which still reads as a name. */export function LibraryCard({asset: a,selected,@@ -887,12 +1040,14 @@ export function LibraryCard({const [hovered, setHovered] = useState(false);const sizeBytes = useMediaFileSize(offline ? "" : libraryMediaUrl(a.fileName, a.residency),- hovered+ hovered,);const frame =area && a.type !== "audio" && a.width && a.height? { w: a.width, h: a.height }- : { w: 1, h: 1 };+ : a.type === "font"+ ? { w: 16, h: 9 }+ : { w: 1, h: 1 };const tileStyle = area? {width: Math.round(Math.sqrt((area * frame.w) / frame.h)),@@ -929,8 +1084,10 @@ export function LibraryCard({data-drag-objectclassName={cn("relative max-w-full cursor-grab overflow-hidden rounded-xl border bg-muted transition-shadow group-hover:shadow-[0_4px_20px_rgba(0,0,0,0.1)] active:cursor-grabbing",- !area && "aspect-square",- selected || flash ? "border-[#0a84ff] ring-2 ring-[#0a84ff]" : "border-border"+ !area && (a.type === "font" ? "aspect-video" : "aspect-square"),+ selected || flash+ ? "border-[#0a84ff] ring-2 ring-[#0a84ff]"+ : "border-border",)}style={tileStyle}>@@ -942,6 +1099,8 @@ export function LibraryCard({<Music className="size-6 text-muted-foreground/50" />) : a.type === "image" ? (<ImageIcon className="size-6 text-muted-foreground/50" />+ ) : a.type === "font" ? (+ <Type className="size-6 text-muted-foreground/50" />) : (<Film className="size-6 text-muted-foreground/50" />)}@@ -979,13 +1138,26 @@ export function LibraryCard({)) : a.type === "image" ? (// eslint-disable-next-line @next/next/no-img-element -- library media file, not Next-optimizable- <img crossOrigin={MEDIA_CORS} src={libraryMediaUrl(a.fileName, a.residency)} alt={a.name} loading="lazy" className="size-full object-cover" />+ <img+ crossOrigin={MEDIA_CORS}+ src={libraryMediaUrl(a.fileName, a.residency)}+ alt={a.name}+ loading="lazy"+ className="size-full object-cover"+ />+ ) : a.type === "font" ? (+ <FontSpecimen+ assetId={a.id}+ className="size-full bg-white text-black"+ />) : (<AudioCardFaceurl={libraryMediaUrl(a.fileName, a.residency)}duration={a.duration}// On hover the + button takes the pill's corner.- durationClassName={!!onUse && "transition-opacity group-hover:opacity-0"}+ durationClassName={+ !!onUse && "transition-opacity group-hover:opacity-0"+ }/>)}{a.type !== "audio" && (a.type === "video" || sizeBytes != null) && (@@ -996,7 +1168,8 @@ export function LibraryCard({data-drag-omitclassName={cn("absolute right-1.5 bottom-1.5 rounded-md bg-black/65 px-1.5 py-0.5 font-mono text-[10px] text-white tabular-nums",- a.type !== "video" && "opacity-0 transition-opacity group-hover:opacity-100"+ a.type !== "video" &&+ "opacity-0 transition-opacity group-hover:opacity-100",)}>{a.type === "video" && (@@ -1005,7 +1178,11 @@ export function LibraryCard({</span>)}{sizeBytes != null && (- <span className={cn(a.type === "video" && "hidden group-hover:inline")}>+ <span+ className={cn(+ a.type === "video" && "hidden group-hover:inline",+ )}+ >{formatBytes(sizeBytes)}</span>)}@@ -1024,7 +1201,9 @@ export function LibraryCard({className={cn("absolute grid size-6 place-items-center rounded-full bg-primary text-primary-foreground opacity-0 shadow transition-all group-hover:opacity-100 hover:scale-110",// Audio keeps play bottom-left; + swaps in where the badge hides.- a.type === "audio" ? "right-1.5 bottom-1.5" : "bottom-1.5 left-1.5"+ a.type === "audio"+ ? "right-1.5 bottom-1.5"+ : "bottom-1.5 left-1.5",)}onClick={(e) => {e.stopPropagation();@@ -1042,7 +1221,7 @@ export function LibraryCard({"absolute top-2 right-2 transition-opacity",offline ? "text-muted-foreground" : "text-white/85",// The actions menu takes this corner on hover.- "group-hover:opacity-0"+ "group-hover:opacity-0",)}/>)}@@ -1055,15 +1234,24 @@ export function LibraryCard({><Ellipsis className="size-3.5" /></DropdownMenuTrigger>- <DropdownMenuContent align="end" className="w-44" onClick={(e) => e.stopPropagation()}>- <DropdownMenuItem onClick={() => downloadLibraryAsset(a)} disabled={offline}>+ <DropdownMenuContent+ align="end"+ className="w-44"+ onClick={(e) => e.stopPropagation()}+ >+ <DropdownMenuItem+ onClick={() => downloadLibraryAsset(a)}+ disabled={offline}+ ><Download /> Download</DropdownMenuItem>{a.source?.url && (// An imported clip keeps the link it came from, so the post it was// cut out of is one click away.<DropdownMenuItem- onClick={() => window.open(a.source!.url, "_blank", "noopener,noreferrer")}+ onClick={() =>+ window.open(a.source!.url, "_blank", "noopener,noreferrer")+ }><ExternalLink /> Open original</DropdownMenuItem>@@ -1085,7 +1273,7 @@ export function LibraryCard({className={cn("absolute top-1.5 left-1.5 max-w-[70%] px-2 py-1 text-[11px] font-medium text-white transition-[max-width] group-hover:max-w-[calc(100%-2.75rem)]",// The emerald fill is its own backdrop; thumbnails need the scrim pill.- a.type !== "audio" && "rounded-lg bg-black/55 backdrop-blur-sm"+ a.type !== "audio" && "rounded-lg bg-black/55 backdrop-blur-sm",)}/></div>diff --git a/site/src/cut/components/Lightbox.tsx b/site/src/cut/components/Lightbox.tsxindex 4e4cdcb5..d35e52a6 100644--- a/site/src/cut/components/Lightbox.tsx+++ b/site/src/cut/components/Lightbox.tsx@@ -3,6 +3,7 @@import { useEffect, useRef, useState } from "react";import { Check, Copy, FileText, Loader2, Music, Plus, X } from "lucide-react";import { Button } from "@/components/ui/button";+import { cn } from "@/lib/utils";import { MEDIA_CORS } from "@/cut/lib/mediaCors";import { addLibraryAssetToProject, fetchLibrary } from "@/cut/lib/library";import { useLightbox, type LightboxItem } from "@/cut/lib/lightbox";@@ -10,6 +11,7 @@ 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 { FontSpecimen } from "./FontSpecimen";import { PeakStrip } from "./AudioPanel";// The asset lightbox: the big version of a stock, generated, or chat asset@@ -52,14 +54,19 @@ export function Lightbox() {} 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);+ 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 =item.kind === "video"- ? await importStockVideo(projectId, { url: item.src, name: item.name })+ ? await importStockVideo(projectId, {+ url: item.src,+ name: item.name,+ }): await importImage(projectId, { url: item.src, name: item.name });useEditor.getState().addAssetAtPlayhead(asset.id);}@@ -76,7 +83,10 @@ export function Lightbox() {const canAdd =!item.bare &&item.kind !== "text" &&- (item.kind !== "audio" || item.assetId !== null || item.libraryId !== undefined);+ item.kind !== "font" &&+ (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@@ -86,11 +96,13 @@ export function Lightbox() {const width =item.kind === "audio"? "min(92vw, 480px)"- : item.kind === "text"- ? "min(92vw, 720px)"- : ratio- ? `min(92vw, 860px, ${Math.round(68 * ratio * 100) / 100}vh)`- : "min(92vw, 860px)";+ : item.kind === "font"+ ? "min(92vw, 1000px)"+ : item.kind === "text"+ ? "min(92vw, 720px)"+ : ratio+ ? `min(92vw, 860px, ${Math.round(68 * ratio * 100) / 100}vh)`+ : "min(92vw, 860px)";return (<div@@ -121,7 +133,10 @@ export function Lightbox() {{canAdd && (<Button className="shrink-0" disabled={adding} onClick={add}>{adding ? (- <Loader2 data-icon="inline-start" className="animate-spin" />+ <Loader2+ data-icon="inline-start"+ className="animate-spin"+ />) : added ? (<Check data-icon="inline-start" />) : (@@ -142,13 +157,19 @@ export function Lightbox() {title="Copy prompt"className="inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10.5px] font-medium text-white/60 transition-colors hover:bg-white/10 hover:text-white"onClick={() => {- void navigator.clipboard.writeText(item.prompt).then(() => {- setCopied(true);- setTimeout(() => setCopied(false), 1500);- });+ void navigator.clipboard+ .writeText(item.prompt)+ .then(() => {+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ });}}>- {copied ? <Check className="size-3 text-emerald-400" /> : <Copy className="size-3" />}+ {copied ? (+ <Check className="size-3 text-emerald-400" />+ ) : (+ <Copy className="size-3" />+ )}{copied ? "Copied" : "Copy"}</button></div>@@ -164,9 +185,16 @@ export function Lightbox() {);}-function LightboxMedia({ item, ratio }: { item: LightboxItem; ratio?: number }) {+function LightboxMedia({+ item,+ ratio,+}: {+ item: LightboxItem;+ ratio?: number;+}) {if (item.kind === "audio") return <AudioBody item={item} />;if (item.kind === "text") return <TextBody item={item} />;+ if (item.kind === "font") return <FontBody item={item} />;const mediaClass = ratio? "block w-full rounded-2xl bg-black object-cover shadow-2xl"@@ -175,7 +203,8 @@ function LightboxMedia({ item, ratio }: { item: LightboxItem; ratio?: number })if (item.kind === "video") {return (- <video crossOrigin={MEDIA_CORS}+ <video+ crossOrigin={MEDIA_CORS}controlsautoPlayloop@@ -189,13 +218,19 @@ function LightboxMedia({ item, ratio }: { item: LightboxItem; ratio?: number })}return (// eslint-disable-next-line @next/next/no-img-element -- static/project image, client-only page- <img crossOrigin={MEDIA_CORS} src={item.src} alt={item.name} className={mediaClass} style={mediaStyle} />+ <img+ crossOrigin={MEDIA_CORS}+ src={item.src}+ alt={item.name}+ className={mediaClass}+ style={mediaStyle}+ />);}function AudioBody({ item }: { item: LightboxItem }) {const asset = useEditor((s) =>- item.assetId ? s.assets.find((a) => a.id === item.assetId) : undefined+ 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@@ -212,7 +247,32 @@ function AudioBody({ item }: { item: LightboxItem }) {{asset?.peaks && asset.peaks.length > 0 && (<PeakStrip peaks={asset.peaks} className="h-10 text-white/85" />)}- <audio ref={audioEl} controls autoPlay src={item.src} className="w-full" />+ <audio+ ref={audioEl}+ controls+ autoPlay+ src={item.src}+ className="w-full"+ />+ </div>+ );+}++/** A font, big: the sheet a font file previews on, the alphabet filling it. */+function FontBody({ item }: { item: LightboxItem }) {+ return (+ <div+ className={cn(+ "overflow-hidden rounded-2xl bg-white text-black shadow-2xl",+ item.poster ? "" : "px-10 py-12"+ )}+ >+ <FontSpecimen+ assetId={item.libraryId ?? ""}+ poster={item.poster}+ pad={0}+ className="w-full"+ /></div>);}diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsxindex 8fae7b33..bc3409c3 100644--- a/site/src/cut/components/SidePanel.tsx+++ b/site/src/cut/components/SidePanel.tsx@@ -72,6 +72,15 @@ import {} from "@/cut/lib/residency";import { isStylePresetTemplate } from "@/cut/lib/stylePresets";import { retryUpload } from "@/cut/lib/importQueue";+import {+ forgetLinkedCopy,+ expandLinkedFiles,+ isLinkedFile,+ linkedAccept,+ isLinkedType,+ shelfForNewItem,+ syncLinkedLibrary,+} from "@/cut/lib/linkedLibrary";import { downloadMedia, isMediaFile, revealMedia } from "@/cut/lib/media";import { mediaUrl, TRANSITION_MAX } from "@/cut/lib/types";import { parseSecondsInput } from "@/cut/components/ScrubValue";@@ -731,7 +740,7 @@ function ProjectFilesPanel({<inputref={inputRef}type="file"- accept="video/*,audio/*"+ accept={`video/*,audio/*,${linkedAccept()}`}multiplehiddenonChange={(e) => {@@ -1214,6 +1223,7 @@ function LibraryPanel({ projectId }: { projectId: string }) {const { id, residency } = deleting;setAssets((prev) => (prev ?? []).filter((a) => a.id !== id));setDeleting(null);+ if (isLinkedType(deleting.type)) forgetLinkedCopy(id);try {await deleteFromLibrary(residency, id);} catch {@@ -1244,18 +1254,27 @@ function LibraryPanel({ projectId }: { projectId: string }) {(folderId ? folders.find((f) => f.id === folderId)?.residency : null) ?? activeResidency();const upload = async (files: FileList | File[], folderId: string | null = openFolder) => {- const list = Array.from(files).filter(isMediaFile);+ const list = (await expandLinkedFiles(Array.from(files))).filter(+ (f) => isMediaFile(f) || isLinkedFile(f)+ );if (list.length === 0) return;const residency = shelfForNew(folderId);setUploading((n) => n + list.length);for (const file of list) {try {- const asset = await uploadToLibrary(file, residency);+ // Something the Library lends rather than copies, dropped outside a+ // folder, takes the shelf every surface can read; dropped into one, the+ // folder still decides.+ const shelf =+ isLinkedFile(file) && !folderId ? await shelfForNewItem(file.size) : residency;+ const asset = await uploadToLibrary(file, shelf);if (folderId) {- await moveLibraryItem(residency, asset.id, folderId).catch(() => {});+ await moveLibraryItem(shelf, asset.id, folderId).catch(() => {});asset.folderId = folderId;}setAssets((prev) => [asset, ...(prev ?? [])]);+ // A lent item is only usable once it is in reach of the menus.+ if (isLinkedType(asset.type)) void syncLinkedLibrary();} catch {// Skip unreadable files; the rest of the batch still uploads.} finally {@@ -1413,7 +1432,8 @@ function LibraryPanel({ projectId }: { projectId: string }) {) : null) : all.length === 0 && folders.length === 0 && templates.length === 0 ? (<div className="text-balance px-3.5 py-6 text-center text-xs text-muted-foreground">- Drag video, audio and image assets here. Library assets are shared across all projects.+ Drag video, audio, image and font files here. Library assets are shared across all+ projects.</div>) : null) : (@@ -1426,7 +1446,10 @@ function LibraryPanel({ projectId }: { projectId: string }) {key={a.id}asset={a}mention- onUse={() => void addLibraryAssetToProject(projectId, a)}+ // A font is used from the font menu; there is nothing to place.+ onUse={+ a.type === "font" ? undefined : () => void addLibraryAssetToProject(projectId, a)+ }onDelete={() => setDeleting(a)}onDragStartExtra={(e) => onCardDragExtra(e, a)}/>diff --git a/site/src/cut/components/SubtitlesPanel.tsx b/site/src/cut/components/SubtitlesPanel.tsxindex 6d940c4c..88949622 100644--- a/site/src/cut/components/SubtitlesPanel.tsx+++ b/site/src/cut/components/SubtitlesPanel.tsx@@ -3,15 +3,9 @@import React, { memo, useEffect, useRef, useState } from "react";import { AlertCircle, Captions, ChevronDown, Languages, Loader2, RefreshCw } from "lucide-react";import { Button } from "@/components/ui/button";-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from "@/components/ui/select";import { Switch } from "@/components/ui/switch";import { ColorField } from "@/cut/components/ColorField";+import { FontPicker } from "@/cut/components/FontPicker";import { parseNumberInput } from "@/cut/components/ScrubValue";import { ValueSlider } from "@/cut/components/ValueSlider";import { GenerateSubtitlesAudio } from "@/cut/components/VoicePicker";@@ -30,7 +24,6 @@ import { TIMELINE_H_MIN, useEditor } from "@/cut/lib/store";import { usePreviewSelector } from "@/cut/lib/playhead";import { PLATE_PAD_X, PLATE_PAD_Y, PLATE_RADIUS, plateFill } from "@/cut/lib/textRender";import {- FONTS,fontStack,type FontId,type SubtitleCue,@@ -231,22 +224,11 @@ function OptionsTab() {</label><div className="flex min-h-8 items-center justify-between text-xs font-medium">Font- <Select+ <FontPicker+ className="sub-font w-28"value={subtitles.font ?? captionStyle(subtitles.style).font}- items={Object.fromEntries(FONTS.map((f) => [f.id, f.label]))}- onValueChange={(v) => useEditor.getState().setSubtitlesView({ font: v as FontId })}- >- <SelectTrigger size="sm" className="sub-font w-28">- <SelectValue />- </SelectTrigger>- <SelectContent>- {FONTS.map((f) => (- <SelectItem key={f.id} value={f.id}>- <span style={{ fontFamily: fontStack(f.id) }}>{f.label}</span>- </SelectItem>- ))}- </SelectContent>- </Select>+ onChange={(v) => useEditor.getState().setSubtitlesView({ font: v as FontId })}+ /></div><div className="flex min-h-8 items-center justify-between text-xs font-medium">Sizediff --git a/site/src/cut/components/TemplateCard.tsx b/site/src/cut/components/TemplateCard.tsxindex 97614a63..f28b0646 100644--- a/site/src/cut/components/TemplateCard.tsx+++ b/site/src/cut/components/TemplateCard.tsx@@ -56,6 +56,8 @@ export function TemplateCard({onRefDrop,onDragStartExtra,extraMenu,+ selectId,+ selected = false,}: {template: LibraryTemplate;/** Resolve a template media file to a playable URL (project or library). */@@ -76,6 +78,10 @@ export function TemplateCard({onDragStartExtra?: (e: React.DragEvent) => void;/** Extra menu items rendered between Rename and Delete. */extraMenu?: React.ReactNode;+ /** Marks the card as sweepable by a marquee under this id, so a template+ * files into folders in the same selection as the media around it. */+ selectId?: string;+ selected?: boolean;}) {const refDrop = useAssetDrop((r) => onRefDrop?.(r));const [renaming, setRenaming] = useState(false);@@ -90,7 +96,8 @@ export function TemplateCard({// equalizer — sound needs no floating preview.const [audioRow, setAudioRow] = useState<number | null>(null);- const itemCount = t.layers.length + t.audio.length + t.texts.length + t.cues.length;+ const itemCount =+ t.layers.length + t.audio.length + t.texts.length + t.cues.length;// The contents, one row per item, in save order: clips and stills, sounds,// titles, then a caption count.@@ -140,8 +147,10 @@ export function TemplateCard({<divref={onRefDrop ? refDrop.attachTarget : undefined}{...(onRefDrop ? refDrop.targetProps : {})}+ data-sel-id={selectId}className={cn(- "group flex flex-col rounded-lg border border-border bg-background px-2.5 py-1.5",+ "group flex flex-col rounded-lg border bg-background px-2.5 py-1.5",+ selected ? "border-[#0a84ff] ring-2 ring-[#0a84ff]" : "border-border",drag ? "cursor-grab active:cursor-grabbing" : "cursor-pointer",onRefDrop && refDrop.active && "border-primary bg-primary/10",)}@@ -180,7 +189,8 @@ export function TemplateCard({<div className="truncate text-[12px] font-medium">{t.name}</div>)}<div className="flex items-center gap-0.5 text-[10.5px] text-muted-foreground">- {formatTime(t.duration)} · {itemCount} item{itemCount === 1 ? "" : "s"}+ {formatTime(t.duration)} · {itemCount} item+ {itemCount === 1 ? "" : "s"}<ChevronDownclassName={cn("size-3 transition-transform",diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex 046059a6..187c650a 100644--- a/site/src/cut/components/Timeline.tsx+++ b/site/src/cut/components/Timeline.tsx@@ -1761,7 +1761,7 @@ export function Timeline() {let duration = 0;if (isLib) {const lib = draggingLibrary();- type = lib?.type;+ type = lib && lib.type !== "font" ? lib.type : undefined;duration = lib?.duration ?? 0;} else if (stockMusic) {type = "audio";diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.tsindex d0de8b4a..2e3c42f9 100644--- a/site/src/cut/lib/aiContext.ts+++ b/site/src/cut/lib/aiContext.ts@@ -7,7 +7,16 @@ import { getClipSpans, overlayLayers, resolveTransitions, totalDuration, useEditimport { playheadAt, skimAt } from "./playhead";import { laneCues, subtitleLaneCount } from "./subtitles";import { watchSweepActive } from "./watch/sweep";-import { frameOf, rectOf, regionLabel, type ClipSpan, type Overlay, type VideoClip } from "./types";+import { libraryFontId, listLibraryFonts } from "./linkedLibrary";+import {+ frameOf,+ rectOf,+ regionLabel,+ uploadedFontId,+ type ClipSpan,+ type Overlay,+ type VideoClip,+} from "./types";const r = (n: number) => Math.round(n * 100) / 100;@@ -86,7 +95,9 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu// content, so it stays visible even when a chat made it.const ownedByOtherChat = (a: { origin?: string; chatId?: string; id: string }) =>a.origin === "chat" && !!a.chatId && a.chatId !== chatId && !placed.has(a.id);- const visibleAssets = s.assets.filter((a) => !ownedByOtherChat(a));+ // A font asset is a typeface, not footage: it is listed under `fonts` with+ // the account's shelf fonts, where a font id is what the model needs.+ const visibleAssets = s.assets.filter((a) => a.type !== "font" && !ownedByOtherChat(a));// The cap trims the tail of a huge media list, and a source someone has// watched and written up stays regardless of where it sits: the record is// what later decisions are made from.@@ -165,6 +176,15 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu// another chat still owns is filtered out above). `origin` marks Cut-made// media (generated/voiceover/recording/stock/freeze); no origin = a user// import shown in the Media panel.+ // Every font a title or caption can be set in beyond the built-in list:+ // the account's own, off the Library shelf, plus any still living in this+ // project from before fonts moved to the shelf.+ fonts: [+ ...listLibraryFonts().map((f) => ({ id: libraryFontId(f.key), label: f.label })),+ ...s.assets+ .filter((a) => a.type === "font")+ .map((a) => ({ id: uploadedFontId(a.id), label: a.name })),+ ],media: shownAssets.map((a) => ({id: a.id,name: a.name,diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 8fbd669b..0bf93610 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -2099,6 +2099,10 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {const lib = (await fetchLibrary()).assets.find((a) => a.id === String(input.id ?? ""));if (!lib)throw new ToolError(`No library asset with id ${String(input.id)}. Call library_list for ids.`);+ if (lib.type === "font")+ throw new ToolError(+ `"${lib.name}" is a font. It is already available to this project — set a title or the captions to font id font:${lib.id}.`+ );// Captured before the import: the media files under the chat that asked,// even if the user switches threads while it copies.const chatId = chatOwner();diff --git a/site/src/cut/lib/assetDrag.ts b/site/src/cut/lib/assetDrag.tsindex d5e57e0e..8ccbd1de 100644--- a/site/src/cut/lib/assetDrag.ts+++ b/site/src/cut/lib/assetDrag.ts@@ -260,6 +260,11 @@ export function setObjectDragImage(e: React.DragEvent) {object.style.height = `${rect.height}px`;object.style.margin = "0";object.style.opacity = "0.85";+ // The ghost floats free of the page, so its edge is drawn at twice the+ // strength the card wears in the grid: a pale tile lifted over a pale+ // backdrop has no shape otherwise.+ const edge = getComputedStyle(el).borderTopColor;+ if (edge) object.style.borderColor = `color-mix(in oklab, ${edge}, black 50%)`;object.style.transition = "opacity 150ms ease, transform 150ms ease";object.style.transformOrigin = `${ox}px ${oy}px`;object.style.transform = `scale(${fit})`;diff --git a/site/src/cut/lib/assetRef.ts b/site/src/cut/lib/assetRef.tsindex c29ca6f4..a78e251e 100644--- a/site/src/cut/lib/assetRef.ts+++ b/site/src/cut/lib/assetRef.ts@@ -109,7 +109,8 @@ export const refFromLibrary = (a: LibraryAsset): AssetRef => ({scope: "library",id: a.id,name: a.name,- kind: a.type,+ // A font is not media to point a tool at; the mapping only stays total.+ kind: a.type === "font" ? "text" : a.type,url: libraryMediaUrl(a.fileName, a.residency),duration: a.duration,...(a.width !== undefined ? { width: a.width } : {}),diff --git a/site/src/cut/lib/backend/browser/library.ts b/site/src/cut/lib/backend/browser/library.tsindex 6a5cc20b..efc435ea 100644--- a/site/src/cut/lib/backend/browser/library.ts+++ b/site/src/cut/lib/backend/browser/library.ts@@ -87,11 +87,13 @@ async function mutateIndex<T>(fn: (idx: LibraryIndex) => T): Promise<T> {const VIDEO_RE = /\.(mp4|mov|m4v|webm|mkv)$/i;const AUDIO_RE = /\.(mp3|m4a|aac|wav|ogg|flac)$/i;const IMAGE_RE = /\.(png|jpe?g|webp|gif|avif|bmp)$/i;+const FONT_RE = /\.(ttf|otf|woff2?)$/i;function typeOf(fileName: string): AssetType | null {if (VIDEO_RE.test(fileName)) return "video";if (AUDIO_RE.test(fileName)) return "audio";if (IMAGE_RE.test(fileName)) return "image";+ if (FONT_RE.test(fileName)) return "font";return null;}diff --git a/site/src/cut/lib/fontArchive.test.ts b/site/src/cut/lib/fontArchive.test.tsnew file mode 100644index 00000000..ddaf2e54--- /dev/null+++ b/site/src/cut/lib/fontArchive.test.ts@@ -0,0 +1,113 @@+import { expect, test } from "bun:test";++import { fontsFromArchive, isFontArchive } from "./fontArchive";++type Bytes = Uint8Array<ArrayBuffer>;++interface Entry {+ name: string;+ body: Bytes;+ deflated?: Bytes;+}++async function deflate(bytes: Bytes): Promise<Bytes> {+ const stream = new Blob([bytes]).stream().pipeThrough(new CompressionStream("deflate-raw"));+ return new Uint8Array(await new Response(stream).arrayBuffer());+}++/** A zip, built by hand: the reader ignores CRCs and timestamps, so they stay+ * zero and the fixture stays readable. */+function zip(entries: Entry[]): File {+ const enc = new TextEncoder();+ const locals: Bytes[] = [];+ const central: Bytes[] = [];+ let at = 0;+ for (const e of entries) {+ const name = enc.encode(e.name);+ const stored = e.deflated ?? e.body;+ const local = new Uint8Array(30 + name.length + stored.length);+ const lv = new DataView(local.buffer);+ lv.setUint32(0, 0x04034b50, true);+ lv.setUint16(8, e.deflated ? 8 : 0, true);+ lv.setUint32(18, stored.length, true);+ lv.setUint32(22, e.body.length, true);+ lv.setUint16(26, name.length, true);+ local.set(name, 30);+ local.set(stored, 30 + name.length);+ locals.push(local);++ const dir = new Uint8Array(46 + name.length);+ const dv = new DataView(dir.buffer);+ dv.setUint32(0, 0x02014b50, true);+ dv.setUint16(10, e.deflated ? 8 : 0, true);+ dv.setUint32(20, stored.length, true);+ dv.setUint32(24, e.body.length, true);+ dv.setUint16(28, name.length, true);+ dv.setUint32(42, at, true);+ dir.set(name, 46);+ central.push(dir);+ at += local.length;+ }+ const dirSize = central.reduce((n, c) => n + c.length, 0);+ const end = new Uint8Array(22);+ const ev = new DataView(end.buffer);+ ev.setUint32(0, 0x06054b50, true);+ ev.setUint16(8, entries.length, true);+ ev.setUint16(10, entries.length, true);+ ev.setUint32(12, dirSize, true);+ ev.setUint32(16, at, true);+ return new File([...locals, ...central, end], "download.zip", { type: "application/zip" });+}++const bytes = (s: string) => new TextEncoder().encode(s) as Bytes;++test("a zip is recognized by extension or type", () => {+ expect(isFontArchive(new File([], "Imperial_Script.zip"))).toBe(true);+ expect(isFontArchive(new File([], "font.ttf"))).toBe(false);+});++test("takes one face per family and leaves the licence behind", async () => {+ const out = await fontsFromArchive(+ zip([+ { name: "Imperial_Script/OFL.txt", body: bytes("licence") },+ { name: "Imperial_Script/ImperialScript-Bold.ttf", body: bytes("bold") },+ { name: "Imperial_Script/ImperialScript-Regular.ttf", body: bytes("regular") },+ { name: "__MACOSX/._ImperialScript-Regular.ttf", body: bytes("junk") },+ ])+ );+ expect(out.map((f) => f.name)).toEqual(["ImperialScript-Regular.ttf"]);+ expect(await out[0].text()).toBe("regular");+});++test("a variable font wins over the static faces beside it", async () => {+ const out = await fontsFromArchive(+ zip([+ { name: "static/Montserrat-Regular.ttf", body: bytes("static") },+ { name: "Montserrat-VariableFont_wght.ttf", body: bytes("variable") },+ ])+ );+ expect(out).toHaveLength(1);+ expect(await out[0].text()).toBe("variable");+});++test("separate families each keep a face", async () => {+ const out = await fontsFromArchive(+ zip([+ { name: "Inter-Regular.otf", body: bytes("inter") },+ { name: "Lora-Regular.otf", body: bytes("lora") },+ ])+ );+ expect(out.map((f) => f.name).sort()).toEqual(["Inter-Regular.otf", "Lora-Regular.otf"]);+});++test("reads a deflated entry", async () => {+ const body = bytes("font bytes ".repeat(40));+ const out = await fontsFromArchive(+ zip([{ name: "Cera-Regular.ttf", body, deflated: await deflate(body) }])+ );+ expect(await out[0].text()).toBe(new TextDecoder().decode(body));+});++test("a file that is not a zip yields nothing", async () => {+ expect(await fontsFromArchive(new File([bytes("not a zip")], "x.zip"))).toEqual([]);+});diff --git a/site/src/cut/lib/fontArchive.ts b/site/src/cut/lib/fontArchive.tsnew file mode 100644index 00000000..4c108c18--- /dev/null+++ b/site/src/cut/lib/fontArchive.ts@@ -0,0 +1,137 @@+/**+ * Font files out of a .zip.+ *+ * A zip is what a font arrives as — Google Fonts hands you one, and so do most+ * foundries — so a zip is what a user drags onto the Library. Reading it here+ * means the file they have in hand is the file that works.+ *+ * Just enough of the ZIP format to walk the central directory and inflate the+ * entries that are fonts; `DecompressionStream` does the real work and exists+ * in both a page and a job.+ */++const FONT_ENTRY = /\.(ttf|otf|woff2?)$/i;+/** Finder's resource-fork shadow directory, and dotfiles generally. */+const JUNK = /(^|\/)(__MACOSX\/|\.)/;++export function isFontArchive(file: File): boolean {+ return file.type === "application/zip" || /\.zip$/i.test(file.name);+}++interface ZipEntry {+ name: string;+ method: number;+ compressedSize: number;+ localHeaderAt: number;+}++/** Walk the central directory backwards from the end-of-directory record. */+function readDirectory(v: DataView): ZipEntry[] {+ const end = v.byteLength;+ let eocd = -1;+ // The record is 22 bytes plus a comment of up to 64KB.+ for (let at = end - 22; at >= 0 && at > end - 22 - 0x10000; at--) {+ if (v.getUint32(at, true) === 0x06054b50) {+ eocd = at;+ break;+ }+ }+ if (eocd < 0) return [];+ const count = v.getUint16(eocd + 10, true);+ let at = v.getUint32(eocd + 16, true);+ const entries: ZipEntry[] = [];+ for (let i = 0; i < count; i++) {+ if (at + 46 > end || v.getUint32(at, true) !== 0x02014b50) break;+ const nameLen = v.getUint16(at + 28, true);+ const extraLen = v.getUint16(at + 30, true);+ const commentLen = v.getUint16(at + 32, true);+ entries.push({+ name: new TextDecoder().decode(+ new Uint8Array(v.buffer, at + 46, nameLen),+ ),+ method: v.getUint16(at + 10, true),+ compressedSize: v.getUint32(at + 20, true),+ localHeaderAt: v.getUint32(at + 42, true),+ });+ at += 46 + nameLen + extraLen + commentLen;+ }+ return entries;+}++async function readEntry(+ buf: ArrayBuffer,+ v: DataView,+ entry: ZipEntry,+): Promise<Blob | null> {+ const at = entry.localHeaderAt;+ if (at + 30 > v.byteLength || v.getUint32(at, true) !== 0x04034b50)+ return null;+ const from =+ at + 30 + v.getUint16(at + 26, true) + v.getUint16(at + 28, true);+ const raw = buf.slice(from, from + entry.compressedSize);+ if (entry.method === 0) return new Blob([raw]);+ if (entry.method !== 8) return null; // Only stored and deflated; fonts are one or the other.+ try {+ const stream = new Blob([raw])+ .stream()+ .pipeThrough(new DecompressionStream("deflate-raw"));+ return await new Response(stream).blob();+ } catch {+ return null;+ }+}++/** The family a face belongs to, from its file name: "Montserrat-Bold.ttf" and+ * "Montserrat-Regular.ttf" are one family. */+const familyOf = (name: string) =>+ name+ .replace(/\.[^.]+$/, "")+ .split(/[-_]/)[0]+ .toLowerCase();++/** How much a face wants to be the one taken from its family: a variable font+ * covers every weight, and a regular is the face a family is read in. */+function rank(name: string): number {+ if (/variablefont/i.test(name)) return 3;+ if (/-regular\./i.test(name)) return 2;+ if (/italic|bold|light|thin|black|medium|semi|extra/i.test(name)) return 0;+ return 1;+}++/**+ * The fonts worth taking out of an archive: one face per family.+ *+ * A family download carries a face per weight — eighteen of them, for some — so+ * taking every one would fill the font menu with near-identical rows and charge+ * the account for all of them. The face that stands for the family comes out,+ * weight and italic stay the inspector's controls, and someone who wants a+ * particular weight uploads that file on its own.+ */+export async function fontsFromArchive(file: File): Promise<File[]> {+ let buf: ArrayBuffer;+ try {+ buf = await file.arrayBuffer();+ } catch {+ return [];+ }+ const v = new DataView(buf);+ const fonts = readDirectory(v).filter(+ (e) => FONT_ENTRY.test(e.name) && !JUNK.test(e.name),+ );+ const best = new Map<string, ZipEntry>();+ for (const entry of fonts) {+ const base = entry.name.split("/").pop() ?? entry.name;+ const family = familyOf(base);+ const held = best.get(family);+ if (!held || rank(base) > rank(held.name.split("/").pop() ?? held.name)) {+ best.set(family, entry);+ }+ }+ const out: File[] = [];+ for (const entry of best.values()) {+ const blob = await readEntry(buf, v, entry);+ if (blob)+ out.push(new File([blob], entry.name.split("/").pop() ?? entry.name));+ }+ return out;+}diff --git a/site/src/cut/lib/fontAssets.ts b/site/src/cut/lib/fontAssets.tsindex 1f96a264..ed2ffc01 100644--- a/site/src/cut/lib/fontAssets.ts+++ b/site/src/cut/lib/fontAssets.ts@@ -38,6 +38,14 @@ export function setFontInstaller(install: FontInstaller): void {installFace = install;}+/** Install one face through whichever seam this process filled. Font bytes+ * reach a family exactly one way, whether they came off a project's media+ * folder or the account's Library shelf. Throws on bytes that are not a font,+ * which is what makes it double as the upload's validity check. */+export function installFontFace(family: string, bytes: ArrayBuffer): Promise<void> {+ return installFace(family, bytes);+}+/** A display label from the uploaded file's name, extension dropped. */const fontLabel = (name: string) => name.replace(/\.(ttf|otf|woff2?|TTF|OTF)$/, "") || "Custom font";diff --git a/site/src/cut/lib/fontCatalog.ts b/site/src/cut/lib/fontCatalog.tsnew file mode 100644index 00000000..3a080b3f--- /dev/null+++ b/site/src/cut/lib/fontCatalog.ts@@ -0,0 +1,33 @@+/**+ * The bundled font families, named once.+ *+ * `googleFonts.ts` maps the next/font loaders onto this list to register them,+ * and the assistant's catalog builds its font sentence from it, so the menu the+ * user sees and the ids the model is taught can't drift apart. Framework-free+ * on purpose: the server imports it too.+ */++export interface BundledFont {+ id: string;+ label: string;+}++export const GOOGLE_FONTS: BundledFont[] = [+ { id: "inter", label: "Inter" },+ { id: "montserrat", label: "Montserrat" },+ { id: "poppins", label: "Poppins" },+ { id: "oswald", label: "Oswald" },+ { id: "space-grotesk", label: "Space Grotesk" },+ { id: "playfair", label: "Playfair Display" },+ { id: "caveat", label: "Caveat" },+ { id: "bebas", label: "Bebas Neue" },+ { id: "anton", label: "Anton" },+ { id: "archivo-black", label: "Archivo Black" },+ { id: "bangers", label: "Bangers" },+ { id: "lobster", label: "Lobster" },+ { id: "pacifico", label: "Pacifico" },+ { id: "permanent-marker", label: "Permanent Marker" },+ { id: "dm-serif", label: "DM Serif Display" },+];++export const GOOGLE_FONT_IDS = GOOGLE_FONTS.map((f) => f.id);diff --git a/site/src/cut/lib/fontName.test.ts b/site/src/cut/lib/fontName.test.tsnew file mode 100644index 00000000..62ae267c--- /dev/null+++ b/site/src/cut/lib/fontName.test.ts@@ -0,0 +1,81 @@+import { describe, expect, test } from "bun:test";+import { familyNameFromSfnt, fontLabelFor } from "./fontName";++/** A minimal but real sfnt: a table directory holding one `name` table whose+ * records are UTF-16BE on the Windows platform, which is what a shipped font+ * carries. */+function sfnt(records: { nameId: number; text: string }[], tag = 0x00010000): ArrayBuffer {+ const strings: number[] = [];+ const meta = records.map((r) => {+ const at = strings.length;+ for (const c of [...r.text]) {+ const unit = c.charCodeAt(0);+ strings.push(unit >> 8, unit & 0xff);+ }+ return { nameId: r.nameId, at, len: strings.length - at };+ });+ const nameLen = 6 + meta.length * 12 + strings.length;+ const buf = new ArrayBuffer(28 + nameLen);+ const v = new DataView(buf);+ v.setUint32(0, tag);+ v.setUint16(4, 1);+ v.setUint32(12, 0x6e616d65);+ v.setUint32(20, 28);+ v.setUint32(24, nameLen);+ const at = 28;+ v.setUint16(at + 2, meta.length);+ v.setUint16(at + 4, 6 + meta.length * 12);+ meta.forEach((m, i) => {+ const rec = at + 6 + i * 12;+ v.setUint16(rec, 3);+ v.setUint16(rec + 2, 1);+ v.setUint16(rec + 4, 0x0409);+ v.setUint16(rec + 6, m.nameId);+ v.setUint16(rec + 8, m.len);+ v.setUint16(rec + 10, m.at);+ });+ new Uint8Array(buf).set(strings, at + 6 + meta.length * 12);+ return buf;+}++describe("familyNameFromSfnt", () => {+ test("prefers the typographic family over the legacy one", () => {+ const buf = sfnt([+ { nameId: 1, text: "Cera Pro Bold" },+ { nameId: 16, text: "Cera Pro" },+ ]);+ expect(familyNameFromSfnt(buf)).toBe("Cera Pro");+ });++ test("falls back to the legacy family when there is no typographic name", () => {+ expect(familyNameFromSfnt(sfnt([{ nameId: 1, text: "Bandit Grotesk" }]))).toBe("Bandit Grotesk");+ });++ test("reads an OpenType CFF file", () => {+ expect(familyNameFromSfnt(sfnt([{ nameId: 16, text: "Wanderlust" }], 0x4f54544f))).toBe(+ "Wanderlust"+ );+ });++ test("declines anything that is not an sfnt", () => {+ const zip = new Uint8Array([0x50, 0x4b, 0x03, 0x04, 0, 0, 0, 0]).buffer;+ expect(familyNameFromSfnt(zip)).toBe(null);+ expect(familyNameFromSfnt(new ArrayBuffer(4))).toBe(null);+ });+});++describe("fontLabelFor", () => {+ test("uses the font's own family name", () => {+ expect(fontLabelFor(sfnt([{ nameId: 16, text: "Cera Pro" }]), "CeraPro-Regular.otf")).toBe(+ "Cera Pro"+ );+ });++ test("falls back to the file name with its extension dropped", () => {+ expect(fontLabelFor(new ArrayBuffer(8), "Bandit-Grotesk.woff2")).toBe("Bandit-Grotesk");+ });++ test("always has something to show", () => {+ expect(fontLabelFor(new ArrayBuffer(8), ".otf")).toBe("Custom font");+ });+});diff --git a/site/src/cut/lib/fontName.ts b/site/src/cut/lib/fontName.tsnew file mode 100644index 00000000..882a2073--- /dev/null+++ b/site/src/cut/lib/fontName.ts@@ -0,0 +1,82 @@+/**+ * The family name a font file calls itself, read out of the sfnt `name` table.+ *+ * The Library shows a font under this name, and there is no rename, so the+ * label has to be right the moment the file lands: "Cera Pro" reads as a font,+ * "CeraPro-Regular-webfont" reads as a download. TrueType and OpenType carry+ * the table in the clear. WOFF and WOFF2 compress it, so those fall back to the+ * file name, which is what a web-delivery file usually says anyway.+ */++const u16 = (v: DataView, at: number) => v.getUint16(at);+const u32 = (v: DataView, at: number) => v.getUint32(at);++/** Name records worth reading, best first: the typographic family (16) names+ * the whole family where the legacy family (1) splits weights into families of+ * their own ("Cera Pro Bold"). */+const NAME_IDS = [16, 1];++/** UTF-16BE for the Windows and Unicode platforms; Mac (platform 1) is a+ * single-byte encoding whose ASCII range is all we need from it. */+function decodeName(bytes: Uint8Array, platformId: number): string {+ if (platformId === 1) return new TextDecoder("latin1").decode(bytes);+ return new TextDecoder("utf-16be").decode(bytes);+}++/** The font's own family name, or null when the file does not carry a readable+ * one (a compressed web font, a collection, damaged bytes). */+export function familyNameFromSfnt(buf: ArrayBuffer): string | null {+ try {+ const v = new DataView(buf);+ if (buf.byteLength < 12) return null;+ const tag = u32(v, 0);+ // 0x00010000 TrueType, "OTTO" OpenType CFF, "true" older Mac TrueType.+ if (tag !== 0x00010000 && tag !== 0x4f54544f && tag !== 0x74727565) return null;+ const tables = u16(v, 4);+ let nameAt = 0;+ for (let i = 0; i < tables; i++) {+ const rec = 12 + i * 16;+ if (rec + 16 > buf.byteLength) return null;+ if (u32(v, rec) === 0x6e616d65) {+ nameAt = u32(v, rec + 8);+ break;+ }+ }+ if (!nameAt || nameAt + 6 > buf.byteLength) return null;+ const count = u16(v, nameAt + 2);+ const strings = nameAt + u16(v, nameAt + 4);+ const found = new Map<number, string>();+ for (let i = 0; i < count; i++) {+ const rec = nameAt + 6 + i * 12;+ if (rec + 12 > buf.byteLength) break;+ const platformId = u16(v, rec);+ const nameId = u16(v, rec + 6);+ if (!NAME_IDS.includes(nameId)) continue;+ // The first record for a name id wins; the table lists the platforms in+ // preference order and every one of them says the same family.+ if (found.has(nameId)) continue;+ const len = u16(v, rec + 8);+ const at = strings + u16(v, rec + 10);+ if (at + len > buf.byteLength) continue;+ const text = decodeName(new Uint8Array(buf, at, len), platformId).trim();+ if (text) found.set(nameId, text);+ }+ for (const id of NAME_IDS) {+ const hit = found.get(id);+ if (hit) return hit;+ }+ return null;+ } catch {+ return null;+ }+}++/** What to label an uploaded font: its own family name, else the file name with+ * its extension dropped. */+export function fontLabelFor(buf: ArrayBuffer, fileName: string): string {+ return (+ familyNameFromSfnt(buf) ||+ fileName.replace(/\.(ttf|otf|woff2?)$/i, "").trim() ||+ "Custom font"+ );+}diff --git a/site/src/cut/lib/fontSpecimen.ts b/site/src/cut/lib/fontSpecimen.tsnew file mode 100644index 00000000..bd4e2832--- /dev/null+++ b/site/src/cut/lib/fontSpecimen.ts@@ -0,0 +1,50 @@+/**+ * The picture a font shows of itself.+ *+ * Drawing the alphabet in a live face depends on that face being installed in+ * whatever page is looking at it, which is a thing that can be true one minute+ * and false the next — a shelf that did not answer, a listing that had not+ * synced. The specimen is baked once, at upload, from bytes that are in hand,+ * and the shelf keeps it as the file's cover. What the card shows afterwards is+ * a picture, so it is the same every time.+ */++import { createRasterCanvas, rasterCanvasToPng } from "./raster";++export const SPECIMEN_LINES = [+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ",+ "abcdefghijklmnopqrstuvwxyz",+ "1234567890",+];++const W = 1600;+const H = 900;+const PAD = 90;+/** Measured at one size and scaled; large enough that rounding doesn't show. */+const PROBE = 100;++/**+ * A 16:9 specimen of an installed family.+ *+ * One size for all three lines: the capitals are the widest, so fitting them+ * sets the size and the rest fall where the face puts them.+ */+export async function specimenPng(family: string): Promise<Blob> {+ const canvas = createRasterCanvas(W, H);+ const ctx = canvas.getContext("2d") as CanvasRenderingContext2D | null;+ if (!ctx) throw new Error("No 2D context for the specimen.");+ ctx.fillStyle = "#ffffff";+ ctx.fillRect(0, 0, W, H);+ ctx.fillStyle = "#111111";+ ctx.textAlign = "center";+ ctx.textBaseline = "middle";+ ctx.font = `${PROBE}px "${family}"`;+ const widest = ctx.measureText(SPECIMEN_LINES[0]).width;+ const size = widest > 0 ? (PROBE * (W - PAD * 2)) / widest : PROBE;+ ctx.font = `${size}px "${family}"`;+ const step = size * 1.35;+ SPECIMEN_LINES.forEach((line, i) => {+ ctx.fillText(line, W / 2, H / 2 + (i - 1) * step);+ });+ return rasterCanvasToPng(canvas);+}diff --git a/site/src/cut/lib/googleFonts.ts b/site/src/cut/lib/googleFonts.tsindex f577e058..453b0dcc 100644--- a/site/src/cut/lib/googleFonts.ts+++ b/site/src/cut/lib/googleFonts.ts@@ -25,6 +25,7 @@ import {Poppins,Space_Grotesk,} from "next/font/google";+import { GOOGLE_FONTS } from "./fontCatalog";import { registerFonts } from "./types";const inter = Inter({ subsets: ["latin"], weight: ["400", "700"], preload: false });@@ -43,20 +44,24 @@ const pacifico = Pacifico({ subsets: ["latin"], weight: "400", preload: false })const permanentMarker = Permanent_Marker({ subsets: ["latin"], weight: "400", preload: false });const dmSerifDisplay = DM_Serif_Display({ subsets: ["latin"], weight: "400", preload: false });-registerFonts([- { id: "inter", label: "Inter", stack: inter.style.fontFamily },- { id: "montserrat", label: "Montserrat", stack: montserrat.style.fontFamily },- { id: "poppins", label: "Poppins", stack: poppins.style.fontFamily },- { id: "oswald", label: "Oswald", stack: oswald.style.fontFamily },- { id: "space-grotesk", label: "Space Grotesk", stack: spaceGrotesk.style.fontFamily },- { id: "playfair", label: "Playfair Display", stack: playfair.style.fontFamily },- { id: "caveat", label: "Caveat", stack: caveat.style.fontFamily },- { id: "bebas", label: "Bebas Neue", stack: bebas.style.fontFamily },- { id: "anton", label: "Anton", stack: anton.style.fontFamily },- { id: "archivo-black", label: "Archivo Black", stack: archivoBlack.style.fontFamily },- { id: "bangers", label: "Bangers", stack: bangers.style.fontFamily },- { id: "lobster", label: "Lobster", stack: lobster.style.fontFamily },- { id: "pacifico", label: "Pacifico", stack: pacifico.style.fontFamily },- { id: "permanent-marker", label: "Permanent Marker", stack: permanentMarker.style.fontFamily },- { id: "dm-serif", label: "DM Serif Display", stack: dmSerifDisplay.style.fontFamily },-]);+// One stack per bundled id; the list itself lives in fontCatalog.ts, which the+// assistant's catalog reads too.+const STACKS: Record<string, string> = {+ inter: inter.style.fontFamily,+ montserrat: montserrat.style.fontFamily,+ poppins: poppins.style.fontFamily,+ oswald: oswald.style.fontFamily,+ "space-grotesk": spaceGrotesk.style.fontFamily,+ playfair: playfair.style.fontFamily,+ caveat: caveat.style.fontFamily,+ bebas: bebas.style.fontFamily,+ anton: anton.style.fontFamily,+ "archivo-black": archivoBlack.style.fontFamily,+ bangers: bangers.style.fontFamily,+ lobster: lobster.style.fontFamily,+ pacifico: pacifico.style.fontFamily,+ "permanent-marker": permanentMarker.style.fontFamily,+ "dm-serif": dmSerifDisplay.style.fontFamily,+};++registerFonts(GOOGLE_FONTS.map((f) => ({ ...f, stack: STACKS[f.id] })));diff --git a/site/src/cut/lib/headless/docSession.ts b/site/src/cut/lib/headless/docSession.tsindex ebfb414d..c1cd08b0 100644--- a/site/src/cut/lib/headless/docSession.ts+++ b/site/src/cut/lib/headless/docSession.ts@@ -1,5 +1,6 @@import type { HeadlessSession } from "./bind";import { syncFontAssets } from "../fontAssets";+import { syncLinkedLibrary } from "../linkedLibrary";import { serializeDoc, useEditor } from "../store";import type { MediaAsset, ProjectDoc } from "../types";@@ -52,8 +53,10 @@ export async function openCloudProject(}));await useEditor.getState().openProjectDoc(projectId, doc, assets);// The page does this from the editor; a run has to do it before it draws,- // or a title set in the project's own font comes out in the fallback face.- await syncFontAssets(assets);+ // or a title set in the user's own font comes out in the fallback face. The+ // account's shelf fonts come along the same way — a run reaches the cloud+ // shelf, so a font kept on a device shelf is the one case that falls back.+ await Promise.all([syncFontAssets(assets), syncLinkedLibrary()]);return { projectId, version };}diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.tsindex 64fbbc9b..1c8a7fd9 100644--- a/site/src/cut/lib/library.ts+++ b/site/src/cut/lib/library.ts@@ -6,9 +6,14 @@ import { readSnapshot, writeSnapshot } from "./cache";import { pollCloudJob } from "./cloudJob";import { downloadFromUrl } from "./download";import { normalizeLink } from "./link";+import { installFontFace } from "./fontAssets";+import { fontLabelFor } from "./fontName";+import { specimenPng } from "./fontSpecimen";import {enrichAsset,importRemote,+ isFontFile,+ MAX_FONT_BYTES,presignedUpload,probeFileMeta,uploadProjectMediaTo,@@ -37,7 +42,7 @@ export interface LibraryAsset {id: string;fileName: string;name: string;- type: "video" | "audio" | "image";+ type: "video" | "audio" | "image" | "font";duration: number;width?: number;height?: number;@@ -329,27 +334,111 @@ export async function moveLibraryItem(if (!res.ok) throw new Error("Could not move item.");}+/**+ * Carry a library file to another shelf, filed where it lands.+ *+ * A folder belongs to one shelf, so filing an item into one can mean crossing+ * shelves. Neither server can see the other, so the bytes come down here and go+ * back up, the item keeps its name and the link it was imported from, and the+ * copy left behind comes off.+ */+export async function carryAssetTo(+ asset: LibraryAsset,+ to: Residency,+ folderId: string | null+): Promise<LibraryAsset> {+ const res = await backendFor(asset.residency).fetch(+ `/api/cut/library/media/${encodeURIComponent(asset.fileName)}`+ );+ if (!res.ok) throw new Error("Could not read that file off its shelf.");+ const from = libraryPosterUrl(asset);+ const cover = from+ ? await backendFor(asset.residency)+ .fetch(`/api/cut/library/media/${encodeURIComponent(asset.posterFile!)}`)+ .then((r) => (r.ok ? r.blob() : null))+ .catch(() => null)+ : null;+ const landed = await uploadToLibrary(new File([await res.blob()], asset.fileName), to, {+ name: asset.name,+ ...(asset.source ? { source: asset.source } : {}),+ ...(cover ? { poster: cover } : {}),+ });+ if (folderId) await moveLibraryItem(to, landed.id, folderId).catch(() => {});+ await deleteFromLibrary(asset.residency, asset.id).catch(() => {});+ return { ...landed, folderId };+}++/** A font is readable when the renderer can install it, so the check runs+ * through the installer seam: the file that passes here is exactly the file a+ * preview and a render job can draw with, and a renamed archive or a truncated+ * download is refused before a byte leaves the browser. It comes back with the+ * family name the font calls itself — the shelf's label and the font menu's —+ * and a specimen drawn in the face it just installed, which becomes the file's+ * cover, so a card never has to have the font installed to show it. */+async function checkFont(file: File): Promise<{ label: string; poster: Blob | null }> {+ if (file.size > MAX_FONT_BYTES) {+ throw new Error(`Fonts are limited to ${Math.round(MAX_FONT_BYTES / 1024 ** 2)}MB.`);+ }+ const bytes = await file.arrayBuffer();+ const family = `lf-check-${file.size}`;+ try {+ await installFontFace(family, bytes);+ } catch {+ throw new Error("That file isn't a font Cut can read.");+ }+ return {+ label: fontLabelFor(bytes, file.name),+ poster: await specimenPng(family).catch(() => null),+ };+}+export async function uploadToLibrary(file: File,- residency: Residency = activeResidency()+ residency: Residency = activeResidency(),+ /** What the shelf should call it and where it came from, when the file is+ * arriving from somewhere that already knows — a carry from another shelf,+ * say. Left out, the file names itself and keeps whatever cover it makes. */+ keep: { name?: string; source?: LibrarySource; poster?: Blob } = {}): Promise<LibraryAsset> {const backend = backendFor(residency);+ // A font has no streams to measure; it is checked by installing it instead,+ // and the check hands back the specimen the shelf keeps as its cover.+ const font = isFontFile(file) ? await checkFont(file) : null;+ const fontLabel = font?.label ?? null;+ const poster = keep.poster ?? font?.poster ?? null;+ const posterName = `${file.name}.specimen.png`;+ const fontMeta = { type: "font" as const, duration: 0 };if (residency === "cloud") {// Presign -> direct R2 PUT -> complete, with the media probed here — the// cloud can't cheaply probe an R2 object the way the engine probes disk.// A file this browser can't decode would land as a zero-length asset it// also couldn't preview, so reject it before any bytes go up.- const meta = await probeFileMeta(file).catch(() => null);- if (!meta || (meta.type !== "image" && !(meta.duration > 0))) {+ const meta = fontLabel ? fontMeta : await probeFileMeta(file).catch(() => null);+ if (!meta || (meta.type !== "image" && meta.type !== "font" && !(meta.duration > 0))) {throw new Error("This file can't be read in this browser, so it can't go in the cloud library. Import it in the Mac app instead.");}const key = await presignedUpload("/api/cut/library/presign", file, file.name, backend);+ // The cover rides up as an object of its own; `complete` marks it and+ // records it against the asset.+ const posterKey = poster+ ? await presignedUpload("/api/cut/library/presign", poster, posterName, backend).catch(+ () => null+ )+ : null;const res = await backend.fetch("/api/cut/library/complete", {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ key, meta: { name: file.name, ...meta } }),+ body: JSON.stringify({+ key,+ ...(posterKey ? { posterKey } : {}),+ meta: {+ name: keep.name ?? fontLabel ?? file.name,+ ...(keep.source ? { source: keep.source } : {}),+ ...meta,+ },+ }),});const body = await apiJson<LibraryAsset>(res);if (!res.ok) throw new Error(body.error ?? "Upload failed.");@@ -357,12 +446,16 @@ export async function uploadToLibrary(}const form = new FormData();form.append("file", file, file.name);+ const name = keep.name ?? fontLabel;+ if (name) form.append("name", name);+ if (keep.source) form.append("source", JSON.stringify(keep.source));+ if (poster) form.append("poster", poster, posterName);if (residency === "browser") {// The shelf is this page's storage, with no ffprobe behind it: the file is// measured here, and one this browser can't read is refused rather than// shelved as an asset nothing can play.- const meta = await probeFileMeta(file).catch(() => null);- if (!meta || (meta.type !== "image" && !(meta.duration > 0))) {+ const meta = fontLabel ? fontMeta : await probeFileMeta(file).catch(() => null);+ if (!meta || (meta.type !== "image" && meta.type !== "font" && !(meta.duration > 0))) {throw new Error("This file can't be read in this browser, so it can't go in the library.");}form.append("meta", JSON.stringify(meta));@@ -420,6 +513,7 @@ export async function importLibraryAsset(projectId: string,lib: LibraryAsset): Promise<MediaAsset> {+ if (lib.type === "font") throw new Error("Fonts are used from the font menu, not the timeline.");return importRemote(projectId,{diff --git a/site/src/cut/lib/lightbox.ts b/site/src/cut/lib/lightbox.tsindex f34723e6..15fa4bd1 100644--- a/site/src/cut/lib/lightbox.ts+++ b/site/src/cut/lib/lightbox.ts@@ -8,7 +8,7 @@ import type { AssetRef } from "./assetRef";// surface can open it and a single mounted overlay renders it.export interface LightboxItem {- kind: "video" | "image" | "audio" | "text";+ kind: "video" | "image" | "audio" | "text" | "font";/** Fetchable source for the media or file. */src: string;name: string;diff --git a/site/src/cut/lib/linkedLibrary/fonts.ts b/site/src/cut/lib/linkedLibrary/fonts.tsnew file mode 100644index 00000000..4bedafe6--- /dev/null+++ b/site/src/cut/lib/linkedLibrary/fonts.ts@@ -0,0 +1,70 @@+"use client";++/**+ * The account's own typefaces: font files on the Library shelf, turned into+ * families the font menu, the DOM preview and the canvas painters resolve.+ *+ * Fonts are the first of the Library's linked kinds — pointed at by a document+ * rather than copied into it — so everything about identity, placement, and+ * travelling with a project lives in `libraryLinks.ts`. What is here is the+ * font-shaped part: installing bytes as a family, and the ids a title or a+ * caption is set in.+ *+ * A job reads the cloud shelf alone, so a font kept on a device shelf draws in+ * the tab and falls back to the base face in a render.+ */++import { installFontFace } from "../fontAssets";+import { isFontFile } from "../media";+import { fontsFromArchive, isFontArchive } from "../fontArchive";+import {+ linkId,+ listLinked,+ registerLinkedKind,+ uploadLinkedItem,+ type LinkedItem,+} from "./registry";+import type { ProjectDoc } from "../types";+import { registerFonts, unregisterFonts } from "../types";++const PREFIX = "font";++/** The registry id a shelf font answers to. `fontStack` falls back tolerantly,+ * so a title set in a font that has since been deleted still renders. */+export const libraryFontId = (key: string) => linkId(PREFIX, key);++/** The CSS/skia family name its bytes are installed under. */+const familyOf = (key: string) => `lf-${key}`;++registerLinkedKind({+ prefix: PREFIX,+ type: "font",+ homeFolder: "Fonts",+ matches: isFontFile,+ accept: ".ttf,.otf,.woff,.woff2,.zip,font/ttf,font/otf,font/woff,font/woff2,application/zip",+ unpack: async (file) => (isFontArchive(file) ? await fontsFromArchive(file) : null),+ extract: (doc: ProjectDoc) => {+ const ids: string[] = [];+ for (const o of doc.overlays ?? []) {+ const font = (o as { font?: string }).font;+ if (font?.startsWith(`${PREFIX}:`)) ids.push(font);+ }+ const cues = doc.subtitles?.font;+ if (cues?.startsWith(`${PREFIX}:`)) ids.push(cues);+ return ids;+ },+ use: async (key, label, bytes) => {+ await installFontFace(familyOf(key), bytes);+ registerFonts([{ id: libraryFontId(key), label, stack: `"${familyOf(key)}"` }]);+ },+ drop: (keys) => unregisterFonts(keys.map(libraryFontId)),+});++/** The account's fonts, one entry per typeface however many shelves hold it. */+export const listLibraryFonts = (): LinkedItem[] => listLinked(PREFIX);++/** Put a font file on the shelf and light it up in the font menu. The file is+ * checked before any bytes move (see `checkFont` in library.ts), so a failure+ * here means nothing landed. */+export const uploadLibraryFont = (file: File): Promise<string> =>+ uploadLinkedItem(PREFIX, file);diff --git a/site/src/cut/lib/linkedLibrary/index.ts b/site/src/cut/lib/linkedLibrary/index.tsnew file mode 100644index 00000000..59c195ff--- /dev/null+++ b/site/src/cut/lib/linkedLibrary/index.ts@@ -0,0 +1,19 @@+"use client";++/**+ * Library items a document links to instead of copying — the whole feature,+ * kinds included.+ *+ * `registry.ts` holds the mechanism and `fonts.ts` (and any kind added later)+ * registers itself against it. Importing this folder is what pulls those+ * registrations in, so everything reads the same complete set of kinds: ask the+ * registry directly and it answers for whichever kinds happened to be loaded,+ * which is how a project moves to the cloud leaving one of them behind.+ *+ * A new linked kind is one module beside this one and one line below.+ */++import "./fonts";++export * from "./registry";+export { libraryFontId, listLibraryFonts, uploadLibraryFont } from "./fonts";diff --git a/site/src/cut/lib/linkedLibrary/registry.ts b/site/src/cut/lib/linkedLibrary/registry.tsnew file mode 100644index 00000000..ac619cf4--- /dev/null+++ b/site/src/cut/lib/linkedLibrary/registry.ts@@ -0,0 +1,417 @@+"use client";++/**+ * Library items a document points at instead of copying.+ *+ * Most of what comes off the Library is copied when it is used: a clip's bytes+ * become the project's own, and the shelf and the project go their separate+ * ways. Some kinds are pointed at instead — a font is named by every title set+ * in it, and the file stays on the shelf where every project can reach it.+ * Those links are what this module keeps honest, for fonts today and for+ * whatever is linked rather than copied next.+ *+ * Three rules hold for every linked kind:+ *+ * - **Identity is the bytes.** A linked item is keyed by a hash of its content,+ * not by the shelf row holding it, so the same file on two shelves is one+ * item and one id. That is what lets a project change residency without a+ * word of it being rewritten.+ * - **New ones land where everything can read them.** The cloud shelf, when+ * there is room and the item is small enough that where it sits is not a real+ * choice — a render job reads no other shelf.+ * - **They travel with the project.** A project moving to the cloud takes the+ * linked items it depends on with it.+ */++import { readSnapshot, writeSnapshot } from "../cache";+import {+ deleteFromLibrary,+ fetchLibrary,+ moveLibraryItem,+ uploadToLibrary,+ type LibraryAsset,+} from "../library";+import { activeResidency, backendFor, type Residency } from "../residency";+import type { ProjectDoc } from "../types";++/** One shelf row carrying a linked item's bytes. */+export interface LinkedCopy {+ assetId: string;+ residency: Residency;+ fileName: string;+ name: string;+}++/** A linked item as its menu knows it: one thing, however many shelves hold it. */+export interface LinkedItem {+ /** Content key — see the module note. */+ key: string;+ prefix: string;+ label: string;+ copies: LinkedCopy[];+}++/**+ * A kind of library item documents link to. Registered once at module load by+ * the feature that owns it.+ */+export interface LinkedKind {+ /** Id prefix a document writes, e.g. "font" for `font:<key>`. */+ prefix: string;+ /** The library asset type carrying it. */+ type: LibraryAsset["type"];+ /** The ids of this kind a document is set in, so a project move can carry+ * them. */+ extract: (doc: ProjectDoc) => string[];+ /** Put one item's bytes to use in this process — installing a font face,+ * say. Throwing leaves the item out of the listing. */+ use?: (key: string, label: string, bytes: ArrayBuffer) => Promise<void>;+ /** Keys that have left the shelf, so the feature can drop them. */+ drop?: (keys: string[]) => void;+ /** Folder a new one is filed into when the shelf has one by that name. */+ homeFolder?: string;+ /** Whether a dropped OS file is one of these. */+ matches: (file: File) => boolean;+ /** What a file picker offers for this kind, archives included. */+ accept?: string;+ /** Files inside an archive of this kind, or `null` when the file is not one.+ * A font arrives as a zip from every foundry that publishes one, and a+ * template or a sticker pack will arrive the same way. */+ unpack?: (file: File) => Promise<File[] | null>;+}++const kinds = new Map<string, LinkedKind>();++export function registerLinkedKind(kind: LinkedKind): void {+ kinds.set(kind.prefix, kind);+}++export const linkId = (prefix: string, key: string) => `${prefix}:${key}`;++/** Whether the Library lends this kind of item rather than copying it — what+ * tells an upload to reach for a shelf every surface can read, and a delete to+ * take it out of the menus that offer it. */+export const isLinkedType = (type: LibraryAsset["type"]): boolean =>+ [...kinds.values()].some((k) => k.type === type);++/** Whether a dropped OS file is a linked kind. */+export const isLinkedFile = (file: File): boolean =>+ [...kinds.values()].some((k) => k.matches(file));++/** What every linked kind takes, for a file input's `accept`. */+export const linkedAccept = (): string =>+ [...kinds.values()].flatMap((k) => (k.accept ? [k.accept] : [])).join(",");++/**+ * A dropped batch with its archives opened.+ *+ * What a user has in hand is what the download gave them, and for a font that+ * is a zip. Opening it here means every intake point — the Library page, the+ * editor's panel, the font menu — takes the file as it arrived. A file no kind+ * claims passes through untouched.+ */+export async function expandLinkedFiles(files: File[]): Promise<File[]> {+ const out: File[] = [];+ for (const file of files) {+ let opened: File[] | null = null;+ for (const kind of kinds.values()) {+ opened = (await kind.unpack?.(file).catch(() => null)) ?? null;+ if (opened) break;+ }+ out.push(...(opened ?? [file]));+ }+ return out;+}++/** Items small enough that which shelf holds them is not a real choice. Past+ * this, a new item stays on the shelf the user is working from, because moving+ * real weight into someone's cloud quota is their call to make. */+export const LINKED_CARRY_MAX_BYTES = 10 * 1024 ** 2;++let items: LinkedItem[] = [];+const byAsset = new Map<string, LinkedItem>();+/** Keys already in use in this process, per kind. */+const used = new Map<string, Promise<void>>();+const listeners = new Set<() => void>();++export const listLinked = (prefix: string): LinkedItem[] =>+ items.filter((i) => i.prefix === prefix);++/** The link id a Library card should render itself as. */+export const linkIdForAsset = (assetId: string): string | null => {+ const hit = byAsset.get(assetId);+ return hit ? linkId(hit.prefix, hit.key) : null;+};++export function onLinkedChanged(cb: () => void): () => void {+ listeners.add(cb);+ return () => listeners.delete(cb);+}++function publish(next: LinkedItem[]): void {+ items = next;+ byAsset.clear();+ for (const i of next) for (const c of i.copies) byAsset.set(c.assetId, i);+ for (const cb of listeners) cb();+}++/** An item's identity: enough SHA-256 to never collide in one account's shelf. */+export async function contentKey(bytes: ArrayBuffer): Promise<string> {+ const digest = await crypto.subtle.digest("SHA-256", bytes);+ return [...new Uint8Array(digest).slice(0, 8)]+ .map((b) => b.toString(16).padStart(2, "0"))+ .join("");+}++const bytesKey = (assetId: string) => `linked/${assetId}`;++/** The bytes for one shelf item: off the shelf when it answers, else the copy+ * kept from the last time it did. Something that has been used once keeps+ * working when the shelf holding it is out of reach.+ *+ * Read through the shelf's own backend rather than its URL: a render job+ * carries its auth in headers the page gets from a cookie, and the browser+ * shelf answers in the page rather than over the network. */+export async function linkedBytes(a: LibraryAsset): Promise<ArrayBuffer> {+ try {+ const res = await backendFor(a.residency).fetch(+ `/api/cut/library/media/${encodeURIComponent(a.fileName)}`,+ );+ if (!res.ok) throw new Error("linked item fetch failed");+ const bytes = await res.arrayBuffer();+ writeSnapshot(bytesKey(a.id), bytes);+ return bytes;+ } catch (e) {+ const hit = await readSnapshot<ArrayBuffer>(bytesKey(a.id));+ if (hit) return hit.value;+ throw e;+ }+}++function put(+ kind: LinkedKind,+ key: string,+ label: string,+ bytes: ArrayBuffer,+): Promise<void> {+ const id = linkId(kind.prefix, key);+ let hit = used.get(id);+ if (hit) return hit;+ hit = (kind.use ? kind.use(key, label, bytes) : Promise.resolve()).catch(+ () => {+ // Bytes that will not load: drop the marker so a later pass retries, and+ // let whatever points at them fall back.+ used.delete(id);+ },+ );+ used.set(id, hit);+ return hit;+}++/**+ * Reconcile this process with the account's linked items: put new ones to use,+ * drop deleted ones, and publish the listing their menus draw.+ *+ * The editor calls this on open and after every upload or delete; a headless+ * run awaits it before drawing anything.+ */+export async function syncLinkedLibrary(): Promise<void> {+ if (kinds.size === 0) return;+ const types = new Set([...kinds.values()].map((k) => k.type));+ let shelf: LibraryAsset[];+ try {+ shelf = (await fetchLibrary()).assets.filter((a) => types.has(a.type));+ } catch {+ // No shelf reachable: keep whatever is already in use rather than tearing+ // the user's items out of a menu mid-session.+ return;+ }+ const kindFor = (a: LibraryAsset) =>+ [...kinds.values()].find((k) => k.type === a.type);+ // Read and key every shelf copy at once, then put them to use in a fixed+ // order: two shelves holding one item may have stored it under different+ // names, and a menu should not label it differently from one session to the+ // next. The cloud copy's name wins, since that is the one every surface reads.+ const read = await Promise.all(+ shelf.map(async (a) => {+ const kind = kindFor(a);+ if (!kind) return null;+ try {+ const bytes = await linkedBytes(a);+ return { a, kind, bytes, key: await contentKey(bytes) };+ } catch {+ return null; // That shelf isn't answering; another copy may still serve.+ }+ }),+ );+ const ordered = read+ .filter((r): r is NonNullable<typeof r> => r !== null)+ .sort(+ (x, y) =>+ Number(y.a.residency === "cloud") - Number(x.a.residency === "cloud") ||+ x.a.fileName.localeCompare(y.a.fileName),+ );+ const found = new Map<string, LinkedItem>();+ for (const { a, kind, bytes, key } of ordered) {+ await put(kind, key, a.name, bytes);+ const copy: LinkedCopy = {+ assetId: a.id,+ residency: a.residency,+ fileName: a.fileName,+ name: a.name,+ };+ const id = linkId(kind.prefix, key);+ const hit = found.get(id);+ if (hit) hit.copies.push(copy);+ else+ found.set(id, {+ key,+ prefix: kind.prefix,+ label: a.name,+ copies: [copy],+ });+ }+ const stale = [...used.keys()].filter((id) => !found.has(id));+ if (stale.length) {+ for (const id of stale) used.delete(id);+ for (const kind of kinds.values()) {+ const mine = stale.filter((id) => id.startsWith(`${kind.prefix}:`));+ if (mine.length)+ kind.drop?.(mine.map((id) => id.slice(kind.prefix.length + 1)));+ }+ }+ publish([...found.values()]);+}++/** Drop one shelf copy the moment it is deleted, so the shelf and the menus+ * never disagree while the round trip settles. */+export function forgetLinkedCopy(assetId: string): void {+ const item = byAsset.get(assetId);+ if (!item) return;+ const next: LinkedItem[] = [];+ for (const i of items) {+ if (i !== item) {+ next.push(i);+ continue;+ }+ const copies = i.copies.filter((c) => c.assetId !== assetId);+ if (copies.length > 0) next.push({ ...i, copies });+ else {+ const id = linkId(i.prefix, i.key);+ used.delete(id);+ kinds.get(i.prefix)?.drop?.([i.key]);+ }+ }+ publish(next);+}++/**+ * Which shelf a new item belongs on, when nothing else has decided (something+ * dropped into a folder belongs to that folder's shelf).+ *+ * The cloud, whenever it is small enough and there is room. It is the only+ * shelf every surface can read — a render job reaches nothing else — and below+ * the carry limit where it sits is not a real choice. A large file, a full+ * account, or a cloud that isn't answering lands it on the shelf the user is+ * working from.+ *+ * Room, never tier: a free account has 250MB and a linked item is under one.+ */+export async function shelfForNewItem(bytes: number): Promise<Residency> {+ const here = activeResidency();+ if (here === "cloud") return "cloud";+ if (bytes > LINKED_CARRY_MAX_BYTES) return here;+ try {+ const res = await backendFor("cloud").fetch("/api/cut/usage");+ if (!res.ok) return here;+ const usage = (await res.json()) as {+ bytes: number;+ quotaBytes: number | null;+ };+ if (usage.quotaBytes === null) return "cloud";+ return usage.bytes + bytes <= usage.quotaBytes ? "cloud" : here;+ } catch {+ return here;+ }+}++/** Put a file on the shelf as a linked item of this kind and return its id. */+export async function uploadLinkedItem(+ prefix: string,+ file: File,+): Promise<string> {+ const kind = kinds.get(prefix);+ const residency = await shelfForNewItem(file.size);+ const asset = await uploadToLibrary(file, residency);+ if (kind?.homeFolder) {+ const home = await fetchLibrary()+ .then((d) =>+ d.folders.find(+ (f) => f.residency === residency && f.name === kind.homeFolder,+ ),+ )+ .catch(() => undefined);+ if (home)+ await moveLibraryItem(residency, asset.id, home.id).catch(() => {});+ }+ const key = await contentKey(await file.arrayBuffer());+ await syncLinkedLibrary();+ return linkId(prefix, key);+}++/** Take a linked item off the shelf, every copy of it. Whatever points at it+ * falls back on its own, so nothing in a document has to be rewritten. */+export async function deleteLinkedItem(item: LinkedItem): Promise<void> {+ const copies = [...item.copies];+ for (const c of copies) forgetLinkedCopy(c.assetId);+ await Promise.all(+ copies.map((c) =>+ deleteFromLibrary(c.residency, c.assetId).catch(() => {}),+ ),+ );+}++/** Every linked id a document is set in, across kinds. */+export function linkedIdsIn(doc: ProjectDoc): string[] {+ const ids = new Set<string>();+ for (const kind of kinds.values())+ for (const id of kind.extract(doc)) ids.add(id);+ return [...ids];+}++/**+ * Make sure the cloud shelf holds these linked items, copying any that live+ * only on a device. What a project needs when it moves to the cloud: a render+ * job reads the cloud shelf alone. The ids don't change — they are the bytes —+ * so the document that referenced them still does.+ */+export async function ensureLinkedOnCloud(+ ids: Iterable<string>,+): Promise<void> {+ const wanted = new Set(ids);+ if (wanted.size === 0) return;+ const missing = items.filter(+ (i) =>+ wanted.has(linkId(i.prefix, i.key)) &&+ !i.copies.some((c) => c.residency === "cloud"),+ );+ if (missing.length === 0) return;+ for (const item of missing) {+ const from = item.copies[0];+ if (!from) continue;+ try {+ const res = await backendFor(from.residency).fetch(+ `/api/cut/library/media/${encodeURIComponent(from.fileName)}`,+ );+ if (!res.ok) continue;+ await uploadToLibrary(+ new File([await res.blob()], from.fileName),+ "cloud",+ );+ } catch {+ // An unreachable shelf or a full account: whatever points at it falls+ // back in a job, and the move itself still goes through.+ }+ }+ await syncLinkedLibrary();+}diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.tsindex ef40aed4..e527f02e 100644--- a/site/src/cut/lib/media.ts+++ b/site/src/cut/lib/media.ts@@ -149,6 +149,16 @@ export function isTextFile(file: File) {return file.type.startsWith("text/") || /\.(txt|md|markdown|srt|vtt|csv|json)$/i.test(file.name);}+/** A font file the Library takes. Browsers often report an empty type for+ * .otf, so the extension has the final say. */+export function isFontFile(file: File) {+ return file.type.startsWith("font/") || /\.(ttf|otf|woff2?)$/i.test(file.name);+}++/** Fonts are small; a file past this is a mistake worth catching before the+ * bytes move. The storage quota is the real ceiling. */+export const MAX_FONT_BYTES = 10 * 1024 ** 2;+/** Claim a name and mint a direct-to-R2 PUT for one file. The name is deduped* and reserved server-side before the URL comes back, so callers can build the* asset's final identity before a single byte moves. */diff --git a/site/src/cut/lib/projectCopy.ts b/site/src/cut/lib/projectCopy.tsindex d64bd58a..bf03644f 100644--- a/site/src/cut/lib/projectCopy.ts+++ b/site/src/cut/lib/projectCopy.ts@@ -7,6 +7,7 @@import type { CutBackend } from "./backend/types";import { fetchCloudThreads, putCloudThread } from "./chatCloud";import { mergeThreads, readProjectThreads, writeProjectThreads } from "./chatThreads";+import { ensureLinkedOnCloud, linkedIdsIn } from "./linkedLibrary";import { uploadProjectMediaTo } from "./media";import { localMediaFile } from "./mediaSync";import type { ProjectDoc } from "./types";@@ -84,6 +85,11 @@ export async function copyProjectAcross(names.set(a.fileName, await uploadProjectMediaTo(dst, summary.id, blob, a.fileName));opts.onProgress?.(names.size, unique);}+ // A project moving to the cloud takes what it links to with it: a render+ // job reads the cloud shelf alone, so a title set in a font that lives only+ // on this Mac would come out in the fallback face once it renders there.+ // Linked ids are the bytes, so nothing in the document changes.+ if (dst.kind === "cloud") await ensureLinkedOnCloud(linkedIdsIn(doc));const copied: ProjectDoc = {...doc,// The copy is a new project; the target backend stamps its own id.diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 67342c30..34bfc44d 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -30,7 +30,8 @@ import { TOP_BAR_TOOLS } from "@/cut/components/TopBar.tools";import { TRANSITIONS_TOOLS } from "@/cut/components/TransitionsPanel.tools";import { LOOK_EFFECTS, OVERLAY_ANIM_STYLE_IDS, OVERLAY_LOOP_STYLE_IDS } from "@donkeycut/effects-kit";import type { AiToolDef } from "../../lib/aiToolDef";-import { TRANSITION_STYLE_IDS } from "../../lib/types";+import { GOOGLE_FONT_IDS } from "../../lib/fontCatalog";+import { FONTS, TRANSITION_STYLE_IDS } from "../../lib/types";export const AI_TOOLS: AiToolDef[] = [...AI_PANEL_TOOLS,@@ -137,12 +138,12 @@ The title lanes hold three overlay element kinds, all sharing timing (start/end)Rows are how elements stack (\`lane\`, 0 = the front row; a higher row draws further back). Two elements on ONE row never overlap in time — placing a title where a shape already sits slides it clear instead of laying it on top — so anything meant to sit over something else names a LOWER row: title on lane 0, the background shape behind it on lane 1. Every add tool and update_overlay take \`lane\`.The frame's own color is set_background, not a full-frame rectangle: it fills the frame behind every clip and element, holds for the whole cut, letterboxes fitted footage, and shows through gaps on track 0. "Make the background white", a colored card behind a title sequence, a text-and-graphics video with no footage at all — all of them start with set_background. A rectangle element is for a panel or a band inside the frame, not for the frame itself.A whole run of text — a lyric video, a kinetic-typography passage, a quote sequence — is add_text_sequence, one call carrying a named look (frame color, card colors, type, motion): read the text-videos skill for the looks and the flow. A video needs no footage. Titles, shapes and stickers over a background color are a complete cut on their own: it plays, exports, and shares like any other. Build one by setting the background, then placing elements on the rows the stack needs — reach for footage only when the user asks for it.-Titles (add_title / update_overlay): text, size (frame px; the design short side is 1080), font (sf=SF Pro, serif=New York, rounded, mono, impact), weight (400/700), color, shadow, plate (translucent dark backdrop).+Titles (add_title / update_overlay): text, size (frame px; the design short side is 1080), font (${FONTS.map((f) => `${f.id}=${f.label}`).join(", ")}), weight (400/700), color, shadow, plate (translucent dark backdrop).Shapes (add_shape): rect, ellipse, line, arrow. w/h are frame fractions; rect/ellipse take fill + fill_opacity, corner radius (rect), and an outline (stroke_color/stroke_width); line/arrow draw in \`fill\` with h as their thickness, and rotation gives them their direction (0° points right, 90° points down).Stickers (add_sticker): a project image asset (generated cutouts in the Elements panel carry origin "sticker"); w is a frame-width fraction and height follows the source's aspect. Lottie JSON uploads become animated stickers that loop for the element's duration.Custom stickers (create_sticker): one call generates the image, removes the background, adds the die-cut outline, and places it — use it when the user asks for a sticker of something they don't have (it spends credits like image generation).Effects (add_effect): time-ranged treatments over the finished picture — the footage and everything laid over it. Two families, one list: the treatments (${EFFECT_TREATMENTS.join(", ")}) and the graded looks (${LOOK_EFFECTS.join(", ")}). Placed like any element and tuned with \`amount\` (update_overlay); an effect added over a clip opens covering that clip, and trims like anything else. One effect at a time reads best, amounts under ~0.5.-Advanced text (update_overlay): italic, align (multi-line), letter_spacing (em), line_height, stroke_color/stroke_width (em outline behind the fill), and richer shadows. Bundled Google families join the system set — inter, montserrat, poppins, oswald, space-grotesk, playfair, caveat, bebas, anton, archivo-black, bangers, lobster, pacifico, permanent-marker, dm-serif — and the user can upload .ttf/.otf fonts (they appear as font ids like "asset:<id>").+Advanced text (update_overlay): italic, align (multi-line), letter_spacing (em), line_height, stroke_color/stroke_width (em outline behind the fill), and richer shadows. Bundled Google families join the system set — ${GOOGLE_FONT_IDS.join(", ")} — and so do the user's own: a .ttf/.otf/.woff/.woff2 file dropped on the Library is offered in every project under a font id like "font:<id>". Editor_state lists the ones this account has under \`fonts\` — use an id from there instead of guessing at a family name, and when someone asks for a typeface that is not in the list, tell them the Library takes font files.Animation (set_overlay_animation): every element takes preset In/Out ramps (${OVERLAY_ANIM_STYLE_IDS.join(", ")} — typewriter for titles only; the per-letter styles sweep a title character by character) and a Loop (${OVERLAY_LOOP_STYLE_IDS.join(", ")}) that runs its whole duration. Entrances 0.3–0.6s read well; one loop per scene, sparingly.Keyframes (set_overlay_keyframes): for motion no preset covers — a path across the frame, a slow push in, a drift that holds first. A key is a whole pose (position, scale, rotation, opacity) at a time in seconds from the element's start; the pose moves linearly between keys and holds outside them, and presets still compose on top. Two or three keys carry almost everything; reach for a preset first and keyframes when the user describes a specific path or timing. In the UI the diamond in the inspector adds a key at the playhead, and dragging the element then records into it. set_clip_keyframes is the same track on a video clip (any track): pans, push-ins, picture-in-picture flights, spins, and fades on the footage itself.Masks (set_mask): trim any element or video clip to a shape — rect, square, circle, linear, mirror — with feather, invert, and its own keyframe track for reveals and wipes. The subject kind trims by the person in the shot (on-device segmentation; preview and export match): inverted sits the item behind the speaker, plain keeps it only on the speaker. Behind-speaker reads well when the speaker is clearly separated from the background; with no detectable person it degrades to the plain picture. Groups: the user can group elements (select several, Group in the inspector) — selecting one selects all, and moves/resize/rotate/timing ride together.diff --git a/site/src/cut/server/cloud/library.ts b/site/src/cut/server/cloud/library.tsindex 575e8547..4058e52d 100644--- a/site/src/cut/server/cloud/library.ts+++ b/site/src/cut/server/cloud/library.ts@@ -25,7 +25,7 @@ import { caught, decodeFileParam, dedupeName, err, redirect, safeFileName, typeO* the source project doc. */interface AssetMeta {name?: string;- type?: "video" | "audio" | "image";+ type?: "video" | "audio" | "image" | "font";duration?: number;width?: number;height?: number;@@ -281,13 +281,36 @@ export const libraryCloud = {/** Finish a library upload: verify, mark complete, register the asset. */async complete(userId: string, req: Request) {try {- const { key, meta } = (await req.json()) as { key?: string; meta?: AssetMeta };+ const { key, posterKey, meta } = (await req.json()) as {+ key?: string;+ posterKey?: string;+ meta?: AssetMeta;+ };if (!key) return err("key is required.", 400);const obj = await prisma.cutMediaObject.findFirst({ where: { userId, r2Key: key } });if (!obj) return err("Unknown upload.", 404);const info = obj.uploadState === "complete" ? null : await head(key);if (obj.uploadState !== "complete" && !info) return err("The upload never arrived.", 400);+ // A cover that came up alongside the file: its own object, finished the+ // same way, named on the asset so the delete cascade takes it too.+ const posterObj = posterKey+ ? await prisma.cutMediaObject.findFirst({ where: { userId, r2Key: posterKey } })+ : null;+ const posterInfo =+ posterObj && posterObj.uploadState !== "complete" ? await head(posterKey!) : null;+ const posterFile = posterInfo || posterObj?.uploadState === "complete" ? posterObj!.fileName : undefined;const row = await prisma.$transaction(async (tx) => {+ if (posterObj && posterInfo) {+ await tx.cutMediaObject.update({+ where: { id: posterObj.id },+ data: {+ uploadState: "complete",+ bytes: BigInt(posterInfo.bytes),+ ...(posterInfo.mime ? { mime: posterInfo.mime } : {}),+ },+ });+ await addUsage(tx, userId, posterInfo.bytes);+ }if (info) {await tx.cutMediaObject.update({where: { id: obj.id },@@ -309,6 +332,9 @@ export const libraryCloud = {duration: meta?.duration ?? 0,...(meta?.width ? { width: meta.width, height: meta.height } : {}),...(meta?.source ? { source: meta.source } : {}),+ ...(posterFile ?? meta?.posterFile+ ? { posterFile: posterFile ?? meta?.posterFile }+ : {}),} as unknown as Prisma.InputJsonValue,},});@@ -616,3 +642,15 @@ export const libraryCloud = {}},};++/** The folder a new account starts with, so the Library shows that it takes+ * font files before anyone has dropped one in. Derived from the user id, so a+ * retried signup lands on the same row; an ordinary folder otherwise, free to+ * rename, empty, or delete. */+export const fontsFolderId = (userId: string) => `fonts-${userId}`;++export async function seedFontsFolder(userId: string): Promise<void> {+ const id = fontsFolderId(userId);+ if (await prisma.cutFolder.findUnique({ where: { id } })) return;+ await prisma.cutFolder.create({ data: { id, userId, name: "Fonts", scope: "library" } });+}diff --git a/site/src/cut/server/cloud/util.ts b/site/src/cut/server/cloud/util.tsindex 0ab2dd3d..ada57def 100644--- a/site/src/cut/server/cloud/util.ts+++ b/site/src/cut/server/cloud/util.ts@@ -61,10 +61,12 @@ export function dedupeName(base: string, taken: ReadonlySet<string>): string {const VIDEO_RE = /\.(mp4|mov|m4v|webm|mkv)$/i;const AUDIO_RE = /\.(mp3|m4a|aac|wav|ogg|flac)$/i;const IMAGE_RE = /\.(png|jpe?g|webp|gif|avif|bmp)$/i;+const FONT_RE = /\.(ttf|otf|woff2?)$/i;-export function typeOf(fileName: string): "video" | "audio" | "image" | null {+export function typeOf(fileName: string): "video" | "audio" | "image" | "font" | null {if (VIDEO_RE.test(fileName)) return "video";if (AUDIO_RE.test(fileName)) return "audio";if (IMAGE_RE.test(fileName)) return "image";+ if (FONT_RE.test(fileName)) return "font";return null;}diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.tsindex 8669a4af..1a7e9bac 100644--- a/site/src/cut/server/library.ts+++ b/site/src/cut/server/library.ts@@ -24,7 +24,7 @@ export interface LibraryAsset {id: string;fileName: string;name: string;- type: "video" | "audio" | "image";+ type: "video" | "audio" | "image" | "font";duration: number;width?: number;height?: number;@@ -163,6 +163,7 @@ export async function listLibrary(): Promise<LibraryAsset[]> {const VIDEO_RE = /\.(mp4|mov|m4v|webm|mkv)$/i;const AUDIO_RE = /\.(mp3|m4a|aac|wav|ogg|flac)$/i;const IMAGE_RE = /\.(png|jpe?g|webp|gif|avif|bmp)$/i;+const FONT_RE = /\.(ttf|otf|woff2?)$/i;function ffprobe(args: string[]): Promise<string> {return new Promise((resolve, reject) => {@@ -210,10 +211,11 @@ async function freeName(original: string) {return uniqueName(base, libMediaPath);}-function typeOf(fileName: string): "video" | "audio" | "image" | null {+function typeOf(fileName: string): "video" | "audio" | "image" | "font" | null {if (VIDEO_RE.test(fileName)) return "video";if (AUDIO_RE.test(fileName)) return "audio";if (IMAGE_RE.test(fileName)) return "image";+ if (FONT_RE.test(fileName)) return "font";return null;}@@ -225,7 +227,8 @@ export async function register(): Promise<LibraryAsset> {const type = typeOf(fileName);if (!type) throw new Error("Unsupported file type.");- const meta = await probe(libMediaPath(fileName));+ const meta: { duration: number; width?: number; height?: number } =+ type === "font" ? { duration: 0 } : await probe(libMediaPath(fileName));const asset: LibraryAsset = {id: crypto.randomUUID().slice(0, 8),fileName,diff --git a/site/src/cut/server/serveFile.ts b/site/src/cut/server/serveFile.tsindex 245e1b2b..3bba35e1 100644--- a/site/src/cut/server/serveFile.ts+++ b/site/src/cut/server/serveFile.ts@@ -22,6 +22,10 @@ const TYPES: Record<string, string> = {".gif": "image/gif",".avif": "image/avif",".heic": "image/heic",+ ".ttf": "font/ttf",+ ".otf": "font/otf",+ ".woff": "font/woff",+ ".woff2": "font/woff2",};export function contentTypeFor(p: string) {diff --git a/site/src/lib/onboarding/signup-grants.ts b/site/src/lib/onboarding/signup-grants.tsindex 4e4e2256..ea6222c1 100644--- a/site/src/lib/onboarding/signup-grants.ts+++ b/site/src/lib/onboarding/signup-grants.ts@@ -1,3 +1,4 @@+import { seedFontsFolder } from "@/cut/server/cloud/library";import { seedStarterProject } from "@/cut/server/cloud/starter";import { creditStringToMicros } from "@/lib/credits/amounts";import { grantCredits } from "@/lib/credits/inference";@@ -17,6 +18,7 @@ export async function provisionSignupGrants(user: EmailUser): Promise<void> {const results = await Promise.allSettled([grantSignupAppCredits(user.id),seedStarterProject(user.id),+ seedFontsFolder(user.id),sendWelcomeEmail(user),syncResendContact(user),]);