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(null); const inputRef = useRef(null); const triggerRef = useRef(null); const positions = useRef(new Map()); 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( '[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( '[data-testid="doc-title"]', )?.textContent; router.back(); await wait(150); const backTitle = document.querySelector( '[data-testid="doc-title"]', )?.textContent; const restored = main?.scrollTop ?? 0; router.forward(); await wait(100); const forwardTitle = document.querySelector( '[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( '[data-testid="doc-title"]', )?.textContent; router.navigate("#/docs/missing"); await wait(120); const notFound = document.querySelector( '[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) => ( ); return (
路由与面板 {window.location.protocol}
{ positions.current.set(routeKey, event.currentTarget.scrollTop); }} > {router.route.name === "docs" && activeDoc && (

{activeDoc.title}

{activeDoc.paragraphs.map((paragraph) => (

{paragraph}

))}
当前 hash:{routeKey}
)} {router.route.name === "settings" && (

设置

设置页是路由的一部分;返回应该回到上一页,而不是固定回首页。

{( [ ["compact", "紧凑排版"], ["panel", "显示右侧检查器"], ["reduceMotion", "减少动效"], ] as const ).map(([key, label]) => ( ))}
)} {(route.name === "notfound" || (route.name === "docs" && !activeDoc)) && (

未找到页面

当前 hash `{routeKey}` 没有对应页面。

)}
{panelOpen && ( )}
{paletteOpen && (
{ setQuery(event.target.value); setSelected(0); }} />
    {commands.map((command, index) => (
  • ))} {commands.length === 0 && (
  • 没有匹配的命令
  • )}
↑↓ 选择 · Enter 执行 Esc 关闭
)}
); } declare global { interface Window { __navigate?: (path: string) => void; __back?: () => void; __forward?: () => void; __openPalette?: () => void; __closePalette?: () => void; __setPaletteQuery?: (value: string) => void; __runFirst?: () => void; __prepareShots?: () => Promise; __snapshot?: () => unknown; __smoke?: () => Promise; } }