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
Prefetch a page's own tabs before the sidebar's routes; mark a clicked sidebar row at once
Adarshe4c0f06ef8cb
diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsxindex 292fcf08..b20ba1bb 100644--- a/src/components/app-sidebar.tsx+++ b/src/components/app-sidebar.tsx@@ -4,7 +4,7 @@ import dynamic from "next/dynamic";import { useLinkStatus } from "next/link";import { usePathname, useSearchParams } from "next/navigation";import { useTheme } from "next-themes";-import { Fragment, Suspense, useCallback, useEffect, useRef, useState } from "react";+import { Fragment, Suspense, useCallback, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore } from "react";import { ChevronRight, ChevronsUpDown, Clapperboard, Cpu, LogIn, LogOut, Moon, Plus, Search, Settings2, Sun, UserPlus, X } from "lucide-react";import {Sidebar,@@ -49,6 +49,7 @@ import { deviceLabel } from "@/lib/gpu/readiness";import { safeLink, useInterest } from "@/lib/hosted";import { useModKey } from "@/lib/keys";import { fullScreenStudio, groupId, NAV_CLOSED_KEY, navActive, NEW_CREATION_HREF, parseClosed, scrollFades, sidebarCookie, SIDEBAR_STATE_SCRIPT, sidebarOpenFromCookie } from "@/lib/nav";+import { isPlainClick } from "@/lib/use-tapped-tab";import { cn } from "@/lib/utils";// The note of a tab that runs the person's jobs on their own computer's ComfyUI (only for someone whose runs go there).@@ -75,10 +76,41 @@ function NavLabel({ children }: { children: React.ReactNode }) {);}+/**+ * The row just clicked: the open page's row from the next frame on, while its route loads, in every group at once (the+ * address says again once the route has moved: TappedRowReset).+ */+let tappedRow: string | null = null;+const tappedListeners = new Set<() => void>();++function setTappedRow(href: string | null) {+ if (tappedRow === href) return;+ tappedRow = href;+ for (const l of tappedListeners) l();+}++function subscribeTapped(cb: () => void) {+ tappedListeners.add(cb);+ return () => {+ tappedListeners.delete(cb);+ };+}++/** Clears the clicked row once the address changes (the route moved, or Back / Forward). Inside Suspense: runtime data. */+function TappedRowReset() {+ const pathname = usePathname();+ const search = useSearchParams().toString();+ useLayoutEffect(() => setTappedRow(null), [pathname, search]);+ return null;+}+function Items({ group, pathname, search }: { group: NavGroupDef; pathname: string; search: URLSearchParams }) {const hrefs = group.items.map((i) => i.href);+ const tapped = useSyncExternalStore(subscribeTapped, () => tappedRow, () => null);+ const [at, query] = tapped ? tapped.split("?") : [pathname];+ const where = tapped ? new URLSearchParams(query ?? "") : search;return group.items.map((item) => {- const active = navActive(item.href, pathname, search, hrefs);+ const active = navActive(item.href, at, where, hrefs);return (<SidebarMenuItem key={item.href} className={cn(group.compact && "min-w-0")}><SidebarMenuButton@@ -90,7 +122,14 @@ function Items({ group, pathname, search }: { group: NavGroupDef; pathname: strigroup.compact && "h-7 gap-1.5 px-2 text-[12px]",)}>- <IntentLink href={item.href} eager={item.eager} settled aria-current={active ? "page" : undefined} title={group.compact && item.short ? item.label : undefined}>+ <IntentLink+ href={item.href}+ eager={item.eager}+ settled+ onClick={(e) => isPlainClick(e) && setTappedRow(item.href)}+ aria-current={active ? "page" : undefined}+ title={group.compact && item.short ? item.label : undefined}+ ><item.icon /><NavLabel>{group.compact ? (item.short ?? item.label) : item.label}</NavLabel></IntentLink>@@ -701,6 +740,7 @@ export function AppSidebar() {})}<Suspense fallback={null}><RevealActive box={content} />+ <TappedRowReset /></Suspense></SidebarContent><SidebarFooter className="gap-1 border-t border-sidebar-border" onClick={closeOnLink}>diff --git a/src/components/intent-link.tsx b/src/components/intent-link.tsxindex a40ef143..f790888b 100644--- a/src/components/intent-link.tsx+++ b/src/components/intent-link.tsx@@ -3,9 +3,9 @@import { Loader2 } from "lucide-react";import Link, { useLinkStatus } from "next/link";import { useRouter } from "next/navigation";-import { useEffect, useState } from "react";+import { useState } from "react";+import { useIdlePrefetch } from "@/lib/idle-prefetch";import { cn } from "@/lib/utils";-import { useSettled } from "@/lib/when-idle";/*** A Link that prefetches on intent: nothing while it merely sits on screen, then the usual prefetch@@ -13,9 +13,9 @@ import { useSettled } from "@/lib/when-idle";* prefetch" of Next's prefetching guide). `eager` rows prefetch as soon as they're on screen, like a* plain Link: the few routes most visits go to next. `settled` rows prefetch once the page has* loaded and the browser is idle, also the ones scrolled out of view (the app's own navigation: a tap- * there must not wait a round trip, a touch comes too late to start one, and rows that only start- * when scrolled into view would queue up in front of the tap). A page full of these no longer- * fetches every route behind it on a cold visit.+ * there must not wait a round trip, and a touch comes too late to start one), after the page's own+ * tabs (useIdlePrefetch's "nav" lane). A page full of these no longer fetches every route behind it+ * on a cold visit.*/export function IntentLink({eager,@@ -27,14 +27,11 @@ export function IntentLink({}: React.ComponentProps<typeof Link> & { eager?: boolean; settled?: boolean }) {const [intent, setIntent] = useState(false);const router = useRouter();- const idle = useSettled();- const now = eager || (settled && idle);const href = typeof props.href === "string" ? props.href : null;- useEffect(() => {- if (settled && idle && href) router.prefetch(href);- }, [settled, idle, href, router]);+ // Not the Link's own viewport prefetch: a row coming on screen later would jump the queue ahead of the page's tabs.+ useIdlePrefetch(settled && href ? [href] : null, "nav");const start = () => {- if (now || intent) return;+ if (eager || intent) return;setIntent(true);// Start the fetch from the event itself: the Link only picks it up after it renders again and// sees itself on screen, a frame or more later (several on a slow phone), which a quick click beats.@@ -43,7 +40,7 @@ export function IntentLink({return (<Link{...props}- prefetch={now || intent ? null : false}+ prefetch={eager || intent ? null : false}onMouseEnter={(e) => {start();onMouseEnter?.(e);diff --git a/src/components/studio/hub-chrome.tsx b/src/components/studio/hub-chrome.tsxindex a9c82d3d..66e8985f 100644--- a/src/components/studio/hub-chrome.tsx+++ b/src/components/studio/hub-chrome.tsx@@ -4,14 +4,13 @@ import Link from "next/link";import { usePathname, useRouter } from "next/navigation";import { createContext, Suspense, useContext, useEffect, useMemo, useRef, useState } from "react";import { createPortal } from "react-dom";-import type { PrefetchOptions } from "next/dist/shared/lib/app-router-context.shared-runtime";import { SidebarTrigger } from "@/components/ui/sidebar";import { EngineSwitch } from "@/components/studio/engine-switch";import { useEngine, useLikelyVisitor } from "@/lib/api";import { HUB_MODES, HUB_TITLE, hubOfPath, modeHref, modeOfPath, type HubKind } from "@/lib/hubs";+import { prefetchOptions, useIdlePrefetch } from "@/lib/idle-prefetch";import { cn } from "@/lib/utils";import { isPlainClick, useTappedTab } from "@/lib/use-tapped-tab";-import { whenIdle } from "@/lib/when-idle";import { useEdgeFade } from "./use-edge-fade";/**@@ -34,9 +33,6 @@ export function HubHeaderExtras({ children }: { children: React.ReactNode }) {return slot ? createPortal(children, slot) : null;}-/** `<Link prefetch={true}>` for a link that isn't on screen: the per-link prefetch of a whole (prerendered) mode page. */-const FULL = { kind: "full" } as unknown as PrefetchOptions;-/*** The hub's mode tabs: underline tabs on their own row under the title; they scroll sideways (with faded edges) on* phones. Each mode is its own history entry, so Back returns to the mode before.@@ -69,10 +65,13 @@ function HubTabs({ kind, pathname, onActive }: { kind: HubKind; pathname: stringif (left < row.scrollLeft || left + el.offsetWidth > row.scrollLeft + row.clientWidth) row.scrollLeft = left - 12;}, [active, ref]);- // Every mode, also the ones scrolled out of the row, once the page is idle (a tab on screen already prefetches itself).- // Once per hub and audience: the client cache keeps what was fetched.- const hrefs = modes.map((m) => modeHref(kind, m.id)).join(" ");- useEffect(() => whenIdle(() => hrefs.split(" ").forEach((href) => router.prefetch(href, FULL))), [hrefs, router]);+ // Every mode's whole page, also the ones scrolled out of the row, once the page is idle (a tab on screen already+ // prefetches itself), ahead of the sidebar's routes: the "page" lane.+ useIdlePrefetch(+ modes.map((m) => modeHref(kind, m.id)),+ "page",+ true,+ );return (<nav aria-label="Modes" className="border-b">@@ -88,7 +87,7 @@ function HubTabs({ kind, pathname, onActive }: { kind: HubKind; pathname: stringprefetchscroll={false}data-mode={m.id}- onTouchStart={() => router.prefetch(href, FULL)}+ onTouchStart={() => router.prefetch(href, prefetchOptions(true))}// A new tab or window (modifier, middle button) leaves this page as it is.onClick={(e) => isPlainClick(e) && tap(m.id)}aria-current={on ? "page" : undefined}diff --git a/src/lib/idle-prefetch.ts b/src/lib/idle-prefetch.tsnew file mode 100644index 00000000..e720cd70--- /dev/null+++ b/src/lib/idle-prefetch.ts@@ -0,0 +1,136 @@+"use client";++import { useRouter } from "next/navigation";+import { useEffect } from "react";+import type { PrefetchOptions } from "next/dist/shared/lib/app-router-context.shared-runtime";++/** Runs `fn` once the browser is idle after the page has loaded (soon after, where requestIdleCallback is missing). Returns a cancel. */+export function whenIdle(fn: () => void): () => void {+ let idle = 0;+ let timer = 0;+ const schedule = () => {+ if (typeof window.requestIdleCallback === "function") idle = window.requestIdleCallback(fn, { timeout: 2000 });+ else timer = window.setTimeout(fn, 300);+ };+ if (document.readyState === "complete") schedule();+ else window.addEventListener("load", schedule, { once: true });+ return () => {+ window.removeEventListener("load", schedule);+ if (idle) window.cancelIdleCallback(idle);+ if (timer) window.clearTimeout(timer);+ };+}++/**+ * Who asked for an idle prefetch: `nav` = the app's own navigation (the sidebar's rows), `page` = the page's own tabs (a+ * hub's modes), the likeliest next tap, which go first.+ */+export type PrefetchLane = "nav" | "page";++interface Job {+ href: string;+ run: () => void;+}++const lanes: Record<PrefetchLane, Set<Job>> = { nav: new Set(), page: new Set() };+let flushing = false;++/**+ * Calls `done` once the server has answered a prefetch for each of `hrefs` and the prefetch traffic has then been quiet+ * for `quiet` ms (Resource Timing; the requests that came before this call count too), at the latest after `max` ms.+ */+export function afterPrefetched(hrefs: string[], done: () => void, quiet = 500, max = 8000): void {+ const want = new Set(hrefs.map((h) => new URL(h, window.location.href).pathname));+ let last = performance.now();+ let over = false;+ let timer = 0;+ let cap = 0;+ let observer: PerformanceObserver | null = null;+ const finish = () => {+ if (over) return;+ over = true;+ observer?.disconnect();+ window.clearTimeout(timer);+ window.clearTimeout(cap);+ done();+ };+ const check = () => {+ window.clearTimeout(timer);+ const still = quiet - (performance.now() - last);+ if (!want.size && still <= 0) finish();+ else timer = window.setTimeout(check, Math.max(50, still));+ };+ cap = window.setTimeout(finish, max);+ try {+ observer = new PerformanceObserver((list) => {+ for (const e of list.getEntries() as PerformanceResourceTiming[]) {+ if (!e.name.includes("_rsc=")) continue;+ want.delete(new URL(e.name).pathname);+ last = Math.max(last, e.responseEnd);+ }+ check();+ });+ observer.observe({ type: "resource", buffered: true });+ } catch {+ // No Resource Timing: the cap decides.+ }+ check();+}++function flush() {+ flushing = false;+ const page = [...lanes.page];+ const nav = [...lanes.nav];+ lanes.page.clear();+ lanes.nav.clear();+ for (const job of page) job.run();+ // Next serves a prefetch's route tree and shell (the sidebar's forty-odd routes) before any route's URL-specific part (a+ // hub mode's own page), so the sidebar's rows go out only once the page's own tabs are in.+ const go = () => nav.forEach((job) => job.run());+ if (page.length && nav.length) afterPrefetched(page.map((job) => job.href), go);+ else go();+}++/** Queues one prefetch of `href` (`run`) for the next idle moment, in its lane. Returns a cancel. */+export function queueIdlePrefetch(lane: PrefetchLane, href: string, run: () => void): () => void {+ const job = { href, run };+ lanes[lane].add(job);+ if (!flushing) {+ flushing = true;+ whenIdle(flush);+ }+ return () => lanes[lane].delete(job);+}++/**+ * router.prefetch's options. `full`: what <Link prefetch={true}> asks for, the whole page with its URL data (a prerendered+ * page comes from the static cache), rather than only the route's shared shell.+ */+export function prefetchOptions(full: boolean, onInvalidate?: () => void): PrefetchOptions {+ return { kind: full ? "full" : "auto", onInvalidate } as unknown as PrefetchOptions;+}++/**+ * Prefetches `hrefs` once the page has loaded and the browser is idle, also links that are off screen (scrolled out of a+ * phone's tab row, below the sidebar's fold), and again whenever Next says the prefetched copy went stale. A tap then+ * renders from the client cache instead of waiting a round trip.+ */+export function useIdlePrefetch(hrefs: readonly string[] | null, lane: PrefetchLane, full = false): void {+ const router = useRouter();+ const key = hrefs?.join("\n") ?? "";+ useEffect(() => {+ if (!key) return;+ let live = true;+ const cancels: (() => void)[] = [];+ for (const href of key.split("\n")) {+ const run = () => {+ if (live) router.prefetch(href, prefetchOptions(full, () => live && cancels.push(queueIdlePrefetch(lane, href, run))));+ };+ cancels.push(queueIdlePrefetch(lane, href, run));+ }+ return () => {+ live = false;+ for (const cancel of cancels) cancel();+ };+ }, [key, lane, full, router]);+}diff --git a/src/lib/when-idle.ts b/src/lib/when-idle.tsdeleted file mode 100644index f1df5049..00000000--- a/src/lib/when-idle.ts+++ /dev/null@@ -1,45 +0,0 @@-"use client";--import { useSyncExternalStore } from "react";--/** Runs `fn` once the browser is idle after the page has loaded (soon after, where requestIdleCallback is missing). Returns a cancel. */-export function whenIdle(fn: () => void): () => void {- let idle = 0;- let timer = 0;- const schedule = () => {- if (typeof window.requestIdleCallback === "function") idle = window.requestIdleCallback(fn, { timeout: 2000 });- else timer = window.setTimeout(fn, 300);- };- if (document.readyState === "complete") schedule();- else window.addEventListener("load", schedule, { once: true });- return () => {- window.removeEventListener("load", schedule);- if (idle) window.cancelIdleCallback(idle);- if (timer) window.clearTimeout(timer);- };-}--let settled = false;-let started = false;-const listeners = new Set<() => void>();--function subscribe(cb: () => void): () => void {- listeners.add(cb);- if (!started) {- started = true;- whenIdle(() => {- settled = true;- for (const l of listeners) l();- });- }- return () => listeners.delete(cb);-}--/** True once the page has loaded and the browser has had an idle moment (false on the server and while hydrating). */-export function useSettled(): boolean {- return useSyncExternalStore(- subscribe,- () => settled,- () => false,- );-}diff --git a/tests/e2e/instant-tabs.mjs b/tests/e2e/instant-tabs.mjsindex 632bab68..4e09ea48 100644--- a/tests/e2e/instant-tabs.mjs+++ b/tests/e2e/instant-tabs.mjs@@ -5,12 +5,14 @@// desktop, over Chrome's "Fast 4G" preset, so a switch that waits for the server shows up as frames:// 1. Hub tabs (Audio, Video tools, Upscale): the title and the tab row are on screen in every frame, the tapped tab is the// current one within two frames, and the area under the tabs always shows a page or its skeleton, never nothing.-// Both after the page has settled (the tabs prefetched) and straight after load (nothing prefetched yet).+// Both after the page has settled (every mode prefetched: no request on the tap, no skeleton) and straight after load+// (nothing prefetched yet: the skeleton under the tabs may show).// 2. Going back to a mode shows that mode's header controls once (the hidden pages kept for Back add none), and Back marks// the tab of the page it returns to (Audio, the Marketing suite).// 2b. Marketing suite tabs: the tapped tab is current within two frames and the tab row never leaves.// 3. Library sections: the tapped section is selected within two frames, with no request to the server.-// 4. Sidebar (desktop): Image → Audio never blanks the content area, and the hub's tabs are there when it lands.+// 4. Sidebar (desktop): Image → Audio never blanks the content area, the clicked row is marked within two frames, and the+// hub's tabs are there when it lands.import assert from "node:assert/strict";import { DESKTOP, launch, openRoute, PHONE } from "./_browser.mjs";@@ -134,7 +136,7 @@ try {for (const settled of [true, false]) {for (const sw of SWITCHES) {if (!step(`${device}${settled ? "" : ", straight after load"}: ${sw.from} → ${sw.tab}`)) continue;- const { ctx, page } = await context(device);+ const { ctx, page, rsc } = await context(device);if (settled) await openRoute(page, app + sw.from, { settleMs: 4000 });// Straight after load: the page has hydrated (a tap before that is a full page load) and the tabs' prefetches are// still on their way over the throttled network.@@ -142,6 +144,7 @@ try {const tab = page.locator(HUB.bar).getByRole("link", { name: sw.tab, exact: true });await tab.waitFor({ timeout: 30_000 });await tab.scrollIntoViewIfNeeded();+ const before = rsc.length;const frames = await sampleSwitch(page, tab, device, HUB, (f) => f.path === sw.to && f.body > 0 && !f.skeleton);const last = frames[frames.length - 1];check(last.path === sw.to && last.body > 0 && !last.skeleton, `never reached ${sw.to} with its page drawn (last frame ${JSON.stringify(last)})`);@@ -153,6 +156,14 @@ try {check(!blank.length, `the page under the tabs was blank in ${blank.length} frame(s), ${blank[0]?.ms}–${blank[blank.length - 1]?.ms} ms`);const moved = frames.findIndex((f) => f.current === sw.tab);check(moved >= 0 && moved <= 1, `the tapped tab became current only at frame ${moved} (${frames[moved]?.ms} ms)`);+ if (settled) {+ // Once the page has settled every mode is prefetched (ahead of the sidebar's routes): the switch is drawn from the+ // client cache, with no request and no skeleton.+ const asked = rsc.slice(before).filter((r) => !r.prefetch);+ check(!asked.length, `the switch waited for the server: ${asked.map((r) => r.url.replace(app, "")).join(", ")}`);+ const skeleton = frames.filter((f) => f.skeleton);+ check(!skeleton.length, `the skeleton showed in ${skeleton.length} frame(s) though the page had settled`);+ }await ctx.close();}}@@ -231,9 +242,12 @@ try {const { ctx, page } = await context("desktop");await openRoute(page, `${app}/image`, { settleMs: 4000 });const audio = page.locator('[data-sidebar="sidebar"]').getByRole("link", { name: /^Audio$/ }).first();- const frames = await sampleSwitch(page, audio, "desktop", { bar: HUB.bar, body: HUB.body }, (f) => f.path === "/audio" && f.bar && f.body > 0 && !f.skeleton);+ const row = '[data-sidebar="sidebar"] [data-active="true"]';+ const frames = await sampleSwitch(page, audio, "desktop", { bar: HUB.bar, body: HUB.body, current: row }, (f) => f.path === "/audio" && f.bar && f.body > 0 && !f.skeleton);const blank = frames.filter((f) => f.content === 0);check(!blank.length, `the content area was blank in ${blank.length} frame(s), from ${blank[0]?.ms} ms`);+ const moved = frames.findIndex((f) => f.current === "Audio");+ check(moved >= 0 && moved <= 1, `the Audio row became the open page's only at frame ${moved} (${frames[moved]?.ms} ms)`);const last = frames[frames.length - 1];check(last.path === "/audio" && last.bar, `Audio did not land with its tabs (last frame ${JSON.stringify(last)})`);await ctx.close();diff --git a/tests/instant-tabs.test.ts b/tests/instant-tabs.test.tsindex d7b2c174..54ac3d2b 100644--- a/tests/instant-tabs.test.ts+++ b/tests/instant-tabs.test.ts@@ -1,6 +1,6 @@import fs from "node:fs";import path from "node:path";-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import { HUB_MODES, hubOfPath, modeHref, modeOfPath, type HubKind } from "@/lib/hubs";const src = (p: string) => fs.readFileSync(path.join(__dirname, "..", p), "utf8");@@ -45,7 +45,7 @@ describe("hub tabs never leave the screen during a switch", () => {// The tab's <Link> has a bare `prefetch` (prefetch={true}: the whole mode page, not only the route's shared shell).const link = chrome.slice(chrome.indexOf("<Link"), chrome.indexOf("</Link>"));expect(link).toMatch(/^ +prefetch\r?$/m);- expect(chrome).toMatch(/whenIdle\(/);+ expect(chrome).toMatch(/useIdlePrefetch\(\s*modes\.map\(\(m\) => modeHref\(kind, m\.id\)\),\s*"page",\s*true,?\s*\)/);// The tapped tab is marked at once, before the route commits.expect(chrome).toMatch(/useTappedTab<string>\(pathname\)/);expect(chrome).toMatch(/onClick=\{\(e\) => isPlainClick\(e\) && tap\(m\.id\)\}/);@@ -80,11 +80,16 @@ describe("other tab bars switch without a round trip", () => {});it("sidebar rows prefetch once the page is idle, not only on hover or touch", () => {- expect(src("src/components/app-sidebar.tsx")).toMatch(/<IntentLink href=\{item\.href\} eager=\{item\.eager\} settled /);+ const sidebar = src("src/components/app-sidebar.tsx");+ expect(sidebar).toMatch(/<IntentLink\s+href=\{item\.href\}\s+eager=\{item\.eager\}\s+settled\s/);+ // The clicked row is the open page's row from the next frame on, in every group; the address takes over once it moves.+ expect(sidebar).toMatch(/onClick=\{\(e\) => isPlainClick\(e\) && setTappedRow\(item\.href\)\}/);+ expect(sidebar).toMatch(/useLayoutEffect\(\(\) => setTappedRow\(null\), \[pathname, search\]\);/);+ expect(sidebar).toMatch(/const active = navActive\(item\.href, at, where, hrefs\);/);const link = src("src/components/intent-link.tsx");- expect(link).toMatch(/const now = eager \|\| \(settled && idle\);/);- // Also the rows scrolled out of view: prefetched on idle, not when a scroll brings them in front of the tap.- expect(link).toMatch(/if \(settled && idle && href\) router\.prefetch\(href\);/);+ // Also the rows scrolled out of view, in the "nav" lane (after the page's own tabs), not the Link's viewport prefetch.+ expect(link).toMatch(/useIdlePrefetch\(settled && href \? \[href\] : null, "nav"\);/);+ expect(link).toMatch(/prefetch=\{eager \|\| intent \? null : false\}/);});it("a tapped tab is marked before the route commits, and dropped once the route moves or the page is hidden", () => {@@ -124,3 +129,103 @@ describe("other tab bars switch without a round trip", () => {expect(src("src/app/(studio)/loading.tsx")).toMatch(/<StudioRouteSkeleton /);});});++describe("idle prefetches: the page's own tabs go before the sidebar's routes", () => {+ let clock = 0;+ let idle: (() => void)[] = [];+ let observed: ((list: { getEntries(): unknown[] }) => void) | null = null;+ let order: string[] = [];++ async function load() {+ vi.useFakeTimers();+ clock = 0;+ idle = [];+ observed = null;+ order = [];+ vi.stubGlobal("document", { readyState: "complete" });+ vi.stubGlobal("performance", { now: () => clock });+ vi.stubGlobal("window", {+ location: { href: "http://app.test/audio" },+ requestIdleCallback: (fn: () => void) => idle.push(fn),+ cancelIdleCallback: () => {},+ addEventListener: () => {},+ removeEventListener: () => {},+ setTimeout: (fn: () => void, ms: number) => setTimeout(fn, ms),+ clearTimeout: (t: number) => clearTimeout(t),+ });+ vi.stubGlobal(+ "PerformanceObserver",+ class {+ constructor(cb: (list: { getEntries(): unknown[] }) => void) {+ observed = cb;+ }+ observe() {}+ disconnect() {}+ },+ );+ return import("@/lib/idle-prefetch");+ }+ const tick = (ms: number) => {+ for (let i = 0; i < ms; i += 10) {+ clock += 10;+ vi.advanceTimersByTime(10);+ }+ };+ const answered = (path: string) => observed!({ getEntries: () => [{ name: `http://app.test${path}?_rsc=x`, responseEnd: clock }] });++ afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ vi.resetModules();+ });++ it("issues the page's tabs first, and the sidebar's rows once the server has answered every tab and gone quiet", async () => {+ const { queueIdlePrefetch } = await load();+ queueIdlePrefetch("nav", "/image", () => order.push("row image"));+ queueIdlePrefetch("page", "/audio/music", () => order.push("tab music"));+ queueIdlePrefetch("page", "/audio/sfx", () => order.push("tab sfx"));+ const cancel = queueIdlePrefetch("nav", "/gone", () => order.push("row gone"));+ cancel();+ expect(order).toEqual([]);+ expect(idle).toHaveLength(1);+ idle[0]();+ expect(order).toEqual(["tab music", "tab sfx"]);+ answered("/audio/music");+ tick(1000);+ expect(order).toEqual(["tab music", "tab sfx"]);+ answered("/audio/sfx");+ tick(400);+ expect(order).toHaveLength(2);+ tick(200);+ expect(order).toEqual(["tab music", "tab sfx", "row image"]);+ // A page that mounts later (a client navigation into a hub) gets its own idle moment.+ queueIdlePrefetch("page", "/audio/loop", () => order.push("tab loop"));+ expect(idle).toHaveLength(2);+ idle[1]();+ expect(order.at(-1)).toBe("tab loop");+ });++ it("lets the sidebar's rows go after 8 s at the latest", async () => {+ const { queueIdlePrefetch } = await load();+ queueIdlePrefetch("page", "/audio/music", () => order.push("tab music"));+ queueIdlePrefetch("nav", "/image", () => order.push("row image"));+ idle[0]();+ tick(7900);+ expect(order).toEqual(["tab music"]);+ tick(200);+ expect(order).toEqual(["tab music", "row image"]);+ });++ it("with no tabs on the page, prefetches the sidebar's rows at the first idle moment", async () => {+ const { queueIdlePrefetch } = await load();+ queueIdlePrefetch("nav", "/image", () => order.push("row image"));+ idle[0]();+ expect(order).toEqual(["row image"]);+ });++ it("relies on Next serving route trees and shells before any URL-specific part (the phase order of its prefetch queue)", () => {+ const scheduler = fs.readFileSync(path.join(__dirname, "..", "node_modules/next/dist/client/components/segment-cache/scheduler.js"), "utf8");+ const compare = scheduler.slice(scheduler.indexOf("function compareQueuePriority"), scheduler.indexOf("function heapPush"));+ expect(compare).toMatch(/const phaseDiff = b\.phase - a\.phase;/);+ });+});