diff --git a/package.json b/package.json index 585ebe93..9759ed08 100644 --- a/package.json +++ b/package.json @@ -22,6 +22,7 @@ "@tauri-apps/api": "^2.9.0", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", + "cmdk": "^1.1.1", "date-fns": "^4.4.0", "lucide-react": "^1.45.0", "radix-ui": "^1.6.7", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 76ae4e4e..02952a4f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -38,6 +38,9 @@ importers: clsx: specifier: ^2.1.1 version: 2.1.1 + cmdk: + specifier: ^1.1.1 + version: 1.1.1(@types/react-dom@19.2.7(@types/react@19.2.18))(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) date-fns: specifier: ^4.4.0 version: 4.4.0 @@ -1784,6 +1787,12 @@ packages: resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} engines: {node: '>=6'} + cmdk@1.1.1: + resolution: {integrity: sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg==} + peerDependencies: + react: ^18 || ^19 || ^19.0.0-rc + react-dom: ^18 || ^19 || ^19.0.0-rc + cn@0.2.6: resolution: {integrity: sha512-+i4L0zUGgRcEnhsxueVrP7iBGxBx5iD0WOTYg1MwFEu2ZyCmH5Ov2V1cul2Ht5UchRQQgftCf4be/RxspuW6QQ==} engines: {node: '>=20'} @@ -4859,6 +4868,18 @@ snapshots: clsx@2.1.1: {} + cmdk@1.1.1(@types/react-dom@19.2.7(@types/react@19.2.18))(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react@19.2.8): + dependencies: + '@radix-ui/react-compose-refs': 1.1.5(@types/react@19.2.18)(react@19.2.8) + '@radix-ui/react-dialog': 1.1.23(@types/react-dom@19.2.7(@types/react@19.2.18))(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) + '@radix-ui/react-id': 1.1.4(@types/react@19.2.18)(react@19.2.8) + '@radix-ui/react-primitive': 2.1.10(@types/react-dom@19.2.7(@types/react@19.2.18))(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) + react: 19.2.8 + react-dom: 19.2.8(react@19.2.8) + transitivePeerDependencies: + - '@types/react' + - '@types/react-dom' + cn@0.2.6: {} code-block-writer@13.0.3: {} diff --git a/src/App.tsx b/src/App.tsx index 1cf202a4..bd531b44 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,7 +1,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { invoke } from "@tauri-apps/api/core"; import { listen } from "@tauri-apps/api/event"; -import { FileCodeIcon, HistoryIcon, RotateCwIcon, SearchIcon } from "lucide-react"; +import { SearchIcon } from "lucide-react"; import { call } from "@/control"; import { useRequests } from "./useRequests"; import { useStableState } from "./useStable"; @@ -31,9 +31,8 @@ import { IconRoute, IconServer, IconSettings, - IconSidebar, } from "./ui/icons"; -import { isMac, isMod, modKey } from "@/platform"; +import { isMac, isMod } from "@/platform"; import Dashboard from "./Dashboard"; import type { CoreStatus, Overview } from "./types"; import { stageLabel } from "./labels"; @@ -42,7 +41,6 @@ import { commonText } from "@/i18n/common.i18n"; import { appText } from "./App.i18n"; import { Button } from "@/ui/button"; import type { LucideIcon } from "lucide-react"; -import { Kbd, KbdGroup } from "@/ui/kbd"; import { Toaster } from "@/ui/sonner"; import { coreText, errorText } from "@/i18n/core.i18n"; import { trouble } from "./launch/trouble"; @@ -58,10 +56,11 @@ import { Banner } from "@/ui/banner"; import { Reveal } from "@/ui/motion"; import { Page, PageHeader, PageTitleContext } from "@/ui/page"; import { ErrorState, TableSkeleton } from "@/ui/states"; -import { resetResources } from "@/lib/resource"; +import { invalidateAll, resetResources } from "@/lib/resource"; import { cn } from "@/lib/utils"; -import { CommandPalette, type Command } from "./CommandPalette"; -import { paletteText } from "./CommandPalette.i18n"; +import { Palette } from "./palette/Palette"; +import { paletteText } from "./palette/palette.i18n"; +import { COMBOS, Keys, isTyping, modalOpen, pageCombo } from "./palette/keys"; import { Sidebar, SidebarContent, @@ -163,11 +162,6 @@ const SOURCES: { group: string; items: { id: Surface; icon: LucideIcon }[] }[] = }, ]; -const ICONS = Object.fromEntries(SOURCES.flatMap((g) => g.items.map((it) => [it.id, it.icon]))) as Record< - Surface, - LucideIcon ->; - /** * core 的状态说成人话。 * @@ -344,6 +338,11 @@ function Shell({ first }: { first: boolean }) { // ⌘R 和配置改动之后立刻重读一次。等下一次事件的话,刚点完「保存」还看着旧值 const [nudge, setNudge] = useState(0); + /** ⌘R、命令面板的「刷新数据」:状态和概览重读,眼前这一页的数据也重取 */ + const refreshAll = useCallback(() => { + setNudge((n) => n + 1); + invalidateAll(); + }, []); /** * 概览页什么时候重新拉数。**不是定时轮询**:跟着对账走,`settled` 每涨一次说明库里 * 确实多了东西(见 useRequests);`nudge` 是手动刷新。都没动的时候一次请求都不发。 @@ -356,6 +355,8 @@ function Shell({ first }: { first: boolean }) { const [configFile, setConfigFile] = useState<{ focus: string | null } | null>(null); const [historyOpen, setHistoryOpen] = useState(false); const [palette, setPalette] = useState(false); + /** 快捷键一览(`?`,或者命令面板左下角) */ + const [shortcuts, setShortcuts] = useState(false); /** * 源列表收起还是展开。**记住用户的选择**;读取放在初始化里而不是 effect 里,否则 @@ -426,14 +427,20 @@ function Shell({ first }: { first: boolean }) { /** * 全局快捷键。**在「正在输入」判断之前处理** —— ⌘F 的全部意义就是从任何地方跳到 * 搜索框,在输入框里按它该重选。行内的方向键导航在流量页里(`TrafficPage`)。 + * 键位和界面上显示的键帽在 `palette/keys.tsx`,改一边要改另一边。 * * · ⌘K 命令面板 · ⌘1…⌘9 按源列表的顺序换页 · ⌘F 流量搜索 · ⌘, 设置 · ⌘R 刷新 + * · `?` 快捷键一览(在打字时不接管) * · ⌘⌥S 收起/展开源列表(访达、邮件、备忘录都是这个键;判 `code` 不判 `key`: * ⌥ 会把 s 变成 ß)。**只在 macOS 上有**:Windows 上 Ctrl+Alt 常是 AltGr, * Linux 上 Ctrl+Alt 加字母常被桌面拿去。那两边用 Ctrl+B(`SidebarProvider` 在听)。 * + * **开着编辑、确认这类对话框时不换页、不开面板**:对话框里可能是改了一半的表单, + * 页面一换就没了(`modalOpen`;命令面板、快捷键一览、右侧的请求详情不算)。换页时 + * 顺手关掉面板和一览 —— 在面板里按 ⌘2、看着一览按 ⌘4 也是换页。 + * * Windows 上是 Ctrl 加同一个键;`preventDefault` 在那边更要紧:WebView2 自己会把 - * Ctrl+F 当成页内查找、Ctrl+R 当成刷新页面。 + * Ctrl+F 当成页内查找、Ctrl+R 当成刷新页面。所以对话框开着时键照样吞掉,只是不做事。 */ useEffect(() => { const onKey = (e: KeyboardEvent) => { @@ -442,10 +449,24 @@ function Shell({ first }: { first: boolean }) { setRailOpen((v) => !v); return; } + if (e.key === "?" && !e.metaKey && !e.ctrlKey && !e.altKey) { + if (e.defaultPrevented || isTyping(e.target) || modalOpen()) return; + e.preventDefault(); + setShortcuts(true); + return; + } if (!isMod(e) || e.altKey) return; const k = e.key.toLowerCase(); + const busy = modalOpen(); + const go = (s: S, params?: NavParams[S]) => { + setPalette(false); + setShortcuts(false); + open(s, params); + }; if (k === "k" && !e.shiftKey) { e.preventDefault(); + if (busy) return; + setShortcuts(false); setPalette((v) => !v); return; } @@ -453,27 +474,27 @@ function Shell({ first }: { first: boolean }) { const s = SURFACES[Number(e.key) - 1]; if (!s) return; e.preventDefault(); - if (linked || s === "settings") open(s); + if (!busy && (linked || s === "settings")) go(s); return; } if (k === "f") { e.preventDefault(); - if (linked) open("requests", { search: true }); + if (!busy && linked) go("requests", { search: true }); return; } if (k === ",") { e.preventDefault(); - open("settings"); + if (!busy) go("settings"); return; } if (k === "r") { e.preventDefault(); - setNudge((n) => n + 1); + refreshAll(); } }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); - }, [linked, open]); + }, [linked, open, refreshAll]); /** * 守护状态。**推过来的,不是问出来的。**先挂监听再读一次当前值,顺序不能反: @@ -594,60 +615,17 @@ function Shell({ first }: { first: boolean }) { const openConfigFile = useCallback((focus: string | null) => setConfigFile({ focus }), []); const go = useCallback((to: string) => open(to as Surface), [open]); - /** ⌘K 里的条目:各页,加几个全局动作 */ - const commands = useMemo(() => { - const zh = appText.zh.surfaces; - const en = appText.en.surfaces; - const pages: Command[] = SURFACES.map((s, i) => { - const Icon = ICONS[s]; - return { - id: s, - group: "pages", - label: t.surfaces[s], - keywords: `${zh[s]} ${en[s]}`, - icon: , - shortcut: [modKey, `${i + 1}`], - disabled: !linked && s !== "settings", - run: () => open(s), - }; - }); - const actions: Command[] = [ - { - id: "config-file", - group: "actions", - label: t.configFile, - keywords: "config.yaml", - icon: , - disabled: !linked, - run: () => setConfigFile({ focus: null }), - }, - { - id: "version-history", - group: "actions", - label: t.versionHistory, - icon: , - disabled: !linked, - run: () => setHistoryOpen(true), - }, - { - id: "refresh", - group: "actions", - label: pt.refresh, - icon: , - shortcut: [modKey, "R"], - run: () => setNudge((n) => n + 1), - }, - { - id: "rail", - group: "actions", - label: railOpen ? t.collapseRail : t.expandRail, - icon: , - shortcut: isMac ? ["⌘", "⌥", "S"] : ["Ctrl", "B"], - run: () => setRailOpen((v) => !v), - }, - ]; - return [...pages, ...actions]; - }, [t, pt, linked, open, railOpen]); + /** 命令面板里只有外壳做得了的几件事。**引用不变**:面板按它们建条目,变了就要重建 */ + const paletteShell = useMemo( + () => ({ + toggleRail: () => setRailOpen((v) => !v), + refresh: refreshAll, + configFile: () => setConfigFile({ focus: null }), + history: () => setHistoryOpen(true), + notices: () => setNoticesAsked((n) => n + 1), + }), + [refreshAll], + ); /** 还没取到概览时的占位:页头照常,内容是表格骨架;读失败了是「读取失败」和重试 */ const skeleton = ( @@ -702,6 +680,8 @@ function Shell({ first }: { first: boolean }) { {g.items.map((it) => { const on = tab === it.id; + /** 在源列表里排第几,⌘1…⌘9 按它数 */ + const index = SURFACES.indexOf(it.id); // 客户端配置里出现了新东西:挂个角标,直到去看过 const badge = it.id === "mcp" ? alerts.length : 0; const Icon = it.icon; @@ -715,7 +695,19 @@ function Shell({ first }: { first: boolean }) { isActive={on} onClick={() => open(it.id)} aria-current={on ? "page" : undefined} - tooltip={badge > 0 ? t.newFindings(label, badge) : label} + /* + 悬浮说明写上这一页的快捷键。**展开时也显示**(shadcn 默认只在收起时 + 显示):名字看得见,但 ⌘1…⌘9 只有在这里才学得到 + */ + tooltip={{ + hidden: false, + children: ( + <> + {badge > 0 ? t.newFindings(label, badge) : label} + + + ), + }} className={cn( "h-7 gap-2.5 px-2 text-(--chrome-text) transition-colors duration-(--motion-fast)", "hover:bg-(--chrome-hover) hover:text-(--chrome-strong) active:bg-(--chrome-selected)", @@ -784,18 +776,7 @@ function Shell({ first }: { first: boolean }) { text={ <> {railOpen ? t.collapseRail : t.expandRail} - {isMac ? ( - - ⌘ - ⌥ - S - - ) : ( - - Ctrl - B - - )} + } > @@ -844,10 +825,7 @@ function Shell({ first }: { first: boolean }) { text={ <> {pt.title} - - {modKey} - K - + } > @@ -1081,7 +1059,19 @@ function Shell({ first }: { first: boolean }) { /> )} {historyOpen && setHistoryOpen(false)} />} - + {/* **所有出错都走这里**(`notify`)。吐司统一在右下角,谁触发的都一样;状态类的 事走横幅,不走吐司。 diff --git a/src/CommandPalette.i18n.ts b/src/CommandPalette.i18n.ts deleted file mode 100644 index e77698f3..00000000 --- a/src/CommandPalette.i18n.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { messages } from "@/i18n"; - -/** ⌘K 的命令面板 */ -export const paletteText = messages( - { - title: "命令", - placeholder: "搜索页面和操作", - pages: "页面", - actions: "操作", - none: "无匹配项", - refresh: "刷新数据", - open: "打开", - move: "选择", - }, - { - title: "Commands", - placeholder: "Search pages and actions", - pages: "Pages", - actions: "Actions", - none: "No matches", - refresh: "Refresh data", - open: "Open", - move: "Select", - }, -); diff --git a/src/CommandPalette.tsx b/src/CommandPalette.tsx deleted file mode 100644 index 44ae339d..00000000 --- a/src/CommandPalette.tsx +++ /dev/null @@ -1,172 +0,0 @@ -import { useEffect, useMemo, useRef, useState, type ReactNode } from "react"; -import { SearchIcon } from "lucide-react"; -import { cn } from "@/lib/utils"; -import { isMac } from "@/platform"; -import { useText } from "@/i18n"; -import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/ui/dialog"; -import { Kbd, KbdGroup } from "@/ui/kbd"; -import { paletteText } from "./CommandPalette.i18n"; - -/** 面板里的一项:一页或一个动作 */ -export interface Command { - id: string; - group: "pages" | "actions"; - label: string; - /** 另一种语言的名字、别名:搜索时也比对,显示时不出现 */ - keywords?: string; - icon?: ReactNode; - /** 右侧的键帽,比如 ⌘1 */ - shortcut?: string[]; - disabled?: boolean; - run: () => void; -} - -/** - * ⌘K 的命令面板:输入几个字,回车跳到那一页或执行那个动作。 - * - * **只做导航和少数几个全局动作**,不做每一页的每一个按钮 —— 那些在页面上, - * 面板里放一份就是两套入口要一起维护。键盘:↑↓ 选、回车执行、Esc 关闭。 - */ -export function CommandPalette({ - open, - onOpenChange, - commands, -}: { - open: boolean; - onOpenChange: (open: boolean) => void; - commands: Command[]; -}) { - const t = useText(paletteText); - const [q, setQ] = useState(""); - const [at, setAt] = useState(0); - const listRef = useRef(null); - - useEffect(() => { - if (open) { - setQ(""); - setAt(0); - } - }, [open]); - - const shown = useMemo(() => { - const needle = q.trim().toLowerCase(); - const ok = commands.filter((c) => !c.disabled); - if (!needle) return ok; - return ok.filter((c) => `${c.label} ${c.keywords ?? ""} ${c.id}`.toLowerCase().includes(needle)); - }, [commands, q]); - - useEffect(() => { - setAt((i) => Math.min(i, Math.max(0, shown.length - 1))); - }, [shown.length]); - - useEffect(() => { - listRef.current?.querySelector(`[data-index="${at}"]`)?.scrollIntoView({ block: "nearest" }); - }, [at]); - - const run = (c: Command | undefined) => { - if (!c) return; - onOpenChange(false); - // 关掉面板之后再动:对话框的焦点归还和新页面挂上不要挤在同一帧 - setTimeout(c.run, 0); - }; - - const groups: { key: Command["group"]; title: string }[] = [ - { key: "pages", title: t.pages }, - { key: "actions", title: t.actions }, - ]; - - return ( - - { - if (e.key === "ArrowDown" || e.key === "ArrowUp") { - e.preventDefault(); - const d = e.key === "ArrowDown" ? 1 : -1; - setAt((i) => (shown.length === 0 ? 0 : (i + d + shown.length) % shown.length)); - } else if (e.key === "Enter" && !e.nativeEvent.isComposing) { - e.preventDefault(); - run(shown[at]); - } - }} - > - {t.title} - {t.placeholder} -
- - { - setQ(e.target.value); - setAt(0); - }} - placeholder={t.placeholder} - spellCheck={false} - aria-label={t.placeholder} - className="h-full min-w-0 flex-1 bg-transparent tw-body outline-none placeholder:text-muted-foreground" - /> -
-
- {shown.length === 0 &&

{t.none}

} - {groups.map((g) => { - const items = shown.filter((c) => c.group === g.key); - if (items.length === 0) return null; - return ( -
-

{g.title}

- {items.map((c) => { - const i = shown.indexOf(c); - return ( -
setAt(i)} - onClick={() => run(c)} - className={cn( - "flex h-8 cursor-default items-center gap-2.5 rounded-md px-2.5 tw-body select-none", - i === at ? "bg-accent text-accent-foreground" : "text-foreground", - )} - > - - {c.icon} - - {c.label} - {/* macOS 上组合键写在一个键帽里(⌘1),和系统菜单一样;别的平台分开写 */} - {c.shortcut && - (isMac ? ( - {c.shortcut.join("")} - ) : ( - - {c.shortcut.map((k) => ( - {k} - ))} - - ))} -
- ); - })} -
- ); - })} -
-
- - - ↑ - ↓ - - {t.move} - - - ↵ - {t.open} - -
-
-
- ); -} diff --git a/src/Config.tsx b/src/Config.tsx index f350bb52..fa9b5bae 100644 --- a/src/Config.tsx +++ b/src/Config.tsx @@ -25,6 +25,9 @@ import { errorText } from "@/i18n/core.i18n"; import { useRemote } from "@/connection/useRemote"; import { remoteText } from "@/connection/remote.i18n"; import type { RemoteCore } from "@/connection/api"; +import { revealSection, useNavParams } from "@/nav"; +import { getLang } from "@/i18n"; +import { sectionTitle } from "@/palette/sections"; /** * 设置:这个应用自己的,和网关那几项配一次就不动的。 @@ -50,6 +53,10 @@ export default function Config({ const t = useText(configText); const rt = useText(remoteText); const remote = useRemote(); + // 命令面板送来的「设置 › 外观」:滚到那一节。节是陆续画出来的,`revealSection` 会等它 + useNavParams("settings", (p) => { + if (p.section) revealSection(p.section, sectionTitle(p.section, getLang())); + }); useEffect(() => { void invoke("autostart_enabled") .then(setAutostart) diff --git a/src/clients/ClientsPage.tsx b/src/clients/ClientsPage.tsx index 4f5368cd..3160b8ce 100644 --- a/src/clients/ClientsPage.tsx +++ b/src/clients/ClientsPage.tsx @@ -8,7 +8,7 @@ import { Page, PageHeader, SummaryItem } from "@/ui/page"; import { Skeleton } from "@/ui/skeleton"; import { EmptyState, Loadable } from "@/ui/states"; import { StatusDot } from "@/ui/status-dot"; -import { useNav } from "@/nav"; +import { useNav, useNavParams } from "@/nav"; import { useText } from "@/i18n"; import { coreText } from "@/i18n/core.i18n"; import { appText } from "@/App.i18n"; @@ -68,6 +68,11 @@ export default function ClientsPage({ const [retargeting, retargetRun] = usePending(); /** 「改为指向服务器」有没改成的:留在页上,直到再改一次或者离开这一页 */ const [retargeted, setRetargeted] = useState(null); + // 命令面板送来的:打开这一行的详情或手动配置,和点那一行一样(见 nav.tsx) + useNavParams("clients", (p) => { + if (p.detail) setDialog({ kind: "detail", id: p.detail }); + else if (p.setup) setDialog({ kind: "manual", id: p.setup }); + }); const data = clients.data; const adopted = data?.clients.filter((c) => c.adopted_at_ms != null) ?? []; diff --git a/src/index.css b/src/index.css index c63cf9c0..7f9d6e22 100644 --- a/src/index.css +++ b/src/index.css @@ -417,6 +417,10 @@ @utility motion-shimmer { animation: tw-shimmer 1.6s ease-in-out infinite; } +/* 高度跟着内容变的列表(命令面板的结果):结果变多变少时走过去 */ +@utility motion-list-height { + transition: height var(--motion-fast) var(--motion-ease); +} @media (prefers-reduced-motion: reduce) { .motion-page, @@ -429,7 +433,8 @@ .motion-row-out { animation-duration: 1ms; } - .motion-bar { + .motion-bar, + .motion-list-height { transition: none; } /* shadcn 组件的进出场(tw-animate-css):保留淡入淡出,去掉位移和缩放 */ diff --git a/src/keys/KeysPage.tsx b/src/keys/KeysPage.tsx index 5a1b4b4c..8bbe97ff 100644 --- a/src/keys/KeysPage.tsx +++ b/src/keys/KeysPage.tsx @@ -81,7 +81,12 @@ export default function KeysPage({ */ const [focus, setFocus] = useState(null); const [highlight, setHighlight] = useState(null); - useNavParams("keys", (p) => setFocus(p.key ?? null)); + useNavParams("keys", (p) => { + setFocus(p.key ?? null); + // 命令面板送来的:打开这一页上的对话框,和点「新建密钥」、点那一行一样(见 nav.tsx) + if (p.edit) setDialog({ kind: "edit", name: p.edit }); + else if (p.create) setDialog({ kind: "edit", name: null }); + }); useEffect(() => { if (!focus || !list?.some((k) => k.name === focus)) return; document.querySelector(`[data-row="${CSS.escape(focus)}"]`)?.scrollIntoView({ block: "center" }); @@ -232,7 +237,8 @@ export default function KeysPage({ )} - {dialog?.kind === "edit" && ( + {/* 编辑要等那把密钥读到了再开:先开的话对话框按「新建」起了表单,读到之后也不会换 */} + {dialog?.kind === "edit" && (dialog.name === null || editing) && ( ; grouped?: boolean; request?: number; search?: boolean }; - clients: undefined; - keys: { key?: string }; - upstreams: { upstream?: string }; - routing: undefined; + clients: { detail?: string; setup?: string }; + keys: { key?: string; edit?: string; create?: boolean }; + upstreams: { + upstream?: string; + edit?: string; + create?: "upstream" | "proxy" | "sheet"; + test?: "speed" | "link"; + }; + routing: { editRoute?: string; editGroup?: string; create?: "route" | "group"; dryRun?: boolean }; security: { focus?: LogFocus }; mcp: undefined; settings: { section?: string }; @@ -88,3 +103,79 @@ export function useNavParams(surface: S, onParams: (params: N cb.current(d.params as NonNullable); }, [d, surface]); } + +/** + * 滚到页面里的一节。页面在 `useNavParams` 里收到「打开到某一节」时调(设置页的 + * `section`)。 + * + * 先找 `[data-section=""]`,没有就找字是 `title` 的标题(`h1`–`h3`)。**节是 + * 陆续画出来的**(语言、外观要先读到当前值),所以等它出现,最多 1.5 秒;它上面 + * 的节后画出来会把它往下挤,所以出现之后再跟 0.6 秒。用户自己滚了、点了、按了键, + * 就不再跟。找不到就什么都不做 —— 停在那一页的顶上。 + */ +export function revealSection(id: string, title?: string) { + if (typeof document === "undefined") return; + let stop = false; + const cancel = () => { + stop = true; + for (const ev of STOP_EVENTS) window.removeEventListener(ev, cancel, true); + }; + for (const ev of STOP_EVENTS) window.addEventListener(ev, cancel, { capture: true, passive: true }); + + const find = (): HTMLElement | null => { + const tagged = document.querySelector(`[data-section="${CSS.escape(id)}"]`); + if (tagged) return tagged; + if (!title) return null; + for (const h of document.querySelectorAll("h1, h2, h3")) { + if (h.textContent?.trim() === title) return h.closest("section") ?? h; + } + return null; + }; + const behavior: ScrollBehavior = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches + ? "auto" + : "smooth"; + /** 离滚动层顶边留一点,标题不贴着工具栏 */ + const MARGIN = 16; + /** 上一次要滚到哪儿。平滑滚动走在半路时 `scrollTop` 不是终点,拿它比会来回拉扯 */ + let target: number | null = null; + const align = (el: HTMLElement) => { + const box = scrollParent(el); + if (!box) return; + const top = Math.max( + 0, + Math.min( + box.scrollHeight - box.clientHeight, + el.getBoundingClientRect().top - box.getBoundingClientRect().top + box.scrollTop - MARGIN, + ), + ); + if (target !== null && Math.abs(top - target) <= 2) return; + target = top; + box.scrollTo({ top, behavior }); + }; + + const start = performance.now(); + let found = 0; + const tick = () => { + if (stop) return; + const now = performance.now(); + const el = find(); + if (el) { + if (found === 0) found = now; + align(el); + } + const done = found > 0 ? now - found > 600 : now - start > 1500; + if (done) cancel(); + else setTimeout(() => requestAnimationFrame(tick), found > 0 ? 120 : 16); + }; + requestAnimationFrame(tick); +} + +const STOP_EVENTS = ["wheel", "pointerdown", "keydown", "touchmove"] as const; + +function scrollParent(el: HTMLElement): HTMLElement | null { + for (let p = el.parentElement; p; p = p.parentElement) { + const oy = getComputedStyle(p).overflowY; + if ((oy === "auto" || oy === "scroll") && p.scrollHeight > p.clientHeight) return p; + } + return null; +} diff --git a/src/palette/Palette.tsx b/src/palette/Palette.tsx new file mode 100644 index 00000000..06bc99d7 --- /dev/null +++ b/src/palette/Palette.tsx @@ -0,0 +1,440 @@ +import { useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react"; +import { invoke } from "@tauri-apps/api/core"; +import { ArrowLeftRightIcon } from "lucide-react"; +import { useLang, useText } from "@/i18n"; +import { useNav } from "@/nav"; +import { useConnections } from "@/connection/ConnectionProvider"; +import { useResource } from "@/lib/resource"; +import { api as clientsApi } from "@/clients/api"; +import { cn } from "@/lib/utils"; +import { notify } from "@/ui/notify"; +import { Button } from "@/ui/button"; +import { Dialog, DialogContent, DialogTitle } from "@/ui/dialog"; +import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandShortcut } from "@/ui/command"; +import type { Overview, RequestRow } from "@/types"; +import type { Found, UpdateView } from "@/updateFlow"; +import { arrange } from "./arrange"; +import { buildItems, requestItems, type GroupId, type Item, type Verb } from "./items"; +import { COMBOS, Keys, type Combo } from "./keys"; +import { normalize, requestIdQuery, score } from "./match"; +import { paletteText } from "./palette.i18n"; +import { ShortcutSheet } from "./ShortcutSheet"; +import { loadUsage, recordUse, type Usage } from "./usage"; + +export interface PaletteProps { + open: boolean; + onOpenChange: (open: boolean) => void; + /** 快捷键一览开着。它和面板挂在一起:面板里能打开它,`?` 也能 */ + shortcuts: boolean; + onShortcutsChange: (open: boolean) => void; + /** 连上 core 了 */ + linked: boolean; + /** 连着的远程 core 断了:内容只读,写配置的动作不出现 */ + readOnly: boolean; + /** 连着远程 core */ + remote: boolean; + ov: Overview | null; + /** 流量页已经取回来的请求(新的在前)。按编号、模型搜 */ + rows: readonly RequestRow[]; + railOpen: boolean; + /** 只有外壳做得了的几件事 */ + shell: { + toggleRail: () => void; + refresh: () => void; + configFile: () => void; + history: () => void; + notices: () => void; + }; +} + +/** + * ⌘K 的命令面板,和 `?` 的快捷键一览。 + * + * **面板不自己做事,只是把人送到做事的地方。**「新建上游」打开的是上游页上那个对话框 + * (`nav.open("upstreams", { create: "upstream" })`),「deepseek」打开的是点那一行 + * 会打开的那个 —— 对话框只有一份,在页面里。面板自己做的只有页面上没有入口的几件: + * 检查更新、切换连接那一级列表。 + * + * 能搜的:页面、操作、上游、密钥、路由、策略组、客户端、连接、设置的各节,以及流量页 + * 已经取回来的请求(按编号、模型)。**都是已经在手上的数据**:概览、流量的 + * 行、连接列表;客户端要现扫一次配置文件,打开面板时读(有缓存,第二次打开立刻有)。 + */ +export function Palette(props: PaletteProps) { + const { open, onOpenChange } = props; + const t = useText(paletteText); + /** 打开之前焦点在哪。关的时候只还给能打字的地方,见 `onCloseAutoFocus` */ + const before = useRef(null); + /** 这次关闭是因为执行了一项:焦点交给那一项打开的东西 */ + const ran = useRef(false); + /** + * 在下一级里按 Esc:回到最外层,不关面板。**只能在对话框那一层拦**:Radix 在 + * document 的捕获阶段处理 Esc,比面板里任何一个按键处理都早 + */ + const escape = useRef<(() => boolean) | null>(null); + // 在 Radix 把焦点挪进面板之前记下来(它在 effect 里挪,这里是 layout effect) + useLayoutEffect(() => { + if (!open) return; + before.current = document.activeElement; + ran.current = false; + }, [open]); + + return ( + <> + + { + // 输入法里按 Esc 是取消这次输入,不是关面板(WebKit 里是 keyCode 229) + if (e.isComposing || e.keyCode === 229 || escape.current?.()) e.preventDefault(); + }} + onCloseAutoFocus={(e) => { + e.preventDefault(); + // 执行了一项:焦点在那一项打开的东西里(对话框、搜索框),不抢回来。只是看了 + // 一眼就关掉:之前在打字的话回到那个输入框;之前在按钮上的不还 —— WebKit + // 里脚本聚焦的按钮会画上一圈焦点框(见 Notices.tsx) + const el = before.current as HTMLElement | null; + if (!ran.current && el && el.isConnected && isTextField(el)) el.focus(); + }} + > + {t.title} + {/* 面板关上(淡出结束)之后 Radix 把里面整个卸掉:下次打开查询、所在的一级都从头来 */} + { + ran.current = true; + onOpenChange(false); + }} + /> + + + + + ); +} + +/** + * 面板里面。**只在开着的时候挂着**(Radix 关上之后卸掉内容):查询、所在的一级、选中的 + * 那一项每次打开都从头来,客户端列表也只在这时候读。 + */ +function PaletteBody({ + linked, + readOnly, + remote, + ov, + rows, + railOpen, + shell, + onShortcutsChange, + escape, + close, +}: PaletteProps & { escape: { current: (() => boolean) | null }; close: () => void }) { + const t = useText(paletteText); + const lang = useLang(); + const nav = useNav(); + const conn = useConnections(); + const [query, setQuery] = useState(""); + const [scope, setScope] = useState<"connections" | null>(null); + /** 选中的那一项,和它是在哪一次查询(哪一级)里选的。见下面 `selected` */ + const [picked, setPicked] = useState<{ value: string; asked: string }>({ value: "", asked: "" }); + const [usage, setUsage] = useState(loadUsage); + + // 客户端:这台机器上的应用。和客户端页、密钥页同一份缓存(`useClients` 的键和取数): + // 看过那两页就立刻有,面板打开时再在后台读一次。没连上 core 不读;读不到就少一组 + const clients = useResource(linked ? "clients" : null, clientsApi.list); + + const items = useMemo( + () => + buildItems({ + nav, + lang, + linked, + readOnly, + remote, + ov, + railOpen, + conn: conn.view, + clients: clients.data, + switchTo: conn.switchTo, + addConnection: conn.add, + shell: { + ...shell, + shortcuts: () => onShortcutsChange(true), + checkUpdates: () => checkForUpdates(t), + }, + }), + // `shell` 和 `t` 不在依赖里:前者是外壳的几个固定动作,后者跟着 `lang` 变 + [nav, lang, linked, readOnly, remote, ov, railOpen, conn.view, clients.data], + ); + + const requests = useMemo(() => { + if (!linked || scope !== null || !normalize(query)) return []; + return requestItems(rows, ov, nav, (title, kw) => score(query, title, kw), requestIdQuery(query), 5); + }, [linked, scope, query, rows, ov, nav]); + + const shown = useMemo( + () => arrange({ items, extra: requests, query, scope, usage }), + [items, requests, query, scope, usage], + ); + const byValue = useMemo(() => new Map(shown.flatMap((g) => g.items.map((x) => [x.value, x.item] as const))), [shown]); + + /* + **选中哪一项由这里算,不交给 cmdk。**结果是自己排的(`shouldFilter` 关着),cmdk + 在查询变了之后先按它记着的上一项去滚、再改选第一项:打一个 `c`,上一次选中的 + 「概览」还在结果里、排到了很下面,列表就跟着滚了下去,第一行反倒看不见。 + + 所以选中的值是**在渲染时算出来的**,和结果同一帧:查询变了、进出了一级,那一次 + 选的就不算了,直接是第一项(进出一级时查询常常本来就是空的,cmdk 不会自己重选); + 结果自己变了(客户端读到了、来了新请求),选中的那一项还在就不动,没了也是第一项。 + */ + const asked = JSON.stringify([scope, query]); + const first = shown.flatMap((g) => g.items).find((x) => !x.item.disabled)?.value ?? ""; + const selected = picked.asked === asked && byValue.has(picked.value) ? picked.value : first; + const current = byValue.get(selected); + + // 查询变了、进出了一级:列表滚回顶上(选中的是第一项,cmdk 不会再滚) + const listRef = useRef(null); + useLayoutEffect(() => { + if (listRef.current) listRef.current.scrollTop = 0; + }, [asked]); + + const run = (item: Item) => { + setUsage(recordUse(item.id)); + if (item.enter) { + setScope(item.enter); + setQuery(""); + return; + } + close(); + // 面板关掉之后再动:对话框的焦点归还和新页面挂上不要挤在同一帧 + setTimeout(item.run, 0); + }; + + const back = () => { + setScope(null); + setQuery(""); + }; + useLayoutEffect(() => { + escape.current = () => { + if (scope === null) return false; + setScope(null); + setQuery(""); + return true; + }; + }, [escape, scope]); + + const q = normalize(query); + const empty = shown.length === 0; + + return ( + setPicked({ value, asked })} + label={t.title} + onKeyDown={(e) => { + // 在下一级里,输入框空着再按退格:回到最外层(Esc 在对话框那一层处理) + if (scope !== null && e.key === "Backspace" && query === "" && !e.nativeEvent.isComposing) { + e.preventDefault(); + back(); + } + }} + > + + + {t.groups.connections} + + ) + } + trail={} + /> + +
+ {shown.map((g) => ( + + {g.items.map(({ item, value }) => ( + run(item)} /> + ))} + + ))} +
+ {empty && {q ? t.none(query.trim()) : t.noConnections}} +
+