The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Elements: clip elements show a still of their clip on cards and Cinema chips
Adarsh156a7e1bce4c
diff --git a/src/components/cinema/prompt-bar.tsx b/src/components/cinema/prompt-bar.tsxindex 4546e99e..cb341afa 100644--- a/src/components/cinema/prompt-bar.tsx+++ b/src/components/cinema/prompt-bar.tsx@@ -37,7 +37,8 @@ import {planCinema,type DirectorSettings,} from "@/lib/catalog/cinema";-import { applyMentions, findMentions, type StudioElement } from "@/lib/catalog/elements";+import { applyMentions, findMentions, isClipRef, type StudioElement } from "@/lib/catalog/elements";+import { ClipMark, ElementThumb } from "@/components/element-thumb";import { referenceWindow, trimLine, trimTarget, windowProblem, type ClipWindow } from "@/lib/av/reference-fit";import { ListFit } from "@/components/av/fit-list";import { ElementClipFix, useElementClipCheck } from "@/components/av/element-clip-fit";@@ -790,16 +791,22 @@ export function PromptBar(props: PromptBarProps) {{mentions.map((el) => {const Icon = ELEMENT_ICONS[el.kind];const emo = settings.emotions?.[el.handle.toLowerCase()];+ const face = (+ <span className="grid size-6 place-items-center overflow-hidden rounded-full bg-muted">+ {el.references[0] ? <ElementThumb src={el.references[0]} mark="none" className="size-full object-cover" /> : <Icon className="size-3.5" />}+ </span>+ );return (<span key={el.id} className="inline-flex h-7 items-center gap-1.5 rounded-full border bg-background pr-2.5 pl-0.5 text-[12px] font-medium">- <span className="grid size-6 place-items-center overflow-hidden rounded-full bg-muted">- {el.references[0] ? (- // eslint-disable-next-line @next/next/no-img-element- <img src={el.references[0]} alt="" className="size-full object-cover" />- ) : (- <Icon className="size-3.5" />- )}- </span>+ {/* A clip element: a still of its clip, with the clip mark on the circle's edge. */}+ {el.references[0] && isClipRef(el.references[0]) ? (+ <span className="relative shrink-0">+ {face}+ <ClipMark size="xs" className="absolute -right-1 -bottom-0.5" />+ </span>+ ) : (+ face+ )}{el.name}{emo && <span className="text-[11px] text-muted-foreground">· {emo.family}</span>}</span>diff --git a/src/components/element-thumb.tsx b/src/components/element-thumb.tsxnew file mode 100644index 00000000..49038240--- /dev/null+++ b/src/components/element-thumb.tsx@@ -0,0 +1,130 @@+"use client";++import { Video } from "lucide-react";+import { useEffect, useState } from "react";+import { CLIP_FRAME_AT, frameSize, stillCache, thumbSource } from "@/lib/clip-thumb";+import { cn } from "@/lib/utils";++/** One frame of a clip, scaled down and kept as a JPEG object URL; null when this browser can't read the clip. */+async function grabStill(clip: string): Promise<string | null> {+ if (typeof document === "undefined") return null;+ const v = document.createElement("video");+ v.muted = true;+ v.playsInline = true;+ v.preload = "auto";+ const event = (name: string) =>+ new Promise<void>((resolve, reject) => {+ const t = setTimeout(() => reject(new Error("timeout")), 10000);+ v.addEventListener(name, () => (clearTimeout(t), resolve()), { once: true });+ v.addEventListener("error", () => (clearTimeout(t), reject(new Error("unreadable"))), { once: true });+ });+ try {+ const loaded = event("loadeddata");+ v.src = clip;+ await loaded;+ const at = Math.min(CLIP_FRAME_AT, Math.max(0, (v.duration || CLIP_FRAME_AT) - 0.05));+ if (Math.abs(v.currentTime - at) > 0.01) {+ const seeked = event("seeked");+ v.currentTime = at;+ await seeked;+ }+ const size = frameSize(v.videoWidth, v.videoHeight);+ if (!size.width) return null;+ const c = document.createElement("canvas");+ c.width = size.width;+ c.height = size.height;+ const ctx = c.getContext("2d");+ if (!ctx) return null;+ ctx.drawImage(v, 0, 0, size.width, size.height);+ const blob = await new Promise<Blob | null>((r) => c.toBlob(r, "image/jpeg", 0.85));+ return blob ? URL.createObjectURL(blob) : null;+ } catch {+ return null;+ } finally {+ v.removeAttribute("src");+ v.load();+ }+}++const stills = stillCache(grabStill);++/** The mark that says a thumbnail is a clip: a small camera on a dark disc. */+export function ClipMark({ className, size = "sm" }: { className?: string; size?: "xs" | "sm" }) {+ return (+ <span+ aria-hidden+ className={cn(+ "pointer-events-none grid place-items-center rounded-full bg-black/60 text-white shadow-sm ring-1 ring-white/25",+ size === "xs" ? "size-3.5" : "size-6 backdrop-blur-sm",+ className,+ )}+ >+ <Video className={size === "xs" ? "size-2" : "size-3.5"} strokeWidth={size === "xs" ? 2.75 : 2.25} />+ </span>+ );+}++/**+ * An element's reference drawn as a thumbnail. A photo is the same <img> as ever (`className` on it). A clip shows a still+ * of itself (its `poster` when one is known, else a frame grabbed in the browser), in a box that takes `className`, with+ * the clip mark in its corner (`mark="none"` leaves it to the caller, as a chip too small for it does). A clip that can't+ * be read shows the mark alone, never a broken image.+ */+export function ElementThumb({+ src,+ poster,+ alt = "",+ className,+ loading,+ mark = "corner",+}: {+ src: string;+ poster?: string | null;+ alt?: string;+ className?: string;+ loading?: "lazy" | "eager";+ mark?: "corner" | "none";+}) {+ const s = thumbSource(src, poster);+ if (s.kind === "image") {+ // eslint-disable-next-line @next/next/no-img-element+ return <img src={s.src} alt={alt} loading={loading} className={className} />;+ }+ return <ClipStill clip={s.clip} poster={s.poster} alt={alt} className={className} loading={loading} mark={mark} />;+}++function ClipStill({ clip, poster, alt, className, loading, mark }: { clip: string; poster?: string; alt: string; className?: string; loading?: "lazy" | "eager"; mark: "corner" | "none" }) {+ // The poster first; if it fails to load, a frame from the clip.+ const [posterFailed, setPosterFailed] = useState(false);+ const usePoster = !!poster && !posterFailed;+ // The grabbed still: known at once when this clip was grabbed before, else once its grab ends (null: can't be read).+ const [got, setGot] = useState<{ clip: string; still: string | null } | null>(null);+ const [broken, setBroken] = useState<string | null>(null);+ const known = stills.peek(clip);+ const still = broken === clip ? null : known !== undefined ? known : got?.clip === clip ? got.still : undefined;+ useEffect(() => {+ if (usePoster || stills.peek(clip) !== undefined) return;+ let gone = false;+ void stills.get(clip).then((s) => {+ if (!gone) setGot({ clip, still: s });+ });+ return () => {+ gone = true;+ };+ }, [clip, usePoster]);+ const shown = usePoster ? poster : still;+ return (+ <span className={cn("relative block overflow-hidden bg-muted", className)} role={alt ? "img" : undefined} aria-label={alt || undefined}>+ {shown && (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={shown} alt="" loading={loading} onError={usePoster ? () => setPosterFailed(true) : () => setBroken(clip)} className="absolute inset-0 size-full object-cover" />+ )}+ {!usePoster && still === null && (+ <span className="absolute inset-0 grid place-items-center text-muted-foreground">+ <Video className={mark === "corner" ? "size-7" : "size-3.5"} />+ </span>+ )}+ {mark === "corner" && (usePoster || still !== null) && <ClipMark className="absolute right-1.5 bottom-1.5" />}+ </span>+ );+}diff --git a/src/components/elements-view.tsx b/src/components/elements-view.tsxindex ecd6e546..a512f957 100644--- a/src/components/elements-view.tsx+++ b/src/components/elements-view.tsx@@ -38,7 +38,8 @@ import { SelfHostNote } from "@/components/self-host-note";import { useEdgeFade } from "@/components/studio/use-edge-fade";import { StarterSection, useStarters } from "@/components/starters/starter-section";import { useDeleteElement, useElements, useIsVisitor, useSaveElement } from "@/lib/api";-import { ELEMENT_KINDS, elementKindInfo, handleFor, MAX_ELEMENT_PHOTOS, type ElementKind, type StudioElement } from "@/lib/catalog/elements";+import { ELEMENT_KINDS, elementKindInfo, handleFor, isClipRef, MAX_ELEMENT_PHOTOS, type ElementKind, type StudioElement } from "@/lib/catalog/elements";+import { ElementThumb } from "@/components/element-thumb";import { isLegacySoulId, SOUL_ID_PHOTOS } from "@/lib/catalog/training";import { copyText } from "@/lib/clipboard";import { starterShown, type StarterCardData } from "@/lib/starters/types";@@ -168,7 +169,7 @@ function ElementForm({ onOpenChange, element, defaultKind = "character", onSavedconst [kind, setKind] = useState<ElementKind>(element?.kind ?? defaultKind);const [name, setName] = useState(element?.name ?? "");const [description, setDescription] = useState(element?.description ?? "");- const [photos, setPhotos] = useState<SlotValue[]>(() => (element?.references ?? []).map((r) => ({ id: nanoid(6), ref: r, preview: r, kind: /\.(mp4|mov|m4v|webm)(\?|#|$)/i.test(r) ? "video" : "image" })));+ const [photos, setPhotos] = useState<SlotValue[]>(() => (element?.references ?? []).map((r) => ({ id: nanoid(6), ref: r, preview: r, kind: isClipRef(r) ? "video" : "image" })));const uploading = photos.some((p) => p.uploading);const refs = photos.filter((p) => p.ref).map((p) => p.ref);@@ -363,11 +364,9 @@ function ElementCard({ el }: { el: StudioElement }) {<div className="grid aspect-square grid-cols-2 grid-rows-2 gap-0.5 bg-muted">{el.references.length ? (el.references.slice(0, 4).map((r, i, arr) => (- // eslint-disable-next-line @next/next/no-img-element- <img+ <ElementThumbkey={`${i}:${r}`}src={r}- alt=""className={cn("size-full object-cover",arr.length === 1 && "col-span-2 row-span-2",diff --git a/src/lib/catalog/elements.ts b/src/lib/catalog/elements.tsindex 6a7209ac..46851c36 100644--- a/src/lib/catalog/elements.ts+++ b/src/lib/catalog/elements.ts@@ -138,7 +138,7 @@ export interface MentionResolution {const ops = (m: ModelDef) => new Set(m.routes.map((r) => r.op));/** A reference that is a clip (a video element), by its file's extension. */-const isClipRef = (ref: string) => /\.(mp4|mov|m4v|webm)(\?|#|$)/i.test(ref);+export const isClipRef = (ref: string) => /\.(mp4|mov|m4v|webm)(\?|#|$)/i.test(ref);/** Element kinds a model's own elements stand for (Kling 4.0: "characters/objects"). */const ELEMENT_KINDS_AS_ELEMENTS = new Set<ElementKind>(["character", "prop"]);diff --git a/src/lib/clip-thumb.ts b/src/lib/clip-thumb.tsnew file mode 100644index 00000000..06988f29--- /dev/null+++ b/src/lib/clip-thumb.ts@@ -0,0 +1,68 @@+import { isClipRef } from "@/lib/catalog/elements";++/**+ * How a reference is drawn as a thumbnail (element cards, @mention chips): a photo as itself; a clip as a still of it, its+ * poster when one is known, else a frame grabbed from the clip in the browser. A clip is never handed to an <img>.+ */+export type ThumbSource = { kind: "image"; src: string } | { kind: "clip"; clip: string; poster?: string };++export function thumbSource(ref: string, poster?: string | null): ThumbSource {+ if (!isClipRef(ref)) return { kind: "image", src: ref };+ return poster && !isClipRef(poster) ? { kind: "clip", clip: ref, poster } : { kind: "clip", clip: ref };+}++/** Where in a clip its still is taken (seconds): just past the start, as the Video studio's chip shows it. */+export const CLIP_FRAME_AT = 0.1;++/** A grabbed still's longest side (px): sharp on a card at 2x, small enough to keep many in memory. */+export const CLIP_FRAME_SIDE = 640;++/** The size a still is drawn at: the clip's own, scaled down so its longest side is at most `max`. */+export function frameSize(width: number, height: number, max = CLIP_FRAME_SIDE): { width: number; height: number } {+ if (!(width > 0) || !(height > 0)) return { width: 0, height: 0 };+ const k = Math.min(1, max / Math.max(width, height));+ return { width: Math.max(1, Math.round(width * k)), height: Math.max(1, Math.round(height * k)) };+}++/**+ * Stills grabbed from clips: one grab per clip address for the page's life (a clip that can't be read stays null, so it+ * isn't tried again), and at most `limit` clips decoding at once, so a page of clip elements doesn't open them all together.+ */+export function stillCache(grab: (clip: string) => Promise<string | null>, limit = 2) {+ const done = new Map<string, string | null>();+ const pending = new Map<string, Promise<string | null>>();+ const waiting: (() => void)[] = [];+ let running = 0;+ const next = () => {+ if (running >= limit) return;+ const go = waiting.shift();+ if (go) go();+ };+ return {+ /** The still if it is ready (a string), null if the clip can't be read, undefined while it isn't known yet. */+ peek: (clip: string): string | null | undefined => done.get(clip),+ get(clip: string): Promise<string | null> {+ if (done.has(clip)) return Promise.resolve(done.get(clip)!);+ const had = pending.get(clip);+ if (had) return had;+ const p = new Promise<string | null>((resolve) => {+ waiting.push(() => {+ running++;+ Promise.resolve()+ .then(() => grab(clip))+ .catch(() => null)+ .then((still) => {+ done.set(clip, still);+ pending.delete(clip);+ running--;+ resolve(still);+ next();+ });+ });+ });+ pending.set(clip, p);+ next();+ return p;+ },+ };+}diff --git a/tests/clip-thumb.test.ts b/tests/clip-thumb.test.tsnew file mode 100644index 00000000..67542129--- /dev/null+++ b/tests/clip-thumb.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from "vitest";+import { frameSize, stillCache, thumbSource } from "@/lib/clip-thumb";++describe("thumbSource", () => {+ it("draws a photo as itself", () => {+ expect(thumbSource("/api/files/abc.png")).toEqual({ kind: "image", src: "/api/files/abc.png" });+ expect(thumbSource("/api/files/abc.jpg?v=2")).toEqual({ kind: "image", src: "/api/files/abc.jpg?v=2" });+ // A poster is ignored for a photo.+ expect(thumbSource("/api/files/abc.webp", "/api/files/other.jpg")).toEqual({ kind: "image", src: "/api/files/abc.webp" });+ });++ it("never hands a clip to an image: its poster when known, else a still to grab", () => {+ for (const clip of ["/api/files/a.mp4", "/api/files/a.MOV", "/x/a.m4v?t=1", "/x/a.webm#t=0.1"]) {+ expect(thumbSource(clip)).toEqual({ kind: "clip", clip });+ expect(thumbSource(clip, null)).toEqual({ kind: "clip", clip });+ }+ expect(thumbSource("/api/files/a.mp4", "/api/files/a-poster.jpg")).toEqual({ kind: "clip", clip: "/api/files/a.mp4", poster: "/api/files/a-poster.jpg" });+ // A "poster" that is itself a clip is not used as one.+ expect(thumbSource("/api/files/a.mp4", "/api/files/b.mp4")).toEqual({ kind: "clip", clip: "/api/files/a.mp4" });+ });+});++describe("frameSize", () => {+ it("scales the longest side down to the limit and keeps the shape", () => {+ expect(frameSize(1920, 1080, 640)).toEqual({ width: 640, height: 360 });+ expect(frameSize(720, 1280, 640)).toEqual({ width: 360, height: 640 });+ expect(frameSize(320, 240, 640)).toEqual({ width: 320, height: 240 });+ expect(frameSize(0, 1080)).toEqual({ width: 0, height: 0 });+ expect(frameSize(NaN, NaN)).toEqual({ width: 0, height: 0 });+ });+});++describe("stillCache", () => {+ it("grabs each clip once, keeps a clip that can't be read as null, and decodes at most `limit` at once", async () => {+ let running = 0;+ let most = 0;+ const calls: string[] = [];+ const grab = async (clip: string) => {+ calls.push(clip);+ running++;+ most = Math.max(most, running);+ await new Promise((r) => setTimeout(r, 5));+ running--;+ if (clip.includes("bad")) throw new Error("unreadable");+ return clip.includes("none") ? null : `blob:${clip}`;+ };+ const cache = stillCache(grab, 2);+ expect(cache.peek("/a.mp4")).toBeUndefined();+ const all = await Promise.all(["/a.mp4", "/b.mp4", "/a.mp4", "/bad.mp4", "/none.mp4", "/c.mp4"].map((c) => cache.get(c)));+ expect(all).toEqual(["blob:/a.mp4", "blob:/b.mp4", "blob:/a.mp4", null, null, "blob:/c.mp4"]);+ expect(calls.sort()).toEqual(["/a.mp4", "/b.mp4", "/bad.mp4", "/c.mp4", "/none.mp4"]);+ expect(most).toBe(2);+ // Known now: no second grab.+ expect(cache.peek("/a.mp4")).toBe("blob:/a.mp4");+ expect(cache.peek("/bad.mp4")).toBeNull();+ await cache.get("/bad.mp4");+ expect(calls).toHaveLength(5);+ });+});