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: open whole, with their pictures, and never show an empty frame
Adarsh2d5b4676300f
diff --git a/src/app/fx-compare.css b/src/app/fx-compare.cssindex afd78d75..7cd3b381 100644--- a/src/app/fx-compare.css+++ b/src/app/fx-compare.css@@ -2,7 +2,8 @@* Fuobe FX's before/after cards (components/fx/fx-compare.tsx). The divider's place is one variable, --fxc-pos, set by* the pointer (once a frame) or a key: the after is cut there with clip-path and the hairline moves by transform, so a* hover never lays anything out. States are data attributes on the card: data-show (rest, after, before: a tap),- * data-hover (a mouse over it), data-follow (the divider is under the mouse: no easing), data-armed (its hover files+ * data-hover (a mouse over it), data-fxc-follow (the divider is under the mouse: no easing; its own name, since+ * motion.css animates any [data-follow]), data-armed (its hover files* are asked for), data-ready (they came). In @layer components, so a* card's own utilities (its size, its corners) win.*/@@ -42,8 +43,8 @@clip-path: inset(0 0 0 var(--fxc-pos));transition: clip-path 260ms var(--fxc-ease);}- .fxc[data-follow] .fxc-after,- .fxc[data-follow] .fxc-line {+ .fxc[data-fxc-follow] .fxc-after,+ .fxc[data-fxc-follow] .fxc-line {transition: none;}/* A cut-out sits on a transparency checkerboard. */diff --git a/src/app/motion.css b/src/app/motion.cssindex 80ae5279..05fae854 100644--- a/src/app/motion.css+++ b/src/app/motion.css@@ -151,9 +151,10 @@/* ----- The top bar's menus (bar-menus.tsx): quick utility motion, transitions only (never keyframes), so a change ofmind half-way turns back from where it is and a fast glide never restarts anything.Big panels (Studios, Apps, Motions & effects, Canvas) sit on one shared sheet under the bar ([data-mega-stage]):- the sheet comes down from the bar (8 px, base, enter) and goes back up (4 px, fast, exit); between two panels its- bottom edge moves to the new height (transform only, base, standard) while the old content leaves sideways (fast,- exit) and the new one comes in from the side the pointer went, a stagger later: every switch ends by 240 ms. The+ the sheet comes down from the bar (8 px, base, enter), solid from its first frame, with its content from half there+ (never an empty sheet), and goes back up (4 px, fast, exit); between two panels its bottom edge moves to the new height (transform only, base, standard) while the+ old content leaves sideways (fast, exit) and the new one comes in from the side the pointer went at the same time,+ from half there: a cross-fade over the one sheet, never a frame of empty sheet; every switch ends by 200 ms. Thecolumns follow 20 ms apart on a fresh open (3 steps at most: every column reads by 260 ms), never on a switch.Cards (Create, More) grow in from their item (scale 0.97, 4 px) and shrink out (0.98, fast, exit).data-phase: open | exit (inert, still painted) | gone (hidden). Under reduced motion every token is 0. ----- */@@ -181,7 +182,8 @@/* The one in front during a switch is the new one; the old one fades under it. */&[data-phase="exit"] { z-index: 0; }&[data-phase="open"] { z-index: 1; }- &[data-phase="open"][data-mega-enter="fresh"] [data-col] { animation: motion-rise-near var(--motion-base) var(--ease-enter) backwards; }+ /* The columns only move (no fade of their own): every card shows from the panel's first frame. */+ &[data-phase="open"][data-mega-enter="fresh"] [data-col] { animation: motion-nudge-near var(--motion-base) var(--ease-enter) backwards; }&[data-phase="open"][data-mega-enter="fresh"] [data-col="1"] { animation-delay: var(--launcher-step); }&[data-phase="open"][data-mega-enter="fresh"] [data-col="2"] { animation-delay: calc(var(--launcher-step) * 2); }&[data-phase="open"][data-mega-enter="fresh"] :is([data-col="3"], [data-col="4"], [data-col="5"], [data-col="6"], [data-col="7"], [data-col="8"]) { animation-delay: calc(var(--launcher-step) * 3); }@@ -190,7 +192,9 @@}@starting-style {[data-mega-panel][data-phase="open"] {- opacity: 0;+ /* The content starts half there (on its solid sheet), so a panel is never seen empty, on an open or however fast+ the pointer crosses the bar. */+ opacity: 0.5;translate: var(--enter-x, 0px) var(--enter-y, calc(var(--motion-d2) * -1));}}@@ -219,12 +223,11 @@translate var(--motion-fast) var(--ease-exit);}&[data-phase="gone"] [data-mega-sheet] { translate: 0 calc(var(--motion-d2) * -1); transition: none; }+ /* Solid from its first frame (the page never shows through a panel coming in): it comes down, it never fades in. */&[data-open] [data-mega-sheet] {opacity: 1;translate: 0 0;- transition:- opacity var(--motion-base) var(--ease-enter),- translate var(--motion-base) var(--ease-enter);+ transition: translate var(--motion-base) var(--ease-enter);}}[data-bar-card] {@@ -444,6 +447,7 @@ img[data-fade="wait"] { opacity: 0; }@keyframes motion-fade-out { to { opacity: 0; } }@keyframes spin { to { transform: rotate(360deg); } }@keyframes motion-rise { from { opacity: 0; translate: 0 var(--motion-d1); } }+@keyframes motion-nudge-near { from { translate: 0 calc(var(--motion-d1) * -1); } }@keyframes motion-rise-near { from { opacity: 0; translate: 0 calc(var(--motion-d1) * -1); } }@keyframes motion-rise-page { from { translate: 0 var(--motion-d2); } }@keyframes motion-settle { from { opacity: 0; scale: 1.02; } }diff --git a/src/components/fx/fx-compare.tsx b/src/components/fx/fx-compare.tsxindex a4fa4126..a76e9117 100644--- a/src/components/fx/fx-compare.tsx+++ b/src/components/fx/fx-compare.tsx@@ -105,9 +105,14 @@ export function FxCompare({ view, sizes, eager, keys, className }: Props) {const arm = () => {if (extra) setArmed(true);};- const oneLoaded = () => {- loaded.current += 1;- if (loaded.current >= extra) setReady(true);+ /** A hover file came (or failed): counted once it is decoded too, so the lens or flipbook never shows an empty frame. */+ const oneLoaded = (e: React.SyntheticEvent<HTMLImageElement>) => {+ const done = () => {+ loaded.current += 1;+ if (loaded.current >= extra) setReady(true);+ };+ if (e.type === "load") void e.currentTarget.decode().then(done, done);+ else done();};// A tap's side: the divider goes all the way (or back to rest); the lens sits over the loupe's own place.@@ -176,7 +181,7 @@ export function FxCompare({ view, sizes, eager, keys, className }: Props) {arm();if (showRef.current !== "rest") setShow("rest");el.dataset.hover = "";- if (kind !== "loupe" && divides) el.dataset.follow = "";+ if (kind !== "loupe" && divides) el.dataset.fxcFollow = "";};const onPointerMove = (e: React.PointerEvent) => {if (!followsPointer(e.pointerType, reducedMotion()) || !divides) return;@@ -191,7 +196,7 @@ export function FxCompare({ view, sizes, eager, keys, className }: Props) {cancelAnimationFrame(raf.current);raf.current = 0;delete el.dataset.hover;- delete el.dataset.follow;+ delete el.dataset.fxcFollow;if (divides) setPos(showPos(showRef.current, rest));};diff --git a/src/components/nav/bar-menus.tsx b/src/components/nav/bar-menus.tsxindex 92bc8aa1..e01dd1b7 100644--- a/src/components/nav/bar-menus.tsx+++ b/src/components/nav/bar-menus.tsx@@ -629,11 +629,12 @@ export function useBarMenu(id: BarMenuId, { big = false, ready, warm }: { big?:const other = open ? menu.prev : menu.id;const sideways = big && !!other && !!ctl?.part(other)?.big;const dir = open ? switchDirection(menu.prev, id) : switchDirection(id, menu.id);- // The old content is gone (two thirds of fast) before the new one starts (two staggers): never two panels' words at once.+ // A cross-fade: the new content comes in from half there (motion.css) as the old one leaves (two thirds of fast), so+ // the sheet is never seen empty, even while the pointer sweeps across several items.const motion =sideways && dir? open- ? { "--enter-x": `calc(var(--motion-d2) * ${dir})`, "--enter-y": "0px", "--enter-delay": "calc(var(--motion-stagger) * 2)" }+ ? { "--enter-x": `calc(var(--motion-d2) * ${dir})`, "--enter-y": "0px" }: { "--exit-x": `calc(var(--motion-d2) * ${-dir})`, "--exit-y": "0px", "--exit-fade": "calc(var(--motion-fast) * .67)" }: {};return {diff --git a/src/components/nav/cover-thumb.tsx b/src/components/nav/cover-thumb.tsxindex c95bc994..5e4fcc41 100644--- a/src/components/nav/cover-thumb.tsx+++ b/src/components/nav/cover-thumb.tsx@@ -58,6 +58,7 @@ export function CoverThumb({size,icon,eager,+ low,sizes: boxSizes,className,}: {@@ -70,6 +71,8 @@ export function CoverThumb({icon?: NavIconName;/** Load at once (a panel about to open) instead of when it comes near the screen. */eager?: boolean;+ /** Load after the pictures around it (a menu's small row pictures, after its lead covers). */+ low?: 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;@@ -94,6 +97,7 @@ export function CoverThumb({height={s.h}alt=""loading={eager ? "eager" : "lazy"}+ fetchPriority={low ? "low" : undefined}decoding="async"draggable={false}className="absolute inset-0 size-full object-cover"diff --git a/src/components/nav/mega-data.ts b/src/components/nav/mega-data.tsindex e63f90eb..5d84b370 100644--- a/src/components/nav/mega-data.ts+++ b/src/components/nav/mega-data.ts@@ -46,7 +46,7 @@ export function warmMenu(id: MegaId): void {}/** A browser asking to save data, or on a slow connection: menus load when asked for only. */-function saveData(): boolean {+export function saveData(): boolean {if (typeof navigator === "undefined") return true;const conn = (navigator as Navigator & { connection?: { saveData?: boolean; effectiveType?: string } }).connection;return !!conn && (!!conn.saveData || /(^|-)2g$|^3g$/.test(conn.effectiveType ?? ""));@@ -84,6 +84,12 @@ export function useMegaMenu(id: MegaId, kind: ViewerKind | undefined): MenuStatereturn { model: entry?.state === "ready" ? entry.model : undefined, failed: entry?.state === "failed", retry };}+/** Once every menu's data on its way now has come (or failed). */+export function menusSettled(): Promise<void> {+ const loading = [...entries.values()].flatMap((e) => (e.state === "loading" ? [e.promise] : []));+ return Promise.allSettled(loading).then(() => {});+}+/** For tests: forget every loaded menu. */export function resetMenus() {entries.clear();diff --git a/src/components/nav/mega-launcher.tsx b/src/components/nav/mega-launcher.tsxindex bb293787..2e50da7f 100644--- a/src/components/nav/mega-launcher.tsx+++ b/src/components/nav/mega-launcher.tsx@@ -1,12 +1,12 @@"use client";-import { lazy, Suspense, useCallback, useEffect, useState } from "react";+import { lazy, memo, startTransition, Suspense, useCallback, useEffect, useRef, useState } from "react";import { MEGA_AREAS, megaMove, megaPanelId, TILE_COLS, type MegaId } from "@/lib/mega-menus";import { activeEntry, launcherActive, subActive } from "@/lib/nav-model";import { cn } from "@/lib/utils";-import { useBarMenu } from "./bar-menus";+import { shows, useBarController, useBarMenu } from "./bar-menus";import { BarTrigger } from "./bar-split";-import { menuReady, warmMenu } from "./mega-data";+import { menuReady, menusSettled, warmMenu } from "./mega-data";import { useSearchPalette } from "./search-context";import { warmNav, type NavPanel } from "./nav-prefetch";@@ -61,13 +61,63 @@ const loadPanel = () =>panelLoaded = true;return m;});-const LazyPanel = lazy(() => loadPanel().then((m) => ({ default: m.MegaPanel })));+/** Memoised: a ready panel stays as it is while the bar's menus open, close and switch (it re-renders on its own data). */+const LazyPanel = lazy(() => loadPanel().then((m) => ({ default: memo(m.MegaPanel) })));/** Loads the panel's body ahead (the bar does when the page is idle; hover and focus on an item do too). */export function preloadMegaPanel(): void {void loadPanel().catch(() => {});}+/** The big panels in the bar's order (the order they get ready in when the pointer's place is not known). */+const BAR_ORDER: readonly MegaId[] = ["studios", "fx", "apps", "motions", "canvas"];+/** Each mounted panel: what gets it ready, whether its item shows at this width, and whether its pictures are ready. */+const primers = new Map<MegaId, { heat: () => void; shows: () => boolean; at: () => number | undefined; done: boolean }>();+let primeQueue: MegaId[] | null = null;+let priming: { id: MegaId; timer: number } | null = null;++/** The next panel in the queue whose item shows gets ready; the one after it waits for its pictures (3 s at most). */+function primeNext(): void {+ while (primeQueue?.length) {+ const id = primeQueue.shift()!;+ const p = primers.get(id);+ if (!p || p.done || !p.shows()) continue;+ priming = { id, timer: window.setTimeout(() => primed(id), 3000) };+ p.heat();+ return;+ }+}++/** `id`'s first screen is ready (or its time ran out): the next panel's turn. */+function primed(id: MegaId): void {+ const p = primers.get(id);+ if (p) p.done = true;+ if (priming?.id !== id) return;+ window.clearTimeout(priming.timer);+ priming = null;+ primeNext();+}++/**+ * The pointer or focus came to the bar: every big panel whose item shows renders its body, closed, so its first+ * screen's pictures load and decode before it opens, and a switch from one to the next never shows empty boxes. One+ * panel at a time, nearest the pointer first (`x`: where it came in; else the bar's order), so a slow connection gets+ * the ones it is about to open whole first (the item the pointer is on gets its own ready at once, as ever).+ */+export function primeMegaPanels(x?: number): void {+ if (primeQueue) return;+ const far = (id: MegaId) => {+ const c = x === undefined ? undefined : primers.get(id)?.at();+ return c === undefined ? Infinity : Math.abs(c - x!);+ };+ primeQueue = [...BAR_ORDER].sort((a, b) => far(a) - far(b));+ // The pictures wait for the panels' code and the menus' data, so on a slow connection they never hold up an open.+ void loadPanel()+ .catch(() => {})+ .then(menusSettled)+ .then(primeNext);+}+/** While a menu's data (or the panel's body) is on its way: its columns at their final sizes, so nothing moves when it comes. */export function MegaSkeleton({ id }: { id?: MegaId }) {if (id === "canvas") {@@ -124,9 +174,49 @@ export function MegaLauncher({ id, active, className }: { id: MegaId; active?: bpreloadMegaPanel();setWarm(true);}, [id]);- const ready = useCallback(() => panelLoaded && menuReady(id), [id]);+ // Its first screen's pictures are decoded (MegaPanel's onPrimed): a hover open waits a moment for them too.+ const pictures = useRef(false);+ const onPrimed = useCallback(() => {+ pictures.current = true;+ primed(id);+ }, [id]);+ const ready = useCallback(() => panelLoaded && menuReady(id) && pictures.current, [id]);const { open, phase, close, entered, style, trigger, surface, triggerRef, surfaceRef } = useBarMenu(id, { big: true, ready, warm: heat });const shown = warm || open;+ const ctl = useBarController();++ // Its place in the bar's queue of panels getting ready (primeMegaPanels): only while its item shows at this width.+ useEffect(() => {+ const t = () => ctl?.part(id)?.trigger;+ const at = () => {+ const r = t()?.getBoundingClientRect();+ return r?.width ? r.left + r.width / 2 : undefined;+ };+ // Rendered as a transition: the closed body's render yields to the pointer and keys (never one long task).+ const prime = () => {+ warmMenu(id);+ preloadMegaPanel();+ startTransition(() => setWarm(true));+ };+ primers.set(id, { heat: prime, shows: () => !!t() && shows(t()!), at, done: pictures.current });+ return () => {+ primers.delete(id);+ };+ }, [ctl, id]);++ // The body's callbacks keep one identity, so the memoised body never re-renders when a menu opens or switches.+ const closeRef = useRef(close);+ const searchRef = useRef(search);+ useEffect(() => {+ closeRef.current = close;+ searchRef.current = search;+ });+ const onClose = useCallback(() => closeRef.current(), []);+ const onSearch = useCallback(() => {+ // The item gets focus first, so it is where Esc in the search comes back to (the panel is gone by then).+ closeRef.current(true);+ searchRef.current.open();+ }, []);// Opened: the routes one click here leads to start loading.useEffect(() => {@@ -176,12 +266,9 @@ export function MegaLauncher({ id, active, className }: { id: MegaId; active?: b><LazyPanelid={id}- onClose={close}- onSearch={() => {- // The item gets focus first, so it is where Esc in the search comes back to (the panel is gone by then).- close(true);- search.open();- }}+ onPrimed={onPrimed}+ onClose={onClose}+ onSearch={onSearch}/></Suspense>)}diff --git a/src/components/nav/mega-panel.tsx b/src/components/nav/mega-panel.tsxindex 74a08c64..ab403cdf 100644--- a/src/components/nav/mega-panel.tsx+++ b/src/components/nav/mega-panel.tsx@@ -105,7 +105,7 @@ export function LeadCard({ e, col, row = 0, span = 1, current, inside, now, clas* the second line, before the line; a name too long for the column takes the second line instead and the line gives way* (it stays in the title). Below 1280 px the name alone, on up to two lines, with its badge beside it.*/-function Row({ e, col, row, current, inside, now, className }: { e: MegaItem; col: number; row: number; current: boolean; inside?: boolean; now: number; className?: string }) {+function Row({ e, col, row, current, inside, now, eager, className }: { e: MegaItem; col: number; row: number; current: boolean; inside?: boolean; now: number; eager?: boolean; className?: string }) {const fresh = isNew(e, now);return (<IntentLink@@ -117,9 +117,10 @@ function Row({ e, col, row, current, inside, now, className }: { e: MegaItem; cotitle={e.line ? `${e.label}: ${e.line}` : e.label}className={cn("nav-row nav-mark-start -mx-2 flex min-h-11 items-center gap-3 rounded-[10px] px-2 py-1 md:max-lg:min-h-10 md:max-lg:py-0.5 [@media(pointer:coarse)]:min-h-11", className)}>- {/* Six columns leave a row its name and line below 1440 px, and its name alone below 1280 px. Its picture loads- when the row shows (lazy): a row hidden by the window's height never fetches it. */}- <CoverThumb id={e.navCover} cover={e.cover} size="row" icon={e.icon} className="max-[1439.98px]:hidden" />+ {/* Six columns leave a row its name and line below 1440 px, and its name alone below 1280 px. `eager`: a row this+ window shows loads its picture with the panel, so it is there on the first frame; any other row's loads when it+ shows (lazy): a row hidden by the window's height never fetches it. */}+ <CoverThumb id={e.navCover} cover={e.cover} size="row" icon={e.icon} eager={eager} low className="max-[1439.98px]:hidden" />{/* Centred while it fits; a name on two lines starts at the top and pushes the line out of the 36 px box. */}<span data-row-text className="flex max-h-9 min-w-0 flex-1 flex-wrap items-center gap-x-1 overflow-hidden [align-content:safe_center] max-xl:flex-nowrap"><span data-row-name className={cn("line-clamp-2 min-w-0 text-[13px] leading-[18px] font-medium", (current || inside) && "font-semibold")}>@@ -219,6 +220,18 @@ function Tile({ e, col, row, current, eager }: { e: MegaItem; col: number; row:);}+/**+ * How many of a list column's rows show their picture in this window (ROW_HIDE's caps; none below 1440 px, where rows+ * show no picture): these load with the panel, before it opens. Read once, when the panel's body first renders (only+ * ever in the browser).+ */+function rowsWithPictures(capped: boolean, families: boolean): number {+ if (typeof window === "undefined" || window.innerWidth < 1440) return 0;+ if (!capped) return Infinity;+ const h = window.innerHeight;+ return h < 800 ? ROW_CAPS.short - (families ? 1 : 0) : h < 960 ? ROW_CAPS.mid : ROW_CAPS.tall;+}+/** Tiles across a tiles column. */const across = (c: MegaColumn) => Math.min(c.span ?? 1, TILE_COLS);@@ -270,6 +283,7 @@ export function MegaColumns({ model, current, now, kind }: { model: MegaModel; cconst families = !!model.families?.length;const tileColumns = model.columns.filter((c) => c.variant === "tiles").length;const places = keyPlaces(model.columns);+ const [pictured] = useState(() => rowsWithPictures(capped, families));// On a studio's feature (Genjutsu's Restyle, Upscale's Video), its studio is marked as holding the page too.const holder = current ? subParent(current) : undefined;@@ -341,7 +355,7 @@ export function MegaColumns({ model, current, now, kind }: { model: MegaModel; c)}{rows.map((e, ri) => (<li key={e.id} className={capped ? ROW_HIDE(ri, families) : undefined}>- <Row e={e} col={col} row={at[ri]} current={current === e.id} inside={holder === e.id} now={now} />+ <Row e={e} col={col} row={at[ri]} current={current === e.id} inside={holder === e.id} now={now} eager={ri < pictured} /><SubLinks e={e} col={col} row={at[ri] + 1} current={current} under /></li>))}@@ -378,8 +392,21 @@ export function LauncherColumns({ kind, current, now }: { kind: ViewerKind | undreturn <MegaColumns model={studiosMenu(kind)} current={current} now={now} kind={kind} />;}-/** The panel's body once it is shown or warmed: it reads the path (client only: the panel never renders on the server). */-export function MegaPanel({ id, onClose, onSearch }: { id: MegaId; onClose: () => void; onSearch: () => void }) {+/**+ * The pictures a closed panel holds ready for its first frame: those it loads with the panel first (lead covers, before+ * and after stills, the first tiles), decoded, so it never opens on empty boxes that fill in after. Resolves once each+ * one is decoded or failed, or after `cap` ms. The rows' small pictures load too, after these (low priority).+ */+function decodePictures(root: HTMLElement, cap = 4000): Promise<void> {+ const imgs = [...root.querySelectorAll<HTMLImageElement>('img:not([loading="lazy"]):not([fetchpriority="low"])')];+ return Promise.race([Promise.allSettled(imgs.map((i) => i.decode())).then(() => {}), new Promise<void>((r) => window.setTimeout(r, cap))]);+}++/**+ * The panel's body once it is shown or warmed: it reads the path (client only: the panel never renders on the server).+ * `onPrimed`: its menu is here and its first screen's pictures are decoded (a hover open waits a moment for it).+ */+export function MegaPanel({ id, onClose, onSearch, onPrimed }: { id: MegaId; onClose: () => void; onSearch: () => void; onPrimed?: () => void }) {const kind = useViewerKind();const pathname = usePathname();const { model, failed, retry } = useMegaMenu(id, kind);@@ -394,8 +421,22 @@ export function MegaPanel({ id, onClose, onSearch }: { id: MegaId; onClose: () =const area = MEGA_AREAS[id];// The query too: moving from one preset to another (/video?preset=…) keeps the path.const search = useSearchParams()?.toString() ?? "";+ const root = useRef<HTMLDivElement>(null);+ const primed = useRef(onPrimed);+ useEffect(() => {+ primed.current = onPrimed;+ });+ useEffect(() => {+ const el = root.current;+ if (!model || !el) return;+ let live = true;+ void decodePictures(el).then(() => live && primed.current?.());+ return () => {+ live = false;+ };+ }, [model]);return (- <div className="max-w-[1680px] px-6 pt-5 pb-6 lg:pt-6 lg:pb-7">+ <div ref={root} className="max-w-[1680px] px-6 pt-5 pb-6 lg:pt-6 lg:pb-7"><div className="flex min-h-10 items-center gap-3 pb-4"><p className="text-[13px] text-muted-foreground" data-count-line>{model ? model.countLine : failed ? "Couldn't load this menu" : " "}diff --git a/src/components/nav/top-bar.tsx b/src/components/nav/top-bar.tsxindex 773aaf8b..3ddfedd9 100644--- a/src/components/nav/top-bar.tsx+++ b/src/components/nav/top-bar.tsx@@ -19,8 +19,8 @@ import { UpdateAvailable } from "@/components/update-available";import { BarPills } from "./status-chips";import { NavPrefetcher, warmNav } from "./nav-prefetch";import type { FetchedMegaId } from "@/lib/mega-menus";-import { loadMenusNow } from "./mega-data";-import { MegaLauncher, preloadMegaPanel } from "./mega-launcher";+import { loadMenusNow, saveData } from "./mega-data";+import { MegaLauncher, preloadMegaPanel, primeMegaPanels } from "./mega-launcher";import { BarCardMenu } from "./bar-split";import { BarIndicator, BarMenusProvider, BarScrim, BarStage, CloseMenusOnRoute, useBarController } from "./bar-menus";import { ViewerSlot } from "./viewer-slot";@@ -277,17 +277,19 @@ function RightCluster() {}/**- * Everything the bar's menus need before their first open: the panels' body (its own chunk) and the data (no- * pictures) of the grouped menus whose item the bar shows at this width. A phone loads none (its sheet asks when it- * shows one); a browser saving data loads only the code.+ * Everything the bar's menus need before their first open: the panels' body (its own chunk), the data of the grouped+ * menus whose item the bar shows at this width, then each of those panels' first screen of pictures, decoded, so the+ * first open and every switch show whole (primeMegaPanels: nearest `x` first, the pointer's place when it came to the+ * bar). A phone loads none (its sheet asks when it shows one); a browser saving data loads only the code.*/-export function warmBar(): void {+export function warmBar(x?: number): void {if (!window.matchMedia("(min-width: 768px)").matches) return;const ids: FetchedMegaId[] = [];if (window.matchMedia("(min-width: 1280px)").matches) ids.push("fx", "apps", "motions");if (window.matchMedia("(min-width: 1440px)").matches) ids.push("canvas");preloadMegaPanel();loadMenusNow(ids);+ if (!saveData()) primeMegaPanels(x);}/**@@ -299,11 +301,11 @@ function MenuPrefetch() {let stop = () => {};const schedule = () => {if (typeof window.requestIdleCallback !== "function") {- const t = window.setTimeout(warmBar, 300);+ const t = window.setTimeout(() => warmBar(), 300);stop = () => window.clearTimeout(t);return;}- const h = window.requestIdleCallback(warmBar, { timeout: 1500 });+ const h = window.requestIdleCallback(() => warmBar(), { timeout: 1500 });stop = () => window.cancelIdleCallback(h);};if (document.readyState === "complete") schedule();@@ -316,17 +318,20 @@ function MenuPrefetch() {return null;}-/** The main nav: its keys (Left and Right along the items); the first pointer or focus near it warms the menus. */+/**+ * The main nav: its keys (Left and Right along the items); the first pointer or focus near it warms the menus (warmBar),+ * if the page's idle time has not already.+ */function MainNav({ children }: { children: React.ReactNode }) {const ctl = useBarController();const warmed = useRef(false);- const warm = () => {+ const warm = (x?: number) => {if (warmed.current) return;warmed.current = true;- warmBar();+ warmBar(x);};return (- <nav aria-label="Main" className="flex min-w-0 items-center gap-0.5" onKeyDown={(e) => ctl?.navKey(e)} onPointerEnter={warm} onFocus={warm}>+ <nav aria-label="Main" className="flex min-w-0 items-center gap-0.5" onKeyDown={(e) => ctl?.navKey(e)} onPointerEnter={(e) => warm(e.clientX)} onFocus={() => warm()}>{children}</nav>);diff --git a/tests/e2e/bar-menus.mjs b/tests/e2e/bar-menus.mjsindex 80a66d23..97c49cdc 100644--- a/tests/e2e/bar-menus.mjs+++ b/tests/e2e/bar-menus.mjs@@ -820,13 +820,16 @@ try {const watch = p.evaluate(async () => {let worst = 0;let both = 0;+ let empty = 0;const end = performance.now() + 500;while (performance.now() < end) {const sheet = document.querySelector("[data-mega-sheet]").getBoundingClientRect();let shown = 0;+ let most = 0;for (const s of document.querySelectorAll("[data-mega-panel]:not([hidden])")) {const cs = getComputedStyle(s);const op = Number(cs.opacity);+ most = Math.max(most, op);if (op < 0.05) continue;if (op > 0.3) shown++;const r = s.getBoundingClientRect();@@ -838,15 +841,18 @@ try {worst = Math.max(worst, bottom - sheet.bottom);}if (shown > 1) both++;+ if (most < 0.45) empty++;await new Promise(requestAnimationFrame);}- return { worst, both };+ return { worst, both, empty };});await sleep(30);await glide(p, { x: rb.x, y: rb.y }, Infinity);const w = await watch;check(w.worst <= 2, `22: ${a} → ${b}: no panel shows past the sheet's edge during the switch`, `${w.worst.toFixed(0)} px`);- check(w.both <= 1, `22: ${a} → ${b}: never two panels' words clearly at once`, `${w.both} frames`);+ // A cross-fade: the two panels' words together only briefly, and never a frame of empty sheet.+ check(w.both <= 4, `22: ${a} → ${b}: two panels' words together only briefly (a cross-fade)`, `${w.both} frames`);+ check(w.empty === 0, `22: ${a} → ${b}: never a frame of empty sheet`, `${w.empty} frames`);}// 23. Create's See all: top right of the card, out of the rows' flow.diff --git a/tests/e2e/mega-menus.mjs b/tests/e2e/mega-menus.mjsindex 0c456f03..e95ee4e1 100644--- a/tests/e2e/mega-menus.mjs+++ b/tests/e2e/mega-menus.mjs@@ -554,17 +554,24 @@ try {await p.goto(`${app}/image`, { waitUntil: "domcontentloaded" });const early = [...urls.values()].filter((u) => u.includes("/nav-menus/")).length;await p.waitForLoadState("load");+ const loadedAt = Date.now();await p.waitForTimeout(4000);const idle = [...urls.values()].filter((u) => u.includes("/nav-menus/"));- const minis = [...urls.values()].filter((u) => /\/previews\/presets\/mini\//.test(u)).length;+ // The menus' pictures (their covers, before and after stills, row pictures): only once the page has loaded.+ const MENU_PICS = /\/previews\/(presets\/(mini|thumbs|hd)|fx|templates\/hd)\//;+ const pics = [...urls].filter(([, u]) => MENU_PICS.test(u));+ const picsEarly = pics.filter(([rid]) => at_.get(rid) < loadedAt - 50).length;+ const picsKB = Math.round(pics.reduce((s, [rid]) => s + (bytes.get(rid) ?? 0), 0) / 1024);check(early === 0, "no menu data with the page itself");check(idle.length === 3, "idle: the three menus' data (apps, motions, canvas), once each", idle.map((u) => new URL(u).pathname).join(" "));- check(minis === 0, "idle: no menu pictures before a menu warms", String(minis));+ check(picsEarly === 0, "the menus' pictures load only after the page itself", String(picsEarly));+ check(pics.length > 0 && picsKB <= 900, "idle: every menu's first screen is ready, with at most 900 KB of pictures at 1440x900", `${pics.length} files, ${picsKB} KB`);// Gzipped as the site's front server sends it (next start here may send it plain).const sizes = [];for (const u of new Set(idle)) sizes.push([new URL(u).pathname, zlib.gzipSync(Buffer.from(await (await fetch(u)).arrayBuffer())).length]);check(sizes.length === 3 && sizes.every(([, b]) => b > 0 && b <= 4096), "each menu's data is at most 4 KB gzipped", sizes.map(([u, b]) => `${u} ${b}`).join(", "));- // Warm, then open: the panel shows within a frame of the click; pictures within budget; nothing moves.+ // Warm, then open: the panel shows within a frame of the click, its first screen's pictures already there (the+ // page's idle time readied every panel); pictures within budget; nothing moves.for (const id of ["apps", "motions", "canvas"]) {const since = Date.now();const item = trig(p, id);@@ -577,12 +584,14 @@ try {b.click();await new Promise((r) => requestAnimationFrame(() => r()));const panel = document.getElementById(`${sel}-launcher`);- return panel && !panel.hidden && panel.querySelector("[data-col]") ? performance.now() - t0 : -1;+ const empty = panel ? [...panel.querySelectorAll("img")].filter((i) => i.checkVisibility() && i.loading !== "lazy" && !(i.complete && i.naturalWidth)).length : -1;+ return { ms: panel && !panel.hidden && panel.querySelector("[data-col]") ? performance.now() - t0 : -1, empty };}, id);- check(ms >= 0 && ms < 100, `${id}: shows within 100 ms of the click once warmed`, `${ms.toFixed?.(1)} ms`);+ check(ms.ms >= 0 && ms.ms < 100, `${id}: shows within 100 ms of the click once warmed`, `${ms.ms.toFixed?.(1)} ms`);+ check(ms.empty === 0, `${id}: opens with its first screen's pictures already there`, `${ms.empty} still loading`);await p.waitForTimeout(2500);const img = [...urls].filter(([rid, u]) => at_.get(rid) >= since && /\/previews\//.test(u)).reduce((s, [rid]) => s + (bytes.get(rid) ?? 0), 0);- check(img <= 250 * 1024, `${id}: first open loads at most 250 KB of pictures at 1440x900`, `${Math.round(img / 1024)} KB`);+ check(img <= 250 * 1024, `${id}: its open loads at most 250 KB more pictures at 1440x900`, `${Math.round(img / 1024)} KB`);await p.keyboard.press("Escape");await p.waitForTimeout(300);const cls = await p.evaluate(() => window.__cls);