forked from longtao.wu/droboticflow
✨ WishForge checkpoint ee35e3fd-cd62-421e-8ff1-a222130f2b2f
This commit is contained in:
parent
f00e9b9506
commit
314c615c00
33
src/App.tsx
33
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<LazyRouteModule>) =>
|
||||
lazy(() =>
|
||||
loader().catch((error) => {
|
||||
const lazyRoute = (loader: () => Promise<LazyRouteModule>) => {
|
||||
const load = memoizeRouteLoader(loader) as () => Promise<LazyRouteModule>;
|
||||
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<LazyRouteModule>) =>
|
||||
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 <div className="flex min-h-[320px] items-center justify-center text-sm text-slate-400">正在加载页面...</div>;
|
||||
}
|
||||
|
||||
@ -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",
|
||||
|
||||
123
src/lib/route-preload.js
Normal file
123
src/lib/route-preload.js
Normal file
@ -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;
|
||||
100
tests/frontend/route-preload.test.mjs
Normal file
100
tests/frontend/route-preload.test.mjs
Normal file
@ -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\)/);
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user