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
Nav menus: every card comes alive on hover
Adarshb5eb48ec9ec8
diff --git a/src/components/nav/cover-thumb.tsx b/src/components/nav/cover-thumb.tsxindex 5e4fcc41..3ff45cc8 100644--- a/src/components/nav/cover-thumb.tsx+++ b/src/components/nav/cover-thumb.tsx@@ -1,12 +1,133 @@"use client";-import { createElement } from "react";+import { createElement, useEffect, useLayoutEffect, useRef, useState } from "react";+import { releaseVideo } from "@/lib/media-release";import { navIcon } from "@/lib/nav-icons";import type { MegaCover } from "@/lib/mega-menus";import type { NavIconName } from "@/lib/nav-model";+import { reducedMotion } from "@/lib/ui-motion";import { cn } from "@/lib/utils";import { useNavCover } from "./nav-ui";+/** The end of a cover clip a loop from inside it never shows (s): where an effect fades back to its photo. */+const CLIP_TAIL = 0.4;+/** How long a clip takes to fade over its still, and back (ms; the class below says the same). */+const CLIP_FADE = 200;++/** How long a mouse stays on a card before it comes alive (ms). */+const ALIVE_AFTER = 120;++/** The one cover clip playing (a menu plays only the card under the pointer: one decoder at a time). */+let playingClip: HTMLVideoElement | null = null;++/** Clips play on hover unless the viewer asks for less motion or to save data. */+function clipsAllowed(): boolean {+ if (reducedMotion()) return false;+ const conn = (navigator as Navigator & { connection?: { saveData?: boolean } }).connection;+ return !conn?.saveData;+}++/**+ * A menu card that comes alive while a mouse is over it or the keys focus it (never on a tap: a touch screen keeps its+ * stills): `alive` goes to its CoverThumb, `handlers` on the card's link.+ */+export function useAliveCard() {+ const [alive, setAlive] = useState(false);+ const timer = useRef(0);+ useEffect(() => () => window.clearTimeout(timer.current), []);+ // A pointer that stays a moment (ALIVE_AFTER): one passing over on its way elsewhere starts nothing.+ const on = (delay: number) => {+ window.clearTimeout(timer.current);+ timer.current = window.setTimeout(() => setAlive(true), delay);+ };+ const off = () => {+ window.clearTimeout(timer.current);+ setAlive(false);+ };+ return {+ alive,+ handlers: {+ onPointerEnter: (e: React.PointerEvent) => e.pointerType === "mouse" && on(ALIVE_AFTER),+ onPointerLeave: (e: React.PointerEvent) => e.pointerType === "mouse" && off(),+ onFocus: (e: React.FocusEvent<HTMLElement>) => e.currentTarget.matches(":focus-visible") && on(0),+ onBlur: off,+ },+ };+}++/**+ * A cover's clip over its still: it shows once its first frame is drawn (so the still stays until then: never a blank+ * frame) and fades in; `leaving`, it fades back out to the still. `at`: a still from inside the clip (a template's+ * peak frame), where it starts and loops back to, short of the clip's last stretch.+ */+function CoverClip({ src, at, leaving, focus }: { src: string; at?: number; leaving: boolean; focus?: string }) {+ const ref = useRef<HTMLVideoElement>(null);+ const [drawn, setDrawn] = useState(false);+ useLayoutEffect(() => {+ const v = ref.current;+ if (!v) return;+ if (playingClip && playingClip !== v) playingClip.pause();+ playingClip = v;+ let live = true;+ let from = 0;+ const seek = () => {+ if (at !== undefined && v.duration && at < v.duration - CLIP_TAIL - 0.3) {+ from = at;+ v.currentTime = at;+ }+ };+ // Shown once a frame is on screen; a loop from inside the clip comes back before its tail.+ const frame = () => {+ if (!live) return;+ setDrawn(true);+ if (from && v.duration && v.currentTime >= v.duration - CLIP_TAIL) v.currentTime = from;+ if ("requestVideoFrameCallback" in v) v.requestVideoFrameCallback(frame);+ };+ const playing = () => ("requestVideoFrameCallback" in v ? v.requestVideoFrameCallback(frame) : frame());+ const tail = () => {+ if (from && v.duration && v.currentTime >= v.duration - CLIP_TAIL) v.currentTime = from;+ };+ v.addEventListener("loadedmetadata", seek, { once: true });+ v.addEventListener("playing", playing, { once: true });+ v.addEventListener("timeupdate", tail);+ v.src = src;+ void v.play().catch(() => {});+ return () => {+ live = false;+ v.removeEventListener("timeupdate", tail);+ if (playingClip === v) playingClip = null;+ releaseVideo(v);+ };+ }, [src, at]);+ return (+ <video+ ref={ref}+ muted+ playsInline+ loop={at === undefined}+ preload="auto"+ aria-hidden+ tabIndex={-1}+ data-cover-clip=""+ data-on={drawn && !leaving ? "" : undefined}+ className="absolute inset-0 size-full object-cover opacity-0 transition-opacity duration-200 ease-out data-[on]:opacity-100"+ style={{ objectPosition: focus ?? "50% 25%" }}+ />+ );+}++/** Mounted while `on`, and for the fade after it (`leaving`): a clip fades back to its still, then lets go of its decoder. */+function useClipPresence(on: boolean): { mounted: boolean; leaving: boolean } {+ const [mounted, setMounted] = useState(on);+ if (on && !mounted) setMounted(true);+ useEffect(() => {+ if (on || !mounted) return;+ const t = window.setTimeout(() => setMounted(false), CLIP_FADE + 40);+ return () => window.clearTimeout(t);+ }, [on, mounted]);+ return { mounted, leaving: mounted && !on };+}+/** A nav cover: a real preset still in a box of fixed size, so nothing moves when the picture arrives. The box shows* the muted fill until then (and the entry's icon when the preset has no cover). Covers are decoration next to a@@ -59,6 +180,7 @@ export function CoverThumb({icon,eager,low,+ alive,sizes: boxSizes,className,}: {@@ -73,6 +195,11 @@ export function CoverThumb({eager?: boolean;/** Load after the pictures around it (a menu's small row pictures, after its lead covers). */low?: boolean;+ /**+ * Its card is pointed at or focused (useAliveCard): its clip plays over the still, where it has one; else the still+ * leans in a little. Neither under reduced motion; no clip when saving data.+ */+ alive?: boolean;/** A fluid box's width for the srcset, when it isn't its size's usual one (a lead card two tracks wide, a phone's tile). */sizes?: string;className?: string;@@ -87,6 +214,11 @@ export function CoverThumb({const hd = sizes ? cover?.hd : undefined;// How the cover sits in a box of another shape (cover-framing.ts): a square keeps its top part by default, where faces are.const whole = cover?.framing?.fit === "whole";+ const [allowed] = useState(() => typeof window !== "undefined" && clipsAllowed());+ // A fetched menu's cover names its clip; a Studios lead's nav cover gives its version (nav-covers.ts).+ const clip = !allowed ? undefined : (cover?.clip ?? (id && nav?.clipV ? `/previews/presets/${id}.mp4?v=${nav.clipV}` : undefined));+ const { mounted, leaving } = useClipPresence(!!alive && !!clip);+ const clipEl = clip && mounted && <CoverClip src={clip} at={cover?.clipAt} leaving={leaving} focus={cover?.framing?.focus} />;const still = cover && (// eslint-disable-next-line @next/next/no-img-element -- versioned static covers, sized by the box (no optimizer round trip)<img@@ -100,7 +232,7 @@ export function CoverThumb({fetchPriority={low ? "low" : undefined}decoding="async"draggable={false}- className="absolute inset-0 size-full object-cover"+ className="absolute inset-0 size-full object-cover motion-safe:transition-[scale] motion-safe:duration-700 motion-safe:ease-out motion-safe:group-data-[alive=lean]/cover:scale-[1.045]"style={{ objectPosition: cover.framing?.focus ?? "50% 25%" }}/>);@@ -113,17 +245,28 @@ export function CoverThumb({still);return (- <span aria-hidden data-cover={cover ? (id ?? "") : undefined} className={cn("relative block shrink-0 overflow-hidden bg-muted", s.box, className)}>+ <span+ aria-hidden+ data-cover={cover ? (id ?? "") : undefined}+ data-alive={alive && cover ? (clip ? "clip" : "lean") : undefined}+ className={cn("group/cover relative block shrink-0 overflow-hidden bg-muted", s.box, className)}+ >{cover && whole ? (<>{/* eslint-disable-next-line @next/next/no-img-element -- the same small copy, blurred behind the whole picture */}<img src={small} alt="" loading={eager ? "eager" : "lazy"} decoding="async" draggable={false} className="absolute inset-0 size-full scale-125 object-cover blur-md brightness-[0.7] saturate-[1.3]" /><span className="absolute inset-0 grid place-items-center [container-type:size]">- <span className="relative aspect-[4/3] w-[min(100cqw,133.334cqh)] overflow-hidden">{img}</span>+ <span className="relative aspect-[4/3] w-[min(100cqw,133.334cqh)] overflow-hidden">+ {img}+ {clipEl}+ </span></span></>) : cover ? (- img+ <>+ {img}+ {clipEl}+ </>) : icon ? (<NavIcon name={icon} className="absolute inset-0 m-auto size-[42%] max-h-6 max-w-6 text-muted-foreground" />) : null}diff --git a/src/components/nav/mega-panel.tsx b/src/components/nav/mega-panel.tsxindex ab403cdf..58fe3a05 100644--- a/src/components/nav/mega-panel.tsx+++ b/src/components/nav/mega-panel.tsx@@ -9,7 +9,7 @@ import { MEGA_AREAS, ROW_CAPS, studiosMenu, TILE_COLS, type MegaColumn, type Megimport { isNew, subParent, type ViewerKind } from "@/lib/nav-model";import { cn } from "@/lib/utils";import { FxCompare } from "@/components/fx/fx-compare";-import { COVER_SIZES, CoverThumb } from "./cover-thumb";+import { COVER_SIZES, CoverThumb, useAliveCard } from "./cover-thumb";import { useMegaMenu } from "./mega-data";import { megaCurrent, MegaSkeleton } from "./mega-launcher";import { useViewerKind } from "./nav-ui";@@ -63,8 +63,11 @@ const LEAD_MAX_BELOW = "max-h-[round(down,max(64px,calc(100dvh_-_640px)),4px)]";* the tracks its column takes, when more than one (Canvas' Start here), for its picture's srcset.*/export function LeadCard({ e, col, row = 0, span = 1, current, inside, now, className }: { e: MegaItem; col: number; row?: number; span?: number; current: boolean; inside?: boolean; now: number; className?: string }) {+ // Pointed at or focused, its cover comes alive (its clip, or a lean in); a Fuobe FX card shows its before and after.+ const { alive, handlers } = useAliveCard();return (<IntentLink+ {...(e.fx ? {} : handlers)}href={e.href}data-col={col}data-row={row}@@ -82,6 +85,7 @@ export function LeadCard({ e, col, row = 0, span = 1, current, inside, now, classize="lead"icon={e.icon}eager+ alive={alive}sizes={span > 1 ? trackSizes(span, 2) : undefined}className={cn(LEAD_BOX, row ? LEAD_MAX_BELOW : LEAD_MAX)}/>@@ -201,8 +205,10 @@ function SubLinks({ e, col, row, current, under }: { e: MegaItem; col: number; r* load with the panel; a later row's when it shows (lazy: a row hidden by the window's height never fetches its own).*/function Tile({ e, col, row, current, eager }: { e: MegaItem; col: number; row: number; current: boolean; eager: boolean }) {+ const { alive, handlers } = useAliveCard();return (<IntentLink+ {...handlers}href={e.href}data-col={col}data-row={row}@@ -211,7 +217,7 @@ function Tile({ e, col, row, current, eager }: { e: MegaItem; col: number; row:className="nav-row nav-mark-under -m-1.5 flex min-w-0 flex-col gap-1.5 rounded-[12px] p-1.5 [container-type:inline-size]">{/* 16:9, its height rounded down to the 4 px grid, so a second row of tiles sits on a whole pixel. */}- <CoverThumb cover={e.cover} size="tile16" icon={e.icon} eager={eager} sizes={trackSizes(1)} className="aspect-auto h-[round(down,56.25cqw,4px)]" />+ <CoverThumb cover={e.cover} size="tile16" icon={e.icon} eager={eager} alive={alive} sizes={trackSizes(1)} className="aspect-auto h-[round(down,56.25cqw,4px)]" /><span className="flex min-w-0 flex-col"><span className={cn("truncate text-[13px] leading-[18px] font-medium", current && "font-semibold")}>{e.label}</span><span className="truncate text-[12px] leading-4 text-muted-foreground">{e.line}</span>diff --git a/src/lib/mega-menus.server.ts b/src/lib/mega-menus.server.tsindex 1f442a9e..214bbad3 100644--- a/src/lib/mega-menus.server.ts+++ b/src/lib/mega-menus.server.ts@@ -126,6 +126,12 @@ export const hasOwnCover = (id: string) => !!presetCover(id)?.poster.startsWith(const presetItem = (p: Preset): MegaItem => ({ id: p.id, href: presetHref(p.id), label: p.name, line: presetLine(p), cover: presetMegaCover(p.id) });+/** A lead card's item with its cover's clip, which plays over the still while the card is pointed at (rows show none). */+function withClip(e: MegaItem): MegaItem {+ const clip = e.cover && presetCover(e.id)?.video;+ return clip ? { ...e, cover: { ...e.cover!, clip } } : e;+}+/*** One column per group: its presets premium first (featuredAll), one of each idea (sameIdea), the first with its own* cover as the lead, then up to ROW_CAPS.tall rows (each with its cover). Columns in the order of their strongest preset.@@ -151,7 +157,7 @@ export function presetColumns(items: readonly Preset[], groups: readonly PresetGlabel: g.label,chip: g.chip,...(family && { family }),- ...(lead && { lead: presetItem(lead) }),+ ...(lead && { lead: withClip(presetItem(lead)) }),rows: rest.slice(0, ROW_CAPS.tall).map(presetItem),};});@@ -185,15 +191,16 @@ export function motionsMenu(): MegaModel {const VISITOR: Viewing = { visitor: true, hasCover: (id) => !!templateCover("canvas", id) };/**- * A template cover as a menu tile shows it: its peak frame (the finished scene), never a clip, with its larger copies- * (the preset's peak frame's, or the tile's own poster's), so a 2x or 3x screen gets one at least as wide as the box.+ * A template cover as a menu tile shows it: its peak frame (the finished scene), with its larger copies (the preset's+ * peak frame's, or the tile's own poster's), so a 2x or 3x screen gets one at least as wide as the box, and its clip+ * from that frame on (clipAt), which plays while the tile is pointed at.*/function templateMegaCover(id: string): MegaCover | undefined {const c = templateCover("canvas", id);if (!c) return undefined;const framing = coverFraming(c.poster);const hd = presetStillSources(c.poster, c.thumb) ?? templateStillSources(c.poster, c.thumb);- return { poster: c.poster, thumb: c.thumb, ...(hd && { hd }), ...(framing && { framing }) };+ return { poster: c.poster, thumb: c.thumb, ...(hd && { hd }), ...(framing && { framing }), ...(c.video && { clip: c.video, ...(c.at !== undefined && { clipAt: c.at }) }) };}/**diff --git a/src/lib/mega-menus.ts b/src/lib/mega-menus.tsindex f8578d47..6371713c 100644--- a/src/lib/mega-menus.ts+++ b/src/lib/mega-menus.ts@@ -35,6 +35,10 @@ export interface MegaCover {hd?: StillSources;/** How it sits in a box of another shape (cover-framing.ts). */framing?: CoverFraming;+ /** Its short muted clip, played over the still while a lead card or tile is pointed at or focused. */+ clip?: string;+ /** Where the clip starts and loops back to (s), when the still is a frame from inside it (a template's peak). */+ clipAt?: number;}export interface MegaItem {@@ -255,16 +259,18 @@ function packItem(e: MegaItem): WireItem {const { href, cover, ...rest } = e;const v = cover && /^\/previews\/presets\/([^/]+)\.jpg\?v=([0-9a-f]{8})$/.exec(cover.poster);const usual = v && v[1] === e.id && JSON.stringify({ ...presetUrls(e.id, v[2]) }) === JSON.stringify({ poster: cover!.poster, thumb: cover!.thumb, mini: cover!.mini });+ // The usual cover goes by its version, with what its URLs don't say (its framing, its clip) beside it.+ const extra = usual && { ...(cover!.framing && { framing: cover!.framing }), ...(cover!.clip && { clip: cover!.clip }), ...(cover!.clipAt !== undefined && { clipAt: cover!.clipAt }) };return {...rest,...(href !== presetPage(e.id) && { href }),- ...(usual ? { cv: v![2], ...(cover!.framing && { cover: { framing: cover!.framing } as MegaCover }) } : cover && { cover }),+ ...(usual ? { cv: v![2], ...(extra && Object.keys(extra).length && { cover: extra as MegaCover }) } : cover && { cover }),};}function unpackItem(w: WireItem): MegaItem {const { cv, href, cover, ...rest } = w;- return { ...rest, href: href ?? presetPage(w.id), ...(cv ? { cover: { ...presetUrls(w.id, cv), ...(cover?.framing && { framing: cover.framing }) } } : cover && { cover }) };+ return { ...rest, href: href ?? presetPage(w.id), ...(cv ? { cover: { ...presetUrls(w.id, cv), ...cover } } : cover && { cover }) };}/** A menu as its file carries it (smaller: presets' covers by version): packMenu on the server, unpackMenu in the browser. */diff --git a/src/lib/nav-covers.ts b/src/lib/nav-covers.tsindex 3cbd1255..c143ee89 100644--- a/src/lib/nav-covers.ts+++ b/src/lib/nav-covers.ts@@ -4,7 +4,7 @@*/import "server-only";import { coverFraming, type CoverFraming } from "./cover-framing";-import { coverIds } from "./nav-model";+import { coverIds, launcherColumns } from "./nav-model";import { hasMini, miniOf } from "./preset-cards";import { presetCover } from "./preset-covers";@@ -17,6 +17,11 @@ export interface NavCover {mini?: string;/** How it sits in a square tile or pill (cover-framing.ts), when it isn't centred there. */framing?: CoverFraming;+ /**+ * Its short muted clip's version, for the Studios menu's lead cards only (a row's picture is too small for a clip):+ * the clip is /previews/presets/<id>.mp4?v=<clipV>, played over the still while the card is pointed at.+ */+ clipV?: string;}/** Keyed by preset id. */@@ -28,12 +33,17 @@ let cached: NavCovers | undefined;export function navCovers(): NavCovers {if (cached) return cached;const out: NavCovers = {};+ // The Studios menu's lead cards, for any viewer: only they play a clip.+ const leads = new Set((["guest", "account", "owner", undefined] as const).flatMap((k) => launcherColumns(k).map((c) => c.lead.cover)));for (const id of coverIds()) {const c = presetCover(id);if (!c) throw new Error(`The navigation names ${id}, which has no cover`);const framing = coverFraming(c.poster);const mini = hasMini(c.poster) ? miniOf(c.poster) : undefined;- out[id] = { thumb: c.thumb, poster: c.poster, ...(mini && { mini }), ...(framing && { framing }) };+ // Only a clip of its own, at the usual place (a stand-in's clip is another preset's).+ const own = `/previews/presets/${id}.mp4?v=`;+ const clipV = leads.has(id) && c.video?.startsWith(own) ? c.video.slice(own.length) : undefined;+ out[id] = { thumb: c.thumb, poster: c.poster, ...(mini && { mini }), ...(framing && { framing }), ...(clipV && { clipV }) };}cached = out;return out;