Skip to content

Open source CapCut alternative.

TypeScript

feat(site): reuse library cards in shared views [rebuild]

David Lea08e0d0d2a3b
diff --git a/site/src/cut/components/CameraRollView.tsx b/site/src/cut/components/CameraRollView.tsx
index 5c492493..a7fc155b 100644
--- a/site/src/cut/components/CameraRollView.tsx
+++ b/site/src/cut/components/CameraRollView.tsx
@@ -20,7 +20,7 @@ import { patchLibrary, refetchLibrary, useLibrary } from "@/cut/lib/queries";
import { formatDate } from "@/cut/lib/time";
import { shapeBand } from "@/cut/lib/types";
import { Lightbox } from "./Lightbox";
-import { LibraryCard } from "./LibraryView";
+import { LibraryCard } from "@/cut/components/LibraryCard";
/** The phone's recordings, synced up from the iOS app: every cloud library
* asset tagged origin "camera", newest first. Clips here are ordinary library
diff --git a/site/src/cut/components/FontSpecimen.tsx b/site/src/cut/components/FontSpecimen.tsx
index 22cbb831..41ca5485 100644
--- a/site/src/cut/components/FontSpecimen.tsx
+++ b/site/src/cut/components/FontSpecimen.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useLayoutEffect, useRef, useState } from "react";
+import { useEffect, useId, useLayoutEffect, useRef, useState } from "react";
import { isCurrentSpecimen, SPECIMEN_LINES } from "@/cut/lib/fontSpecimen";
import { linkIdForAsset, onLinkedChanged } from "@/cut/lib/linkedLibrary";
import { MEDIA_CORS } from "@/cut/lib/mediaCors";
@@ -30,6 +30,7 @@ const SAFETY = 0.97;
*/
export function FontSpecimen({
assetId,
+ src,
poster,
lines: LINES = SPECIMEN_LINES,
fitHeight = false,
@@ -38,6 +39,8 @@ export function FontSpecimen({
}: {
/** The library asset holding the font file. */
assetId: string;
+ /** A protected font URL for a viewer outside the signed-in library. */
+ src?: string;
/** The specimen the shelf keeps for this file. */
poster?: string;
/** What to set in the face. A card takes one line, the big view the whole
@@ -59,8 +62,22 @@ export function FontSpecimen({
useEffect(() => onFontsChanged(again), []);
useEffect(() => onLinkedChanged(again), []);
const id = linkIdForAsset(assetId) ?? "";
- const family = fontStack(id);
- const installed = hasFont(id);
+ const localId = useId();
+ const [loadedFont, setLoadedFont] = useState<{ src: string; family: string } | null>(null);
+ useEffect(() => {
+ if (!src) return;
+ let live = true;
+ const face = new FontFace(`shared-${localId}`, `url(${JSON.stringify(src)})`);
+ void face.load().then(() => {
+ if (!live) return;
+ document.fonts.add(face);
+ setLoadedFont({ src, family: face.family });
+ }).catch(() => {});
+ return () => { live = false; document.fonts.delete(face); };
+ }, [src, localId]);
+ const localFamily = loadedFont?.src === src ? loadedFont?.family : undefined;
+ const family = localFamily ? JSON.stringify(localFamily) : fontStack(id);
+ const installed = !!localFamily || hasFont(id);
const box = useRef<HTMLDivElement>(null);
const probe = useRef<HTMLSpanElement>(null);
const [size, setSize] = useState(0);
diff --git a/site/src/cut/components/LibraryCard.tsx b/site/src/cut/components/LibraryCard.tsx
new file mode 100644
index 00000000..5519089f
--- /dev/null
+++ b/site/src/cut/components/LibraryCard.tsx
@@ -0,0 +1,437 @@
+"use client";
+
+import { useState, type ReactNode } from "react";
+import { Download, Ellipsis, ExternalLink, Film, Image as ImageIcon, Music, Plus, Share2, Trash2, Type } from "lucide-react";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
+import { Skeleton } from "@/components/ui/skeleton";
+import { MediaCardShell } from "@/cut/components/MediaCardShell";
+import { ShelfBadge } from "@/cut/components/ShelfBadge";
+import { AudioCardFace } from "@/cut/components/AudioPanel";
+import { CopyNameLabel } from "@/cut/components/AssetRefs";
+import { FontSpecimen } from "@/cut/components/FontSpecimen";
+import { useInView } from "@/cut/hooks/useInView";
+import { useMediaFileSize } from "@/cut/hooks/useMediaFileSize";
+import { MEDIA_CORS } from "@/cut/lib/mediaCors";
+import { setLibraryDragData } from "@/cut/lib/assetDrag";
+import { refFromLibrary } from "@/cut/lib/assetRef";
+import { fileKind } from "@/cut/lib/media";
+import { libraryMediaUrl, libraryPosterUrl, downloadLibraryAsset, type LibraryAsset } from "@/cut/lib/library";
+import { lightboxItemFromLibrary, type LightboxItem } from "@/cut/lib/lightbox";
+import { availableResidencies } from "@/cut/lib/residency";
+import { SPECIMEN_BG, SPECIMEN_INK, SPECIMEN_META } from "@/cut/lib/fontSpecimen";
+import { PICKED_RING } from "@/cut/lib/assetPick";
+import { formatTime } from "@/cut/lib/time";
+import { formatBytes } from "@/lib/bytes";
+import { cn } from "@/lib/utils";
+
+export const LIBRARY_TILE_AREA = 180 * 320;
+export const LIBRARY_AUDIO_TILE_AREA = LIBRARY_TILE_AREA * 0.7 ** 2;
+
+type SharedMedia = { src: string; poster?: string; downloadHref: string };
+
+/** The library media card, with protected media URLs supplied by a share viewer. */
+export function LibraryCard({
+ asset: a,
+ sharedMedia,
+ selected,
+ offline = false,
+ area,
+ mention = false,
+ caption,
+ dragGroup,
+ onClick,
+ onDelete,
+ onUse,
+ onShare,
+ onDragStartExtra,
+}: {
+ asset: LibraryAsset;
+ sharedMedia?: SharedMedia;
+ selected?: boolean;
+ /** The shelf this item is on isn't answering: it lists from memory, so the
+ * card shows what it knows and reaches for no media it can't load. */
+ offline?: boolean;
+ /** Tile area in square pixels. When set, the tile takes the media's own
+ * aspect at this shared area — a wide clip spreads, a tall one stands, and
+ * every card carries the same weight. Unset, the tile fills its grid cell
+ * as a square. Audio and unmeasured assets sit square either way. */
+ area?: number;
+ /** The card sits beside a prompt (the editor's Library panel), so its name
+ * doubles as a mention token to copy. */
+ mention?: boolean;
+ /** A line under the tile — where the Camera Roll puts a recording's date. */
+ caption?: ReactNode;
+ /** Everything picked on this shelf right now. Dragging a card that is one of
+ * them carries the whole set, so a drop lands the lot. */
+ dragGroup?: LibraryAsset[];
+ onClick?: (e: React.MouseEvent) => void;
+ onDelete?: () => void;
+ onUse?: () => void;
+ onShare?: () => void;
+ onDragStartExtra?: (e: React.DragEvent) => void;
+}) {
+ // ⌘C over the card copies its mention token. A card inside the current
+ // selection carries the whole set, the same rule its drag follows. A font is
+ // used from the font menu, so it names nothing a prompt can point a tool
+ // at.
+ const refs = () => sharedMedia ? [] :
+ (selected && dragGroup?.length ? dragGroup : [a])
+ .filter((x) => x.type !== "font")
+ .map(refFromLibrary);
+ // With one shelf listed, every card is on it — the badge would say nothing.
+ // Phone recordings all come up from the cloud, so they carry none either.
+ const bothShelves =
+ !sharedMedia && a.origin !== "camera" && (availableResidencies().length > 1 || offline);
+ // Each card is a real media element, so the source waits until the tile has
+ // been scrolled near: a large library would otherwise pull every file's
+ // metadata across the network the moment the page opened.
+ const [tileRef, seen] = useInView<HTMLDivElement>();
+ const src = sharedMedia?.src ?? libraryMediaUrl(a.fileName, a.residency);
+ const poster = sharedMedia ? sharedMedia.poster : libraryPosterUrl(a);
+ const view = (): LightboxItem => sharedMedia ? {
+ kind: a.type, src, name: a.title || a.name, prompt: "", assetId: null, bare: true,
+ duration: a.duration, poster, ...(a.width && a.height ? { ratio: a.width / a.height } : {}),
+ } : lightboxItemFromLibrary(a, !onUse);
+
+ // Poster from the video itself so the still matches what plays on hover.
+ // An ffmpeg still washes out iPhone HDR (HLG) footage — the browser tone-maps
+ // the video correctly, so we render the frame instead of a baked thumbnail.
+ const posterT = Math.min(1, Math.max(0.1, (a.duration || 2) / 10));
+ // Whether the tile's own picture has painted. Until it does the tile is a
+ // shimmering slab, so a clip that lands while the page is open takes its
+ // place in the grid at once and resolves into itself a moment later.
+ const [painted, setPainted] = useState(false);
+ // The size pill only shows on hover, so the lookup waits for the first one.
+ // A font wears its size in the footer at rest, so that one asks as it scrolls
+ // into view.
+ const [hovered, setHovered] = useState(false);
+ const font = a.type === "font";
+ const sizeBytes = useMediaFileSize(
+ offline ? "" : src,
+ hovered || (font && seen),
+ );
+ // TTF · 42 KB — what the file is, and how much of it there is.
+ const fontMeta = [
+ fileKind(a.fileName),
+ sizeBytes != null && formatBytes(sizeBytes),
+ ]
+ .filter(Boolean)
+ .join(" · ");
+ const frame =
+ area && a.type !== "audio" && a.width && a.height
+ ? { w: a.width, h: a.height }
+ : font
+ ? { w: 16, h: 6 }
+ : { w: 1, h: 1 };
+ const tileStyle = {
+ ...(area
+ ? {
+ width: Math.round(Math.sqrt((area * frame.w) / frame.h)),
+ aspectRatio: `${frame.w} / ${frame.h}`,
+ }
+ : {}),
+ ...(font ? { backgroundColor: SPECIMEN_BG, color: SPECIMEN_INK } : {}),
+ };
+
+ return (
+ <MediaCardShell
+ scope="library"
+ id={a.id}
+ refs={refs}
+ // Without a + button there is no project to add it to, so the viewer
+ // opens bare.
+ view={offline ? undefined : view}
+ restTime={posterT}
+ draggable={!offline && !sharedMedia}
+ className="group flex min-w-0 max-w-full flex-col"
+ onClick={onClick}
+ onDragStart={(e) => {
+ if (sharedMedia) return;
+ setLibraryDragData(e, a, dragGroup);
+ onDragStartExtra?.(e);
+ }}
+ onHover={() => setHovered(true)}
+ >
+ {({ flash, videoRef }) => (
+ <>
+ <div
+ ref={tileRef}
+ data-drag-object
+ className={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 && (font ? "aspect-[16/7]" : "aspect-square"),
+ // The sheet is the card, so nothing is drawn around it; the type
+ // scales with the tile, which runs from a panel column to a full row.
+ font && "@container flex flex-col",
+ selected || flash
+ ? PICKED_RING
+ : font
+ ? "border-transparent"
+ : "border-border",
+ )}
+ style={tileStyle}
+ >
+ {font ? (
+ // A pangram set in the face, and under a hairline the name it goes by
+ // with the file behind it. Nothing to load from a shelf that isn't
+ // answering, so that card shows the kind mark instead.
+ <div className="flex size-full min-h-0 flex-col">
+ <div className="grid min-h-0 flex-1 place-items-center px-3 pt-3 @[220px]:px-5 @[220px]:pt-5">
+ {offline ? (
+ <Type className="size-6 text-white/35" />
+ ) : (
+ <FontSpecimen
+ assetId={a.id}
+ src={sharedMedia && seen ? src : undefined}
+ fitHeight
+ pad={0}
+ className="size-full"
+ />
+ )}
+ </div>
+ <div className="mx-3 flex items-center justify-between gap-2 border-t border-white/10 py-2 @[220px]:mx-5 @[220px]:py-3">
+ <CopyNameLabel
+ name={a.name}
+ label={a.title}
+ dark
+ mention={false}
+ className="min-w-0 text-[11px] font-medium @[220px]:text-[13px]"
+ />
+ {fontMeta && (
+ <span
+ data-drag-omit
+ className="shrink-0 text-[10px] tabular-nums @[220px]:text-[11px]"
+ style={{ color: SPECIMEN_META }}
+ >
+ {fontMeta}
+ </span>
+ )}
+ </div>
+ </div>
+ ) : offline ? (
+ // Nothing to load from a shelf that isn't answering, so the card
+ // shows what it knows: the kind of file, its name, its length.
+ <span className="grid size-full place-items-center">
+ {a.type === "audio" ? (
+ <Music className="size-6 text-muted-foreground/50" />
+ ) : a.type === "image" ? (
+ <ImageIcon className="size-6 text-muted-foreground/50" />
+ ) : (
+ <Film className="size-6 text-muted-foreground/50" />
+ )}
+ </span>
+ ) : a.type === "video" ? (
+ seen && (
+ <>
+ <video
+ crossOrigin={MEDIA_CORS}
+ ref={videoRef}
+ src={`${src}#t=${posterT}`}
+ poster={poster}
+ muted
+ loop
+ playsInline
+ preload="metadata"
+ className="size-full object-cover"
+ // Whichever lands first: a clip with a stored poster paints
+ // from that, one without paints its own first frame.
+ onLoadedMetadata={() => setPainted(true)}
+ onLoadedData={() => setPainted(true)}
+ onError={() => setPainted(true)}
+ />
+ {/* The source's own cover — a video's thumbnail where it came
+ from — is the face at rest: the element's poster gives way as
+ soon as the browser has the frame at #t, and that frame is
+ whatever the clip happens to hold a second in. Hovering
+ uncovers the video, which is what plays. */}
+ {poster && (
+ // eslint-disable-next-line @next/next/no-img-element -- library media file, not Next-optimizable
+ <img
+ crossOrigin={MEDIA_CORS}
+ src={poster}
+ alt=""
+ aria-hidden
+ className="pointer-events-none absolute inset-0 size-full object-cover transition-opacity group-hover:opacity-0"
+ onLoad={() => setPainted(true)}
+ onError={() => setPainted(true)}
+ />
+ )}
+ </>
+ )
+ ) : a.type === "image" ? (
+ // eslint-disable-next-line @next/next/no-img-element -- library media file, not Next-optimizable
+ <img
+ crossOrigin={MEDIA_CORS}
+ src={src}
+ alt={a.name}
+ loading="lazy"
+ className="size-full object-cover"
+ onLoad={() => setPainted(true)}
+ onError={() => setPainted(true)}
+ />
+ ) : (
+ <AudioCardFace
+ url={src}
+ duration={a.duration}
+ // On hover the + button takes the pill's corner.
+ durationClassName={
+ !!onUse && "transition-opacity group-hover:opacity-0"
+ }
+ />
+ )}
+ {!offline && !font && a.type !== "audio" && !painted && (
+ <Skeleton
+ data-drag-omit
+ aria-hidden
+ className="pointer-events-none absolute inset-0 rounded-none"
+ />
+ )}
+ {a.type !== "audio" &&
+ !font &&
+ (a.type === "video" || sizeBytes != null) && (
+ // Length and size share one pill in the corner: on a card this narrow
+ // two of them collide. The length reads at rest, the size takes over
+ // on hover, where the + button is what the pointer is there for.
+ <span
+ data-drag-omit
+ className={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" && (
+ <span className={cn(sizeBytes != null && "group-hover:hidden")}>
+ {formatTime(a.duration)}
+ </span>
+ )}
+ {sizeBytes != null && (
+ <span
+ className={cn(
+ a.type === "video" && "hidden group-hover:inline",
+ )}
+ >
+ {formatBytes(sizeBytes)}
+ </span>
+ )}
+ </span>
+ )}
+ {a.type === "audio" && sizeBytes != null && (
+ // Clear of the play circle, matching the face's duration pill.
+ <span className="absolute bottom-3 left-12 rounded-md bg-[#2b4e42] px-1.5 py-0.5 font-mono text-[10px] text-[#d6eddf] tabular-nums opacity-0 transition-opacity group-hover:opacity-100">
+ {formatBytes(sizeBytes)}
+ </span>
+ )}
+ {onUse && (
+ <button
+ aria-label="Add to timeline"
+ title="Add to timeline"
+ 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 font's bottom edge is its footer, so its + takes the corner
+ // the name used to sit in.
+ a.type === "audio"
+ ? "right-1.5 bottom-1.5"
+ : font
+ ? "top-1.5 left-1.5"
+ : "bottom-1.5 left-1.5",
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ onUse();
+ }}
+ >
+ <Plus className="size-3.5" />
+ </button>
+ )}
+ {bothShelves && (
+ <ShelfBadge
+ residency={a.residency}
+ offline={offline}
+ className={cn(
+ "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",
+ )}
+ />
+ )}
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ aria-label="More actions"
+ title="More actions"
+ className={cn(
+ "absolute top-1.5 right-1.5 grid size-6 place-items-center rounded-full text-white opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100",
+ // A black scrim disappears into the charcoal sheet.
+ font
+ ? "bg-white/10 hover:bg-white/20"
+ : "bg-black/40 hover:bg-black/60",
+ )}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <Ellipsis className="size-3.5" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ // Hung off the card's right edge rather than laid over the media:
+ // the tile stays readable behind the open menu.
+ align="start"
+ alignOffset={4}
+ className="w-44"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {onShare && <DropdownMenuItem disabled={offline} onClick={onShare}><Share2 /> Share</DropdownMenuItem>}
+ {sharedMedia ? (
+ <DropdownMenuItem render={<a href={sharedMedia.downloadHref} />}>
+ <Download /> Download
+ </DropdownMenuItem>
+ ) : (
+ <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")
+ }
+ >
+ <ExternalLink /> Open original
+ </DropdownMenuItem>
+ )}
+ {onDelete && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" onClick={onDelete}>
+ <Trash2 /> Delete
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {!font && (
+ <CopyNameLabel
+ name={a.name}
+ label={a.title}
+ dark={a.type === "audio"}
+ mention={mention}
+ 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",
+ )}
+ />
+ )}
+ </div>
+ {caption && (
+ <div data-drag-omit className="mt-2 px-0.5 text-xs text-muted-foreground">
+ {caption}
+ </div>
+ )}
+ </>
+ )}
+ </MediaCardShell>
+ );
+}
diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsx
index 4950f07f..89bd7ad4 100644
--- a/site/src/cut/components/LibraryView.tsx
+++ b/site/src/cut/components/LibraryView.tsx
@@ -1,26 +1,16 @@
"use client";
-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useRouter, useSearchParams } from "next/navigation";
import {
- Cloud,
- Download,
- Ellipsis,
- ExternalLink,
- Film,
FolderOpen,
FolderPlus,
- Image as ImageIcon,
- Laptop,
Link as LinkIcon,
Loader2,
- Music,
- Plus,
RotateCcw,
Share2,
Trash2,
- Type,
Upload,
X,
} from "lucide-react";
@@ -29,8 +19,6 @@ import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useElapsed } from "@/cut/hooks/useElapsed";
import {
@@ -57,14 +45,10 @@ import {
TooltipTrigger,
} from "@/components/ui/tooltip";
import { Skeleton } from "@/components/ui/skeleton";
-import { MEDIA_CORS } from "@/cut/lib/mediaCors";
-import {
- setLibraryDragData,
- setObjectDragImage,
-} from "@/cut/lib/assetDrag";
-import { useInView } from "@/cut/hooks/useInView";
-import { MediaCardShell } from "./MediaCardShell";
-import { assetTypeOf, fileKind, isMediaFile, MEDIA_ACCEPT } from "@/cut/lib/media";
+import { setObjectDragImage } from "@/cut/lib/assetDrag";
+import { LibraryCard, LIBRARY_TILE_AREA, LIBRARY_AUDIO_TILE_AREA } from "@/cut/components/LibraryCard";
+import { ShelfBadge } from "@/cut/components/ShelfBadge";
+import { assetTypeOf, isMediaFile, MEDIA_ACCEPT } from "@/cut/lib/media";
import { isFontArchive } from "@/cut/lib/fontArchive";
import { libraryKey, libraryScope, patchLibrary, refetchLibrary, useLibrary } from "@/cut/lib/queries";
import {
@@ -72,11 +56,9 @@ import {
deleteFromLibrary,
deleteLibraryFolder,
deleteTemplate,
- downloadLibraryAsset,
estimatedShape,
importUrlToLibrary,
libraryMediaUrl,
- libraryPosterUrl,
carryAssetTo,
carryTemplateTo,
moveLibraryItem,
@@ -95,11 +77,7 @@ import { reportActivity } from "@/cut/lib/tabActivity";
import { useNewProjectTarget } from "@/cut/lib/newProject";
import { useListedResidencies, useLocalCompute } from "@/cut/lib/backend/hooks";
import { setNeedsApp } from "@/cut/lib/needsApp";
-import {
- availableResidencies,
- RESIDENCY_LABEL,
- type Residency,
-} from "@/cut/lib/residency";
+import type { Residency } from "@/cut/lib/residency";
import { LibraryShareDialog } from "@/cut/components/LibraryShareDialog";
import type { LibraryShareTarget } from "@/cut/lib/librarySharing";
import { Lightbox } from "./Lightbox";
@@ -116,22 +94,10 @@ import {
syncLinkedLibrary,
} from "@/cut/lib/linkedLibrary";
import { shapeBand } from "@/cut/lib/types";
-import { formatTime } from "@/cut/lib/time";
import { cn } from "@/lib/utils";
-import { refFromLibrary } from "@/cut/lib/assetRef";
-import { CopyNameLabel } from "./AssetRefs";
-import { FontSpecimen } from "./FontSpecimen";
-import {
- SPECIMEN_BG,
- SPECIMEN_INK,
- SPECIMEN_META,
-} from "@/cut/lib/fontSpecimen";
import { AudioCardFace } from "./AudioPanel";
import { childrenOf, folderTrail, folderWithin, parentOf } from "@/cut/lib/folderTree";
import { FolderCrumb, FolderShelf, Marquee } from "./desktopFolders";
-import { formatBytes } from "@/lib/bytes";
-import { useMediaFileSize } from "@/cut/hooks/useMediaFileSize";
-import { PICKED_RING } from "@/cut/lib/assetPick";
// A dragged library selection travels as a JSON array of asset ids, so a whole
// marquee-selected collection can be dropped onto a folder at once.
@@ -359,33 +325,6 @@ function PendingTile({
);
}
-/** Which shelf an item sits on, on its card. The library merges both, so the
- * badge is how you tell a clip on this Mac from one in the cloud — and, when
- * the app isn't answering, why that clip is showing but not usable. */
-export function ShelfBadge({
- residency,
- offline = false,
- className,
-}: {
- residency: Residency;
- offline?: boolean;
- className?: string;
-}) {
- const Icon = residency === "cloud" ? Cloud : Laptop;
- return (
- <span
- title={
- offline
- ? "Local — open the Donkey app to use it"
- : RESIDENCY_LABEL[residency]
- }
- className={className}
- >
- <Icon className="size-3" />
- </span>
- );
-}
-
export function LibraryView() {
const router = useRouter();
const base = useCutBase();
@@ -870,8 +809,8 @@ export function LibraryView() {
});
for (const a of shown) band(shapeOf(a)).push({ asset: a });
// Sound tiles are 70% of the shared tile's width and height.
- const TILE_AREA = 180 * 320;
- const audioArea = TILE_AREA * 0.7 ** 2;
+ const TILE_AREA = LIBRARY_TILE_AREA;
+ const audioArea = LIBRARY_AUDIO_TILE_AREA;
const shownTemplates = templates.filter(
(t) => (t.folderId ?? null) === openFolder,
);
@@ -1263,399 +1202,3 @@ export function LibraryView() {
</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,
- offline = false,
- area,
- mention = false,
- caption,
- dragGroup,
- onClick,
- onDelete,
- onUse,
- onShare,
- onDragStartExtra,
-}: {
- asset: LibraryAsset;
- selected?: boolean;
- /** The shelf this item is on isn't answering: it lists from memory, so the
- * card shows what it knows and reaches for no media it can't load. */
- offline?: boolean;
- /** Tile area in square pixels. When set, the tile takes the media's own
- * aspect at this shared area — a wide clip spreads, a tall one stands, and
- * every card carries the same weight. Unset, the tile fills its grid cell
- * as a square. Audio and unmeasured assets sit square either way. */
- area?: number;
- /** The card sits beside a prompt (the editor's Library panel), so its name
- * doubles as a mention token to copy. */
- mention?: boolean;
- /** A line under the tile — where the Camera Roll puts a recording's date. */
- caption?: ReactNode;
- /** Everything picked on this shelf right now. Dragging a card that is one of
- * them carries the whole set, so a drop lands the lot. */
- dragGroup?: LibraryAsset[];
- onClick?: (e: React.MouseEvent) => void;
- onDelete?: () => void;
- onUse?: () => void;
- onShare?: () => void;
- onDragStartExtra?: (e: React.DragEvent) => void;
-}) {
- // ⌘C over the card copies its mention token. A card inside the current
- // selection carries the whole set, the same rule its drag follows. A font is
- // used from the font menu, so it names nothing a prompt can point a tool
- // at.
- const refs = () =>
- (selected && dragGroup?.length ? dragGroup : [a])
- .filter((x) => x.type !== "font")
- .map(refFromLibrary);
- // With one shelf listed, every card is on it — the badge would say nothing.
- // Phone recordings all come up from the cloud, so they carry none either.
- const bothShelves =
- a.origin !== "camera" && (availableResidencies().length > 1 || offline);
- // Each card is a real media element, so the source waits until the tile has
- // been scrolled near: a large library would otherwise pull every file's
- // metadata across the network the moment the page opened.
- const [tileRef, seen] = useInView<HTMLDivElement>();
- // Poster from the video itself so the still matches what plays on hover.
- // An ffmpeg still washes out iPhone HDR (HLG) footage — the browser tone-maps
- // the video correctly, so we render the frame instead of a baked thumbnail.
- const posterT = Math.min(1, Math.max(0.1, (a.duration || 2) / 10));
- // Whether the tile's own picture has painted. Until it does the tile is a
- // shimmering slab, so a clip that lands while the page is open takes its
- // place in the grid at once and resolves into itself a moment later.
- const [painted, setPainted] = useState(false);
- // The size pill only shows on hover, so the lookup waits for the first one.
- // A font wears its size in the footer at rest, so that one asks as it scrolls
- // into view.
- const [hovered, setHovered] = useState(false);
- const font = a.type === "font";
- const sizeBytes = useMediaFileSize(
- offline ? "" : libraryMediaUrl(a.fileName, a.residency),
- hovered || (font && seen),
- );
- // TTF · 42 KB — what the file is, and how much of it there is.
- const fontMeta = [
- fileKind(a.fileName),
- sizeBytes != null && formatBytes(sizeBytes),
- ]
- .filter(Boolean)
- .join(" · ");
- const frame =
- area && a.type !== "audio" && a.width && a.height
- ? { w: a.width, h: a.height }
- : font
- ? { w: 16, h: 6 }
- : { w: 1, h: 1 };
- const tileStyle = {
- ...(area
- ? {
- width: Math.round(Math.sqrt((area * frame.w) / frame.h)),
- aspectRatio: `${frame.w} / ${frame.h}`,
- }
- : {}),
- ...(font ? { backgroundColor: SPECIMEN_BG, color: SPECIMEN_INK } : {}),
- };
-
- return (
- <MediaCardShell
- scope="library"
- id={a.id}
- refs={refs}
- // Without a + button there is no project to add it to, so the viewer
- // opens bare.
- view={offline ? undefined : () => lightboxItemFromLibrary(a, !onUse)}
- restTime={posterT}
- draggable={!offline}
- className="group flex flex-col"
- onClick={onClick}
- onDragStart={(e) => {
- setLibraryDragData(e, a, dragGroup);
- onDragStartExtra?.(e);
- }}
- onHover={() => setHovered(true)}
- >
- {({ flash, videoRef }) => (
- <>
- <div
- ref={tileRef}
- data-drag-object
- className={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 && (font ? "aspect-[16/7]" : "aspect-square"),
- // The sheet is the card, so nothing is drawn around it; the type
- // scales with the tile, which runs from a panel column to a full row.
- font && "@container flex flex-col",
- selected || flash
- ? PICKED_RING
- : font
- ? "border-transparent"
- : "border-border",
- )}
- style={tileStyle}
- >
- {font ? (
- // A pangram set in the face, and under a hairline the name it goes by
- // with the file behind it. Nothing to load from a shelf that isn't
- // answering, so that card shows the kind mark instead.
- <div className="flex size-full min-h-0 flex-col">
- <div className="grid min-h-0 flex-1 place-items-center px-3 pt-3 @[220px]:px-5 @[220px]:pt-5">
- {offline ? (
- <Type className="size-6 text-white/35" />
- ) : (
- <FontSpecimen
- assetId={a.id}
- fitHeight
- pad={0}
- className="size-full"
- />
- )}
- </div>
- <div className="mx-3 flex items-center justify-between gap-2 border-t border-white/10 py-2 @[220px]:mx-5 @[220px]:py-3">
- <CopyNameLabel
- name={a.name}
- label={a.title}
- dark
- mention={false}
- className="min-w-0 text-[11px] font-medium @[220px]:text-[13px]"
- />
- {fontMeta && (
- <span
- data-drag-omit
- className="shrink-0 text-[10px] tabular-nums @[220px]:text-[11px]"
- style={{ color: SPECIMEN_META }}
- >
- {fontMeta}
- </span>
- )}
- </div>
- </div>
- ) : offline ? (
- // Nothing to load from a shelf that isn't answering, so the card
- // shows what it knows: the kind of file, its name, its length.
- <span className="grid size-full place-items-center">
- {a.type === "audio" ? (
- <Music className="size-6 text-muted-foreground/50" />
- ) : a.type === "image" ? (
- <ImageIcon className="size-6 text-muted-foreground/50" />
- ) : (
- <Film className="size-6 text-muted-foreground/50" />
- )}
- </span>
- ) : a.type === "video" ? (
- seen && (
- <>
- <video
- crossOrigin={MEDIA_CORS}
- ref={videoRef}
- src={`${libraryMediaUrl(a.fileName, a.residency)}#t=${posterT}`}
- poster={libraryPosterUrl(a)}
- muted
- loop
- playsInline
- preload="metadata"
- className="size-full object-cover"
- // Whichever lands first: a clip with a stored poster paints
- // from that, one without paints its own first frame.
- onLoadedMetadata={() => setPainted(true)}
- onLoadedData={() => setPainted(true)}
- onError={() => setPainted(true)}
- />
- {/* The source's own cover — a video's thumbnail where it came
- from — is the face at rest: the element's poster gives way as
- soon as the browser has the frame at #t, and that frame is
- whatever the clip happens to hold a second in. Hovering
- uncovers the video, which is what plays. */}
- {libraryPosterUrl(a) && (
- // eslint-disable-next-line @next/next/no-img-element -- library media file, not Next-optimizable
- <img
- crossOrigin={MEDIA_CORS}
- src={libraryPosterUrl(a)}
- alt=""
- aria-hidden
- className="pointer-events-none absolute inset-0 size-full object-cover transition-opacity group-hover:opacity-0"
- onLoad={() => setPainted(true)}
- onError={() => setPainted(true)}
- />
- )}
- </>
- )
- ) : 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"
- onLoad={() => setPainted(true)}
- onError={() => setPainted(true)}
- />
- ) : (
- <AudioCardFace
- url={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"
- }
- />
- )}
- {!offline && !font && a.type !== "audio" && !painted && (
- <Skeleton
- data-drag-omit
- aria-hidden
- className="pointer-events-none absolute inset-0 rounded-none"
- />
- )}
- {a.type !== "audio" &&
- !font &&
- (a.type === "video" || sizeBytes != null) && (
- // Length and size share one pill in the corner: on a card this narrow
- // two of them collide. The length reads at rest, the size takes over
- // on hover, where the + button is what the pointer is there for.
- <span
- data-drag-omit
- className={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" && (
- <span className={cn(sizeBytes != null && "group-hover:hidden")}>
- {formatTime(a.duration)}
- </span>
- )}
- {sizeBytes != null && (
- <span
- className={cn(
- a.type === "video" && "hidden group-hover:inline",
- )}
- >
- {formatBytes(sizeBytes)}
- </span>
- )}
- </span>
- )}
- {a.type === "audio" && sizeBytes != null && (
- // Clear of the play circle, matching the face's duration pill.
- <span className="absolute bottom-3 left-12 rounded-md bg-[#2b4e42] px-1.5 py-0.5 font-mono text-[10px] text-[#d6eddf] tabular-nums opacity-0 transition-opacity group-hover:opacity-100">
- {formatBytes(sizeBytes)}
- </span>
- )}
- {onUse && (
- <button
- aria-label="Add to timeline"
- title="Add to timeline"
- 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 font's bottom edge is its footer, so its + takes the corner
- // the name used to sit in.
- a.type === "audio"
- ? "right-1.5 bottom-1.5"
- : font
- ? "top-1.5 left-1.5"
- : "bottom-1.5 left-1.5",
- )}
- onClick={(e) => {
- e.stopPropagation();
- onUse();
- }}
- >
- <Plus className="size-3.5" />
- </button>
- )}
- {bothShelves && (
- <ShelfBadge
- residency={a.residency}
- offline={offline}
- className={cn(
- "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",
- )}
- />
- )}
- <DropdownMenu>
- <DropdownMenuTrigger
- aria-label="More actions"
- title="More actions"
- className={cn(
- "absolute top-1.5 right-1.5 grid size-6 place-items-center rounded-full text-white opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100",
- // A black scrim disappears into the charcoal sheet.
- font
- ? "bg-white/10 hover:bg-white/20"
- : "bg-black/40 hover:bg-black/60",
- )}
- onClick={(e) => e.stopPropagation()}
- >
- <Ellipsis className="size-3.5" />
- </DropdownMenuTrigger>
- <DropdownMenuContent
- // Hung off the card's right edge rather than laid over the media:
- // the tile stays readable behind the open menu.
- align="start"
- alignOffset={4}
- className="w-44"
- onClick={(e) => e.stopPropagation()}
- >
- {onShare && <DropdownMenuItem disabled={offline} onClick={onShare}><Share2 /> Share</DropdownMenuItem>}
- <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")
- }
- >
- <ExternalLink /> Open original
- </DropdownMenuItem>
- )}
- {onDelete && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem variant="destructive" onClick={onDelete}>
- <Trash2 /> Delete
- </DropdownMenuItem>
- </>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
- {!font && (
- <CopyNameLabel
- name={a.name}
- label={a.title}
- dark={a.type === "audio"}
- mention={mention}
- 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",
- )}
- />
- )}
- </div>
- {caption && (
- <div data-drag-omit className="mt-2 px-0.5 text-xs text-muted-foreground">
- {caption}
- </div>
- )}
- </>
- )}
- </MediaCardShell>
- );
-}
diff --git a/site/src/cut/components/Lightbox.tsx b/site/src/cut/components/Lightbox.tsx
index 85681326..757b1067 100644
--- a/site/src/cut/components/Lightbox.tsx
+++ b/site/src/cut/components/Lightbox.tsx
@@ -374,6 +374,7 @@ function FontBody({ item }: { item: LightboxItem }) {
>
<FontSpecimen
assetId={item.libraryId ?? ""}
+ src={!item.libraryId ? item.src : undefined}
poster={item.poster}
lines={SPECIMEN_ALPHABET}
pad={0}
diff --git a/site/src/cut/components/SharedLibraryView.tsx b/site/src/cut/components/SharedLibraryView.tsx
index 7811a402..d6c5ed38 100644
--- a/site/src/cut/components/SharedLibraryView.tsx
+++ b/site/src/cut/components/SharedLibraryView.tsx
@@ -2,34 +2,24 @@
import Link from "next/link";
import { useParams, useSearchParams } from "next/navigation";
-import { Download, Folder, Loader2, Type } from "lucide-react";
+import { Download, Folder, Loader2 } from "lucide-react";
import { buttonVariants } from "@/components/ui/button";
import { useSharedLibrary } from "@/queries/sharing";
import { ApiError } from "@/queries/apiClient";
import { librarySharePath, type SharedLibraryAsset } from "@/cut/lib/librarySharing";
import { authHrefFor } from "@/app/_components/landing/useAppEntryHref";
-import { useInView } from "@/cut/hooks/useInView";
+import { LibraryCard, LIBRARY_TILE_AREA, LIBRARY_AUDIO_TILE_AREA } from "@/cut/components/LibraryCard";
+import { Lightbox } from "@/cut/components/Lightbox";
import { useCutBase } from "@/cut/lib/nav";
function Asset({ asset, token }: { asset: SharedLibraryAsset; token: string }) {
- const [ref, visible] = useInView<HTMLDivElement>();
const src = `/api/cut-shared/library/${encodeURIComponent(token)}/media/${encodeURIComponent(asset.id)}`;
- return <div ref={ref} className="overflow-hidden rounded-xl border bg-background">
- <div className="grid aspect-video place-items-center bg-muted">
- {visible && (asset.type === "video"
- ? <video aria-label={asset.name} controls playsInline preload="metadata" src={src} className="size-full object-contain" />
- : asset.type === "audio"
- ? <audio aria-label={asset.name} controls preload="none" src={src} className="w-full px-3" />
- : asset.type === "image"
- // eslint-disable-next-line @next/next/no-img-element -- Protected media resolves through the share access check.
- ? <img alt={asset.name} src={src} loading="lazy" className="size-full object-contain" />
- : <Type className="size-8 text-muted-foreground" />)}
- </div>
- <div className="flex items-center justify-between gap-3 p-3">
- <span className="truncate text-sm font-medium" title={asset.name}>{asset.name}</span>
- <a href={`${src}?download=1`} aria-label={`Download ${asset.name}`} className={buttonVariants({ variant: "ghost", size: "icon" })}><Download className="size-4" /></a>
- </div>
- </div>;
+ const poster = asset.hasPoster ? `${src}?poster=1` : undefined;
+ return <LibraryCard
+ asset={{ ...asset, addedAt: 0, residency: "cloud" }}
+ area={asset.type === "audio" ? LIBRARY_AUDIO_TILE_AREA : LIBRARY_TILE_AREA}
+ sharedMedia={{ src, poster, downloadHref: `${src}?download=1` }}
+ />;
}
export function SharedLibraryView() {
@@ -49,7 +39,7 @@ export function SharedLibraryView() {
};
const data = query.data;
const status = query.error instanceof ApiError ? query.error.status : 0;
- return <main className="app-surface min-h-dvh bg-background font-system text-foreground">
+ return <main className="app-surface min-h-dvh min-w-0 bg-background font-system text-foreground">
<div className="mx-auto max-w-6xl px-5 py-9 sm:px-10">
<header className="mb-8 flex items-center justify-between gap-4">
<Link href={base} className="text-lg font-semibold">Donkey Cut</Link>
@@ -73,7 +63,7 @@ export function SharedLibraryView() {
<Folder className="size-10 fill-[#8cc5ff] text-[#8cc5ff]" /><span className="line-clamp-2 text-xs font-medium">{f.name}</span>
</Link>)}
</div>}
- <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
+ <div className="flex flex-wrap items-start gap-4">
{data.assets.map((asset) => <Asset key={asset.id} asset={asset} token={token} />)}
</div>
{data.templates.map((t) => <section key={t.id} className="mt-5 rounded-xl border p-4">
@@ -88,5 +78,6 @@ export function SharedLibraryView() {
</nav>
</>}
</div>
+ <Lightbox />
</main>;
}
diff --git a/site/src/cut/components/ShelfBadge.tsx b/site/src/cut/components/ShelfBadge.tsx
new file mode 100644
index 00000000..d65e5153
--- /dev/null
+++ b/site/src/cut/components/ShelfBadge.tsx
@@ -0,0 +1,29 @@
+import { Cloud, Laptop } from "lucide-react";
+import { RESIDENCY_LABEL, type Residency } from "@/cut/lib/residency";
+
+/** Which shelf an item sits on, on its card. The library merges both, so the
+ * badge is how you tell a clip on this Mac from one in the cloud — and, when
+ * the app isn't answering, why that clip is showing but not usable. */
+export function ShelfBadge({
+ residency,
+ offline = false,
+ className,
+}: {
+ residency: Residency;
+ offline?: boolean;
+ className?: string;
+}) {
+ const Icon = residency === "cloud" ? Cloud : Laptop;
+ return (
+ <span
+ title={
+ offline
+ ? "Local — open the Donkey app to use it"
+ : RESIDENCY_LABEL[residency]
+ }
+ className={className}
+ >
+ <Icon className="size-3" />
+ </span>
+ );
+}
diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsx
index a0e4dd8a..c2418f1a 100644
--- a/site/src/cut/components/SidePanel.tsx
+++ b/site/src/cut/components/SidePanel.tsx
@@ -136,7 +136,8 @@ import { StockVideosPanel } from "./StockVideosPanel";
import { STOCK_MUSIC } from "@/cut/lib/stockMusicManifest";
import { STOCK_SFX } from "@/cut/lib/stockSfxManifest";
import { STOCK_VIDEOS } from "@/cut/lib/stockVideoManifest";
-import { LibraryCard, ShelfBadge } from "./LibraryView";
+import { LibraryCard } from "@/cut/components/LibraryCard";
+import { ShelfBadge } from "@/cut/components/ShelfBadge";
import { MediaCardShell } from "./MediaCardShell";
import { lightboxItemFromAsset } from "@/cut/lib/lightbox";
import { PICKED_RING } from "@/cut/lib/assetPick";
diff --git a/site/src/cut/lib/librarySharing.ts b/site/src/cut/lib/librarySharing.ts
index c87a0e94..64a85fd1 100644
--- a/site/src/cut/lib/librarySharing.ts
+++ b/site/src/cut/lib/librarySharing.ts
@@ -22,6 +22,9 @@ export type SharedLibraryAsset = {
type: "video" | "audio" | "image" | "font";
duration: number;
fileName: string;
+ width?: number;
+ height?: number;
+ hasPoster?: boolean;
};
export type SharedLibraryPage = {
name: string;
diff --git a/site/src/cut/server/cloud/librarySharing.test.ts b/site/src/cut/server/cloud/librarySharing.test.ts
index 0df1a06b..73b066d8 100644
--- a/site/src/cut/server/cloud/librarySharing.test.ts
+++ b/site/src/cut/server/cloud/librarySharing.test.ts
@@ -134,4 +134,38 @@ describe("library sharing", () => {
expect((await api.media(request(), token, "asset")).status).toBe(404);
});
+ test("shared cards receive dimensions and poster availability without private metadata", async () => {
+ const { api, db } = harness();
+ const meta = { ...asset.meta, width: 1920, height: 1080, posterFile: "private-cover.jpg", source: { url: "https://private.test" } };
+ db.cutLibraryAsset.findMany.mockResolvedValue([{ ...asset, meta }]);
+ const body = await (await api.list(request(), token)).json();
+ expect(body.assets[0]).toMatchObject({ width: 1920, height: 1080, hasPoster: true });
+ expect(JSON.stringify(body)).not.toContain("private");
+ });
+
+ test("poster requests resolve only the asset's stored poster in the owner's library", async () => {
+ const { api, db, sign } = harness();
+ const meta = { ...asset.meta, posterFile: "cover.jpg" };
+ db.cutLibraryAsset.findFirst.mockResolvedValue({ ...asset, meta });
+ db.cutMediaObject.findFirst.mockResolvedValue({ id: "poster", fileName: "cover.jpg", r2Key: "cut/owner/library/cover.jpg", updatedAt: now });
+ const response = await api.media(new Request(`${request().url}?poster=1&file=unrelated.jpg`), token, "asset");
+ expect(response.status).toBe(302);
+ expect(db.cutMediaObject.findFirst.mock.calls[0][0]).toEqual({ where: { userId: "owner", kind: "library", uploadState: "complete", fileName: "cover.jpg" } });
+ expect(sign.mock.calls[0]).toEqual(["cut/owner/library/cover.jpg", { version: String(now.getTime()) }]);
+ });
+
+ test("posters keep share access and folder boundaries", async () => {
+ const req = new Request(`${request().url}?poster=1`);
+ for (const scenario of ["missing", "moved", "restricted", "revoked"] as const) {
+ const { api, db, sign } = harness();
+ const meta = { ...asset.meta, posterFile: "cover.jpg" };
+ if (scenario === "moved") db.cutLibraryAsset.findFirst.mockResolvedValue({ ...asset, meta, folderId: "sibling" });
+ if (scenario === "restricted") db.cutLibraryShare.findUnique.mockResolvedValue({ ...share, access: "restricted" });
+ if (scenario === "revoked") db.cutLibraryShare.findUnique.mockResolvedValue(null);
+ expect((await api.media(req, token, "asset")).status).toBe(scenario === "restricted" ? 401 : 404);
+ expect(sign).not.toHaveBeenCalled();
+ expect(db.cutMediaObject.findFirst).not.toHaveBeenCalled();
+ }
+ });
+
});
diff --git a/site/src/cut/server/cloud/librarySharing.ts b/site/src/cut/server/cloud/librarySharing.ts
index b570c634..84bea4a9 100644
--- a/site/src/cut/server/cloud/librarySharing.ts
+++ b/site/src/cut/server/cloud/librarySharing.ts
@@ -98,7 +98,10 @@ export function createLibrarySharing(
const object = byId.get(a.mediaObjectId);
if (!object) return [];
const v = assetView(a, object);
- return [{ id: v.id, name: v.title || v.name, fileName: v.fileName, type: v.type, duration: v.duration }];
+ return [{ id: v.id, name: v.title || v.name, fileName: v.fileName, type: v.type, duration: v.duration,
+ ...(v.width && v.height ? { width: v.width, height: v.height } : {}),
+ ...(v.posterFile ? { hasPoster: true } : {}),
+ }];
});
const body: SharedLibraryPage = {
name: trail[0]?.name ?? publicAssets[0]?.name ?? "Shared asset",
@@ -121,13 +124,14 @@ export function createLibrarySharing(
template: z.string().min(1).max(128).optional(),
file: z.string().min(1).max(512).optional(),
download: z.enum(["1"]).optional(),
+ poster: z.enum(["1"]).optional(),
}).safeParse(Object.fromEntries(new URL(req.url).searchParams));
if (!query.success) return err("Invalid media request.", 400);
let folderId: string | null;
let fileName: string;
let mediaObjectId: string | undefined;
if (query.data.template) {
- if (target.kind !== "folder" || query.data.template !== assetId) return err("Not found.", 404);
+ if (query.data.poster || target.kind !== "folder" || query.data.template !== assetId) return err("Not found.", 404);
const row = await db.cutTemplate.findFirst({ where: { id: assetId, userId: share.userId } });
if (!row) return err("Not found.", 404);
const template = templateView(row);
@@ -142,8 +146,14 @@ export function createLibrarySharing(
});
if (!row) return err("Not found.", 404);
folderId = row.folderId;
- mediaObjectId = row.mediaObjectId;
- fileName = "";
+ if (query.data.poster) {
+ const posterFile = assetView(row, { fileName: "" }).posterFile;
+ if (!posterFile) return err("Not found.", 404);
+ fileName = posterFile;
+ } else {
+ mediaObjectId = row.mediaObjectId;
+ fileName = "";
+ }
}
if (target.kind === "folder") {
if (!folderId || !(await sharedFolderTrail(target.id, folderId, (id) =>
diff --git a/site/src/cut/server/http/library.ts b/site/src/cut/server/http/library.ts
index 0c162168..20c177aa 100644
--- a/site/src/cut/server/http/library.ts
+++ b/site/src/cut/server/http/library.ts
@@ -15,8 +15,8 @@ import {
updateFolder,
renameTemplate,
saveTemplate,
- useInProject,
- useTemplate,
+ copyLibraryAssetToProject,
+ copyTemplateToProject,
type LibrarySource,
type TemplateInput,
} from "../library";
@@ -74,7 +74,7 @@ export const libraryApi = {
async useTemplate(req: Request, { id }: { id: string }) {
try {
const { projectId } = (await req.json()) as { projectId: string };
- return Response.json(await useTemplate(id, projectId));
+ return Response.json(await copyTemplateToProject(id, projectId));
} catch (e) {
return caught(e, "Could not add the template.");
}
@@ -210,7 +210,7 @@ export const libraryApi = {
assetId: string;
projectId: string;
};
- const fileName = await useInProject(assetId, projectId);
+ const fileName = await copyLibraryAssetToProject(assetId, projectId);
return Response.json({ fileName });
} catch (e) {
return caught(e, "Could not add from library.");
diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.ts
index 300ca9d0..55409738 100644
--- a/site/src/cut/server/library.ts
+++ b/site/src/cut/server/library.ts
@@ -359,7 +359,7 @@ export async function addDownloaded(
/** Copy a library asset into a project's media folder. Returns the file name
* inside the project. */
-export async function useInProject(
+export async function copyLibraryAssetToProject(
assetId: string,
projectId: string,
): Promise<string> {
@@ -591,7 +591,7 @@ export async function saveTemplate(
/** Materialize a template into a project: copy its media in and hand the client
* the project file names (in template media order) plus the stored edit. */
-export async function useTemplate(templateId: string, projectId: string) {
+export async function copyTemplateToProject(templateId: string, projectId: string) {
if (!(await readProject(projectId))) throw new Error("Project not found.");
const idx = await readIndex();
const template = (idx.templates ?? []).find((x) => x.id === templateId);