From 314c615c008d26087b4d61fc438b219fb2edfbed Mon Sep 17 00:00:00 2001 From: WishForge Agent Date: Tue, 27 Oct 2026 15:12:24 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20WishForge=20checkpoint=20ee35e3fd-c?= =?UTF-8?q?d62-421e-8ff1-a222130f2b2f?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/App.tsx | 33 ++++++- src/components/Sidebar.tsx | 15 +++- src/lib/route-preload.js | 123 ++++++++++++++++++++++++++ tests/frontend/route-preload.test.mjs | 100 +++++++++++++++++++++ 4 files changed, 267 insertions(+), 4 deletions(-) create mode 100644 src/lib/route-preload.js create mode 100644 tests/frontend/route-preload.test.mjs diff --git a/src/App.tsx b/src/App.tsx index 16b961da..121a28bd 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -8,6 +8,7 @@ import { BrowserRouter as Router, Routes, Route } from "react-router-dom"; import { Layout } from "./components/Layout"; import { TimeZoneProvider } from "./context/TimeZoneContext"; import { UserProvider } from "./context/UserContext"; +import { memoizeRouteLoader, registerRoutePreload } from "./lib/route-preload.js"; type LazyRouteModule = { default: React.ComponentType }; @@ -60,9 +61,10 @@ class RouteErrorBoundary extends React.Component<{ children: React.ReactNode }, } } -const lazyRoute = (loader: () => Promise) => - lazy(() => - loader().catch((error) => { +const lazyRoute = (loader: () => Promise) => { + const load = memoizeRouteLoader(loader) as () => Promise; + const component = lazy(() => + load().catch((error) => { console.error("Route chunk load failed", error); if ( routeChunkErrorPattern.test(String(error?.message || error || "")) && @@ -74,6 +76,8 @@ const lazyRoute = (loader: () => Promise) => return { default: RouteLoadError }; }), ); + return Object.assign(component, { preload: load }); +}; const Dashboard = lazyRoute(() => import("./pages/Dashboard")); const Projects = lazyRoute(() => import("./pages/Projects")); @@ -92,6 +96,29 @@ const ObjectStorageBrowser = lazyRoute(() => import("./pages/ObjectStorageBrowse const ObjectSync = lazyRoute(() => import("./pages/ObjectSync")); const Sampling = lazyRoute(() => import("./pages/Sampling")); +const routeTable = [ + { path: "/", Page: Dashboard }, + { path: "/projects", Page: Projects }, + { path: "/project/:id", Page: ProjectDetail }, + { path: "/operators", Page: Operators }, + { path: "/workflow/:id", Page: WorkflowEditor }, + { path: "/data-assets", Page: DataAssets }, + { path: "/data-operations", Page: DataOperations }, + { path: "/database", Page: DatabaseBrowser }, + { path: "/object-storage", Page: ObjectStorageBrowser }, + { path: "/object-sync", Page: ObjectSync }, + { path: "/sampling", Page: Sampling }, + { path: "/monitoring", Page: Monitoring }, + { path: "/audit", Page: Audit }, + { path: "/settings", Page: Settings }, + { path: "/templates", Page: Templates }, + { path: "/users", Page: Users }, +]; + +for (const { path, Page } of routeTable) { + registerRoutePreload(path, Page.preload); +} + function RouteFallback() { return
正在加载页面...
; } diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx index 8e4cf833..9f99d396 100644 --- a/src/components/Sidebar.tsx +++ b/src/components/Sidebar.tsx @@ -1,5 +1,5 @@ import React, { useEffect, useMemo, useState } from "react"; -import { NavLink } from "react-router-dom"; +import { NavLink, useLocation } from "react-router-dom"; import { Logo } from "./Logo"; import { useUser } from "../context/UserContext"; import { @@ -29,6 +29,7 @@ import { import { cn } from "../lib/utils"; import { getActionErrorMessage } from "../lib/action-errors.js"; import { getUserRoleLabel } from "../lib/user-roles"; +import { preloadRoute, scheduleIdleRoutePreload } from "../lib/route-preload.js"; const navItems = [ { @@ -117,6 +118,15 @@ export function Sidebar({ isCollapsed, onToggle }: SidebarProps) { return navItems.filter((item) => item.roles.includes(role)); }, [role]); + const { pathname } = useLocation(); + // Warm up the remaining navigable pages in the background once the current + // page has settled; hover/focus below covers anything not fetched yet. + useEffect(() => { + const paths = filteredNavItems.map((item) => item.path).filter((path) => path !== pathname); + return scheduleIdleRoutePreload(paths, preloadRoute); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [filteredNavItems]); + const handleSaveProfile = async (event: React.FormEvent) => { event.preventDefault(); if (!profileDraft) { @@ -169,6 +179,9 @@ export function Sidebar({ isCollapsed, onToggle }: SidebarProps) { key={item.path} to={item.path} title={isCollapsed ? item.label : undefined} + onMouseEnter={() => void preloadRoute(item.path)} + onFocus={() => void preloadRoute(item.path)} + onTouchStart={() => void preloadRoute(item.path)} className={({ isActive }) => cn( "flex items-center gap-3 px-3 py-2 rounded-md text-sm font-medium transition-colors", diff --git a/src/lib/route-preload.js b/src/lib/route-preload.js new file mode 100644 index 00000000..4fea838f --- /dev/null +++ b/src/lib/route-preload.js @@ -0,0 +1,123 @@ +// Route chunk preloading. Lazy routes share a memoized loader with this +// registry, so a chunk fetched on hover or idle is reused by React.lazy and +// the navigation renders without waiting on the network. + +export function memoizeRouteLoader(loader) { + let pending = null; + return () => { + if (!pending) { + pending = Promise.resolve() + .then(loader) + .catch((error) => { + // Drop failed attempts so the next preload or render retries. + pending = null; + throw error; + }); + } + return pending; + }; +} + +export function matchRoutePattern(pattern, path) { + const cleanPath = String(path || "").split(/[?#]/)[0]; + const patternSegments = String(pattern || "").split("/").filter(Boolean); + const pathSegments = cleanPath.split("/").filter(Boolean); + if (patternSegments.length !== pathSegments.length) { + return false; + } + return patternSegments.every((segment, index) => segment.startsWith(":") || segment === pathSegments[index]); +} + +export function createRoutePreloadRegistry() { + const entries = []; + + const register = (pattern, loader) => { + const existing = entries.find((entry) => entry.pattern === pattern); + if (existing) { + existing.loader = loader; + } else { + entries.push({ pattern, loader }); + } + }; + + const preload = (path) => { + const entry = entries.find((candidate) => matchRoutePattern(candidate.pattern, path)); + if (!entry) { + return Promise.resolve(false); + } + return Promise.resolve() + .then(entry.loader) + .then( + () => true, + // Preloading is best effort; the real navigation reports load errors. + () => false, + ); + }; + + return { register, preload }; +} + +export function shouldSkipIdlePreload(nav = globalThis.navigator) { + const connection = nav?.connection; + if (!connection) { + return false; + } + return Boolean(connection.saveData) || /(^|-)2g$/.test(String(connection.effectiveType || "")); +} + +// Preloads routes one at a time while the browser is idle so background +// chunk downloads never compete with the current page's own requests. +export function scheduleIdleRoutePreload(paths, preload, options = {}) { + const win = options.win ?? globalThis; + const initialDelay = options.initialDelay ?? 1500; + const queue = [...new Set(paths)]; + let cancelled = false; + let timer = null; + let idleHandle = null; + + if (!queue.length || shouldSkipIdlePreload(win.navigator)) { + return () => {}; + } + + const whenIdle = (callback) => { + if (typeof win.requestIdleCallback === "function") { + idleHandle = win.requestIdleCallback(callback, { timeout: 3000 }); + } else { + timer = win.setTimeout(callback, 200); + } + }; + + const next = () => { + if (cancelled || !queue.length) { + return; + } + whenIdle(() => { + idleHandle = null; + timer = null; + if (cancelled) { + return; + } + preload(queue.shift()).finally(next); + }); + }; + + timer = win.setTimeout(() => { + timer = null; + next(); + }, initialDelay); + + return () => { + cancelled = true; + if (timer !== null) { + win.clearTimeout(timer); + } + if (idleHandle !== null && typeof win.cancelIdleCallback === "function") { + win.cancelIdleCallback(idleHandle); + } + }; +} + +const routePreloads = createRoutePreloadRegistry(); + +export const registerRoutePreload = routePreloads.register; +export const preloadRoute = routePreloads.preload; diff --git a/tests/frontend/route-preload.test.mjs b/tests/frontend/route-preload.test.mjs new file mode 100644 index 00000000..14cd7ad0 --- /dev/null +++ b/tests/frontend/route-preload.test.mjs @@ -0,0 +1,100 @@ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import test from "node:test"; + +import { + createRoutePreloadRegistry, + matchRoutePattern, + memoizeRouteLoader, + scheduleIdleRoutePreload, + shouldSkipIdlePreload, +} from "../../src/lib/route-preload.js"; + +const appURL = new URL("../../src/App.tsx", import.meta.url); +const sidebarURL = new URL("../../src/components/Sidebar.tsx", import.meta.url); + +test("memoized route loader shares one in-flight import and retries after failure", async () => { + let calls = 0; + let fail = true; + const load = memoizeRouteLoader(async () => { + calls += 1; + if (fail) { + throw new Error("Failed to fetch dynamically imported module"); + } + return { default: "Page" }; + }); + + await assert.rejects(Promise.all([load(), load()])); + assert.equal(calls, 1); + + fail = false; + assert.deepEqual(await load(), { default: "Page" }); + await load(); + assert.equal(calls, 2); +}); + +test("route patterns match dynamic segments and ignore query strings", () => { + assert.equal(matchRoutePattern("/", "/"), true); + assert.equal(matchRoutePattern("/project/:id", "/project/abc?tab=runs"), true); + assert.equal(matchRoutePattern("/project/:id", "/projects"), false); + assert.equal(matchRoutePattern("/projects", "/projects/"), true); +}); + +test("registry preloads matching routes and swallows load errors", async () => { + const registry = createRoutePreloadRegistry(); + const loaded = []; + registry.register("/monitoring", async () => loaded.push("monitoring")); + registry.register("/broken", async () => { + throw new Error("boom"); + }); + + assert.equal(await registry.preload("/monitoring"), true); + assert.equal(await registry.preload("/broken"), false); + assert.equal(await registry.preload("/unknown"), false); + assert.deepEqual(loaded, ["monitoring"]); +}); + +test("idle preload runs sequentially and can be cancelled", async () => { + const timers = []; + const win = { + navigator: {}, + setTimeout: (callback) => timers.push(callback) && timers.length, + clearTimeout: () => {}, + }; + const preloaded = []; + const preload = async (path) => { + preloaded.push(path); + return true; + }; + + const cancel = scheduleIdleRoutePreload(["/a", "/b", "/a"], preload, { win }); + const flush = async () => { + while (timers.length) { + timers.shift()(); + await new Promise((resolve) => setImmediate(resolve)); + } + }; + + timers.shift()(); + timers.shift()(); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(preloaded, ["/a"]); + cancel(); + await flush(); + assert.deepEqual(preloaded, ["/a"]); +}); + +test("idle preload is skipped on data-saver or 2g connections", () => { + assert.equal(shouldSkipIdlePreload({ connection: { saveData: true } }), true); + assert.equal(shouldSkipIdlePreload({ connection: { effectiveType: "slow-2g" } }), true); + assert.equal(shouldSkipIdlePreload({ connection: { effectiveType: "4g" } }), false); + assert.equal(shouldSkipIdlePreload({}), false); +}); + +test("lazy routes register for preloading and sidebar links warm them up", async () => { + const [app, sidebar] = await Promise.all([readFile(appURL, "utf8"), readFile(sidebarURL, "utf8")]); + assert.match(app, /registerRoutePreload\(path, Page\.preload\)/); + assert.match(app, /memoizeRouteLoader\(loader\)/); + assert.match(sidebar, /onMouseEnter=\{\(\) => void preloadRoute\(item\.path\)\}/); + assert.match(sidebar, /scheduleIdleRoutePreload\(paths, preloadRoute\)/); +});