示例工程 20-routing-and-panels
20-routing-and-panels/app/src/App.tsx
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { hashOf, useRouter } from "./lib/router";
type Doc = {
id: string;
title: string;
group: string;
paragraphs: string[];
};
const docs: Doc[] = [
{
id: "intro",
title: "路由与面板导论",
group: "起步",
paragraphs: [
"桌面应用没有地址栏,但用户仍然需要「我在哪」「怎么回去」这两个问题的答案。Hash 路由给出当前位置,历史栈给出回去的路。",
"本章用三栏布局承载文档、正文与检查器;命令面板把导航与动作收进一个入口;设置页展示「返回」不总是回首页。",
"在打包后的 Electron 里,页面从 file:// 加载。服务端路径式路由会 404,Hash 路由不会改变文件路径,因此是桌面端的稳妥选择。",
"下面的长正文用于测试滚动位置恢复:切到另一页再返回,正文应回到原位置,而不是顶部。",
"回到顶部再读一遍:路由状态应该可观察、可测试、可回退。把这三件事做好,导航就不会变成猜测。",
"为什么不用 History API 的 pushState?在 file:// 下,pushState 的路径无法对应真实文件,刷新或重启后可能 404;Hash 只改片段,文件路径不变。",
"Hash 路由的代价是 URL 不好看,但桌面应用没有地址栏,用户看不到它;内部状态用 hash 表达,开发与调试反而方便。",
"后退与前进要有独立的历史栈,不能只依赖浏览器按钮;本章把栈保存在渲染进程,路由变化时同步 hash。",
"命令面板是导航的补充,不是替代:左侧目录适合浏览,命令面板适合知道名字时的快速跳转。",
"检查器显示当前 route 与协议,是为了让「我在哪」可观察;调试时不用猜 hash 是否更新。",
"设置页与文档页共用同一个内容区,但面包屑与返回语义不同;返回应回到来源页,而不是固定首页。",
"如果用户从命令面板跳到设置,后退应回到跳转前的页面;如果从侧边栏进入,后退应回到上一个文档。",
"滚动位置按 route 保存,返回时恢复;这是长文档的基本体验,不需要引入路由库。",
"无效 hash 显示未找到页,并保留当前历史;不要自动重定向,否则用户不知道发生了什么。",
],
},
{
id: "layout",
title: "三栏布局与检查器",
group: "布局",
paragraphs: [
"左栏是导航,中栏是内容,右栏是检查器。三栏各有独立滚动,不要把整页塞进一个滚动容器。",
"检查器显示当前路由、协议、历史位置与面板开关;它是开发工具,也是用户理解状态的窗口。",
"窄屏时右栏收起,导航变成抽屉;本章只实现收起开关,抽屉留给移动端章节。",
"中栏的宽度用 max-width 限制,长行会影响阅读;代码与表格单独横向滚动。",
],
},
{
id: "commands",
title: "命令面板",
group: "交互",
paragraphs: [
"⌘K / Ctrl+K 打开命令面板,输入过滤,方向键选择,Enter 执行,Esc 关闭。",
"命令既可以是导航(打开某页),也可以是动作(收起检查器、回到导论)。统一入口比散落的按钮更容易发现。",
"打开时焦点进入输入框,关闭时焦点回到触发按钮;这是对话框的基本可访问性要求。",
],
},
];
const commandCatalog = [
...docs.map((doc) => ({
id: `doc-${doc.id}`,
title: `打开:${doc.title}`,
hint: doc.group,
run: (navigate: (path: string) => void) => navigate(`#/docs/${doc.id}`),
})),
{
id: "settings",
title: "打开:设置",
hint: "应用",
run: (navigate: (path: string) => void) => navigate("#/settings"),
},
{
id: "toggle-panel",
title: "动作:切换右侧检查器",
hint: "布局",
run: () => undefined,
},
{
id: "home",
title: "动作:回到导论",
hint: "导航",
run: (navigate: (path: string) => void) => navigate("#/docs/intro"),
},
];
const defaultSettings = { compact: false, panel: true, reduceMotion: false };
export default function App() {
const router = useRouter();
const [paletteOpen, setPaletteOpen] = useState(false);
const [query, setQuery] = useState("");
const [selected, setSelected] = useState(0);
const [panelOpen, setPanelOpen] = useState(true);
const [settings, setSettings] = useState(() => {
try {
const raw = localStorage.getItem("route-lab-settings");
return raw
? { ...defaultSettings, ...(JSON.parse(raw) as object) }
: defaultSettings;
} catch {
return defaultSettings;
}
});
const mainRef = useRef<HTMLDivElement | null>(null);
const inputRef = useRef<HTMLInputElement | null>(null);
const triggerRef = useRef<HTMLButtonElement | null>(null);
const positions = useRef(new Map<string, number>());
const route = router.route;
const routeKey = hashOf(route);
const activeDoc =
route.name === "docs" ? docs.find((doc) => doc.id === route.id) : undefined;
const title =
router.route.name === "settings"
? "设置"
: router.route.name === "notfound"
? "未找到页面"
: (activeDoc?.title ?? "未找到页面");
const commands = useMemo(() => {
const text = query.trim().toLowerCase();
const base = commandCatalog.filter(
(command) =>
text.length === 0 ||
command.title.toLowerCase().includes(text) ||
command.hint.toLowerCase().includes(text),
);
if (panelOpen) {
return base.map((command) =>
command.id === "toggle-panel"
? { ...command, title: "动作:收起右侧检查器" }
: command,
);
}
return base.map((command) =>
command.id === "toggle-panel"
? { ...command, title: "动作:展开右侧检查器" }
: command,
);
}, [panelOpen, query]);
const runCommand = useCallback(
(command: (typeof commandCatalog)[number]) => {
if (command.id === "toggle-panel") {
setPanelOpen((value) => !value);
} else {
command.run(router.navigate);
}
setPaletteOpen(false);
setQuery("");
requestAnimationFrame(() => triggerRef.current?.focus());
},
[router.navigate],
);
useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
const target = event.target as HTMLElement | null;
const editing =
target instanceof HTMLInputElement ||
target instanceof HTMLTextAreaElement;
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
event.preventDefault();
setPaletteOpen((value) => !value);
return;
}
if (event.key === "/" && !editing && !paletteOpen) {
event.preventDefault();
setPaletteOpen(true);
return;
}
if (!paletteOpen) return;
if (event.key === "Escape") {
event.preventDefault();
setPaletteOpen(false);
return;
}
if (event.key === "ArrowDown") {
event.preventDefault();
setSelected((value) => Math.min(commands.length - 1, value + 1));
} else if (event.key === "ArrowUp") {
event.preventDefault();
setSelected((value) => Math.max(0, value - 1));
} else if (event.key === "Enter") {
event.preventDefault();
const command = commands[selected];
if (command) runCommand(command);
}
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [commands, paletteOpen, runCommand, selected]);
useEffect(() => {
if (paletteOpen) {
requestAnimationFrame(() => inputRef.current?.focus());
}
}, [paletteOpen]);
useEffect(() => {
if (!paletteOpen) setSelected(0);
}, [paletteOpen, query]);
useEffect(() => {
const element = mainRef.current;
if (!element) return;
const target = positions.current.get(routeKey) ?? 0;
const frame = requestAnimationFrame(() => {
element.scrollTop = target;
});
return () => cancelAnimationFrame(frame);
}, [routeKey]);
useEffect(() => {
try {
localStorage.setItem("route-lab-settings", JSON.stringify(settings));
} catch {
// 忽略存储失败。
}
}, [settings]);
const toggleSetting = (key: keyof typeof defaultSettings): void => {
setSettings((current) => ({ ...current, [key]: !current[key] }));
};
useEffect(() => {
window.__navigate = (path) => router.navigate(path);
window.__back = () => router.back();
window.__forward = () => router.forward();
window.__openPalette = () => setPaletteOpen(true);
window.__closePalette = () => setPaletteOpen(false);
window.__setPaletteQuery = (value) => {
setQuery(value);
setSelected(0);
};
window.__runFirst = () => {
const command = commands[0];
if (command) runCommand(command);
};
window.__snapshot = () => ({
route: routeKey,
title,
canBack: router.canBack,
canForward: router.canForward,
panelOpen,
paletteOpen,
settings,
});
window.__prepareShots = async () => {
setPanelOpen(true);
router.navigate("#/docs/layout");
};
window.__smoke = async () => {
const wait = (ms: number) =>
new Promise((resolve) => setTimeout(resolve, ms));
router.navigate("#/docs/intro");
await wait(100);
const intro = document.querySelector<HTMLElement>(
'[data-testid="doc-title"]',
)?.textContent;
const main = mainRef.current;
if (main) {
main.scrollTop = 200;
main.dispatchEvent(new Event("scroll", { bubbles: true }));
}
await wait(80);
router.navigate("#/docs/layout");
await wait(100);
const layout = document.querySelector<HTMLElement>(
'[data-testid="doc-title"]',
)?.textContent;
router.back();
await wait(150);
const backTitle = document.querySelector<HTMLElement>(
'[data-testid="doc-title"]',
)?.textContent;
const restored = main?.scrollTop ?? 0;
router.forward();
await wait(100);
const forwardTitle = document.querySelector<HTMLElement>(
'[data-testid="doc-title"]',
)?.textContent;
setPaletteOpen(true);
setQuery("设置");
await wait(120);
const command = commandCatalog.find((item) => item.id === "settings");
if (command) runCommand(command);
await wait(150);
const settingsTitle = document.querySelector<HTMLElement>(
'[data-testid="doc-title"]',
)?.textContent;
router.navigate("#/docs/missing");
await wait(120);
const notFound = document.querySelector<HTMLElement>(
'[data-testid="not-found"]',
)?.textContent;
router.back();
await wait(100);
return {
intro,
layout,
backTitle,
forwardTitle,
settingsTitle,
restored,
notFound,
canForward: router.canForward,
};
};
}, [commands, panelOpen, routeKey, router, runCommand, settings, title]);
const navItem = (doc: Doc) => (
<button
key={doc.id}
className={`flex w-full items-center justify-between rounded-md px-3 py-2 text-left text-sm ${
router.route.name === "docs" && router.route.id === doc.id
? "bg-panel font-medium text-primary"
: "text-muted hover:bg-panel hover:text-text"
}`}
data-testid={`nav-${doc.id}`}
onClick={() => router.navigate(`#/docs/${doc.id}`)}
>
<span>{doc.title}</span>
<span className="text-[10px] text-muted">{doc.group}</span>
</button>
);
return (
<div className={settings.compact ? "h-screen text-sm" : "h-screen"}>
<header className="flex h-14 items-center justify-between border-b border-border px-5">
<div className="flex items-center gap-3">
<span className="font-semibold">路由与面板</span>
<span className="rounded-full border border-border px-2 py-0.5 text-[11px] text-muted">
{window.location.protocol}
</span>
</div>
<div className="flex items-center gap-2">
<button
className="h-8 rounded border border-border px-2 text-xs disabled:opacity-40"
disabled={!router.canBack}
onClick={router.back}
data-testid="back"
>
后退
</button>
<button
className="h-8 rounded border border-border px-2 text-xs disabled:opacity-40"
disabled={!router.canForward}
onClick={router.forward}
data-testid="forward"
>
前进
</button>
<button
ref={triggerRef}
className="h-8 rounded border border-border px-2 text-xs"
onClick={() => setPaletteOpen(true)}
data-testid="palette-trigger"
>
⌘K 搜索
</button>
</div>
</header>
<div
className="grid h-[calc(100vh-3.5rem)]"
style={{
gridTemplateColumns: `220px minmax(0, 1fr) ${
panelOpen ? "260px" : "0px"
}`,
}}
>
<aside className="overflow-auto border-r border-border p-3">
<div className="px-3 py-2 text-[11px] uppercase tracking-wide text-muted">
文档
</div>
{docs.map(navItem)}
<div className="mt-4 px-3 py-2 text-[11px] uppercase tracking-wide text-muted">
应用
</div>
<button
className={`w-full rounded-md px-3 py-2 text-left text-sm ${
router.route.name === "settings"
? "bg-panel font-medium text-primary"
: "text-muted hover:bg-panel"
}`}
data-testid="nav-settings"
onClick={() => router.navigate("#/settings")}
>
设置
</button>
</aside>
<main
ref={mainRef}
className="overflow-auto px-8 py-6"
data-testid="main-scroll"
onScroll={(event) => {
positions.current.set(routeKey, event.currentTarget.scrollTop);
}}
>
<nav className="text-xs text-muted" data-testid="breadcrumb">
{router.route.name === "settings"
? "应用 / 设置"
: router.route.name === "docs"
? `文档 / ${activeDoc?.group ?? "未知"} / ${title}`
: "未找到"}
</nav>
{router.route.name === "docs" && activeDoc && (
<article className="mt-3 max-w-2xl">
<h1 className="text-2xl font-semibold" data-testid="doc-title">
{activeDoc.title}
</h1>
<div className="mt-4 flex flex-col gap-4 text-sm leading-7 text-text">
{activeDoc.paragraphs.map((paragraph) => (
<p key={paragraph}>{paragraph}</p>
))}
</div>
<div className="mt-6 rounded-card border border-border bg-panel p-4 text-xs text-muted">
当前 hash:<code>{routeKey}</code>
</div>
</article>
)}
{router.route.name === "settings" && (
<article className="mt-3 max-w-xl">
<h1 className="text-2xl font-semibold" data-testid="doc-title">
设置
</h1>
<p className="mt-2 text-sm text-muted">
设置页是路由的一部分;返回应该回到上一页,而不是固定回首页。
</p>
<div className="mt-5 flex flex-col gap-3">
{(
[
["compact", "紧凑排版"],
["panel", "显示右侧检查器"],
["reduceMotion", "减少动效"],
] as const
).map(([key, label]) => (
<label
key={key}
className="flex items-center justify-between rounded-card border border-border bg-panel px-4 py-3 text-sm"
>
<span>{label}</span>
<input
type="checkbox"
checked={settings[key]}
onChange={() => toggleSetting(key)}
data-testid={`setting-${key}`}
/>
</label>
))}
</div>
</article>
)}
{(route.name === "notfound" ||
(route.name === "docs" && !activeDoc)) && (
<div className="mt-10 max-w-xl rounded-card border border-border bg-panel p-6">
<h1 className="text-xl font-semibold" data-testid="doc-title">
未找到页面
</h1>
<p className="mt-2 text-sm text-muted" data-testid="not-found">
当前 hash `{routeKey}` 没有对应页面。
</p>
<button
className="mt-4 rounded-card bg-primary px-3 py-1.5 text-sm text-primary-foreground"
onClick={() => router.navigate("#/docs/intro")}
>
回到导论
</button>
</div>
)}
</main>
{panelOpen && (
<aside
className="overflow-auto border-l border-border p-4 text-xs"
data-testid="inspector"
>
<div className="font-semibold text-text">检查器</div>
<dl className="mt-3 flex flex-col gap-2">
<div className="flex justify-between gap-2">
<dt className="text-muted">route</dt>
<dd>
<code data-testid="inspector-route">{routeKey}</code>
</dd>
</div>
<div className="flex justify-between gap-2">
<dt className="text-muted">protocol</dt>
<dd>
<code>{window.location.protocol}</code>
</dd>
</div>
<div className="flex justify-between gap-2">
<dt className="text-muted">canBack</dt>
<dd>{String(router.canBack)}</dd>
</div>
<div className="flex justify-between gap-2">
<dt className="text-muted">canForward</dt>
<dd>{String(router.canForward)}</dd>
</div>
</dl>
<p className="mt-4 text-muted">
打包后协议是 file:;Hash 不改变文件路径,因此不会 404。
</p>
<button
className="mt-4 w-full rounded border border-border px-2 py-1.5"
onClick={() => setPanelOpen(false)}
data-testid="close-panel"
>
收起检查器
</button>
</aside>
)}
</div>
{paletteOpen && (
<div
className="fixed inset-0 z-50 flex items-start justify-center bg-black/30 pt-24"
role="dialog"
aria-modal="true"
aria-label="命令面板"
data-testid="palette"
>
<div className="w-[520px] overflow-hidden rounded-card border border-border bg-surface shadow-xl">
<input
ref={inputRef}
className="w-full border-b border-border bg-surface px-4 py-3 text-sm outline-none"
placeholder="输入命令或页面名…"
value={query}
data-testid="palette-input"
onChange={(event) => {
setQuery(event.target.value);
setSelected(0);
}}
/>
<ul className="max-h-72 overflow-auto p-1">
{commands.map((command, index) => (
<li key={command.id}>
<button
className={`flex w-full items-center justify-between rounded-md px-3 py-2 text-left text-sm ${
index === selected
? "bg-primary-soft text-primary"
: "text-text hover:bg-panel"
}`}
data-testid={`palette-item-${command.id}`}
onMouseEnter={() => setSelected(index)}
onClick={() => runCommand(command)}
>
<span>{command.title}</span>
<span className="text-[10px] text-muted">
{command.hint}
</span>
</button>
</li>
))}
{commands.length === 0 && (
<li className="px-3 py-6 text-center text-sm text-muted">
没有匹配的命令
</li>
)}
</ul>
<div className="flex justify-between border-t border-border px-3 py-2 text-[11px] text-muted">
<span>↑↓ 选择 · Enter 执行</span>
<span>Esc 关闭</span>
</div>
</div>
</div>
)}
</div>
);
}
declare global {
interface Window {
__navigate?: (path: string) => void;
__back?: () => void;
__forward?: () => void;
__openPalette?: () => void;
__closePalette?: () => void;
__setPaletteQuery?: (value: string) => void;
__runFirst?: () => void;
__prepareShots?: () => Promise<void>;
__snapshot?: () => unknown;
__smoke?: () => Promise<unknown>;
}
}